pi-web-ui 0.114.2 → 0.114.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/server/agent-service.js +29 -5
- package/dist/server/context-usage.js +105 -0
- package/dist/server/protocol-version.js +1 -1
- package/package.json +1 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BIlQ89vr.js → BgTasksModal-BvnUHjFe.js} +1 -1
- package/web/dist/assets/{BgTasksModal-Ck2sjlPM.js → BgTasksModal-DSC8ncW3.js} +1 -1
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BSg9ghPV.js} +2 -2
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DxW7C3Sz.js} +2 -2
- package/web/dist/assets/{DeviceCenter-BQdDcO8A.js → DeviceCenter-Bmgr-Bwm.js} +1 -1
- package/web/dist/assets/{DeviceCenter-CHRKL0Vy.js → DeviceCenter-Cl9MBXaH.js} +1 -1
- package/web/dist/assets/{DeviceGroups-D2rogxEN.js → DeviceGroups-aeLD2msl.js} +1 -1
- package/web/dist/assets/{Dropdown-ZLS04O8p.js → Dropdown-D1Jl35dw.js} +1 -1
- package/web/dist/assets/{FilePreview-B9xoU6ON.js → FilePreview-6CqoDF_P.js} +1 -1
- package/web/dist/assets/{FilePreview-DUQpVZkH.js → FilePreview-CJa27G_Q.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-BXEGvUZq.js → GlobalSearchModal-CJX35rZL.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-CnVPmfOI.js → GlobalSearchModal-CMW0xz0P.js} +1 -1
- package/web/dist/assets/{GroupConversation-CyIpQzDd.js → GroupConversation-Cq4daBFb.js} +1 -1
- package/web/dist/assets/{GroupConversation-DgYV3uYS.js → GroupConversation-DoELa83U.js} +1 -1
- package/web/dist/assets/{ModelConfigModal-DDZccDYt.js → ModelConfigModal-Bp7tfKYh.js} +1 -1
- package/web/dist/assets/{PiSetupModal-DHbqfx8T.js → PiSetupModal-DD8srwBJ.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-C-MK36Dk.js → ProviderOAuthControls-C6tfXb88.js} +1 -1
- package/web/dist/assets/{SCMPanel-sVZcV7dR.js → SCMPanel-CghgsyBN.js} +1 -1
- package/web/dist/assets/{SCMPanel-imYI2Ecw.js → SCMPanel-D8-8aqwC.js} +1 -1
- package/web/dist/assets/{SettingsModal-Xw1Yoi3_.js → SettingsModal-BbBe2rYo.js} +1 -1
- package/web/dist/assets/{SettingsModal-mb4e34-0.js → SettingsModal-qETiVPKj.js} +1 -1
- package/web/dist/assets/{TerminalPanel-CLkJJvxg.js → TerminalPanel-Da-Xs4Wk.js} +1 -1
- package/web/dist/assets/{TerminalPanel-DpcIellm.js → TerminalPanel-DnS4tFQO.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-4-fFAZe7.js → TuiOverlayModal-CGyGkKYl.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-DCu01lks.js → TuiOverlayModal-CpBKjG6x.js} +1 -1
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-7EvUHhKQ.js} +1 -1
- package/web/dist/assets/{fi-DaSO0Q-m.js → fi-NyN-ZrgD.js} +2 -2
- package/web/dist/assets/{index-Cdh3sibd.js → index-DK3F5ZJo.js} +50 -50
- package/web/dist/assets/{index-DWw_SxRq.js → index-DQMii2he.js} +50 -50
- package/web/dist/assets/index-vwBnwzkr.css +1 -0
- package/web/dist/assets/{plugin-host-BRBg6zmQ.js → plugin-host-BCnX3P8U.js} +1 -1
- package/web/dist/assets/{theme-DDl-Oy1b.js → theme-D2DMH6tH.js} +1 -1
- package/web/dist/index.html +8 -8
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./math-1uRJCsA9.js","./rolldown-runtime-hePW80VL.js","./markdown-BggnuQ4H.js","./react-CR5VJ85Q.js","./markdown-C8LL_u4z.css","./math-BorAY7qD.css","./TerminalPanel-
|
|
2
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,$t as n,A as r,At as i,B as a,Bt as o,C as s,D as c,Dt as l,E as u,Et as d,F as f,G as p,Gt as m,H as h,Ht as g,I as _,It as v,J as y,Jt as b,K as x,L as S,Lt as C,M as w,Mt as T,N as E,O as D,Ot as O,P as k,Pt as A,Q as j,R as M,Rt as N,S as P,St as ee,T as F,Tt as te,U as ne,Ut as re,V as I,Vt as L,W as ie,Wt as ae,X as oe,Xt as se,Y as ce,Yt as R,Z as le,Zt as ue,_ as z,_t as de,a as B,an as V,at as fe,b as pe,bt as me,c as he,cn as H,ct as ge,d as U,dn as W,dt as G,en as _e,et as K,fn as q,ft as J,g as ve,gt as Y,h as ye,ht as be,i as xe,in as Se,j as Ce,jt as we,k as Te,kt as Ee,l as De,ln as X,lt as Oe,m as ke,mt as Ae,n as je,nn as Me,nt as Ne,o as Pe,on as Fe,ot as Ie,p as Le,pn as Re,pt as ze,q as Be,qt as Ve,r as He,rn as Ue,rt as We,s as Ge,sn as Ke,st as qe,t as Je,tn as Ye,tt as Xe,u as Ze,un as Qe,ut as $e,v as et,vt as tt,w as nt,wt as rt,x as it,xt as at,y as ot,yt as st,z as ct,zt as lt}from"./fi-DaSO0Q-m.js";import{i as ut,n as dt,r as ft,t as pt}from"./react-CR5VJ85Q.js";import{t as mt}from"./shortcut-stack-hhrDyRBn.js";import{t as ht}from"./uuid-BzDIGCwP.js";import{n as gt,t as _t}from"./Dropdown-ZLS04O8p.js";import{a as vt,i as yt,n as bt,t as xt}from"./theme-DDl-Oy1b.js";import{i as St,n as Ct,r as wt,t as Tt}from"./desktop-YguLbrX1.js";import{A as Et,C as Dt,D as Ot,E as kt,O as At,S as jt,T as Mt,_ as Nt,a as Pt,b as Ft,c as It,g as Lt,h as Rt,i as zt,k as Bt,l as Vt,m as Ht,n as Ut,o as Wt,r as Gt,t as Kt,u as qt,v as Jt,w as Yt,x as Xt,y as Zt}from"./plugin-host-BRBg6zmQ.js";import{a as Qt,c as $t,i as en,l as tn,n as nn,o as rn,r as an,s as on,t as Z,u as sn}from"./app-globals-DcyO0UPi.js";import{a as cn,c as ln,d as un,h as dn,l as fn,m as pn,s as mn,t as hn,u as gn}from"./markdown-BggnuQ4H.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function _n(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.get(String(t))??null},key(t){return[...e.keys()][Number(t)>>>0]??null},removeItem(t){e.delete(String(t))},setItem(t,n){e.set(String(t),String(n))}}}function vn(e){let t=Re(e.location.pathname);if(!t)return!1;let n=!1;for(let t of[`localStorage`,`sessionStorage`])try{e[t]}catch{n=!0,Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:_n()})}if(!n)return!1;let r=e.fetch;return e.fetch=(n,i)=>{let a=typeof n==`string`?n:n instanceof URL?n.href:n.url,o=new URL(a,e.document.baseURI||e.location.href);return o.origin===e.location.origin&&o.pathname.startsWith(t)?r.call(e,n,{...i,credentials:`omit`}):r.call(e,n,i)},!0}var yn=typeof window<`u`&&vn(window),bn=ft(),xn=dt(),Q=e(ut(),1);function Sn(e,t,n,r={}){let{align:i=`right`,side:a=`bottom`,gap:o=6,margin:s=8}=r,c=t.width,l=t.height,u=Math.max(0,n.width-c-s),d=Math.max(0,n.height-l-s),f=i===`left`?e.left:e.right-c;f=Math.max(s,Math.min(f,u));let p;return a===`top`?(p=e.top-l-o,p<s&&e.bottom+o+l<=n.height-s&&(p=e.bottom+o)):(p=e.bottom+o,p+l>n.height-s&&e.top-l-o>=s&&(p=e.top-l-o)),p>d&&(p=d),p<s&&(p=s),{x:Math.round(f),y:Math.round(p)}}function Cn(e){let{open:t=!0,anchor:n,anchorEl:r,onClose:i,isInside:a,align:o=`right`,side:s=`bottom`,gap:c=6,margin:l=8}=e,u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(i);(0,Q.useLayoutEffect)(()=>{p.current=i});let m=()=>{if(!n)return null;if(`current`in n)return n.current?.getBoundingClientRect()??null;if(typeof n.getBoundingClientRect==`function`)return n.getBoundingClientRect();let e=n;return typeof e.left==`number`&&typeof e.right==`number`&&typeof e.top==`number`&&typeof e.bottom==`number`?e:null},h=()=>r||(n&&`current`in n?n.current:n&&typeof n.getBoundingClientRect==`function`?n:null),g=()=>{if(!t)return;let e=u.current;if(!e)return;let n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return;let r=h(),i=r&&r.isConnected?r.getBoundingClientRect():m();if(!i)return;let a=Sn(i,{width:n.width,height:n.height},{width:window.innerWidth,height:window.innerHeight},{align:o,side:s,gap:c,margin:l});f(e=>e?.x===a.x&&e?.y===a.y?e:a)};return(0,Q.useLayoutEffect)(()=>{t?g():f(null)},[t,n,r,o,s,c,l]),mt(()=>{p.current()},t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>e instanceof Node&&!!(u.current?.contains(e)||h()?.contains(e)||a?.(e)),n=t=>{e(t.target)||p.current()};return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`resize`,g,!0),window.addEventListener(`scroll`,g,!0),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`resize`,g,!0),window.removeEventListener(`scroll`,g,!0)}},[t,n,r]),{panelRef:u,pos:d,style:{position:`fixed`,left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},measure:g}}async function wn(e,t,n,r){let i=window.piDesktop,a=i?.openHub?null:window.open(`about:blank`,`_blank`);if(!i?.openHub&&!a)throw Error(r?`请允许弹出窗口后重试。`:`Allow popups and try again.`);a&&(a.opener=null);try{let o=await fetch(Qe(q(`/api/device-center/devices/${encodeURIComponent(e)}/open`)),{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,signal:AbortSignal.timeout(15e3)});if(!o.ok)throw Error(r?`无法打开设备,请确认设备在线且本机绑定有效。`:`Could not open the device. Check connectivity and local pairing.`);let s=await o.json(),c=new URL(s.url),l=new URL(t);if(![`http:`,`https:`].includes(c.protocol)||c.hostname!==l.hostname||c.username||c.password||!(c.pathname===`/__device/open`||c.origin===l.origin&&c.pathname===`/device/${encodeURIComponent(e)}/__open`))throw Error(`Invalid device access URL`);if(c.searchParams.delete(`next`),n&&c.searchParams.set(`next`,`/desktop`),i?.openHub){if(!await i.openHub(c.href))throw Error(r?`无法打开设备窗口。`:`Could not open device window.`)}else a&&a.location.replace(c.href)}catch(e){throw a?.close(),e}}var $=pt();function Tn({hubUrl:e,currentDeviceId:t}){let{locale:n}=Ue(),r=H(n),[i,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let e=!1,t,n;async function i(){t=new AbortController;try{let n=await fetch(Qe(q(`/api/device-center/devices`)),{signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]),credentials:`same-origin`});if(!n.ok)throw Error(n.status===409?r?`请重新绑定本机以读取设备列表。`:`Pair this computer again to read the device list.`:r?`无法读取设备列表,请重试。`:`Could not load devices. Try again.`);let i=await n.json();if(!Array.isArray(i.devices))throw Error(r?`设备列表格式异常。`:`Invalid device list.`);e||(o(i.devices),c(``))}catch(t){e||(o([]),c(t instanceof Error?t.message:String(t)))}finally{e||(n=setTimeout(i,5e3))}}return i(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[e,t,l,r]);function d(t){try{let n=new URL(e);return![`http:`,`https:`].includes(n.protocol)||n.username||n.password?void 0:new URL(`/device/${encodeURIComponent(t)}`,n).href}catch{return}}async function f(t,n,i=!1){t.preventDefault();try{await wn(n,e,i,r),c(``)}catch(e){c(e instanceof Error?e.message:String(e))}}return(0,$.jsxs)(`section`,{className:`dc-card`,"aria-label":r?`所有设备`:`All devices`,children:[(0,$.jsxs)(`div`,{className:`dc-card-header`,children:[(0,$.jsx)(`span`,{className:`dc-icon`,children:(0,$.jsx)(st,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{children:[r?`所有设备`:`All devices`,` · `,i.length]}),(0,$.jsx)(`p`,{children:r?`同一账号下的设备,使用本机绑定授权直接访问。`:`Devices in your account. Access is authorized through this computer's pairing.`})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-icon-button`,"aria-label":r?`刷新设备`:`Refresh devices`,onClick:()=>u(e=>e+1),children:(0,$.jsx)(te,{})})]}),s&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:s}),(0,$.jsx)(`div`,{className:`dd-list`,children:i.map(e=>(0,$.jsxs)(`div`,{className:`dd-device`,children:[(0,$.jsx)(`span`,{className:`dc-device-icon`,children:(0,$.jsx)(st,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`dd-identity`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:e.id===t?r?`本机`:`This device`:e.id})]}),(0,$.jsx)(`span`,{className:`dc-status ${e.online?`is-online`:`is-offline`}`,children:e.online?r?`在线`:`Online`:r?`离线`:`Offline`}),d(e.id)&&(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`a`,{className:`dc-button`,href:d(e.id),target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void f(t,e.id),children:[(0,$.jsx)(a,{"aria-hidden":!0}),r?`打开设备`:`Open device`]}),(0,$.jsxs)(`a`,{className:`dc-button`,href:`${d(e.id)}/desktop`,target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void f(t,e.id,!0),children:[(0,$.jsx)(st,{"aria-hidden":!0}),r?`远程桌面`:`Remote desktop`]})]})]},e.id))})]})}function En({label:e=`pi-web-ui`,barItem:t=!1,onContextMenu:n}){let{locale:r}=Ue(),i=H(r),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),l=(0,Q.useRef)(null),{panelRef:u,style:d}=Cn({open:s&&!!a,anchor:l,align:`left`,onClose:()=>c(!1)});(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(Qe(q(`/api/device-center/chat-status`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)return;let r=await n.json();if(!e){let e=r.local!==!0&&typeof r.hubUrl==`string`&&!!r.hubUrl&&typeof r.deviceId==`string`&&!!r.deviceId;o(e?{hubUrl:r.hubUrl,deviceId:r.deviceId}:null),e||c(!1)}}catch{}finally{e||(n=setTimeout(r,15e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[]);let f=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{className:t?`brand-logo bar-item-brand-logo bar-item-icon`:`brand-logo`,src:q(`/icons/icon-192.png`),alt:`pi-web-ui`,width:26,height:26,draggable:!1}),(0,$.jsx)(`span`,{className:t?`brand-name bar-item-text`:`brand-name`,children:e})]}),p=t?`bar-item brand bar-item-brand`:`brand`;return a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:l,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,type:`button`,className:`${p} brand-device-trigger`,title:i?`设备列表`:`Devices`,"aria-label":i?`设备列表`:`Devices`,"aria-haspopup":`dialog`,"aria-expanded":s,onClick:()=>c(e=>!e),children:f}),s&&(0,bn.createPortal)((0,$.jsx)(`div`,{ref:u,style:d,className:`brand-device-panel`,role:`dialog`,"aria-label":i?`设备列表`:`Devices`,children:(0,$.jsx)(Tn,{hubUrl:a.hubUrl,currentDeviceId:a.deviceId})}),document.body)]}):(0,$.jsx)(`span`,{className:p,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,children:f})}function Dn(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`},child:[{tag:`path`,attr:{d:`M11.646 15.146 5.854 9.354a.5.5 0 0 1 .353-.854h11.586a.5.5 0 0 1 .353.854l-5.793 5.792a.5.5 0 0 1-.707 0Z`},child:[]}]})(e)}function On(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`},child:[]},{tag:`path`,attr:{d:`M7 11v4a2 2 0 0 0 2 2h4`},child:[]},{tag:`rect`,attr:{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`},child:[]}]})(e)}function kn(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 17H7l-4 4v-7`},child:[]},{tag:`path`,attr:{d:`M14 17h1`},child:[]},{tag:`path`,attr:{d:`M14 3h1`},child:[]},{tag:`path`,attr:{d:`M19 3a2 2 0 0 1 2 2`},child:[]},{tag:`path`,attr:{d:`M21 14v1a2 2 0 0 1-2 2`},child:[]},{tag:`path`,attr:{d:`M21 9v1`},child:[]},{tag:`path`,attr:{d:`M3 9v1`},child:[]},{tag:`path`,attr:{d:`M5 3a2 2 0 0 0-2 2`},child:[]},{tag:`path`,attr:{d:`M9 3h1`},child:[]}]})(e)}function An(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2`},child:[]},{tag:`path`,attr:{d:`M8.5 2h7`},child:[]},{tag:`path`,attr:{d:`M7 16h10`},child:[]}]})(e)}function jn(e){return e.map(e=>e.kind===`package`?`pi update npm:${e.name}`:e.kind===`git-extension`?`pi update ${Mn(e.source??e.name)}`:e.kind===`plugin`?`pi-web-ui install ${e.source??e.name} --name ${e.pluginId??e.name} --force`:`npm i -g ${e.name}@latest`).join(`; `)}function Mn(e){return e.startsWith(`git:`)?e:`git:${e}`}var Nn=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost),Pn=null,Fn=0;function In(){return Pn?.available===!0?Pn.pages??[]:[]}function Ln(){Date.now()-Fn<5e3||Rn().catch(()=>{})}async function Rn(){if(wt())return{available:!1,pages:[],desktop:!0,error:`桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)`};let e=Nn();if(!e)return{available:!1,pages:[],error:`宿主页面桥不可用:这个 pi-web-ui 页面还没装上扩展桥(装/启用 page-picker 后刷新本页)`};try{let t=await e({op:`status`,timeoutMs:5e3});if(!t.ok)return{available:!1,pages:[],error:t.error??`扩展没有返回状态`};let n=t.result??{},r={available:n.installed===!0,aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,pages:Array.isArray(n.pages)?n.pages:[]};return r.available&&(Pn=r,Fn=Date.now()),r}catch(e){return{available:!1,pages:[],error:e instanceof Error?e.message:String(e)}}}function zn(e){return e.length===1?e[0]:null}function Bn(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:`page`,key:`page:${e.origin}`}}async function Vn(){let e=Nn();if(!e)return!1;try{return(await e({op:`openOptions`,timeoutMs:5e3})).ok===!0}catch{return!1}}function Hn(e=45e3){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(!0),i=(0,Q.useCallback)(async e=>{let t=await Rn();r.current&&(n(t),e&&!t.available&&setTimeout(()=>{r.current&&i(!1)},1500))},[]);return(0,Q.useEffect)(()=>{r.current=!0,i(!0);let t=setInterval(()=>void i(!1),Math.max(5e3,e));return()=>{r.current=!1,clearInterval(t)}},[i,e]),{status:t,refresh:()=>void i(!0)}}function Un(){let e=V(),{status:t,refresh:n}=Hn(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),s=(0,Q.useRef)(null),c=t?.pages??[],l=t?.available===!0&&(c.length===0||t.aiControl===!1),u=zn(c),d=e=>{o(e),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>o(null),2600)},f=t=>{let n=Ft({attachments:[Bn(t)]});d(e(n?`browserControlCited`:`browserControlCiteFailed`))},p=()=>{i(!0),n()};return(0,$.jsxs)(`span`,{className:`bc-anchor`,children:[u?(0,$.jsxs)(`span`,{className:`browser-control-split`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control single${l?` attention`:``}`,"data-tip":e(`browserControlSingleTip`,{name:u.title||u.origin}),title:e(`browserControlSingleTip`,{name:u.title||u.origin}),onClick:()=>f(u),children:[(0,$.jsx)(st,{size:14,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`bc-chip-label`,children:u.title||u.origin})]}),(0,$.jsx)(`button`,{type:`button`,className:`chip browser-control caret`,"data-tip":e(`browserControlOpenPanel`),title:e(`browserControlOpenPanel`),"aria-label":e(`browserControlOpenPanel`),onClick:p,children:`▾`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${l?` attention`:``}`,"data-tip":t?.error??e(l?`browserControlEmpty`:`browserControlTip`),title:t?.error??e(l?`browserControlEmpty`:`browserControlTip`),onClick:p,children:[(0,$.jsx)(st,{size:14,"aria-hidden":!0}),(0,$.jsxs)(`span`,{children:[e(`browserControl`),c.length>0?` · ${c.length}`:``]})]}),a&&(0,$.jsx)(`span`,{className:`bc-flash`,children:a}),r&&(0,$.jsx)(Wn,{status:t,onRefresh:n,onCite:f,onClose:()=>i(!1)})]})}function Wn({status:e,onRefresh:t,onCite:n,onClose:r}){let i=V(),[a,o]=(0,Q.useState)(!1),s=e?.pages??[],c=async()=>{o(!0);try{await Vn()||t()}finally{o(!1)}};return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:r,children:(0,$.jsxs)(`div`,{className:`modal browser-control-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":i(`close`),onClick:r,children:`✕`}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(st,{size:16,"aria-hidden":!0}),(0,$.jsx)(`h2`,{children:i(`browserControl`)})]}),(0,$.jsx)(`div`,{className:`modal-desc`,children:i(`browserControlTip`)}),e===null&&(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlChecking`)}),e?.available===!1&&!e.desktop&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlOffline`)}),e?.desktop===!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlDesktop`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlDesktopLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:window.location.href,target:`_blank`,rel:`noreferrer noopener`,children:i(`browserControlOpenInBrowser`)})})]}),e?.available===!1&&!e.desktop&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlInstall`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlInstallLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:`https://github.com/xing-shuyin/pi-web-ui/releases/latest/download/page-picker-extension.zip`,target:`_blank`,rel:`noreferrer noopener`,children:i(`browserControlInstallDownload`)})}),(0,$.jsxs)(`ol`,{className:`bc-steps`,children:[(0,$.jsx)(`li`,{children:i(`browserControlInstallStep1`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep2`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep3`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep4`)})]})]}),e?.available===!0&&e.aiControl===!1&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlDisabled`)}),e?.available===!0&&s.length===0&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlEmpty`)}),s.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlPages`)}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:s.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`bc-title`,title:e.title,children:e.title}),(0,$.jsx)(`span`,{className:`bc-origin`,title:e.origin,children:e.origin}),(0,$.jsx)(`span`,{className:`bc-open${e.open?` on`:``}`,children:e.open?i(`browserControlPageOpen`):i(`browserControlPageClosed`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,title:i(`browserControlCiteTip`,{name:e.title||e.origin}),onClick:()=>n(e),children:i(`browserControlCite`)})]},e.origin))}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlCiteNote`)})]}),e?.desktop!==!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlExamples`)}),(0,$.jsxs)(`ul`,{className:`bc-examples`,children:[(0,$.jsx)(`li`,{children:i(`browserControlExample1`)}),(0,$.jsx)(`li`,{children:i(`browserControlExample2`)})]})]}),(0,$.jsxs)(`div`,{className:`bc-actions`,children:[e?.desktop!==!0&&(0,$.jsx)(`button`,{type:`button`,className:`primary`,disabled:a,onClick:()=>void c(),children:i(`browserControlOpenOptions`)}),(0,$.jsx)(`button`,{type:`button`,onClick:t,children:i(`browserControlRefresh`)})]})]})})}var Gn=`canvas`,Kn=`terminal`,qn=[Kn],Jn=[`terminal_create`,`terminal_list`,`terminal_close`,`terminal_input`,`terminal_key`,`terminal_read`,`terminal_wait`],Yn=`conversation`,Xn=`communicate`,Zn=[Yn,`subagent`],Qn=[`subagent_spawn`,`subagent_get_result`,`subagent_steer`,`subagent_list`,`subagent_stop`,`subagent_wait_all`,`subagent_templates`,`subagent_handoff`],$n=`edit_soft`,er=`delegate_task`,tr=`ask_user_question`,nr=`browser_page`,rr=`skill`,ir=`schedule`,ar=[`schedule_task`,`schedule_list`,`schedule_cancel`],or=`eval`,sr=`present_files`,cr=`claim_files`,lr=`plan_update`,ur=`compact_context`,dr=`patch`,fr=`mcp_manage`,pr=`sandbox`,mr=`worktree`,hr=`device_collab`,gr=`codemode`,_r=`tool_search`,vr=[...qn.map(e=>({name:e,group:`terminal`,defaultOn:!1,dshVisible:!0})),...Zn.map(e=>({name:e,group:`subagent`,defaultOn:!0,dshVisible:!1})),{name:Xn,group:`subagent`,defaultOn:!0,dshVisible:!1,descKey:`communicateEnabledDesc`,offHintKey:`communicateOffHint`},{name:$n,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`editSoftEnabledDesc`,offHintKey:`editSoftOffHint`},{name:er,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`delegateTaskEnabledDesc`,offHintKey:`delegateTaskOffHint`},{name:tr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`questionnaireEnabledDesc`,offHintKey:`questionnaireOffHint`},{name:nr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`browserPageEnabledDesc`,offHintKey:`browserPageOffHint`},{name:cr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`claimFilesEnabledDesc`,offHintKey:`claimFilesOffHint`},{name:lr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`planUpdateEnabledDesc`,offHintKey:`planUpdateOffHint`},{name:dr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`patchToolEnabledDesc`,offHintKey:`patchToolOffHint`},{name:`lsp`,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`lspToolEnabledDesc`,offHintKey:`lspToolOffHint`},{name:sr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`presentFilesEnabledDesc`,offHintKey:`presentFilesOffHint`},{name:rr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`skillEnabledDesc`,offHintKey:`skillOffHint`},{name:or,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`evalEnabledDesc`,offHintKey:`evalOffHint`},{name:gr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`codemodeEnabledDesc`,offHintKey:`codemodeOffHint`},{name:_r,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolSearchEnabledDesc`,offHintKey:`toolSearchOffHint`},{name:ir,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`scheduleTaskEnabledDesc`,offHintKey:`scheduleTaskOffHint`},{name:ur,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`compactContextEnabledDesc`,offHintKey:`compactContextOffHint`},{name:fr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`mcpManageEnabledDesc`,offHintKey:`mcpManageOffHint`},{name:pr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`sandboxEnabledDesc`,offHintKey:`sandboxOffHint`},{name:mr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`toolsWorktreeDesc`,offHintKey:`toolsWorktreeOffHint`},{name:hr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolsDeviceCollabDesc`,offHintKey:`toolsDeviceCollabOffHint`},{name:Gn,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`canvasToolEnabledDesc`,offHintKey:`canvasToolOffHint`}],yr=[{name:`bash`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreBashDesc`},{name:`read`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreReadDesc`},{name:`edit`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreEditDesc`},{name:`write`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreWriteDesc`},{name:`powershell`,group:`core`,defaultOn:!1,platform:`win32`,allowAgentToggle:!1,descKey:`toolCorePowershellDesc`},{name:`ls`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreLsDesc`},{name:`grep`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreGrepDesc`},{name:`find`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreFindDesc`}],br=[...yr.map(e=>({name:e.name,group:`core`,defaultOn:e.defaultOn,platform:e.platform,allowAgentToggle:e.allowAgentToggle,dshVisible:!1,descKey:e.descKey})),...vr];new Map(br.map(e=>[e.name,e]));var xr=new Set(br.map(e=>e.name)),Sr=br.map(e=>e.name);function Cr(e){let t=new Set(wr(e));return Sr.filter(e=>!t.has(e))}function wr(e){if(!Array.isArray(e))return Tr();let t=[];for(let n of e){let e=n;if(typeof e==`string`&&Jn.includes(e)&&(e=Kn),typeof e==`string`&&Qn.includes(e)&&(e=Yn),e===`conversation_read`&&(e=Yn),typeof e==`string`&&Zn.includes(e)){for(let e of Zn)t.includes(e)||t.push(e);continue}typeof e==`string`&&ar.includes(e)&&(e=ir),typeof e==`string`&&xr.has(e)&&!t.includes(e)&&t.push(e)}return t}function Tr(){return br.filter(e=>!e.defaultOn).map(e=>e.name)}function Er(e,t){let n=Array.from(e);if(!t||t===`standard`)return n;if(t===`ask`)return[];if(t===`minimal`)return n.filter(e=>e===`bash`||e===`read`);if(t===`code`){let e=new Set([`bash`,`read`,`edit`,`write`,`edit_soft`]);return n.filter(t=>e.has(t))}if(t===`reader`){let e=new Set([`write`,`edit`,`edit_soft`,`bash`,`powershell`,`terminal_create`,`terminal_input`,`terminal_close`,`terminal_key`,`codemode`]);return n.filter(t=>!e.has(t))}return n}function Dr(e){return Er([rr],e).includes(rr)}var Or=new Set([`svg`,`g`,`path`,`circle`,`rect`,`line`,`polyline`,`polygon`,`ellipse`,`use`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`]),kr=new Set(`viewBox.xmlns.d.fill.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-dasharray.opacity.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.width.height.points.offset.stop-color.stop-opacity.fill-opacity.stroke-opacity.stroke-miterlimit.fill-rule.clip-rule.vector-effect.preserveAspectRatio.transform.clip-path.id.href.xlink:href.xmlns:xlink.gradientUnits.gradientTransform`.split(`.`)),Ar=new Set([`script`,`style`,`title`,`desc`,`foreignobject`]),jr=new Set([...Or].map(e=>e.toLowerCase())),Mr=new Set([...kr].map(e=>e.toLowerCase()));function Nr(e){return jr.has(e.toLowerCase())}function Pr(e){return Mr.has(e.toLowerCase())}function Fr(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>8192||!/^<svg[\s>]/.test(t.startsWith(`<?xml`)?t.slice(t.indexOf(`?>`)+2).trimStart():t))return null;if(typeof DOMParser>`u`)return/<script[\s>]/i.test(t)||/\son\w+\s*=/i.test(t)||/javascript\s*:/i.test(t)?null:t;let n=new DOMParser().parseFromString(t,`image/svg+xml`);if(n.querySelector(`parsererror`))return null;let r=n.documentElement;if(r.tagName.toLowerCase()!==`svg`)return null;let i=e=>{for(let t of Array.from(e.children)){let e=t.tagName.toLowerCase();if(!Nr(e)){Ar.has(e)?t.remove():(i(t),t.replaceWith(...t.childNodes));continue}for(let e of Array.from(t.attributes)){let n=e.name.toLowerCase();(!Pr(n)||/^on/i.test(n)||/^(javascript|data|vbscript):/i.test(e.value.trim()))&&t.removeAttribute(e.name)}i(t)}};for(let e of Array.from(r.attributes)){let t=e.name.toLowerCase();(!Pr(t)||/^on/i.test(t))&&r.removeAttribute(e.name)}return i(r),new XMLSerializer().serializeToString(r)}function Ir({icon:e,iconSvg:t,className:n}){let r=Fr(t);return r?(0,$.jsx)(`span`,{className:n??`plugin-icon-svg`,"aria-hidden":!0,dangerouslySetInnerHTML:{__html:r}}):e?(0,$.jsx)(`span`,{className:n?`${n} plugin-icon-glyph`:`plugin-icon-glyph`,"aria-hidden":!0,children:e}):null}var Lr={projects:`host:lp-projects`,convs:`host:lp-running`,sessions:`host:lp-history`},Rr=[`projects`,`convs`,`sessions`],zr=new Map(Object.keys(Lr).map(e=>[Lr[e],e])),Br=`plugin:`;function Vr(e){return e.startsWith(Br)&&e.length>7}function Hr(e){let t=[],n=new Set;for(let r of e??[]){let e=null,i,a=zr.get(r.id);a?e=a:r.source?.startsWith(`plugin:`)&&r.kind===`view`&&(e=`${Br}${r.id}`,i=r),e&&!n.has(e)&&(n.add(e),t.push({key:e,shown:!r.hidden,...i?{entry:i}:{}}))}for(let e of Rr)n.has(e)||t.push({key:e,shown:!0});return t}function Ur(e){let t=e.filter(e=>e.key!==`groups`),n=t.findIndex(e=>e.key===`projects`&&e.shown);return t.splice(n+1,0,{key:`groups`,shown:!0}),t}function Wr(e,t){return e.filter(e=>e.shown&&t(e.key)).map(e=>e.key)}function Gr(e,t){let n=[];for(let r=0;r+1<e.length;r++){let i=e[r],a=e[r+1];!t(i)&&!t(a)&&n.push([i,a])}return n}function Kr(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(!r||typeof r!=`object`||Array.isArray(r))return n;for(let[e,i]of Object.entries(r))(e in t||Vr(e))&&typeof i==`number`&&Number.isFinite(i)&&i>0&&(n[e]=i)}catch{}return n}var qr=new Set([`view`,`action`,`badge`,`menu`,`page`,`organizer`,`divider`,`toggle`,`input`,`progress`,`select`]),Jr=new Set([`disabled`,`always`,`never`,`file.isDir`,`file.isFile`,`session.isRunning`,`message.hasSelection`]),Yr=`topbar.primary,topbar.overflow,notice.actions,leftpanel.sections,leftpanel.projects.actions,leftpanel.project,leftpanel.running.actions,leftpanel.running,leftpanel.history.actions,leftpanel.history,leftpanel.sessions,chat.header,chat.empty,message.actions,goalbar.actions,composer.leading,composer.actions,rightpanel.tabs,terminal.toolbar,scm.toolbar,bottombar,file.preview.toolbar,contextmenu.topbar,contextmenu.message,contextmenu.session,contextmenu.project,contextmenu.file,contextmenu.toolcall,tool.card.footer,settings.pages,tasks.panel,modal.dialog,sidebar.left,sidebar.right`.split(`,`),Xr=Yr.map(e=>({slot:e,cardinality:`list`}));function Zr(e){return Xr.find(t=>t.slot===e)?.cardinality??`list`}function Qr(e,t){if(t===`list`)return{entries:[...e],conflicts:[]};let n=e.findIndex(e=>!e.hidden);if(n<0)return{entries:[...e],conflicts:[]};let r=e.filter((e,t)=>t!==n&&!e.hidden);return{entries:e.map((e,t)=>t===n||e.hidden?e:{...e,hidden:!0}),winner:e[n],conflicts:r}}var $r=[{id:`host:lp-projects`,slot:`leftpanel.sections`,labelKey:`recentProjects`,icon:`folder`,kind:`action`,order:10},{id:`host:lp-running`,slot:`leftpanel.sections`,labelKey:`runningConversations`,icon:`activity`,kind:`action`,order:20},{id:`host:lp-history`,slot:`leftpanel.sections`,labelKey:`historySessions`,icon:`clock`,kind:`action`,order:30},{id:`host:brand`,slot:`topbar.primary`,labelKey:`brand`,kind:`badge`,order:1,group:`brand`},{id:`host:open-project`,slot:`topbar.primary`,labelKey:`openProject`,icon:`folder`,kind:`action`,order:3,group:`primary`},{id:`host:history`,slot:`topbar.primary`,labelKey:`openHistory`,icon:`menu`,kind:`action`,order:0,group:`panels`},{id:`host:files`,slot:`topbar.primary`,labelKey:`openFiles`,icon:`folder`,kind:`action`,order:97,group:`panels`,align:`end`},{id:`host:new-chat`,slot:`topbar.primary`,labelKey:`newChat`,icon:`plus`,kind:`action`,order:96,group:`primary`,align:`end`},{id:`host:new-ephemeral-chat`,slot:`topbar.primary`,labelKey:`newChatEphemeral`,icon:`chat`,kind:`action`,order:96.5,group:`primary`,align:`end`},{id:`host:new-sandbox`,slot:`topbar.primary`,labelKey:`newSandbox`,icon:`sandbox`,kind:`action`,order:96.6,group:`primary`,align:`end`},{id:`host:chat`,slot:`topbar.primary`,labelKey:`chat`,icon:`chat`,kind:`view`,view:`chat`,order:20,group:`views`,align:`end`},{id:`host:terminal`,slot:`topbar.primary`,labelKey:`terminal`,icon:`terminal`,kind:`view`,view:`terminal`,order:21,group:`views`,align:`end`},{id:`host:git`,slot:`topbar.primary`,labelKey:`scmTab`,icon:`git`,kind:`view`,view:`git`,order:22,group:`views`,align:`end`},{id:`host:canvas`,slot:`topbar.primary`,labelKey:`canvasTab`,icon:`share`,kind:`view`,view:`canvas`,order:22.5,group:`views`,align:`end`},{id:`host:plugins`,slot:`topbar.primary`,labelKey:`pluginMenuTitle`,icon:`🧩`,kind:`action`,order:24,group:`views`,align:`end`},{id:`host:search`,slot:`topbar.primary`,labelKey:`searchGlobal`,icon:`search`,kind:`action`,order:40,group:`tools`,align:`end`},{id:`host:browser`,slot:`topbar.primary`,labelKey:`browserControl`,icon:`browser`,kind:`action`,order:41,group:`tools`,align:`end`,hidden:!0},{id:`host:tasks`,slot:`topbar.primary`,labelKey:`bgTasks`,icon:`layers`,kind:`action`,order:42,group:`tools`,align:`end`},{id:`host:zen-mode`,slot:`topbar.primary`,labelKey:`zenMode`,icon:`feather`,kind:`action`,order:43,group:`tools`,align:`end`},{id:`host:device-center`,slot:`topbar.primary`,labelKey:`deviceCenter`,icon:`globe`,kind:`view`,view:`devices`,order:59,group:`system`,align:`end`},{id:`host:settings`,slot:`topbar.primary`,labelKey:`settingsTitle`,icon:`settings`,kind:`action`,order:60,group:`system`,align:`end`},{id:`host:language`,slot:`topbar.primary`,labelKey:`language`,icon:`globe`,kind:`action`,order:80,group:`system`,hidden:!0,align:`end`},{id:`host:theme`,slot:`topbar.primary`,labelKey:`theme`,icon:`sun`,kind:`action`,order:82,group:`system`,hidden:!0,align:`end`},{id:`host:update`,slot:`topbar.primary`,labelKey:`update`,icon:`download`,kind:`action`,order:90,group:`system`,align:`end`,hidden:!0},{id:`host:github`,slot:`topbar.primary`,labelKey:`githubRepo`,icon:`github`,kind:`action`,order:200,group:`system`,align:`end`,hidden:!0},{id:`host:conn`,slot:`bottombar`,labelKey:`connected`,icon:`dot`,kind:`badge`,order:5,group:`status`},{id:`host:engine`,slot:`bottombar`,labelKey:`engineBadge`,icon:`aperture`,kind:`action`,order:6,group:`status`},{id:`host:ctx`,slot:`bottombar`,labelKey:`context`,icon:`gauge`,kind:`badge`,order:10,group:`usage`},{id:`host:cost`,slot:`bottombar`,labelKey:`cumulativeCost`,icon:`coins`,kind:`badge`,order:11,group:`usage`},{id:`host:cache`,slot:`bottombar`,labelKey:`cacheHit`,icon:`database`,kind:`badge`,order:12,group:`usage`},{id:`host:msg-count`,slot:`bottombar`,labelKey:`messages`,icon:`message`,kind:`badge`,order:13,group:`usage`},{id:`host:plugin-status`,slot:`bottombar`,labelKey:`pluginStatus`,icon:`activity`,kind:`badge`,order:14,group:`status`},{id:`host:working`,slot:`bottombar`,labelKey:`working`,icon:`activity`,kind:`badge`,order:15,group:`status`},{id:`host:status-delegate`,slot:`bottombar`,labelKey:`delegateModeBadge`,icon:`eye`,kind:`badge`,order:16,group:`status`},{id:`host:host-metrics`,slot:`bottombar`,labelKey:`hostResources`,icon:`cpu`,kind:`badge`,order:19,group:`host`,align:`end`},{id:`host:cwd`,slot:`bottombar`,labelKey:`cwdTip`,icon:`folder`,kind:`action`,order:20,group:`context`,align:`end`},{id:`host:msg-reask`,slot:`message.actions`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,order:9},{id:`host:msg-edit-reask`,slot:`message.actions`,labelKey:`editReask`,icon:`edit`,kind:`action`,order:10},{id:`host:msg-fork`,slot:`message.actions`,labelKey:`forkSession`,icon:`branch`,kind:`action`,order:15},{id:`host:msg-rollback`,slot:`message.actions`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,order:16},{id:`host:msg-copy`,slot:`message.actions`,labelKey:`copyMessage`,icon:`copy`,kind:`action`,order:20},{id:`host:msg-copy-text`,slot:`message.actions`,labelKey:`copyText`,icon:`text`,kind:`action`,order:21},{id:`host:msg-copy-markdown`,slot:`message.actions`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,order:22},{id:`host:msg-copy-image`,slot:`message.actions`,labelKey:`copyImage`,icon:`image`,kind:`action`,order:23},{id:`host:msg-speak`,slot:`message.actions`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,order:24},{id:`host:composer-upload`,slot:`composer.actions`,labelKey:`uploadFile`,icon:`upload`,kind:`action`,order:10,align:`start`},{id:`host:composer-templates`,slot:`composer.actions`,labelKey:`tpl.openPicker`,icon:`grid`,kind:`action`,order:110,align:`start`},{id:`host:composer-model`,slot:`composer.actions`,labelKey:`selectModel`,icon:`cpu`,kind:`action`,order:120,align:`start`},{id:`host:composer-thinking`,slot:`composer.actions`,labelKey:`thinkingLevel`,icon:`zap`,kind:`action`,order:130,align:`start`},{id:`host:composer-dsh-perm`,slot:`composer.actions`,labelKey:`dshPerm`,icon:`lock`,kind:`action`,order:140,align:`start`},{id:`host:composer-dsh-preset`,slot:`composer.actions`,labelKey:`dshPreset`,icon:`layers`,kind:`action`,order:150,align:`start`},{id:`host:composer-send`,slot:`composer.actions`,labelKey:`sendTip`,icon:`send`,kind:`action`,order:200,align:`end`},{id:`host:fp-md`,slot:`file.preview.toolbar`,labelKey:`showMarkdownPreview`,icon:`eye`,kind:`action`,order:10},{id:`host:fp-toc`,slot:`file.preview.toolbar`,labelKey:`previewTocLabel`,icon:`list`,kind:`action`,order:15},{id:`host:fp-html`,slot:`file.preview.toolbar`,labelKey:`showHtmlPreview`,icon:`code`,kind:`action`,order:20},{id:`host:fp-edit`,slot:`file.preview.toolbar`,labelKey:`editFile`,icon:`edit`,kind:`action`,order:30},{id:`host:fp-wrap`,slot:`file.preview.toolbar`,labelKey:`enableWrap`,icon:`wrap`,kind:`action`,order:40},{id:`host:fp-zoom`,slot:`file.preview.toolbar`,labelKey:`zoomIn`,icon:`zoom`,kind:`action`,order:50},{id:`host:fp-download`,slot:`file.preview.toolbar`,labelKey:`downloadFile`,icon:`download`,kind:`action`,order:60},{id:`host:fp-ref`,slot:`file.preview.toolbar`,labelKey:`referenceTip`,icon:`link`,kind:`action`,order:70},{id:`host:fp-full`,slot:`file.preview.toolbar`,labelKey:`fullscreen`,icon:`maximize`,kind:`action`,order:80},{id:`host:fp-close`,slot:`file.preview.toolbar`,labelKey:`close`,icon:`x`,kind:`action`,order:90},{id:`host:goal-pill`,slot:`goalbar.actions`,labelKey:`goalBarTitle`,icon:`target`,kind:`action`,order:5},{id:`host:goal-set`,slot:`goalbar.actions`,labelKey:`goalBarSet`,icon:`check`,kind:`action`,order:10},{id:`host:goal-wizard`,slot:`goalbar.actions`,labelKey:`goalWizardBtn`,icon:`search`,kind:`action`,order:20},{id:`host:goal-lock`,slot:`goalbar.actions`,labelKey:`goalBarLocked`,icon:`lock`,kind:`action`,order:30},{id:`host:goal-plan`,slot:`goalbar.actions`,labelKey:`planMode`,icon:`list`,kind:`action`,order:25},{id:`host:goal-collapse`,slot:`goalbar.actions`,labelKey:`collapsePanel`,icon:`chevron-up`,kind:`action`,order:40},{id:`host:goal-model`,slot:`goalbar.actions`,labelKey:`goalBarReviewModel`,icon:`cpu`,kind:`action`,order:50},{id:`host:goal-rounds`,slot:`goalbar.actions`,labelKey:`goalBarMaxRounds`,icon:`hash`,kind:`action`,order:60},{id:`host:goal-execmodel`,slot:`goalbar.actions`,labelKey:`goalBarExecModel`,icon:`cpu`,kind:`action`,order:55},{id:`host:goal-openrole`,slot:`goalbar.actions`,labelKey:`goalBarOpenExec`,icon:`search`,kind:`action`,order:65},{id:`host:goal-clear`,slot:`goalbar.actions`,labelKey:`goalBarClear`,icon:`x`,kind:`action`,order:70},{id:`host:scm-changes`,slot:`scm.toolbar`,labelKey:`scmChanges`,icon:`file`,kind:`action`,order:10},{id:`host:scm-history`,slot:`scm.toolbar`,labelKey:`scmHistory`,icon:`clock`,kind:`action`,order:20},{id:`host:scm-refresh`,slot:`scm.toolbar`,labelKey:`scmRefreshTip`,icon:`refresh`,kind:`action`,order:30},{id:`host:scm-branch`,slot:`scm.toolbar`,labelKey:`scmSwitchBranch`,icon:`git`,kind:`action`,order:40},{id:`host:scm-switch`,slot:`scm.toolbar`,labelKey:`scmSwitch`,icon:`git`,kind:`action`,order:50},{id:`host:scm-push`,slot:`scm.toolbar`,labelKey:`scmPush`,icon:`upload`,kind:`action`,order:60},{id:`host:scm-pull`,slot:`scm.toolbar`,labelKey:`scmPull`,icon:`download`,kind:`action`,order:70},{id:`host:scm-input`,slot:`scm.toolbar`,labelKey:`scmCommitPlaceholder`,icon:`edit`,kind:`action`,order:80},{id:`host:scm-genmsg`,slot:`scm.toolbar`,labelKey:`scmGenMsg`,icon:`cpu`,kind:`action`,order:85},{id:`host:scm-commit`,slot:`scm.toolbar`,labelKey:`scmCommit`,icon:`check`,kind:`action`,order:90},{id:`host:scm-commit-all`,slot:`scm.toolbar`,labelKey:`scmCommitAll`,icon:`check`,kind:`action`,order:100},{id:`host:scm-term`,slot:`scm.toolbar`,labelKey:`terminal`,icon:`terminal`,kind:`action`,order:110},{id:`host:term-cmd-refresh`,slot:`terminal.toolbar`,labelKey:`rerun`,icon:`refresh`,kind:`action`,order:10},{id:`host:term-cmd-new`,slot:`terminal.toolbar`,labelKey:`newCommand`,icon:`plus`,kind:`action`,order:20},{id:`host:term-tab-new`,slot:`terminal.toolbar`,labelKey:`newTerminal`,icon:`plus`,kind:`action`,order:30},{id:`host:right-files`,slot:`rightpanel.tabs`,labelKey:`openFiles`,icon:`folder`,kind:`view`,view:`files`,order:10},{id:`host:conv-rename`,slot:`contextmenu.session`,labelKey:`renameSession`,icon:`edit`,kind:`action`,context:`session`,order:1},{id:`host:conv-pin`,slot:`contextmenu.session`,labelKey:`pinConversation`,icon:`pin`,kind:`action`,context:`session`,order:2},{id:`host:conv-takeover`,slot:`contextmenu.session`,labelKey:`takeoverConversation`,icon:`chat`,kind:`action`,context:`session`,order:5},{id:`host:conv-dismiss-subagents`,slot:`contextmenu.session`,labelKey:`dismissFinishedSubagents`,icon:`x`,kind:`action`,context:`session`,order:10},{id:`host:conv-force-dismiss`,slot:`contextmenu.session`,labelKey:`forceDismissConversation`,icon:`x`,kind:`action`,context:`session`,order:20},{id:`host:conv-persist`,slot:`contextmenu.session`,labelKey:`persistSubagent`,icon:`save`,kind:`action`,context:`session`,order:25},{id:`host:conv-copy-id`,slot:`contextmenu.session`,labelKey:`copyConversationId`,icon:`copy`,kind:`action`,context:`session`,order:30},{id:`host:conv-copy-path`,slot:`contextmenu.session`,labelKey:`copyConversationPath`,icon:`copy`,kind:`action`,context:`session`,order:40},{id:`host:conv-copy-link`,slot:`contextmenu.session`,labelKey:`copyConversationLink`,icon:`link`,kind:`action`,context:`session`,order:45},{id:`host:conv-quote`,slot:`contextmenu.session`,labelKey:`quoteConversation`,icon:`chat`,kind:`action`,context:`session`,order:50},{id:`host:file-open`,slot:`contextmenu.file`,labelKey:`fileOpenPreview`,icon:`open`,kind:`action`,context:`file`,order:11,group:`open`},{id:`host:file-enter`,slot:`contextmenu.file`,labelKey:`fileEnterDir`,icon:`folder`,kind:`action`,context:`file`,order:12,group:`open`},{id:`host:file-download`,slot:`contextmenu.file`,labelKey:`downloadFile`,icon:`download`,kind:`action`,context:`file`,order:13,group:`open`},{id:`host:file-compress`,slot:`contextmenu.file`,labelKey:`fileCompress`,icon:`file`,kind:`action`,context:`file`,order:16,group:`archive`},{id:`host:file-extract`,slot:`contextmenu.file`,labelKey:`fileExtract`,icon:`folder`,kind:`action`,context:`file`,order:17,group:`archive`},{id:`host:file-compress-download`,slot:`contextmenu.file`,labelKey:`fileCompressDownload`,icon:`download`,kind:`action`,context:`file`,order:18,group:`archive`},{id:`host:file-upload-folder`,slot:`contextmenu.file`,labelKey:`fileUploadFolder`,icon:`upload`,kind:`action`,context:`file`,order:25,group:`new`},{id:`host:file-open-project`,slot:`contextmenu.file`,labelKey:`openAsProject`,icon:`folder`,kind:`action`,context:`file`,order:14,group:`open`},{id:`host:file-add-root`,slot:`contextmenu.file`,labelKey:`addWorkspaceRoot`,icon:`folder`,kind:`action`,context:`file`,order:15,group:`open`},{id:`host:file-reveal`,slot:`contextmenu.file`,labelKey:`fileReveal`,icon:`folder`,kind:`action`,context:`file`,order:16,group:`open`},{id:`host:file-open-default`,slot:`contextmenu.file`,labelKey:`fileOpenDefault`,icon:`open`,kind:`action`,context:`file`,order:17,group:`open`},{id:`host:file-new-file`,slot:`contextmenu.file`,labelKey:`fileNewFile`,icon:`file`,kind:`action`,context:`file`,order:21,group:`new`},{id:`host:file-new-dir`,slot:`contextmenu.file`,labelKey:`fileNewDir`,icon:`folder`,kind:`action`,context:`file`,order:22,group:`new`},{id:`host:file-upload`,slot:`contextmenu.file`,labelKey:`uploadToFolder`,icon:`upload`,kind:`action`,context:`file`,order:23,group:`new`},{id:`host:file-paste`,slot:`contextmenu.file`,labelKey:`filePaste`,icon:`paste`,kind:`action`,context:`file`,order:24,group:`new`},{id:`host:file-attach-ref`,slot:`contextmenu.file`,labelKey:`referenceTip`,icon:`link`,kind:`action`,context:`file`,order:32,group:`chat`},{id:`host:file-attach-folder`,slot:`contextmenu.file`,labelKey:`linkFolderTip`,icon:`link`,kind:`action`,context:`file`,order:33,group:`chat`},{id:`host:file-rename`,slot:`contextmenu.file`,labelKey:`fileRename`,icon:`edit`,kind:`action`,context:`file`,order:41,group:`edit`},{id:`host:file-duplicate`,slot:`contextmenu.file`,labelKey:`fileDuplicate`,icon:`copy`,kind:`action`,context:`file`,order:42,group:`edit`},{id:`host:file-cut`,slot:`contextmenu.file`,labelKey:`fileCut`,icon:`cut`,kind:`action`,context:`file`,order:43,group:`edit`},{id:`host:file-copy`,slot:`contextmenu.file`,labelKey:`fileCopyEntry`,icon:`copy`,kind:`action`,context:`file`,order:44,group:`edit`},{id:`host:file-copy-name`,slot:`contextmenu.file`,labelKey:`copyName`,icon:`copy`,kind:`action`,context:`file`,order:51,group:`clipboard`},{id:`host:file-copy-path`,slot:`contextmenu.file`,labelKey:`copyPath`,icon:`copy`,kind:`action`,context:`file`,order:52,group:`clipboard`},{id:`host:file-copy-rel`,slot:`contextmenu.file`,labelKey:`fileCopyRelPath`,icon:`copy`,kind:`action`,context:`file`,order:53,group:`clipboard`},{id:`host:file-refresh`,slot:`contextmenu.file`,labelKey:`fileRefresh`,icon:`refresh`,kind:`action`,context:`file`,order:54,group:`clipboard`},{id:`host:file-delete`,slot:`contextmenu.file`,labelKey:`fileDelete`,icon:`trash`,kind:`action`,context:`file`,order:61,group:`danger`},{id:`host:msg-ctx-copy-markdown`,slot:`contextmenu.message`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,context:`message`,order:10,group:`copy`},{id:`host:msg-ctx-copy-text`,slot:`contextmenu.message`,labelKey:`copyText`,icon:`text`,kind:`action`,context:`message`,order:11,group:`copy`},{id:`host:msg-ctx-copy-image`,slot:`contextmenu.message`,labelKey:`copyImage`,icon:`image`,kind:`action`,context:`message`,order:12,group:`copy`},{id:`host:msg-ctx-copy-link`,slot:`contextmenu.message`,labelKey:`copyMessageLink`,icon:`link`,kind:`action`,context:`message`,order:13,group:`copy`},{id:`host:msg-ctx-reask`,slot:`contextmenu.message`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,context:`message`,order:19,group:`action`},{id:`host:msg-ctx-edit-reask`,slot:`contextmenu.message`,labelKey:`editReask`,icon:`edit`,kind:`action`,context:`message`,order:20,group:`action`},{id:`host:msg-ctx-fork`,slot:`contextmenu.message`,labelKey:`forkSession`,icon:`branch`,kind:`action`,context:`message`,order:21,group:`action`},{id:`host:msg-ctx-rollback`,slot:`contextmenu.message`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,context:`message`,order:22,group:`action`},{id:`host:msg-ctx-speak`,slot:`contextmenu.message`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,context:`message`,order:23,group:`action`},{id:`host:tool-info`,slot:`contextmenu.toolcall`,labelKey:`toolInfoMenuLabel`,icon:`info`,kind:`action`,context:`toolcall`,order:10}],ei=`__view`,ti=new Set([`host:settings`,`host:history`,`host:files`]),ni=new Set([`host:history`,`host:files`]);function ri(e){return`${e}:${ei}`}function ii(e){return e.source.startsWith(`plugin:`)?e.id===ri(e.source.slice(7)):!1}function ai(e,t,n){let r=ri(t),i=(e?.hidden??[]).filter(e=>e!==r),a=(e?.shown??[]).filter(e=>e!==r);return n?a.push(r):i.push(r),{...e,hidden:i,shown:a}}function oi(e,t){let n=t.map(ri),r=new Set(n),i=(e?.order??[]).filter(e=>!r.has(e));return{...e,order:[...i,...n]}}var si=`host:brand`,ci=[`host:brand-logo`,`host:brand-name`];function li(e){if(!((e.hidden??[]).some(e=>ci.includes(e))||(e.shown??[]).some(e=>ci.includes(e))||(e.order??[]).some(e=>ci.includes(e))||ci.some(t=>e.align?.[t]!==void 0)||ci.some(t=>e.groups?.[t]!==void 0)||ci.some(t=>e.labels?.[t]!==void 0)||ci.some(t=>e.slots?.[t]!==void 0)))return e;let t=e=>{if(!e)return;let t=[];for(let n of e){let e=ci.includes(n)?si:n;t.includes(e)||t.push(e)}return t},n=(e,t)=>{if(!e)return;let n={};for(let[t,r]of Object.entries(e))ci.includes(t)||(n[t]=r);if(n[si]===void 0){let r=t?e[ci[0]]??e[ci[1]]:e[ci[1]]??e[ci[0]];r!==void 0&&(n[si]=r)}return n},r=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ci.includes(n)||(t[n]=r);if(t[si]===void 0){let n=e[ci[0]]??e[ci[1]];n!==void 0&&(t[si]=n)}return t},i=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ci.includes(n)||(t[n]=r);if(t[si]===void 0){let n=e[ci[0]]??e[ci[1]];n!==void 0&&(t[si]=n)}return t};return{...e,...e.hidden?{hidden:t(e.hidden)}:{},...e.shown?{shown:t(e.shown)}:{},...e.order?{order:t(e.order)}:{},...e.groups?{groups:n(e.groups,!0)}:{},...e.labels?{labels:n(e.labels,!1)}:{},...e.align?{align:r(e.align)}:{},...e.slots?{slots:i(e.slots)}:{}}}function ui(e){return e.map(e=>{if(e.view===!1)return e;let t=e.ui?.items??[];if(t.some(e=>e.id===`__view`))return e;let n={id:ei,slot:`topbar.primary`,label:e.name,...e.icon?{icon:e.icon}:{},...e.iconSvg?{iconSvg:e.iconSvg}:{},kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!0};return{...e,ui:{items:[...t,n],arrange:e.ui?.arrange??[]}}})}function di(e){return typeof e==`string`&&Yr.includes(e)}function fi(e,t){return t?e.label:e.labelEn??e.label}function pi(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function mi(e,t,n,r,i){let a=`${e}#${r.id}`,o=hi(a,t,n,r.children,i),s=pi(r,i),c=gi(r.options,i),l=_i(r.progress);return{id:a,slot:t,source:n,label:fi(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??`action`,...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...l===void 0?{}:{progress:l},...r.when?{when:r.when}:{},...c?{options:c}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[]}}function hi(e,t,n,r,i){return r?.length?r.map((r,a)=>({entry:mi(e,t,n,r,i),index:a})).sort((e,t)=>e.entry.order===t.entry.order?e.index-t.index:e.entry.order-t.entry.order).map(e=>e.entry):[]}function gi(e,t){if(e?.length)return e.slice(0,32).map(e=>({value:e.value,label:t?e.label??e.labelEn??e.value:e.labelEn??e.label??e.value}))}function _i(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function vi(e,t,n,r,i,a){let o=hi(e,t,n,r.children,i),s=pi(r,i),c=_i(r.progress),l=gi(r.options,i);return{id:e,slot:t,source:n,label:fi(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??(t===`settings.pages`?`page`:`action`),...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:r.align??`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...c===void 0?{}:{progress:c},...l?{options:l}:{},...r.when?{when:r.when}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[],seq:a}}function yi(e,t){return[...e].sort((e,n)=>{let r=t.get(e.id),i=t.get(n.id);return r!==void 0||i!==void 0?r!==void 0&&i!==void 0?r-i:r===void 0?1:-1:e.order===n.order?e.seq-n.seq:e.order-n.order})}function bi(e,t){let n=e.filter(e=>ii(e)&&!t.has(e.id));if(n.length===0)return e;let r=e.filter(e=>!ii(e)||t.has(e.id)),i=[`host:git`,`host:terminal`,`host:chat`].map(e=>r.findIndex(t=>t.id===e)).find(e=>e>=0)??-1,a=r.findIndex(e=>e.id===`host:plugins`),o=i+1;return a>=o&&(o=a),o=Math.max(0,Math.min(o,r.length)),[...r.slice(0,o),...n,...r.slice(o)]}function xi(e,t){let n=H(t.locale),r=new Set(t.disabledPlugins??[]),i=li(t.layout??{}),a=e=>{t.diagnostics?.push({level:e.level??`warn`,...e})},o=new Map,s=0;for(let e of $r)o.set(e.id,{id:e.id,slot:e.slot,source:`host`,label:t.t(e.labelKey),labelKey:e.labelKey,...e.icon?{icon:e.icon}:{},kind:e.kind,...e.view?{view:e.view}:{},...e.group?{group:e.group}:{},order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[],seq:s++});for(let t of e){if(r.has(t.id)){let e=t.ui?.items?.length??0,n=t.ui?.arrange?.length??0;(e>0||n>0)&&a({level:`info`,pluginId:t.id,message:`plugin "${t.id}" is disabled by the user — its ${e} UI item(s) are not rendered`});continue}if(t.error){a({level:`error`,pluginId:t.id,message:`plugin "${t.id}" failed to activate (${t.error}) — its UI items are not rendered`});continue}let e=`plugin:${t.id}`;for(let r of t.ui?.items??[]){if(!di(r.slot)){a({pluginId:t.id,entryId:r.id,message:`item "${t.id}:${r.id}" declares unknown slot "${String(r.slot)}" — dropped (valid slots: see docs/architecture-plugins.md)`});continue}if(r.slot===`leftpanel.sections`&&r.kind!==`view`){a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" targets leftpanel.sections: only kind="view" (a plugin section) is accepted — dropped`});continue}if(r.kind&&!qr.has(r.kind)&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares unknown kind "${r.kind}" — the render layer falls back to a plain button`}),Array.isArray(r.when))for(let e of r.when)Jr.has(e)||a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares when:"${e}" which the host does not know — it is ignored (the item still renders)`});else r.when!==void 0&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" has a non-array "when" — ignored`});let i=`${t.id}:${r.id}`,c=o.get(i);c&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item id "${r.id}" is declared more than once — the later declaration wins (order/visibility are inherited from the first)`}),o.set(i,vi(i,r.slot,e,r,n,c?.seq??s++))}}for(let t of e)if(!(t.error||r.has(t.id)))for(let e of t.ui?.arrange??[]){let n=o.get(e.id);Ci(o,e,t.id),n||a({pluginId:t.id,entryId:e.id,message:`arrange target "${e.id}" does not exist — op ignored (is the providing plugin installed / not disabled?)`})}let c=new Map,l=(e,t)=>{let n=c.get(e)??[];n.includes(t)||n.push(t),c.set(e,n)};for(let e of i.hidden??[]){let t=o.get(e);t&&(t.hidden=!0,l(e,`hidden`))}for(let e of i.shown??[]){let t=o.get(e);t&&(t.hidden=!1,l(e,`hidden`))}for(let[e,t]of Object.entries(i.groups??{})){let n=o.get(e);n&&(n.group=t,l(e,`group`))}for(let[e,t]of Object.entries(i.align??{})){let n=o.get(e);!n||t!==`start`&&t!==`center`&&t!==`end`||(n.align=t,l(e,`align`))}for(let[e,t]of Object.entries(i.labels??{})){let n=o.get(e);n&&(n.label=t,n.labelExplicit=!0,l(e,`label`))}for(let[e,t]of Object.entries(i.slots??{})){let n=o.get(e);n&&di(t)&&n.slot!==t&&(n.movedFrom=n.movedFrom??n.slot,n.slot=t,l(e,`slot`))}for(let e of ti){let t=o.get(e);t&&(i.slots?.[e]||(t.slot=`topbar.primary`),t.hidden=!1)}let u=new Map;(i.order??[]).forEach((e,t)=>{o.has(e)&&(u.has(e)||u.set(e,t),l(e,`order`))});for(let e of Object.values(Lr)){let t=o.get(e);t&&t.slot!==`leftpanel.sections`&&(a({entryId:e,slot:t.slot,message:`"${e}" must stay in leftpanel.sections — the move is ignored`}),t.slot=`leftpanel.sections`,delete t.movedFrom)}let d=new Map;for(let e of Yr)d.set(e,[]);for(let e of o.values())d.get(e.slot)?.push(e);let f={};for(let e of Yr){let t=yi(d.get(e)??[],u),n=Qr(e===`topbar.primary`?bi(t,u):t,Zr(e));if(n.winner&&n.conflicts.length>0)for(let t of n.conflicts)a({level:`error`,pluginId:t.source.startsWith(`plugin:`)?t.source.slice(7):void 0,entryId:t.id,slot:e,message:`slot "${e}" is single-cardinality; "${n.winner.id}" won and "${t.id}" was hidden`});f[e]=n.entries.map(e=>Si(e,c.get(e.id)??[]))}return f}function Si(e,t){let n={...e,userOverrides:t};return delete n.seq,n}function Ci(e,t,n){let r=e.get(t.id);if(!r)return;let i=!1;t.hide!==void 0&&(r.hidden=t.hide,i=!0),t.group!==void 0&&(r.group=t.group,i=!0),t.order!==void 0&&(r.order=t.order,i=!0),t.align!==void 0&&(r.align=t.align,i=!0),t.label!==void 0&&(r.label=t.label,r.labelExplicit=!0,i=!0),t.hint!==void 0&&(r.hint=t.hint,i=!0),t.icon!==void 0&&(r.icon=t.icon,i=!0),t.iconSvg!==void 0&&(r.iconSvg=t.iconSvg||void 0,i=!0),t.slot!==void 0&&di(t.slot)&&t.slot!==r.slot&&(r.movedFrom=r.movedFrom??r.slot,r.slot=t.slot,i=!0),i&&r.source!==`plugin:${n}`&&!r.arrangedBy.includes(n)&&r.arrangedBy.push(n)}function wi(e){let t=[],n=[],r=[];for(let i of e)i.align===`end`?r.push(i):i.align===`center`?n.push(i):t.push(i);return{start:t,center:n,end:r}}function Ti(e,t){let n=e??{},r={},i=t===si?[t,...ci]:[t],a=(n.hidden??[]).filter(e=>!i.includes(e)),o=(n.shown??[]).filter(e=>!i.includes(e)),s=(n.order??[]).filter(e=>!i.includes(e));a.length>0&&(r.hidden=a),o.length>0&&(r.shown=o),s.length>0&&(r.order=s);let c=Di(n.groups,t),l=Di(n.labels,t),u=Di(n.align,t),d=Di(n.slots,t);if(t===si)for(let e of ci)c=Di(c,e),l=Di(l,e),u=Di(u,e),d=Di(d,e);return c&&(r.groups=c),l&&(r.labels=l),u&&(r.align=u),d&&(r.slots=d),n.topbarText!==void 0&&(r.topbarText=n.topbarText),n.sideDockFloat!==void 0&&(r.sideDockFloat=n.sideDockFloat),r}function Ei(){return{}}function Di(e,t){if(!e)return;let n={},r=!1;for(let[i,a]of Object.entries(e))i!==t&&(n[i]=a,r=!0);return r?n:void 0}var Oi=new Set([`host:files`]);function ki(e,t){let n=e=>e===`center`?1:e===`end`?2:0;return[...e].sort((e,r)=>n(e.align)-n(r.align)||t(e.id)-t(r.id))}function Ai(e,t,n,r,i=new Set){let a=new Set;if(!Number.isFinite(t)||t<=0)return a;let o=e.filter(e=>i.has(e.id)&&e.width>0).reduce((e,t)=>e+t.width+n,0),s=Math.max(0,t-Math.max(0,r)-o),c=0,l=!1;for(let t of e){if(!(t.width>0)||i.has(t.id))continue;let e=t.width+n;if(l||c+e>s){l=!0,a.add(t.id);continue}c+=e}return a}var ji=null,Mi=new Set;function Ni(){for(let e of Mi)e()}function Pi(e){ji={x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,slot:e.slot,target:e.target??{id:``},entries:Array.isArray(e.entries)?e.entries:[],...typeof e.onHostAction==`function`?{onHostAction:e.onHostAction}:{}},Ni()}function Fi(){ji!==null&&(ji=null,Ni())}function Ii(e){return Mi.add(e),()=>{Mi.delete(e)}}function Li(){return ji}function Ri(){return(0,Q.useSyncExternalStore)(Ii,Li,Li)}function zi(e){return Number.isFinite(e)?e:0}function Bi(e,t,n,r,i,a){let o=Math.max(0,zi(n)),s=Math.max(0,zi(r)),c=Math.max(8,zi(i)-o-8),l=Math.max(8,zi(a)-s-8);return{x:Math.min(Math.max(8,zi(e)),c),y:Math.min(Math.max(8,zi(t)),l)}}function Vi(e,t){let n=String(t?.kind??``);if(e===`contextmenu.file`)return{"file.isDir":n===`dir`||n===`list`&&t?.id!==`@root`,"file.isFile":n===`file`};if(e===`contextmenu.session`)return{"session.isRunning":n===`running`};if(e===`contextmenu.message`){let e=!1;try{let t=window.getSelection?.();e=!!t&&!t.isCollapsed&&t.toString().trim().length>0}catch{e=!1}return{"message.hasSelection":e}}return{}}function Hi(e,t){if(!Array.isArray(e)||e.length===0)return!1;for(let n of e){if(typeof n!=`string`||!n)continue;let e=n.trim();if(e===`disabled`||e===`never`)return!0;if(e!==`always`){if(e.startsWith(`!`)){let n=e.slice(1).trim();if(!n)continue;if(!t||t[n]!==!0)return!0;continue}if(t&&t[e]===!1)return!0}}return!1}function Ui(e,t){return!e||Hi(e.when,t)}function Wi(e){let t=new Map;return{items:(Array.isArray(e)?e:[]).map(e=>{if(!e||e.kind!==`select`||!e.options?.length||e.children?.length)return e;let n=e.options.map((t,n)=>({id:`${e.id}#${n}`,slot:e.slot,source:e.source,label:t.label,kind:`action`,order:100,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));return n.forEach((n,r)=>t.set(n.id,{parent:e,value:e.options[r].value})),{...e,kind:`menu`,children:n}}),selectParents:t}}function Gi(e){if(!Array.isArray(e)||e.length===0)return[];let t=e.filter(e=>e&&e.hidden!==!0),n=t.filter(e=>e.kind!==`divider`),r=new Map,i=new Map;n.forEach((e,t)=>{let n=e.group??``;r.has(n)||r.set(n,t);let a=Number.isFinite(e.order)?e.order:100,o=i.get(n);(o===void 0||a<o)&&i.set(n,a)});let a=[...r.keys()].sort((e,t)=>{let n=i.get(e)??100,a=i.get(t)??100;return n===a?(r.get(e)??0)-(r.get(t)??0):n-a}),o=new Map(a.map((e,t)=>[e,t])),s=new Map;n.forEach((e,t)=>s.set(e,t));let c=[...n].sort((e,t)=>{let n=o.get(e.group??``)??0,r=o.get(t.group??``)??0;if(n!==r)return n-r;let i=Number.isFinite(e.order)?e.order:100,a=Number.isFinite(t.order)?t.order:100;return i===a?(s.get(e)??0)-(s.get(t)??0):i-a}),l=new Map;t.forEach((e,n)=>{if(e.kind!==`divider`)return;let r=t.slice(n+1).find(e=>e.kind!==`divider`);if(!r)return;let i=l.get(r)??[];i.push(e),l.set(r,i)});let u=[];for(let e of c){for(let t of l.get(e)??[])u.push(t);u.push(e)}return u}function Ki(e){let t=[],n=null,r=!1;return e.forEach((e,i)=>{if(!e||e.kind===`divider`){r=!0;return}let a=e.group??``;n!==null&&(r||a!==n)&&t.push({kind:`sep`,key:`sep:${i}`}),t.push({kind:`item`,key:`${e.id}#${i}`,index:i,entry:e}),n=a,r=!1}),t}function qi(e,t){return!e||e.kind===`divider`||e.hidden===!0?!1:!Ui(e,t)}function Ji(e,t,n,r){let i=Array.isArray(e)?e.length:0;if(i===0)return-1;let a=n>=0?1:-1,o=Number.isFinite(t)?Math.trunc(t):-1;(o<0||o>=i)&&(o=a>0?-1:i);for(let t=0;t<i;t++)if(o=(o+a+i)%i,qi(e[o],r))return o;return-1}var Yi={menu:`☰`,folder:`📁`,plus:`+`,chat:`💬`,terminal:`▙`,git:`⎇`,search:`🔍`,browser:`🌐`,layers:`🗂`,settings:`⚙`,sound:`🔊`,globe:`🌍`,sun:`☀`,download:`⤓`,github:`⌗`,x:`✕`,upload:`⬆`,copy:`⧉`,cut:`✂`,paste:`📋`,trash:`🗑`,file:`📄`,open:`↗`,refresh:`⟳`,link:`🔗`,edit:`✎`,dot:`●`,info:`ⓘ`,cpu:`▣`,gauge:`▤`,coins:`◉`,database:`▥`,message:`✉`,activity:`〜`,markdown:`📄`,text:`≡`,image:`🖼`,branch:`⚚`,undo:`↺`,pin:`📌`,volume:`🔊`};function Xi(e){let t=(e??``).trim();return t?Yi[t.toLowerCase()]||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:``):``}function Zi(e,t,n){let r=Math.max(8,e.left-8),i=e.bottom+8;return r+t.width>n.width-8&&(r=Math.max(8,e.right+8-t.width)),i+t.height>n.height-8&&(i=Math.max(8,e.top-8-t.height)),{left:r,top:i}}function Qi(){return typeof window<`u`&&window.matchMedia?.(`(hover: hover) and (pointer: fine)`)?.matches===!0}function $i(e){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)({left:0,top:0});return(0,Q.useEffect)(()=>{if(!r)return;let e=n.current,i=t.current;if(!e||!i)return;let a=e.getBoundingClientRect(),s=Zi(i.getBoundingClientRect(),a,{width:window.innerWidth,height:window.innerHeight});o(e=>e.left===s.left&&e.top===s.top?e:s)},[r,e]),(0,Q.useEffect)(()=>{if(!r)return;let e=0,a=()=>{cancelAnimationFrame(e),e=requestAnimationFrame(()=>{let e=t.current,r=n.current;if(!e||!r)return;let a=e.getBoundingClientRect();if(a.bottom<0||a.top>window.innerHeight||a.right<0||a.left>window.innerWidth){i(!1);return}let s=Zi(a,r.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});o(e=>e.left===s.left&&e.top===s.top?e:s)})};return window.addEventListener(`scroll`,a,!0),window.addEventListener(`resize`,a),()=>{cancelAnimationFrame(e),window.removeEventListener(`scroll`,a,!0),window.removeEventListener(`resize`,a)}},[r]),{anchorRef:t,show:()=>{let e=t.current?.getBoundingClientRect();e&&(o({left:Math.max(8,e.left-8),top:e.bottom+8}),i(!0))},hide:()=>i(!1),onKeyDown:e=>{e.key===`Escape`&&e.target.blur()},tipPortal:r&&(0,bn.createPortal)((0,$.jsx)(`span`,{ref:n,className:`set-tip-bubble open`,role:`tooltip`,style:{position:`fixed`,left:a.left,top:a.top},children:e}),document.body)}}function ea({text:e}){let{anchorRef:t,show:n,hide:r,onKeyDown:i,tipPortal:a}=$i(e);return(0,$.jsxs)(`span`,{ref:t,className:`set-tip`,tabIndex:0,"aria-label":e,onMouseEnter:n,onMouseLeave:r,onFocus:n,onBlur:r,onKeyDown:i,children:[(0,$.jsx)(K,{}),a]})}function ta({tip:e,children:t,onMouseEnter:n,onMouseLeave:r,onFocus:i,onBlur:a,onKeyDown:o,...s}){let{anchorRef:c,show:l,hide:u,onKeyDown:d,tipPortal:f}=$i(e);return(0,$.jsxs)(`button`,{ref:c,type:`button`,"aria-label":s[`aria-label`]??e,...s,onMouseEnter:e=>{l(),n?.(e)},onMouseLeave:e=>{u(),r?.(e)},onFocus:e=>{l(),i?.(e)},onBlur:e=>{u(),a?.(e)},onKeyDown:e=>{d(e),o?.(e)},children:[t,f]})}var na=new Set;function ra(e){return na.add(e),()=>{na.delete(e)}}function ia(e){for(let t of na)try{t(e)}catch(e){console.error(`[remote-ssh-client] listener error:`,e)}}function aa(e,t,n,r){return`ssh://${e}@${t}:${n}${r.startsWith(`/`)?r:`/${r}`}`}function oa(e){return!!(e&&e.startsWith(`ssh://`))}function sa(e){if(!oa(e))return null;let t=/^ssh:\/\/([^@]+)@([^:]+):(\d+)(\/.*)$/.exec(e);return t?{username:t[1],host:t[2],port:parseInt(t[3],10),remotePath:t[4]}:null}var ca=1;function la(e){let t=`probe_${Date.now()}_${ca++}`;return new Promise(n=>{let r=ra(e=>{e.type===`remote_ssh_probe_result`&&e.reqId===t&&(r(),n({ok:e.ok,connectionId:e.connectionId,error:e.error,system:e.system,tools:e.tools,packageManager:e.packageManager,suggestedInstall:e.suggestedInstall}))});Z({type:`remote_ssh_probe`,reqId:t,params:e})||(r(),n({ok:!1,error:`WebSocket 连接不可用,请稍候重试`}))})}function ua(e,t){let n=`listdir_${Date.now()}_${ca++}`;return new Promise(r=>{let i=ra(e=>{e.type===`remote_ssh_list_dir_result`&&e.reqId===n&&(i(),r({ok:e.ok,connectionId:e.connectionId,path:e.path,parentPath:e.parentPath,items:e.items,error:e.error}))});Z({type:`remote_ssh_list_dir`,reqId:n,connectionId:e,path:t})||(i(),r({ok:!1,connectionId:e,path:t||`/`,items:[],error:`WebSocket 连接不可用`}))})}function da(e,t){let n=`install_${Date.now()}_${ca++}`;return new Promise(r=>{let i=ra(e=>{e.type===`remote_ssh_install_result`&&e.reqId===n&&(i(),r({ok:e.ok,connectionId:e.connectionId,tool:e.tool,output:e.output,error:e.error}))});Z({type:`remote_ssh_install_tools`,reqId:n,connectionId:e,tools:t})||(i(),r({ok:!1,connectionId:e,tool:t[0]||``,error:`WebSocket 连接不可用`}))})}function fa(){let e=`profiles_${Date.now()}_${ca++}`;return new Promise(t=>{let n=ra(r=>{r.type===`remote_ssh_profiles_result`&&r.reqId===e&&(n(),t(r.profiles))});Z({type:`remote_ssh_list_profiles`,reqId:e})||(n(),t([]))})}function pa(e){Z({type:`remote_ssh_delete_profile`,name:e})}var ma=`@root`,ha=e=>e.endsWith(`/`)?e:e+`/`;function ga(e,t){let n=t.trim(),r=e.replace(/\\/g,`/`);return r.endsWith(`/`)?r+n:(/^[A-Za-z]:$/.test(r),r+`/`+n)}function _a(e){let t=e.trim();return!(!t||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`))}var va=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;if(t===`@root`||t===`/`)return null;let n=t.lastIndexOf(`/`);if(n<0)return/^[A-Za-z]:$/.test(t)?ma:null;if(n===0)return`/`;let r=t.slice(0,n);return/^[A-Za-z]:$/.test(r)?r+`/`:r};function ya({currentCwd:e,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,mode:o=`folder`,onCreateProject:s,className:c,backdropClassName:l,role:u,ariaLabel:d,localOnly:f=!1}){let p=V(),m=H(Se()),h=rn().remoteSsh&&!f,_=en(`homeDir`),v=en(`desktopDir`),[b,x]=(0,Q.useState)(()=>h&&oa(e)?`remote`:`local`);(0,Q.useEffect)(()=>{!h&&b===`remote`&&x(`local`)},[h,b]);let[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(-1),P=(0,Q.useRef)(null),ee=(0,Q.useRef)(null),[F,te]=(0,Q.useState)([]),[ne,re]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(`22`),[ie,ae]=(0,Q.useState)(``),[oe,se]=(0,Q.useState)(`password`),[ce,ue]=(0,Q.useState)(``),[de,B]=(0,Q.useState)(`~/.ssh/id_rsa`),[fe,pe]=(0,Q.useState)(!0),[me,ge]=(0,Q.useState)(``),[U,W]=(0,Q.useState)(!1),[G,_e]=(0,Q.useState)(null),[K,q]=(0,Q.useState)(null),[J,ve]=(0,Q.useState)(null),[Y,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)([]),[Ce,Te]=(0,Q.useState)(!1),[Ee,X]=(0,Q.useState)(`/`),[Oe,Ae]=(0,Q.useState)(`/`),[je,Me]=(0,Q.useState)([]),[Ne,Pe]=(0,Q.useState)(!1),[Fe,Ie]=(0,Q.useState)(!1),[Le,Re]=(0,Q.useState)(``),[ze,Ve]=(0,Q.useState)(null),He=n.filter(e=>e.type===`dir`);(0,Q.useEffect)(()=>{if(oa(e)){let t=sa(e);t&&(re(t.host),L(String(t.port)),ae(t.username),X(t.remotePath),Ae(t.remotePath))}else{let t=(e||``).replace(/\\/g,`/`);C(t),T(t)}D(!1),k(``),j(null),N(-1)},[e]),(0,Q.useEffect)(()=>{let e=requestAnimationFrame(()=>{P.current?.focus()});return()=>cancelAnimationFrame(e)},[b]),(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(E||Fe?(D(!1),k(``),j(null),Ie(!1),Re(``),Ve(null)):i())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,Fe,i]),(0,Q.useEffect)(()=>{if(b!==`local`)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:ha(S)})},60);return()=>clearTimeout(e)},[S,b]),(0,Q.useEffect)(()=>{if(b!==`local`||w===S)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:w})},150);return()=>clearTimeout(e)},[w,S,b]);let Ue=e=>{let t=e.trim();t&&t!==`@root`&&a(t)},We=e=>{C(e),T(e),N(-1),j(null)},Ge=()=>{let e=O.trim();if(e&&S!==`@root`){if(o===`project`){if(!_a(e)){j(p(`invalidProjectName`));return}let t=ga(S,e);s?s(t):(Z({type:`make_dir`,path:t}),a(t)),D(!1),k(``),j(null),i()}else Z({type:`make_dir`,path:`${ha(S)}${e}`}),setTimeout(()=>{Z({type:`complete_path`,path:ha(S)})},80),k(``),D(!1)}},Ke=e=>{if(e.key===`Escape`)e.stopPropagation(),E?(D(!1),k(``),j(null)):i();else if(e.key===`Enter`&&!e.nativeEvent.isComposing)Ue(w);else if(e.key===`Tab`){if(He.length===0)return;e.preventDefault();let t=M>=0?(M+1)%He.length:0;N(t),T(He[t].path),C(He[t].path)}},qe=async t=>{let n=(t?.host??ne).trim(),r=t?.port??(parseInt(I,10)||22),i=(t?.username??ie).trim();if(!n||!i){_e(m?`请填写主机地址和用户名`:`Please provide host address and username`);return}W(!0),_e(null);let a=await la({host:n,port:r,username:i,auth:t?.auth??(oe===`password`?{type:`password`,password:ce}:oe===`key`?{type:`key`,privateKeyPath:de}:{type:`agent`}),saveProfile:fe,profileName:t?.profileName||me.trim()||void 0});if(W(!1),!a.ok||!a.connectionId){_e(a.error||(m?`连接远程服务器失败`:`Failed to connect to remote server`));return}q(a.connectionId),ve(a.system??null),ye(a.tools??null),xe(a.suggestedInstall??[]);let o=oa(e)?sa(e)?.remotePath:null,s=o&&o!==`/`?o:a.system?.homeDir||`/`;X(s),Ae(s),Ye(a.connectionId,s),fa().then(e=>te(e))},Je=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{b===`remote`&&fa().then(t=>{if(te(t),!Je.current&&!K&&!U&&oa(e)){let n=sa(e);if(n){let e=t.find(e=>e.host===n.host&&(e.username===n.username||!n.username)&&(e.port===n.port||!n.port&&e.port===22))||t.find(e=>e.host===n.host&&e.username===n.username)||t.find(e=>e.host===n.host);e&&(Je.current=!0,re(e.host),L(String(e.port)),ae(e.username),se(e.authType),e.privateKeyPath&&B(e.privateKeyPath),qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}}))}}})},[b,e,K,U]);let Ye=async(e,t)=>{Pe(!0),_e(null);let n=await ua(e,t);Pe(!1),n.ok?(X(n.path),Ae(n.path),Me(n.items)):_e(n.error||(m?`读取远程目录失败`:`Failed to read remote directory`))},Ze=async e=>{if(!K)return;Te(!0),_e(null);let t=await da(K,[e]);Te(!1),t.ok?(xe(t=>t.filter(t=>t!==e)),Y&&e===`git`&&ye({...Y,git:{installed:!0,version:m?`已安装`:`Installed`}})):_e(t.error||(m?`安装 ${e} 失败,可能需要远端 sudo 权限`:`Failed to install ${e}, remote sudo permissions may be required`))},Qe=e=>{let t=parseInt(I,10)||22,n=J?.homeDir||`/`,r=(e||``).trim()||Ee||`/`;r===`~`?r=n:(r.startsWith(`~/`)||r.startsWith(`~\\`))&&(r=`${n.replace(/\/+$/,``)}/${r.slice(2).replace(/\\/g,`/`)}`),a(aa(ie,ne,t,r)),i()},$e=()=>{let e=Le.trim();if(!e||!K)return;if(!_a(e)){Ve(p(`invalidProjectName`));return}let t=parseInt(I,10)||22,n=Ee.replace(/\/+$/,``)||`/`,r=n===`/`?`/${e}`:`${n}/${e}`,c=aa(ie,ne,t,r);if(o===`project`)s?s(c):(Z({type:`make_dir`,path:c}),a(c)),Ie(!1),Re(``),Ve(null),i();else{Z({type:`make_dir`,path:c}),Re(``),Ie(!1),Ve(null);let e=K,t=Ee;setTimeout(()=>{Ye(e,t)},300)}},et=va(S),tt=va(Ee),nt=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);return/^[A-Za-z]:/.test(t)?t.toLowerCase():t},rt=nt(S),it=!!S&&S!==`@root`&&rt!==nt(e)&&!r.some(e=>nt(e)===rt);return(0,bn.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`status-cwd-backdrop ${l??``}`.trim(),onClick:i,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation()}),(0,$.jsxs)(`div`,{className:`cwd-picker ${c??``}`.trim(),role:u,"aria-label":d,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[h?(0,$.jsxs)(`div`,{className:`cwd-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${b===`local`?`active`:``}`,onClick:()=>x(`local`),children:[`💻 `,p(`workspaceModeLocal`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${b===`remote`?`active`:``}`,onClick:()=>x(`remote`),children:[`🌐 `,p(`workspaceModeRemote`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:p(`close`),"aria-label":p(`close`),onClick:i,children:(0,$.jsx)(R,{})})]}):(0,$.jsxs)(`div`,{className:`cwd-mode-tabs cwd-mode-tabs-single`,children:[(0,$.jsxs)(`div`,{className:`cwd-mode-tab active`,style:{cursor:`default`},children:[`💻 `,p(`workspaceModeLocal`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:p(`close`),"aria-label":p(`close`),onClick:i,children:(0,$.jsx)(R,{})})]}),b===`local`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:S===`@root`?p(`computer`):S,children:[S===`@root`?(0,$.jsx)(t,{}):(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:S===`@root`?p(`computer`):S})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":p(`projectPickerTitle`),children:[(0,$.jsx)(ta,{className:`cwd-jump ${S===`@root`?`active`:``}`,tip:p(`computer`),onClick:()=>We(`@root`),children:(0,$.jsx)(t,{})}),_!==``&&(0,$.jsx)(ta,{className:`cwd-jump ${nt(S)===nt(_)?`active`:``}`,tip:`${p(`homeDir`)} ${_}`,onClick:()=>We(_),children:(0,$.jsx)(Xe,{})}),v!==``&&(0,$.jsx)(ta,{className:`cwd-jump ${nt(S)===nt(v)?`active`:``}`,tip:`${p(`desktopDir`)} ${v}`,onClick:()=>We(v),children:(0,$.jsx)(st,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-sep`,"aria-hidden":`true`}),(0,$.jsx)(ta,{className:`cwd-jump tool-up`,tip:et?`${p(`cwdGoUp`)} · ${et}`:`${p(`cwdGoUp`)} · ${m?`已在顶层`:`already at top`}`,"aria-disabled":!et,onClick:()=>{et&&We(et)},children:(0,$.jsx)(De,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-root`,tip:it?p(`addWorkspaceRootHint`):S===`@root`?`${p(`addWorkspaceRoot`)} · ${m?`此电脑本身不是目录`:`This PC is not a directory`}`:rt===nt(e)?`${p(`addWorkspaceRoot`)} · ${m?`已是当前项目目录`:`Already the current project`}`:`${p(`addWorkspaceRoot`)} · ${m?`已在工作区根中`:`Already a workspace root`}`,"aria-disabled":!it,onClick:()=>{it&&Z({type:`set_workspace_roots`,roots:[...r,S]})},children:(0,$.jsx)(ke,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-new ${E?`active`:``}`,tip:S===`@root`?`${p(`cwdNewFolder`)} · ${m?`此电脑下不能新建`:`Cannot create here`}`:p(E?`cwdCancel`:`cwdNewFolder`),"aria-disabled":S===`@root`,onClick:()=>{S!==`@root`&&(E?(D(!1),k(``),j(null)):(k(``),j(null),D(!0)))},children:(0,$.jsx)(y,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`}),(0,$.jsx)(ta,{className:`cwd-jump primary tool-pick`,tip:S===`@root`?`${p(`cwdPickCurrent`)} · ${m?`此电脑不能作为工作目录`:`This PC cannot be a workspace`}`:`${p(`cwdPickCurrent`)} · ${S}`,"aria-disabled":S===`@root`,onClick:()=>Ue(S),children:(0,$.jsx)(z,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{ref:P,className:`status-cwd-input cwd-picker-input`,value:w,placeholder:p(`enterPath`),spellCheck:!1,onChange:e=>{T(e.target.value),N(-1)},onKeyDown:Ke}),w.trim()!==``&&w!==S&&(0,$.jsx)(ta,{className:`cwd-jump tool-enter`,tip:`${p(`cwdEnter`)} · ${w.trim()}`,onClick:()=>{C(w.trim()),N(-1)},children:(0,$.jsx)(he,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[et&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdGoUp`)} · ${et}`,onClick:()=>We(et),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),He.length===0&&!et&&(0,$.jsx)(`div`,{className:`cwd-empty`,children:p(`cwdEmpty`)}),He.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdEnter`)} ${e.path}`,onClick:()=>{C(e.path),T(e.path),N(-1)},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),(0,$.jsx)(ta,{className:`cwd-jump tool-choose`,tip:`${p(`cwdChoose`)} · ${e.path}`,onClick:()=>Ue(e.path),children:(0,$.jsx)(z,{})})]},e.path))]}),E&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{ref:ee,value:O,autoFocus:!0,spellCheck:!1,placeholder:p(`cwdNewName`),onChange:e=>{k(e.target.value),A&&j(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),Ge()):e.key===`Escape`&&(e.stopPropagation(),D(!1),k(``),j(null))}}),(0,$.jsx)(ta,{className:`cwd-jump primary`,tip:p(`cwdCreate`),onClick:Ge,children:(0,$.jsx)(z,{})}),(0,$.jsx)(ta,{className:`cwd-jump`,tip:p(`cwdCancel`),onClick:()=>{D(!1),k(``),j(null)},children:(0,$.jsx)(R,{})})]}),A&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:A})]})]}),b===`remote`&&(0,$.jsx)(`div`,{className:`cwd-ssh-container`,children:K?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-box`,children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-header`,children:[(0,$.jsxs)(`span`,{children:[`🌐 `,ie,`@`,ne,` (`,J?.os,` `,J?.arch,`)`]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,onClick:()=>{q(null),ve(null),ye(null)},children:p(`sshDisconnect`)})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,flexWrap:`wrap`,fontSize:`10px`},children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.git.installed?`ok`:`missing`}`,children:[`Git: `,Y?.git.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.node.installed?`ok`:`missing`}`,children:[`Node: `,Y?.node.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.bash.installed?`ok`:`missing`}`,children:[`Bash: `,Y?.bash.installed?`✓`:`✗`]})]}),be.length>0&&(0,$.jsxs)(`div`,{className:`cwd-ssh-install-box`,children:[(0,$.jsxs)(`div`,{children:[`⚠️`,` `,m?`远端环境未检测到 Git / 基础工具,SCM 与执行功能可能受限。`:`Git / essential tools not detected on remote host; SCM and execution features may be limited.`]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,marginTop:`2px`},children:[(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,disabled:Ce,onClick:()=>void Ze(be[0]),children:Ce?p(`sshInstalling`):`⚡ ${p(`sshInstallTool`)} ${be[0]}`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>xe([]),children:p(`sshSkipAndBrowse`)})]})]})]}),(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:Ee,children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{children:Ee})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":p(`workspaceModeRemote`),children:[(0,$.jsx)(ta,{className:`cwd-jump tool-up`,tip:Ee===`/`?`${p(`cwdGoUp`)} · ${m?`已在顶层`:`already at top`}`:`${p(`cwdGoUp`)} · ${va(Ee)||`/`}`,"aria-disabled":Ee===`/`||Ne,onClick:()=>{if(Ne)return;let e=va(Ee);e&&K&&Ye(K,e)},children:(0,$.jsx)(De,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-new ${Fe?`active`:``}`,tip:p(Fe?`cwdCancel`:`cwdNewFolder`),onClick:()=>Ie(e=>!e),children:(0,$.jsx)(y,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{className:`status-cwd-input cwd-picker-input`,value:Oe,placeholder:p(`enterPath`),spellCheck:!1,onChange:e=>Ae(e.target.value),onKeyDown:e=>{e.key===`Enter`&&K&&Ye(K,Oe)}}),Oe.trim()&&Oe.trim()!==Ee&&K&&(0,$.jsx)(ta,{className:`cwd-jump tool-enter`,tip:`${p(`cwdEnter`)} · ${Oe.trim()}`,onClick:()=>void Ye(K,Oe),children:(0,$.jsx)(he,{})}),(0,$.jsx)(ta,{className:`cwd-jump primary tool-pick`,tip:`${p(`sshOpenRemoteWorkspace`)} · ${Oe.trim()||Ee}`,onClick:()=>Qe(Oe.trim()||Ee),children:(0,$.jsx)(z,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[!Ne&&tt&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdGoUp`)} · ${tt}`,onClick:()=>{K&&Ye(K,tt)},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),Ne?(0,$.jsx)(`div`,{className:`cwd-empty`,children:m?`正在加载远程目录…`:`Loading remote directory…`}):je.length===0?(0,$.jsx)(`div`,{className:`cwd-empty`,children:p(`cwdEmpty`)}):je.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${e.type===`dir`?p(`cwdEnter`):``} ${e.path}`,onClick:()=>{e.type===`dir`&&K&&Ye(K,e.path)},children:[e.type===`dir`?(0,$.jsx)(Be,{}):(0,$.jsx)(`span`,{children:`📄`}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),e.type===`dir`&&(0,$.jsx)(ta,{className:`cwd-jump tool-choose`,tip:`${p(`cwdChoose`)} · ${e.path}`,onClick:()=>Qe(e.path),children:(0,$.jsx)(z,{})})]},e.path))]}),K&&Fe&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{value:Le,autoFocus:!0,spellCheck:!1,placeholder:p(`cwdNewName`),onChange:e=>{Re(e.target.value),ze&&Ve(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),$e()):e.key===`Escape`&&(e.stopPropagation(),Ie(!1),Re(``),Ve(null))}}),(0,$.jsx)(ta,{className:`cwd-jump primary`,tip:p(`cwdCreate`),onClick:$e,children:(0,$.jsx)(z,{})}),(0,$.jsx)(ta,{className:`cwd-jump`,tip:p(`cwdCancel`),onClick:()=>{Ie(!1),Re(``),Ve(null)},children:(0,$.jsx)(R,{})})]}),ze&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:ze})]})]}):(0,$.jsxs)(`div`,{className:`cwd-ssh-form`,children:[F.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profiles-title`,children:[`📋 `,p(`sshSavedProfiles`)]}),F.map(e=>(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-card`,onClick:()=>{re(e.host),L(String(e.port)),ae(e.username),se(e.authType),e.privateKeyPath&&B(e.privateKeyPath),qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}})},children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-meta`,children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-name`,children:[(0,$.jsx)(we,{style:{marginRight:`4px`}}),e.name]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-addr`,children:[e.username,`@`,e.host,`:`,e.port]})]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,title:p(`delete`),onClick:t=>{t.stopPropagation(),confirm(p(`sshDeleteProfileConfirm`))&&(pa(e.name),te(t=>t.filter(t=>t.name!==e.name)))},children:(0,$.jsx)(g,{})})]},e.name))]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,style:{marginTop:`4px`},children:[(0,$.jsxs)(`label`,{children:[p(`sshHost`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:ne,placeholder:`192.168.1.100`,onChange:e=>re(e.target.value)}),(0,$.jsxs)(`label`,{style:{width:`32px`,textAlign:`right`},children:[p(`sshPort`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,style:{width:`45px`,flex:`none`},value:I,onChange:e=>L(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshUser`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:ie,placeholder:`root / ubuntu`,onChange:e=>ae(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshAuthType`),`:`]}),(0,$.jsxs)(`select`,{className:`cwd-ssh-select`,value:oe,onChange:e=>se(e.target.value),children:[(0,$.jsx)(`option`,{value:`password`,children:p(`sshPassword`)}),(0,$.jsx)(`option`,{value:`key`,children:p(`sshKeyPath`)}),(0,$.jsx)(`option`,{value:`agent`,children:p(`sshAgent`)})]})]}),oe===`password`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshPassword`),`:`]}),(0,$.jsx)(`input`,{type:`password`,className:`cwd-ssh-input`,value:ce,placeholder:`••••••••`,onChange:e=>ue(e.target.value)})]}),oe===`key`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshKeyPath`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:de,placeholder:`~/.ssh/id_rsa`,onChange:e=>B(e.target.value)})]}),(0,$.jsx)(`div`,{className:`cwd-ssh-row`,style:{fontSize:`11px`,color:`var(--text-dim)`},children:(0,$.jsxs)(`label`,{style:{width:`auto`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:fe,onChange:e=>pe(e.target.checked),style:{marginRight:`4px`}}),p(`sshSaveProfile`)]})}),fe&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshProfileName`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:me,placeholder:`my-server`,onChange:e=>ge(e.target.value)})]}),G&&(0,$.jsxs)(`div`,{style:{color:`var(--red)`,fontSize:`11px`,padding:`2px 0`},children:[`⚠️ `,G]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,style:{marginTop:`4px`},disabled:U,onClick:()=>void qe(),children:p(U?`sshConnecting`:`sshConnectAndProbe`)})]})})]})]}),document.body)}function ba({open:e,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,onCreateProject:o,mode:s=`project`,localOnly:c}){let l=V();return e?(0,$.jsx)(ya,{localOnly:c,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:e=>{a(e),i()},onCreateProject:o,mode:s,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:l(`projectPickerTitle`)}):null}function xa(e){return n({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M53.92,34.62A8,8,0,1,0,42.08,45.38L67.37,73.2A69.82,69.82,0,0,0,38,87.63a16,16,0,0,0-1.29,23.78L85,159.71,42.34,202.34a8,8,0,0,0,11.32,11.32L96.29,171l48.29,48.29A16,16,0,0,0,155.9,224c.38,0,.75,0,1.13,0a15.93,15.93,0,0,0,11.64-6.33,89.75,89.75,0,0,0,11.58-20.27l21.84,24a8,8,0,1,0,11.84-10.76ZM155.9,208,48,100.08C58.23,91.83,69.2,87.72,80.66,87.81l87.16,95.88C165.59,193.56,160.24,202.23,155.9,208Zm79.42-104-44.64,44.79a8,8,0,1,1-11.33-11.3L224,92.7,163.32,32,122.1,73.35a8,8,0,0,1-11.33-11.29L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.32,104Z`},child:[]}]})(e)}function Sa(e){return n({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M235.33,104l-53.47,53.65c4.56,12.67,6.45,33.89-13.19,60A15.93,15.93,0,0,1,157,224c-.38,0-.75,0-1.13,0a16,16,0,0,1-11.32-4.69L96.29,171,53.66,213.66a8,8,0,0,1-11.32-11.32L85,159.71l-48.3-48.3A16,16,0,0,1,38,87.63c25.42-20.51,49.75-16.48,60.4-13.14L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.33,104Z`},child:[]}]})(e)}function Ca({anchorRect:e,anchorEl:t,plugins:n,pinnedIds:r,orderedPluginIds:i,onTogglePin:a,onReorder:o,onOpenView:s,onOpenPluginSettings:c,onManagePlugins:l,onClose:u}){let{t:d}=Ue(),{panelRef:f,style:p,measure:m}=Cn({anchor:e,anchorEl:t,onClose:u}),[,h]=(0,Q.useState)(null),g=(0,Q.useRef)(null),[_,y]=(0,Q.useState)(null),b=(0,Q.useMemo)(()=>{let e=new Map((i??[]).map((e,t)=>[e,t]));return n.map((e,t)=>({plugin:e,index:t})).sort((t,n)=>(e.get(t.plugin.id)??1e6+t.index)-(e.get(n.plugin.id)??1e6+n.index)).map(({plugin:e})=>e)},[n,i]),{viewPlugins:x,extPlugins:S}=(0,Q.useMemo)(()=>{let e=[],t=[];for(let n of b)n.view!==!1&&!n.error?e.push(n):t.push(n);return{viewPlugins:e,extPlugins:t}},[b]);(0,Q.useLayoutEffect)(()=>{m()},[b,m]);let C=(e,t)=>{let n=b.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=r+t;if(r<0||i<0||i>=n.length)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},w=(e,t)=>{if(!e||e===t)return;let n=b.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=n.indexOf(t);if(r<0||i<0)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},T=(e,t)=>{let n=e.view===!1||!!e.error,i=!n&&r.has(e.id),o=e.iconSvg?void 0:e.icon&&!/[a-z]/i.test(e.icon)?e.icon:void 0;return(0,$.jsxs)(`div`,{className:`pm-row${_===e.id?` drop-target`:``}${t?` pm-row-ext`:``}`,role:`none`,onDragOver:t=>{!n&&g.current&&(t.preventDefault(),y(e.id))},onDrop:t=>{t.preventDefault(),w(t.dataTransfer.getData(`text/plain`)||g.current,e.id),g.current=null,h(null),y(null)},children:[n?(0,$.jsx)(`span`,{className:`pm-drag-placeholder`,"aria-hidden":!0}):(0,$.jsx)(`button`,{type:`button`,className:`pm-drag`,draggable:!0,"aria-label":d(`pluginMenuReorder`),title:d(`pluginMenuReorderHint`),onDragStart:t=>{h(e.id),g.current=e.id,t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e.id);let n=document.createElement(`div`);n.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0`,document.body.appendChild(n),t.dataTransfer.setDragImage(n,0,0),requestAnimationFrame(()=>n.remove())},onDragEnd:()=>{g.current=null,h(null),y(null)},onKeyDown:t=>{(t.key===`ArrowUp`||t.key===`ArrowDown`)&&(t.preventDefault(),C(e.id,t.key===`ArrowUp`?-1:1))},children:(0,$.jsx)(ze,{"aria-hidden":!0})}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-row-main`,disabled:n,title:e.error??(n?d(`pluginMenuNoView`):e.name),onClick:()=>s(e.id),children:[o||e.iconSvg?(0,$.jsx)(Ir,{icon:o,iconSvg:e.iconSvg,className:`pm-icon`}):(0,$.jsx)(ye,{className:`pm-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-name`,children:e.name}),e.error?(0,$.jsx)(`span`,{className:`pm-err-tag`,title:e.error,children:d(`pluginPhaseFailed`)}):t?(0,$.jsx)(`span`,{className:`pm-ext-tag`,title:d(`pluginMenuNoView`),children:d(`pluginBadgeBg`)}):null]}),(0,$.jsxs)(`div`,{className:`pm-row-actions`,children:[e.hasSettings&&c&&(0,$.jsx)(`button`,{type:`button`,className:`pm-action-btn`,title:d(`pluginQuickSettings`),onClick:()=>{u(),c(e.id)},children:(0,$.jsx)(v,{"aria-hidden":!0})}),!n&&(0,$.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":i,"aria-label":d(i?`pluginMenuUnpin`:`pluginMenuPin`),title:d(i?`pluginMenuUnpin`:`pluginMenuPin`),className:`pm-pin${i?` on`:``}`,onClick:()=>a(e.id,!i),children:i?(0,$.jsx)(Sa,{"aria-hidden":!0}):(0,$.jsx)(xa,{"aria-hidden":!0})})]})]},e.id)};return(0,bn.createPortal)((0,$.jsxs)(`div`,{ref:f,className:`pm-panel`,role:`menu`,"aria-label":d(`pluginMenuTitle`),style:p,children:[(0,$.jsxs)(`div`,{className:`pm-head`,"aria-hidden":`true`,children:[(0,$.jsxs)(`div`,{className:`pm-head-left`,children:[(0,$.jsx)(ye,{className:`pm-head-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-head-title`,children:d(`pluginMenuTitle`)}),(0,$.jsx)(`span`,{className:`pm-head-count`,children:n.length})]}),c&&(0,$.jsxs)(`button`,{type:`button`,className:`pm-head-btn`,title:d(`pluginManagerDesc`),onClick:()=>{u(),c()},children:[(0,$.jsx)(v,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuSettings`)})]})]}),(0,$.jsx)(`div`,{className:`pm-list`,children:n.length===0?(0,$.jsx)(`div`,{className:`pm-empty`,children:d(`pluginMenuEmpty`)}):(0,$.jsxs)($.Fragment,{children:[x.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[S.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:d(`pluginGroupViews`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:x.length})]}),x.map(e=>T(e,!1))]}),S.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[x.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:d(`pluginGroupExtensions`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:S.length})]}),S.map(e=>T(e,!0))]})]})}),(0,$.jsxs)(`div`,{className:`pm-footer`,children:[c&&(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn primary`,onClick:()=>{u(),c()},children:[(0,$.jsx)(v,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuSettings`)})]}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn pm-manage`,onClick:()=>{u(),l()},children:[(0,$.jsx)(at,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuManage`)})]})]})]}),document.body)}var wa=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Ta(e,t=[],n){let r=[],i=e=>{r.includes(e)||r.push(e)};e.optionsFrom&&i(``);for(let t of e.options??[])i(typeof t==`string`?t:t.value);if(e.optionsFrom===`models`)for(let e of t)i(`${e.provider}/${e.id}`);else if(e.optionsFrom===`thinkingLevels`)for(let e of wa)i(e);let a=typeof n==`string`?n:n==null?``:String(n);return a&&i(a),r}var Ea={activity:(0,$.jsx)(Je,{}),aperture:(0,$.jsx)(B,{}),branch:(0,$.jsx)(ce,{}),browser:(0,$.jsx)(le,{}),chat:(0,$.jsx)(Ae,{}),check:(0,$.jsx)(z,{}),"chevron-up":(0,$.jsx)(s,{}),clock:(0,$.jsx)(u,{}),code:(0,$.jsx)(c,{}),coins:(0,$.jsx)(_,{}),copy:(0,$.jsx)(Te,{}),cpu:(0,$.jsx)(E,{}),cut:(0,$.jsx)(O,{}),database:(0,$.jsx)(f,{}),dot:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`●`}),download:(0,$.jsx)(S,{}),edit:(0,$.jsx)(M,{}),engine:(0,$.jsx)(B,{}),eye:(0,$.jsx)(I,{}),feather:(0,$.jsx)(ne,{}),file:(0,$.jsx)(ie,{}),folder:(0,$.jsx)(Be,{}),gauge:(0,$.jsx)(Je,{}),git:(0,$.jsx)(ce,{}),github:(0,$.jsx)(oe,{}),globe:(0,$.jsx)(le,{}),grid:(0,$.jsx)(j,{}),hash:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`#`}),image:(0,$.jsx)(Ne,{}),info:(0,$.jsx)(We,{}),layers:(0,$.jsx)(fe,{}),link:(0,$.jsx)(qe,{}),list:(0,$.jsx)(ge,{}),lock:(0,$.jsx)(Oe,{}),markdown:(0,$.jsx)(x,{}),maximize:(0,$.jsx)(J,{}),menu:(0,$.jsx)(ze,{}),minimize:(0,$.jsx)(de,{}),message:(0,$.jsx)(Ae,{}),open:(0,$.jsx)(a,{}),paste:(0,$.jsx)(F,{}),pin:(0,$.jsx)(xe,{}),plus:(0,$.jsx)(rt,{}),refresh:(0,$.jsx)(te,{}),sandbox:(0,$.jsx)(An,{}),save:(0,$.jsx)(l,{}),share:(0,$.jsx)(On,{}),search:(0,$.jsx)(Ee,{}),send:(0,$.jsx)(i,{}),settings:(0,$.jsx)(T,{}),sound:(0,$.jsx)(b,{}),sun:(0,$.jsx)(N,{}),target:(0,$.jsx)(k,{}),terminal:(0,$.jsx)(o,{}),text:(0,$.jsx)(re,{}),trash:(0,$.jsx)(g,{}),undo:(0,$.jsx)(w,{}),upload:(0,$.jsx)(m,{}),volume:(0,$.jsx)(b,{}),wrap:(0,$.jsx)(r,{}),x:(0,$.jsx)(R,{}),zap:(0,$.jsx)(se,{}),zoom:(0,$.jsx)(ue,{})};Object.keys(Ea);function Da(e){if(e.iconSvg)return(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg});if(!e.icon)return null;let t=Ea[e.icon];return t===void 0?/[a-z]/i.test(e.icon)?null:(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:e.icon}):t}var Oa=0,ka=``;function Aa(){typeof document<`u`&&(Oa===0&&(ka=document.body.style.overflow,document.body.style.overflow=`hidden`),Oa++)}function ja(){typeof document<`u`&&(Oa=Math.max(0,Oa-1),Oa===0&&(document.body.style.overflow=ka))}function Ma({open:e=!0,onClose:t,title:n,icon:r,headerActions:i,allowFullscreen:a=!1,fullscreen:o,onFullscreenChange:s,children:c,className:l=``,backdropClassName:u=``,style:d,closeOnBackdropClick:f=!0,closeOnEscape:p=!0,showCloseButton:m=!0,ariaLabel:h,lockScroll:g=!0}){let _=V(),v=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{v.current=t});let y=o!==void 0,[b,x]=(0,Q.useState)(!1),S=a?y?o:b:!1,C=()=>{let e=!S;y||x(e),s?.(e)};if(mt(()=>a&&S?(y||x(!1),s?.(!1),!0):p?(v.current(),!0):!1,e),(0,Q.useEffect)(()=>{if(e&&g)return Aa(),()=>{ja()}},[e,g]),!e)return null;let w=e=>{e.target===e.currentTarget&&f&&v.current()},T=h??(typeof n==`string`?n:void 0),E=`modal-backdrop ${u} ${S?`fullscreen`:``}`.trim(),D=`modal ${l} ${a?`has-fullscreen-toggle`:``} ${S?`fullscreen`:``}`.trim();return(0,bn.createPortal)((0,$.jsx)(`div`,{className:E,onClick:w,role:`presentation`,children:(0,$.jsxs)(`div`,{className:D,role:`dialog`,"aria-modal":`true`,"aria-label":T,style:d,onClick:e=>e.stopPropagation(),children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`modal-fullscreen-btn ${S?`active`:``}`,"aria-label":_(S?`exitFullscreen`:`fullscreen`),title:_(S?`exitFullscreen`:`fullscreen`),onClick:C,children:S?(0,$.jsx)(Y,{}):(0,$.jsx)(G,{})}),m&&(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":_(`close`),onClick:()=>v.current(),children:`✕`}),n?(0,$.jsxs)(`div`,{className:`modal-head`,onDoubleClick:e=>{if(!a)return;let t=e.target;t&&!t.closest(`button, a, input, textarea, select`)&&C()},children:[r?(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:r}):null,(0,$.jsx)(`span`,{className:`modal-head-title`,children:n}),i?(0,$.jsx)(`div`,{className:`modal-head-actions`,children:i}):null]}):null,c]})}),document.body)}function Na({plugin:e,models:t=[]}){let n=V(),r=Se(),i=H(r),a=e.settingsSchema??[],[o,s]=(0,Q.useState)(()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);return t}),[c,l]=(0,Q.useState)(!1);if(a.length===0)return null;let u=(e,t)=>s(n=>({...n,[e]:t})),d=e=>Ta(e,t,o[e.key]).map(r=>{if(r===``)return{value:``,label:n(`pluginSettingsInherit`)};if(e.optionsFrom===`thinkingLevels`&&wa.includes(r))return{value:r,label:n(`thinking.${r}`)};if(e.optionsFrom===`models`){let e=t.find(e=>`${e.provider}/${e.id}`===r);if(e)return{value:r,label:e.label}}let a=e.options?.find(e=>(typeof e==`string`?e:e.value)===r);return a&&typeof a==`object`?{value:r,label:i?a.label??a.labelEn??a.value:a.labelEn??a.label??a.value}:{value:r,label:r}}),f=a.some(t=>t.type===`secret`?String(o[t.key]??``)!==``:o[t.key]!==e.settingsValues?.[t.key]);return(0,$.jsxs)(`div`,{className:`plugin-settings-form`,children:[(0,$.jsx)(`div`,{className:`plugin-settings-fields`,children:a.map(t=>(0,$.jsxs)(`label`,{className:`plugin-settings-field`,"data-key":t.key,title:t.hint,children:[(0,$.jsxs)(`span`,{className:`plugin-settings-label`,children:[(0,$.jsx)(`span`,{className:`plugin-settings-label-text`,title:t.label,children:t.label}),t.hint&&(0,$.jsx)(`span`,{className:`plugin-settings-hint`,children:t.hint})]}),(0,$.jsx)(`span`,{className:`plugin-settings-control`,children:t.type===`boolean`?(0,$.jsx)(`input`,{type:`checkbox`,checked:!!o[t.key],onChange:e=>u(t.key,e.target.checked)}):t.type===`secret`?(0,$.jsx)(`input`,{type:`password`,value:String(o[t.key]??``),placeholder:n(e.settingsValues?.[t.key]?`pluginSecretSet`:`pluginSecretUnset`),autoComplete:`new-password`,onChange:e=>u(t.key,e.target.value)}):t.type===`select`?(0,$.jsx)(`select`,{value:String(o[t.key]??``),onChange:e=>u(t.key,e.target.value),children:d(t).map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,$.jsx)(`input`,{type:t.type===`password`?`password`:t.type===`number`?`number`:`text`,value:String(o[t.key]??``),min:t.min,max:t.max,onChange:e=>u(t.key,t.type===`number`?Number(e.target.value):e.target.value)})})]},t.key))}),(0,$.jsxs)(`div`,{className:`plugin-settings-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-save`,disabled:!f||c,onClick:()=>{l(!0),Z({type:`plugin_settings`,pluginId:e.id,values:o}),setTimeout(()=>l(!1),800)},children:n(c?`pluginSettingsSaving`:`pluginSettingsSave`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-reset`,onClick:()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);s(t)},children:n(`pluginSettingsReset`)})]})]})}function Pa({plugin:e}){if(e.iconSvg)return(0,$.jsx)(Ir,{iconSvg:e.iconSvg});if(e.icon){if(!/[a-z]/i.test(e.icon))return(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:e.icon});let t=Da({icon:e.icon});if(t)return(0,$.jsx)(`span`,{className:`plugin-mgr-named-icon`,children:t})}return e.view===!1?e.settingsSchema&&e.settingsSchema.length>0?(0,$.jsx)(v,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(ye,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(Ie,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0})}function Fa({open:e=!0,onClose:t,focusPluginId:n,plugins:r,disabledPlugins:i,models:o=[],onTogglePlugin:s,onOpenView:c,onOpenMarketplace:l}){let u=V(),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`all`),[h,g]=(0,Q.useState)({}),[_,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(new Map),C=(0,Q.useMemo)(()=>new Set(i),[i]),w=(0,Q.useMemo)(()=>{let e=0,t=0,n=0;for(let i of r){let r=!!(i.settingsSchema&&i.settingsSchema.length>0),a=C.has(i.id),o=!!i.error;r&&e++,!a&&!o&&t++,a&&n++}return{total:r.length,configurable:e,enabled:t,disabled:n}},[r,C]);(0,Q.useEffect)(()=>{if(!e||!n)return;g(e=>({...e,[n]:!0})),y(n),r.find(e=>e.id===n)&&m(`all`);let t=setTimeout(()=>{let e=S.current.get(n);e&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},120),i=setTimeout(()=>{y(null)},2600);return()=>{clearTimeout(t),clearTimeout(i)}},[e,n,r]);let T=(0,Q.useCallback)(e=>{g(t=>({...t,[e]:!t[e]}))},[]),E=(0,Q.useCallback)(()=>{let e=r.some(e=>e.settingsSchema?.length&&!h[e.id]),t={};for(let n of r)n.settingsSchema?.length&&(t[n.id]=e);g(t)},[r,h]),D=(0,Q.useMemo)(()=>{let e=d.trim().toLowerCase();return r.filter(t=>{let n=!!(t.settingsSchema&&t.settingsSchema.length>0),r=C.has(t.id),i=!!t.error;if(p===`configurable`&&!n||p===`enabled`&&(r||i)||p===`disabled`&&!r)return!1;if(e){let n=t.name?.toLowerCase().includes(e),r=t.id?.toLowerCase().includes(e),i=t.description?.toLowerCase().includes(e);if(!n&&!r&&!i)return!1}return!0})},[r,p,d,C]),O=(0,Q.useCallback)(()=>{x(!0),Z({type:`plugins_reload`}),setTimeout(()=>x(!1),800)},[]);return(0,$.jsxs)(Ma,{open:e,onClose:t,className:`plugin-mgr-modal`,ariaLabel:u(`pluginManagerTitle`),showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-head`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-title-row`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-title-left`,title:u(`pluginCountSummary`,{total:w.total,enabled:w.enabled,configurable:w.configurable}),children:[(0,$.jsx)(ye,{className:`plugin-mgr-title-icon`,"aria-hidden":!0}),(0,$.jsx)(`h2`,{className:`plugin-mgr-title`,children:u(`pluginManagerTitle`)})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-title-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,title:u(`pluginRescanHint`),onClick:O,disabled:b,children:[(0,$.jsx)(te,{className:b?`spin`:``,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginRescan`)})]}),l&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{t(),l()},children:[(0,$.jsx)(at,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginGoMarket`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-close-btn`,"aria-label":u(`close`),title:u(`close`),onClick:t,children:(0,$.jsx)(R,{"aria-hidden":!0})})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-toolbar`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-search-wrap`,children:[(0,$.jsx)(Ee,{className:`plugin-mgr-search-icon`,"aria-hidden":!0}),(0,$.jsx)(`input`,{type:`text`,className:`plugin-mgr-search-input`,placeholder:u(`pluginSearchPlaceholder`),value:d,onChange:e=>f(e.target.value)}),d&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-search-clear`,onClick:()=>f(``),"aria-label":`Clear`,children:(0,$.jsx)(R,{"aria-hidden":!0})})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-filters`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`all`?` active`:``}`,onClick:()=>m(`all`),children:[u(`pluginFilterAll`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.total})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`configurable`?` active`:``}`,onClick:()=>m(`configurable`),children:[(0,$.jsx)(v,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),u(`pluginFilterConfigurable`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.configurable})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`enabled`?` active`:``}`,onClick:()=>m(`enabled`),children:[(0,$.jsx)(z,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),u(`pluginFilterEnabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.enabled})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`disabled`?` active`:``}`,onClick:()=>m(`disabled`),children:[u(`pluginFilterDisabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.disabled})]})]}),w.configurable>0&&(0,$.jsx)(`div`,{className:`plugin-mgr-expand-action`,children:(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-text-btn`,onClick:E,children:r.some(e=>e.settingsSchema?.length&&!h[e.id])?u(`pluginExpandAll`):u(`pluginCollapseAll`)})})]})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-body`,children:D.length===0?(0,$.jsxs)(`div`,{className:`plugin-mgr-empty`,children:[(0,$.jsx)(ye,{className:`plugin-mgr-empty-icon`,"aria-hidden":!0}),(0,$.jsx)(`p`,{children:u(d||p!==`all`?`pluginEmptyFilter`:`pluginMenuEmpty`)}),(d||p!==`all`)&&(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{f(``),m(`all`)},children:u(`pluginFilterAll`)})]}):(0,$.jsx)(`div`,{className:`plugin-mgr-list`,children:D.map(e=>{let n=!!(e.settingsSchema&&e.settingsSchema.length>0),r=C.has(e.id),i=!!e.error,l=!!h[e.id],d=e.view!==!1&&!i,f=_===e.id,p=e.homepage||(e.source?.startsWith(`http`)?e.source:void 0);return(0,$.jsxs)(`div`,{ref:t=>{t?S.current.set(e.id,t):S.current.delete(e.id)},className:`plugin-mgr-card${r?` disabled`:``}${i?` has-error`:``}${f?` highlighted`:``}`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-head`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-identity`,children:[(0,$.jsx)(`div`,{className:`plugin-mgr-card-icon-wrap`,children:(0,$.jsx)(Pa,{plugin:e})}),(0,$.jsxs)(`div`,{className:`plugin-mgr-card-names`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-name-row`,children:[(0,$.jsx)(`span`,{className:`plugin-mgr-card-name`,children:e.name}),e.version&&(0,$.jsxs)(`span`,{className:`plugin-mgr-card-ver`,children:[`v`,e.version]}),(0,$.jsx)(`span`,{className:`plugin-mgr-card-id`,children:e.id})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-badges`,children:[n&&(0,$.jsxs)(`span`,{className:`plugin-badge config`,title:u(`pluginBadgeConfig`),children:[(0,$.jsx)(v,{"aria-hidden":!0}),u(`pluginBadgeConfig`)]}),d?(0,$.jsx)(`span`,{className:`plugin-badge view`,children:u(`pluginBadgeView`)}):(0,$.jsx)(`span`,{className:`plugin-badge bg`,children:u(`pluginBadgeBg`)}),e.agentTools&&e.agentTools.length>0&&(0,$.jsx)(`span`,{className:`plugin-badge tools`,children:u(`pluginBadgeTools`,{count:e.agentTools.length})}),i&&(0,$.jsxs)(`span`,{className:`plugin-badge error`,children:[(0,$.jsx)(He,{"aria-hidden":!0}),`Error`]})]})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-card-controls`,children:[p&&(0,$.jsx)(`a`,{href:p,target:`_blank`,rel:`noreferrer noopener`,className:`plugin-mgr-icon-btn`,title:u(`pluginOfficialLink`),children:(0,$.jsx)(a,{"aria-hidden":!0})}),d&&!r&&c&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-open-view`,onClick:()=>{t(),c(e.id)},title:u(`pluginOpenView`),children:[(0,$.jsx)(I,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginOpenView`)})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-toggle-wrap`,children:(0,$.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!r&&!i,disabled:i,title:u(r?`pluginToggleEnable`:`pluginToggleDisable`),className:`plugin-mgr-switch${!r&&!i?` on`:``}`,onClick:()=>s(e),children:(0,$.jsx)(`span`,{className:`plugin-mgr-switch-thumb`})})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`plugin-mgr-card-desc`,title:e.description,children:e.description}),e.error&&(0,$.jsxs)(`div`,{className:`plugin-mgr-card-error`,children:[(0,$.jsx)(He,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:e.error})]}),n&&(0,$.jsxs)(`div`,{className:`plugin-mgr-settings-section`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-settings-toggle`,onClick:()=>T(e.id),"aria-expanded":l,children:[l?(0,$.jsx)(pe,{"aria-hidden":!0}):(0,$.jsx)(P,{"aria-hidden":!0}),(0,$.jsx)(v,{className:`plugin-mgr-settings-icon`,"aria-hidden":!0}),(0,$.jsxs)(`span`,{className:`plugin-mgr-settings-toggle-title`,children:[u(`pluginSettingsTitle`),` (`,e.settingsSchema.length,`)`]}),(0,$.jsx)(`span`,{className:`plugin-mgr-settings-toggle-hint`,children:u(l?`pluginSettingsHide`:`pluginSettingsShow`)})]}),l&&(0,$.jsx)(`div`,{className:`plugin-mgr-settings-content`,children:(0,$.jsx)(Na,{plugin:e,models:o})})]})]},e.id)})})})]})}function Ia({onClose:e}){let t=V(),{locale:n,setLocale:r,reloadPacks:i}=Ue(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``);async function d(){try{let e=await fetch(Qe(q(`/api/locales`)));if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();o(t.packs??[]),c(``)}catch(e){c(t(`localeListFailed`,{error:e instanceof Error?e.message:String(e)}))}}(0,Q.useEffect)(()=>{d()},[]);async function f(e){u(e),c(``);try{let t=await fetch(Qe(q(`/api/locales/${e}/install`)),{method:`POST`});if(!t.ok){let e=`HTTP ${t.status}`;try{e=(await t.json()).error??e}catch{}throw Error(e)}await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}async function p(e){u(e),c(``);try{let t=await fetch(Qe(q(`/api/locales/${e}`)),{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);Me(e),n===e&&r(`zh`),await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:e,children:(0,$.jsxs)(`div`,{className:`bg-task-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`bg-task-head`,children:[(0,$.jsxs)(`span`,{className:`bg-task-title`,children:[(0,$.jsx)(le,{}),` `,t(`localePacks`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:t(`close`),onClick:e,children:(0,$.jsx)(R,{})})]}),s&&(0,$.jsx)(`div`,{className:`bg-task-empty`,children:s}),a===null&&!s?(0,$.jsx)(`div`,{className:`bg-task-empty`,children:t(`loading`)}):(0,$.jsx)(`ul`,{className:`bg-task-list`,children:(a??[]).map(e=>{let n=l===e.code;return(0,$.jsxs)(`li`,{className:`bg-task-item`,children:[(0,$.jsxs)(`div`,{className:`bg-task-info`,children:[(0,$.jsxs)(`div`,{className:`bg-task-line1`,children:[(0,$.jsx)(`span`,{className:`bg-task-port`,children:e.nativeName}),e.installed&&e.version&&(0,$.jsxs)(`span`,{className:`bg-task-name`,children:[`v`,e.version]})]}),(0,$.jsxs)(`div`,{className:`bg-task-line2`,children:[(0,$.jsx)(`span`,{children:e.code}),e.installed?(0,$.jsxs)(`span`,{children:[t(`localeInstalled`),` · `,t(`localeRemoveHint`)]}):(0,$.jsx)(`span`,{children:t(`localeGetMore`)})]})]}),e.installed?(0,$.jsxs)(`button`,{type:`button`,className:`btn bg-task-stop`,disabled:n,title:t(`localeRemove`),onClick:()=>void p(e.code),children:[(0,$.jsx)(g,{}),(0,$.jsx)(`span`,{children:t(n?`localeRemoving`:`localeRemove`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:n,title:t(`localeInstall`),onClick:()=>void f(e.code),children:[(0,$.jsx)(S,{}),(0,$.jsx)(`span`,{children:t(n?`localeDownloading`:`localeInstall`)})]})]},e.code)})}),(0,$.jsx)(`div`,{className:`bg-task-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:t(`bgTaskRefresh`),onClick:()=>void d(),children:[(0,$.jsx)(te,{}),(0,$.jsx)(`span`,{children:t(`bgTaskRefresh`)})]})})]})})}var La=`xing-shuyin/pi-web-ui`,Ra={state:`idle`,version:null,percent:0,message:null};function za(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Ba(e,t){switch(t.state){case`checking`:return{...e,state:`checking`,message:null};case`available`:return{...e,state:`available`,version:t.version??e.version,message:null};case`up-to-date`:return{...e,state:`up-to-date`,version:t.version??e.version,message:null};case`downloading`:return{...e,state:`downloading`,percent:za(t.percent),message:null};case`downloaded`:return{...e,state:`downloaded`,version:t.version??e.version,percent:100,message:null};case`error`:return{...e,state:`error`,message:t.message??`unknown error`};default:return e}}function Va(e){if(!wt(e))return null;let t=(e??(typeof window>`u`?void 0:window))?.piDesktop?.updater;return!t||typeof t.check!=`function`||typeof t.download!=`function`?null:t}function Ha(e){return e instanceof Error?e.message:String(e)}function Ua(e){let t=(e??``).trim().replace(/^v/,``);return t?`https://github.com/${La}/releases/tag/v${t}`:`https://github.com/${La}/releases/latest`}function Wa(){let[e]=(0,Q.useState)(()=>Va()),[t,n]=(0,Q.useState)(Ra);(0,Q.useEffect)(()=>{if(e)return e.onEvent(e=>n(t=>Ba(t,e)))},[e]);let r=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`checking`,message:null})),e.check().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)}))))},[e]),i=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`downloading`,message:null})),e.download().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)}))))},[e]),a=(0,Q.useCallback)(()=>{e&&e.quitAndInstall().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)})))},[e]);return{...t,bridge:e,check:r,download:i,quitAndInstall:a}}function Ga(e){let t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),r=Math.max(0,e.cacheWrite??0),i=t+n+r;return{totalInput:i,miss:t,read:n,write:r,hitRate:i>0?Math.min(n/i,1):0,writeRate:i>0?Math.min(r/i,1):0}}var Ka=2e3;function qa(e,t,n=Ka){return e.filter(e=>t-e.t<=n)}function Ja(e,t=Ka){if(e.length<2)return 0;let n=e[e.length-1],r=e.find(e=>e.t>=n.t-t)??e[0],i=(n.t-r.t)/1e3;return i<=0?0:Math.max(0,(n.out-r.out)/i)}function Ya(e){if(!e)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r>=12352&&r<=12543||r>=13312&&r<=19903||r>=19968&&r<=40959||r>=63744&&r<=64255||r>=65280&&r<=65519||r===12288)&&t++}let n=e.length-t;return Math.round(t+n/4)}function Xa(e){let t=0;for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text?t+=Ya(n.text):n.type===`thinking`&&typeof n.thinking==`string`&&n.thinking&&(t+=Ya(n.thinking));return t}var Za=[{id:`pi`,titleKey:`settingsEnginePiTitle`,badge:`PI`,tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-pi`,packageName:`@earendil-works/pi-coding-agent`,installCommand:`npm i -g @earendil-works/pi-coding-agent`},{id:`dsh`,titleKey:`settingsEngineDshTitle`,badge:`DSH`,tagKey:`engineTagFast`,descKey:`settingsEngineDshDesc`,colorClass:`engine-dsh`,packageName:`@deepseek-ai/dsh`,installCommand:`npm i -g @deepseek-ai/dsh`},{id:`claude`,titleKey:`settingsEngineClaudeTitle`,badge:`CLAUDE`,tagKey:`engineTagUniversal`,descKey:`settingsEngineClaudeDesc`,colorClass:`engine-claude`,packageName:`@anthropic-ai/claude-code`,installCommand:`npm i -g @anthropic-ai/claude-code`},{id:`codex`,titleKey:`settingsEngineCodexTitle`,badge:`CODEX`,tagKey:`engineTagUniversal`,descKey:`settingsEngineCodexDesc`,colorClass:`engine-codex`,packageName:`@openai/codex`,installCommand:`npm i -g @openai/codex`},{id:`durable`,titleKey:`settingsEngineDurableTitle`,badge:`DURABLE`,tagKey:`engineTagDurable`,descKey:`settingsEngineDurableDesc`,colorClass:`engine-durable`,packageName:`@earendil-works/pi-durable`,installCommand:`npm i -g @earendil-works/pi-durable`}];function Qa({direction:e,align:t,className:n,label:r,caret:i=!1,bar:a,portal:o}){let{engine:s}=Qt(),c=on(),{t:l}=Ue(),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=e??(a===`left`?`right`:a===`right`?`left`:a===`bottom`?`up`:`down`),m=o??(a===`left`||a===`right`||a===`bottom`),h=e=>{e&&Z({type:`check_engines`}),d(e)},g=Za.find(e=>e.id===s)??{id:s,titleKey:`settingsEnginePiTitle`,badge:s.toUpperCase(),tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-${s}`},_=l(g.titleKey),v=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(B,{className:`bar-item-icon engine-picker-icon`}),r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`chip-sub bar-item-text engine-picker-name`,children:r}),(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${g.colorClass}`,children:g.badge})]}):(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${g.colorClass}`,children:g.badge})]});return(0,$.jsx)(`div`,{ref:f,className:`engine-picker-wrap ${g.colorClass} ${n??``}`,"data-bar-item":`host:engine`,children:(0,$.jsxs)(_t,{trigger:v,open:u,onOpenChange:h,direction:p,align:t??(a===`right`?`right`:`left`),fit:!0,caret:i,portal:m,triggerClassName:`bar-item chip engine-picker-btn ${g.colorClass}`,menuClassName:`engine-picker-menu`,tip:`${l(`engineBadge`)}: ${r??_} — ${l(`engineSwitchTip`)}`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-header`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-title`,children:[(0,$.jsx)(B,{}),(0,$.jsx)(`span`,{children:l(`settingsEngineSection`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-subtitle`,children:l(`enginePickerDesc`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-list`,role:`menu`,children:Za.map(e=>{let t=e.id===s,n=c.find(t=>t.id===e.id),r=e.id===`pi`||(n?n.installed:!1),i=!!n?.updating,a=!!(r&&n?.hasUpdate&&n?.latestVersion),o=a||i,u=t=>{t.stopPropagation(),d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}))},f=t=>{t.stopPropagation(),!i&&(d(!1),Z({type:`update_engine`,engineId:e.id}))},p=()=>{if(!r){d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}));return}d(!1),t||Z({type:`switch_engine`,engine:e.id})};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,title:r?void 0:l(`engineInstallTip`),className:`engine-picker-item ${e.colorClass}${t?` active`:``}${r?``:` uninstalled`}`,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),p())},onClick:p,children:[(0,$.jsxs)(`div`,{className:`engine-picker-item-head`,children:[(0,$.jsx)(B,{className:`engine-picker-item-icon`}),(0,$.jsx)(`span`,{className:`engine-badge ${e.colorClass}`,children:e.badge}),l(e.titleKey)!==e.badge&&(0,$.jsx)(`span`,{className:`engine-picker-item-name`,children:l(e.titleKey)}),(0,$.jsx)(`span`,{className:`engine-picker-item-tag${r?i||a?` update-available`:``:` uninstalled`}`,title:a?l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}):void 0,children:l(r?i?`engineUpdating`:a?`engineUpdateAvailable`:e.tagKey:`engineNotInstalled`)}),!r&&e.installCommand&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-install-btn`,title:l(`engineInstallTip`),onClick:u,children:[(0,$.jsx)(S,{className:`engine-install-icon`}),(0,$.jsx)(`span`,{children:l(`engineInstall`)})]}),o&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-update-btn`,disabled:i,title:i?l(`engineUpdating`):l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}),onClick:f,children:[(0,$.jsx)(te,{className:`engine-update-icon${i?` spinning`:``}`}),(0,$.jsx)(`span`,{children:l(i?`engineUpdating`:`engineUpdate`)})]}),t&&(0,$.jsx)(z,{className:`engine-picker-check`})]}),(0,$.jsx)(`div`,{className:`engine-picker-item-desc`,children:l(e.descKey)})]},e.id)})})]})})}function $a(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}function eo(e){return e===`zh-TW`?`TW`:e.startsWith(`zh`)?`ZH`:e.startsWith(`ja`)?`JA`:e.startsWith(`ko`)?`KO`:e.startsWith(`fr`)?`FR`:e.startsWith(`de`)?`DE`:e.startsWith(`es`)?`ES`:e.startsWith(`ru`)?`RU`:e.startsWith(`pt`)?`PT`:e.startsWith(`it`)?`IT`:`EN`}function to({entry:e,bar:t,chat:n,view:r,plugins:i,onViewChange:a,onOpenPanel:s,onOpenSettings:c,onOpenGlobalSearch:l,onOpenBgTasks:u,onOpenProjectPicker:d,onOpenPluginMenu:p,isPluginMenuOpen:m,isProjectPickerOpen:h,onUiAction:g,uiContextEntries:_,dropdownProps:v,zenMode:b,onToggleZenMode:x,onOpenSandboxModal:C}){let w=V(),{locale:D,packs:O,setLocale:k}=Ue(),{engine:A}=Qt(),j=A===`dsh`,[M,P]=(0,Q.useState)(!1),[ee,F]=(0,Q.useState)(!1),[te,re]=(0,Q.useState)(!1),I=n.settings?.uiLayout,L=n.state,ie=L?.stats,ae=L?.isStreaming??!1,se=L?.turnTiming,R=!!se&&se.finishedAt===void 0,[ue,z]=(0,Q.useState)(Date.now);(0,Q.useEffect)(()=>{if(e.id!==`host:working`||!R)return;z(Date.now());let t=window.setInterval(()=>z(Date.now()),1e3);return()=>window.clearInterval(t)},[e.id,R,se?.startedAt]);let de=Zt(ie?.cost??0),B=(0,Q.useRef)([]),pe=L?.streamingMessage?Xa(L.streamingMessage.content):0;(0,Q.useEffect)(()=>{if(!ae){B.current=[];return}let e=Date.now(),t=B.current,n=t[t.length-1];n&&e-n.t<250||(B.current=qa([...t,{t:e,out:pe}],e))},[ae,pe]);let me=ae?Ja(B.current):0,he=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{he.current!==null&&window.clearTimeout(he.current)},[]);let ge=n=>{n.preventDefault(),n.stopPropagation();let r=t=>{let n={...I?.slots,[e.id]:t},r={...I?.align};(t===`sidebar.left`||t===`sidebar.right`)&&!r[e.id]&&(r[e.id]=`center`),Z({type:`set_settings`,uiLayout:{...I,slots:n,...r[e.id]?{align:r}:{}}})},i=()=>{let t=new Set(I?.hidden??[]);t.add(e.id);let n=(I?.shown??[]).filter(t=>t!==e.id);Z({type:`set_settings`,uiLayout:{...I,hidden:[...t],shown:n}})},a=()=>{Z({type:`set_settings`,uiLayout:Ti(I,e.id)})},o=[];t!==`top`&&o.push({id:`host:move-top`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToTop`),kind:`action`,order:10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`bottom`&&o.push({id:`host:move-bottom`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToBottom`),kind:`action`,order:20,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`left`&&o.push({id:`host:move-left`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToLeft`),kind:`action`,order:30,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`right`&&o.push({id:`host:move-right`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToRight`),kind:`action`,order:40,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),ti.has(e.id)||o.push({id:`host:hide-item`,slot:`contextmenu.topbar`,source:`host`,label:w(`uiLayoutHide`),kind:`action`,order:50,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),(e.userOverrides&&e.userOverrides.length>0||I?.slots?.[e.id]||I?.labels?.[e.id]||I?.align?.[e.id]||I?.order?.includes(e.id))&&o.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:w(`uiLayoutRestore`),kind:`action`,order:60,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),_&&_.length>0&&o.push(..._),Pi({x:n.clientX,y:n.clientY,slot:`contextmenu.topbar`,target:{id:e.id,label:e.label},entries:o,onHostAction:e=>{e.id===`host:move-top`?r(`topbar.primary`):e.id===`host:move-bottom`?r(`bottombar`):e.id===`host:move-left`?r(`sidebar.left`):e.id===`host:move-right`?r(`sidebar.right`):e.id===`host:hide-item`?i():e.id===`host:restore-item`&&a()}})},U=e.id,W=e.labelExplicit?e.label:``,G=e=>W||e,_e=e=>W?`${W} ${e}`:e;if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`bar-item bar-item-select`,title:e.hint??e.label,"data-tip":e.hint??e.label,"aria-label":e.label,value:t,onChange:t=>g?.(e,t.target.value),onContextMenu:ge,"data-bar-item":U,children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})}if(U===`host:brand`)return(0,$.jsx)(En,{label:G(`pi-web-ui`),barItem:!0,onContextMenu:ge});if(U===`host:conn`){let e=n.ready?`ok`:n.status===`closed`?`error`:`busy`,t=n.ready?w(`connected`):n.status===`closed`?w(`reconnecting`):w(`connecting`),r=n.ready&&typeof n.latencyMs==`number`&&Number.isFinite(n.latencyMs)&&n.latencyMs>=0?Math.round(n.latencyMs):null,i=r===null?null:`${r}ms`,a=r===null?``:r<100?`ok`:r<300?`mid`:`warn`,o=i?`${t} · ${w(`networkLatency`)}: ${i}`:t;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-conn ${e} bar-item-conn`,title:o,"data-tip":o,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(`span`,{className:`status-dot ${e}`}),(0,$.jsx)(`span`,{className:`status-conn-label bar-item-text`,children:_e(t)}),i&&(0,$.jsx)(`span`,{className:`status-latency ${a}`,children:i})]})}if(U===`host:engine`)return(0,$.jsx)(`span`,{onContextMenu:ge,"data-bar-item":U,className:`bar-item-engine-wrap`,style:{display:`inline-flex`,alignItems:`center`},children:(0,$.jsx)(Qa,{direction:t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`,align:e.align===`end`||t===`right`?`right`:`left`,caret:!1,bar:t,portal:!0,label:e.labelExplicit?e.label:void 0})});if(U===`host:ctx`){let e=ie?.contextUsage,t=e?.softCap??null,n=t!==null&&t>0&&t<(e?.contextWindow??0),r=n?t:e?.contextWindow??0,i=e?.tokens!==null&&e?.tokens!==void 0&&r>0?Math.min(100,Math.round(e.tokens/r*100)):null,a=e?.tokens!==null&&e?.tokens!==void 0?$a(e.tokens):null,o=r>0?$a(r):null,s=a!==null&&o!==null&&i!==null?`${a} / ${o}`:`—`,c=i===null?``:i>=80?`warn`:i>=50?`mid`:`ok`,l=n?`${w(`contextUsage`)}: ${$a(e?.tokens??0)} / ${$a(t)} (${w(`softCapMarker`)}, max ${$a(e?.contextWindow??0)})`:t!==null&&t>0?`${w(`contextUsage`)}: ${s} · ${w(`softCapMarker`)}: ${$a(t)}`:`${w(`contextUsage`)}: ${s}`,u=i!==null&&i>0?+(31.42*(1-Math.min(i,100)/100)).toFixed(2):31.42;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-ctx bar-item-ctx`,title:l,"data-tip":l,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsxs)(`svg`,{className:`ctx-ring ${c}`,viewBox:`0 0 14 14`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{className:`ctx-ring-bg`,cx:`7`,cy:`7`,r:`5`}),i!==null&&i>0&&(0,$.jsx)(`circle`,{className:`ctx-ring-fill`,cx:`7`,cy:`7`,r:`5`,strokeDasharray:31.42,strokeDashoffset:u,"data-percent":i})]}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[W?`${W} `:``,a!==null&&o!==null?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`ctx-val`,children:a}),(0,$.jsx)(`span`,{className:`status-sep`,children:`/`}),(0,$.jsx)(`span`,{className:`ctx-max`,children:o})]}):s]})]})}if(U===`host:cache`){let e=Ga(ie?.tokens??{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}),t=e.hitRate*100,n=e.totalInput===0?``:e.hitRate>=.7?`ok`:e.hitRate>=.4?`mid`:`warn`,r=e.totalInput>0?`${t.toFixed(1)}%`:`—`,i=w(`cacheHitTip`,{read:$a(e.read),write:$a(e.write),miss:$a(e.miss),input:$a(e.totalInput)}),a=e.totalInput>0?`${w(`cacheHit`)}: ${r} · ${i}`:w(`cacheHit`),o=e.totalInput===0;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cache bar-item-cache${o?` is-zero`:``}`,title:a,"data-tip":a,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(f,{className:`bar-item-icon`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[W?`${W} `:``,(0,$.jsx)(`b`,{className:`cache-pct ${n}`,children:r})]})]})}if(U===`host:cost`){let e=ie?.cost??0,t=de.tooltip||w(`cumulativeCost`);return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cost bar-item-cost${e<=0?` is-zero`:``}${W?` has-name`:``}`,title:t,"data-tip":t,onContextMenu:ge,"data-bar-item":U,children:[W?(0,$.jsx)(`span`,{className:`bar-item-text`,children:W}):null,de.symbol?(0,$.jsx)(`span`,{className:`bar-item-char`,children:de.symbol}):null,(0,$.jsx)(`span`,{className:`bar-item-text`,children:de.value})]})}if(U===`host:msg-count`){let e=ie?.totalMessages??0,t=`${w(`sessionMessages`)}: ${e}`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-msg-count bar-item-msg-count${e===0?` is-zero`:``}`,title:t,"data-tip":t,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(Ae,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(String(e))})]})}if(U===`host:working`){if(!ae&&!se)return null;let e=ae||R,t=w(e?`working`:`done`),n=se?Math.max(0,Math.floor(((se.finishedAt??ue)-se.startedAt)/1e3)):0,r=n<3600?`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`:`${Math.floor(n/3600)}:${String(Math.floor(n/60)%60).padStart(2,`0`)}:${String(n%60).padStart(2,`0`)}`,i=(L?.queue?.steering?.length??0)+(L?.queue?.followUp?.length??0);return(0,$.jsxs)(`span`,{className:`bar-item status-item bar-item-working${e?` working`:``}`,title:`${t}${se?` · ${r}`:``}`,"data-tip":`${t}${se?` · ${r}`:``}`,onContextMenu:ge,"data-bar-item":U,children:[e&&(0,$.jsx)(`span`,{className:`working-spin`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[G(t),i>0&&` ⏳ ${i}`]}),se&&(0,$.jsx)(`span`,{className:`bar-item-duration`,children:r}),e&&me>0&&(0,$.jsx)(`span`,{className:`status-rate bar-item-rate`,title:w(`rateTip`),children:`${Math.round(me)}${w(`tps`)}`})]})}if(U===`host:status-delegate`)return L?.delegateMode?(0,$.jsxs)(`span`,{className:`bar-item status-item delegate-badge bar-item-delegate`,title:L.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),"data-tip":L.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(`span`,{className:`bar-item-icon`,children:`🔎`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:G(w(`delegateModeBadge`))}),L.delegateConvId?(0,$.jsx)(`button`,{type:`button`,className:`delegate-badge-open`,title:w(`delegateModeOpenTip`),onClick:()=>Z({type:`switch_conversation`,id:L.delegateConvId}),children:`↗`}):null]}):null;if(U===`host:host-metrics`){let e=n.hostMetrics;if(!e)return null;let t=e.cpuPercent===null||!Number.isFinite(e.cpuPercent)?`—`:`${Math.round(e.cpuPercent)}%`,r=Number.isFinite(e.memoryPercent)?`${Math.round(e.memoryPercent)}%`:`—`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-host-metrics bar-item-host-metrics`,title:`${w(`hostResourcesTip`)}\n${w(`hostProcessor`)}: ${t} · ${w(`hostMemory`)}: ${r}`,"data-tip":`${w(`hostResourcesTip`)}\n${w(`hostProcessor`)}: ${t} · ${w(`hostMemory`)}: ${r}`,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(E,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(`${t} · ${r}`)})]})}if(U===`host:browser`)return n.settings?.disabledAgentTools?.includes(`browser_page`)?null:(0,$.jsx)(`span`,{className:`bar-item-wrap`,onContextMenu:ge,"data-bar-item":U,children:(0,$.jsx)(Un,{})});let K=t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`;if(U===`host:language`)return(0,$.jsxs)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:M,onOpenChange:P,tip:G(w(`language`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(eo(D))})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`language`)}),O.map(e=>(0,$.jsx)(gt,{active:D===e.code,onClick:()=>{k(e.code),P(!1)},children:e.nativeName},e.code)),v?.onLocaleModalOpen?(0,$.jsxs)(gt,{onClick:()=>{P(!1),v.onLocaleModalOpen?.()},children:[(0,$.jsx)(S,{}),` `,w(`localeGetMore`)]}):null]});if(U===`host:theme`){let e=v?.themes??[],n=v?.theme??null;return(0,$.jsx)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:ee,onOpenChange:t=>{F(t),t&&e.length===0&&v?.reloadThemes?.()},tip:G(w(`theme`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(N,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:G(w(`theme`))})]}),children:(()=>{let t=e.filter(e=>e.group===`classic`),r=e.filter(e=>e.group!==`classic`),i=e=>{let t=H(D)?e.name:e.nameEn??e.name,n=e.scheme===`light`?w(`themeLight`):e.scheme===`dark`?w(`themeDark`):``;return n?H(D)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[t.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`themeGroupClassics`)}),t.map(e=>(0,$.jsx)(gt,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:t.length>0?w(`themeGroupBuiltin`):w(`theme`)}),(0,$.jsx)(gt,{active:n===null,onClick:()=>{v?.onThemeChange?.(null),F(!1)},children:w(`themeDefault`)}),r.map(e=>(0,$.jsx)(gt,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]})})()})}if(U===`host:update`){let e=v?.updatesCount??0;return v?.managed?(0,$.jsxs)(`span`,{className:`bar-item chip`,title:w(`updatesManaged`),"data-tip":w(`updatesManaged`),onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(S,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(`v${v?.appVersion??n.update?.current??`…`}`)})]}):(0,$.jsxs)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:te,onOpenChange:e=>{re(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},tip:G(w(`update`)),fit:!0,caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(S,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(`v${n.update?.current??`…`}`)}),n.update&&!n.update.upToDate&&(0,$.jsx)(`span`,{className:`update-dot`}),e>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:e})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`update`)}),v?.renderUpdateBody?.(),v?.renderAllUpdatesBody?.()]})}let q=null,J=e.label,ve=null,Y=!1,be=!1,xe=``,Se,Ce,we;switch(U){case`host:chat`:q=(0,$.jsx)(Ae,{className:`bar-item-icon`}),J=G(w(`chat`)),Y=r===`chat`,be=!0,Ce=()=>a?.(`chat`);break;case`host:terminal`:q=(0,$.jsx)(o,{className:`bar-item-icon`}),J=G(w(`terminal`)),Y=r===`terminal`,be=!0,Ce=()=>a?.(`terminal`);break;case`host:git`:q=(0,$.jsx)(ce,{className:`bar-item-icon`}),J=G(w(`scmTab`)),Y=r===`git`,be=!0,Ce=()=>a?.(`git`);break;case`host:canvas`:q=(0,$.jsx)(On,{className:`bar-item-icon`}),J=G(w(`canvasTab`)),Y=r===`canvas`,be=!0,Ce=()=>a?.(`canvas`);break;case`host:new-chat`:q=(0,$.jsx)(rt,{className:`bar-item-icon`}),J=G(w(`newChat`)),xe=`chip newchat`,Ce=()=>{a?.(`chat`),Z({type:`new_chat`}),Xt()};break;case`host:new-ephemeral-chat`:if(j)return null;q=(0,$.jsx)(kn,{className:`bar-item-icon`}),J=G(w(`newChatEphemeral`)),xe=`chip newchat ephemeral-chat-btn`,Ce=()=>{a?.(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt()};break;case`host:new-sandbox`:q=(0,$.jsx)(An,{className:`bar-item-icon`}),J=G(w(`newSandbox`)),xe=`chip newchat sandbox-chip`,Ce=()=>C?.();break;case`host:history`:if(r&&r!==`chat`)return null;q=(0,$.jsx)(ze,{className:`bar-item-icon`}),J=G(w(`openHistory`)),xe=`panel-toggle`,Ce=()=>s?.(`left`);break;case`host:files`:if(r&&r!==`chat`)return null;q=(0,$.jsx)(Be,{className:`bar-item-icon`}),J=G(w(`openFiles`)),xe=`panel-toggle has-label`,Ce=()=>s?.(`right`);break;case`host:open-project`:q=(0,$.jsx)(y,{className:`bar-item-icon`}),J=G(w(`openProject`)),xe=`chip open-project`,Y=!!h,Ce=()=>d?.();break;case`host:search`:q=(0,$.jsx)(Ee,{className:`bar-item-icon`}),J=G(w(`searchGlobal`)),xe=`chip`,Ce=()=>l?.();break;case`host:tasks`:q=(0,$.jsx)(fe,{className:`bar-item-icon`}),J=G(w(`bgTasks`)),xe=`chip bg-task-chip`,n.bgServers.length>0&&(ve=(0,$.jsx)(`span`,{className:`bg-task-badge bar-item-badge`,children:n.bgServers.length})),Ce=()=>u?.();break;case`host:zen-mode`:q=(0,$.jsx)(ne,{className:`bar-item-icon`}),J=G(w(`zenMode`)),xe=`chip chip-zen`,Y=!!b,Se=w(`zenModeTip`),Ce=()=>x?.();break;case`host:device-center`:q=(0,$.jsx)(le,{className:`bar-item-icon`}),J=G(w(`deviceCenter`)),xe=`chip`,Se=w(`deviceCenterTip`),be=!0,Y=r===`devices`,Ce=()=>a?.(`devices`);break;case`host:settings`:q=(0,$.jsx)(T,{className:`bar-item-icon`}),J=G(w(`settings`)),xe=`chip`,Ce=()=>c?.();break;case`host:plugins`:q=(0,$.jsx)(ye,{className:`bar-item-icon`}),J=G(w(`pluginMenuTitle`)),xe=`chip`,Ce=e=>{p?p(e.currentTarget):c?.(`plugins`)};break;case`host:github`:q=(0,$.jsx)(oe,{className:`bar-item-icon`}),J=G(`GitHub`),xe=`chip github`,Ce=()=>window.open(`https://github.com/xing-shuyin/pi-web-ui`,`_blank`,`noreferrer,noopener`);break;case`host:cwd`:q=(0,$.jsx)(Be,{className:`bar-item-icon`}),J=_e(L?.cwd?L.cwd.split(/[/\\]/).pop()||L.cwd:w(`openProject`)),xe=`status-item status-cwd`,Y=!!h,Ce=()=>{he.current!==null&&(window.clearTimeout(he.current),he.current=null),he.current=window.setTimeout(()=>{d?.(),he.current=null},220)},we=e=>{e.preventDefault(),e.stopPropagation(),he.current!==null&&(window.clearTimeout(he.current),he.current=null),Z({type:`new_chat`}),Xt()};break;case`host:plugin-status`:if(n.statuses.length===0)return null;q=(0,$.jsx)(Je,{className:`bar-item-icon`}),J=_e(n.statuses.map(e=>e.text).join(` · `)),xe=`status-item ext-status`;break;default:if(e.kind===`view`){let t=e.view??``;Y=r===t,be=!0;let o=(i??n.plugins??[]).find(t=>`plugin:${t.id}`===e.source);xe=`plugin-tab${o?.error?` broken`:``}`,o?.error&&(Se=`${e.label}: ${o.error}`);let s=e.iconSvg||o?.iconSvg,c=e.icon||o?.icon;q=s?(0,$.jsx)(Ir,{icon:c,iconSvg:s,className:`bar-item-icon plugin-icon-svg`}):c?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:c}):null,Ce=()=>a?.(t)}else{let n=e.iconSvg,r=e.icon;xe=t===`bottom`?`status-item status-action chip`:`chip`,q=n?(0,$.jsx)(Ir,{icon:r,iconSvg:n,className:`bar-item-icon plugin-icon-svg`}):r?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:r}):null,e.badge&&(ve=(0,$.jsx)(`span`,{className:`bar-item-badge`,children:e.badge})),Ce=()=>g?.(e)}}let Te=Se??e.hint??J,De=[`bar-item`,be?`tb-tab${Y?` active`:``}`:``,xe,Y&&!be?`active`:``].filter(Boolean).join(` `);return(0,$.jsxs)(`button`,{type:`button`,role:be?`tab`:void 0,"aria-selected":be?Y:void 0,"aria-haspopup":U===`host:plugins`?`menu`:void 0,"aria-expanded":U===`host:plugins`?!!m:void 0,className:De,title:Te,"data-tip":Te,"aria-label":J,onClick:Ce,onDoubleClick:we,onContextMenu:ge,"data-bar-item":U,children:[q,(0,$.jsx)(`span`,{className:`bar-item-text`,children:J}),ve]})}function no(){let{locale:e}=Ue(),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(()=>typeof window<`u`);if((0,Q.useEffect)(()=>{i(!0);let e=Ct();if(!e)return;e.isMaximized().then(n);let t=e.onMaximizedChange(e=>{n(e)});return()=>t()},[]),!r||!wt()||Tt()===`darwin`)return null;let a=Ct();if(!a)return null;let o=H(e);return(0,$.jsxs)(`div`,{className:`window-controls`,"aria-label":`Window controls`,children:[(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void a.minimize(),title:o?`最小化`:`Minimize`,"aria-label":o?`最小化`:`Minimize`,children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M1.5 5.5H9.5`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void a.toggleMaximize(),title:t?o?`向下还原`:`Restore`:o?`最大化`:`Maximize`,"aria-label":t?o?`向下还原`:`Restore`:o?`最大化`:`Maximize`,children:t?(0,$.jsxs)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:[(0,$.jsx)(`path`,{d:`M3 3V1.5C3 1.22 3.22 1 3.5 1H9.5C9.78 1 10 1.22 10 1.5V7.5C10 7.78 9.78 8 9.5 8H8`,stroke:`currentColor`,strokeWidth:`1.1`}),(0,$.jsx)(`rect`,{x:`1`,y:`3`,width:`7`,height:`7`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})]}):(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`rect`,{x:`1.5`,y:`1.5`,width:`8`,height:`8`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn win-ctrl-close`,onClick:()=>void a.close(),title:o?`关闭`:`Close`,"aria-label":o?`关闭`:`Close`,children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 2L9 9M9 2L2 9`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})})]})}var ro={name:`@earendil-works/pi-coding-agent`,kind:`pi-core`,current:``,latest:null,upToDate:!1};function io({anchorRef:e,open:t,onClose:n,children:r}){let{panelRef:i,style:a,measure:o}=Cn({open:t,anchor:e,onClose:n});return(0,Q.useLayoutEffect)(()=>{t&&o()},[t,r,o]),t?(0,bn.createPortal)((0,$.jsx)(`div`,{ref:i,className:`plugin-topbar-menu portal`,role:`menu`,style:a,children:r}),document.body):null}function ao(){let[e,t]=(0,Q.useState)(()=>typeof window<`u`&&window.matchMedia!==void 0&&window.matchMedia(`(max-width: 768px)`).matches);return(0,Q.useEffect)(()=>{if(typeof window>`u`||window.matchMedia===void 0)return;let e=window.matchMedia(`(max-width: 768px)`),n=e=>t(e.matches);return typeof e.addEventListener==`function`?e.addEventListener(`change`,n):e.addListener(n),()=>{typeof e.removeEventListener==`function`?e.removeEventListener(`change`,n):e.removeListener(n)}},[]),e}function oo({chat:e,terminal:t,view:n,plugins:r,uiPrimary:i,uiOverflow:a,uiContextTopbar:s,onUiAction:c,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onManagePlugins:f,onOpenBgTasks:p,onOpenGlobalSearch:m,themes:h,theme:g,onThemeChange:_,reloadThemes:v,onOpenIconEdit:b,zenMode:x,onToggleZenMode:C,onOpenSandboxModal:w}){let{locale:E,setLocale:D,t:O,packs:k}=Ue(),[A,j]=(0,Q.useState)(!1),[P,ee]=(0,Q.useState)(!1),[F,te]=(0,Q.useState)(null),[re,I]=(0,Q.useState)(!1),[L,ie]=(0,Q.useState)(null),ae=en(`cwd`),se=en(`workspaceRoots`),R=$t(),ue=rn().ephemeralChat!==!1&&!R,z=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{z.current!==null&&window.clearTimeout(z.current)},[]);let de=(0,Q.useRef)(null),B=t=>!e.tabs||t===`chat`||e.tabs.includes(t),V=[...a??[]].filter(e=>(e.source!==`host`||e.id!==`host:brand`)&&!ii(e)),pe=new Set([...i??[],...a??[]].filter(e=>ii(e)&&!e.hidden).map(e=>e.source.slice(7))),me=new Map((e.settings?.uiLayout?.order??[]).map((e,t)=>[e,t])),he=r.map((e,t)=>({id:e.id,index:t})).sort((e,t)=>(me.get(`${e.id}:__view`)??1e6+e.index)-(me.get(`${t.id}:__view`)??1e6+t.index)).map(e=>e.id),ge=i===void 0?[`host:history`,`host:brand`,`host:engine`,`host:open-project`,`host:chat`,`host:terminal`,`host:git`,`host:canvas`,`host:plugins`,`host:search`,`host:browser`,`host:tasks`,`host:zen-mode`,`host:device-center`,`host:settings`,`host:language`,`host:theme`,`host:update`,`host:github`,`host:new-chat`,`host:new-ephemeral-chat`,`host:new-sandbox`,`host:files`].map(e=>({id:e,entry:null})):i.map(e=>({id:e.id,entry:e})),U=(B(`plugins`)?r:[]).filter(e=>e.view!==!1&&e.error&&!ge.some(t=>t.id===`${e.id}:__view`)).map(e=>({id:`${e.id}:__view`,slot:`topbar.primary`,source:`plugin:${e.id}`,label:e.name,kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!1,userOverrides:[],arrangedBy:[]})),W=e=>{if(e.source!==`host`)return!1;switch(e.id){case`host:history`:return u(`left`),!0;case`host:files`:return u(`right`),!0;case`host:new-chat`:return l(`chat`),Z({type:`new_chat`}),Xt(),!0;case`host:new-ephemeral-chat`:return l(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt(),!0;case`host:new-sandbox`:return w?.(),!0;case`host:open-project`:return ee(!0),!0;case`host:search`:return m(),!0;case`host:tasks`:return p(),!0;case`host:zen-mode`:return C?.(),!0;case`host:device-center`:return l(`devices`),!0;case`host:settings`:return d(),!0;case`host:plugins`:return te(de.current?{rect:de.current.getBoundingClientRect(),el:de.current}:null),!0;default:return!1}},G=(t,n,r)=>{t.preventDefault(),t.stopPropagation();let i=e.settings?.uiLayout,a=e=>{let t={...i?.slots,[n]:e},r={...i?.align};(e===`sidebar.left`||e===`sidebar.right`)&&!r[n]&&(r[n]=`center`),Z({type:`set_settings`,uiLayout:{...i,slots:t,...r[n]?{align:r}:{}}})},o=()=>{let e=new Set(i?.hidden??[]);e.add(n);let t=(i?.shown??[]).filter(e=>e!==n);Z({type:`set_settings`,uiLayout:{...i,hidden:[...e],shown:t}})},c=()=>{Z({type:`set_settings`,uiLayout:Ti(i,n)})},l=[{id:`host:move-bottom`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToBottom`),kind:`action`,order:10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-left`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToLeft`),kind:`action`,order:20,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-right`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToRight`),kind:`action`,order:30,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}];ti.has(n)||l.push({id:`host:hide-item`,slot:`contextmenu.topbar`,source:`host`,label:O(`uiLayoutHide`),kind:`action`,order:40,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),(i?.slots?.[n]||i?.labels?.[n]||i?.align?.[n]||i?.order?.includes(n))&&l.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:O(`uiLayoutRestore`),kind:`action`,order:50,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),s&&s.length>0&&l.push(...s),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.topbar`,target:{id:n,label:r},entries:l,onHostAction:e=>{e.id===`host:move-bottom`?a(`bottombar`):e.id===`host:move-left`?a(`sidebar.left`):e.id===`host:move-right`?a(`sidebar.right`):e.id===`host:hide-item`?o():e.id===`host:restore-item`&&c()}})},{appVersion:_e}=Qt(),K=tn(),q=sn(),[J,ve]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{J&&e.status===`open`&&ve(!1)},[J,e.status]);let[Y,be]=(0,Q.useState)(!1),[xe,Se]=(0,Q.useState)(!1),[Ce,we]=(0,Q.useState)(!1),Te=wt(),De=Wa(),[X,Oe]=(0,Q.useState)(!1),ke=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{if(ke.current.size===0)return;let t=!1;for(let n of Array.from(ke.current)){let r=e.terminals.find(e=>e.id===n);r&&!r.running&&(ke.current.delete(n),t=!0)}t&&e.ready&&(Z({type:`check_update`}),Z({type:`check_updates_all`,force:!0}))},[e.terminals,e.ready]);let je=()=>{if(!e.ready)return;let n=O(`updateTabTitle`),r={name:n,command:`npm i -g pi-web-ui@latest`,cwd:"${pwd}"},i=e.terminals.find(e=>e.title===n);if(i)ke.current.add(i.id),t.restart(i.id),Z({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:r,cols:80,rows:24});else{let i=ht();ke.current.add(i),t.create({id:i,conversationId:e.activeConversationId||e.state?.conversationId||``,title:n,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:r})}we(!1),l(`terminal`)},Me=(n,r)=>{if(!e.ready||n.length===0)return;let i={name:r,command:jn(n),cwd:"${pwd}"},a=e.terminals.find(e=>e.title===r);if(a)ke.current.add(a.id),t.restart(a.id),Z({type:`run_command`,terminalId:a.id,conversationId:a.conversationId,command:i,cols:80,rows:24});else{let n=ht();ke.current.add(n),t.create({id:n,conversationId:e.activeConversationId||e.state?.conversationId||``,title:r,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:i})}we(!1),l(`terminal`)},Ne=e.updatesAll??[],Pe=e.updatesSdk,Fe=Pe&&Pe.newerInstalled?{running:Pe.running,installed:Pe.newerInstalled}:null,Ie=Pe?.bundledInUse===!0,Le=Ne.find(e=>e.kind===`pi-core`&&!e.error),Re=Ie&&(!Le||!Le.upToDate),Ve=Re&&!Le,He=Ne.filter(e=>!e.upToDate&&!e.error).length,We=Ne.filter(e=>!e.upToDate&&!e.error&&e.kind!==`webui`),Ge=e=>e.kind===`git-extension`&&e.source?e.source:e.name,Ke=e=>e.kind===`git-extension`&&e.source&&e.source!==e.name?`${e.source} (${e.name})`:e.name,qe=e=>{let t=e.replace(/ \([0-9a-f]{7}\)$/,``);return/^[0-9a-f]{7}$/.test(t)?``:t},Je=e=>(e.match(/\(([0-9a-f]{7})\)$/)??e.match(/^([0-9a-f]{7})$/))?.[1]??null,Xe=(e,t)=>{if(!t)return qe(e);let n=qe(e),r=qe(t);if(n!==r)return`${n} → ${r}`;let i=Je(e),a=Je(t);return i&&a&&i!==a?n?`${n} (${i} → ${a})`:`${i} → ${a}`:n},Ze=()=>(0,$.jsxs)(`div`,{className:`dd-updates-all`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`updatesAllTitle`)}),e.updatesAll===null?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`checkingUpdate`)}):Ne.length===0?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updatesAllUpToDate`)}):(0,$.jsx)(`ul`,{className:`dd-all-list`,children:Ne.map(e=>{let t=Fe!=null&&e.kind===`pi-core`,n=!e.error&&(!e.upToDate||t);return(0,$.jsxs)(`li`,{className:`dd-all-item${e.error?` err`:n?` warn`:``}`,children:[e.kind!==`webui`&&!e.upToDate&&!e.error&&(0,$.jsx)(`button`,{type:`button`,className:`dd-update-btn`,onClick:()=>Me([e],O(`updatePkgTabTitle`,{name:e.name})),children:O(`updateBtn`)}),(0,$.jsx)(`span`,{className:`dd-all-name`,title:Ke(e),children:Ge(e)}),(0,$.jsxs)(`span`,{className:`dd-all-meta`,children:[(0,$.jsx)(`span`,{className:`dd-all-kind`,children:e.kind===`webui`?O(`kindWebUi`):e.kind===`pi-core`?O(`kindPiCore`):e.kind===`engine`?O(`kindEngine`):e.kind===`git-extension`?O(`kindGitExtension`):e.kind===`plugin`?O(`kindPlugin`):O(`kindPackage`)}),(0,$.jsx)(`span`,{className:`dd-all-vers`,title:e.error?e.error:e.kind===`git-extension`?e.upToDate?e.current:`${e.current} → ${e.latest}`:void 0,children:e.error?e.kind===`pi-core`&&e.current===`unknown`?O(`piCoreUndetected`):O(`updateCheckFailed`):e.kind===`git-extension`?e.upToDate?qe(e.current):Xe(e.current,e.latest):e.kind===`plugin`?e.upToDate?e.current.startsWith(`v`)?e.current:qe(e.current):Xe(e.current,e.latest):e.upToDate?`v${e.current}`:(0,$.jsxs)($.Fragment,{children:[`v`,e.current,` → v`,e.latest]})}),t&&!e.error&&(0,$.jsx)(`span`,{className:`dd-split-run`,children:O(`piCoreSplitRun`,{running:Fe.running})})]})]},`${e.kind}:${e.name}`)})}),Fe&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`piSdkSplitNote`,{running:Fe.running,installed:Fe.installed})}),Re&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`piSdkBundledNote`,{running:Pe.running})}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[Ve&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Me([ro],O(`installGlobalEngineTabTitle`)),children:O(`installGlobalEngineBtn`)}),We.length>0&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Me(We,O(`updateAllTabTitle`)),children:O(`updateAllBtn`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,style:We.length>0?{flex:1}:void 0,onClick:()=>Z({type:`check_updates_all`,force:!0}),children:O(`updatesAllRefresh`)})]})]}),Qe=()=>{let t=Ua(e.update?.latest??De.version),n=(0,$.jsx)(`a`,{className:`dd-refresh dd-more-link`,href:t,target:`_blank`,rel:`noreferrer noopener`,children:O(`updateDesktopManual`)});if(!De.bridge)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopNoBridge`)}),n]});switch(De.state){case`checking`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopChecking`)}),n]});case`available`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopAvailable`,{version:De.version??e.update?.latest??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.download(),children:O(`updateDesktopDownload`)}),n]});case`downloading`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopDownloading`,{n:De.percent})}),n]});case`downloaded`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`updateDesktopDownloaded`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.quitAndInstall(),children:O(`updateDesktopInstall`)}),n]});case`up-to-date`:return(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`upToDate`)});case`error`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopError`,{error:De.message??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>De.check(),children:O(`updateDesktopCheck`)}),n]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.check(),children:O(`updateDesktopCheck`)}),n]})}},$e=()=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-update`,children:[(0,$.jsxs)(`div`,{className:`dd-row`,children:[(0,$.jsx)(`span`,{children:O(`currentVersion`)}),(0,$.jsxs)(`b`,{children:[`v`,e.update?.current??`…`]})]}),(0,$.jsxs)(`div`,{className:`dd-row`,children:[(0,$.jsx)(`span`,{children:O(`latestVersion`)}),(0,$.jsx)(`b`,{children:e.update===null?O(`checkingUpdate`):e.update.error?e.update.error:e.update.latest?`v${e.update.latest}`:O(`checkingUpdate`)})]}),e.update&&e.update.upToDate&&(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`upToDate`)}),e.update&&!e.update.upToDate&&e.update.latest&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateAvailable`,{version:e.update.latest})}),e.update?.latestPublishedAt&&Date.now()-new Date(e.update.latestPublishedAt).getTime()<18e5&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateJustPublished`,{version:e.update.latest??``})}),e.update&&!e.update.upToDate&&e.update.latest&&!Te&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateTerminalHint`)}),e.update&&!e.update.upToDate&&e.update.latest&&Te&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopNote`)})]}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>Z({type:`check_update`}),children:e.update===null?O(`checkingUpdate`):O(`checkUpdate`)}),e.update&&!e.update.upToDate&&e.update.latest&&!Te&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:je,children:O(`updateNow`)}),e.update&&!e.update.upToDate&&e.update.latest&&Te&&Qe(),q&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,disabled:J,title:O(`restartServiceTip`,{name:q.name}),onClick:()=>{J||(ve(!0),Z({type:`restart_service`}))},children:O(J?`restartingService`:`restartService`)})]})]}),et=ao(),tt={"host:brand":(0,$.jsx)(En,{}),"host:open-project":(0,$.jsxs)(`button`,{type:`button`,className:`chip open-project`,"data-tip":O(`openProject`),onClick:()=>ee(!0),children:[(0,$.jsx)(y,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`openProject`)})]}),"host:history":n===`chat`&&B(`history`)?(0,$.jsx)(`button`,{type:`button`,className:`panel-toggle`,"data-tip":O(`openHistory`),"aria-label":O(`openHistory`),onClick:()=>u(`left`),children:(0,$.jsx)(ze,{})}):null,"host:files":n===`chat`&&B(`files`)?(0,$.jsxs)(`button`,{type:`button`,className:`panel-toggle has-label`,"data-tip":O(`openFiles`),"aria-label":O(`openFiles`),onClick:()=>u(`right`),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:O(`openFiles`)})]}):null,"host:new-chat":B(`new-chat`)?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat`,"data-tip":O(`newChatTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`}),Xt()},children:[(0,$.jsx)(rt,{}),(0,$.jsx)(`span`,{children:O(`newChat`)})]}):null,"host:new-ephemeral-chat":ue?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat ephemeral-chat-btn`,"data-tip":O(`newChatEphemeralTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt()},children:[(0,$.jsx)(kn,{}),(0,$.jsx)(`span`,{children:O(`newChatEphemeral`)})]}):null,"host:new-sandbox":(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat sandbox-chip`,"data-tip":O(`newSandboxTip`),"aria-label":O(`newSandboxTip`),onClick:()=>w?.(),children:[(0,$.jsx)(An,{}),(0,$.jsx)(`span`,{children:O(`newSandbox`)})]}),"host:chat":(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`chat`,className:`tb-tab${n===`chat`?` active`:``}`,"data-tip":O(`chat`),onClick:()=>l(`chat`),children:[(0,$.jsx)(Ae,{}),(0,$.jsx)(`span`,{children:O(`chat`)})]}),"host:terminal":B(`terminal`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`terminal`,className:`tb-tab${n===`terminal`?` active`:``}`,"data-tip":O(`terminal`),onClick:()=>l(`terminal`),children:[(0,$.jsx)(o,{}),(0,$.jsx)(`span`,{children:O(`terminal`)})]}):null,"host:git":B(`git`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`git`,className:`tb-tab${n===`git`?` active`:``}`,"data-tip":O(`scmTab`),onClick:()=>l(`git`),children:[(0,$.jsx)(ce,{}),(0,$.jsx)(`span`,{children:O(`scmTab`)})]}):null,"host:canvas":B(`canvas`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`canvas`,className:`tb-tab${n===`canvas`?` active`:``}`,"data-tip":O(`canvasTab`),onClick:()=>l(`canvas`),children:[(0,$.jsx)(On,{}),(0,$.jsx)(`span`,{children:O(`canvasTab`)})]}):null,"host:plugins":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`pluginMenuTitle`),"aria-haspopup":`menu`,"aria-expanded":F!==null,onClick:e=>{let t=e.currentTarget;te(e=>e?.el===t?null:{rect:t.getBoundingClientRect(),el:t})},children:[(0,$.jsx)(ye,{"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`pluginMenuTitle`)})]}),"host:search":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`searchGlobalTip`),onClick:m,children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`searchGlobal`)})]}),"host:browser":e.settings?.disabledAgentTools?.includes(`browser_page`)??!1?null:(0,$.jsx)(Un,{}),"host:tasks":(0,$.jsxs)(`button`,{type:`button`,className:`chip bg-task-chip`,"data-tip":O(`bgTasksTip`),onClick:p,children:[(0,$.jsx)(fe,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`bgTasks`)}),e.bgServers.length>0&&(0,$.jsx)(`span`,{className:`bg-task-badge`,children:e.bgServers.length})]}),"host:zen-mode":(0,$.jsxs)(`button`,{type:`button`,className:`chip chip-zen${x?` active`:``}`,"data-tip":O(`zenModeTip`),onClick:C,"aria-label":O(`zenMode`),"aria-pressed":x,children:[(0,$.jsx)(ne,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`zenMode`)})]}),"host:device-center":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`deviceCenterTip`),onClick:()=>l(`devices`),"aria-pressed":n===`devices`,children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`deviceCenter`)})]}),"host:settings":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`settingsTitle`),onClick:d,children:[(0,$.jsx)(T,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`settings`)})]}),"host:language":(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:Ye(E)})]}),tip:O(`language`),open:Y,onOpenChange:be,caret:!1,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`language`)}),k.map(e=>(0,$.jsx)(gt,{active:E===e.code,onClick:()=>{D(e.code),be(!1)},children:e.nativeName},e.code)),(0,$.jsxs)(gt,{onClick:()=>{be(!1),Oe(!0)},children:[(0,$.jsx)(S,{}),` `,O(`localeGetMore`)]})]}),"host:theme":(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(N,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`theme`)})]}),tip:O(`theme`),open:xe,caret:!1,onOpenChange:e=>{Se(e),e&&h.length===0&&v()},children:(()=>{let e=h.filter(e=>e.group===`classic`),t=h.filter(e=>e.group!==`classic`),n=e=>{let t=H(E)?e.name:e.nameEn??e.name,n=e.scheme===`light`?O(`themeLight`):e.scheme===`dark`?O(`themeDark`):``;return n?H(E)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[e.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`themeGroupClassics`)}),e.map(e=>(0,$.jsx)(gt,{active:g===e.id,onClick:()=>{_(e.id),Se(!1)},children:n(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:e.length>0?O(`themeGroupBuiltin`):O(`theme`)}),(0,$.jsx)(gt,{active:g===null,onClick:()=>{_(null),Se(!1)},children:O(`themeDefault`)}),t.map(e=>(0,$.jsx)(gt,{active:g===e.id,onClick:()=>{_(e.id),Se(!1)},children:n(e)},e.id))]})})()}),"host:update":K?(0,$.jsxs)(`span`,{className:`chip`,"data-tip":O(`updatesManaged`),children:[(0,$.jsx)(S,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,_e??e.update?.current??`…`]})]}):(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(S,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,e.update?.current??`…`]}),e.update&&!e.update.upToDate&&(0,$.jsx)(`span`,{className:`update-dot`,title:O(`updateAvailable`,{version:e.update.latest??``})}),He>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:O(`updatesAllBadge`,{n:He})})]}),tip:O(`update`),open:Ce,caret:!1,onOpenChange:e=>{we(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},fit:!0,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`update`)}),$e(),Ze()]}),"host:github":(0,$.jsx)(`a`,{className:`chip github`,href:`https://github.com/xing-shuyin/pi-web-ui`,target:`_blank`,rel:`noreferrer noopener`,"data-tip":O(`githubRepo`),children:(0,$.jsx)(oe,{})}),"host:conn":(0,$.jsxs)(`span`,{className:`chip`,"data-tip":e.status,children:[(0,$.jsx)(`span`,{className:`status-dot ${e.status===`open`?`ok`:`busy`}`}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.status})]}),"host:engine":(0,$.jsx)(Qa,{direction:`down`,align:`left`,caret:!1,bar:`top`}),"host:ctx":(0,$.jsx)(`span`,{className:`chip`,"data-tip":O(`contextUsage`),children:(0,$.jsx)(`span`,{className:`chip-sub`,children:(e.state?.stats?.contextUsage?.tokens??0)>0?`${e.state?.stats?.contextUsage?.tokens}`:O(`contextUsage`)})}),"host:cost":(()=>{let t=Jt(e.state?.stats?.cost??0,{fixedDigits:4});return(0,$.jsx)(`span`,{className:`chip`,"data-tip":t.tooltip||O(`cumulativeCost`),children:(0,$.jsxs)(`span`,{className:`chip-sub`,children:[t.symbol,t.value]})})})(),"host:cwd":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":e.state?.cwd??``,onClick:()=>{z.current!==null&&(window.clearTimeout(z.current),z.current=null),z.current=window.setTimeout(()=>{ee(!0),z.current=null},220)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),z.current!==null&&(window.clearTimeout(z.current),z.current=null),Z({type:`new_chat`}),Xt()},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.state?.cwd?.split(/[/\\]/).pop()||e.state?.cwd})]})},nt=new Set([`host:search`,`host:tasks`,`host:settings`,`host:plugins`]),it=new Set([`host:language`,`host:theme`,`host:update`,`host:browser`,`host:engine`]),at=e=>nt.has(e)&&!B(e.slice(5)),ot=e=>{if(e.kind===`view`){if(!B(`plugins`))return null;let t=e.view??``,i=r.find(t=>`plugin:${t.id}`===e.source),a=i?.error?`${e.label}: ${i.error}`:e.hint??e.label;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===t,className:`tb-tab plugin-tab${n===t?` active`:``}${i?.error?` broken`:``}`,"data-tip":a,onClick:()=>l(t),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`plugin-topbar-item plugin-topbar-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>c?.(e,t.target.value),onContextMenu:t=>G(t,e.id,e.label),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`plugin-topbar-item`,"data-tip":e.hint??e.label,onClick:()=>c?.(e),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)},st=[];for(let t of ge){if(t.entry?.hidden||at(t.id))continue;let i=null;t.entry?i=(0,$.jsx)(to,{entry:t.entry,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onOpenGlobalSearch:m,onOpenBgTasks:p,onOpenProjectPicker:()=>ee(!0),isProjectPickerOpen:P,onOpenPluginMenu:e=>te(t=>t?.el===e?null:{rect:e.getBoundingClientRect(),el:e}),isPluginMenuOpen:F!==null,onUiAction:c,uiContextEntries:s,zenMode:x,onToggleZenMode:C,onOpenSandboxModal:w,dropdownProps:{theme:g,themes:h,onThemeChange:_,reloadThemes:v,onLocaleModalOpen:()=>Oe(!0),renderUpdateBody:$e,renderAllUpdatesBody:Ze,updatesCount:He,managed:K,appVersion:_e}},t.id):t.id.startsWith(`host:`)&&tt[t.id]&&(i=tt[t.id]),i&&st.push({id:t.id,entry:t.entry,node:i})}for(let t of U){let i=(0,$.jsx)(to,{entry:t,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onUiAction:c,uiContextEntries:s},t.id);i&&st.push({id:t.id,entry:t,node:i})}let ct=e=>e.entry?.align??`start`,[lt,ut]=(0,Q.useState)(()=>new Set),dt=(0,Q.useRef)(null),ft=(0,Q.useRef)(new Map),pt=st.filter(e=>!lt.has(e.id)),mt=et?pt.filter(e=>Oi.has(e.id)):[],vt=et?pt.filter(e=>!Oi.has(e.id)):pt,yt=et?st.filter(e=>!Oi.has(e.id)):st,bt=[...yt.filter(e=>ct(e)===`start`),...yt.filter(e=>ct(e)===`center`),...yt.filter(e=>ct(e)===`end`)],xt=bt.filter(e=>!lt.has(e.id)),St=(0,Q.useRef)(bt),Ct=(0,Q.useRef)(xt);(0,Q.useLayoutEffect)(()=>{St.current=bt,Ct.current=xt});let Tt=()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`)),n=Ct.current;t.length===n.length&&n.forEach((e,n)=>ft.current.set(e.id,t[n].offsetWidth));for(let n of t){let t=n;t.offsetWidth>0&&e.clientWidth>0&&t.offsetLeft+t.offsetWidth/2<Math.min(220,e.clientWidth/2)?t.setAttribute(`data-tip-align`,`right`):t.removeAttribute(`data-tip-align`)}let r=Number.parseFloat(getComputedStyle(e).columnGap)||0,i=St.current,a=Ai(i.map(e=>({id:e.id,width:e.entry?ft.current.get(e.id)??0:0})),e.clientWidth,r,0,ti);ut(e=>e.size===a.size&&[...a].every(t=>e.has(t))?e:a)},Et=`${pt.map(e=>`${e.id}:${e.entry?.label??``}`).join(`|`)}|${n}|${(e.tabs??[]).join(`,`)}|${et?`m`:`d`}`;(0,Q.useLayoutEffect)(Tt,[Et]),(0,Q.useEffect)(()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>Tt());return t.observe(e),()=>t.disconnect()},[Et]);let Dt=vt.filter(e=>ct(e)===`start`),Ot=vt.filter(e=>ct(e)===`center`),kt=vt.filter(e=>ct(e)===`end`),At=st.filter(e=>lt.has(e.id)&&e.entry).map(e=>e.entry),jt=new Map;[...i??[],...a??[]].forEach((e,t)=>{jt.has(e.id)||jt.set(e.id,t)});let Mt=ki([...V,...At],e=>jt.get(e)??999999),Nt=e=>e.icon&&!/[a-z]/i.test(e.icon)?e.icon:null,Pt=e.settings?.uiLayout?.topbarText===!1;return(0,$.jsxs)(`header`,{className:`topbar${Pt?` no-labels`:``}`,"data-pi-anchor":`topbar`,children:[(0,$.jsxs)(`div`,{className:`topbar-flow`,ref:dt,role:`toolbar`,"aria-label":O(`viewSwitch`),children:[Dt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(Ot.length>0||kt.length>0)&&(0,$.jsx)(`span`,{className:`tb-spacer${Ot.length===0&&kt.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Ot.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),Ot.length>0&&(0,$.jsx)(`span`,{className:`tb-spacer${kt.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),kt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id))]}),(Mt.length>0||st.length>0)&&(0,$.jsxs)(`div`,{className:`plugin-topbar-more`,children:[(0,$.jsx)(`button`,{ref:de,type:`button`,className:`plugin-topbar-item`,"aria-haspopup":`menu`,"aria-expanded":A,"aria-label":O(`pluginTopbarMore`),"data-tip":O(`pluginTopbarMore`),onClick:()=>j(e=>!e),children:(0,$.jsx)(Dn,{})}),(0,$.jsxs)(io,{anchorRef:de,open:A,onClose:()=>j(!1),children:[Mt.map(e=>{let t=e.source===`host`&&it.has(e.id)?tt[e.id]:void 0;if(t!==void 0)return(0,$.jsx)(Q.Fragment,{children:t},e.id);if(e.source===`host`&&e.id===`host:github`)return(0,$.jsxs)(`a`,{role:`menuitem`,className:`chip github`,href:`https://github.com/xing-shuyin/pi-web-ui`,target:`_blank`,rel:`noreferrer noopener`,title:O(`githubRepo`),onClick:()=>j(!1),children:[(0,$.jsx)(oe,{}),(0,$.jsx)(`span`,{children:`GitHub`})]},e.id);if(e.source===`host`){let t=tt[e.id];if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}else{let t=ot(e);if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsxs)(`label`,{className:`plugin-topbar-overflow-select tb-row`,title:e.hint??e.label,children:[Nt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Nt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label}),(0,$.jsx)(`select`,{"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>{j(!1),W(e)||c?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]},e.id):(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,title:e.hint??e.label,onClick:()=>{j(!1),W(e)||c?.(e)},children:[Nt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Nt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label})]},e.id)}),(0,$.jsx)(`div`,{className:`tb-menu-divider`,"aria-hidden":`true`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,onClick:()=>{j(!1),b()},children:[(0,$.jsx)(M,{}),(0,$.jsx)(`span`,{className:`tb-row-text`,children:O(`uiIconEdit`)})]})]})]}),mt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(0,$.jsx)(no,{}),X&&(0,$.jsx)(Ia,{onClose:()=>Oe(!1)}),F&&(0,$.jsx)(Ca,{anchorRect:F.rect,anchorEl:F.el,plugins:r.map(t=>{let n=(e.plugins??[]).find(e=>e.id===t.id);return{...t,hasSettings:!!(n?.settingsSchema&&n.settingsSchema.length>0)}}),pinnedIds:pe,orderedPluginIds:he,onTogglePin:(t,n)=>Z({type:`set_settings`,uiLayout:ai(e.settings?.uiLayout,t,n)}),onReorder:t=>Z({type:`set_settings`,uiLayout:oi(e.settings?.uiLayout,t)}),onOpenView:e=>{te(null),l(`plugin:${e}`)},onOpenPluginSettings:e=>{ie(e??null),I(!0)},onManagePlugins:f,onClose:()=>te(null)}),re&&(0,$.jsx)(Fa,{open:re,onClose:()=>{I(!1),ie(null)},focusPluginId:L,plugins:e.plugins??[],disabledPlugins:e.settings?.disabledPlugins??[],models:e.settings?.subagentModels??[],onTogglePlugin:t=>{let n=new Set(e.settings?.disabledPlugins??[]);n.has(t.id)?n.delete(t.id):n.add(t.id),Z({type:`set_settings`,disabledPlugins:[...n]})},onOpenView:e=>{I(!1),l(`plugin:${e}`)},onOpenMarketplace:()=>{I(!1),f()}}),P&&(0,$.jsx)(ba,{open:!0,currentCwd:ae,pathCompletions:e.pathCompletions??[],workspaceRoots:se,onClose:()=>ee(!1),onSelectDirectory:e=>Z({type:`set_cwd`,path:e}),onCreateProject:e=>Z({type:`make_dir`,path:e,setAsCwd:!0})})]})}function so(e){return`@${e.name}(${e.id})`}function co(e,t){return e.filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(t.toLocaleLowerCase())).map(e=>({providerId:`host:group-devices`,providerLabel:`Bot`,title:e.name,hint:e.id,text:so(e)}))}function lo(e,t){return[...new Set(t.filter(t=>e.includes(so(t))).map(e=>e.id))]}function uo(e,t,n,r=!1){let i=new Map,a=[],o=new Map(n.map(e=>[e.id,e]));for(let e of t?.bots??[])o.set(e.id,{...o.get(e.id),...e});let s=r?{queued:`排队中`,running:`运行中`,completed:`已完成`,failed:`失败`,interrupted:`已中断`}:{queued:`Queued`,running:`Running`,completed:`Completed`,failed:`Failed`,interrupted:`Interrupted`},c=new Map((t?.tasks??[]).map(e=>[e.id,e])),l=new Set,u=(e,t,n)=>{let r=e?o.get(e):void 0,i=r?.deviceName||n||r?.deviceId;return i?`${t} · ${i}`:t};for(let e of t?.messages??[]){let t=`group-message:${e.id}`;if(a.push({id:t,role:e.sender.type===`bot`?`assistant`:`user`,timestamp:e.createdAt,content:[{type:`text`,text:e.text}]}),e.sender.type!==`bot`){i.set(t,e.sender.name);continue}let n=(e.taskIds??[]).map(e=>c.get(e)).filter(t=>!!t&&t.botId===e.sender.id);for(let e of n)e.report&&l.add(e.id);let r=[...new Set(n.map(e=>s[e.status]))].join(` · `),o=u(e.sender.id,e.sender.name,e.sender.sourceDeviceId);i.set(t,r?`${o} · ${r}`:o)}for(let e of t?.tasks??[]){if(l.has(e.id))continue;let t=`group-task:${e.id}`,n=o.get(e.botId);i.set(t,`${u(e.botId,n?.name??e.botId,e.deviceId)} · ${s[e.status]}`),a.push({id:t,role:`assistant`,timestamp:e.createdAt,content:[{type:`text`,text:e.report||`${s[e.status]}\n\n${e.text}`}]})}return a.sort((e,t)=>(e.timestamp??0)-(t.timestamp??0)),{state:{clientId:`device-group`,cwd:``,sessionId:`device-group:${e}`,conversationId:`device-group:${e}`,rev:0,messages:a,streamingMessage:null,isStreaming:!1,model:null,thinkingLevel:``,availableThinkingLevels:[],queue:{steering:[],followUp:[]},tools:[],version:0,piConfigured:!0,piAgentInstalled:!0,stats:{totalMessages:a.length,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,contextUsage:{tokens:null,contextWindow:0,percent:null}}},labels:i}}function fo(e,t,n,r,i){let a=JSON.stringify({roomId:t,text:n,targetBotIds:[...r].sort()});return e?.fingerprint===a?e:{fingerprint:a,key:i()}}function po(e,t,n){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)i--,a--;return n.flatMap(e=>{if(e.end<=r)return[e];if(e.start>=i){let t=a-i;return[{...e,start:e.start+t,end:e.end+t}]}return[]})}function mo(e,t){let n=e;for(let e of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e.start)+so(e.member)+n.slice(e.end);return{text:n,targets:[...new Set(t.map(e=>e.member.id))]}}function ho(e,t,n,r,i){let a=i.filter(i=>t===n?r===`Backspace`?t>i.start&&t<=i.end+ +(e[i.end]===` `):t>=i.start&&t<i.end:t<i.end&&n>i.start);return a.length?{start:Math.min(t,...a.map(e=>e.start)),end:Math.max(n,...a.map(e=>e.end))}:null}var go=new Map,_o=new Map;function vo(e,t){let n=_o.get(e);if(n)n(t);else{let n=go.get(e)??[];n.some(e=>e.id===t.id)||n.push(t),go.set(e,n)}window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{roomId:e}}))}function yo(e,t){_o.set(e,t);let n=go.get(e)??[];go.delete(e);for(let e of n)t(e);return()=>{_o.get(e)===t&&_o.delete(e)}}function bo(e,t,n){let r=`@${n.name}`,i=e.slice(0,t),a=`${i&&!/\s$/.test(i)?` `:``}${r} `;return{text:i+a+e.slice(t),cursor:t+a.length}}function xo({botIds:e,roomId:t}){let{locale:n}=Ue(),r=H(n),[i,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t,n;async function i(){t=new AbortController;try{let n=async e=>{let n=await fetch(Qe(q(`/api/device-center/${e}`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)throw Error(r?`无法加载群成员,请重试。`:`Could not load members. Try again.`);return n.json()},[i,a]=await Promise.all([n(`chat-status`),n(`bots`)]);if(!i.hubUrl||!Array.isArray(a.bots))throw Error(r?`设备绑定无效。`:`Invalid device binding.`);e||(o({hubUrl:i.hubUrl,deviceId:i.deviceId,bots:a.bots}),c(``))}catch(t){e||c(t instanceof Error?t.message:String(t))}finally{t.abort(),e||(n=setTimeout(i,15e3))}}return i(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[r]);async function d(e,t){if(i&&!l){u(!0);try{await wn(e.deviceId,i.hubUrl,t,r),c(``)}catch(e){c(e instanceof Error?e.message:String(e))}finally{u(!1)}}}return(0,$.jsxs)(`div`,{className:`dg-side-members`,children:[s&&(0,$.jsx)(`div`,{className:`dg-side-error`,role:`alert`,children:s}),!i&&!s&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:r?`加载中…`:`Loading…`}),e.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:r?`暂无成员`:`No members`}),i&&e.map(e=>{let n=i.bots.find(t=>t.id===e);return(0,$.jsxs)(`div`,{className:`dg-side-member`,children:[(0,$.jsxs)(`div`,{className:`dg-side-member-name`,title:n?.name||e,children:[(0,$.jsx)(`span`,{children:n?.name||e}),(0,$.jsx)(`small`,{children:n?.online?r?`在线`:`Online`:r?`离线`:`Offline`}),t&&n&&(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:r?`引用成员`:`Reference member`,"aria-label":`${r?`引用成员`:`Reference member`} · ${n.name}`,onClick:()=>vo(t,n),children:(0,$.jsx)(U,{"aria-hidden":!0})})]}),n?.deviceId&&i.deviceId&&n.deviceId!==i.deviceId&&(0,$.jsxs)(`div`,{className:`dg-side-member-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:l||!n?.deviceId,onClick:()=>n&&void d(n,!0),children:[(0,$.jsx)(st,{"aria-hidden":!0}),r?`远程桌面`:`Remote desktop`]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:l||!n?.deviceId,onClick:()=>n&&void d(n,!1),children:[(0,$.jsx)(a,{"aria-hidden":!0}),r?`访问设备`:`Open device`]})]})]},e)})]})}function So(e,t){let n=e.trim().replace(/\\/g,`/`);if(!n)return``;let r=/^(?:[a-z]:\/|\/)/i.test(n)?n:`${t.replace(/\\/g,`/`).replace(/\/$/,``)}/${n}`,i=r.match(/^(?:[a-z]:\/|\/\/[^/]+\/[^/]+\/?|\/)/i)?.[0];if(!i)return n;let a=[];for(let e of r.slice(i.length).split(`/`))e===`..`?a.pop():e&&e!==`.`&&a.push(e);return i.replace(/\/$/,``)+`/`+a.join(`/`)}function Co({cwd:e,onSelectCwd:t,onOpenProjectPicker:n,projects:r=[],workspaceRoots:i=[],pathCompletions:a=[],mode:o=`project`,baseCwd:s,onCreateProject:c,className:l=``,placeholder:d=`如 . 或 web 或绝对路径`,inputId:f,disabled:p=!1,commitOnBlur:m=!1,localOnly:h=!1,onPickerOpenChange:g}){let[_,v]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(e);(0,Q.useEffect)(()=>x(e),[e]);let[S,C]=(0,Q.useState)(!1),w=(0,Q.useRef)(null),T=V();(0,Q.useEffect)(()=>{let e=e=>{w.current&&!w.current.contains(e.target)&&v(!1)};if(_)return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[_]);let E=[{label:`. (当前项目根目录)`,value:`.`},{label:`web (前端目录)`,value:`web`},{label:`server (后端服务)`,value:`server`},{label:`tests (测试套件)`,value:`tests`},{label:`src (源码目录)`,value:`src`},{label:`docs (文档目录)`,value:`docs`}],D=()=>{C(!1),g?.(!1)},O=()=>{p||(n?n():(v(!1),C(!0),g?.(!0)))},k=e&&e!==`.`?e:s||e||`.`;return(0,$.jsxs)(`div`,{className:`universal-path-picker-root ${l}`,ref:w,children:[(0,$.jsxs)(`div`,{className:`universal-path-input-group`,children:[(0,$.jsx)(Be,{className:`universal-path-icon`}),(0,$.jsx)(`input`,{type:`text`,className:`universal-path-input`,value:m?b:e,id:f,disabled:p,onChange:e=>m?x(e.target.value):t(e.target.value),onBlur:()=>{m&&b!==e&&t(b)},onKeyDown:n=>{m&&n.key===`Enter`&&(n.preventDefault(),b!==e&&t(b))},placeholder:d,title:`工作目录: ${e||`.`}`}),(0,$.jsx)(`button`,{type:`button`,className:`universal-path-dropdown-toggle`,disabled:p,onClick:()=>v(!_),title:`选择推荐子目录或最近项目`,children:(0,$.jsx)(pe,{})})]}),(0,$.jsx)(ta,{className:`universal-path-browse-btn`,tip:T(`projectPickerTitle`),disabled:p,onClick:O,children:(0,$.jsx)(y,{})}),_&&(0,$.jsxs)(`div`,{className:`universal-path-menu`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[i.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`工作区根目录`}),i.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e),v(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e})},e))]}),(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`推荐子目录`}),E.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.value),v(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e.label})},e.value)),r.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`universal-path-menu-header`,children:[(0,$.jsx)(u,{}),` 最近项目`]}),r.slice(0,6).map(e=>{let n=e.path.split(/[/\\]/).filter(Boolean).pop()||e.path;return(0,$.jsxs)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.path),v(!1)},title:e.path,children:[(0,$.jsx)(`span`,{className:`path-title`,children:n}),(0,$.jsx)(`span`,{className:`path-sub`,children:e.path})]},e.path)})]})]}),!n&&S&&(0,$.jsx)(ba,{localOnly:h,open:!0,currentCwd:k,pathCompletions:a,workspaceRoots:i,onClose:D,onSelectDirectory:e=>{t(e),D()},onCreateProject:c?e=>{c(e),D()}:void 0,mode:o})]})}var wo=`pi-web-model-usage`;function To(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){let e=typeof r==`number`?Math.floor(r):0;Number.isFinite(e)&&e>0&&(t[n]=e)}return t}function Eo(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function Do(e,t){let n=t;return e.map((e,t)=>({m:e,i:t,count:n[e.id]??0})).sort((e,t)=>t.count-e.count||e.i-t.i).map(e=>e.m)}function Oo(){try{let e=localStorage.getItem(wo);return e?To(JSON.parse(e)):{}}catch{return{}}}function ko(e){try{localStorage.setItem(wo,JSON.stringify(e))}catch{}}function Ao(e){let t=Eo(Oo(),e);return ko(t),t}function jo(e,t){return t?t===e.id||`${e.provider}/${e.id}`===t||t.includes(`/`)&&t.split(`/`)[1]===e.id:!1}function Mo({models:e,modelsLoading:t=!1,providerKeys:n={},defaultModel:r,currentModelId:i,active:a,onEnsureModels:o,loading:s=!1,onRefresh:c,onManageModels:l,onPickModel:u,onToggleDefault:d,isRowActive:f,extraTopRow:p,listRef:m,autoFocusSearch:h=!1,hideTitle:g=!1,bodyStyle:_,scrollStyle:v}){let y=V(),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null),[w,E]=(0,Q.useState)({}),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(o);k.current=o,(0,Q.useEffect)(()=>{if(!a){x(``),C(null),O(!1);return}E(Oo()),k.current()},[a]);let A=(0,Q.useMemo)(()=>e.filter(e=>e.enabled!==!1).length,[e]),j=e.some(e=>e.enabled===!1),M=(0,Q.useMemo)(()=>!j||D?e:e.filter(e=>e.enabled!==!1||jo(e,i)),[e,j,D,i]),N=(0,Q.useMemo)(()=>{let e=b.trim().toLowerCase(),t=M;return S&&(t=t.filter(e=>e.provider===S.provider)),Do(e?t.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):t,w)},[M,b,S,w]),P=(0,Q.useMemo)(()=>{let e=new Map;for(let t of M)e.set(t.provider,(e.get(t.provider)??0)+1);let t=[];for(let[r,i]of[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))){let e=n[r];if(e&&e.length>1)for(let n of e)t.push({provider:r,count:i,keyName:n.name});else t.push({provider:r,count:i,keyName:null})}return t},[M,n]),ee=(0,Q.useMemo)(()=>{let e=[];for(let t of N){let r=null,a=n[t.provider];if(a&&a.length>1&&(r=a.find(e=>e.active)??a[0],S?.provider===t.provider&&S.keyName)){let e=a.find(e=>e.name===S.keyName);e&&(r=e)}let o=f?f(t,r):jo(t,i)&&(!r||r.active);e.push({model:t,key:r,active:o})}return e},[N,n,S,f,i]);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,children:[!g&&(0,$.jsx)(`span`,{className:`dd-header-title`,children:y(`availableModels`)}),(0,$.jsxs)(`div`,{className:`dd-header-actions`,style:g?{marginLeft:`auto`}:void 0,children:[!!r&&(0,$.jsxs)(`div`,{className:`dd-header-default`,title:`默认模型: ${r}`,children:[(0,$.jsx)(`span`,{className:`dd-header-default-star`,children:`★`}),(0,$.jsx)(`span`,{className:`dd-header-default-name`,children:r.includes(`/`)?r.split(`/`).slice(1).join(`/`):r}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-default-clear`,title:`清除全局默认模型`,onClick:e=>{e.stopPropagation(),Z({type:`clear_default_model`})},children:`✕`})]}),j&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-toggle ${D?`active`:``}`,onClick:()=>O(e=>!e),title:D?y(`showEnabledModelsTitle`,{n:A}):y(`showAllModelsTitle`,{n:e.length}),children:D?y(`showEnabledModels`,{n:A}):y(`showAllModels`,{n:e.length})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-refresh-btn`,onClick:c,title:y(`refreshModels`),"aria-label":y(`refreshModels`),children:(0,$.jsx)(te,{className:s||t?`spin`:``})}),l&&(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-manage-btn`,onClick:l,title:y(`manageModels`),"aria-label":y(`manageModels`),children:(0,$.jsx)(T,{})})]})]}),(0,$.jsxs)(`div`,{className:`dd-search-row`,children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`input`,{className:`dd-search`,type:`text`,autoFocus:h,placeholder:y(`searchModels`),value:b,onChange:e=>x(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`dd-model-body`,style:_,children:[P.length>1&&(0,$.jsxs)(`div`,{className:`dd-provider-col`,children:[(0,$.jsx)(`div`,{className:`dd-provider-head`,children:y(`providers`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-provider-item ${S===null?`active`:``}`,onClick:()=>C(null),children:(0,$.jsx)(`span`,{children:y(`allProviders`)})}),P.map(e=>{let t=S?.provider===e.provider&&S?.keyName===e.keyName;return(0,$.jsxs)(`button`,{type:`button`,className:`dd-provider-item ${t?`active`:``}`,onClick:()=>C(t?null:{provider:e.provider,keyName:e.keyName}),title:e.keyName?`${e.provider} · ${e.keyName}`:`${e.provider} · ${e.count}`,children:[(0,$.jsxs)(`span`,{className:`dd-provider-txt`,children:[(0,$.jsx)(`span`,{className:`dd-provider-name`,children:e.provider}),e.keyName&&(0,$.jsx)(`span`,{className:`dd-provider-key`,children:e.keyName})]}),(0,$.jsx)(`span`,{className:`dd-provider-count`,children:e.count})]},e.keyName?`${e.provider}::${e.keyName}`:e.provider)})]}),(0,$.jsxs)(`div`,{className:`dd-model-scroll`,ref:m,style:v,children:[(s||t)&&(0,$.jsx)(`div`,{className:`dd-loading`,children:y(`loading`)}),e.length===0&&!s&&!t&&(0,$.jsx)(`div`,{className:`dd-loading`,children:y(`noModels`)}),p,N.length===0&&M.length>0&&(0,$.jsxs)(`div`,{className:`dd-loading`,children:[(0,$.jsx)(`div`,{children:y(`noModelMatches`)}),j&&!D&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-switch-link`,onClick:()=>O(!0),children:y(`searchAllModelsHint`,{n:e.length})})]}),ee.map(e=>{let t=e.model,n=r!==void 0&&r===t.id;return(0,$.jsxs)(gt,{active:e.active,onClick:()=>u(t,e.key),children:[(0,$.jsxs)(`span`,{className:`dd-model-cell`,children:[(0,$.jsx)(`span`,{className:`dd-model-name`,children:t.name}),(0,$.jsxs)(`span`,{className:`dd-model-meta`,children:[(0,$.jsx)(`span`,{className:`dd-model-provider`,children:t.provider}),(0,$.jsx)(`span`,{className:`dd-model-id`,children:t.id.includes(`/`)?t.id.split(`/`).slice(1).join(`/`):t.id}),e.key&&(0,$.jsxs)(`span`,{className:`dd-model-key ${e.key.active?`active`:``}`,children:[e.key.active?`●`:`○`,` `,e.key.name]}),(w[t.id]??0)>0&&(0,$.jsx)(`span`,{className:`dd-model-usage`,children:y(`modelUsedCount`,{n:w[t.id]})}),(t.reasoning||t.vision||D&&t.enabled===!1)&&(0,$.jsxs)(`span`,{className:`dd-model-badges`,children:[t.reasoning&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:y(`reasoning`)}),t.vision&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:y(`vision`)}),D&&t.enabled===!1&&(0,$.jsx)(`span`,{className:`dd-model-badge out-of-scope`,children:y(`notInScopeBadge`)})]})]})]}),r!==void 0&&(d?(0,$.jsx)(`button`,{type:`button`,className:`dd-star-btn ${n?`active`:``}`,title:n?`当前全局默认模型(点击取消默认)`:`设为全局默认模型`,onClick:e=>{e.stopPropagation(),d(t,n)},children:n?`★`:`☆`}):(0,$.jsx)(`span`,{className:`dd-star-btn ${n?`active`:``}`,children:n?`★`:`☆`}))]},e.key?`${t.id}::${e.key.name}`:t.id)})]})]})]})}function No({title:e,entries:t,selected:n,onChange:r,disabled:i,pending:a}){let o=V(),s=(0,Q.useId)(),[c,l]=(0,Q.useState)(``),u=new Set(t.map(e=>e.id)),d=n.filter(e=>!u.has(e)),f=[...t,...d.map(e=>({id:e,name:e}))],p=c.trim().toLowerCase(),m=f.filter(e=>[e.name,e.id,e.description,e.path].some(e=>e?.toLowerCase().includes(p))),h=m.filter(e=>u.has(e.id)&&e.status!==`disabled`);return(0,$.jsxs)(`fieldset`,{className:`dc-bot-catalog`,disabled:i,children:[(0,$.jsxs)(`legend`,{children:[e,` `,(0,$.jsxs)(`span`,{className:`dc-bot-count`,children:[n.length,` `,o(`localBotSelected`)]})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-actions`,children:[(0,$.jsx)(`input`,{type:`search`,"aria-label":`${o(`localBotSearch`)} ${e}`,placeholder:o(`localBotSearch`),value:c,onChange:e=>l(e.target.value)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:a||!h.length,onClick:()=>r([...new Set([...n,...h.map(e=>e.id)])]),children:o(p?`localBotSelectVisible`:`localBotSelectAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:!n.length,onClick:()=>r([]),children:o(`localBotClear`)})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-list`,children:[m.map((e,t)=>(0,$.jsxs)(`label`,{className:`dc-bot-option`,htmlFor:`${s}-${t}`,children:[(0,$.jsx)(`input`,{id:`${s}-${t}`,type:`checkbox`,checked:n.includes(e.id),disabled:e.status===`disabled`&&!n.includes(e.id),onChange:t=>r(t.target.checked?[...new Set([...n,e.id])]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),!u.has(e.id)&&(0,$.jsx)(`small`,{children:o(a?`localBotUnverified`:`localBotUnavailable`)}),e.description&&(0,$.jsx)(`small`,{children:e.description}),e.status===`not_loaded`&&(0,$.jsx)(`small`,{children:o(`localBotMcpNotLoaded`)}),e.status===`disabled`&&(0,$.jsx)(`small`,{children:o(`localBotMcpDisabled`)}),e.source&&(0,$.jsx)(`small`,{children:e.source}),e.path&&(0,$.jsx)(`small`,{children:e.path})]})]},e.id)),!m.length&&(0,$.jsx)(`p`,{children:o(a?`localBotOptionsLoading`:`localBotNoOptions`)})]})]})}var Po=e=>e.id.startsWith(`${e.provider}/`)?e.id.slice(e.provider.length+1):e.id,Fo=()=>({name:``,description:``,systemPrompt:``,cwd:``,tools:[],skills:[],mcpServers:[],enabled:!0});async function Io(e,t,n){let r=await fetch(Qe(q(`/api/device-center/${e}`)),{method:n?`POST`:`GET`,credentials:`same-origin`,signal:t,...n?{headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}:{}}),i=await r.json();if(!r.ok)throw Error(i.error||String(r.status));return i}function Lo({pathCompletions:e=[],createOnly:t=!1,onCreated:n,onCancel:r}){let i=V(),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(()=>t?Fo():null),l=()=>{c(null),r?.()},[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(`identity`),O=(0,Q.useRef)(null),k=(0,Q.useRef)(``),A=(0,Q.useRef)(null),j=s!==null;(0,Q.useEffect)(()=>{if(!j)return;let e=A.current,t=document.activeElement,n=document.body.style.overflow;return document.body.style.overflow=`hidden`,D(`identity`),e?.showModal?.(),()=>{e?.close?.(),document.body.style.overflow=n,t?.focus()}},[j]),(0,Q.useEffect)(()=>{let e=new AbortController;return Io(`local-bots`,e.signal).then(t=>{if(!e.signal.aborted){if(!Array.isArray(t.bots))throw Error(`Invalid Bot list`);o(t.bots)}}).catch(t=>{e.signal.aborted||p(String(t))}),()=>{e.abort(),O.current?.abort()}},[]);let M=s?.cwd;(0,Q.useEffect)(()=>{if(M===void 0)return;let e=new AbortController;return x(!0),y(``),_(null),Io(M?`local-bot-options?cwd=${encodeURIComponent(M)}`:`local-bot-options`,e.signal).then(t=>{if(!e.signal.aborted){if(![t.models,t.tools,t.skills,t.mcpServers,t.projects].every(Array.isArray)||!t.defaultCwd||!t.cwd)throw Error(i(`localBotOptionsInvalid`));k.current=t.defaultCwd,_(t),M||c(e=>e&&!e.cwd?{...e,cwd:t.cwd}:e)}}).catch(t=>{e.signal.aborted||y(String(t))}).finally(()=>{e.signal.aborted||x(!1)}),()=>e.abort()},[M,S]),(0,Q.useEffect)(()=>{if(!w)return;let e=e=>{e.key===`Escape`&&T(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[w]);async function N(e=!1){if(!s||u)return;let t=new AbortController;O.current=t,d(!0),p(``),h(``);try{let r=await Io(e?`local-bots/${encodeURIComponent(s.id)}/delete`:`local-bots`,t.signal,e?{revision:s.revision}:s);if(t.signal.aborted)return;o(t=>e?t.filter(e=>e.id!==s.id):[...t.filter(e=>e.id!==r.bot.id),r.bot]),c(null),T(!1),h(r.synced===!1?i(`localBotSyncFailed`):i(`localBotSaved`)),e||n?.(r.bot,r.synced!==!1)}catch(e){t.signal.aborted||p(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||d(!1)}}let P=g?.models.find(e=>e.provider===s?.model?.provider&&Po(e)===s?.model?.modelId);return(0,$.jsxs)(`section`,{className:`dc-card dc-bots${t?` is-create-only`:``}`,"aria-label":i(`localBotTitle`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h2`,{children:i(`localBotTitle`)}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:u,onClick:()=>{c(Fo()),p(``),T(!1)},children:i(`localBotCreate`)})]}),(0,$.jsx)(`p`,{children:i(`localBotHint`)}),f&&!s&&(0,$.jsx)(`p`,{role:`alert`,children:f}),m&&(0,$.jsx)(`p`,{role:`status`,children:m}),(0,$.jsxs)(`div`,{className:`dc-bot-workspace${s?` is-editing`:``}`,children:[(0,$.jsx)(`div`,{className:`dc-bot-list`,"aria-label":i(`localBotTitle`),children:a.map(e=>(0,$.jsxs)(`button`,{className:`dc-button dc-bot-item${s?.id===e.id?` is-selected`:``}`,"aria-pressed":s?.id===e.id,disabled:u,onClick:()=>{c(structuredClone(e)),p(``),T(!1)},children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:e.name.slice(0,2).toUpperCase()}),(0,$.jsxs)(`span`,{className:`dc-bot-item-copy`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsxs)(`small`,{className:e.enabled?`is-enabled`:``,children:[e.enabled?i(`localBotEnabled`):i(`localBotDisabled`),` · r`,e.revision]})]})]},e.id))}),s&&(0,$.jsx)(`dialog`,{ref:A,className:`dc-bot-drawer`,"aria-label":i(`localBotTitle`),onCancel:e=>{e.preventDefault(),!u&&!w&&l()},onClick:e=>{if(e.target!==e.currentTarget||u)return;let t=e.currentTarget.getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&l()},children:(0,$.jsxs)(`form`,{className:`dc-bot-editor`,onSubmit:e=>{e.preventDefault(),N()},children:[(0,$.jsxs)(`header`,{className:`dc-bot-editor-head`,children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:s.name.slice(0,2).toUpperCase()||`B`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{children:s.name||i(`localBotCreate`)}),s.id&&(0,$.jsxs)(`small`,{children:[s.id,` · r`,s.revision]})]}),(0,$.jsxs)(`label`,{className:`dc-bot-enabled`,children:[(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,disabled:u,checked:s.enabled,onChange:e=>c({...s,enabled:e.target.checked})}),i(`localBotEnable`)]}),(0,$.jsx)(`button`,{className:`dc-button dc-bot-drawer-close`,type:`button`,"aria-label":i(`localBotCancel`),disabled:u,onClick:l,children:`×`})]}),(0,$.jsx)(`div`,{className:`dc-bot-tabs`,role:`tablist`,"aria-label":i(`localBotTitle`),children:[[`identity`,i(`localBotIdentity`)],[`runtime`,i(`localBotRuntime`)],[`permissions`,i(`localBotPermissions`)]].map(([e,t],n,r)=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,id:`bot-tab-${e}`,"aria-controls":`bot-panel-${e}`,"aria-selected":E===e,tabIndex:E===e?0:-1,onClick:()=>D(e),onKeyDown:e=>{let t=n;if(e.key===`ArrowRight`)t=(n+1)%r.length;else if(e.key===`ArrowLeft`)t=(n+r.length-1)%r.length;else if(e.key===`Home`)t=0;else if(e.key===`End`)t=r.length-1;else return;e.preventDefault(),D(r[t][0]),document.getElementById(`bot-tab-${r[t][0]}`)?.focus()},children:t},e))}),(0,$.jsxs)(`div`,{className:`dc-bot-editor-body`,children:[f&&(0,$.jsx)(`p`,{className:`dc-bot-error`,role:`alert`,children:f}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-identity`,"aria-labelledby":`bot-tab-identity`,hidden:E!==`identity`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotIdentityHint`)}),(0,$.jsxs)(`fieldset`,{className:`dc-bot-section`,disabled:u,children:[(0,$.jsx)(`legend`,{children:i(`localBotIdentity`)}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotName`),(0,$.jsx)(`input`,{required:!0,value:s.name,onChange:e=>c({...s,name:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotDescription`),(0,$.jsx)(`textarea`,{rows:2,value:s.description,onChange:e=>c({...s,description:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotSystemPrompt`),(0,$.jsx)(`textarea`,{rows:9,className:`dc-bot-prompt`,spellCheck:!1,value:s.systemPrompt,onChange:e=>c({...s,systemPrompt:e.target.value})})]})]}),(0,$.jsx)(`p`,{className:`dc-bot-local-note`,children:i(`localBotPrivatePrompt`)})]}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-runtime`,"aria-labelledby":`bot-tab-runtime`,hidden:E!==`runtime`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotRuntimeHint`)}),(0,$.jsxs)(`fieldset`,{className:`dc-bot-section`,disabled:u,children:[(0,$.jsx)(`legend`,{children:i(`localBotRuntime`)}),(0,$.jsxs)(`div`,{className:`dc-field`,children:[(0,$.jsx)(`label`,{htmlFor:`local-bot-cwd`,children:i(`localBotCwd`)}),(0,$.jsx)(Co,{inputId:`local-bot-cwd`,localOnly:!0,commitOnBlur:!0,pathCompletions:e,cwd:s.cwd,baseCwd:k.current||s.cwd,projects:g?.projects.map(e=>({...e,lastUsed:0}))??[],disabled:u,onSelectCwd:e=>c({...s,cwd:So(e,k.current||s.cwd)})})]}),(0,$.jsxs)(`div`,{className:`dc-field`,children:[(0,$.jsx)(`span`,{children:i(`localBotModel`)}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,"aria-haspopup":`dialog`,onClick:()=>T(!0),children:s.model?P?.name??`${s.model.provider}/${s.model.modelId}`:i(`localBotInheritModel`)}),s.model&&(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,onClick:()=>c({...s,model:void 0}),children:i(`localBotInheritModel`)})]}),s.model&&!P&&(0,$.jsx)(`small`,{children:i(b?`localBotUnverified`:`localBotUnavailable`)})]})]})]}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-permissions`,"aria-labelledby":`bot-tab-permissions`,hidden:E!==`permissions`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotPermissionsHint`)}),(0,$.jsxs)(`div`,{className:`dc-bot-options-status`,"aria-live":`polite`,children:[b&&(0,$.jsx)(`span`,{children:i(`localBotOptionsLoading`)}),v&&(0,$.jsx)(`span`,{role:`alert`,children:v}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:b||u,onClick:()=>C(e=>e+1),children:i(v?`deviceHubRetry`:`localBotReload`)})]}),(0,$.jsx)(`div`,{className:`dc-bot-permissions`,children:[[`tools`,i(`localBotTools`)],[`skills`,i(`localBotSkills`)],[`mcpServers`,i(`localBotMcpServers`)]].map(([e,t])=>(0,$.jsx)(No,{title:t,entries:g?.[e]??[],selected:s[e],disabled:u,pending:b||!!v,onChange:t=>c({...s,[e]:t})},e))})]})]}),(0,$.jsxs)(`footer`,{className:`dc-actions dc-bot-editor-footer`,children:[(0,$.jsx)(`button`,{className:`dc-button dc-bot-save`,disabled:u||!s.cwd||!s.name.trim(),children:i(`localBotSave`)}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:u,onClick:()=>{l(),T(!1)},children:i(`localBotCancel`)}),s.id&&(0,$.jsx)(`button`,{className:`dc-button is-danger`,type:`button`,disabled:u,onClick:()=>{window.confirm(i(`localBotDeleteConfirm`))&&N(!0)},children:i(`localBotDelete`)})]})]})})]}),s&&w&&(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop dc-bot-model-backdrop`,onClick:e=>{e.target===e.currentTarget&&T(!1)},children:(0,$.jsxs)(`div`,{className:`dc-bot-model-modal dd-menu-model`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`localBotModel`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h3`,{children:i(`localBotModel`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>T(!1),children:i(`localBotCancel`)})]}),(0,$.jsx)(Mo,{models:g?.models??[],modelsLoading:b,defaultModel:g?.defaultModel,currentModelId:s.model?`${s.model.provider}/${s.model.modelId}`:null,active:!0,onEnsureModels:()=>{},onRefresh:()=>C(e=>e+1),onPickModel:e=>{c({...s,model:{provider:e.provider,modelId:Po(e)}}),T(!1)},isRowActive:e=>e.provider===s.model?.provider&&Po(e)===s.model.modelId,extraTopRow:(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>{c({...s,model:void 0}),T(!1)},children:i(`localBotInheritModel`)}),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{overflowY:`auto`,minHeight:0}}),v&&(0,$.jsx)(`p`,{role:`alert`,children:v})]})}),A.current??document.body)]})}function Ro({room:e,onClose:t}){let{locale:n}=Ue(),r=H(n),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(e.botIds),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!0),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(0),b=(0,Q.useRef)(null),x=()=>{!m&&!u&&t()};mt(x),(0,Q.useEffect)(()=>()=>b.current?.abort(),[]),(0,Q.useEffect)(()=>{let t=new AbortController;return p(!0),Promise.all([Ho(`bots`,t.signal),Ho(`rooms/${encodeURIComponent(e.id)}`,t.signal)]).then(([e,n])=>{t.signal.aborted||(a(e.bots),s(n.room.botIds))}).catch(e=>{t.signal.aborted||_(e instanceof Error?e.message:String(e))}).finally(()=>{t.signal.aborted||p(!1)}),()=>t.abort()},[e.id,v]);async function S(n){if(b.current)return;let r=new AbortController;b.current=r,h(!0),_(``);try{let i=`rooms/${encodeURIComponent(e.id)}`,a=await Ho(i,r.signal);if(r.signal.aborted||(await Ho(`${i}/members`,r.signal,{botIds:[...new Set([...a.room.botIds,...n])]}),r.signal.aborted))return;window.dispatchEvent(new CustomEvent(zo)),t()}catch(e){r.signal.aborted||_(e instanceof Error?e.message:String(e))}finally{b.current=null,r.signal.aborted||h(!1)}}return(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:x,children:(0,$.jsxs)(`div`,{className:`device-group-bot-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":r?`添加或新建 Bot`:`Add or create Bot`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsxs)(`h2`,{children:[r?`添加 Bot`:`Add Bot`,` · `,e.name]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:m||u,onClick:x,children:r?`关闭`:`Close`})]}),g&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:g}),(0,$.jsx)(`p`,{children:r?`选择已有 Bot 加入群组,或在本机新建 Bot。`:`Add existing Bots to this group or create a Bot on this computer.`}),f?(0,$.jsx)(`p`,{children:r?`加载中…`:`Loading…`}):(0,$.jsxs)(`div`,{className:`dg-bot-choices`,children:[i.filter(e=>e.enabled&&!o.includes(e.id)).map(e=>(0,$.jsxs)(`label`,{className:`dg-bot-choice`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:m||u,checked:c.includes(e.id),onChange:t=>l(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[e.name,e.deviceName&&(0,$.jsx)(`small`,{children:e.deviceName})]})]},e.id)),!i.some(e=>e.enabled&&!o.includes(e.id))&&(0,$.jsx)(`p`,{children:r?`没有可添加的 Bot,可以新建一个。`:`No Bots available to add. Create a new one.`})]}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:m||u,onClick:()=>{d(!0),_(``)},children:r?`新建 Bot`:`Create Bot`}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:f||m||u||!c.length,onClick:()=>void S(c),children:m?r?`正在添加…`:`Adding…`:r?`添加到群组`:`Add to group`})]}),u&&(0,$.jsx)(Lo,{createOnly:!0,onCancel:()=>d(!1),onCreated:(e,t)=>{if(d(!1),y(e=>e+1),!t||!e.enabled){_(r?`Bot 已保存;请启用并同步到中心后,再添加到群组。`:`Bot saved. Enable and sync it to the hub before adding it to the group.`);return}S([e.id])}})]})}),document.body)}var zo=`pi-web-ui:device-groups-changed`,Bo={zh:{groups:`群组`,create:`建群`,rename:`重命名`,members:`管理成员`,delete:`删除群组`,save:`保存`,cancel:`取消`,empty:`还没有群组`,loading:`加载中…`,expand:`展开群组`,collapse:`折叠群组`,bind:`请先在设备设置中绑定本机,旧版绑定请重新绑定。`,settings:`打开设备中心`,failed:`群组请求失败,请重试。`,retry:`重试`,forbidden:`无法访问群组,请检查本机访问权限。`,running:`群内仍有排队或运行中的任务,请等待任务结束后再操作。`,confirm:`确定删除群组“{name}”?`,name:`群名称`},en:{groups:`Groups`,create:`Create group`,rename:`Rename`,members:`Manage members`,delete:`Delete group`,save:`Save`,cancel:`Cancel`,empty:`No groups yet`,loading:`Loading…`,expand:`Expand groups`,collapse:`Collapse groups`,bind:`Bind this computer in device settings first. Older bindings must be renewed.`,settings:`Open device center`,failed:`Group request failed. Please retry.`,retry:`Retry`,forbidden:`Group access denied. Check local access permissions.`,running:`This group has queued or running tasks. Wait for them to finish before making this change.`,confirm:`Delete group “{name}”?`,name:`Group name`}},Vo=class extends Error{status;code;constructor(e,t){super(`Device group request failed (${e})`),this.status=e,this.code=t}};async function Ho(e,t,n){let r=await fetch(Qe(q(`/api/device-center/${e}`)),{signal:AbortSignal.any([t,AbortSignal.timeout(15e3)]),...n===void 0?{}:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}}),i=await r.json().catch(()=>({}));if(!r.ok)throw new Vo(r.status,typeof i?.code==`string`?i.code:``);return i}function Uo(e){return e instanceof Vo?[`NOT_PAIRED`,`REPAIR_REQUIRED`,`DEVICE_CHANGED`].includes(e.code)?`bind`:[`ROOM_BUSY`,`ROOM_RUNNING`,`TASKS_RUNNING`,`ACTIVE_TASKS`].includes(e.code)?`running`:e.status===403?`forbidden`:`failed`:`failed`}function Wo(e,t,n){let r,i=0,a=!1,o=!1,s=()=>{if(o)return;let c=++i;if(r){a=!0;return}let l=new AbortController;r=l,e(l.signal).then(e=>{!o&&c===i&&t(e)},e=>{!o&&c===i&&!l.signal.aborted&&n(e)}).finally(()=>{r=void 0,a&&!o&&(a=!1,s())})};return{refresh:s,pause:()=>{i++,a=!1,r?.abort()},stop:()=>{o=!0,i++,a=!1,r?.abort()}}}function Go(e){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:e}))}function Ko({active:e=!0,selectedRoomId:t,flex:n,onCollapsedChange:r}){let{locale:i}=Ue(),a=Bo[H(i)?`zh`:`en`],[o,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>r?.(o),[o,r]);let[p,m]=(0,Q.useState)([]),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(!0),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(null),O=(0,Q.useRef)(null),k=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(k.current=!0,()=>{k.current=!1,O.current?.abort()}),[]),(0,Q.useEffect)(()=>{if(!e)return;let t=!1,n=Wo(async e=>{let n=await Ho(`chat-status`,e);if(t=!!(n.hubUrl&&n.deviceId),!t)return[];let r=await Ho(`rooms`,e);if(!Array.isArray(r.rooms))throw Error(`Invalid rooms response`);return r.rooms},e=>{g(t),m(e),b(null),v(!1)},e=>{b(Uo(e)),v(!1)});D.current=n;let r=()=>{document.hidden||n.refresh()},i=()=>{document.hidden?n.pause():r()};r();let a=window.setInterval(r,15e3);return window.addEventListener(zo,r),document.addEventListener(`visibilitychange`,i),()=>{n.stop(),D.current=null,window.clearInterval(a),window.removeEventListener(zo,r),document.removeEventListener(`visibilitychange`,i)}},[e]);let A=async(e,t)=>{if(O.current||t===`delete`&&!window.confirm(a.confirm.replace(`{name}`,e.name)))return;let n=new AbortController;O.current=n,E(!0),b(null);try{if(await Ho(`rooms/${encodeURIComponent(e.id)}/${t}`,n.signal,t===`rename`?{name:C.trim()}:{}),!k.current||n.signal.aborted)return;S(null),window.dispatchEvent(new CustomEvent(zo))}catch(e){k.current&&!n.signal.aborted&&b(Uo(e))}finally{O.current=null,k.current&&E(!1)}},j=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=[`rename`,`members`,`delete`].map((e,t)=>({id:`host:device-group-${e}`,slot:`contextmenu.project`,source:`host`,label:a[e],kind:`action`,action:e,order:t,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.id,kind:`device-group`,label:t.name},entries:n,onHostAction:e=>{O.current||(e.action===`rename`?(S(t.id),w(t.name)):e.action===`members`?Go({roomId:t.id,manage:!0}):e.action===`delete`&&A(t,`delete`))}})};return h===!1||h===null&&_?null:(0,$.jsxs)(`section`,{className:`lp-section dg-side-section ${o?`collapsed`:``}`,"aria-label":a.groups,style:!o&&n!==void 0?{flex:`${n} 1 0px`}:void 0,children:[(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,"aria-expanded":!o,title:o?a.expand:a.collapse,onClick:()=>c(!o),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[a.groups,` (`,p.length,`)`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:o?(0,$.jsx)(pe,{}):(0,$.jsx)(s,{})})]}),(0,$.jsx)(`div`,{className:`lp-section-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action`,title:a.create,"aria-label":a.create,onClick:()=>Go({create:!0}),children:(0,$.jsx)(rt,{})})})]}),!o&&(0,$.jsxs)(`div`,{className:`lp-section-body dg-side-body`,children:[y&&(0,$.jsxs)(`div`,{className:`dg-side-error`,role:`status`,children:[a[y],y===`bind`?(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>Go({}),children:a.settings}):(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>D.current?.refresh(),children:a.retry})]}),!y&&p.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:_?a.loading:a.empty}),p.map(e=>(0,$.jsxs)(`div`,{className:`dg-side-item`,children:[(0,$.jsxs)(`div`,{className:`dg-side-heading`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-expanded":d.has(e.id),"aria-label":`${e.name} · ${H(i)?`成员`:`Members`}`,onClick:()=>f(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:d.has(e.id)?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})}),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`dg-side-row${t===e.id?` is-selected`:``}`,"aria-current":t===e.id?`page`:void 0,title:e.name,onClick:()=>Go({roomId:e.id}),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Go({roomId:e.id}))},onContextMenu:t=>j(t,e),children:[(0,$.jsx)(Ve,{}),(0,$.jsx)(`span`,{className:`dg-side-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-label":`${e.name} · ${H(i)?`添加 Bot`:`Add Bot`}`,title:H(i)?`添加或新建 Bot`:`Add or create Bot`,onClick:()=>u(e),children:(0,$.jsx)(rt,{})})]}),d.has(e.id)&&(0,$.jsx)(xo,{botIds:e.botIds,roomId:e.id}),x===e.id&&(0,$.jsxs)(`form`,{className:`dg-side-rename`,onSubmit:t=>{t.preventDefault(),C.trim()&&A(e,`rename`)},children:[(0,$.jsx)(`input`,{className:`dc-input`,"aria-label":a.name,value:C,maxLength:120,autoFocus:!0,disabled:T,onChange:e=>w(e.target.value),onKeyDown:e=>{e.key===`Escape`&&S(null)}}),(0,$.jsx)(`button`,{type:`submit`,className:`dc-button`,disabled:T||!C.trim(),children:a.save}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:T,onClick:()=>S(null),children:a.cancel})]})]},e.id))]}),l&&(0,$.jsx)(Ro,{room:l,onClose:()=>u(null)})]})}function qo(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(r&&typeof r==`object`&&!Array.isArray(r))for(let e of Object.keys(t)){let t=r[e];typeof t==`number`&&Number.isFinite(t)&&t>0&&(n[e]=t)}}catch{}return n}function Jo(e){let t=e.start.above+e.start.below,n=Math.max(1,e.availablePx)/(e.totalWeight>0?e.totalWeight:1),r=e.minAbovePx/n,i=e.minBelowPx/n;if(r+i>=t){let n=e.minAbovePx+e.minBelowPx||1,r=t*e.minAbovePx/n;return{above:r,below:t-r}}let a=Math.min(t-i,Math.max(r,e.start.above+e.deltaPx/n));return{above:a,below:t-a}}function Yo(e,t,n){let r=new Map(e.map(e=>[e.id,e])),i=e=>e.parentId?r.get(e.parentId)?.cwd??e.cwd:e.cwd,a=e.find(e=>e.id===n),o=a?i(a):t,s=new Map;for(let t of e){let e=i(t),n=s.get(e)??[];n.push(t),s.set(e,n)}let c=[...s.entries()].map(([e,t])=>({cwd:e,isCurrent:e===o,convs:t}));return c.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:e.cwd<t.cwd?-1:+(e.cwd>t.cwd)),c}function Xo(e,t=new Set){let n=new Map(e.map(e=>[e.id,e])),r=new Map,i=[];for(let t of e)if(t.parentId&&n.has(t.parentId)){let e=r.get(t.parentId)??[];e.push(t),r.set(t.parentId,e)}else i.push(t);let a=e=>{let t=[],n=[...r.get(e)??[]],i=new Set;for(;n.length>0;){let e=n.shift();if(i.has(e.id))continue;i.add(e.id),t.push(e);let a=r.get(e.id);a&&n.push(...a)}return t},o=[],s=new Set,c=new Set,l=(e,n)=>{if(s.has(e.id)||c.has(e.id))return;s.add(e.id);let i=r.get(e.id)??[],u=i.length>0,d=u&&t.has(e.id),f=0,p=!1,m=!1,h=!1;if(u){let t=a(e.id);if(f=t.length,p=t.some(e=>e.isStreaming),m=t.some(e=>!!e.error),h=t.some(e=>!!e.hasQuestion),d)for(let e of t)c.add(e.id)}if(o.push({c:e,depth:n,hasKids:u,isCollapsed:d,descendantCount:f,hasStreaming:p,hasError:m,hasQuestion:h}),!d)for(let e of i)l(e,n+1)};for(let e of i)l(e,0);for(let t of e)l(t,0);return o}function Zo({className:e,width:t=`1em`,height:n=`1em`,...r}){let i=[`half-ring-spin`,e].filter(Boolean).join(` `);return(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,width:t,height:n,className:i,"aria-hidden":`true`,...r,children:(0,$.jsx)(`path`,{d:`M 12 2 A 10 10 0 0 1 12 22`})})}function Qo(e){if(!e)return null;let t=e.startsWith(`#`)?e.slice(1):e;if(!t.trim())return null;let n=new URLSearchParams(t),r=n.get(`s`)?.trim()??``;if(!r)return null;let i=n.get(`m`)?.trim()||void 0;return i?{sessionId:r,messageId:i}:{sessionId:r}}function $o(e){let t=e?.sessionId?.trim()??``;if(!t)return``;let n=e?.messageId?.trim()??``,r=`#s=${encodeURIComponent(t)}`;return n?`${r}&m=${encodeURIComponent(n)}`:r}function es(e,t){let n=$o(t);try{let t=new URL(e);return t.searchParams.delete(`token`),t.hash=n,t.toString()}catch{return`${e.split(`#`)[0]??e}${n}`}}function ts(e){if(!e)return null;let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);if(!t)return null;let n=t.split(`/`),r=n[n.length-1]??``;if(!r)return null;if(r===`session.jsonl`)return(n[n.length-2]?.trim()??``)||null;let i=r.endsWith(`.jsonl`)?r.slice(0,-6):r;if(!i)return null;let a=i.lastIndexOf(`_`);return(a>=0?i.slice(a+1).trim():i.trim())||null}function ns(e,t){let n=t?.trim()??``;if(!n||e.length===0)return null;let r=e.find(e=>e.id===n);if(r)return r.id;let i=/^([a-z]+-\d+)-\d+$/.exec(n);if(i){let t=`${i[1]}-`,n=e.find(e=>e.id.startsWith(t));if(n)return n.id}return null}function rs(e,t,n,r,i){return e.find(e=>t(e)===n)??e.find(e=>!r.has(t(e))&&i(e))}function is(e,t,n){if(n)return e.filter(e=>e.id!==n);if(!t)return e;let r=e.findIndex(e=>e.id===t.id);return r<0?[...e,t]:e.map((e,n)=>n===r?t:e)}var as=`pi:canvas-list-result`,os=new Set([`canvas`,`canvases`,`画布`,`工作流`,`workflow`,`workflows`]);function ss(e,t,n,r=10){let i=t.toLowerCase();return e.filter(e=>!i||os.has(i)||e.name.toLowerCase().includes(i)||e.id.toLowerCase().includes(i)).slice(0,Math.max(0,r)).map(e=>({providerId:`host:canvases`,providerLabel:n,title:`${n} · ${e.name}`,text:e.name,hint:e.id,attachments:[{path:e.id,name:e.name,mode:`canvas`}]}))}function cs(e,t=1800){return new Promise(n=>{let r=e=>{clearTimeout(a),window.removeEventListener(as,i),n(e)},i=e=>{let t=e.detail;r(t.graphs)},a=setTimeout(()=>r([]),t);window.addEventListener(as,i);try{e()||r([])}catch{r([])}})}function ls(){let e=new Map,t=new Map,n=(e,t,n)=>JSON.stringify([n??`legacy`,n===`client`?``:e,t]),r=(e,t)=>[...e].filter(e=>{let[n,,r]=JSON.parse(e);return n===`legacy`&&r===t}),i=(e,t,n)=>{try{if(n){if(!e.reset)return;e.reset()}e.write(t)}catch{}};return{write(a,o,s,c=!1,l){let u=n(a,o,l),d=l||e.get(u)?.size?[u]:r(e.keys(),o);for(let t of d)for(let n of e.get(t)??[])i(n,s,c);let f=t.get(u)??(l?void 0:t.get(r(t.keys(),o)[0]));if(!l)for(let e of r(t.keys(),o))t.delete(e);t.set(u,{data:(c?s:(f?.data??``)+s).slice(-2e5),reset:c||(f?.reset??!1)})},register(a,o,s,c){let l=n(a,o,c),u=e.get(l);u||e.set(l,u=new Set),u.add(s);let d=t.get(l)??(c?void 0:t.get(r(t.keys(),o)[0]));return d&&i(s,d.data,d.reset),()=>{let t=e.get(l);t?.delete(s),t?.size||e.delete(l)}},reconcile(e,r){let i=new Set(r.map(t=>n(e,t.id,t.ownerKind??`client`)));for(let n of t.keys()){let[r,a]=JSON.parse(n);(r===`client`||a===e)&&!i.has(n)&&t.delete(n)}},clear(){t.clear()}}}function us(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.text!=`string`||!t.text.trim()||typeof t.messageId!=`string`||!t.messageId||typeof t.role!=`string`||!t.role?null:{text:t.text,messageId:t.messageId,role:t.role,...typeof t.sessionId==`string`&&t.sessionId?{sessionId:t.sessionId}:{}}}function ds(e){return`<quoted-text>\n${JSON.stringify(e)}\n</quoted-text>`}function fs(e){let t=/^<quoted-text>\n([^\n]*)\n<\/quoted-text>$/.exec(e);if(!t)return null;try{return us(JSON.parse(t[1]))}catch{return null}}function ps(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function ms(e,t=[],n=[],r=[]){let i=[],a=(e??``).trim();a&&i.push(a);for(let e of r)e&&i.push(`<attached-image name="${ps(e)}" />`);for(let e of t){let t=(e??``).trim();t&&i.push(t)}for(let e of n)i.push(ds(e));return i.join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./math-1uRJCsA9.js","./rolldown-runtime-hePW80VL.js","./markdown-BggnuQ4H.js","./react-CR5VJ85Q.js","./markdown-C8LL_u4z.css","./math-BorAY7qD.css","./TerminalPanel-Da-Xs4Wk.js","./fi-NyN-ZrgD.js","./uuid-BzDIGCwP.js","./theme-D2DMH6tH.js","./app-globals-DcyO0UPi.js","./xterm-Cf5xxe4g.js","./xterm-B1njb2Cr.css","./SCMPanel-CghgsyBN.js","./DeviceCenter-Bmgr-Bwm.js","./DeviceGroups-aeLD2msl.js","./shortcut-stack-hhrDyRBn.js","./CanvasStudio-DxW7C3Sz.js","./plugin-host-BCnX3P8U.js","./desktop-7EvUHhKQ.js","./es-DWMIuDU2.js","./PiSetupModal-DD8srwBJ.js","./ProviderOAuthControls-C6tfXb88.js","./ModelConfigModal-Bp7tfKYh.js","./SettingsModal-BbBe2rYo.js","./BgTasksModal-DSC8ncW3.js","./TuiOverlayModal-CpBKjG6x.js","./GlobalSearchModal-CMW0xz0P.js","./FilePreview-CJa27G_Q.js","./GroupConversation-DoELa83U.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,$t as n,A as r,At as i,B as a,Bt as o,C as s,D as c,Dt as l,E as u,Et as d,F as f,G as p,Gt as m,H as h,Ht as g,I as _,It as v,J as y,Jt as b,K as x,L as S,Lt as C,M as w,Mt as T,N as E,O as D,Ot as O,P as k,Pt as A,Q as j,R as M,Rt as N,S as P,St as ee,T as F,Tt as te,U as ne,Ut as re,V as I,Vt as L,W as ie,Wt as ae,X as oe,Xt as se,Y as ce,Yt as R,Z as le,Zt as ue,_ as z,_t as de,a as B,an as V,at as fe,b as pe,bt as me,c as he,cn as H,ct as ge,d as U,dn as W,dt as G,en as _e,et as K,fn as q,ft as J,g as ve,gt as Y,h as ye,ht as be,i as xe,in as Se,j as Ce,jt as we,k as Te,kt as Ee,l as De,ln as X,lt as Oe,m as ke,mt as Ae,n as je,nn as Me,nt as Ne,o as Pe,on as Fe,ot as Ie,p as Le,pn as Re,pt as ze,q as Be,qt as Ve,r as He,rn as Ue,rt as We,s as Ge,sn as Ke,st as qe,t as Je,tn as Ye,tt as Xe,u as Ze,un as Qe,ut as $e,v as et,vt as tt,w as nt,wt as rt,x as it,xt as at,y as ot,yt as st,z as ct,zt as lt}from"./fi-NyN-ZrgD.js";import{i as ut,n as dt,r as ft,t as pt}from"./react-CR5VJ85Q.js";import{t as mt}from"./shortcut-stack-hhrDyRBn.js";import{t as ht}from"./uuid-BzDIGCwP.js";import{n as gt,t as _t}from"./Dropdown-D1Jl35dw.js";import{a as vt,i as yt,n as bt,t as xt}from"./theme-D2DMH6tH.js";import{i as St,n as Ct,r as wt,t as Tt}from"./desktop-7EvUHhKQ.js";import{A as Et,C as Dt,D as Ot,E as kt,O as At,S as jt,T as Mt,_ as Nt,a as Pt,b as Ft,c as It,g as Lt,h as Rt,i as zt,k as Bt,l as Vt,m as Ht,n as Ut,o as Wt,r as Gt,t as Kt,u as qt,v as Jt,w as Yt,x as Xt,y as Zt}from"./plugin-host-BCnX3P8U.js";import{a as Qt,c as $t,i as en,l as tn,n as nn,o as rn,r as an,s as on,t as Z,u as sn}from"./app-globals-DcyO0UPi.js";import{a as cn,c as ln,d as un,h as dn,l as fn,m as pn,s as mn,t as hn,u as gn}from"./markdown-BggnuQ4H.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function _n(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.get(String(t))??null},key(t){return[...e.keys()][Number(t)>>>0]??null},removeItem(t){e.delete(String(t))},setItem(t,n){e.set(String(t),String(n))}}}function vn(e){let t=Re(e.location.pathname);if(!t)return!1;let n=!1;for(let t of[`localStorage`,`sessionStorage`])try{e[t]}catch{n=!0,Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:_n()})}if(!n)return!1;let r=e.fetch;return e.fetch=(n,i)=>{let a=typeof n==`string`?n:n instanceof URL?n.href:n.url,o=new URL(a,e.document.baseURI||e.location.href);return o.origin===e.location.origin&&o.pathname.startsWith(t)?r.call(e,n,{...i,credentials:`omit`}):r.call(e,n,i)},!0}var yn=typeof window<`u`&&vn(window),bn=ft(),xn=dt(),Q=e(ut(),1);function Sn(e,t,n,r={}){let{align:i=`right`,side:a=`bottom`,gap:o=6,margin:s=8}=r,c=t.width,l=t.height,u=Math.max(0,n.width-c-s),d=Math.max(0,n.height-l-s),f=i===`left`?e.left:e.right-c;f=Math.max(s,Math.min(f,u));let p;return a===`top`?(p=e.top-l-o,p<s&&e.bottom+o+l<=n.height-s&&(p=e.bottom+o)):(p=e.bottom+o,p+l>n.height-s&&e.top-l-o>=s&&(p=e.top-l-o)),p>d&&(p=d),p<s&&(p=s),{x:Math.round(f),y:Math.round(p)}}function Cn(e){let{open:t=!0,anchor:n,anchorEl:r,onClose:i,isInside:a,align:o=`right`,side:s=`bottom`,gap:c=6,margin:l=8}=e,u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(i);(0,Q.useLayoutEffect)(()=>{p.current=i});let m=()=>{if(!n)return null;if(`current`in n)return n.current?.getBoundingClientRect()??null;if(typeof n.getBoundingClientRect==`function`)return n.getBoundingClientRect();let e=n;return typeof e.left==`number`&&typeof e.right==`number`&&typeof e.top==`number`&&typeof e.bottom==`number`?e:null},h=()=>r||(n&&`current`in n?n.current:n&&typeof n.getBoundingClientRect==`function`?n:null),g=()=>{if(!t)return;let e=u.current;if(!e)return;let n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return;let r=h(),i=r&&r.isConnected?r.getBoundingClientRect():m();if(!i)return;let a=Sn(i,{width:n.width,height:n.height},{width:window.innerWidth,height:window.innerHeight},{align:o,side:s,gap:c,margin:l});f(e=>e?.x===a.x&&e?.y===a.y?e:a)};return(0,Q.useLayoutEffect)(()=>{t?g():f(null)},[t,n,r,o,s,c,l]),mt(()=>{p.current()},t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>e instanceof Node&&!!(u.current?.contains(e)||h()?.contains(e)||a?.(e)),n=t=>{e(t.target)||p.current()};return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`resize`,g,!0),window.addEventListener(`scroll`,g,!0),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`resize`,g,!0),window.removeEventListener(`scroll`,g,!0)}},[t,n,r]),{panelRef:u,pos:d,style:{position:`fixed`,left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},measure:g}}async function wn(e,t,n,r){let i=window.piDesktop,a=i?.openHub?null:window.open(`about:blank`,`_blank`);if(!i?.openHub&&!a)throw Error(r?`请允许弹出窗口后重试。`:`Allow popups and try again.`);a&&(a.opener=null);try{let o=await fetch(Qe(q(`/api/device-center/devices/${encodeURIComponent(e)}/open`)),{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,signal:AbortSignal.timeout(15e3)});if(!o.ok)throw Error(r?`无法打开设备,请确认设备在线且本机绑定有效。`:`Could not open the device. Check connectivity and local pairing.`);let s=await o.json(),c=new URL(s.url),l=new URL(t);if(![`http:`,`https:`].includes(c.protocol)||c.hostname!==l.hostname||c.username||c.password||!(c.pathname===`/__device/open`||c.origin===l.origin&&c.pathname===`/device/${encodeURIComponent(e)}/__open`))throw Error(`Invalid device access URL`);if(c.searchParams.delete(`next`),n&&c.searchParams.set(`next`,`/desktop`),i?.openHub){if(!await i.openHub(c.href))throw Error(r?`无法打开设备窗口。`:`Could not open device window.`)}else a&&a.location.replace(c.href)}catch(e){throw a?.close(),e}}var $=pt();function Tn({hubUrl:e,currentDeviceId:t}){let{locale:n}=Ue(),r=H(n),[i,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let e=!1,t,n;async function i(){t=new AbortController;try{let n=await fetch(Qe(q(`/api/device-center/devices`)),{signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]),credentials:`same-origin`});if(!n.ok)throw Error(n.status===409?r?`请重新绑定本机以读取设备列表。`:`Pair this computer again to read the device list.`:r?`无法读取设备列表,请重试。`:`Could not load devices. Try again.`);let i=await n.json();if(!Array.isArray(i.devices))throw Error(r?`设备列表格式异常。`:`Invalid device list.`);e||(o(i.devices),c(``))}catch(t){e||(o([]),c(t instanceof Error?t.message:String(t)))}finally{e||(n=setTimeout(i,5e3))}}return i(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[e,t,l,r]);function d(t){try{let n=new URL(e);return![`http:`,`https:`].includes(n.protocol)||n.username||n.password?void 0:new URL(`/device/${encodeURIComponent(t)}`,n).href}catch{return}}async function f(t,n,i=!1){t.preventDefault();try{await wn(n,e,i,r),c(``)}catch(e){c(e instanceof Error?e.message:String(e))}}return(0,$.jsxs)(`section`,{className:`dc-card`,"aria-label":r?`所有设备`:`All devices`,children:[(0,$.jsxs)(`div`,{className:`dc-card-header`,children:[(0,$.jsx)(`span`,{className:`dc-icon`,children:(0,$.jsx)(st,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{children:[r?`所有设备`:`All devices`,` · `,i.length]}),(0,$.jsx)(`p`,{children:r?`同一账号下的设备,使用本机绑定授权直接访问。`:`Devices in your account. Access is authorized through this computer's pairing.`})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-icon-button`,"aria-label":r?`刷新设备`:`Refresh devices`,onClick:()=>u(e=>e+1),children:(0,$.jsx)(te,{})})]}),s&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:s}),(0,$.jsx)(`div`,{className:`dd-list`,children:i.map(e=>(0,$.jsxs)(`div`,{className:`dd-device`,children:[(0,$.jsx)(`span`,{className:`dc-device-icon`,children:(0,$.jsx)(st,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`dd-identity`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`span`,{children:e.id===t?r?`本机`:`This device`:e.id})]}),(0,$.jsx)(`span`,{className:`dc-status ${e.online?`is-online`:`is-offline`}`,children:e.online?r?`在线`:`Online`:r?`离线`:`Offline`}),d(e.id)&&(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`a`,{className:`dc-button`,href:d(e.id),target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void f(t,e.id),children:[(0,$.jsx)(a,{"aria-hidden":!0}),r?`打开设备`:`Open device`]}),(0,$.jsxs)(`a`,{className:`dc-button`,href:`${d(e.id)}/desktop`,target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void f(t,e.id,!0),children:[(0,$.jsx)(st,{"aria-hidden":!0}),r?`远程桌面`:`Remote desktop`]})]})]},e.id))})]})}function En({label:e=`pi-web-ui`,barItem:t=!1,onContextMenu:n}){let{locale:r}=Ue(),i=H(r),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),l=(0,Q.useRef)(null),{panelRef:u,style:d}=Cn({open:s&&!!a,anchor:l,align:`left`,onClose:()=>c(!1)});(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(Qe(q(`/api/device-center/chat-status`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)return;let r=await n.json();if(!e){let e=r.local!==!0&&typeof r.hubUrl==`string`&&!!r.hubUrl&&typeof r.deviceId==`string`&&!!r.deviceId;o(e?{hubUrl:r.hubUrl,deviceId:r.deviceId}:null),e||c(!1)}}catch{}finally{e||(n=setTimeout(r,15e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[]);let f=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{className:t?`brand-logo bar-item-brand-logo bar-item-icon`:`brand-logo`,src:q(`/icons/icon-192.png`),alt:`pi-web-ui`,width:26,height:26,draggable:!1}),(0,$.jsx)(`span`,{className:t?`brand-name bar-item-text`:`brand-name`,children:e})]}),p=t?`bar-item brand bar-item-brand`:`brand`;return a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:l,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,type:`button`,className:`${p} brand-device-trigger`,title:i?`设备列表`:`Devices`,"aria-label":i?`设备列表`:`Devices`,"aria-haspopup":`dialog`,"aria-expanded":s,onClick:()=>c(e=>!e),children:f}),s&&(0,bn.createPortal)((0,$.jsx)(`div`,{ref:u,style:d,className:`brand-device-panel`,role:`dialog`,"aria-label":i?`设备列表`:`Devices`,children:(0,$.jsx)(Tn,{hubUrl:a.hubUrl,currentDeviceId:a.deviceId})}),document.body)]}):(0,$.jsx)(`span`,{className:p,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,children:f})}function Dn(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`},child:[{tag:`path`,attr:{d:`M11.646 15.146 5.854 9.354a.5.5 0 0 1 .353-.854h11.586a.5.5 0 0 1 .353.854l-5.793 5.792a.5.5 0 0 1-.707 0Z`},child:[]}]})(e)}function On(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`},child:[]},{tag:`path`,attr:{d:`M7 11v4a2 2 0 0 0 2 2h4`},child:[]},{tag:`rect`,attr:{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`},child:[]}]})(e)}function kn(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 17H7l-4 4v-7`},child:[]},{tag:`path`,attr:{d:`M14 17h1`},child:[]},{tag:`path`,attr:{d:`M14 3h1`},child:[]},{tag:`path`,attr:{d:`M19 3a2 2 0 0 1 2 2`},child:[]},{tag:`path`,attr:{d:`M21 14v1a2 2 0 0 1-2 2`},child:[]},{tag:`path`,attr:{d:`M21 9v1`},child:[]},{tag:`path`,attr:{d:`M3 9v1`},child:[]},{tag:`path`,attr:{d:`M5 3a2 2 0 0 0-2 2`},child:[]},{tag:`path`,attr:{d:`M9 3h1`},child:[]}]})(e)}function An(e){return n({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2`},child:[]},{tag:`path`,attr:{d:`M8.5 2h7`},child:[]},{tag:`path`,attr:{d:`M7 16h10`},child:[]}]})(e)}function jn(e){return e.map(e=>e.kind===`package`?`pi update npm:${e.name}`:e.kind===`git-extension`?`pi update ${Mn(e.source??e.name)}`:e.kind===`plugin`?`pi-web-ui install ${e.source??e.name} --name ${e.pluginId??e.name} --force`:`npm i -g ${e.name}@latest`).join(`; `)}function Mn(e){return e.startsWith(`git:`)?e:`git:${e}`}var Nn=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost),Pn=null,Fn=0;function In(){return Pn?.available===!0?Pn.pages??[]:[]}function Ln(){Date.now()-Fn<5e3||Rn().catch(()=>{})}async function Rn(){if(wt())return{available:!1,pages:[],desktop:!0,error:`桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)`};let e=Nn();if(!e)return{available:!1,pages:[],error:`宿主页面桥不可用:这个 pi-web-ui 页面还没装上扩展桥(装/启用 page-picker 后刷新本页)`};try{let t=await e({op:`status`,timeoutMs:5e3});if(!t.ok)return{available:!1,pages:[],error:t.error??`扩展没有返回状态`};let n=t.result??{},r={available:n.installed===!0,aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,pages:Array.isArray(n.pages)?n.pages:[]};return r.available&&(Pn=r,Fn=Date.now()),r}catch(e){return{available:!1,pages:[],error:e instanceof Error?e.message:String(e)}}}function zn(e){return e.length===1?e[0]:null}function Bn(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:`page`,key:`page:${e.origin}`}}async function Vn(){let e=Nn();if(!e)return!1;try{return(await e({op:`openOptions`,timeoutMs:5e3})).ok===!0}catch{return!1}}function Hn(e=45e3){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(!0),i=(0,Q.useCallback)(async e=>{let t=await Rn();r.current&&(n(t),e&&!t.available&&setTimeout(()=>{r.current&&i(!1)},1500))},[]);return(0,Q.useEffect)(()=>{r.current=!0,i(!0);let t=setInterval(()=>void i(!1),Math.max(5e3,e));return()=>{r.current=!1,clearInterval(t)}},[i,e]),{status:t,refresh:()=>void i(!0)}}function Un(){let e=V(),{status:t,refresh:n}=Hn(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),s=(0,Q.useRef)(null),c=t?.pages??[],l=t?.available===!0&&(c.length===0||t.aiControl===!1),u=zn(c),d=e=>{o(e),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>o(null),2600)},f=t=>{let n=Ft({attachments:[Bn(t)]});d(e(n?`browserControlCited`:`browserControlCiteFailed`))},p=()=>{i(!0),n()};return(0,$.jsxs)(`span`,{className:`bc-anchor`,children:[u?(0,$.jsxs)(`span`,{className:`browser-control-split`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control single${l?` attention`:``}`,"data-tip":e(`browserControlSingleTip`,{name:u.title||u.origin}),title:e(`browserControlSingleTip`,{name:u.title||u.origin}),onClick:()=>f(u),children:[(0,$.jsx)(st,{size:14,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`bc-chip-label`,children:u.title||u.origin})]}),(0,$.jsx)(`button`,{type:`button`,className:`chip browser-control caret`,"data-tip":e(`browserControlOpenPanel`),title:e(`browserControlOpenPanel`),"aria-label":e(`browserControlOpenPanel`),onClick:p,children:`▾`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${l?` attention`:``}`,"data-tip":t?.error??e(l?`browserControlEmpty`:`browserControlTip`),title:t?.error??e(l?`browserControlEmpty`:`browserControlTip`),onClick:p,children:[(0,$.jsx)(st,{size:14,"aria-hidden":!0}),(0,$.jsxs)(`span`,{children:[e(`browserControl`),c.length>0?` · ${c.length}`:``]})]}),a&&(0,$.jsx)(`span`,{className:`bc-flash`,children:a}),r&&(0,$.jsx)(Wn,{status:t,onRefresh:n,onCite:f,onClose:()=>i(!1)})]})}function Wn({status:e,onRefresh:t,onCite:n,onClose:r}){let i=V(),[a,o]=(0,Q.useState)(!1),s=e?.pages??[],c=async()=>{o(!0);try{await Vn()||t()}finally{o(!1)}};return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:r,children:(0,$.jsxs)(`div`,{className:`modal browser-control-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":i(`close`),onClick:r,children:`✕`}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(st,{size:16,"aria-hidden":!0}),(0,$.jsx)(`h2`,{children:i(`browserControl`)})]}),(0,$.jsx)(`div`,{className:`modal-desc`,children:i(`browserControlTip`)}),e===null&&(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlChecking`)}),e?.available===!1&&!e.desktop&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlOffline`)}),e?.desktop===!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlDesktop`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlDesktopLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:window.location.href,target:`_blank`,rel:`noreferrer noopener`,children:i(`browserControlOpenInBrowser`)})})]}),e?.available===!1&&!e.desktop&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlInstall`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlInstallLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:`https://github.com/xing-shuyin/pi-web-ui/releases/latest/download/page-picker-extension.zip`,target:`_blank`,rel:`noreferrer noopener`,children:i(`browserControlInstallDownload`)})}),(0,$.jsxs)(`ol`,{className:`bc-steps`,children:[(0,$.jsx)(`li`,{children:i(`browserControlInstallStep1`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep2`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep3`)}),(0,$.jsx)(`li`,{children:i(`browserControlInstallStep4`)})]})]}),e?.available===!0&&e.aiControl===!1&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlDisabled`)}),e?.available===!0&&s.length===0&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:i(`browserControlEmpty`)}),s.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlPages`)}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:s.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`bc-title`,title:e.title,children:e.title}),(0,$.jsx)(`span`,{className:`bc-origin`,title:e.origin,children:e.origin}),(0,$.jsx)(`span`,{className:`bc-open${e.open?` on`:``}`,children:e.open?i(`browserControlPageOpen`):i(`browserControlPageClosed`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,title:i(`browserControlCiteTip`,{name:e.title||e.origin}),onClick:()=>n(e),children:i(`browserControlCite`)})]},e.origin))}),(0,$.jsx)(`div`,{className:`bc-note`,children:i(`browserControlCiteNote`)})]}),e?.desktop!==!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:i(`browserControlExamples`)}),(0,$.jsxs)(`ul`,{className:`bc-examples`,children:[(0,$.jsx)(`li`,{children:i(`browserControlExample1`)}),(0,$.jsx)(`li`,{children:i(`browserControlExample2`)})]})]}),(0,$.jsxs)(`div`,{className:`bc-actions`,children:[e?.desktop!==!0&&(0,$.jsx)(`button`,{type:`button`,className:`primary`,disabled:a,onClick:()=>void c(),children:i(`browserControlOpenOptions`)}),(0,$.jsx)(`button`,{type:`button`,onClick:t,children:i(`browserControlRefresh`)})]})]})})}var Gn=`canvas`,Kn=`terminal`,qn=[Kn],Jn=[`terminal_create`,`terminal_list`,`terminal_close`,`terminal_input`,`terminal_key`,`terminal_read`,`terminal_wait`],Yn=`conversation`,Xn=`communicate`,Zn=[Yn,`subagent`],Qn=[`subagent_spawn`,`subagent_get_result`,`subagent_steer`,`subagent_list`,`subagent_stop`,`subagent_wait_all`,`subagent_templates`,`subagent_handoff`],$n=`edit_soft`,er=`delegate_task`,tr=`ask_user_question`,nr=`browser_page`,rr=`skill`,ir=`schedule`,ar=[`schedule_task`,`schedule_list`,`schedule_cancel`],or=`eval`,sr=`present_files`,cr=`claim_files`,lr=`plan_update`,ur=`compact_context`,dr=`patch`,fr=`mcp_manage`,pr=`sandbox`,mr=`worktree`,hr=`device_collab`,gr=`codemode`,_r=`tool_search`,vr=[...qn.map(e=>({name:e,group:`terminal`,defaultOn:!1,dshVisible:!0})),...Zn.map(e=>({name:e,group:`subagent`,defaultOn:!0,dshVisible:!1})),{name:Xn,group:`subagent`,defaultOn:!0,dshVisible:!1,descKey:`communicateEnabledDesc`,offHintKey:`communicateOffHint`},{name:$n,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`editSoftEnabledDesc`,offHintKey:`editSoftOffHint`},{name:er,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`delegateTaskEnabledDesc`,offHintKey:`delegateTaskOffHint`},{name:tr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`questionnaireEnabledDesc`,offHintKey:`questionnaireOffHint`},{name:nr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`browserPageEnabledDesc`,offHintKey:`browserPageOffHint`},{name:cr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`claimFilesEnabledDesc`,offHintKey:`claimFilesOffHint`},{name:lr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`planUpdateEnabledDesc`,offHintKey:`planUpdateOffHint`},{name:dr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`patchToolEnabledDesc`,offHintKey:`patchToolOffHint`},{name:`lsp`,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`lspToolEnabledDesc`,offHintKey:`lspToolOffHint`},{name:sr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`presentFilesEnabledDesc`,offHintKey:`presentFilesOffHint`},{name:rr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`skillEnabledDesc`,offHintKey:`skillOffHint`},{name:or,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`evalEnabledDesc`,offHintKey:`evalOffHint`},{name:gr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`codemodeEnabledDesc`,offHintKey:`codemodeOffHint`},{name:_r,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolSearchEnabledDesc`,offHintKey:`toolSearchOffHint`},{name:ir,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`scheduleTaskEnabledDesc`,offHintKey:`scheduleTaskOffHint`},{name:ur,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`compactContextEnabledDesc`,offHintKey:`compactContextOffHint`},{name:fr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`mcpManageEnabledDesc`,offHintKey:`mcpManageOffHint`},{name:pr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`sandboxEnabledDesc`,offHintKey:`sandboxOffHint`},{name:mr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`toolsWorktreeDesc`,offHintKey:`toolsWorktreeOffHint`},{name:hr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolsDeviceCollabDesc`,offHintKey:`toolsDeviceCollabOffHint`},{name:Gn,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`canvasToolEnabledDesc`,offHintKey:`canvasToolOffHint`}],yr=[{name:`bash`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreBashDesc`},{name:`read`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreReadDesc`},{name:`edit`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreEditDesc`},{name:`write`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreWriteDesc`},{name:`powershell`,group:`core`,defaultOn:!1,platform:`win32`,allowAgentToggle:!1,descKey:`toolCorePowershellDesc`},{name:`ls`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreLsDesc`},{name:`grep`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreGrepDesc`},{name:`find`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreFindDesc`}],br=[...yr.map(e=>({name:e.name,group:`core`,defaultOn:e.defaultOn,platform:e.platform,allowAgentToggle:e.allowAgentToggle,dshVisible:!1,descKey:e.descKey})),...vr];new Map(br.map(e=>[e.name,e]));var xr=new Set(br.map(e=>e.name)),Sr=br.map(e=>e.name);function Cr(e){let t=new Set(wr(e));return Sr.filter(e=>!t.has(e))}function wr(e){if(!Array.isArray(e))return Tr();let t=[];for(let n of e){let e=n;if(typeof e==`string`&&Jn.includes(e)&&(e=Kn),typeof e==`string`&&Qn.includes(e)&&(e=Yn),e===`conversation_read`&&(e=Yn),typeof e==`string`&&Zn.includes(e)){for(let e of Zn)t.includes(e)||t.push(e);continue}typeof e==`string`&&ar.includes(e)&&(e=ir),typeof e==`string`&&xr.has(e)&&!t.includes(e)&&t.push(e)}return t}function Tr(){return br.filter(e=>!e.defaultOn).map(e=>e.name)}function Er(e,t){let n=Array.from(e);if(!t||t===`standard`)return n;if(t===`ask`)return[];if(t===`minimal`)return n.filter(e=>e===`bash`||e===`read`);if(t===`code`){let e=new Set([`bash`,`read`,`edit`,`write`,`edit_soft`]);return n.filter(t=>e.has(t))}if(t===`reader`){let e=new Set([`write`,`edit`,`edit_soft`,`bash`,`powershell`,`terminal_create`,`terminal_input`,`terminal_close`,`terminal_key`,`codemode`]);return n.filter(t=>!e.has(t))}return n}function Dr(e){return Er([rr],e).includes(rr)}var Or=new Set([`svg`,`g`,`path`,`circle`,`rect`,`line`,`polyline`,`polygon`,`ellipse`,`use`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`]),kr=new Set(`viewBox.xmlns.d.fill.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-dasharray.opacity.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.width.height.points.offset.stop-color.stop-opacity.fill-opacity.stroke-opacity.stroke-miterlimit.fill-rule.clip-rule.vector-effect.preserveAspectRatio.transform.clip-path.id.href.xlink:href.xmlns:xlink.gradientUnits.gradientTransform`.split(`.`)),Ar=new Set([`script`,`style`,`title`,`desc`,`foreignobject`]),jr=new Set([...Or].map(e=>e.toLowerCase())),Mr=new Set([...kr].map(e=>e.toLowerCase()));function Nr(e){return jr.has(e.toLowerCase())}function Pr(e){return Mr.has(e.toLowerCase())}function Fr(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>8192||!/^<svg[\s>]/.test(t.startsWith(`<?xml`)?t.slice(t.indexOf(`?>`)+2).trimStart():t))return null;if(typeof DOMParser>`u`)return/<script[\s>]/i.test(t)||/\son\w+\s*=/i.test(t)||/javascript\s*:/i.test(t)?null:t;let n=new DOMParser().parseFromString(t,`image/svg+xml`);if(n.querySelector(`parsererror`))return null;let r=n.documentElement;if(r.tagName.toLowerCase()!==`svg`)return null;let i=e=>{for(let t of Array.from(e.children)){let e=t.tagName.toLowerCase();if(!Nr(e)){Ar.has(e)?t.remove():(i(t),t.replaceWith(...t.childNodes));continue}for(let e of Array.from(t.attributes)){let n=e.name.toLowerCase();(!Pr(n)||/^on/i.test(n)||/^(javascript|data|vbscript):/i.test(e.value.trim()))&&t.removeAttribute(e.name)}i(t)}};for(let e of Array.from(r.attributes)){let t=e.name.toLowerCase();(!Pr(t)||/^on/i.test(t))&&r.removeAttribute(e.name)}return i(r),new XMLSerializer().serializeToString(r)}function Ir({icon:e,iconSvg:t,className:n}){let r=Fr(t);return r?(0,$.jsx)(`span`,{className:n??`plugin-icon-svg`,"aria-hidden":!0,dangerouslySetInnerHTML:{__html:r}}):e?(0,$.jsx)(`span`,{className:n?`${n} plugin-icon-glyph`:`plugin-icon-glyph`,"aria-hidden":!0,children:e}):null}var Lr={projects:`host:lp-projects`,convs:`host:lp-running`,sessions:`host:lp-history`},Rr=[`projects`,`convs`,`sessions`],zr=new Map(Object.keys(Lr).map(e=>[Lr[e],e])),Br=`plugin:`;function Vr(e){return e.startsWith(Br)&&e.length>7}function Hr(e){let t=[],n=new Set;for(let r of e??[]){let e=null,i,a=zr.get(r.id);a?e=a:r.source?.startsWith(`plugin:`)&&r.kind===`view`&&(e=`${Br}${r.id}`,i=r),e&&!n.has(e)&&(n.add(e),t.push({key:e,shown:!r.hidden,...i?{entry:i}:{}}))}for(let e of Rr)n.has(e)||t.push({key:e,shown:!0});return t}function Ur(e){let t=e.filter(e=>e.key!==`groups`),n=t.findIndex(e=>e.key===`projects`&&e.shown);return t.splice(n+1,0,{key:`groups`,shown:!0}),t}function Wr(e,t){return e.filter(e=>e.shown&&t(e.key)).map(e=>e.key)}function Gr(e,t){let n=[];for(let r=0;r+1<e.length;r++){let i=e[r],a=e[r+1];!t(i)&&!t(a)&&n.push([i,a])}return n}function Kr(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(!r||typeof r!=`object`||Array.isArray(r))return n;for(let[e,i]of Object.entries(r))(e in t||Vr(e))&&typeof i==`number`&&Number.isFinite(i)&&i>0&&(n[e]=i)}catch{}return n}var qr=new Set([`view`,`action`,`badge`,`menu`,`page`,`organizer`,`divider`,`toggle`,`input`,`progress`,`select`]),Jr=new Set([`disabled`,`always`,`never`,`file.isDir`,`file.isFile`,`session.isRunning`,`message.hasSelection`]),Yr=`topbar.primary,topbar.overflow,notice.actions,leftpanel.sections,leftpanel.projects.actions,leftpanel.project,leftpanel.running.actions,leftpanel.running,leftpanel.history.actions,leftpanel.history,leftpanel.sessions,chat.header,chat.empty,message.actions,goalbar.actions,composer.leading,composer.actions,rightpanel.tabs,terminal.toolbar,scm.toolbar,bottombar,file.preview.toolbar,contextmenu.topbar,contextmenu.message,contextmenu.session,contextmenu.project,contextmenu.file,contextmenu.toolcall,tool.card.footer,settings.pages,tasks.panel,modal.dialog,sidebar.left,sidebar.right`.split(`,`),Xr=Yr.map(e=>({slot:e,cardinality:`list`}));function Zr(e){return Xr.find(t=>t.slot===e)?.cardinality??`list`}function Qr(e,t){if(t===`list`)return{entries:[...e],conflicts:[]};let n=e.findIndex(e=>!e.hidden);if(n<0)return{entries:[...e],conflicts:[]};let r=e.filter((e,t)=>t!==n&&!e.hidden);return{entries:e.map((e,t)=>t===n||e.hidden?e:{...e,hidden:!0}),winner:e[n],conflicts:r}}var $r=[{id:`host:lp-projects`,slot:`leftpanel.sections`,labelKey:`recentProjects`,icon:`folder`,kind:`action`,order:10},{id:`host:lp-running`,slot:`leftpanel.sections`,labelKey:`runningConversations`,icon:`activity`,kind:`action`,order:20},{id:`host:lp-history`,slot:`leftpanel.sections`,labelKey:`historySessions`,icon:`clock`,kind:`action`,order:30},{id:`host:brand`,slot:`topbar.primary`,labelKey:`brand`,kind:`badge`,order:1,group:`brand`},{id:`host:open-project`,slot:`topbar.primary`,labelKey:`openProject`,icon:`folder`,kind:`action`,order:3,group:`primary`},{id:`host:history`,slot:`topbar.primary`,labelKey:`openHistory`,icon:`menu`,kind:`action`,order:0,group:`panels`},{id:`host:files`,slot:`topbar.primary`,labelKey:`openFiles`,icon:`folder`,kind:`action`,order:97,group:`panels`,align:`end`},{id:`host:new-chat`,slot:`topbar.primary`,labelKey:`newChat`,icon:`plus`,kind:`action`,order:96,group:`primary`,align:`end`},{id:`host:new-ephemeral-chat`,slot:`topbar.primary`,labelKey:`newChatEphemeral`,icon:`chat`,kind:`action`,order:96.5,group:`primary`,align:`end`},{id:`host:new-sandbox`,slot:`topbar.primary`,labelKey:`newSandbox`,icon:`sandbox`,kind:`action`,order:96.6,group:`primary`,align:`end`},{id:`host:chat`,slot:`topbar.primary`,labelKey:`chat`,icon:`chat`,kind:`view`,view:`chat`,order:20,group:`views`,align:`end`},{id:`host:terminal`,slot:`topbar.primary`,labelKey:`terminal`,icon:`terminal`,kind:`view`,view:`terminal`,order:21,group:`views`,align:`end`},{id:`host:git`,slot:`topbar.primary`,labelKey:`scmTab`,icon:`git`,kind:`view`,view:`git`,order:22,group:`views`,align:`end`},{id:`host:canvas`,slot:`topbar.primary`,labelKey:`canvasTab`,icon:`share`,kind:`view`,view:`canvas`,order:22.5,group:`views`,align:`end`},{id:`host:plugins`,slot:`topbar.primary`,labelKey:`pluginMenuTitle`,icon:`🧩`,kind:`action`,order:24,group:`views`,align:`end`},{id:`host:search`,slot:`topbar.primary`,labelKey:`searchGlobal`,icon:`search`,kind:`action`,order:40,group:`tools`,align:`end`},{id:`host:browser`,slot:`topbar.primary`,labelKey:`browserControl`,icon:`browser`,kind:`action`,order:41,group:`tools`,align:`end`,hidden:!0},{id:`host:tasks`,slot:`topbar.primary`,labelKey:`bgTasks`,icon:`layers`,kind:`action`,order:42,group:`tools`,align:`end`},{id:`host:zen-mode`,slot:`topbar.primary`,labelKey:`zenMode`,icon:`feather`,kind:`action`,order:43,group:`tools`,align:`end`},{id:`host:device-center`,slot:`topbar.primary`,labelKey:`deviceCenter`,icon:`globe`,kind:`view`,view:`devices`,order:59,group:`system`,align:`end`},{id:`host:settings`,slot:`topbar.primary`,labelKey:`settingsTitle`,icon:`settings`,kind:`action`,order:60,group:`system`,align:`end`},{id:`host:language`,slot:`topbar.primary`,labelKey:`language`,icon:`globe`,kind:`action`,order:80,group:`system`,hidden:!0,align:`end`},{id:`host:theme`,slot:`topbar.primary`,labelKey:`theme`,icon:`sun`,kind:`action`,order:82,group:`system`,hidden:!0,align:`end`},{id:`host:update`,slot:`topbar.primary`,labelKey:`update`,icon:`download`,kind:`action`,order:90,group:`system`,align:`end`,hidden:!0},{id:`host:github`,slot:`topbar.primary`,labelKey:`githubRepo`,icon:`github`,kind:`action`,order:200,group:`system`,align:`end`,hidden:!0},{id:`host:conn`,slot:`bottombar`,labelKey:`connected`,icon:`dot`,kind:`badge`,order:5,group:`status`},{id:`host:engine`,slot:`bottombar`,labelKey:`engineBadge`,icon:`aperture`,kind:`action`,order:6,group:`status`},{id:`host:ctx`,slot:`bottombar`,labelKey:`context`,icon:`gauge`,kind:`badge`,order:10,group:`usage`},{id:`host:cost`,slot:`bottombar`,labelKey:`cumulativeCost`,icon:`coins`,kind:`badge`,order:11,group:`usage`},{id:`host:cache`,slot:`bottombar`,labelKey:`cacheHit`,icon:`database`,kind:`badge`,order:12,group:`usage`},{id:`host:msg-count`,slot:`bottombar`,labelKey:`messages`,icon:`message`,kind:`badge`,order:13,group:`usage`},{id:`host:plugin-status`,slot:`bottombar`,labelKey:`pluginStatus`,icon:`activity`,kind:`badge`,order:14,group:`status`},{id:`host:working`,slot:`bottombar`,labelKey:`working`,icon:`activity`,kind:`badge`,order:15,group:`status`},{id:`host:status-delegate`,slot:`bottombar`,labelKey:`delegateModeBadge`,icon:`eye`,kind:`badge`,order:16,group:`status`},{id:`host:host-metrics`,slot:`bottombar`,labelKey:`hostResources`,icon:`cpu`,kind:`badge`,order:19,group:`host`,align:`end`},{id:`host:cwd`,slot:`bottombar`,labelKey:`cwdTip`,icon:`folder`,kind:`action`,order:20,group:`context`,align:`end`},{id:`host:msg-reask`,slot:`message.actions`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,order:9},{id:`host:msg-edit-reask`,slot:`message.actions`,labelKey:`editReask`,icon:`edit`,kind:`action`,order:10},{id:`host:msg-fork`,slot:`message.actions`,labelKey:`forkSession`,icon:`branch`,kind:`action`,order:15},{id:`host:msg-rollback`,slot:`message.actions`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,order:16},{id:`host:msg-copy`,slot:`message.actions`,labelKey:`copyMessage`,icon:`copy`,kind:`action`,order:20},{id:`host:msg-copy-text`,slot:`message.actions`,labelKey:`copyText`,icon:`text`,kind:`action`,order:21},{id:`host:msg-copy-markdown`,slot:`message.actions`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,order:22},{id:`host:msg-copy-image`,slot:`message.actions`,labelKey:`copyImage`,icon:`image`,kind:`action`,order:23},{id:`host:msg-speak`,slot:`message.actions`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,order:24},{id:`host:composer-upload`,slot:`composer.actions`,labelKey:`uploadFile`,icon:`upload`,kind:`action`,order:10,align:`start`},{id:`host:composer-templates`,slot:`composer.actions`,labelKey:`tpl.openPicker`,icon:`grid`,kind:`action`,order:110,align:`start`},{id:`host:composer-model`,slot:`composer.actions`,labelKey:`selectModel`,icon:`cpu`,kind:`action`,order:120,align:`start`},{id:`host:composer-thinking`,slot:`composer.actions`,labelKey:`thinkingLevel`,icon:`zap`,kind:`action`,order:130,align:`start`},{id:`host:composer-dsh-perm`,slot:`composer.actions`,labelKey:`dshPerm`,icon:`lock`,kind:`action`,order:140,align:`start`},{id:`host:composer-dsh-preset`,slot:`composer.actions`,labelKey:`dshPreset`,icon:`layers`,kind:`action`,order:150,align:`start`},{id:`host:composer-send`,slot:`composer.actions`,labelKey:`sendTip`,icon:`send`,kind:`action`,order:200,align:`end`},{id:`host:fp-md`,slot:`file.preview.toolbar`,labelKey:`showMarkdownPreview`,icon:`eye`,kind:`action`,order:10},{id:`host:fp-toc`,slot:`file.preview.toolbar`,labelKey:`previewTocLabel`,icon:`list`,kind:`action`,order:15},{id:`host:fp-html`,slot:`file.preview.toolbar`,labelKey:`showHtmlPreview`,icon:`code`,kind:`action`,order:20},{id:`host:fp-edit`,slot:`file.preview.toolbar`,labelKey:`editFile`,icon:`edit`,kind:`action`,order:30},{id:`host:fp-wrap`,slot:`file.preview.toolbar`,labelKey:`enableWrap`,icon:`wrap`,kind:`action`,order:40},{id:`host:fp-zoom`,slot:`file.preview.toolbar`,labelKey:`zoomIn`,icon:`zoom`,kind:`action`,order:50},{id:`host:fp-download`,slot:`file.preview.toolbar`,labelKey:`downloadFile`,icon:`download`,kind:`action`,order:60},{id:`host:fp-ref`,slot:`file.preview.toolbar`,labelKey:`referenceTip`,icon:`link`,kind:`action`,order:70},{id:`host:fp-full`,slot:`file.preview.toolbar`,labelKey:`fullscreen`,icon:`maximize`,kind:`action`,order:80},{id:`host:fp-close`,slot:`file.preview.toolbar`,labelKey:`close`,icon:`x`,kind:`action`,order:90},{id:`host:goal-pill`,slot:`goalbar.actions`,labelKey:`goalBarTitle`,icon:`target`,kind:`action`,order:5},{id:`host:goal-set`,slot:`goalbar.actions`,labelKey:`goalBarSet`,icon:`check`,kind:`action`,order:10},{id:`host:goal-wizard`,slot:`goalbar.actions`,labelKey:`goalWizardBtn`,icon:`search`,kind:`action`,order:20},{id:`host:goal-lock`,slot:`goalbar.actions`,labelKey:`goalBarLocked`,icon:`lock`,kind:`action`,order:30},{id:`host:goal-plan`,slot:`goalbar.actions`,labelKey:`planMode`,icon:`list`,kind:`action`,order:25},{id:`host:goal-collapse`,slot:`goalbar.actions`,labelKey:`collapsePanel`,icon:`chevron-up`,kind:`action`,order:40},{id:`host:goal-model`,slot:`goalbar.actions`,labelKey:`goalBarReviewModel`,icon:`cpu`,kind:`action`,order:50},{id:`host:goal-rounds`,slot:`goalbar.actions`,labelKey:`goalBarMaxRounds`,icon:`hash`,kind:`action`,order:60},{id:`host:goal-execmodel`,slot:`goalbar.actions`,labelKey:`goalBarExecModel`,icon:`cpu`,kind:`action`,order:55},{id:`host:goal-openrole`,slot:`goalbar.actions`,labelKey:`goalBarOpenExec`,icon:`search`,kind:`action`,order:65},{id:`host:goal-clear`,slot:`goalbar.actions`,labelKey:`goalBarClear`,icon:`x`,kind:`action`,order:70},{id:`host:scm-changes`,slot:`scm.toolbar`,labelKey:`scmChanges`,icon:`file`,kind:`action`,order:10},{id:`host:scm-history`,slot:`scm.toolbar`,labelKey:`scmHistory`,icon:`clock`,kind:`action`,order:20},{id:`host:scm-refresh`,slot:`scm.toolbar`,labelKey:`scmRefreshTip`,icon:`refresh`,kind:`action`,order:30},{id:`host:scm-branch`,slot:`scm.toolbar`,labelKey:`scmSwitchBranch`,icon:`git`,kind:`action`,order:40},{id:`host:scm-switch`,slot:`scm.toolbar`,labelKey:`scmSwitch`,icon:`git`,kind:`action`,order:50},{id:`host:scm-push`,slot:`scm.toolbar`,labelKey:`scmPush`,icon:`upload`,kind:`action`,order:60},{id:`host:scm-pull`,slot:`scm.toolbar`,labelKey:`scmPull`,icon:`download`,kind:`action`,order:70},{id:`host:scm-input`,slot:`scm.toolbar`,labelKey:`scmCommitPlaceholder`,icon:`edit`,kind:`action`,order:80},{id:`host:scm-genmsg`,slot:`scm.toolbar`,labelKey:`scmGenMsg`,icon:`cpu`,kind:`action`,order:85},{id:`host:scm-commit`,slot:`scm.toolbar`,labelKey:`scmCommit`,icon:`check`,kind:`action`,order:90},{id:`host:scm-commit-all`,slot:`scm.toolbar`,labelKey:`scmCommitAll`,icon:`check`,kind:`action`,order:100},{id:`host:scm-term`,slot:`scm.toolbar`,labelKey:`terminal`,icon:`terminal`,kind:`action`,order:110},{id:`host:term-cmd-refresh`,slot:`terminal.toolbar`,labelKey:`rerun`,icon:`refresh`,kind:`action`,order:10},{id:`host:term-cmd-new`,slot:`terminal.toolbar`,labelKey:`newCommand`,icon:`plus`,kind:`action`,order:20},{id:`host:term-tab-new`,slot:`terminal.toolbar`,labelKey:`newTerminal`,icon:`plus`,kind:`action`,order:30},{id:`host:right-files`,slot:`rightpanel.tabs`,labelKey:`openFiles`,icon:`folder`,kind:`view`,view:`files`,order:10},{id:`host:conv-rename`,slot:`contextmenu.session`,labelKey:`renameSession`,icon:`edit`,kind:`action`,context:`session`,order:1},{id:`host:conv-pin`,slot:`contextmenu.session`,labelKey:`pinConversation`,icon:`pin`,kind:`action`,context:`session`,order:2},{id:`host:conv-takeover`,slot:`contextmenu.session`,labelKey:`takeoverConversation`,icon:`chat`,kind:`action`,context:`session`,order:5},{id:`host:conv-dismiss-subagents`,slot:`contextmenu.session`,labelKey:`dismissFinishedSubagents`,icon:`x`,kind:`action`,context:`session`,order:10},{id:`host:conv-force-dismiss`,slot:`contextmenu.session`,labelKey:`forceDismissConversation`,icon:`x`,kind:`action`,context:`session`,order:20},{id:`host:conv-persist`,slot:`contextmenu.session`,labelKey:`persistSubagent`,icon:`save`,kind:`action`,context:`session`,order:25},{id:`host:conv-copy-id`,slot:`contextmenu.session`,labelKey:`copyConversationId`,icon:`copy`,kind:`action`,context:`session`,order:30},{id:`host:conv-copy-path`,slot:`contextmenu.session`,labelKey:`copyConversationPath`,icon:`copy`,kind:`action`,context:`session`,order:40},{id:`host:conv-copy-link`,slot:`contextmenu.session`,labelKey:`copyConversationLink`,icon:`link`,kind:`action`,context:`session`,order:45},{id:`host:conv-quote`,slot:`contextmenu.session`,labelKey:`quoteConversation`,icon:`chat`,kind:`action`,context:`session`,order:50},{id:`host:file-open`,slot:`contextmenu.file`,labelKey:`fileOpenPreview`,icon:`open`,kind:`action`,context:`file`,order:11,group:`open`},{id:`host:file-enter`,slot:`contextmenu.file`,labelKey:`fileEnterDir`,icon:`folder`,kind:`action`,context:`file`,order:12,group:`open`},{id:`host:file-download`,slot:`contextmenu.file`,labelKey:`downloadFile`,icon:`download`,kind:`action`,context:`file`,order:13,group:`open`},{id:`host:file-compress`,slot:`contextmenu.file`,labelKey:`fileCompress`,icon:`file`,kind:`action`,context:`file`,order:16,group:`archive`},{id:`host:file-extract`,slot:`contextmenu.file`,labelKey:`fileExtract`,icon:`folder`,kind:`action`,context:`file`,order:17,group:`archive`},{id:`host:file-compress-download`,slot:`contextmenu.file`,labelKey:`fileCompressDownload`,icon:`download`,kind:`action`,context:`file`,order:18,group:`archive`},{id:`host:file-upload-folder`,slot:`contextmenu.file`,labelKey:`fileUploadFolder`,icon:`upload`,kind:`action`,context:`file`,order:25,group:`new`},{id:`host:file-open-project`,slot:`contextmenu.file`,labelKey:`openAsProject`,icon:`folder`,kind:`action`,context:`file`,order:14,group:`open`},{id:`host:file-add-root`,slot:`contextmenu.file`,labelKey:`addWorkspaceRoot`,icon:`folder`,kind:`action`,context:`file`,order:15,group:`open`},{id:`host:file-reveal`,slot:`contextmenu.file`,labelKey:`fileReveal`,icon:`folder`,kind:`action`,context:`file`,order:16,group:`open`},{id:`host:file-open-default`,slot:`contextmenu.file`,labelKey:`fileOpenDefault`,icon:`open`,kind:`action`,context:`file`,order:17,group:`open`},{id:`host:file-new-file`,slot:`contextmenu.file`,labelKey:`fileNewFile`,icon:`file`,kind:`action`,context:`file`,order:21,group:`new`},{id:`host:file-new-dir`,slot:`contextmenu.file`,labelKey:`fileNewDir`,icon:`folder`,kind:`action`,context:`file`,order:22,group:`new`},{id:`host:file-upload`,slot:`contextmenu.file`,labelKey:`uploadToFolder`,icon:`upload`,kind:`action`,context:`file`,order:23,group:`new`},{id:`host:file-paste`,slot:`contextmenu.file`,labelKey:`filePaste`,icon:`paste`,kind:`action`,context:`file`,order:24,group:`new`},{id:`host:file-attach-ref`,slot:`contextmenu.file`,labelKey:`referenceTip`,icon:`link`,kind:`action`,context:`file`,order:32,group:`chat`},{id:`host:file-attach-folder`,slot:`contextmenu.file`,labelKey:`linkFolderTip`,icon:`link`,kind:`action`,context:`file`,order:33,group:`chat`},{id:`host:file-rename`,slot:`contextmenu.file`,labelKey:`fileRename`,icon:`edit`,kind:`action`,context:`file`,order:41,group:`edit`},{id:`host:file-duplicate`,slot:`contextmenu.file`,labelKey:`fileDuplicate`,icon:`copy`,kind:`action`,context:`file`,order:42,group:`edit`},{id:`host:file-cut`,slot:`contextmenu.file`,labelKey:`fileCut`,icon:`cut`,kind:`action`,context:`file`,order:43,group:`edit`},{id:`host:file-copy`,slot:`contextmenu.file`,labelKey:`fileCopyEntry`,icon:`copy`,kind:`action`,context:`file`,order:44,group:`edit`},{id:`host:file-copy-name`,slot:`contextmenu.file`,labelKey:`copyName`,icon:`copy`,kind:`action`,context:`file`,order:51,group:`clipboard`},{id:`host:file-copy-path`,slot:`contextmenu.file`,labelKey:`copyPath`,icon:`copy`,kind:`action`,context:`file`,order:52,group:`clipboard`},{id:`host:file-copy-rel`,slot:`contextmenu.file`,labelKey:`fileCopyRelPath`,icon:`copy`,kind:`action`,context:`file`,order:53,group:`clipboard`},{id:`host:file-refresh`,slot:`contextmenu.file`,labelKey:`fileRefresh`,icon:`refresh`,kind:`action`,context:`file`,order:54,group:`clipboard`},{id:`host:file-delete`,slot:`contextmenu.file`,labelKey:`fileDelete`,icon:`trash`,kind:`action`,context:`file`,order:61,group:`danger`},{id:`host:msg-ctx-copy-markdown`,slot:`contextmenu.message`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,context:`message`,order:10,group:`copy`},{id:`host:msg-ctx-copy-text`,slot:`contextmenu.message`,labelKey:`copyText`,icon:`text`,kind:`action`,context:`message`,order:11,group:`copy`},{id:`host:msg-ctx-copy-image`,slot:`contextmenu.message`,labelKey:`copyImage`,icon:`image`,kind:`action`,context:`message`,order:12,group:`copy`},{id:`host:msg-ctx-copy-link`,slot:`contextmenu.message`,labelKey:`copyMessageLink`,icon:`link`,kind:`action`,context:`message`,order:13,group:`copy`},{id:`host:msg-ctx-reask`,slot:`contextmenu.message`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,context:`message`,order:19,group:`action`},{id:`host:msg-ctx-edit-reask`,slot:`contextmenu.message`,labelKey:`editReask`,icon:`edit`,kind:`action`,context:`message`,order:20,group:`action`},{id:`host:msg-ctx-fork`,slot:`contextmenu.message`,labelKey:`forkSession`,icon:`branch`,kind:`action`,context:`message`,order:21,group:`action`},{id:`host:msg-ctx-rollback`,slot:`contextmenu.message`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,context:`message`,order:22,group:`action`},{id:`host:msg-ctx-speak`,slot:`contextmenu.message`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,context:`message`,order:23,group:`action`},{id:`host:tool-info`,slot:`contextmenu.toolcall`,labelKey:`toolInfoMenuLabel`,icon:`info`,kind:`action`,context:`toolcall`,order:10}],ei=`__view`,ti=new Set([`host:settings`,`host:history`,`host:files`]),ni=new Set([`host:history`,`host:files`]);function ri(e){return`${e}:${ei}`}function ii(e){return e.source.startsWith(`plugin:`)?e.id===ri(e.source.slice(7)):!1}function ai(e,t,n){let r=ri(t),i=(e?.hidden??[]).filter(e=>e!==r),a=(e?.shown??[]).filter(e=>e!==r);return n?a.push(r):i.push(r),{...e,hidden:i,shown:a}}function oi(e,t){let n=t.map(ri),r=new Set(n),i=(e?.order??[]).filter(e=>!r.has(e));return{...e,order:[...i,...n]}}var si=`host:brand`,ci=[`host:brand-logo`,`host:brand-name`];function li(e){if(!((e.hidden??[]).some(e=>ci.includes(e))||(e.shown??[]).some(e=>ci.includes(e))||(e.order??[]).some(e=>ci.includes(e))||ci.some(t=>e.align?.[t]!==void 0)||ci.some(t=>e.groups?.[t]!==void 0)||ci.some(t=>e.labels?.[t]!==void 0)||ci.some(t=>e.slots?.[t]!==void 0)))return e;let t=e=>{if(!e)return;let t=[];for(let n of e){let e=ci.includes(n)?si:n;t.includes(e)||t.push(e)}return t},n=(e,t)=>{if(!e)return;let n={};for(let[t,r]of Object.entries(e))ci.includes(t)||(n[t]=r);if(n[si]===void 0){let r=t?e[ci[0]]??e[ci[1]]:e[ci[1]]??e[ci[0]];r!==void 0&&(n[si]=r)}return n},r=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ci.includes(n)||(t[n]=r);if(t[si]===void 0){let n=e[ci[0]]??e[ci[1]];n!==void 0&&(t[si]=n)}return t},i=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ci.includes(n)||(t[n]=r);if(t[si]===void 0){let n=e[ci[0]]??e[ci[1]];n!==void 0&&(t[si]=n)}return t};return{...e,...e.hidden?{hidden:t(e.hidden)}:{},...e.shown?{shown:t(e.shown)}:{},...e.order?{order:t(e.order)}:{},...e.groups?{groups:n(e.groups,!0)}:{},...e.labels?{labels:n(e.labels,!1)}:{},...e.align?{align:r(e.align)}:{},...e.slots?{slots:i(e.slots)}:{}}}function ui(e){return e.map(e=>{if(e.view===!1)return e;let t=e.ui?.items??[];if(t.some(e=>e.id===`__view`))return e;let n={id:ei,slot:`topbar.primary`,label:e.name,...e.icon?{icon:e.icon}:{},...e.iconSvg?{iconSvg:e.iconSvg}:{},kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!0};return{...e,ui:{items:[...t,n],arrange:e.ui?.arrange??[]}}})}function di(e){return typeof e==`string`&&Yr.includes(e)}function fi(e,t){return t?e.label:e.labelEn??e.label}function pi(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function mi(e,t,n,r,i){let a=`${e}#${r.id}`,o=hi(a,t,n,r.children,i),s=pi(r,i),c=gi(r.options,i),l=_i(r.progress);return{id:a,slot:t,source:n,label:fi(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??`action`,...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...l===void 0?{}:{progress:l},...r.when?{when:r.when}:{},...c?{options:c}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[]}}function hi(e,t,n,r,i){return r?.length?r.map((r,a)=>({entry:mi(e,t,n,r,i),index:a})).sort((e,t)=>e.entry.order===t.entry.order?e.index-t.index:e.entry.order-t.entry.order).map(e=>e.entry):[]}function gi(e,t){if(e?.length)return e.slice(0,32).map(e=>({value:e.value,label:t?e.label??e.labelEn??e.value:e.labelEn??e.label??e.value}))}function _i(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function vi(e,t,n,r,i,a){let o=hi(e,t,n,r.children,i),s=pi(r,i),c=_i(r.progress),l=gi(r.options,i);return{id:e,slot:t,source:n,label:fi(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??(t===`settings.pages`?`page`:`action`),...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:r.align??`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...c===void 0?{}:{progress:c},...l?{options:l}:{},...r.when?{when:r.when}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[],seq:a}}function yi(e,t){return[...e].sort((e,n)=>{let r=t.get(e.id),i=t.get(n.id);return r!==void 0||i!==void 0?r!==void 0&&i!==void 0?r-i:r===void 0?1:-1:e.order===n.order?e.seq-n.seq:e.order-n.order})}function bi(e,t){let n=e.filter(e=>ii(e)&&!t.has(e.id));if(n.length===0)return e;let r=e.filter(e=>!ii(e)||t.has(e.id)),i=[`host:git`,`host:terminal`,`host:chat`].map(e=>r.findIndex(t=>t.id===e)).find(e=>e>=0)??-1,a=r.findIndex(e=>e.id===`host:plugins`),o=i+1;return a>=o&&(o=a),o=Math.max(0,Math.min(o,r.length)),[...r.slice(0,o),...n,...r.slice(o)]}function xi(e,t){let n=H(t.locale),r=new Set(t.disabledPlugins??[]),i=li(t.layout??{}),a=e=>{t.diagnostics?.push({level:e.level??`warn`,...e})},o=new Map,s=0;for(let e of $r)o.set(e.id,{id:e.id,slot:e.slot,source:`host`,label:t.t(e.labelKey),labelKey:e.labelKey,...e.icon?{icon:e.icon}:{},kind:e.kind,...e.view?{view:e.view}:{},...e.group?{group:e.group}:{},order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[],seq:s++});for(let t of e){if(r.has(t.id)){let e=t.ui?.items?.length??0,n=t.ui?.arrange?.length??0;(e>0||n>0)&&a({level:`info`,pluginId:t.id,message:`plugin "${t.id}" is disabled by the user — its ${e} UI item(s) are not rendered`});continue}if(t.error){a({level:`error`,pluginId:t.id,message:`plugin "${t.id}" failed to activate (${t.error}) — its UI items are not rendered`});continue}let e=`plugin:${t.id}`;for(let r of t.ui?.items??[]){if(!di(r.slot)){a({pluginId:t.id,entryId:r.id,message:`item "${t.id}:${r.id}" declares unknown slot "${String(r.slot)}" — dropped (valid slots: see docs/architecture-plugins.md)`});continue}if(r.slot===`leftpanel.sections`&&r.kind!==`view`){a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" targets leftpanel.sections: only kind="view" (a plugin section) is accepted — dropped`});continue}if(r.kind&&!qr.has(r.kind)&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares unknown kind "${r.kind}" — the render layer falls back to a plain button`}),Array.isArray(r.when))for(let e of r.when)Jr.has(e)||a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares when:"${e}" which the host does not know — it is ignored (the item still renders)`});else r.when!==void 0&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" has a non-array "when" — ignored`});let i=`${t.id}:${r.id}`,c=o.get(i);c&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item id "${r.id}" is declared more than once — the later declaration wins (order/visibility are inherited from the first)`}),o.set(i,vi(i,r.slot,e,r,n,c?.seq??s++))}}for(let t of e)if(!(t.error||r.has(t.id)))for(let e of t.ui?.arrange??[]){let n=o.get(e.id);Ci(o,e,t.id),n||a({pluginId:t.id,entryId:e.id,message:`arrange target "${e.id}" does not exist — op ignored (is the providing plugin installed / not disabled?)`})}let c=new Map,l=(e,t)=>{let n=c.get(e)??[];n.includes(t)||n.push(t),c.set(e,n)};for(let e of i.hidden??[]){let t=o.get(e);t&&(t.hidden=!0,l(e,`hidden`))}for(let e of i.shown??[]){let t=o.get(e);t&&(t.hidden=!1,l(e,`hidden`))}for(let[e,t]of Object.entries(i.groups??{})){let n=o.get(e);n&&(n.group=t,l(e,`group`))}for(let[e,t]of Object.entries(i.align??{})){let n=o.get(e);!n||t!==`start`&&t!==`center`&&t!==`end`||(n.align=t,l(e,`align`))}for(let[e,t]of Object.entries(i.labels??{})){let n=o.get(e);n&&(n.label=t,n.labelExplicit=!0,l(e,`label`))}for(let[e,t]of Object.entries(i.slots??{})){let n=o.get(e);n&&di(t)&&n.slot!==t&&(n.movedFrom=n.movedFrom??n.slot,n.slot=t,l(e,`slot`))}for(let e of ti){let t=o.get(e);t&&(i.slots?.[e]||(t.slot=`topbar.primary`),t.hidden=!1)}let u=new Map;(i.order??[]).forEach((e,t)=>{o.has(e)&&(u.has(e)||u.set(e,t),l(e,`order`))});for(let e of Object.values(Lr)){let t=o.get(e);t&&t.slot!==`leftpanel.sections`&&(a({entryId:e,slot:t.slot,message:`"${e}" must stay in leftpanel.sections — the move is ignored`}),t.slot=`leftpanel.sections`,delete t.movedFrom)}let d=new Map;for(let e of Yr)d.set(e,[]);for(let e of o.values())d.get(e.slot)?.push(e);let f={};for(let e of Yr){let t=yi(d.get(e)??[],u),n=Qr(e===`topbar.primary`?bi(t,u):t,Zr(e));if(n.winner&&n.conflicts.length>0)for(let t of n.conflicts)a({level:`error`,pluginId:t.source.startsWith(`plugin:`)?t.source.slice(7):void 0,entryId:t.id,slot:e,message:`slot "${e}" is single-cardinality; "${n.winner.id}" won and "${t.id}" was hidden`});f[e]=n.entries.map(e=>Si(e,c.get(e.id)??[]))}return f}function Si(e,t){let n={...e,userOverrides:t};return delete n.seq,n}function Ci(e,t,n){let r=e.get(t.id);if(!r)return;let i=!1;t.hide!==void 0&&(r.hidden=t.hide,i=!0),t.group!==void 0&&(r.group=t.group,i=!0),t.order!==void 0&&(r.order=t.order,i=!0),t.align!==void 0&&(r.align=t.align,i=!0),t.label!==void 0&&(r.label=t.label,r.labelExplicit=!0,i=!0),t.hint!==void 0&&(r.hint=t.hint,i=!0),t.icon!==void 0&&(r.icon=t.icon,i=!0),t.iconSvg!==void 0&&(r.iconSvg=t.iconSvg||void 0,i=!0),t.slot!==void 0&&di(t.slot)&&t.slot!==r.slot&&(r.movedFrom=r.movedFrom??r.slot,r.slot=t.slot,i=!0),i&&r.source!==`plugin:${n}`&&!r.arrangedBy.includes(n)&&r.arrangedBy.push(n)}function wi(e){let t=[],n=[],r=[];for(let i of e)i.align===`end`?r.push(i):i.align===`center`?n.push(i):t.push(i);return{start:t,center:n,end:r}}function Ti(e,t){let n=e??{},r={},i=t===si?[t,...ci]:[t],a=(n.hidden??[]).filter(e=>!i.includes(e)),o=(n.shown??[]).filter(e=>!i.includes(e)),s=(n.order??[]).filter(e=>!i.includes(e));a.length>0&&(r.hidden=a),o.length>0&&(r.shown=o),s.length>0&&(r.order=s);let c=Di(n.groups,t),l=Di(n.labels,t),u=Di(n.align,t),d=Di(n.slots,t);if(t===si)for(let e of ci)c=Di(c,e),l=Di(l,e),u=Di(u,e),d=Di(d,e);return c&&(r.groups=c),l&&(r.labels=l),u&&(r.align=u),d&&(r.slots=d),n.topbarText!==void 0&&(r.topbarText=n.topbarText),n.sideDockFloat!==void 0&&(r.sideDockFloat=n.sideDockFloat),r}function Ei(){return{}}function Di(e,t){if(!e)return;let n={},r=!1;for(let[i,a]of Object.entries(e))i!==t&&(n[i]=a,r=!0);return r?n:void 0}var Oi=new Set([`host:files`]);function ki(e,t){let n=e=>e===`center`?1:e===`end`?2:0;return[...e].sort((e,r)=>n(e.align)-n(r.align)||t(e.id)-t(r.id))}function Ai(e,t,n,r,i=new Set){let a=new Set;if(!Number.isFinite(t)||t<=0)return a;let o=e.filter(e=>i.has(e.id)&&e.width>0).reduce((e,t)=>e+t.width+n,0),s=Math.max(0,t-Math.max(0,r)-o),c=0,l=!1;for(let t of e){if(!(t.width>0)||i.has(t.id))continue;let e=t.width+n;if(l||c+e>s){l=!0,a.add(t.id);continue}c+=e}return a}var ji=null,Mi=new Set;function Ni(){for(let e of Mi)e()}function Pi(e){ji={x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,slot:e.slot,target:e.target??{id:``},entries:Array.isArray(e.entries)?e.entries:[],...typeof e.onHostAction==`function`?{onHostAction:e.onHostAction}:{}},Ni()}function Fi(){ji!==null&&(ji=null,Ni())}function Ii(e){return Mi.add(e),()=>{Mi.delete(e)}}function Li(){return ji}function Ri(){return(0,Q.useSyncExternalStore)(Ii,Li,Li)}function zi(e){return Number.isFinite(e)?e:0}function Bi(e,t,n,r,i,a){let o=Math.max(0,zi(n)),s=Math.max(0,zi(r)),c=Math.max(8,zi(i)-o-8),l=Math.max(8,zi(a)-s-8);return{x:Math.min(Math.max(8,zi(e)),c),y:Math.min(Math.max(8,zi(t)),l)}}function Vi(e,t){let n=String(t?.kind??``);if(e===`contextmenu.file`)return{"file.isDir":n===`dir`||n===`list`&&t?.id!==`@root`,"file.isFile":n===`file`};if(e===`contextmenu.session`)return{"session.isRunning":n===`running`};if(e===`contextmenu.message`){let e=!1;try{let t=window.getSelection?.();e=!!t&&!t.isCollapsed&&t.toString().trim().length>0}catch{e=!1}return{"message.hasSelection":e}}return{}}function Hi(e,t){if(!Array.isArray(e)||e.length===0)return!1;for(let n of e){if(typeof n!=`string`||!n)continue;let e=n.trim();if(e===`disabled`||e===`never`)return!0;if(e!==`always`){if(e.startsWith(`!`)){let n=e.slice(1).trim();if(!n)continue;if(!t||t[n]!==!0)return!0;continue}if(t&&t[e]===!1)return!0}}return!1}function Ui(e,t){return!e||Hi(e.when,t)}function Wi(e){let t=new Map;return{items:(Array.isArray(e)?e:[]).map(e=>{if(!e||e.kind!==`select`||!e.options?.length||e.children?.length)return e;let n=e.options.map((t,n)=>({id:`${e.id}#${n}`,slot:e.slot,source:e.source,label:t.label,kind:`action`,order:100,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));return n.forEach((n,r)=>t.set(n.id,{parent:e,value:e.options[r].value})),{...e,kind:`menu`,children:n}}),selectParents:t}}function Gi(e){if(!Array.isArray(e)||e.length===0)return[];let t=e.filter(e=>e&&e.hidden!==!0),n=t.filter(e=>e.kind!==`divider`),r=new Map,i=new Map;n.forEach((e,t)=>{let n=e.group??``;r.has(n)||r.set(n,t);let a=Number.isFinite(e.order)?e.order:100,o=i.get(n);(o===void 0||a<o)&&i.set(n,a)});let a=[...r.keys()].sort((e,t)=>{let n=i.get(e)??100,a=i.get(t)??100;return n===a?(r.get(e)??0)-(r.get(t)??0):n-a}),o=new Map(a.map((e,t)=>[e,t])),s=new Map;n.forEach((e,t)=>s.set(e,t));let c=[...n].sort((e,t)=>{let n=o.get(e.group??``)??0,r=o.get(t.group??``)??0;if(n!==r)return n-r;let i=Number.isFinite(e.order)?e.order:100,a=Number.isFinite(t.order)?t.order:100;return i===a?(s.get(e)??0)-(s.get(t)??0):i-a}),l=new Map;t.forEach((e,n)=>{if(e.kind!==`divider`)return;let r=t.slice(n+1).find(e=>e.kind!==`divider`);if(!r)return;let i=l.get(r)??[];i.push(e),l.set(r,i)});let u=[];for(let e of c){for(let t of l.get(e)??[])u.push(t);u.push(e)}return u}function Ki(e){let t=[],n=null,r=!1;return e.forEach((e,i)=>{if(!e||e.kind===`divider`){r=!0;return}let a=e.group??``;n!==null&&(r||a!==n)&&t.push({kind:`sep`,key:`sep:${i}`}),t.push({kind:`item`,key:`${e.id}#${i}`,index:i,entry:e}),n=a,r=!1}),t}function qi(e,t){return!e||e.kind===`divider`||e.hidden===!0?!1:!Ui(e,t)}function Ji(e,t,n,r){let i=Array.isArray(e)?e.length:0;if(i===0)return-1;let a=n>=0?1:-1,o=Number.isFinite(t)?Math.trunc(t):-1;(o<0||o>=i)&&(o=a>0?-1:i);for(let t=0;t<i;t++)if(o=(o+a+i)%i,qi(e[o],r))return o;return-1}var Yi={menu:`☰`,folder:`📁`,plus:`+`,chat:`💬`,terminal:`▙`,git:`⎇`,search:`🔍`,browser:`🌐`,layers:`🗂`,settings:`⚙`,sound:`🔊`,globe:`🌍`,sun:`☀`,download:`⤓`,github:`⌗`,x:`✕`,upload:`⬆`,copy:`⧉`,cut:`✂`,paste:`📋`,trash:`🗑`,file:`📄`,open:`↗`,refresh:`⟳`,link:`🔗`,edit:`✎`,dot:`●`,info:`ⓘ`,cpu:`▣`,gauge:`▤`,coins:`◉`,database:`▥`,message:`✉`,activity:`〜`,markdown:`📄`,text:`≡`,image:`🖼`,branch:`⚚`,undo:`↺`,pin:`📌`,volume:`🔊`};function Xi(e){let t=(e??``).trim();return t?Yi[t.toLowerCase()]||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:``):``}function Zi(e,t,n){let r=Math.max(8,e.left-8),i=e.bottom+8;return r+t.width>n.width-8&&(r=Math.max(8,e.right+8-t.width)),i+t.height>n.height-8&&(i=Math.max(8,e.top-8-t.height)),{left:r,top:i}}function Qi(){return typeof window<`u`&&window.matchMedia?.(`(hover: hover) and (pointer: fine)`)?.matches===!0}function $i(e){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)({left:0,top:0});return(0,Q.useEffect)(()=>{if(!r)return;let e=n.current,i=t.current;if(!e||!i)return;let a=e.getBoundingClientRect(),s=Zi(i.getBoundingClientRect(),a,{width:window.innerWidth,height:window.innerHeight});o(e=>e.left===s.left&&e.top===s.top?e:s)},[r,e]),(0,Q.useEffect)(()=>{if(!r)return;let e=0,a=()=>{cancelAnimationFrame(e),e=requestAnimationFrame(()=>{let e=t.current,r=n.current;if(!e||!r)return;let a=e.getBoundingClientRect();if(a.bottom<0||a.top>window.innerHeight||a.right<0||a.left>window.innerWidth){i(!1);return}let s=Zi(a,r.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});o(e=>e.left===s.left&&e.top===s.top?e:s)})};return window.addEventListener(`scroll`,a,!0),window.addEventListener(`resize`,a),()=>{cancelAnimationFrame(e),window.removeEventListener(`scroll`,a,!0),window.removeEventListener(`resize`,a)}},[r]),{anchorRef:t,show:()=>{let e=t.current?.getBoundingClientRect();e&&(o({left:Math.max(8,e.left-8),top:e.bottom+8}),i(!0))},hide:()=>i(!1),onKeyDown:e=>{e.key===`Escape`&&e.target.blur()},tipPortal:r&&(0,bn.createPortal)((0,$.jsx)(`span`,{ref:n,className:`set-tip-bubble open`,role:`tooltip`,style:{position:`fixed`,left:a.left,top:a.top},children:e}),document.body)}}function ea({text:e}){let{anchorRef:t,show:n,hide:r,onKeyDown:i,tipPortal:a}=$i(e);return(0,$.jsxs)(`span`,{ref:t,className:`set-tip`,tabIndex:0,"aria-label":e,onMouseEnter:n,onMouseLeave:r,onFocus:n,onBlur:r,onKeyDown:i,children:[(0,$.jsx)(K,{}),a]})}function ta({tip:e,children:t,onMouseEnter:n,onMouseLeave:r,onFocus:i,onBlur:a,onKeyDown:o,...s}){let{anchorRef:c,show:l,hide:u,onKeyDown:d,tipPortal:f}=$i(e);return(0,$.jsxs)(`button`,{ref:c,type:`button`,"aria-label":s[`aria-label`]??e,...s,onMouseEnter:e=>{l(),n?.(e)},onMouseLeave:e=>{u(),r?.(e)},onFocus:e=>{l(),i?.(e)},onBlur:e=>{u(),a?.(e)},onKeyDown:e=>{d(e),o?.(e)},children:[t,f]})}var na=new Set;function ra(e){return na.add(e),()=>{na.delete(e)}}function ia(e){for(let t of na)try{t(e)}catch(e){console.error(`[remote-ssh-client] listener error:`,e)}}function aa(e,t,n,r){return`ssh://${e}@${t}:${n}${r.startsWith(`/`)?r:`/${r}`}`}function oa(e){return!!(e&&e.startsWith(`ssh://`))}function sa(e){if(!oa(e))return null;let t=/^ssh:\/\/([^@]+)@([^:]+):(\d+)(\/.*)$/.exec(e);return t?{username:t[1],host:t[2],port:parseInt(t[3],10),remotePath:t[4]}:null}var ca=1;function la(e){let t=`probe_${Date.now()}_${ca++}`;return new Promise(n=>{let r=ra(e=>{e.type===`remote_ssh_probe_result`&&e.reqId===t&&(r(),n({ok:e.ok,connectionId:e.connectionId,error:e.error,system:e.system,tools:e.tools,packageManager:e.packageManager,suggestedInstall:e.suggestedInstall}))});Z({type:`remote_ssh_probe`,reqId:t,params:e})||(r(),n({ok:!1,error:`WebSocket 连接不可用,请稍候重试`}))})}function ua(e,t){let n=`listdir_${Date.now()}_${ca++}`;return new Promise(r=>{let i=ra(e=>{e.type===`remote_ssh_list_dir_result`&&e.reqId===n&&(i(),r({ok:e.ok,connectionId:e.connectionId,path:e.path,parentPath:e.parentPath,items:e.items,error:e.error}))});Z({type:`remote_ssh_list_dir`,reqId:n,connectionId:e,path:t})||(i(),r({ok:!1,connectionId:e,path:t||`/`,items:[],error:`WebSocket 连接不可用`}))})}function da(e,t){let n=`install_${Date.now()}_${ca++}`;return new Promise(r=>{let i=ra(e=>{e.type===`remote_ssh_install_result`&&e.reqId===n&&(i(),r({ok:e.ok,connectionId:e.connectionId,tool:e.tool,output:e.output,error:e.error}))});Z({type:`remote_ssh_install_tools`,reqId:n,connectionId:e,tools:t})||(i(),r({ok:!1,connectionId:e,tool:t[0]||``,error:`WebSocket 连接不可用`}))})}function fa(){let e=`profiles_${Date.now()}_${ca++}`;return new Promise(t=>{let n=ra(r=>{r.type===`remote_ssh_profiles_result`&&r.reqId===e&&(n(),t(r.profiles))});Z({type:`remote_ssh_list_profiles`,reqId:e})||(n(),t([]))})}function pa(e){Z({type:`remote_ssh_delete_profile`,name:e})}var ma=`@root`,ha=e=>e.endsWith(`/`)?e:e+`/`;function ga(e,t){let n=t.trim(),r=e.replace(/\\/g,`/`);return r.endsWith(`/`)?r+n:(/^[A-Za-z]:$/.test(r),r+`/`+n)}function _a(e){let t=e.trim();return!(!t||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`))}var va=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;if(t===`@root`||t===`/`)return null;let n=t.lastIndexOf(`/`);if(n<0)return/^[A-Za-z]:$/.test(t)?ma:null;if(n===0)return`/`;let r=t.slice(0,n);return/^[A-Za-z]:$/.test(r)?r+`/`:r};function ya({currentCwd:e,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,mode:o=`folder`,onCreateProject:s,className:c,backdropClassName:l,role:u,ariaLabel:d,localOnly:f=!1}){let p=V(),m=H(Se()),h=rn().remoteSsh&&!f,_=en(`homeDir`),v=en(`desktopDir`),[b,x]=(0,Q.useState)(()=>h&&oa(e)?`remote`:`local`);(0,Q.useEffect)(()=>{!h&&b===`remote`&&x(`local`)},[h,b]);let[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(-1),P=(0,Q.useRef)(null),ee=(0,Q.useRef)(null),[F,te]=(0,Q.useState)([]),[ne,re]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(`22`),[ie,ae]=(0,Q.useState)(``),[oe,se]=(0,Q.useState)(`password`),[ce,ue]=(0,Q.useState)(``),[de,B]=(0,Q.useState)(`~/.ssh/id_rsa`),[fe,pe]=(0,Q.useState)(!0),[me,ge]=(0,Q.useState)(``),[U,W]=(0,Q.useState)(!1),[G,_e]=(0,Q.useState)(null),[K,q]=(0,Q.useState)(null),[J,ve]=(0,Q.useState)(null),[Y,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)([]),[Ce,Te]=(0,Q.useState)(!1),[Ee,X]=(0,Q.useState)(`/`),[Oe,Ae]=(0,Q.useState)(`/`),[je,Me]=(0,Q.useState)([]),[Ne,Pe]=(0,Q.useState)(!1),[Fe,Ie]=(0,Q.useState)(!1),[Le,Re]=(0,Q.useState)(``),[ze,Ve]=(0,Q.useState)(null),He=n.filter(e=>e.type===`dir`);(0,Q.useEffect)(()=>{if(oa(e)){let t=sa(e);t&&(re(t.host),L(String(t.port)),ae(t.username),X(t.remotePath),Ae(t.remotePath))}else{let t=(e||``).replace(/\\/g,`/`);C(t),T(t)}D(!1),k(``),j(null),N(-1)},[e]),(0,Q.useEffect)(()=>{let e=requestAnimationFrame(()=>{P.current?.focus()});return()=>cancelAnimationFrame(e)},[b]),(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(E||Fe?(D(!1),k(``),j(null),Ie(!1),Re(``),Ve(null)):i())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[E,Fe,i]),(0,Q.useEffect)(()=>{if(b!==`local`)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:ha(S)})},60);return()=>clearTimeout(e)},[S,b]),(0,Q.useEffect)(()=>{if(b!==`local`||w===S)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:w})},150);return()=>clearTimeout(e)},[w,S,b]);let Ue=e=>{let t=e.trim();t&&t!==`@root`&&a(t)},We=e=>{C(e),T(e),N(-1),j(null)},Ge=()=>{let e=O.trim();if(e&&S!==`@root`){if(o===`project`){if(!_a(e)){j(p(`invalidProjectName`));return}let t=ga(S,e);s?s(t):(Z({type:`make_dir`,path:t}),a(t)),D(!1),k(``),j(null),i()}else Z({type:`make_dir`,path:`${ha(S)}${e}`}),setTimeout(()=>{Z({type:`complete_path`,path:ha(S)})},80),k(``),D(!1)}},Ke=e=>{if(e.key===`Escape`)e.stopPropagation(),E?(D(!1),k(``),j(null)):i();else if(e.key===`Enter`&&!e.nativeEvent.isComposing)Ue(w);else if(e.key===`Tab`){if(He.length===0)return;e.preventDefault();let t=M>=0?(M+1)%He.length:0;N(t),T(He[t].path),C(He[t].path)}},qe=async t=>{let n=(t?.host??ne).trim(),r=t?.port??(parseInt(I,10)||22),i=(t?.username??ie).trim();if(!n||!i){_e(m?`请填写主机地址和用户名`:`Please provide host address and username`);return}W(!0),_e(null);let a=await la({host:n,port:r,username:i,auth:t?.auth??(oe===`password`?{type:`password`,password:ce}:oe===`key`?{type:`key`,privateKeyPath:de}:{type:`agent`}),saveProfile:fe,profileName:t?.profileName||me.trim()||void 0});if(W(!1),!a.ok||!a.connectionId){_e(a.error||(m?`连接远程服务器失败`:`Failed to connect to remote server`));return}q(a.connectionId),ve(a.system??null),ye(a.tools??null),xe(a.suggestedInstall??[]);let o=oa(e)?sa(e)?.remotePath:null,s=o&&o!==`/`?o:a.system?.homeDir||`/`;X(s),Ae(s),Ye(a.connectionId,s),fa().then(e=>te(e))},Je=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{b===`remote`&&fa().then(t=>{if(te(t),!Je.current&&!K&&!U&&oa(e)){let n=sa(e);if(n){let e=t.find(e=>e.host===n.host&&(e.username===n.username||!n.username)&&(e.port===n.port||!n.port&&e.port===22))||t.find(e=>e.host===n.host&&e.username===n.username)||t.find(e=>e.host===n.host);e&&(Je.current=!0,re(e.host),L(String(e.port)),ae(e.username),se(e.authType),e.privateKeyPath&&B(e.privateKeyPath),qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}}))}}})},[b,e,K,U]);let Ye=async(e,t)=>{Pe(!0),_e(null);let n=await ua(e,t);Pe(!1),n.ok?(X(n.path),Ae(n.path),Me(n.items)):_e(n.error||(m?`读取远程目录失败`:`Failed to read remote directory`))},Ze=async e=>{if(!K)return;Te(!0),_e(null);let t=await da(K,[e]);Te(!1),t.ok?(xe(t=>t.filter(t=>t!==e)),Y&&e===`git`&&ye({...Y,git:{installed:!0,version:m?`已安装`:`Installed`}})):_e(t.error||(m?`安装 ${e} 失败,可能需要远端 sudo 权限`:`Failed to install ${e}, remote sudo permissions may be required`))},Qe=e=>{let t=parseInt(I,10)||22,n=J?.homeDir||`/`,r=(e||``).trim()||Ee||`/`;r===`~`?r=n:(r.startsWith(`~/`)||r.startsWith(`~\\`))&&(r=`${n.replace(/\/+$/,``)}/${r.slice(2).replace(/\\/g,`/`)}`),a(aa(ie,ne,t,r)),i()},$e=()=>{let e=Le.trim();if(!e||!K)return;if(!_a(e)){Ve(p(`invalidProjectName`));return}let t=parseInt(I,10)||22,n=Ee.replace(/\/+$/,``)||`/`,r=n===`/`?`/${e}`:`${n}/${e}`,c=aa(ie,ne,t,r);if(o===`project`)s?s(c):(Z({type:`make_dir`,path:c}),a(c)),Ie(!1),Re(``),Ve(null),i();else{Z({type:`make_dir`,path:c}),Re(``),Ie(!1),Ve(null);let e=K,t=Ee;setTimeout(()=>{Ye(e,t)},300)}},et=va(S),tt=va(Ee),nt=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);return/^[A-Za-z]:/.test(t)?t.toLowerCase():t},rt=nt(S),it=!!S&&S!==`@root`&&rt!==nt(e)&&!r.some(e=>nt(e)===rt);return(0,bn.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`status-cwd-backdrop ${l??``}`.trim(),onClick:i,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation()}),(0,$.jsxs)(`div`,{className:`cwd-picker ${c??``}`.trim(),role:u,"aria-label":d,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[h?(0,$.jsxs)(`div`,{className:`cwd-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${b===`local`?`active`:``}`,onClick:()=>x(`local`),children:[`💻 `,p(`workspaceModeLocal`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${b===`remote`?`active`:``}`,onClick:()=>x(`remote`),children:[`🌐 `,p(`workspaceModeRemote`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:p(`close`),"aria-label":p(`close`),onClick:i,children:(0,$.jsx)(R,{})})]}):(0,$.jsxs)(`div`,{className:`cwd-mode-tabs cwd-mode-tabs-single`,children:[(0,$.jsxs)(`div`,{className:`cwd-mode-tab active`,style:{cursor:`default`},children:[`💻 `,p(`workspaceModeLocal`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:p(`close`),"aria-label":p(`close`),onClick:i,children:(0,$.jsx)(R,{})})]}),b===`local`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:S===`@root`?p(`computer`):S,children:[S===`@root`?(0,$.jsx)(t,{}):(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:S===`@root`?p(`computer`):S})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":p(`projectPickerTitle`),children:[(0,$.jsx)(ta,{className:`cwd-jump ${S===`@root`?`active`:``}`,tip:p(`computer`),onClick:()=>We(`@root`),children:(0,$.jsx)(t,{})}),_!==``&&(0,$.jsx)(ta,{className:`cwd-jump ${nt(S)===nt(_)?`active`:``}`,tip:`${p(`homeDir`)} ${_}`,onClick:()=>We(_),children:(0,$.jsx)(Xe,{})}),v!==``&&(0,$.jsx)(ta,{className:`cwd-jump ${nt(S)===nt(v)?`active`:``}`,tip:`${p(`desktopDir`)} ${v}`,onClick:()=>We(v),children:(0,$.jsx)(st,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-sep`,"aria-hidden":`true`}),(0,$.jsx)(ta,{className:`cwd-jump tool-up`,tip:et?`${p(`cwdGoUp`)} · ${et}`:`${p(`cwdGoUp`)} · ${m?`已在顶层`:`already at top`}`,"aria-disabled":!et,onClick:()=>{et&&We(et)},children:(0,$.jsx)(De,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-root`,tip:it?p(`addWorkspaceRootHint`):S===`@root`?`${p(`addWorkspaceRoot`)} · ${m?`此电脑本身不是目录`:`This PC is not a directory`}`:rt===nt(e)?`${p(`addWorkspaceRoot`)} · ${m?`已是当前项目目录`:`Already the current project`}`:`${p(`addWorkspaceRoot`)} · ${m?`已在工作区根中`:`Already a workspace root`}`,"aria-disabled":!it,onClick:()=>{it&&Z({type:`set_workspace_roots`,roots:[...r,S]})},children:(0,$.jsx)(ke,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-new ${E?`active`:``}`,tip:S===`@root`?`${p(`cwdNewFolder`)} · ${m?`此电脑下不能新建`:`Cannot create here`}`:p(E?`cwdCancel`:`cwdNewFolder`),"aria-disabled":S===`@root`,onClick:()=>{S!==`@root`&&(E?(D(!1),k(``),j(null)):(k(``),j(null),D(!0)))},children:(0,$.jsx)(y,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`}),(0,$.jsx)(ta,{className:`cwd-jump primary tool-pick`,tip:S===`@root`?`${p(`cwdPickCurrent`)} · ${m?`此电脑不能作为工作目录`:`This PC cannot be a workspace`}`:`${p(`cwdPickCurrent`)} · ${S}`,"aria-disabled":S===`@root`,onClick:()=>Ue(S),children:(0,$.jsx)(z,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{ref:P,className:`status-cwd-input cwd-picker-input`,value:w,placeholder:p(`enterPath`),spellCheck:!1,onChange:e=>{T(e.target.value),N(-1)},onKeyDown:Ke}),w.trim()!==``&&w!==S&&(0,$.jsx)(ta,{className:`cwd-jump tool-enter`,tip:`${p(`cwdEnter`)} · ${w.trim()}`,onClick:()=>{C(w.trim()),N(-1)},children:(0,$.jsx)(he,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[et&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdGoUp`)} · ${et}`,onClick:()=>We(et),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),He.length===0&&!et&&(0,$.jsx)(`div`,{className:`cwd-empty`,children:p(`cwdEmpty`)}),He.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdEnter`)} ${e.path}`,onClick:()=>{C(e.path),T(e.path),N(-1)},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),(0,$.jsx)(ta,{className:`cwd-jump tool-choose`,tip:`${p(`cwdChoose`)} · ${e.path}`,onClick:()=>Ue(e.path),children:(0,$.jsx)(z,{})})]},e.path))]}),E&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{ref:ee,value:O,autoFocus:!0,spellCheck:!1,placeholder:p(`cwdNewName`),onChange:e=>{k(e.target.value),A&&j(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),Ge()):e.key===`Escape`&&(e.stopPropagation(),D(!1),k(``),j(null))}}),(0,$.jsx)(ta,{className:`cwd-jump primary`,tip:p(`cwdCreate`),onClick:Ge,children:(0,$.jsx)(z,{})}),(0,$.jsx)(ta,{className:`cwd-jump`,tip:p(`cwdCancel`),onClick:()=>{D(!1),k(``),j(null)},children:(0,$.jsx)(R,{})})]}),A&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:A})]})]}),b===`remote`&&(0,$.jsx)(`div`,{className:`cwd-ssh-container`,children:K?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-box`,children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-header`,children:[(0,$.jsxs)(`span`,{children:[`🌐 `,ie,`@`,ne,` (`,J?.os,` `,J?.arch,`)`]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,onClick:()=>{q(null),ve(null),ye(null)},children:p(`sshDisconnect`)})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,flexWrap:`wrap`,fontSize:`10px`},children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.git.installed?`ok`:`missing`}`,children:[`Git: `,Y?.git.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.node.installed?`ok`:`missing`}`,children:[`Node: `,Y?.node.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.bash.installed?`ok`:`missing`}`,children:[`Bash: `,Y?.bash.installed?`✓`:`✗`]})]}),be.length>0&&(0,$.jsxs)(`div`,{className:`cwd-ssh-install-box`,children:[(0,$.jsxs)(`div`,{children:[`⚠️`,` `,m?`远端环境未检测到 Git / 基础工具,SCM 与执行功能可能受限。`:`Git / essential tools not detected on remote host; SCM and execution features may be limited.`]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,marginTop:`2px`},children:[(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,disabled:Ce,onClick:()=>void Ze(be[0]),children:Ce?p(`sshInstalling`):`⚡ ${p(`sshInstallTool`)} ${be[0]}`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>xe([]),children:p(`sshSkipAndBrowse`)})]})]})]}),(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:Ee,children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{children:Ee})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":p(`workspaceModeRemote`),children:[(0,$.jsx)(ta,{className:`cwd-jump tool-up`,tip:Ee===`/`?`${p(`cwdGoUp`)} · ${m?`已在顶层`:`already at top`}`:`${p(`cwdGoUp`)} · ${va(Ee)||`/`}`,"aria-disabled":Ee===`/`||Ne,onClick:()=>{if(Ne)return;let e=va(Ee);e&&K&&Ye(K,e)},children:(0,$.jsx)(De,{})}),(0,$.jsx)(ta,{className:`cwd-jump tool-new ${Fe?`active`:``}`,tip:p(Fe?`cwdCancel`:`cwdNewFolder`),onClick:()=>Ie(e=>!e),children:(0,$.jsx)(y,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{className:`status-cwd-input cwd-picker-input`,value:Oe,placeholder:p(`enterPath`),spellCheck:!1,onChange:e=>Ae(e.target.value),onKeyDown:e=>{e.key===`Enter`&&K&&Ye(K,Oe)}}),Oe.trim()&&Oe.trim()!==Ee&&K&&(0,$.jsx)(ta,{className:`cwd-jump tool-enter`,tip:`${p(`cwdEnter`)} · ${Oe.trim()}`,onClick:()=>void Ye(K,Oe),children:(0,$.jsx)(he,{})}),(0,$.jsx)(ta,{className:`cwd-jump primary tool-pick`,tip:`${p(`sshOpenRemoteWorkspace`)} · ${Oe.trim()||Ee}`,onClick:()=>Qe(Oe.trim()||Ee),children:(0,$.jsx)(z,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[!Ne&&tt&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${p(`cwdGoUp`)} · ${tt}`,onClick:()=>{K&&Ye(K,tt)},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),Ne?(0,$.jsx)(`div`,{className:`cwd-empty`,children:m?`正在加载远程目录…`:`Loading remote directory…`}):je.length===0?(0,$.jsx)(`div`,{className:`cwd-empty`,children:p(`cwdEmpty`)}):je.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${e.type===`dir`?p(`cwdEnter`):``} ${e.path}`,onClick:()=>{e.type===`dir`&&K&&Ye(K,e.path)},children:[e.type===`dir`?(0,$.jsx)(Be,{}):(0,$.jsx)(`span`,{children:`📄`}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),e.type===`dir`&&(0,$.jsx)(ta,{className:`cwd-jump tool-choose`,tip:`${p(`cwdChoose`)} · ${e.path}`,onClick:()=>Qe(e.path),children:(0,$.jsx)(z,{})})]},e.path))]}),K&&Fe&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{value:Le,autoFocus:!0,spellCheck:!1,placeholder:p(`cwdNewName`),onChange:e=>{Re(e.target.value),ze&&Ve(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),$e()):e.key===`Escape`&&(e.stopPropagation(),Ie(!1),Re(``),Ve(null))}}),(0,$.jsx)(ta,{className:`cwd-jump primary`,tip:p(`cwdCreate`),onClick:$e,children:(0,$.jsx)(z,{})}),(0,$.jsx)(ta,{className:`cwd-jump`,tip:p(`cwdCancel`),onClick:()=>{Ie(!1),Re(``),Ve(null)},children:(0,$.jsx)(R,{})})]}),ze&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:ze})]})]}):(0,$.jsxs)(`div`,{className:`cwd-ssh-form`,children:[F.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profiles-title`,children:[`📋 `,p(`sshSavedProfiles`)]}),F.map(e=>(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-card`,onClick:()=>{re(e.host),L(String(e.port)),ae(e.username),se(e.authType),e.privateKeyPath&&B(e.privateKeyPath),qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}})},children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-meta`,children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-name`,children:[(0,$.jsx)(we,{style:{marginRight:`4px`}}),e.name]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-addr`,children:[e.username,`@`,e.host,`:`,e.port]})]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,title:p(`delete`),onClick:t=>{t.stopPropagation(),confirm(p(`sshDeleteProfileConfirm`))&&(pa(e.name),te(t=>t.filter(t=>t.name!==e.name)))},children:(0,$.jsx)(g,{})})]},e.name))]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,style:{marginTop:`4px`},children:[(0,$.jsxs)(`label`,{children:[p(`sshHost`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:ne,placeholder:`192.168.1.100`,onChange:e=>re(e.target.value)}),(0,$.jsxs)(`label`,{style:{width:`32px`,textAlign:`right`},children:[p(`sshPort`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,style:{width:`45px`,flex:`none`},value:I,onChange:e=>L(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshUser`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:ie,placeholder:`root / ubuntu`,onChange:e=>ae(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshAuthType`),`:`]}),(0,$.jsxs)(`select`,{className:`cwd-ssh-select`,value:oe,onChange:e=>se(e.target.value),children:[(0,$.jsx)(`option`,{value:`password`,children:p(`sshPassword`)}),(0,$.jsx)(`option`,{value:`key`,children:p(`sshKeyPath`)}),(0,$.jsx)(`option`,{value:`agent`,children:p(`sshAgent`)})]})]}),oe===`password`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshPassword`),`:`]}),(0,$.jsx)(`input`,{type:`password`,className:`cwd-ssh-input`,value:ce,placeholder:`••••••••`,onChange:e=>ue(e.target.value)})]}),oe===`key`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshKeyPath`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:de,placeholder:`~/.ssh/id_rsa`,onChange:e=>B(e.target.value)})]}),(0,$.jsx)(`div`,{className:`cwd-ssh-row`,style:{fontSize:`11px`,color:`var(--text-dim)`},children:(0,$.jsxs)(`label`,{style:{width:`auto`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:fe,onChange:e=>pe(e.target.checked),style:{marginRight:`4px`}}),p(`sshSaveProfile`)]})}),fe&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[p(`sshProfileName`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:me,placeholder:`my-server`,onChange:e=>ge(e.target.value)})]}),G&&(0,$.jsxs)(`div`,{style:{color:`var(--red)`,fontSize:`11px`,padding:`2px 0`},children:[`⚠️ `,G]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,style:{marginTop:`4px`},disabled:U,onClick:()=>void qe(),children:p(U?`sshConnecting`:`sshConnectAndProbe`)})]})})]})]}),document.body)}function ba({open:e,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,onCreateProject:o,mode:s=`project`,localOnly:c}){let l=V();return e?(0,$.jsx)(ya,{localOnly:c,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:e=>{a(e),i()},onCreateProject:o,mode:s,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:l(`projectPickerTitle`)}):null}function xa(e){return n({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M53.92,34.62A8,8,0,1,0,42.08,45.38L67.37,73.2A69.82,69.82,0,0,0,38,87.63a16,16,0,0,0-1.29,23.78L85,159.71,42.34,202.34a8,8,0,0,0,11.32,11.32L96.29,171l48.29,48.29A16,16,0,0,0,155.9,224c.38,0,.75,0,1.13,0a15.93,15.93,0,0,0,11.64-6.33,89.75,89.75,0,0,0,11.58-20.27l21.84,24a8,8,0,1,0,11.84-10.76ZM155.9,208,48,100.08C58.23,91.83,69.2,87.72,80.66,87.81l87.16,95.88C165.59,193.56,160.24,202.23,155.9,208Zm79.42-104-44.64,44.79a8,8,0,1,1-11.33-11.3L224,92.7,163.32,32,122.1,73.35a8,8,0,0,1-11.33-11.29L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.32,104Z`},child:[]}]})(e)}function Sa(e){return n({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M235.33,104l-53.47,53.65c4.56,12.67,6.45,33.89-13.19,60A15.93,15.93,0,0,1,157,224c-.38,0-.75,0-1.13,0a16,16,0,0,1-11.32-4.69L96.29,171,53.66,213.66a8,8,0,0,1-11.32-11.32L85,159.71l-48.3-48.3A16,16,0,0,1,38,87.63c25.42-20.51,49.75-16.48,60.4-13.14L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.33,104Z`},child:[]}]})(e)}function Ca({anchorRect:e,anchorEl:t,plugins:n,pinnedIds:r,orderedPluginIds:i,onTogglePin:a,onReorder:o,onOpenView:s,onOpenPluginSettings:c,onManagePlugins:l,onClose:u}){let{t:d}=Ue(),{panelRef:f,style:p,measure:m}=Cn({anchor:e,anchorEl:t,onClose:u}),[,h]=(0,Q.useState)(null),g=(0,Q.useRef)(null),[_,y]=(0,Q.useState)(null),b=(0,Q.useMemo)(()=>{let e=new Map((i??[]).map((e,t)=>[e,t]));return n.map((e,t)=>({plugin:e,index:t})).sort((t,n)=>(e.get(t.plugin.id)??1e6+t.index)-(e.get(n.plugin.id)??1e6+n.index)).map(({plugin:e})=>e)},[n,i]),{viewPlugins:x,extPlugins:S}=(0,Q.useMemo)(()=>{let e=[],t=[];for(let n of b)n.view!==!1&&!n.error?e.push(n):t.push(n);return{viewPlugins:e,extPlugins:t}},[b]);(0,Q.useLayoutEffect)(()=>{m()},[b,m]);let C=(e,t)=>{let n=b.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=r+t;if(r<0||i<0||i>=n.length)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},w=(e,t)=>{if(!e||e===t)return;let n=b.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=n.indexOf(t);if(r<0||i<0)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},T=(e,t)=>{let n=e.view===!1||!!e.error,i=!n&&r.has(e.id),o=e.iconSvg?void 0:e.icon&&!/[a-z]/i.test(e.icon)?e.icon:void 0;return(0,$.jsxs)(`div`,{className:`pm-row${_===e.id?` drop-target`:``}${t?` pm-row-ext`:``}`,role:`none`,onDragOver:t=>{!n&&g.current&&(t.preventDefault(),y(e.id))},onDrop:t=>{t.preventDefault(),w(t.dataTransfer.getData(`text/plain`)||g.current,e.id),g.current=null,h(null),y(null)},children:[n?(0,$.jsx)(`span`,{className:`pm-drag-placeholder`,"aria-hidden":!0}):(0,$.jsx)(`button`,{type:`button`,className:`pm-drag`,draggable:!0,"aria-label":d(`pluginMenuReorder`),title:d(`pluginMenuReorderHint`),onDragStart:t=>{h(e.id),g.current=e.id,t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e.id);let n=document.createElement(`div`);n.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0`,document.body.appendChild(n),t.dataTransfer.setDragImage(n,0,0),requestAnimationFrame(()=>n.remove())},onDragEnd:()=>{g.current=null,h(null),y(null)},onKeyDown:t=>{(t.key===`ArrowUp`||t.key===`ArrowDown`)&&(t.preventDefault(),C(e.id,t.key===`ArrowUp`?-1:1))},children:(0,$.jsx)(ze,{"aria-hidden":!0})}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-row-main`,disabled:n,title:e.error??(n?d(`pluginMenuNoView`):e.name),onClick:()=>s(e.id),children:[o||e.iconSvg?(0,$.jsx)(Ir,{icon:o,iconSvg:e.iconSvg,className:`pm-icon`}):(0,$.jsx)(ye,{className:`pm-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-name`,children:e.name}),e.error?(0,$.jsx)(`span`,{className:`pm-err-tag`,title:e.error,children:d(`pluginPhaseFailed`)}):t?(0,$.jsx)(`span`,{className:`pm-ext-tag`,title:d(`pluginMenuNoView`),children:d(`pluginBadgeBg`)}):null]}),(0,$.jsxs)(`div`,{className:`pm-row-actions`,children:[e.hasSettings&&c&&(0,$.jsx)(`button`,{type:`button`,className:`pm-action-btn`,title:d(`pluginQuickSettings`),onClick:()=>{u(),c(e.id)},children:(0,$.jsx)(v,{"aria-hidden":!0})}),!n&&(0,$.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":i,"aria-label":d(i?`pluginMenuUnpin`:`pluginMenuPin`),title:d(i?`pluginMenuUnpin`:`pluginMenuPin`),className:`pm-pin${i?` on`:``}`,onClick:()=>a(e.id,!i),children:i?(0,$.jsx)(Sa,{"aria-hidden":!0}):(0,$.jsx)(xa,{"aria-hidden":!0})})]})]},e.id)};return(0,bn.createPortal)((0,$.jsxs)(`div`,{ref:f,className:`pm-panel`,role:`menu`,"aria-label":d(`pluginMenuTitle`),style:p,children:[(0,$.jsxs)(`div`,{className:`pm-head`,"aria-hidden":`true`,children:[(0,$.jsxs)(`div`,{className:`pm-head-left`,children:[(0,$.jsx)(ye,{className:`pm-head-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-head-title`,children:d(`pluginMenuTitle`)}),(0,$.jsx)(`span`,{className:`pm-head-count`,children:n.length})]}),c&&(0,$.jsxs)(`button`,{type:`button`,className:`pm-head-btn`,title:d(`pluginManagerDesc`),onClick:()=>{u(),c()},children:[(0,$.jsx)(v,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuSettings`)})]})]}),(0,$.jsx)(`div`,{className:`pm-list`,children:n.length===0?(0,$.jsx)(`div`,{className:`pm-empty`,children:d(`pluginMenuEmpty`)}):(0,$.jsxs)($.Fragment,{children:[x.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[S.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:d(`pluginGroupViews`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:x.length})]}),x.map(e=>T(e,!1))]}),S.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[x.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:d(`pluginGroupExtensions`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:S.length})]}),S.map(e=>T(e,!0))]})]})}),(0,$.jsxs)(`div`,{className:`pm-footer`,children:[c&&(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn primary`,onClick:()=>{u(),c()},children:[(0,$.jsx)(v,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuSettings`)})]}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn pm-manage`,onClick:()=>{u(),l()},children:[(0,$.jsx)(at,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuManage`)})]})]})]}),document.body)}var wa=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Ta(e,t=[],n){let r=[],i=e=>{r.includes(e)||r.push(e)};e.optionsFrom&&i(``);for(let t of e.options??[])i(typeof t==`string`?t:t.value);if(e.optionsFrom===`models`)for(let e of t)i(`${e.provider}/${e.id}`);else if(e.optionsFrom===`thinkingLevels`)for(let e of wa)i(e);let a=typeof n==`string`?n:n==null?``:String(n);return a&&i(a),r}var Ea={activity:(0,$.jsx)(Je,{}),aperture:(0,$.jsx)(B,{}),branch:(0,$.jsx)(ce,{}),browser:(0,$.jsx)(le,{}),chat:(0,$.jsx)(Ae,{}),check:(0,$.jsx)(z,{}),"chevron-up":(0,$.jsx)(s,{}),clock:(0,$.jsx)(u,{}),code:(0,$.jsx)(c,{}),coins:(0,$.jsx)(_,{}),copy:(0,$.jsx)(Te,{}),cpu:(0,$.jsx)(E,{}),cut:(0,$.jsx)(O,{}),database:(0,$.jsx)(f,{}),dot:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`●`}),download:(0,$.jsx)(S,{}),edit:(0,$.jsx)(M,{}),engine:(0,$.jsx)(B,{}),eye:(0,$.jsx)(I,{}),feather:(0,$.jsx)(ne,{}),file:(0,$.jsx)(ie,{}),folder:(0,$.jsx)(Be,{}),gauge:(0,$.jsx)(Je,{}),git:(0,$.jsx)(ce,{}),github:(0,$.jsx)(oe,{}),globe:(0,$.jsx)(le,{}),grid:(0,$.jsx)(j,{}),hash:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`#`}),image:(0,$.jsx)(Ne,{}),info:(0,$.jsx)(We,{}),layers:(0,$.jsx)(fe,{}),link:(0,$.jsx)(qe,{}),list:(0,$.jsx)(ge,{}),lock:(0,$.jsx)(Oe,{}),markdown:(0,$.jsx)(x,{}),maximize:(0,$.jsx)(J,{}),menu:(0,$.jsx)(ze,{}),minimize:(0,$.jsx)(de,{}),message:(0,$.jsx)(Ae,{}),open:(0,$.jsx)(a,{}),paste:(0,$.jsx)(F,{}),pin:(0,$.jsx)(xe,{}),plus:(0,$.jsx)(rt,{}),refresh:(0,$.jsx)(te,{}),sandbox:(0,$.jsx)(An,{}),save:(0,$.jsx)(l,{}),share:(0,$.jsx)(On,{}),search:(0,$.jsx)(Ee,{}),send:(0,$.jsx)(i,{}),settings:(0,$.jsx)(T,{}),sound:(0,$.jsx)(b,{}),sun:(0,$.jsx)(N,{}),target:(0,$.jsx)(k,{}),terminal:(0,$.jsx)(o,{}),text:(0,$.jsx)(re,{}),trash:(0,$.jsx)(g,{}),undo:(0,$.jsx)(w,{}),upload:(0,$.jsx)(m,{}),volume:(0,$.jsx)(b,{}),wrap:(0,$.jsx)(r,{}),x:(0,$.jsx)(R,{}),zap:(0,$.jsx)(se,{}),zoom:(0,$.jsx)(ue,{})};Object.keys(Ea);function Da(e){if(e.iconSvg)return(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg});if(!e.icon)return null;let t=Ea[e.icon];return t===void 0?/[a-z]/i.test(e.icon)?null:(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:e.icon}):t}var Oa=0,ka=``;function Aa(){typeof document<`u`&&(Oa===0&&(ka=document.body.style.overflow,document.body.style.overflow=`hidden`),Oa++)}function ja(){typeof document<`u`&&(Oa=Math.max(0,Oa-1),Oa===0&&(document.body.style.overflow=ka))}function Ma({open:e=!0,onClose:t,title:n,icon:r,headerActions:i,allowFullscreen:a=!1,fullscreen:o,onFullscreenChange:s,children:c,className:l=``,backdropClassName:u=``,style:d,closeOnBackdropClick:f=!0,closeOnEscape:p=!0,showCloseButton:m=!0,ariaLabel:h,lockScroll:g=!0}){let _=V(),v=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{v.current=t});let y=o!==void 0,[b,x]=(0,Q.useState)(!1),S=a?y?o:b:!1,C=()=>{let e=!S;y||x(e),s?.(e)};if(mt(()=>a&&S?(y||x(!1),s?.(!1),!0):p?(v.current(),!0):!1,e),(0,Q.useEffect)(()=>{if(e&&g)return Aa(),()=>{ja()}},[e,g]),!e)return null;let w=e=>{e.target===e.currentTarget&&f&&v.current()},T=h??(typeof n==`string`?n:void 0),E=`modal-backdrop ${u} ${S?`fullscreen`:``}`.trim(),D=`modal ${l} ${a?`has-fullscreen-toggle`:``} ${S?`fullscreen`:``}`.trim();return(0,bn.createPortal)((0,$.jsx)(`div`,{className:E,onClick:w,role:`presentation`,children:(0,$.jsxs)(`div`,{className:D,role:`dialog`,"aria-modal":`true`,"aria-label":T,style:d,onClick:e=>e.stopPropagation(),children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`modal-fullscreen-btn ${S?`active`:``}`,"aria-label":_(S?`exitFullscreen`:`fullscreen`),title:_(S?`exitFullscreen`:`fullscreen`),onClick:C,children:S?(0,$.jsx)(Y,{}):(0,$.jsx)(G,{})}),m&&(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":_(`close`),onClick:()=>v.current(),children:`✕`}),n?(0,$.jsxs)(`div`,{className:`modal-head`,onDoubleClick:e=>{if(!a)return;let t=e.target;t&&!t.closest(`button, a, input, textarea, select`)&&C()},children:[r?(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:r}):null,(0,$.jsx)(`span`,{className:`modal-head-title`,children:n}),i?(0,$.jsx)(`div`,{className:`modal-head-actions`,children:i}):null]}):null,c]})}),document.body)}function Na({plugin:e,models:t=[]}){let n=V(),r=Se(),i=H(r),a=e.settingsSchema??[],[o,s]=(0,Q.useState)(()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);return t}),[c,l]=(0,Q.useState)(!1);if(a.length===0)return null;let u=(e,t)=>s(n=>({...n,[e]:t})),d=e=>Ta(e,t,o[e.key]).map(r=>{if(r===``)return{value:``,label:n(`pluginSettingsInherit`)};if(e.optionsFrom===`thinkingLevels`&&wa.includes(r))return{value:r,label:n(`thinking.${r}`)};if(e.optionsFrom===`models`){let e=t.find(e=>`${e.provider}/${e.id}`===r);if(e)return{value:r,label:e.label}}let a=e.options?.find(e=>(typeof e==`string`?e:e.value)===r);return a&&typeof a==`object`?{value:r,label:i?a.label??a.labelEn??a.value:a.labelEn??a.label??a.value}:{value:r,label:r}}),f=a.some(t=>t.type===`secret`?String(o[t.key]??``)!==``:o[t.key]!==e.settingsValues?.[t.key]);return(0,$.jsxs)(`div`,{className:`plugin-settings-form`,children:[(0,$.jsx)(`div`,{className:`plugin-settings-fields`,children:a.map(t=>(0,$.jsxs)(`label`,{className:`plugin-settings-field`,"data-key":t.key,title:t.hint,children:[(0,$.jsxs)(`span`,{className:`plugin-settings-label`,children:[(0,$.jsx)(`span`,{className:`plugin-settings-label-text`,title:t.label,children:t.label}),t.hint&&(0,$.jsx)(`span`,{className:`plugin-settings-hint`,children:t.hint})]}),(0,$.jsx)(`span`,{className:`plugin-settings-control`,children:t.type===`boolean`?(0,$.jsx)(`input`,{type:`checkbox`,checked:!!o[t.key],onChange:e=>u(t.key,e.target.checked)}):t.type===`secret`?(0,$.jsx)(`input`,{type:`password`,value:String(o[t.key]??``),placeholder:n(e.settingsValues?.[t.key]?`pluginSecretSet`:`pluginSecretUnset`),autoComplete:`new-password`,onChange:e=>u(t.key,e.target.value)}):t.type===`select`?(0,$.jsx)(`select`,{value:String(o[t.key]??``),onChange:e=>u(t.key,e.target.value),children:d(t).map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,$.jsx)(`input`,{type:t.type===`password`?`password`:t.type===`number`?`number`:`text`,value:String(o[t.key]??``),min:t.min,max:t.max,onChange:e=>u(t.key,t.type===`number`?Number(e.target.value):e.target.value)})})]},t.key))}),(0,$.jsxs)(`div`,{className:`plugin-settings-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-save`,disabled:!f||c,onClick:()=>{l(!0),Z({type:`plugin_settings`,pluginId:e.id,values:o}),setTimeout(()=>l(!1),800)},children:n(c?`pluginSettingsSaving`:`pluginSettingsSave`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-reset`,onClick:()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);s(t)},children:n(`pluginSettingsReset`)})]})]})}function Pa({plugin:e}){if(e.iconSvg)return(0,$.jsx)(Ir,{iconSvg:e.iconSvg});if(e.icon){if(!/[a-z]/i.test(e.icon))return(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:e.icon});let t=Da({icon:e.icon});if(t)return(0,$.jsx)(`span`,{className:`plugin-mgr-named-icon`,children:t})}return e.view===!1?e.settingsSchema&&e.settingsSchema.length>0?(0,$.jsx)(v,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(ye,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(Ie,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0})}function Fa({open:e=!0,onClose:t,focusPluginId:n,plugins:r,disabledPlugins:i,models:o=[],onTogglePlugin:s,onOpenView:c,onOpenMarketplace:l}){let u=V(),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`all`),[h,g]=(0,Q.useState)({}),[_,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(new Map),C=(0,Q.useMemo)(()=>new Set(i),[i]),w=(0,Q.useMemo)(()=>{let e=0,t=0,n=0;for(let i of r){let r=!!(i.settingsSchema&&i.settingsSchema.length>0),a=C.has(i.id),o=!!i.error;r&&e++,!a&&!o&&t++,a&&n++}return{total:r.length,configurable:e,enabled:t,disabled:n}},[r,C]);(0,Q.useEffect)(()=>{if(!e||!n)return;g(e=>({...e,[n]:!0})),y(n),r.find(e=>e.id===n)&&m(`all`);let t=setTimeout(()=>{let e=S.current.get(n);e&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},120),i=setTimeout(()=>{y(null)},2600);return()=>{clearTimeout(t),clearTimeout(i)}},[e,n,r]);let T=(0,Q.useCallback)(e=>{g(t=>({...t,[e]:!t[e]}))},[]),E=(0,Q.useCallback)(()=>{let e=r.some(e=>e.settingsSchema?.length&&!h[e.id]),t={};for(let n of r)n.settingsSchema?.length&&(t[n.id]=e);g(t)},[r,h]),D=(0,Q.useMemo)(()=>{let e=d.trim().toLowerCase();return r.filter(t=>{let n=!!(t.settingsSchema&&t.settingsSchema.length>0),r=C.has(t.id),i=!!t.error;if(p===`configurable`&&!n||p===`enabled`&&(r||i)||p===`disabled`&&!r)return!1;if(e){let n=t.name?.toLowerCase().includes(e),r=t.id?.toLowerCase().includes(e),i=t.description?.toLowerCase().includes(e);if(!n&&!r&&!i)return!1}return!0})},[r,p,d,C]),O=(0,Q.useCallback)(()=>{x(!0),Z({type:`plugins_reload`}),setTimeout(()=>x(!1),800)},[]);return(0,$.jsxs)(Ma,{open:e,onClose:t,className:`plugin-mgr-modal`,ariaLabel:u(`pluginManagerTitle`),showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-head`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-title-row`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-title-left`,title:u(`pluginCountSummary`,{total:w.total,enabled:w.enabled,configurable:w.configurable}),children:[(0,$.jsx)(ye,{className:`plugin-mgr-title-icon`,"aria-hidden":!0}),(0,$.jsx)(`h2`,{className:`plugin-mgr-title`,children:u(`pluginManagerTitle`)})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-title-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,title:u(`pluginRescanHint`),onClick:O,disabled:b,children:[(0,$.jsx)(te,{className:b?`spin`:``,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginRescan`)})]}),l&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{t(),l()},children:[(0,$.jsx)(at,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginGoMarket`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-close-btn`,"aria-label":u(`close`),title:u(`close`),onClick:t,children:(0,$.jsx)(R,{"aria-hidden":!0})})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-toolbar`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-search-wrap`,children:[(0,$.jsx)(Ee,{className:`plugin-mgr-search-icon`,"aria-hidden":!0}),(0,$.jsx)(`input`,{type:`text`,className:`plugin-mgr-search-input`,placeholder:u(`pluginSearchPlaceholder`),value:d,onChange:e=>f(e.target.value)}),d&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-search-clear`,onClick:()=>f(``),"aria-label":`Clear`,children:(0,$.jsx)(R,{"aria-hidden":!0})})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-filters`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`all`?` active`:``}`,onClick:()=>m(`all`),children:[u(`pluginFilterAll`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.total})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`configurable`?` active`:``}`,onClick:()=>m(`configurable`),children:[(0,$.jsx)(v,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),u(`pluginFilterConfigurable`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.configurable})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`enabled`?` active`:``}`,onClick:()=>m(`enabled`),children:[(0,$.jsx)(z,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),u(`pluginFilterEnabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.enabled})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${p===`disabled`?` active`:``}`,onClick:()=>m(`disabled`),children:[u(`pluginFilterDisabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:w.disabled})]})]}),w.configurable>0&&(0,$.jsx)(`div`,{className:`plugin-mgr-expand-action`,children:(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-text-btn`,onClick:E,children:r.some(e=>e.settingsSchema?.length&&!h[e.id])?u(`pluginExpandAll`):u(`pluginCollapseAll`)})})]})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-body`,children:D.length===0?(0,$.jsxs)(`div`,{className:`plugin-mgr-empty`,children:[(0,$.jsx)(ye,{className:`plugin-mgr-empty-icon`,"aria-hidden":!0}),(0,$.jsx)(`p`,{children:u(d||p!==`all`?`pluginEmptyFilter`:`pluginMenuEmpty`)}),(d||p!==`all`)&&(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{f(``),m(`all`)},children:u(`pluginFilterAll`)})]}):(0,$.jsx)(`div`,{className:`plugin-mgr-list`,children:D.map(e=>{let n=!!(e.settingsSchema&&e.settingsSchema.length>0),r=C.has(e.id),i=!!e.error,l=!!h[e.id],d=e.view!==!1&&!i,f=_===e.id,p=e.homepage||(e.source?.startsWith(`http`)?e.source:void 0);return(0,$.jsxs)(`div`,{ref:t=>{t?S.current.set(e.id,t):S.current.delete(e.id)},className:`plugin-mgr-card${r?` disabled`:``}${i?` has-error`:``}${f?` highlighted`:``}`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-head`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-identity`,children:[(0,$.jsx)(`div`,{className:`plugin-mgr-card-icon-wrap`,children:(0,$.jsx)(Pa,{plugin:e})}),(0,$.jsxs)(`div`,{className:`plugin-mgr-card-names`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-name-row`,children:[(0,$.jsx)(`span`,{className:`plugin-mgr-card-name`,children:e.name}),e.version&&(0,$.jsxs)(`span`,{className:`plugin-mgr-card-ver`,children:[`v`,e.version]}),(0,$.jsx)(`span`,{className:`plugin-mgr-card-id`,children:e.id})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-badges`,children:[n&&(0,$.jsxs)(`span`,{className:`plugin-badge config`,title:u(`pluginBadgeConfig`),children:[(0,$.jsx)(v,{"aria-hidden":!0}),u(`pluginBadgeConfig`)]}),d?(0,$.jsx)(`span`,{className:`plugin-badge view`,children:u(`pluginBadgeView`)}):(0,$.jsx)(`span`,{className:`plugin-badge bg`,children:u(`pluginBadgeBg`)}),e.agentTools&&e.agentTools.length>0&&(0,$.jsx)(`span`,{className:`plugin-badge tools`,children:u(`pluginBadgeTools`,{count:e.agentTools.length})}),i&&(0,$.jsxs)(`span`,{className:`plugin-badge error`,children:[(0,$.jsx)(He,{"aria-hidden":!0}),`Error`]})]})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-card-controls`,children:[p&&(0,$.jsx)(`a`,{href:p,target:`_blank`,rel:`noreferrer noopener`,className:`plugin-mgr-icon-btn`,title:u(`pluginOfficialLink`),children:(0,$.jsx)(a,{"aria-hidden":!0})}),d&&!r&&c&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-open-view`,onClick:()=>{t(),c(e.id)},title:u(`pluginOpenView`),children:[(0,$.jsx)(I,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginOpenView`)})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-toggle-wrap`,children:(0,$.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!r&&!i,disabled:i,title:u(r?`pluginToggleEnable`:`pluginToggleDisable`),className:`plugin-mgr-switch${!r&&!i?` on`:``}`,onClick:()=>s(e),children:(0,$.jsx)(`span`,{className:`plugin-mgr-switch-thumb`})})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`plugin-mgr-card-desc`,title:e.description,children:e.description}),e.error&&(0,$.jsxs)(`div`,{className:`plugin-mgr-card-error`,children:[(0,$.jsx)(He,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:e.error})]}),n&&(0,$.jsxs)(`div`,{className:`plugin-mgr-settings-section`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-settings-toggle`,onClick:()=>T(e.id),"aria-expanded":l,children:[l?(0,$.jsx)(pe,{"aria-hidden":!0}):(0,$.jsx)(P,{"aria-hidden":!0}),(0,$.jsx)(v,{className:`plugin-mgr-settings-icon`,"aria-hidden":!0}),(0,$.jsxs)(`span`,{className:`plugin-mgr-settings-toggle-title`,children:[u(`pluginSettingsTitle`),` (`,e.settingsSchema.length,`)`]}),(0,$.jsx)(`span`,{className:`plugin-mgr-settings-toggle-hint`,children:u(l?`pluginSettingsHide`:`pluginSettingsShow`)})]}),l&&(0,$.jsx)(`div`,{className:`plugin-mgr-settings-content`,children:(0,$.jsx)(Na,{plugin:e,models:o})})]})]},e.id)})})})]})}function Ia({onClose:e}){let t=V(),{locale:n,setLocale:r,reloadPacks:i}=Ue(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``);async function d(){try{let e=await fetch(Qe(q(`/api/locales`)));if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();o(t.packs??[]),c(``)}catch(e){c(t(`localeListFailed`,{error:e instanceof Error?e.message:String(e)}))}}(0,Q.useEffect)(()=>{d()},[]);async function f(e){u(e),c(``);try{let t=await fetch(Qe(q(`/api/locales/${e}/install`)),{method:`POST`});if(!t.ok){let e=`HTTP ${t.status}`;try{e=(await t.json()).error??e}catch{}throw Error(e)}await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}async function p(e){u(e),c(``);try{let t=await fetch(Qe(q(`/api/locales/${e}`)),{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);Me(e),n===e&&r(`zh`),await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:e,children:(0,$.jsxs)(`div`,{className:`bg-task-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`bg-task-head`,children:[(0,$.jsxs)(`span`,{className:`bg-task-title`,children:[(0,$.jsx)(le,{}),` `,t(`localePacks`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:t(`close`),onClick:e,children:(0,$.jsx)(R,{})})]}),s&&(0,$.jsx)(`div`,{className:`bg-task-empty`,children:s}),a===null&&!s?(0,$.jsx)(`div`,{className:`bg-task-empty`,children:t(`loading`)}):(0,$.jsx)(`ul`,{className:`bg-task-list`,children:(a??[]).map(e=>{let n=l===e.code;return(0,$.jsxs)(`li`,{className:`bg-task-item`,children:[(0,$.jsxs)(`div`,{className:`bg-task-info`,children:[(0,$.jsxs)(`div`,{className:`bg-task-line1`,children:[(0,$.jsx)(`span`,{className:`bg-task-port`,children:e.nativeName}),e.installed&&e.version&&(0,$.jsxs)(`span`,{className:`bg-task-name`,children:[`v`,e.version]})]}),(0,$.jsxs)(`div`,{className:`bg-task-line2`,children:[(0,$.jsx)(`span`,{children:e.code}),e.installed?(0,$.jsxs)(`span`,{children:[t(`localeInstalled`),` · `,t(`localeRemoveHint`)]}):(0,$.jsx)(`span`,{children:t(`localeGetMore`)})]})]}),e.installed?(0,$.jsxs)(`button`,{type:`button`,className:`btn bg-task-stop`,disabled:n,title:t(`localeRemove`),onClick:()=>void p(e.code),children:[(0,$.jsx)(g,{}),(0,$.jsx)(`span`,{children:t(n?`localeRemoving`:`localeRemove`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:n,title:t(`localeInstall`),onClick:()=>void f(e.code),children:[(0,$.jsx)(S,{}),(0,$.jsx)(`span`,{children:t(n?`localeDownloading`:`localeInstall`)})]})]},e.code)})}),(0,$.jsx)(`div`,{className:`bg-task-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:t(`bgTaskRefresh`),onClick:()=>void d(),children:[(0,$.jsx)(te,{}),(0,$.jsx)(`span`,{children:t(`bgTaskRefresh`)})]})})]})})}var La=`xing-shuyin/pi-web-ui`,Ra={state:`idle`,version:null,percent:0,message:null};function za(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Ba(e,t){switch(t.state){case`checking`:return{...e,state:`checking`,message:null};case`available`:return{...e,state:`available`,version:t.version??e.version,message:null};case`up-to-date`:return{...e,state:`up-to-date`,version:t.version??e.version,message:null};case`downloading`:return{...e,state:`downloading`,percent:za(t.percent),message:null};case`downloaded`:return{...e,state:`downloaded`,version:t.version??e.version,percent:100,message:null};case`error`:return{...e,state:`error`,message:t.message??`unknown error`};default:return e}}function Va(e){if(!wt(e))return null;let t=(e??(typeof window>`u`?void 0:window))?.piDesktop?.updater;return!t||typeof t.check!=`function`||typeof t.download!=`function`?null:t}function Ha(e){return e instanceof Error?e.message:String(e)}function Ua(e){let t=(e??``).trim().replace(/^v/,``);return t?`https://github.com/${La}/releases/tag/v${t}`:`https://github.com/${La}/releases/latest`}function Wa(){let[e]=(0,Q.useState)(()=>Va()),[t,n]=(0,Q.useState)(Ra);(0,Q.useEffect)(()=>{if(e)return e.onEvent(e=>n(t=>Ba(t,e)))},[e]);let r=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`checking`,message:null})),e.check().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)}))))},[e]),i=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`downloading`,message:null})),e.download().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)}))))},[e]),a=(0,Q.useCallback)(()=>{e&&e.quitAndInstall().catch(e=>n(t=>({...t,state:`error`,message:Ha(e)})))},[e]);return{...t,bridge:e,check:r,download:i,quitAndInstall:a}}function Ga(e){let t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),r=Math.max(0,e.cacheWrite??0),i=t+n+r;return{totalInput:i,miss:t,read:n,write:r,hitRate:i>0?Math.min(n/i,1):0,writeRate:i>0?Math.min(r/i,1):0}}var Ka=2e3;function qa(e,t,n=Ka){return e.filter(e=>t-e.t<=n)}function Ja(e,t=Ka){if(e.length<2)return 0;let n=e[e.length-1],r=e.find(e=>e.t>=n.t-t)??e[0],i=(n.t-r.t)/1e3;return i<=0?0:Math.max(0,(n.out-r.out)/i)}function Ya(e){if(!e)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r>=12352&&r<=12543||r>=13312&&r<=19903||r>=19968&&r<=40959||r>=63744&&r<=64255||r>=65280&&r<=65519||r===12288)&&t++}let n=e.length-t;return Math.round(t+n/4)}function Xa(e){let t=0;for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text?t+=Ya(n.text):n.type===`thinking`&&typeof n.thinking==`string`&&n.thinking&&(t+=Ya(n.thinking));return t}var Za=[{id:`pi`,titleKey:`settingsEnginePiTitle`,badge:`PI`,tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-pi`,packageName:`@earendil-works/pi-coding-agent`,installCommand:`npm i -g @earendil-works/pi-coding-agent`},{id:`dsh`,titleKey:`settingsEngineDshTitle`,badge:`DSH`,tagKey:`engineTagFast`,descKey:`settingsEngineDshDesc`,colorClass:`engine-dsh`,packageName:`@deepseek-ai/dsh`,installCommand:`npm i -g @deepseek-ai/dsh`},{id:`claude`,titleKey:`settingsEngineClaudeTitle`,badge:`CLAUDE`,tagKey:`engineTagUniversal`,descKey:`settingsEngineClaudeDesc`,colorClass:`engine-claude`,packageName:`@anthropic-ai/claude-code`,installCommand:`npm i -g @anthropic-ai/claude-code`},{id:`codex`,titleKey:`settingsEngineCodexTitle`,badge:`CODEX`,tagKey:`engineTagUniversal`,descKey:`settingsEngineCodexDesc`,colorClass:`engine-codex`,packageName:`@openai/codex`,installCommand:`npm i -g @openai/codex`},{id:`durable`,titleKey:`settingsEngineDurableTitle`,badge:`DURABLE`,tagKey:`engineTagDurable`,descKey:`settingsEngineDurableDesc`,colorClass:`engine-durable`,packageName:`@earendil-works/pi-durable`,installCommand:`npm i -g @earendil-works/pi-durable`}];function Qa({direction:e,align:t,className:n,label:r,caret:i=!1,bar:a,portal:o}){let{engine:s}=Qt(),c=on(),{t:l}=Ue(),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=e??(a===`left`?`right`:a===`right`?`left`:a===`bottom`?`up`:`down`),m=o??(a===`left`||a===`right`||a===`bottom`),h=e=>{e&&Z({type:`check_engines`}),d(e)},g=Za.find(e=>e.id===s)??{id:s,titleKey:`settingsEnginePiTitle`,badge:s.toUpperCase(),tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-${s}`},_=l(g.titleKey),v=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(B,{className:`bar-item-icon engine-picker-icon`}),r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`chip-sub bar-item-text engine-picker-name`,children:r}),(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${g.colorClass}`,children:g.badge})]}):(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${g.colorClass}`,children:g.badge})]});return(0,$.jsx)(`div`,{ref:f,className:`engine-picker-wrap ${g.colorClass} ${n??``}`,"data-bar-item":`host:engine`,children:(0,$.jsxs)(_t,{trigger:v,open:u,onOpenChange:h,direction:p,align:t??(a===`right`?`right`:`left`),fit:!0,caret:i,portal:m,triggerClassName:`bar-item chip engine-picker-btn ${g.colorClass}`,menuClassName:`engine-picker-menu`,tip:`${l(`engineBadge`)}: ${r??_} — ${l(`engineSwitchTip`)}`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-header`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-title`,children:[(0,$.jsx)(B,{}),(0,$.jsx)(`span`,{children:l(`settingsEngineSection`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-subtitle`,children:l(`enginePickerDesc`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-list`,role:`menu`,children:Za.map(e=>{let t=e.id===s,n=c.find(t=>t.id===e.id),r=e.id===`pi`||(n?n.installed:!1),i=!!n?.updating,a=!!(r&&n?.hasUpdate&&n?.latestVersion),o=a||i,u=t=>{t.stopPropagation(),d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}))},f=t=>{t.stopPropagation(),!i&&(d(!1),Z({type:`update_engine`,engineId:e.id}))},p=()=>{if(!r){d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}));return}d(!1),t||Z({type:`switch_engine`,engine:e.id})};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,title:r?void 0:l(`engineInstallTip`),className:`engine-picker-item ${e.colorClass}${t?` active`:``}${r?``:` uninstalled`}`,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),p())},onClick:p,children:[(0,$.jsxs)(`div`,{className:`engine-picker-item-head`,children:[(0,$.jsx)(B,{className:`engine-picker-item-icon`}),(0,$.jsx)(`span`,{className:`engine-badge ${e.colorClass}`,children:e.badge}),l(e.titleKey)!==e.badge&&(0,$.jsx)(`span`,{className:`engine-picker-item-name`,children:l(e.titleKey)}),(0,$.jsx)(`span`,{className:`engine-picker-item-tag${r?i||a?` update-available`:``:` uninstalled`}`,title:a?l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}):void 0,children:l(r?i?`engineUpdating`:a?`engineUpdateAvailable`:e.tagKey:`engineNotInstalled`)}),!r&&e.installCommand&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-install-btn`,title:l(`engineInstallTip`),onClick:u,children:[(0,$.jsx)(S,{className:`engine-install-icon`}),(0,$.jsx)(`span`,{children:l(`engineInstall`)})]}),o&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-update-btn`,disabled:i,title:i?l(`engineUpdating`):l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}),onClick:f,children:[(0,$.jsx)(te,{className:`engine-update-icon${i?` spinning`:``}`}),(0,$.jsx)(`span`,{children:l(i?`engineUpdating`:`engineUpdate`)})]}),t&&(0,$.jsx)(z,{className:`engine-picker-check`})]}),(0,$.jsx)(`div`,{className:`engine-picker-item-desc`,children:l(e.descKey)})]},e.id)})})]})})}function $a(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}var eo={systemPrompt:`settingsSystemPrompt`,memoryFiles:`contextMemoryFiles`,tools:`contextTools`,skills:`contextSkills`,toolResults:`contextToolResults`,messages:`messages`,other:`contextOther`};function to({context:e,bar:t,title:n,onContextMenu:r,children:i}){let a=V(),o=(0,Q.useId)(),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(!1),{panelRef:u,style:d,measure:f}=Cn({open:c,anchor:s,side:t===`bottom`?`top`:`bottom`,align:t===`left`?`left`:`right`,onClose:()=>l(!1)}),p=e?.contextWindow??0,m=e?.softCap??0,h=m>0&&m<p?m:p,g=typeof e?.tokens==`number`&&Number.isFinite(e.tokens)&&h>0,_=g?Math.max(0,e.tokens):0,v=Math.min(100,Math.round(_/(h||1)*100)),y=Math.max(0,h-_),b=e?.categories?.filter(e=>e.tokens>0&&e.category in eo)??[],x=b.length>0,S=b.map(e=>({...e,label:a(eo[e.category])}));return!x&&_>0&&S.push({category:`other`,tokens:_,label:a(`contextUsed`)}),(0,Q.useLayoutEffect)(()=>{c&&f()}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:s,type:`button`,className:`bar-item status-item status-ctx bar-item-ctx`,title:c?void 0:n,"data-tip":c?void 0:n,"data-bar-item":`host:ctx`,"aria-label":n,"aria-haspopup":`dialog`,"aria-expanded":c,"aria-controls":c?o:void 0,onContextMenu:r,onClick:()=>l(e=>!e),children:i}),c&&(0,bn.createPortal)((0,$.jsxs)(`div`,{ref:u,id:o,style:d,className:`context-usage-panel`,role:`dialog`,"aria-labelledby":`${o}-title`,children:[(0,$.jsxs)(`header`,{className:`context-usage-header`,children:[(0,$.jsx)(`h3`,{id:`${o}-title`,children:a(`context`)}),(0,$.jsx)(`span`,{children:g?a(`contextPercent`,{percent:v}):`—`})]}),g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`context-usage-bar`,role:`meter`,"aria-label":a(`contextUsage`),"aria-valuemin":0,"aria-valuemax":h,"aria-valuenow":Math.min(_,h),"aria-valuetext":`${$a(_)} / ${$a(h)}`,children:[S.map(e=>(0,$.jsx)(`span`,{"data-category":e.category,style:{flexGrow:e.tokens}},e.category)),(0,$.jsx)(`span`,{"data-category":`free`,style:{flexGrow:y}})]}),(0,$.jsx)(`p`,{className:`context-usage-tokens`,children:a(x||e?.estimated?`contextTokensEstimated`:`contextTokens`,{used:$a(_),total:$a(h)})}),(0,$.jsxs)(`ul`,{className:`context-usage-categories`,"aria-label":a(`contextUsage`),children:[S.map(e=>(0,$.jsxs)(`li`,{"data-category":e.category,children:[(0,$.jsx)(`span`,{className:`context-usage-dot`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`context-usage-label`,children:e.label}),(0,$.jsx)(`span`,{className:`context-usage-value`,title:e.tokens.toLocaleString(),children:$a(e.tokens)})]},e.category)),(0,$.jsxs)(`li`,{"data-category":`free`,children:[(0,$.jsx)(`span`,{className:`context-usage-dot`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`context-usage-label`,children:a(`contextFree`)}),(0,$.jsx)(`span`,{className:`context-usage-value`,title:y.toLocaleString(),children:$a(y)})]})]}),(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(x?`contextBreakdownEstimate`:`contextBreakdownUnavailable`)}),m>0&&(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextSoftCap`,{cap:$a(m),max:$a(p)})})]}):(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextUsageUnavailable`)})]}),document.body)]})}function no(e){return e===`zh-TW`?`TW`:e.startsWith(`zh`)?`ZH`:e.startsWith(`ja`)?`JA`:e.startsWith(`ko`)?`KO`:e.startsWith(`fr`)?`FR`:e.startsWith(`de`)?`DE`:e.startsWith(`es`)?`ES`:e.startsWith(`ru`)?`RU`:e.startsWith(`pt`)?`PT`:e.startsWith(`it`)?`IT`:`EN`}function ro({entry:e,bar:t,chat:n,view:r,plugins:i,onViewChange:a,onOpenPanel:s,onOpenSettings:c,onOpenGlobalSearch:l,onOpenBgTasks:u,onOpenProjectPicker:d,onOpenPluginMenu:p,isPluginMenuOpen:m,isProjectPickerOpen:h,onUiAction:g,uiContextEntries:_,dropdownProps:v,zenMode:b,onToggleZenMode:x,onOpenSandboxModal:C}){let w=V(),{locale:D,packs:O,setLocale:k}=Ue(),{engine:A}=Qt(),j=A===`dsh`,[M,P]=(0,Q.useState)(!1),[ee,F]=(0,Q.useState)(!1),[te,re]=(0,Q.useState)(!1),I=n.settings?.uiLayout,L=n.state,ie=L?.stats,ae=L?.isStreaming??!1,se=L?.turnTiming,R=!!se&&se.finishedAt===void 0,[ue,z]=(0,Q.useState)(Date.now);(0,Q.useEffect)(()=>{if(e.id!==`host:working`||!R)return;z(Date.now());let t=window.setInterval(()=>z(Date.now()),1e3);return()=>window.clearInterval(t)},[e.id,R,se?.startedAt]);let de=Zt(ie?.cost??0),B=(0,Q.useRef)([]),pe=L?.streamingMessage?Xa(L.streamingMessage.content):0;(0,Q.useEffect)(()=>{if(!ae){B.current=[];return}let e=Date.now(),t=B.current,n=t[t.length-1];n&&e-n.t<250||(B.current=qa([...t,{t:e,out:pe}],e))},[ae,pe]);let me=ae?Ja(B.current):0,he=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{he.current!==null&&window.clearTimeout(he.current)},[]);let ge=n=>{n.preventDefault(),n.stopPropagation();let r=t=>{let n={...I?.slots,[e.id]:t},r={...I?.align};(t===`sidebar.left`||t===`sidebar.right`)&&!r[e.id]&&(r[e.id]=`center`),Z({type:`set_settings`,uiLayout:{...I,slots:n,...r[e.id]?{align:r}:{}}})},i=()=>{let t=new Set(I?.hidden??[]);t.add(e.id);let n=(I?.shown??[]).filter(t=>t!==e.id);Z({type:`set_settings`,uiLayout:{...I,hidden:[...t],shown:n}})},a=()=>{Z({type:`set_settings`,uiLayout:Ti(I,e.id)})},o=[];t!==`top`&&o.push({id:`host:move-top`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToTop`),kind:`action`,order:10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`bottom`&&o.push({id:`host:move-bottom`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToBottom`),kind:`action`,order:20,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`left`&&o.push({id:`host:move-left`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToLeft`),kind:`action`,order:30,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t!==`right`&&o.push({id:`host:move-right`,slot:`contextmenu.topbar`,source:`host`,label:w(`moveToRight`),kind:`action`,order:40,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),ti.has(e.id)||o.push({id:`host:hide-item`,slot:`contextmenu.topbar`,source:`host`,label:w(`uiLayoutHide`),kind:`action`,order:50,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),(e.userOverrides&&e.userOverrides.length>0||I?.slots?.[e.id]||I?.labels?.[e.id]||I?.align?.[e.id]||I?.order?.includes(e.id))&&o.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:w(`uiLayoutRestore`),kind:`action`,order:60,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),_&&_.length>0&&o.push(..._),Pi({x:n.clientX,y:n.clientY,slot:`contextmenu.topbar`,target:{id:e.id,label:e.label},entries:o,onHostAction:e=>{e.id===`host:move-top`?r(`topbar.primary`):e.id===`host:move-bottom`?r(`bottombar`):e.id===`host:move-left`?r(`sidebar.left`):e.id===`host:move-right`?r(`sidebar.right`):e.id===`host:hide-item`?i():e.id===`host:restore-item`&&a()}})},U=e.id,W=e.labelExplicit?e.label:``,G=e=>W||e,_e=e=>W?`${W} ${e}`:e;if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`bar-item bar-item-select`,title:e.hint??e.label,"data-tip":e.hint??e.label,"aria-label":e.label,value:t,onChange:t=>g?.(e,t.target.value),onContextMenu:ge,"data-bar-item":U,children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})}if(U===`host:brand`)return(0,$.jsx)(En,{label:G(`pi-web-ui`),barItem:!0,onContextMenu:ge});if(U===`host:conn`){let e=n.ready?`ok`:n.status===`closed`?`error`:`busy`,t=n.ready?w(`connected`):n.status===`closed`?w(`reconnecting`):w(`connecting`),r=n.ready&&typeof n.latencyMs==`number`&&Number.isFinite(n.latencyMs)&&n.latencyMs>=0?Math.round(n.latencyMs):null,i=r===null?null:`${r}ms`,a=r===null?``:r<100?`ok`:r<300?`mid`:`warn`,o=i?`${t} · ${w(`networkLatency`)}: ${i}`:t;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-conn ${e} bar-item-conn`,title:o,"data-tip":o,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(`span`,{className:`status-dot ${e}`}),(0,$.jsx)(`span`,{className:`status-conn-label bar-item-text`,children:_e(t)}),i&&(0,$.jsx)(`span`,{className:`status-latency ${a}`,children:i})]})}if(U===`host:engine`)return(0,$.jsx)(`span`,{onContextMenu:ge,"data-bar-item":U,className:`bar-item-engine-wrap`,style:{display:`inline-flex`,alignItems:`center`},children:(0,$.jsx)(Qa,{direction:t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`,align:e.align===`end`||t===`right`?`right`:`left`,caret:!1,bar:t,portal:!0,label:e.labelExplicit?e.label:void 0})});if(U===`host:ctx`){let e=ie?.contextUsage,r=e?.softCap??null,i=r!==null&&r>0&&r<(e?.contextWindow??0),a=i?r:e?.contextWindow??0,o=e?.tokens!==null&&e?.tokens!==void 0&&a>0?Math.min(100,Math.round(e.tokens/a*100)):null,s=e?.tokens!==null&&e?.tokens!==void 0?$a(e.tokens):null,c=a>0?$a(a):null,l=s!==null&&c!==null&&o!==null?`${s} / ${c}`:`—`,u=o===null?``:o>=80?`warn`:o>=50?`mid`:`ok`,d=i?`${w(`contextUsage`)}: ${$a(e?.tokens??0)} / ${$a(r)} (${w(`softCapMarker`)}, max ${$a(e?.contextWindow??0)})`:r!==null&&r>0?`${w(`contextUsage`)}: ${l} · ${w(`softCapMarker`)}: ${$a(r)}`:`${w(`contextUsage`)}: ${l}`,f=o!==null&&o>0?+(31.42*(1-Math.min(o,100)/100)).toFixed(2):31.42;return(0,$.jsxs)(to,{context:e,bar:t,title:d,onContextMenu:ge,children:[(0,$.jsxs)(`svg`,{className:`ctx-ring ${u}`,viewBox:`0 0 14 14`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{className:`ctx-ring-bg`,cx:`7`,cy:`7`,r:`5`}),o!==null&&o>0&&(0,$.jsx)(`circle`,{className:`ctx-ring-fill`,cx:`7`,cy:`7`,r:`5`,strokeDasharray:31.42,strokeDashoffset:f,"data-percent":o})]}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[W?`${W} `:``,s!==null&&c!==null?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`ctx-val`,children:s}),(0,$.jsx)(`span`,{className:`status-sep`,children:`/`}),(0,$.jsx)(`span`,{className:`ctx-max`,children:c})]}):l]})]},`${n.engine}:${L?.conversationId??L?.sessionId??``}`)}if(U===`host:cache`){let e=Ga(ie?.tokens??{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}),t=e.hitRate*100,n=e.totalInput===0?``:e.hitRate>=.7?`ok`:e.hitRate>=.4?`mid`:`warn`,r=e.totalInput>0?`${t.toFixed(1)}%`:`—`,i=w(`cacheHitTip`,{read:$a(e.read),write:$a(e.write),miss:$a(e.miss),input:$a(e.totalInput)}),a=e.totalInput>0?`${w(`cacheHit`)}: ${r} · ${i}`:w(`cacheHit`),o=e.totalInput===0;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cache bar-item-cache${o?` is-zero`:``}`,title:a,"data-tip":a,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(f,{className:`bar-item-icon`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[W?`${W} `:``,(0,$.jsx)(`b`,{className:`cache-pct ${n}`,children:r})]})]})}if(U===`host:cost`){let e=ie?.cost??0,t=de.tooltip||w(`cumulativeCost`);return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cost bar-item-cost${e<=0?` is-zero`:``}${W?` has-name`:``}`,title:t,"data-tip":t,onContextMenu:ge,"data-bar-item":U,children:[W?(0,$.jsx)(`span`,{className:`bar-item-text`,children:W}):null,de.symbol?(0,$.jsx)(`span`,{className:`bar-item-char`,children:de.symbol}):null,(0,$.jsx)(`span`,{className:`bar-item-text`,children:de.value})]})}if(U===`host:msg-count`){let e=ie?.totalMessages??0,t=`${w(`sessionMessages`)}: ${e}`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-msg-count bar-item-msg-count${e===0?` is-zero`:``}`,title:t,"data-tip":t,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(Ae,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(String(e))})]})}if(U===`host:working`){if(!ae&&!se)return null;let e=ae||R,t=w(e?`working`:`done`),n=se?Math.max(0,Math.floor(((se.finishedAt??ue)-se.startedAt)/1e3)):0,r=n<3600?`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`:`${Math.floor(n/3600)}:${String(Math.floor(n/60)%60).padStart(2,`0`)}:${String(n%60).padStart(2,`0`)}`,i=(L?.queue?.steering?.length??0)+(L?.queue?.followUp?.length??0);return(0,$.jsxs)(`span`,{className:`bar-item status-item bar-item-working${e?` working`:``}`,title:`${t}${se?` · ${r}`:``}`,"data-tip":`${t}${se?` · ${r}`:``}`,onContextMenu:ge,"data-bar-item":U,children:[e&&(0,$.jsx)(`span`,{className:`working-spin`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[G(t),i>0&&` ⏳ ${i}`]}),se&&(0,$.jsx)(`span`,{className:`bar-item-duration`,children:r}),e&&me>0&&(0,$.jsx)(`span`,{className:`status-rate bar-item-rate`,title:w(`rateTip`),children:`${Math.round(me)}${w(`tps`)}`})]})}if(U===`host:status-delegate`)return L?.delegateMode?(0,$.jsxs)(`span`,{className:`bar-item status-item delegate-badge bar-item-delegate`,title:L.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),"data-tip":L.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(`span`,{className:`bar-item-icon`,children:`🔎`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:G(w(`delegateModeBadge`))}),L.delegateConvId?(0,$.jsx)(`button`,{type:`button`,className:`delegate-badge-open`,title:w(`delegateModeOpenTip`),onClick:()=>Z({type:`switch_conversation`,id:L.delegateConvId}),children:`↗`}):null]}):null;if(U===`host:host-metrics`){let e=n.hostMetrics;if(!e)return null;let t=e.cpuPercent===null||!Number.isFinite(e.cpuPercent)?`—`:`${Math.round(e.cpuPercent)}%`,r=Number.isFinite(e.memoryPercent)?`${Math.round(e.memoryPercent)}%`:`—`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-host-metrics bar-item-host-metrics`,title:`${w(`hostResourcesTip`)}\n${w(`hostProcessor`)}: ${t} · ${w(`hostMemory`)}: ${r}`,"data-tip":`${w(`hostResourcesTip`)}\n${w(`hostProcessor`)}: ${t} · ${w(`hostMemory`)}: ${r}`,onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(E,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(`${t} · ${r}`)})]})}if(U===`host:browser`)return n.settings?.disabledAgentTools?.includes(`browser_page`)?null:(0,$.jsx)(`span`,{className:`bar-item-wrap`,onContextMenu:ge,"data-bar-item":U,children:(0,$.jsx)(Un,{})});let K=t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`;if(U===`host:language`)return(0,$.jsxs)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:M,onOpenChange:P,tip:G(w(`language`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(no(D))})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`language`)}),O.map(e=>(0,$.jsx)(gt,{active:D===e.code,onClick:()=>{k(e.code),P(!1)},children:e.nativeName},e.code)),v?.onLocaleModalOpen?(0,$.jsxs)(gt,{onClick:()=>{P(!1),v.onLocaleModalOpen?.()},children:[(0,$.jsx)(S,{}),` `,w(`localeGetMore`)]}):null]});if(U===`host:theme`){let e=v?.themes??[],n=v?.theme??null;return(0,$.jsx)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:ee,onOpenChange:t=>{F(t),t&&e.length===0&&v?.reloadThemes?.()},tip:G(w(`theme`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(N,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:G(w(`theme`))})]}),children:(()=>{let t=e.filter(e=>e.group===`classic`),r=e.filter(e=>e.group!==`classic`),i=e=>{let t=H(D)?e.name:e.nameEn??e.name,n=e.scheme===`light`?w(`themeLight`):e.scheme===`dark`?w(`themeDark`):``;return n?H(D)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[t.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`themeGroupClassics`)}),t.map(e=>(0,$.jsx)(gt,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:t.length>0?w(`themeGroupBuiltin`):w(`theme`)}),(0,$.jsx)(gt,{active:n===null,onClick:()=>{v?.onThemeChange?.(null),F(!1)},children:w(`themeDefault`)}),r.map(e=>(0,$.jsx)(gt,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]})})()})}if(U===`host:update`){let e=v?.updatesCount??0;return v?.managed?(0,$.jsxs)(`span`,{className:`bar-item chip`,title:w(`updatesManaged`),"data-tip":w(`updatesManaged`),onContextMenu:ge,"data-bar-item":U,children:[(0,$.jsx)(S,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(`v${v?.appVersion??n.update?.current??`…`}`)})]}):(0,$.jsxs)(_t,{direction:K,align:t===`right`?`right`:`left`,portal:!0,open:te,onOpenChange:e=>{re(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},tip:G(w(`update`)),fit:!0,caret:!1,triggerClassName:`bar-item chip`,onContextMenu:ge,dataBarItem:U,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(S,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(`v${n.update?.current??`…`}`)}),n.update&&!n.update.upToDate&&(0,$.jsx)(`span`,{className:`update-dot`}),e>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:e})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`update`)}),v?.renderUpdateBody?.(),v?.renderAllUpdatesBody?.()]})}let q=null,J=e.label,ve=null,Y=!1,be=!1,xe=``,Se,Ce,we;switch(U){case`host:chat`:q=(0,$.jsx)(Ae,{className:`bar-item-icon`}),J=G(w(`chat`)),Y=r===`chat`,be=!0,Ce=()=>a?.(`chat`);break;case`host:terminal`:q=(0,$.jsx)(o,{className:`bar-item-icon`}),J=G(w(`terminal`)),Y=r===`terminal`,be=!0,Ce=()=>a?.(`terminal`);break;case`host:git`:q=(0,$.jsx)(ce,{className:`bar-item-icon`}),J=G(w(`scmTab`)),Y=r===`git`,be=!0,Ce=()=>a?.(`git`);break;case`host:canvas`:q=(0,$.jsx)(On,{className:`bar-item-icon`}),J=G(w(`canvasTab`)),Y=r===`canvas`,be=!0,Ce=()=>a?.(`canvas`);break;case`host:new-chat`:q=(0,$.jsx)(rt,{className:`bar-item-icon`}),J=G(w(`newChat`)),xe=`chip newchat`,Ce=()=>{a?.(`chat`),Z({type:`new_chat`}),Xt()};break;case`host:new-ephemeral-chat`:if(j)return null;q=(0,$.jsx)(kn,{className:`bar-item-icon`}),J=G(w(`newChatEphemeral`)),xe=`chip newchat ephemeral-chat-btn`,Ce=()=>{a?.(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt()};break;case`host:new-sandbox`:q=(0,$.jsx)(An,{className:`bar-item-icon`}),J=G(w(`newSandbox`)),xe=`chip newchat sandbox-chip`,Ce=()=>C?.();break;case`host:history`:if(r&&r!==`chat`)return null;q=(0,$.jsx)(ze,{className:`bar-item-icon`}),J=G(w(`openHistory`)),xe=`panel-toggle`,Ce=()=>s?.(`left`);break;case`host:files`:if(r&&r!==`chat`)return null;q=(0,$.jsx)(Be,{className:`bar-item-icon`}),J=G(w(`openFiles`)),xe=`panel-toggle has-label`,Ce=()=>s?.(`right`);break;case`host:open-project`:q=(0,$.jsx)(y,{className:`bar-item-icon`}),J=G(w(`openProject`)),xe=`chip open-project`,Y=!!h,Ce=()=>d?.();break;case`host:search`:q=(0,$.jsx)(Ee,{className:`bar-item-icon`}),J=G(w(`searchGlobal`)),xe=`chip`,Ce=()=>l?.();break;case`host:tasks`:q=(0,$.jsx)(fe,{className:`bar-item-icon`}),J=G(w(`bgTasks`)),xe=`chip bg-task-chip`,n.bgServers.length>0&&(ve=(0,$.jsx)(`span`,{className:`bg-task-badge bar-item-badge`,children:n.bgServers.length})),Ce=()=>u?.();break;case`host:zen-mode`:q=(0,$.jsx)(ne,{className:`bar-item-icon`}),J=G(w(`zenMode`)),xe=`chip chip-zen`,Y=!!b,Se=w(`zenModeTip`),Ce=()=>x?.();break;case`host:device-center`:q=(0,$.jsx)(le,{className:`bar-item-icon`}),J=G(w(`deviceCenter`)),xe=`chip`,Se=w(`deviceCenterTip`),be=!0,Y=r===`devices`,Ce=()=>a?.(`devices`);break;case`host:settings`:q=(0,$.jsx)(T,{className:`bar-item-icon`}),J=G(w(`settings`)),xe=`chip`,Ce=()=>c?.();break;case`host:plugins`:q=(0,$.jsx)(ye,{className:`bar-item-icon`}),J=G(w(`pluginMenuTitle`)),xe=`chip`,Ce=e=>{p?p(e.currentTarget):c?.(`plugins`)};break;case`host:github`:q=(0,$.jsx)(oe,{className:`bar-item-icon`}),J=G(`GitHub`),xe=`chip github`,Ce=()=>window.open(`https://github.com/xing-shuyin/pi-web-ui`,`_blank`,`noreferrer,noopener`);break;case`host:cwd`:q=(0,$.jsx)(Be,{className:`bar-item-icon`}),J=_e(L?.cwd?L.cwd.split(/[/\\]/).pop()||L.cwd:w(`openProject`)),xe=`status-item status-cwd`,Y=!!h,Ce=()=>{he.current!==null&&(window.clearTimeout(he.current),he.current=null),he.current=window.setTimeout(()=>{d?.(),he.current=null},220)},we=e=>{e.preventDefault(),e.stopPropagation(),he.current!==null&&(window.clearTimeout(he.current),he.current=null),Z({type:`new_chat`}),Xt()};break;case`host:plugin-status`:if(n.statuses.length===0)return null;q=(0,$.jsx)(Je,{className:`bar-item-icon`}),J=_e(n.statuses.map(e=>e.text).join(` · `)),xe=`status-item ext-status`;break;default:if(e.kind===`view`){let t=e.view??``;Y=r===t,be=!0;let o=(i??n.plugins??[]).find(t=>`plugin:${t.id}`===e.source);xe=`plugin-tab${o?.error?` broken`:``}`,o?.error&&(Se=`${e.label}: ${o.error}`);let s=e.iconSvg||o?.iconSvg,c=e.icon||o?.icon;q=s?(0,$.jsx)(Ir,{icon:c,iconSvg:s,className:`bar-item-icon plugin-icon-svg`}):c?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:c}):null,Ce=()=>a?.(t)}else{let n=e.iconSvg,r=e.icon;xe=t===`bottom`?`status-item status-action chip`:`chip`,q=n?(0,$.jsx)(Ir,{icon:r,iconSvg:n,className:`bar-item-icon plugin-icon-svg`}):r?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:r}):null,e.badge&&(ve=(0,$.jsx)(`span`,{className:`bar-item-badge`,children:e.badge})),Ce=()=>g?.(e)}}let Te=Se??e.hint??J,De=[`bar-item`,be?`tb-tab${Y?` active`:``}`:``,xe,Y&&!be?`active`:``].filter(Boolean).join(` `);return(0,$.jsxs)(`button`,{type:`button`,role:be?`tab`:void 0,"aria-selected":be?Y:void 0,"aria-haspopup":U===`host:plugins`?`menu`:void 0,"aria-expanded":U===`host:plugins`?!!m:void 0,className:De,title:Te,"data-tip":Te,"aria-label":J,onClick:Ce,onDoubleClick:we,onContextMenu:ge,"data-bar-item":U,children:[q,(0,$.jsx)(`span`,{className:`bar-item-text`,children:J}),ve]})}function io(){let{locale:e}=Ue(),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(()=>typeof window<`u`);if((0,Q.useEffect)(()=>{i(!0);let e=Ct();if(!e)return;e.isMaximized().then(n);let t=e.onMaximizedChange(e=>{n(e)});return()=>t()},[]),!r||!wt()||Tt()===`darwin`)return null;let a=Ct();if(!a)return null;let o=H(e);return(0,$.jsxs)(`div`,{className:`window-controls`,"aria-label":`Window controls`,children:[(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void a.minimize(),title:o?`最小化`:`Minimize`,"aria-label":o?`最小化`:`Minimize`,children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M1.5 5.5H9.5`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void a.toggleMaximize(),title:t?o?`向下还原`:`Restore`:o?`最大化`:`Maximize`,"aria-label":t?o?`向下还原`:`Restore`:o?`最大化`:`Maximize`,children:t?(0,$.jsxs)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:[(0,$.jsx)(`path`,{d:`M3 3V1.5C3 1.22 3.22 1 3.5 1H9.5C9.78 1 10 1.22 10 1.5V7.5C10 7.78 9.78 8 9.5 8H8`,stroke:`currentColor`,strokeWidth:`1.1`}),(0,$.jsx)(`rect`,{x:`1`,y:`3`,width:`7`,height:`7`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})]}):(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`rect`,{x:`1.5`,y:`1.5`,width:`8`,height:`8`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn win-ctrl-close`,onClick:()=>void a.close(),title:o?`关闭`:`Close`,"aria-label":o?`关闭`:`Close`,children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 2L9 9M9 2L2 9`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})})]})}var ao={name:`@earendil-works/pi-coding-agent`,kind:`pi-core`,current:``,latest:null,upToDate:!1};function oo({anchorRef:e,open:t,onClose:n,children:r}){let{panelRef:i,style:a,measure:o}=Cn({open:t,anchor:e,onClose:n});return(0,Q.useLayoutEffect)(()=>{t&&o()},[t,r,o]),t?(0,bn.createPortal)((0,$.jsx)(`div`,{ref:i,className:`plugin-topbar-menu portal`,role:`menu`,style:a,children:r}),document.body):null}function so(){let[e,t]=(0,Q.useState)(()=>typeof window<`u`&&window.matchMedia!==void 0&&window.matchMedia(`(max-width: 768px)`).matches);return(0,Q.useEffect)(()=>{if(typeof window>`u`||window.matchMedia===void 0)return;let e=window.matchMedia(`(max-width: 768px)`),n=e=>t(e.matches);return typeof e.addEventListener==`function`?e.addEventListener(`change`,n):e.addListener(n),()=>{typeof e.removeEventListener==`function`?e.removeEventListener(`change`,n):e.removeListener(n)}},[]),e}function co({chat:e,terminal:t,view:n,plugins:r,uiPrimary:i,uiOverflow:a,uiContextTopbar:s,onUiAction:c,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onManagePlugins:f,onOpenBgTasks:p,onOpenGlobalSearch:m,themes:h,theme:g,onThemeChange:_,reloadThemes:v,onOpenIconEdit:b,zenMode:x,onToggleZenMode:C,onOpenSandboxModal:w}){let{locale:E,setLocale:D,t:O,packs:k}=Ue(),[A,j]=(0,Q.useState)(!1),[P,ee]=(0,Q.useState)(!1),[F,te]=(0,Q.useState)(null),[re,I]=(0,Q.useState)(!1),[L,ie]=(0,Q.useState)(null),ae=en(`cwd`),se=en(`workspaceRoots`),R=$t(),ue=rn().ephemeralChat!==!1&&!R,z=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{z.current!==null&&window.clearTimeout(z.current)},[]);let de=(0,Q.useRef)(null),B=t=>!e.tabs||t===`chat`||e.tabs.includes(t),V=[...a??[]].filter(e=>(e.source!==`host`||e.id!==`host:brand`)&&!ii(e)),pe=new Set([...i??[],...a??[]].filter(e=>ii(e)&&!e.hidden).map(e=>e.source.slice(7))),me=new Map((e.settings?.uiLayout?.order??[]).map((e,t)=>[e,t])),he=r.map((e,t)=>({id:e.id,index:t})).sort((e,t)=>(me.get(`${e.id}:__view`)??1e6+e.index)-(me.get(`${t.id}:__view`)??1e6+t.index)).map(e=>e.id),ge=i===void 0?[`host:history`,`host:brand`,`host:engine`,`host:open-project`,`host:chat`,`host:terminal`,`host:git`,`host:canvas`,`host:plugins`,`host:search`,`host:browser`,`host:tasks`,`host:zen-mode`,`host:device-center`,`host:settings`,`host:language`,`host:theme`,`host:update`,`host:github`,`host:new-chat`,`host:new-ephemeral-chat`,`host:new-sandbox`,`host:files`].map(e=>({id:e,entry:null})):i.map(e=>({id:e.id,entry:e})),U=(B(`plugins`)?r:[]).filter(e=>e.view!==!1&&e.error&&!ge.some(t=>t.id===`${e.id}:__view`)).map(e=>({id:`${e.id}:__view`,slot:`topbar.primary`,source:`plugin:${e.id}`,label:e.name,kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!1,userOverrides:[],arrangedBy:[]})),W=e=>{if(e.source!==`host`)return!1;switch(e.id){case`host:history`:return u(`left`),!0;case`host:files`:return u(`right`),!0;case`host:new-chat`:return l(`chat`),Z({type:`new_chat`}),Xt(),!0;case`host:new-ephemeral-chat`:return l(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt(),!0;case`host:new-sandbox`:return w?.(),!0;case`host:open-project`:return ee(!0),!0;case`host:search`:return m(),!0;case`host:tasks`:return p(),!0;case`host:zen-mode`:return C?.(),!0;case`host:device-center`:return l(`devices`),!0;case`host:settings`:return d(),!0;case`host:plugins`:return te(de.current?{rect:de.current.getBoundingClientRect(),el:de.current}:null),!0;default:return!1}},G=(t,n,r)=>{t.preventDefault(),t.stopPropagation();let i=e.settings?.uiLayout,a=e=>{let t={...i?.slots,[n]:e},r={...i?.align};(e===`sidebar.left`||e===`sidebar.right`)&&!r[n]&&(r[n]=`center`),Z({type:`set_settings`,uiLayout:{...i,slots:t,...r[n]?{align:r}:{}}})},o=()=>{let e=new Set(i?.hidden??[]);e.add(n);let t=(i?.shown??[]).filter(e=>e!==n);Z({type:`set_settings`,uiLayout:{...i,hidden:[...e],shown:t}})},c=()=>{Z({type:`set_settings`,uiLayout:Ti(i,n)})},l=[{id:`host:move-bottom`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToBottom`),kind:`action`,order:10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-left`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToLeft`),kind:`action`,order:20,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-right`,slot:`contextmenu.topbar`,source:`host`,label:O(`moveToRight`),kind:`action`,order:30,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}];ti.has(n)||l.push({id:`host:hide-item`,slot:`contextmenu.topbar`,source:`host`,label:O(`uiLayoutHide`),kind:`action`,order:40,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),(i?.slots?.[n]||i?.labels?.[n]||i?.align?.[n]||i?.order?.includes(n))&&l.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:O(`uiLayoutRestore`),kind:`action`,order:50,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),s&&s.length>0&&l.push(...s),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.topbar`,target:{id:n,label:r},entries:l,onHostAction:e=>{e.id===`host:move-bottom`?a(`bottombar`):e.id===`host:move-left`?a(`sidebar.left`):e.id===`host:move-right`?a(`sidebar.right`):e.id===`host:hide-item`?o():e.id===`host:restore-item`&&c()}})},{appVersion:_e}=Qt(),K=tn(),q=sn(),[J,ve]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{J&&e.status===`open`&&ve(!1)},[J,e.status]);let[Y,be]=(0,Q.useState)(!1),[xe,Se]=(0,Q.useState)(!1),[Ce,we]=(0,Q.useState)(!1),Te=wt(),De=Wa(),[X,Oe]=(0,Q.useState)(!1),ke=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{if(ke.current.size===0)return;let t=!1;for(let n of Array.from(ke.current)){let r=e.terminals.find(e=>e.id===n);r&&!r.running&&(ke.current.delete(n),t=!0)}t&&e.ready&&(Z({type:`check_update`}),Z({type:`check_updates_all`,force:!0}))},[e.terminals,e.ready]);let je=()=>{if(!e.ready)return;let n=O(`updateTabTitle`),r={name:n,command:`npm i -g pi-web-ui@latest`,cwd:"${pwd}"},i=e.terminals.find(e=>e.title===n);if(i)ke.current.add(i.id),t.restart(i.id),Z({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:r,cols:80,rows:24});else{let i=ht();ke.current.add(i),t.create({id:i,conversationId:e.activeConversationId||e.state?.conversationId||``,title:n,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:r})}we(!1),l(`terminal`)},Me=(n,r)=>{if(!e.ready||n.length===0)return;let i={name:r,command:jn(n),cwd:"${pwd}"},a=e.terminals.find(e=>e.title===r);if(a)ke.current.add(a.id),t.restart(a.id),Z({type:`run_command`,terminalId:a.id,conversationId:a.conversationId,command:i,cols:80,rows:24});else{let n=ht();ke.current.add(n),t.create({id:n,conversationId:e.activeConversationId||e.state?.conversationId||``,title:r,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:i})}we(!1),l(`terminal`)},Ne=e.updatesAll??[],Pe=e.updatesSdk,Fe=Pe&&Pe.newerInstalled?{running:Pe.running,installed:Pe.newerInstalled}:null,Ie=Pe?.bundledInUse===!0,Le=Ne.find(e=>e.kind===`pi-core`&&!e.error),Re=Ie&&(!Le||!Le.upToDate),Ve=Re&&!Le,He=Ne.filter(e=>!e.upToDate&&!e.error).length,We=Ne.filter(e=>!e.upToDate&&!e.error&&e.kind!==`webui`),Ge=e=>e.kind===`git-extension`&&e.source?e.source:e.name,Ke=e=>e.kind===`git-extension`&&e.source&&e.source!==e.name?`${e.source} (${e.name})`:e.name,qe=e=>{let t=e.replace(/ \([0-9a-f]{7}\)$/,``);return/^[0-9a-f]{7}$/.test(t)?``:t},Je=e=>(e.match(/\(([0-9a-f]{7})\)$/)??e.match(/^([0-9a-f]{7})$/))?.[1]??null,Xe=(e,t)=>{if(!t)return qe(e);let n=qe(e),r=qe(t);if(n!==r)return`${n} → ${r}`;let i=Je(e),a=Je(t);return i&&a&&i!==a?n?`${n} (${i} → ${a})`:`${i} → ${a}`:n},Ze=()=>(0,$.jsxs)(`div`,{className:`dd-updates-all`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`updatesAllTitle`)}),e.updatesAll===null?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`checkingUpdate`)}):Ne.length===0?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updatesAllUpToDate`)}):(0,$.jsx)(`ul`,{className:`dd-all-list`,children:Ne.map(e=>{let t=Fe!=null&&e.kind===`pi-core`,n=!e.error&&(!e.upToDate||t);return(0,$.jsxs)(`li`,{className:`dd-all-item${e.error?` err`:n?` warn`:``}`,children:[e.kind!==`webui`&&!e.upToDate&&!e.error&&(0,$.jsx)(`button`,{type:`button`,className:`dd-update-btn`,onClick:()=>Me([e],O(`updatePkgTabTitle`,{name:e.name})),children:O(`updateBtn`)}),(0,$.jsx)(`span`,{className:`dd-all-name`,title:Ke(e),children:Ge(e)}),(0,$.jsxs)(`span`,{className:`dd-all-meta`,children:[(0,$.jsx)(`span`,{className:`dd-all-kind`,children:e.kind===`webui`?O(`kindWebUi`):e.kind===`pi-core`?O(`kindPiCore`):e.kind===`engine`?O(`kindEngine`):e.kind===`git-extension`?O(`kindGitExtension`):e.kind===`plugin`?O(`kindPlugin`):O(`kindPackage`)}),(0,$.jsx)(`span`,{className:`dd-all-vers`,title:e.error?e.error:e.kind===`git-extension`?e.upToDate?e.current:`${e.current} → ${e.latest}`:void 0,children:e.error?e.kind===`pi-core`&&e.current===`unknown`?O(`piCoreUndetected`):O(`updateCheckFailed`):e.kind===`git-extension`?e.upToDate?qe(e.current):Xe(e.current,e.latest):e.kind===`plugin`?e.upToDate?e.current.startsWith(`v`)?e.current:qe(e.current):Xe(e.current,e.latest):e.upToDate?`v${e.current}`:(0,$.jsxs)($.Fragment,{children:[`v`,e.current,` → v`,e.latest]})}),t&&!e.error&&(0,$.jsx)(`span`,{className:`dd-split-run`,children:O(`piCoreSplitRun`,{running:Fe.running})})]})]},`${e.kind}:${e.name}`)})}),Fe&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`piSdkSplitNote`,{running:Fe.running,installed:Fe.installed})}),Re&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`piSdkBundledNote`,{running:Pe.running})}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[Ve&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Me([ao],O(`installGlobalEngineTabTitle`)),children:O(`installGlobalEngineBtn`)}),We.length>0&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Me(We,O(`updateAllTabTitle`)),children:O(`updateAllBtn`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,style:We.length>0?{flex:1}:void 0,onClick:()=>Z({type:`check_updates_all`,force:!0}),children:O(`updatesAllRefresh`)})]})]}),Qe=()=>{let t=Ua(e.update?.latest??De.version),n=(0,$.jsx)(`a`,{className:`dd-refresh dd-more-link`,href:t,target:`_blank`,rel:`noreferrer noopener`,children:O(`updateDesktopManual`)});if(!De.bridge)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopNoBridge`)}),n]});switch(De.state){case`checking`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopChecking`)}),n]});case`available`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopAvailable`,{version:De.version??e.update?.latest??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.download(),children:O(`updateDesktopDownload`)}),n]});case`downloading`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopDownloading`,{n:De.percent})}),n]});case`downloaded`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`updateDesktopDownloaded`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.quitAndInstall(),children:O(`updateDesktopInstall`)}),n]});case`up-to-date`:return(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`upToDate`)});case`error`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopError`,{error:De.message??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>De.check(),children:O(`updateDesktopCheck`)}),n]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>De.check(),children:O(`updateDesktopCheck`)}),n]})}},$e=()=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-update`,children:[(0,$.jsxs)(`div`,{className:`dd-row`,children:[(0,$.jsx)(`span`,{children:O(`currentVersion`)}),(0,$.jsxs)(`b`,{children:[`v`,e.update?.current??`…`]})]}),(0,$.jsxs)(`div`,{className:`dd-row`,children:[(0,$.jsx)(`span`,{children:O(`latestVersion`)}),(0,$.jsx)(`b`,{children:e.update===null?O(`checkingUpdate`):e.update.error?e.update.error:e.update.latest?`v${e.update.latest}`:O(`checkingUpdate`)})]}),e.update&&e.update.upToDate&&(0,$.jsx)(`div`,{className:`dd-note ok`,children:O(`upToDate`)}),e.update&&!e.update.upToDate&&e.update.latest&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateAvailable`,{version:e.update.latest})}),e.update?.latestPublishedAt&&Date.now()-new Date(e.update.latestPublishedAt).getTime()<18e5&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateJustPublished`,{version:e.update.latest??``})}),e.update&&!e.update.upToDate&&e.update.latest&&!Te&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateTerminalHint`)}),e.update&&!e.update.upToDate&&e.update.latest&&Te&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopNote`)})]}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>Z({type:`check_update`}),children:e.update===null?O(`checkingUpdate`):O(`checkUpdate`)}),e.update&&!e.update.upToDate&&e.update.latest&&!Te&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:je,children:O(`updateNow`)}),e.update&&!e.update.upToDate&&e.update.latest&&Te&&Qe(),q&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,disabled:J,title:O(`restartServiceTip`,{name:q.name}),onClick:()=>{J||(ve(!0),Z({type:`restart_service`}))},children:O(J?`restartingService`:`restartService`)})]})]}),et=so(),tt={"host:brand":(0,$.jsx)(En,{}),"host:open-project":(0,$.jsxs)(`button`,{type:`button`,className:`chip open-project`,"data-tip":O(`openProject`),onClick:()=>ee(!0),children:[(0,$.jsx)(y,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`openProject`)})]}),"host:history":n===`chat`&&B(`history`)?(0,$.jsx)(`button`,{type:`button`,className:`panel-toggle`,"data-tip":O(`openHistory`),"aria-label":O(`openHistory`),onClick:()=>u(`left`),children:(0,$.jsx)(ze,{})}):null,"host:files":n===`chat`&&B(`files`)?(0,$.jsxs)(`button`,{type:`button`,className:`panel-toggle has-label`,"data-tip":O(`openFiles`),"aria-label":O(`openFiles`),onClick:()=>u(`right`),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:O(`openFiles`)})]}):null,"host:new-chat":B(`new-chat`)?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat`,"data-tip":O(`newChatTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`}),Xt()},children:[(0,$.jsx)(rt,{}),(0,$.jsx)(`span`,{children:O(`newChat`)})]}):null,"host:new-ephemeral-chat":ue?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat ephemeral-chat-btn`,"data-tip":O(`newChatEphemeralTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`,ephemeral:!0}),Xt()},children:[(0,$.jsx)(kn,{}),(0,$.jsx)(`span`,{children:O(`newChatEphemeral`)})]}):null,"host:new-sandbox":(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat sandbox-chip`,"data-tip":O(`newSandboxTip`),"aria-label":O(`newSandboxTip`),onClick:()=>w?.(),children:[(0,$.jsx)(An,{}),(0,$.jsx)(`span`,{children:O(`newSandbox`)})]}),"host:chat":(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`chat`,className:`tb-tab${n===`chat`?` active`:``}`,"data-tip":O(`chat`),onClick:()=>l(`chat`),children:[(0,$.jsx)(Ae,{}),(0,$.jsx)(`span`,{children:O(`chat`)})]}),"host:terminal":B(`terminal`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`terminal`,className:`tb-tab${n===`terminal`?` active`:``}`,"data-tip":O(`terminal`),onClick:()=>l(`terminal`),children:[(0,$.jsx)(o,{}),(0,$.jsx)(`span`,{children:O(`terminal`)})]}):null,"host:git":B(`git`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`git`,className:`tb-tab${n===`git`?` active`:``}`,"data-tip":O(`scmTab`),onClick:()=>l(`git`),children:[(0,$.jsx)(ce,{}),(0,$.jsx)(`span`,{children:O(`scmTab`)})]}):null,"host:canvas":B(`canvas`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`canvas`,className:`tb-tab${n===`canvas`?` active`:``}`,"data-tip":O(`canvasTab`),onClick:()=>l(`canvas`),children:[(0,$.jsx)(On,{}),(0,$.jsx)(`span`,{children:O(`canvasTab`)})]}):null,"host:plugins":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`pluginMenuTitle`),"aria-haspopup":`menu`,"aria-expanded":F!==null,onClick:e=>{let t=e.currentTarget;te(e=>e?.el===t?null:{rect:t.getBoundingClientRect(),el:t})},children:[(0,$.jsx)(ye,{"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`pluginMenuTitle`)})]}),"host:search":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`searchGlobalTip`),onClick:m,children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`searchGlobal`)})]}),"host:browser":e.settings?.disabledAgentTools?.includes(`browser_page`)??!1?null:(0,$.jsx)(Un,{}),"host:tasks":(0,$.jsxs)(`button`,{type:`button`,className:`chip bg-task-chip`,"data-tip":O(`bgTasksTip`),onClick:p,children:[(0,$.jsx)(fe,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`bgTasks`)}),e.bgServers.length>0&&(0,$.jsx)(`span`,{className:`bg-task-badge`,children:e.bgServers.length})]}),"host:zen-mode":(0,$.jsxs)(`button`,{type:`button`,className:`chip chip-zen${x?` active`:``}`,"data-tip":O(`zenModeTip`),onClick:C,"aria-label":O(`zenMode`),"aria-pressed":x,children:[(0,$.jsx)(ne,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`zenMode`)})]}),"host:device-center":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`deviceCenterTip`),onClick:()=>l(`devices`),"aria-pressed":n===`devices`,children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`deviceCenter`)})]}),"host:settings":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":O(`settingsTitle`),onClick:d,children:[(0,$.jsx)(T,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`settings`)})]}),"host:language":(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:Ye(E)})]}),tip:O(`language`),open:Y,onOpenChange:be,caret:!1,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`language`)}),k.map(e=>(0,$.jsx)(gt,{active:E===e.code,onClick:()=>{D(e.code),be(!1)},children:e.nativeName},e.code)),(0,$.jsxs)(gt,{onClick:()=>{be(!1),Oe(!0)},children:[(0,$.jsx)(S,{}),` `,O(`localeGetMore`)]})]}),"host:theme":(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(N,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`theme`)})]}),tip:O(`theme`),open:xe,caret:!1,onOpenChange:e=>{Se(e),e&&h.length===0&&v()},children:(()=>{let e=h.filter(e=>e.group===`classic`),t=h.filter(e=>e.group!==`classic`),n=e=>{let t=H(E)?e.name:e.nameEn??e.name,n=e.scheme===`light`?O(`themeLight`):e.scheme===`dark`?O(`themeDark`):``;return n?H(E)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[e.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`themeGroupClassics`)}),e.map(e=>(0,$.jsx)(gt,{active:g===e.id,onClick:()=>{_(e.id),Se(!1)},children:n(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:e.length>0?O(`themeGroupBuiltin`):O(`theme`)}),(0,$.jsx)(gt,{active:g===null,onClick:()=>{_(null),Se(!1)},children:O(`themeDefault`)}),t.map(e=>(0,$.jsx)(gt,{active:g===e.id,onClick:()=>{_(e.id),Se(!1)},children:n(e)},e.id))]})})()}),"host:update":K?(0,$.jsxs)(`span`,{className:`chip`,"data-tip":O(`updatesManaged`),children:[(0,$.jsx)(S,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,_e??e.update?.current??`…`]})]}):(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(S,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,e.update?.current??`…`]}),e.update&&!e.update.upToDate&&(0,$.jsx)(`span`,{className:`update-dot`,title:O(`updateAvailable`,{version:e.update.latest??``})}),He>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:O(`updatesAllBadge`,{n:He})})]}),tip:O(`update`),open:Ce,caret:!1,onOpenChange:e=>{we(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},fit:!0,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`update`)}),$e(),Ze()]}),"host:github":(0,$.jsx)(`a`,{className:`chip github`,href:`https://github.com/xing-shuyin/pi-web-ui`,target:`_blank`,rel:`noreferrer noopener`,"data-tip":O(`githubRepo`),children:(0,$.jsx)(oe,{})}),"host:conn":(0,$.jsxs)(`span`,{className:`chip`,"data-tip":e.status,children:[(0,$.jsx)(`span`,{className:`status-dot ${e.status===`open`?`ok`:`busy`}`}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.status})]}),"host:engine":(0,$.jsx)(Qa,{direction:`down`,align:`left`,caret:!1,bar:`top`}),"host:ctx":(0,$.jsx)(`span`,{className:`chip`,"data-tip":O(`contextUsage`),children:(0,$.jsx)(`span`,{className:`chip-sub`,children:(e.state?.stats?.contextUsage?.tokens??0)>0?`${e.state?.stats?.contextUsage?.tokens}`:O(`contextUsage`)})}),"host:cost":(()=>{let t=Jt(e.state?.stats?.cost??0,{fixedDigits:4});return(0,$.jsx)(`span`,{className:`chip`,"data-tip":t.tooltip||O(`cumulativeCost`),children:(0,$.jsxs)(`span`,{className:`chip-sub`,children:[t.symbol,t.value]})})})(),"host:cwd":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":e.state?.cwd??``,onClick:()=>{z.current!==null&&(window.clearTimeout(z.current),z.current=null),z.current=window.setTimeout(()=>{ee(!0),z.current=null},220)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),z.current!==null&&(window.clearTimeout(z.current),z.current=null),Z({type:`new_chat`}),Xt()},children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.state?.cwd?.split(/[/\\]/).pop()||e.state?.cwd})]})},nt=new Set([`host:search`,`host:tasks`,`host:settings`,`host:plugins`]),it=new Set([`host:language`,`host:theme`,`host:update`,`host:browser`,`host:engine`]),at=e=>nt.has(e)&&!B(e.slice(5)),ot=e=>{if(e.kind===`view`){if(!B(`plugins`))return null;let t=e.view??``,i=r.find(t=>`plugin:${t.id}`===e.source),a=i?.error?`${e.label}: ${i.error}`:e.hint??e.label;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===t,className:`tb-tab plugin-tab${n===t?` active`:``}${i?.error?` broken`:``}`,"data-tip":a,onClick:()=>l(t),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`plugin-topbar-item plugin-topbar-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>c?.(e,t.target.value),onContextMenu:t=>G(t,e.id,e.label),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`plugin-topbar-item`,"data-tip":e.hint??e.label,onClick:()=>c?.(e),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ir,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)},st=[];for(let t of ge){if(t.entry?.hidden||at(t.id))continue;let i=null;t.entry?i=(0,$.jsx)(ro,{entry:t.entry,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onOpenGlobalSearch:m,onOpenBgTasks:p,onOpenProjectPicker:()=>ee(!0),isProjectPickerOpen:P,onOpenPluginMenu:e=>te(t=>t?.el===e?null:{rect:e.getBoundingClientRect(),el:e}),isPluginMenuOpen:F!==null,onUiAction:c,uiContextEntries:s,zenMode:x,onToggleZenMode:C,onOpenSandboxModal:w,dropdownProps:{theme:g,themes:h,onThemeChange:_,reloadThemes:v,onLocaleModalOpen:()=>Oe(!0),renderUpdateBody:$e,renderAllUpdatesBody:Ze,updatesCount:He,managed:K,appVersion:_e}},t.id):t.id.startsWith(`host:`)&&tt[t.id]&&(i=tt[t.id]),i&&st.push({id:t.id,entry:t.entry,node:i})}for(let t of U){let i=(0,$.jsx)(ro,{entry:t,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onUiAction:c,uiContextEntries:s},t.id);i&&st.push({id:t.id,entry:t,node:i})}let ct=e=>e.entry?.align??`start`,[lt,ut]=(0,Q.useState)(()=>new Set),dt=(0,Q.useRef)(null),ft=(0,Q.useRef)(new Map),pt=st.filter(e=>!lt.has(e.id)),mt=et?pt.filter(e=>Oi.has(e.id)):[],vt=et?pt.filter(e=>!Oi.has(e.id)):pt,yt=et?st.filter(e=>!Oi.has(e.id)):st,bt=[...yt.filter(e=>ct(e)===`start`),...yt.filter(e=>ct(e)===`center`),...yt.filter(e=>ct(e)===`end`)],xt=bt.filter(e=>!lt.has(e.id)),St=(0,Q.useRef)(bt),Ct=(0,Q.useRef)(xt);(0,Q.useLayoutEffect)(()=>{St.current=bt,Ct.current=xt});let Tt=()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`)),n=Ct.current;t.length===n.length&&n.forEach((e,n)=>ft.current.set(e.id,t[n].offsetWidth));for(let n of t){let t=n;t.offsetWidth>0&&e.clientWidth>0&&t.offsetLeft+t.offsetWidth/2<Math.min(220,e.clientWidth/2)?t.setAttribute(`data-tip-align`,`right`):t.removeAttribute(`data-tip-align`)}let r=Number.parseFloat(getComputedStyle(e).columnGap)||0,i=St.current,a=Ai(i.map(e=>({id:e.id,width:e.entry?ft.current.get(e.id)??0:0})),e.clientWidth,r,0,ti);ut(e=>e.size===a.size&&[...a].every(t=>e.has(t))?e:a)},Et=`${pt.map(e=>`${e.id}:${e.entry?.label??``}`).join(`|`)}|${n}|${(e.tabs??[]).join(`,`)}|${et?`m`:`d`}`;(0,Q.useLayoutEffect)(Tt,[Et]),(0,Q.useEffect)(()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>Tt());return t.observe(e),()=>t.disconnect()},[Et]);let Dt=vt.filter(e=>ct(e)===`start`),Ot=vt.filter(e=>ct(e)===`center`),kt=vt.filter(e=>ct(e)===`end`),At=st.filter(e=>lt.has(e.id)&&e.entry).map(e=>e.entry),jt=new Map;[...i??[],...a??[]].forEach((e,t)=>{jt.has(e.id)||jt.set(e.id,t)});let Mt=ki([...V,...At],e=>jt.get(e)??999999),Nt=e=>e.icon&&!/[a-z]/i.test(e.icon)?e.icon:null,Pt=e.settings?.uiLayout?.topbarText===!1;return(0,$.jsxs)(`header`,{className:`topbar${Pt?` no-labels`:``}`,"data-pi-anchor":`topbar`,children:[(0,$.jsxs)(`div`,{className:`topbar-flow`,ref:dt,role:`toolbar`,"aria-label":O(`viewSwitch`),children:[Dt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(Ot.length>0||kt.length>0)&&(0,$.jsx)(`span`,{className:`tb-spacer${Ot.length===0&&kt.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Ot.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),Ot.length>0&&(0,$.jsx)(`span`,{className:`tb-spacer${kt.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),kt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id))]}),(Mt.length>0||st.length>0)&&(0,$.jsxs)(`div`,{className:`plugin-topbar-more`,children:[(0,$.jsx)(`button`,{ref:de,type:`button`,className:`plugin-topbar-item`,"aria-haspopup":`menu`,"aria-expanded":A,"aria-label":O(`pluginTopbarMore`),"data-tip":O(`pluginTopbarMore`),onClick:()=>j(e=>!e),children:(0,$.jsx)(Dn,{})}),(0,$.jsxs)(oo,{anchorRef:de,open:A,onClose:()=>j(!1),children:[Mt.map(e=>{let t=e.source===`host`&&it.has(e.id)?tt[e.id]:void 0;if(t!==void 0)return(0,$.jsx)(Q.Fragment,{children:t},e.id);if(e.source===`host`&&e.id===`host:github`)return(0,$.jsxs)(`a`,{role:`menuitem`,className:`chip github`,href:`https://github.com/xing-shuyin/pi-web-ui`,target:`_blank`,rel:`noreferrer noopener`,title:O(`githubRepo`),onClick:()=>j(!1),children:[(0,$.jsx)(oe,{}),(0,$.jsx)(`span`,{children:`GitHub`})]},e.id);if(e.source===`host`){let t=tt[e.id];if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}else{let t=ot(e);if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsxs)(`label`,{className:`plugin-topbar-overflow-select tb-row`,title:e.hint??e.label,children:[Nt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Nt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label}),(0,$.jsx)(`select`,{"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>{j(!1),W(e)||c?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]},e.id):(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,title:e.hint??e.label,onClick:()=>{j(!1),W(e)||c?.(e)},children:[Nt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Nt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label})]},e.id)}),(0,$.jsx)(`div`,{className:`tb-menu-divider`,"aria-hidden":`true`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,onClick:()=>{j(!1),b()},children:[(0,$.jsx)(M,{}),(0,$.jsx)(`span`,{className:`tb-row-text`,children:O(`uiIconEdit`)})]})]})]}),mt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(0,$.jsx)(io,{}),X&&(0,$.jsx)(Ia,{onClose:()=>Oe(!1)}),F&&(0,$.jsx)(Ca,{anchorRect:F.rect,anchorEl:F.el,plugins:r.map(t=>{let n=(e.plugins??[]).find(e=>e.id===t.id);return{...t,hasSettings:!!(n?.settingsSchema&&n.settingsSchema.length>0)}}),pinnedIds:pe,orderedPluginIds:he,onTogglePin:(t,n)=>Z({type:`set_settings`,uiLayout:ai(e.settings?.uiLayout,t,n)}),onReorder:t=>Z({type:`set_settings`,uiLayout:oi(e.settings?.uiLayout,t)}),onOpenView:e=>{te(null),l(`plugin:${e}`)},onOpenPluginSettings:e=>{ie(e??null),I(!0)},onManagePlugins:f,onClose:()=>te(null)}),re&&(0,$.jsx)(Fa,{open:re,onClose:()=>{I(!1),ie(null)},focusPluginId:L,plugins:e.plugins??[],disabledPlugins:e.settings?.disabledPlugins??[],models:e.settings?.subagentModels??[],onTogglePlugin:t=>{let n=new Set(e.settings?.disabledPlugins??[]);n.has(t.id)?n.delete(t.id):n.add(t.id),Z({type:`set_settings`,disabledPlugins:[...n]})},onOpenView:e=>{I(!1),l(`plugin:${e}`)},onOpenMarketplace:()=>{I(!1),f()}}),P&&(0,$.jsx)(ba,{open:!0,currentCwd:ae,pathCompletions:e.pathCompletions??[],workspaceRoots:se,onClose:()=>ee(!1),onSelectDirectory:e=>Z({type:`set_cwd`,path:e}),onCreateProject:e=>Z({type:`make_dir`,path:e,setAsCwd:!0})})]})}function lo(e){return`@${e.name}(${e.id})`}function uo(e,t){return e.filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(t.toLocaleLowerCase())).map(e=>({providerId:`host:group-devices`,providerLabel:`Bot`,title:e.name,hint:e.id,text:lo(e)}))}function fo(e,t){return[...new Set(t.filter(t=>e.includes(lo(t))).map(e=>e.id))]}function po(e,t,n,r=!1){let i=new Map,a=[],o=new Map(n.map(e=>[e.id,e]));for(let e of t?.bots??[])o.set(e.id,{...o.get(e.id),...e});let s=r?{queued:`排队中`,running:`运行中`,completed:`已完成`,failed:`失败`,interrupted:`已中断`}:{queued:`Queued`,running:`Running`,completed:`Completed`,failed:`Failed`,interrupted:`Interrupted`},c=new Map((t?.tasks??[]).map(e=>[e.id,e])),l=new Set,u=(e,t,n)=>{let r=e?o.get(e):void 0,i=r?.deviceName||n||r?.deviceId;return i?`${t} · ${i}`:t};for(let e of t?.messages??[]){let t=`group-message:${e.id}`;if(a.push({id:t,role:e.sender.type===`bot`?`assistant`:`user`,timestamp:e.createdAt,content:[{type:`text`,text:e.text}]}),e.sender.type!==`bot`){i.set(t,e.sender.name);continue}let n=(e.taskIds??[]).map(e=>c.get(e)).filter(t=>!!t&&t.botId===e.sender.id);for(let e of n)e.report&&l.add(e.id);let r=[...new Set(n.map(e=>s[e.status]))].join(` · `),o=u(e.sender.id,e.sender.name,e.sender.sourceDeviceId);i.set(t,r?`${o} · ${r}`:o)}for(let e of t?.tasks??[]){if(l.has(e.id))continue;let t=`group-task:${e.id}`,n=o.get(e.botId);i.set(t,`${u(e.botId,n?.name??e.botId,e.deviceId)} · ${s[e.status]}`),a.push({id:t,role:`assistant`,timestamp:e.createdAt,content:[{type:`text`,text:e.report||`${s[e.status]}\n\n${e.text}`}]})}return a.sort((e,t)=>(e.timestamp??0)-(t.timestamp??0)),{state:{clientId:`device-group`,cwd:``,sessionId:`device-group:${e}`,conversationId:`device-group:${e}`,rev:0,messages:a,streamingMessage:null,isStreaming:!1,model:null,thinkingLevel:``,availableThinkingLevels:[],queue:{steering:[],followUp:[]},tools:[],version:0,piConfigured:!0,piAgentInstalled:!0,stats:{totalMessages:a.length,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,contextUsage:{tokens:null,contextWindow:0,percent:null}}},labels:i}}function mo(e,t,n,r,i){let a=JSON.stringify({roomId:t,text:n,targetBotIds:[...r].sort()});return e?.fingerprint===a?e:{fingerprint:a,key:i()}}function ho(e,t,n){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)i--,a--;return n.flatMap(e=>{if(e.end<=r)return[e];if(e.start>=i){let t=a-i;return[{...e,start:e.start+t,end:e.end+t}]}return[]})}function go(e,t){let n=e;for(let e of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e.start)+lo(e.member)+n.slice(e.end);return{text:n,targets:[...new Set(t.map(e=>e.member.id))]}}function _o(e,t,n,r,i){let a=i.filter(i=>t===n?r===`Backspace`?t>i.start&&t<=i.end+ +(e[i.end]===` `):t>=i.start&&t<i.end:t<i.end&&n>i.start);return a.length?{start:Math.min(t,...a.map(e=>e.start)),end:Math.max(n,...a.map(e=>e.end))}:null}var vo=new Map,yo=new Map;function bo(e,t){let n=yo.get(e);if(n)n(t);else{let n=vo.get(e)??[];n.some(e=>e.id===t.id)||n.push(t),vo.set(e,n)}window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{roomId:e}}))}function xo(e,t){yo.set(e,t);let n=vo.get(e)??[];vo.delete(e);for(let e of n)t(e);return()=>{yo.get(e)===t&&yo.delete(e)}}function So(e,t,n){let r=`@${n.name}`,i=e.slice(0,t),a=`${i&&!/\s$/.test(i)?` `:``}${r} `;return{text:i+a+e.slice(t),cursor:t+a.length}}function Co({botIds:e,roomId:t}){let{locale:n}=Ue(),r=H(n),[i,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t,n;async function i(){t=new AbortController;try{let n=async e=>{let n=await fetch(Qe(q(`/api/device-center/${e}`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)throw Error(r?`无法加载群成员,请重试。`:`Could not load members. Try again.`);return n.json()},[i,a]=await Promise.all([n(`chat-status`),n(`bots`)]);if(!i.hubUrl||!Array.isArray(a.bots))throw Error(r?`设备绑定无效。`:`Invalid device binding.`);e||(o({hubUrl:i.hubUrl,deviceId:i.deviceId,bots:a.bots}),c(``))}catch(t){e||c(t instanceof Error?t.message:String(t))}finally{t.abort(),e||(n=setTimeout(i,15e3))}}return i(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[r]);async function d(e,t){if(i&&!l){u(!0);try{await wn(e.deviceId,i.hubUrl,t,r),c(``)}catch(e){c(e instanceof Error?e.message:String(e))}finally{u(!1)}}}return(0,$.jsxs)(`div`,{className:`dg-side-members`,children:[s&&(0,$.jsx)(`div`,{className:`dg-side-error`,role:`alert`,children:s}),!i&&!s&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:r?`加载中…`:`Loading…`}),e.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:r?`暂无成员`:`No members`}),i&&e.map(e=>{let n=i.bots.find(t=>t.id===e);return(0,$.jsxs)(`div`,{className:`dg-side-member`,children:[(0,$.jsxs)(`div`,{className:`dg-side-member-name`,title:n?.name||e,children:[(0,$.jsx)(`span`,{children:n?.name||e}),(0,$.jsx)(`small`,{children:n?.online?r?`在线`:`Online`:r?`离线`:`Offline`}),t&&n&&(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:r?`引用成员`:`Reference member`,"aria-label":`${r?`引用成员`:`Reference member`} · ${n.name}`,onClick:()=>bo(t,n),children:(0,$.jsx)(U,{"aria-hidden":!0})})]}),n?.deviceId&&i.deviceId&&n.deviceId!==i.deviceId&&(0,$.jsxs)(`div`,{className:`dg-side-member-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:l||!n?.deviceId,onClick:()=>n&&void d(n,!0),children:[(0,$.jsx)(st,{"aria-hidden":!0}),r?`远程桌面`:`Remote desktop`]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:l||!n?.deviceId,onClick:()=>n&&void d(n,!1),children:[(0,$.jsx)(a,{"aria-hidden":!0}),r?`访问设备`:`Open device`]})]})]},e)})]})}function wo(e,t){let n=e.trim().replace(/\\/g,`/`);if(!n)return``;let r=/^(?:[a-z]:\/|\/)/i.test(n)?n:`${t.replace(/\\/g,`/`).replace(/\/$/,``)}/${n}`,i=r.match(/^(?:[a-z]:\/|\/\/[^/]+\/[^/]+\/?|\/)/i)?.[0];if(!i)return n;let a=[];for(let e of r.slice(i.length).split(`/`))e===`..`?a.pop():e&&e!==`.`&&a.push(e);return i.replace(/\/$/,``)+`/`+a.join(`/`)}function To({cwd:e,onSelectCwd:t,onOpenProjectPicker:n,projects:r=[],workspaceRoots:i=[],pathCompletions:a=[],mode:o=`project`,baseCwd:s,onCreateProject:c,className:l=``,placeholder:d=`如 . 或 web 或绝对路径`,inputId:f,disabled:p=!1,commitOnBlur:m=!1,localOnly:h=!1,onPickerOpenChange:g}){let[_,v]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(e);(0,Q.useEffect)(()=>x(e),[e]);let[S,C]=(0,Q.useState)(!1),w=(0,Q.useRef)(null),T=V();(0,Q.useEffect)(()=>{let e=e=>{w.current&&!w.current.contains(e.target)&&v(!1)};if(_)return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[_]);let E=[{label:`. (当前项目根目录)`,value:`.`},{label:`web (前端目录)`,value:`web`},{label:`server (后端服务)`,value:`server`},{label:`tests (测试套件)`,value:`tests`},{label:`src (源码目录)`,value:`src`},{label:`docs (文档目录)`,value:`docs`}],D=()=>{C(!1),g?.(!1)},O=()=>{p||(n?n():(v(!1),C(!0),g?.(!0)))},k=e&&e!==`.`?e:s||e||`.`;return(0,$.jsxs)(`div`,{className:`universal-path-picker-root ${l}`,ref:w,children:[(0,$.jsxs)(`div`,{className:`universal-path-input-group`,children:[(0,$.jsx)(Be,{className:`universal-path-icon`}),(0,$.jsx)(`input`,{type:`text`,className:`universal-path-input`,value:m?b:e,id:f,disabled:p,onChange:e=>m?x(e.target.value):t(e.target.value),onBlur:()=>{m&&b!==e&&t(b)},onKeyDown:n=>{m&&n.key===`Enter`&&(n.preventDefault(),b!==e&&t(b))},placeholder:d,title:`工作目录: ${e||`.`}`}),(0,$.jsx)(`button`,{type:`button`,className:`universal-path-dropdown-toggle`,disabled:p,onClick:()=>v(!_),title:`选择推荐子目录或最近项目`,children:(0,$.jsx)(pe,{})})]}),(0,$.jsx)(ta,{className:`universal-path-browse-btn`,tip:T(`projectPickerTitle`),disabled:p,onClick:O,children:(0,$.jsx)(y,{})}),_&&(0,$.jsxs)(`div`,{className:`universal-path-menu`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[i.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`工作区根目录`}),i.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e),v(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e})},e))]}),(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`推荐子目录`}),E.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.value),v(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e.label})},e.value)),r.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`universal-path-menu-header`,children:[(0,$.jsx)(u,{}),` 最近项目`]}),r.slice(0,6).map(e=>{let n=e.path.split(/[/\\]/).filter(Boolean).pop()||e.path;return(0,$.jsxs)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.path),v(!1)},title:e.path,children:[(0,$.jsx)(`span`,{className:`path-title`,children:n}),(0,$.jsx)(`span`,{className:`path-sub`,children:e.path})]},e.path)})]})]}),!n&&S&&(0,$.jsx)(ba,{localOnly:h,open:!0,currentCwd:k,pathCompletions:a,workspaceRoots:i,onClose:D,onSelectDirectory:e=>{t(e),D()},onCreateProject:c?e=>{c(e),D()}:void 0,mode:o})]})}var Eo=`pi-web-model-usage`;function Do(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){let e=typeof r==`number`?Math.floor(r):0;Number.isFinite(e)&&e>0&&(t[n]=e)}return t}function Oo(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function ko(e,t){let n=t;return e.map((e,t)=>({m:e,i:t,count:n[e.id]??0})).sort((e,t)=>t.count-e.count||e.i-t.i).map(e=>e.m)}function Ao(){try{let e=localStorage.getItem(Eo);return e?Do(JSON.parse(e)):{}}catch{return{}}}function jo(e){try{localStorage.setItem(Eo,JSON.stringify(e))}catch{}}function Mo(e){let t=Oo(Ao(),e);return jo(t),t}function No(e,t){return t?t===e.id||`${e.provider}/${e.id}`===t||t.includes(`/`)&&t.split(`/`)[1]===e.id:!1}function Po({models:e,modelsLoading:t=!1,providerKeys:n={},defaultModel:r,currentModelId:i,active:a,onEnsureModels:o,loading:s=!1,onRefresh:c,onManageModels:l,onPickModel:u,onToggleDefault:d,isRowActive:f,extraTopRow:p,listRef:m,autoFocusSearch:h=!1,hideTitle:g=!1,bodyStyle:_,scrollStyle:v}){let y=V(),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null),[w,E]=(0,Q.useState)({}),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(o);k.current=o,(0,Q.useEffect)(()=>{if(!a){x(``),C(null),O(!1);return}E(Ao()),k.current()},[a]);let A=(0,Q.useMemo)(()=>e.filter(e=>e.enabled!==!1).length,[e]),j=e.some(e=>e.enabled===!1),M=(0,Q.useMemo)(()=>!j||D?e:e.filter(e=>e.enabled!==!1||No(e,i)),[e,j,D,i]),N=(0,Q.useMemo)(()=>{let e=b.trim().toLowerCase(),t=M;return S&&(t=t.filter(e=>e.provider===S.provider)),ko(e?t.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):t,w)},[M,b,S,w]),P=(0,Q.useMemo)(()=>{let e=new Map;for(let t of M)e.set(t.provider,(e.get(t.provider)??0)+1);let t=[];for(let[r,i]of[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))){let e=n[r];if(e&&e.length>1)for(let n of e)t.push({provider:r,count:i,keyName:n.name});else t.push({provider:r,count:i,keyName:null})}return t},[M,n]),ee=(0,Q.useMemo)(()=>{let e=[];for(let t of N){let r=null,a=n[t.provider];if(a&&a.length>1&&(r=a.find(e=>e.active)??a[0],S?.provider===t.provider&&S.keyName)){let e=a.find(e=>e.name===S.keyName);e&&(r=e)}let o=f?f(t,r):No(t,i)&&(!r||r.active);e.push({model:t,key:r,active:o})}return e},[N,n,S,f,i]);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,children:[!g&&(0,$.jsx)(`span`,{className:`dd-header-title`,children:y(`availableModels`)}),(0,$.jsxs)(`div`,{className:`dd-header-actions`,style:g?{marginLeft:`auto`}:void 0,children:[!!r&&(0,$.jsxs)(`div`,{className:`dd-header-default`,title:`默认模型: ${r}`,children:[(0,$.jsx)(`span`,{className:`dd-header-default-star`,children:`★`}),(0,$.jsx)(`span`,{className:`dd-header-default-name`,children:r.includes(`/`)?r.split(`/`).slice(1).join(`/`):r}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-default-clear`,title:`清除全局默认模型`,onClick:e=>{e.stopPropagation(),Z({type:`clear_default_model`})},children:`✕`})]}),j&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-toggle ${D?`active`:``}`,onClick:()=>O(e=>!e),title:D?y(`showEnabledModelsTitle`,{n:A}):y(`showAllModelsTitle`,{n:e.length}),children:D?y(`showEnabledModels`,{n:A}):y(`showAllModels`,{n:e.length})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-refresh-btn`,onClick:c,title:y(`refreshModels`),"aria-label":y(`refreshModels`),children:(0,$.jsx)(te,{className:s||t?`spin`:``})}),l&&(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-manage-btn`,onClick:l,title:y(`manageModels`),"aria-label":y(`manageModels`),children:(0,$.jsx)(T,{})})]})]}),(0,$.jsxs)(`div`,{className:`dd-search-row`,children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`input`,{className:`dd-search`,type:`text`,autoFocus:h,placeholder:y(`searchModels`),value:b,onChange:e=>x(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`dd-model-body`,style:_,children:[P.length>1&&(0,$.jsxs)(`div`,{className:`dd-provider-col`,children:[(0,$.jsx)(`div`,{className:`dd-provider-head`,children:y(`providers`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-provider-item ${S===null?`active`:``}`,onClick:()=>C(null),children:(0,$.jsx)(`span`,{children:y(`allProviders`)})}),P.map(e=>{let t=S?.provider===e.provider&&S?.keyName===e.keyName;return(0,$.jsxs)(`button`,{type:`button`,className:`dd-provider-item ${t?`active`:``}`,onClick:()=>C(t?null:{provider:e.provider,keyName:e.keyName}),title:e.keyName?`${e.provider} · ${e.keyName}`:`${e.provider} · ${e.count}`,children:[(0,$.jsxs)(`span`,{className:`dd-provider-txt`,children:[(0,$.jsx)(`span`,{className:`dd-provider-name`,children:e.provider}),e.keyName&&(0,$.jsx)(`span`,{className:`dd-provider-key`,children:e.keyName})]}),(0,$.jsx)(`span`,{className:`dd-provider-count`,children:e.count})]},e.keyName?`${e.provider}::${e.keyName}`:e.provider)})]}),(0,$.jsxs)(`div`,{className:`dd-model-scroll`,ref:m,style:v,children:[(s||t)&&(0,$.jsx)(`div`,{className:`dd-loading`,children:y(`loading`)}),e.length===0&&!s&&!t&&(0,$.jsx)(`div`,{className:`dd-loading`,children:y(`noModels`)}),p,N.length===0&&M.length>0&&(0,$.jsxs)(`div`,{className:`dd-loading`,children:[(0,$.jsx)(`div`,{children:y(`noModelMatches`)}),j&&!D&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-switch-link`,onClick:()=>O(!0),children:y(`searchAllModelsHint`,{n:e.length})})]}),ee.map(e=>{let t=e.model,n=r!==void 0&&r===t.id;return(0,$.jsxs)(gt,{active:e.active,onClick:()=>u(t,e.key),children:[(0,$.jsxs)(`span`,{className:`dd-model-cell`,children:[(0,$.jsx)(`span`,{className:`dd-model-name`,children:t.name}),(0,$.jsxs)(`span`,{className:`dd-model-meta`,children:[(0,$.jsx)(`span`,{className:`dd-model-provider`,children:t.provider}),(0,$.jsx)(`span`,{className:`dd-model-id`,children:t.id.includes(`/`)?t.id.split(`/`).slice(1).join(`/`):t.id}),e.key&&(0,$.jsxs)(`span`,{className:`dd-model-key ${e.key.active?`active`:``}`,children:[e.key.active?`●`:`○`,` `,e.key.name]}),(w[t.id]??0)>0&&(0,$.jsx)(`span`,{className:`dd-model-usage`,children:y(`modelUsedCount`,{n:w[t.id]})}),(t.reasoning||t.vision||D&&t.enabled===!1)&&(0,$.jsxs)(`span`,{className:`dd-model-badges`,children:[t.reasoning&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:y(`reasoning`)}),t.vision&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:y(`vision`)}),D&&t.enabled===!1&&(0,$.jsx)(`span`,{className:`dd-model-badge out-of-scope`,children:y(`notInScopeBadge`)})]})]})]}),r!==void 0&&(d?(0,$.jsx)(`button`,{type:`button`,className:`dd-star-btn ${n?`active`:``}`,title:n?`当前全局默认模型(点击取消默认)`:`设为全局默认模型`,onClick:e=>{e.stopPropagation(),d(t,n)},children:n?`★`:`☆`}):(0,$.jsx)(`span`,{className:`dd-star-btn ${n?`active`:``}`,children:n?`★`:`☆`}))]},e.key?`${t.id}::${e.key.name}`:t.id)})]})]})]})}function Fo({title:e,entries:t,selected:n,onChange:r,disabled:i,pending:a}){let o=V(),s=(0,Q.useId)(),[c,l]=(0,Q.useState)(``),u=new Set(t.map(e=>e.id)),d=n.filter(e=>!u.has(e)),f=[...t,...d.map(e=>({id:e,name:e}))],p=c.trim().toLowerCase(),m=f.filter(e=>[e.name,e.id,e.description,e.path].some(e=>e?.toLowerCase().includes(p))),h=m.filter(e=>u.has(e.id)&&e.status!==`disabled`);return(0,$.jsxs)(`fieldset`,{className:`dc-bot-catalog`,disabled:i,children:[(0,$.jsxs)(`legend`,{children:[e,` `,(0,$.jsxs)(`span`,{className:`dc-bot-count`,children:[n.length,` `,o(`localBotSelected`)]})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-actions`,children:[(0,$.jsx)(`input`,{type:`search`,"aria-label":`${o(`localBotSearch`)} ${e}`,placeholder:o(`localBotSearch`),value:c,onChange:e=>l(e.target.value)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:a||!h.length,onClick:()=>r([...new Set([...n,...h.map(e=>e.id)])]),children:o(p?`localBotSelectVisible`:`localBotSelectAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:!n.length,onClick:()=>r([]),children:o(`localBotClear`)})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-list`,children:[m.map((e,t)=>(0,$.jsxs)(`label`,{className:`dc-bot-option`,htmlFor:`${s}-${t}`,children:[(0,$.jsx)(`input`,{id:`${s}-${t}`,type:`checkbox`,checked:n.includes(e.id),disabled:e.status===`disabled`&&!n.includes(e.id),onChange:t=>r(t.target.checked?[...new Set([...n,e.id])]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),!u.has(e.id)&&(0,$.jsx)(`small`,{children:o(a?`localBotUnverified`:`localBotUnavailable`)}),e.description&&(0,$.jsx)(`small`,{children:e.description}),e.status===`not_loaded`&&(0,$.jsx)(`small`,{children:o(`localBotMcpNotLoaded`)}),e.status===`disabled`&&(0,$.jsx)(`small`,{children:o(`localBotMcpDisabled`)}),e.source&&(0,$.jsx)(`small`,{children:e.source}),e.path&&(0,$.jsx)(`small`,{children:e.path})]})]},e.id)),!m.length&&(0,$.jsx)(`p`,{children:o(a?`localBotOptionsLoading`:`localBotNoOptions`)})]})]})}var Io=e=>e.id.startsWith(`${e.provider}/`)?e.id.slice(e.provider.length+1):e.id,Lo=()=>({name:``,description:``,systemPrompt:``,cwd:``,tools:[],skills:[],mcpServers:[],enabled:!0});async function Ro(e,t,n){let r=await fetch(Qe(q(`/api/device-center/${e}`)),{method:n?`POST`:`GET`,credentials:`same-origin`,signal:t,...n?{headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}:{}}),i=await r.json();if(!r.ok)throw Error(i.error||String(r.status));return i}function zo({pathCompletions:e=[],createOnly:t=!1,onCreated:n,onCancel:r}){let i=V(),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(()=>t?Lo():null),l=()=>{c(null),r?.()},[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(`identity`),O=(0,Q.useRef)(null),k=(0,Q.useRef)(``),A=(0,Q.useRef)(null),j=s!==null;(0,Q.useEffect)(()=>{if(!j)return;let e=A.current,t=document.activeElement,n=document.body.style.overflow;return document.body.style.overflow=`hidden`,D(`identity`),e?.showModal?.(),()=>{e?.close?.(),document.body.style.overflow=n,t?.focus()}},[j]),(0,Q.useEffect)(()=>{let e=new AbortController;return Ro(`local-bots`,e.signal).then(t=>{if(!e.signal.aborted){if(!Array.isArray(t.bots))throw Error(`Invalid Bot list`);o(t.bots)}}).catch(t=>{e.signal.aborted||p(String(t))}),()=>{e.abort(),O.current?.abort()}},[]);let M=s?.cwd;(0,Q.useEffect)(()=>{if(M===void 0)return;let e=new AbortController;return x(!0),y(``),_(null),Ro(M?`local-bot-options?cwd=${encodeURIComponent(M)}`:`local-bot-options`,e.signal).then(t=>{if(!e.signal.aborted){if(![t.models,t.tools,t.skills,t.mcpServers,t.projects].every(Array.isArray)||!t.defaultCwd||!t.cwd)throw Error(i(`localBotOptionsInvalid`));k.current=t.defaultCwd,_(t),M||c(e=>e&&!e.cwd?{...e,cwd:t.cwd}:e)}}).catch(t=>{e.signal.aborted||y(String(t))}).finally(()=>{e.signal.aborted||x(!1)}),()=>e.abort()},[M,S]),(0,Q.useEffect)(()=>{if(!w)return;let e=e=>{e.key===`Escape`&&T(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[w]);async function N(e=!1){if(!s||u)return;let t=new AbortController;O.current=t,d(!0),p(``),h(``);try{let r=await Ro(e?`local-bots/${encodeURIComponent(s.id)}/delete`:`local-bots`,t.signal,e?{revision:s.revision}:s);if(t.signal.aborted)return;o(t=>e?t.filter(e=>e.id!==s.id):[...t.filter(e=>e.id!==r.bot.id),r.bot]),c(null),T(!1),h(r.synced===!1?i(`localBotSyncFailed`):i(`localBotSaved`)),e||n?.(r.bot,r.synced!==!1)}catch(e){t.signal.aborted||p(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||d(!1)}}let P=g?.models.find(e=>e.provider===s?.model?.provider&&Io(e)===s?.model?.modelId);return(0,$.jsxs)(`section`,{className:`dc-card dc-bots${t?` is-create-only`:``}`,"aria-label":i(`localBotTitle`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h2`,{children:i(`localBotTitle`)}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:u,onClick:()=>{c(Lo()),p(``),T(!1)},children:i(`localBotCreate`)})]}),(0,$.jsx)(`p`,{children:i(`localBotHint`)}),f&&!s&&(0,$.jsx)(`p`,{role:`alert`,children:f}),m&&(0,$.jsx)(`p`,{role:`status`,children:m}),(0,$.jsxs)(`div`,{className:`dc-bot-workspace${s?` is-editing`:``}`,children:[(0,$.jsx)(`div`,{className:`dc-bot-list`,"aria-label":i(`localBotTitle`),children:a.map(e=>(0,$.jsxs)(`button`,{className:`dc-button dc-bot-item${s?.id===e.id?` is-selected`:``}`,"aria-pressed":s?.id===e.id,disabled:u,onClick:()=>{c(structuredClone(e)),p(``),T(!1)},children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:e.name.slice(0,2).toUpperCase()}),(0,$.jsxs)(`span`,{className:`dc-bot-item-copy`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsxs)(`small`,{className:e.enabled?`is-enabled`:``,children:[e.enabled?i(`localBotEnabled`):i(`localBotDisabled`),` · r`,e.revision]})]})]},e.id))}),s&&(0,$.jsx)(`dialog`,{ref:A,className:`dc-bot-drawer`,"aria-label":i(`localBotTitle`),onCancel:e=>{e.preventDefault(),!u&&!w&&l()},onClick:e=>{if(e.target!==e.currentTarget||u)return;let t=e.currentTarget.getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&l()},children:(0,$.jsxs)(`form`,{className:`dc-bot-editor`,onSubmit:e=>{e.preventDefault(),N()},children:[(0,$.jsxs)(`header`,{className:`dc-bot-editor-head`,children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:s.name.slice(0,2).toUpperCase()||`B`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{children:s.name||i(`localBotCreate`)}),s.id&&(0,$.jsxs)(`small`,{children:[s.id,` · r`,s.revision]})]}),(0,$.jsxs)(`label`,{className:`dc-bot-enabled`,children:[(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,disabled:u,checked:s.enabled,onChange:e=>c({...s,enabled:e.target.checked})}),i(`localBotEnable`)]}),(0,$.jsx)(`button`,{className:`dc-button dc-bot-drawer-close`,type:`button`,"aria-label":i(`localBotCancel`),disabled:u,onClick:l,children:`×`})]}),(0,$.jsx)(`div`,{className:`dc-bot-tabs`,role:`tablist`,"aria-label":i(`localBotTitle`),children:[[`identity`,i(`localBotIdentity`)],[`runtime`,i(`localBotRuntime`)],[`permissions`,i(`localBotPermissions`)]].map(([e,t],n,r)=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,id:`bot-tab-${e}`,"aria-controls":`bot-panel-${e}`,"aria-selected":E===e,tabIndex:E===e?0:-1,onClick:()=>D(e),onKeyDown:e=>{let t=n;if(e.key===`ArrowRight`)t=(n+1)%r.length;else if(e.key===`ArrowLeft`)t=(n+r.length-1)%r.length;else if(e.key===`Home`)t=0;else if(e.key===`End`)t=r.length-1;else return;e.preventDefault(),D(r[t][0]),document.getElementById(`bot-tab-${r[t][0]}`)?.focus()},children:t},e))}),(0,$.jsxs)(`div`,{className:`dc-bot-editor-body`,children:[f&&(0,$.jsx)(`p`,{className:`dc-bot-error`,role:`alert`,children:f}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-identity`,"aria-labelledby":`bot-tab-identity`,hidden:E!==`identity`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotIdentityHint`)}),(0,$.jsxs)(`fieldset`,{className:`dc-bot-section`,disabled:u,children:[(0,$.jsx)(`legend`,{children:i(`localBotIdentity`)}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotName`),(0,$.jsx)(`input`,{required:!0,value:s.name,onChange:e=>c({...s,name:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotDescription`),(0,$.jsx)(`textarea`,{rows:2,value:s.description,onChange:e=>c({...s,description:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`dc-field`,children:[i(`localBotSystemPrompt`),(0,$.jsx)(`textarea`,{rows:9,className:`dc-bot-prompt`,spellCheck:!1,value:s.systemPrompt,onChange:e=>c({...s,systemPrompt:e.target.value})})]})]}),(0,$.jsx)(`p`,{className:`dc-bot-local-note`,children:i(`localBotPrivatePrompt`)})]}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-runtime`,"aria-labelledby":`bot-tab-runtime`,hidden:E!==`runtime`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotRuntimeHint`)}),(0,$.jsxs)(`fieldset`,{className:`dc-bot-section`,disabled:u,children:[(0,$.jsx)(`legend`,{children:i(`localBotRuntime`)}),(0,$.jsxs)(`div`,{className:`dc-field`,children:[(0,$.jsx)(`label`,{htmlFor:`local-bot-cwd`,children:i(`localBotCwd`)}),(0,$.jsx)(To,{inputId:`local-bot-cwd`,localOnly:!0,commitOnBlur:!0,pathCompletions:e,cwd:s.cwd,baseCwd:k.current||s.cwd,projects:g?.projects.map(e=>({...e,lastUsed:0}))??[],disabled:u,onSelectCwd:e=>c({...s,cwd:wo(e,k.current||s.cwd)})})]}),(0,$.jsxs)(`div`,{className:`dc-field`,children:[(0,$.jsx)(`span`,{children:i(`localBotModel`)}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,"aria-haspopup":`dialog`,onClick:()=>T(!0),children:s.model?P?.name??`${s.model.provider}/${s.model.modelId}`:i(`localBotInheritModel`)}),s.model&&(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,onClick:()=>c({...s,model:void 0}),children:i(`localBotInheritModel`)})]}),s.model&&!P&&(0,$.jsx)(`small`,{children:i(b?`localBotUnverified`:`localBotUnavailable`)})]})]})]}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-permissions`,"aria-labelledby":`bot-tab-permissions`,hidden:E!==`permissions`,children:[(0,$.jsx)(`p`,{className:`dc-bot-section-intro`,children:i(`localBotPermissionsHint`)}),(0,$.jsxs)(`div`,{className:`dc-bot-options-status`,"aria-live":`polite`,children:[b&&(0,$.jsx)(`span`,{children:i(`localBotOptionsLoading`)}),v&&(0,$.jsx)(`span`,{role:`alert`,children:v}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:b||u,onClick:()=>C(e=>e+1),children:i(v?`deviceHubRetry`:`localBotReload`)})]}),(0,$.jsx)(`div`,{className:`dc-bot-permissions`,children:[[`tools`,i(`localBotTools`)],[`skills`,i(`localBotSkills`)],[`mcpServers`,i(`localBotMcpServers`)]].map(([e,t])=>(0,$.jsx)(Fo,{title:t,entries:g?.[e]??[],selected:s[e],disabled:u,pending:b||!!v,onChange:t=>c({...s,[e]:t})},e))})]})]}),(0,$.jsxs)(`footer`,{className:`dc-actions dc-bot-editor-footer`,children:[(0,$.jsx)(`button`,{className:`dc-button dc-bot-save`,disabled:u||!s.cwd||!s.name.trim(),children:i(`localBotSave`)}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:u,onClick:()=>{l(),T(!1)},children:i(`localBotCancel`)}),s.id&&(0,$.jsx)(`button`,{className:`dc-button is-danger`,type:`button`,disabled:u,onClick:()=>{window.confirm(i(`localBotDeleteConfirm`))&&N(!0)},children:i(`localBotDelete`)})]})]})})]}),s&&w&&(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop dc-bot-model-backdrop`,onClick:e=>{e.target===e.currentTarget&&T(!1)},children:(0,$.jsxs)(`div`,{className:`dc-bot-model-modal dd-menu-model`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`localBotModel`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h3`,{children:i(`localBotModel`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>T(!1),children:i(`localBotCancel`)})]}),(0,$.jsx)(Po,{models:g?.models??[],modelsLoading:b,defaultModel:g?.defaultModel,currentModelId:s.model?`${s.model.provider}/${s.model.modelId}`:null,active:!0,onEnsureModels:()=>{},onRefresh:()=>C(e=>e+1),onPickModel:e=>{c({...s,model:{provider:e.provider,modelId:Io(e)}}),T(!1)},isRowActive:e=>e.provider===s.model?.provider&&Io(e)===s.model.modelId,extraTopRow:(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>{c({...s,model:void 0}),T(!1)},children:i(`localBotInheritModel`)}),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{overflowY:`auto`,minHeight:0}}),v&&(0,$.jsx)(`p`,{role:`alert`,children:v})]})}),A.current??document.body)]})}function Bo({room:e,onClose:t}){let{locale:n}=Ue(),r=H(n),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(e.botIds),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!0),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(0),b=(0,Q.useRef)(null),x=()=>{!m&&!u&&t()};mt(x),(0,Q.useEffect)(()=>()=>b.current?.abort(),[]),(0,Q.useEffect)(()=>{let t=new AbortController;return p(!0),Promise.all([Wo(`bots`,t.signal),Wo(`rooms/${encodeURIComponent(e.id)}`,t.signal)]).then(([e,n])=>{t.signal.aborted||(a(e.bots),s(n.room.botIds))}).catch(e=>{t.signal.aborted||_(e instanceof Error?e.message:String(e))}).finally(()=>{t.signal.aborted||p(!1)}),()=>t.abort()},[e.id,v]);async function S(n){if(b.current)return;let r=new AbortController;b.current=r,h(!0),_(``);try{let i=`rooms/${encodeURIComponent(e.id)}`,a=await Wo(i,r.signal);if(r.signal.aborted||(await Wo(`${i}/members`,r.signal,{botIds:[...new Set([...a.room.botIds,...n])]}),r.signal.aborted))return;window.dispatchEvent(new CustomEvent(Vo)),t()}catch(e){r.signal.aborted||_(e instanceof Error?e.message:String(e))}finally{b.current=null,r.signal.aborted||h(!1)}}return(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:x,children:(0,$.jsxs)(`div`,{className:`device-group-bot-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":r?`添加或新建 Bot`:`Add or create Bot`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsxs)(`h2`,{children:[r?`添加 Bot`:`Add Bot`,` · `,e.name]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:m||u,onClick:x,children:r?`关闭`:`Close`})]}),g&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:g}),(0,$.jsx)(`p`,{children:r?`选择已有 Bot 加入群组,或在本机新建 Bot。`:`Add existing Bots to this group or create a Bot on this computer.`}),f?(0,$.jsx)(`p`,{children:r?`加载中…`:`Loading…`}):(0,$.jsxs)(`div`,{className:`dg-bot-choices`,children:[i.filter(e=>e.enabled&&!o.includes(e.id)).map(e=>(0,$.jsxs)(`label`,{className:`dg-bot-choice`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:m||u,checked:c.includes(e.id),onChange:t=>l(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[e.name,e.deviceName&&(0,$.jsx)(`small`,{children:e.deviceName})]})]},e.id)),!i.some(e=>e.enabled&&!o.includes(e.id))&&(0,$.jsx)(`p`,{children:r?`没有可添加的 Bot,可以新建一个。`:`No Bots available to add. Create a new one.`})]}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:m||u,onClick:()=>{d(!0),_(``)},children:r?`新建 Bot`:`Create Bot`}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:f||m||u||!c.length,onClick:()=>void S(c),children:m?r?`正在添加…`:`Adding…`:r?`添加到群组`:`Add to group`})]}),u&&(0,$.jsx)(zo,{createOnly:!0,onCancel:()=>d(!1),onCreated:(e,t)=>{if(d(!1),y(e=>e+1),!t||!e.enabled){_(r?`Bot 已保存;请启用并同步到中心后,再添加到群组。`:`Bot saved. Enable and sync it to the hub before adding it to the group.`);return}S([e.id])}})]})}),document.body)}var Vo=`pi-web-ui:device-groups-changed`,Ho={zh:{groups:`群组`,create:`建群`,rename:`重命名`,members:`管理成员`,delete:`删除群组`,save:`保存`,cancel:`取消`,empty:`还没有群组`,loading:`加载中…`,expand:`展开群组`,collapse:`折叠群组`,bind:`请先在设备设置中绑定本机,旧版绑定请重新绑定。`,settings:`打开设备中心`,failed:`群组请求失败,请重试。`,retry:`重试`,forbidden:`无法访问群组,请检查本机访问权限。`,running:`群内仍有排队或运行中的任务,请等待任务结束后再操作。`,confirm:`确定删除群组“{name}”?`,name:`群名称`},en:{groups:`Groups`,create:`Create group`,rename:`Rename`,members:`Manage members`,delete:`Delete group`,save:`Save`,cancel:`Cancel`,empty:`No groups yet`,loading:`Loading…`,expand:`Expand groups`,collapse:`Collapse groups`,bind:`Bind this computer in device settings first. Older bindings must be renewed.`,settings:`Open device center`,failed:`Group request failed. Please retry.`,retry:`Retry`,forbidden:`Group access denied. Check local access permissions.`,running:`This group has queued or running tasks. Wait for them to finish before making this change.`,confirm:`Delete group “{name}”?`,name:`Group name`}},Uo=class extends Error{status;code;constructor(e,t){super(`Device group request failed (${e})`),this.status=e,this.code=t}};async function Wo(e,t,n){let r=await fetch(Qe(q(`/api/device-center/${e}`)),{signal:AbortSignal.any([t,AbortSignal.timeout(15e3)]),...n===void 0?{}:{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}}),i=await r.json().catch(()=>({}));if(!r.ok)throw new Uo(r.status,typeof i?.code==`string`?i.code:``);return i}function Go(e){return e instanceof Uo?[`NOT_PAIRED`,`REPAIR_REQUIRED`,`DEVICE_CHANGED`].includes(e.code)?`bind`:[`ROOM_BUSY`,`ROOM_RUNNING`,`TASKS_RUNNING`,`ACTIVE_TASKS`].includes(e.code)?`running`:e.status===403?`forbidden`:`failed`:`failed`}function Ko(e,t,n){let r,i=0,a=!1,o=!1,s=()=>{if(o)return;let c=++i;if(r){a=!0;return}let l=new AbortController;r=l,e(l.signal).then(e=>{!o&&c===i&&t(e)},e=>{!o&&c===i&&!l.signal.aborted&&n(e)}).finally(()=>{r=void 0,a&&!o&&(a=!1,s())})};return{refresh:s,pause:()=>{i++,a=!1,r?.abort()},stop:()=>{o=!0,i++,a=!1,r?.abort()}}}function qo(e){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:e}))}function Jo({active:e=!0,selectedRoomId:t,flex:n,onCollapsedChange:r}){let{locale:i}=Ue(),a=Ho[H(i)?`zh`:`en`],[o,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>r?.(o),[o,r]);let[p,m]=(0,Q.useState)([]),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(!0),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(null),O=(0,Q.useRef)(null),k=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(k.current=!0,()=>{k.current=!1,O.current?.abort()}),[]),(0,Q.useEffect)(()=>{if(!e)return;let t=!1,n=Ko(async e=>{let n=await Wo(`chat-status`,e);if(t=!!(n.hubUrl&&n.deviceId),!t)return[];let r=await Wo(`rooms`,e);if(!Array.isArray(r.rooms))throw Error(`Invalid rooms response`);return r.rooms},e=>{g(t),m(e),b(null),v(!1)},e=>{b(Go(e)),v(!1)});D.current=n;let r=()=>{document.hidden||n.refresh()},i=()=>{document.hidden?n.pause():r()};r();let a=window.setInterval(r,15e3);return window.addEventListener(Vo,r),document.addEventListener(`visibilitychange`,i),()=>{n.stop(),D.current=null,window.clearInterval(a),window.removeEventListener(Vo,r),document.removeEventListener(`visibilitychange`,i)}},[e]);let A=async(e,t)=>{if(O.current||t===`delete`&&!window.confirm(a.confirm.replace(`{name}`,e.name)))return;let n=new AbortController;O.current=n,E(!0),b(null);try{if(await Wo(`rooms/${encodeURIComponent(e.id)}/${t}`,n.signal,t===`rename`?{name:C.trim()}:{}),!k.current||n.signal.aborted)return;S(null),window.dispatchEvent(new CustomEvent(Vo))}catch(e){k.current&&!n.signal.aborted&&b(Go(e))}finally{O.current=null,k.current&&E(!1)}},j=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=[`rename`,`members`,`delete`].map((e,t)=>({id:`host:device-group-${e}`,slot:`contextmenu.project`,source:`host`,label:a[e],kind:`action`,action:e,order:t,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.id,kind:`device-group`,label:t.name},entries:n,onHostAction:e=>{O.current||(e.action===`rename`?(S(t.id),w(t.name)):e.action===`members`?qo({roomId:t.id,manage:!0}):e.action===`delete`&&A(t,`delete`))}})};return h===!1||h===null&&_?null:(0,$.jsxs)(`section`,{className:`lp-section dg-side-section ${o?`collapsed`:``}`,"aria-label":a.groups,style:!o&&n!==void 0?{flex:`${n} 1 0px`}:void 0,children:[(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,"aria-expanded":!o,title:o?a.expand:a.collapse,onClick:()=>c(!o),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[a.groups,` (`,p.length,`)`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:o?(0,$.jsx)(pe,{}):(0,$.jsx)(s,{})})]}),(0,$.jsx)(`div`,{className:`lp-section-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action`,title:a.create,"aria-label":a.create,onClick:()=>qo({create:!0}),children:(0,$.jsx)(rt,{})})})]}),!o&&(0,$.jsxs)(`div`,{className:`lp-section-body dg-side-body`,children:[y&&(0,$.jsxs)(`div`,{className:`dg-side-error`,role:`status`,children:[a[y],y===`bind`?(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>qo({}),children:a.settings}):(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>D.current?.refresh(),children:a.retry})]}),!y&&p.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:_?a.loading:a.empty}),p.map(e=>(0,$.jsxs)(`div`,{className:`dg-side-item`,children:[(0,$.jsxs)(`div`,{className:`dg-side-heading`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-expanded":d.has(e.id),"aria-label":`${e.name} · ${H(i)?`成员`:`Members`}`,onClick:()=>f(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:d.has(e.id)?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})}),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`dg-side-row${t===e.id?` is-selected`:``}`,"aria-current":t===e.id?`page`:void 0,title:e.name,onClick:()=>qo({roomId:e.id}),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),qo({roomId:e.id}))},onContextMenu:t=>j(t,e),children:[(0,$.jsx)(Ve,{}),(0,$.jsx)(`span`,{className:`dg-side-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-label":`${e.name} · ${H(i)?`添加 Bot`:`Add Bot`}`,title:H(i)?`添加或新建 Bot`:`Add or create Bot`,onClick:()=>u(e),children:(0,$.jsx)(rt,{})})]}),d.has(e.id)&&(0,$.jsx)(Co,{botIds:e.botIds,roomId:e.id}),x===e.id&&(0,$.jsxs)(`form`,{className:`dg-side-rename`,onSubmit:t=>{t.preventDefault(),C.trim()&&A(e,`rename`)},children:[(0,$.jsx)(`input`,{className:`dc-input`,"aria-label":a.name,value:C,maxLength:120,autoFocus:!0,disabled:T,onChange:e=>w(e.target.value),onKeyDown:e=>{e.key===`Escape`&&S(null)}}),(0,$.jsx)(`button`,{type:`submit`,className:`dc-button`,disabled:T||!C.trim(),children:a.save}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:T,onClick:()=>S(null),children:a.cancel})]})]},e.id))]}),l&&(0,$.jsx)(Bo,{room:l,onClose:()=>u(null)})]})}function Yo(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(r&&typeof r==`object`&&!Array.isArray(r))for(let e of Object.keys(t)){let t=r[e];typeof t==`number`&&Number.isFinite(t)&&t>0&&(n[e]=t)}}catch{}return n}function Xo(e){let t=e.start.above+e.start.below,n=Math.max(1,e.availablePx)/(e.totalWeight>0?e.totalWeight:1),r=e.minAbovePx/n,i=e.minBelowPx/n;if(r+i>=t){let n=e.minAbovePx+e.minBelowPx||1,r=t*e.minAbovePx/n;return{above:r,below:t-r}}let a=Math.min(t-i,Math.max(r,e.start.above+e.deltaPx/n));return{above:a,below:t-a}}function Zo(e,t,n){let r=new Map(e.map(e=>[e.id,e])),i=e=>e.parentId?r.get(e.parentId)?.cwd??e.cwd:e.cwd,a=e.find(e=>e.id===n),o=a?i(a):t,s=new Map;for(let t of e){let e=i(t),n=s.get(e)??[];n.push(t),s.set(e,n)}let c=[...s.entries()].map(([e,t])=>({cwd:e,isCurrent:e===o,convs:t}));return c.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:e.cwd<t.cwd?-1:+(e.cwd>t.cwd)),c}function Qo(e,t=new Set){let n=new Map(e.map(e=>[e.id,e])),r=new Map,i=[];for(let t of e)if(t.parentId&&n.has(t.parentId)){let e=r.get(t.parentId)??[];e.push(t),r.set(t.parentId,e)}else i.push(t);let a=e=>{let t=[],n=[...r.get(e)??[]],i=new Set;for(;n.length>0;){let e=n.shift();if(i.has(e.id))continue;i.add(e.id),t.push(e);let a=r.get(e.id);a&&n.push(...a)}return t},o=[],s=new Set,c=new Set,l=(e,n)=>{if(s.has(e.id)||c.has(e.id))return;s.add(e.id);let i=r.get(e.id)??[],u=i.length>0,d=u&&t.has(e.id),f=0,p=!1,m=!1,h=!1;if(u){let t=a(e.id);if(f=t.length,p=t.some(e=>e.isStreaming),m=t.some(e=>!!e.error),h=t.some(e=>!!e.hasQuestion),d)for(let e of t)c.add(e.id)}if(o.push({c:e,depth:n,hasKids:u,isCollapsed:d,descendantCount:f,hasStreaming:p,hasError:m,hasQuestion:h}),!d)for(let e of i)l(e,n+1)};for(let e of i)l(e,0);for(let t of e)l(t,0);return o}function $o({className:e,width:t=`1em`,height:n=`1em`,...r}){let i=[`half-ring-spin`,e].filter(Boolean).join(` `);return(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,width:t,height:n,className:i,"aria-hidden":`true`,...r,children:(0,$.jsx)(`path`,{d:`M 12 2 A 10 10 0 0 1 12 22`})})}function es(e){if(!e)return null;let t=e.startsWith(`#`)?e.slice(1):e;if(!t.trim())return null;let n=new URLSearchParams(t),r=n.get(`s`)?.trim()??``;if(!r)return null;let i=n.get(`m`)?.trim()||void 0;return i?{sessionId:r,messageId:i}:{sessionId:r}}function ts(e){let t=e?.sessionId?.trim()??``;if(!t)return``;let n=e?.messageId?.trim()??``,r=`#s=${encodeURIComponent(t)}`;return n?`${r}&m=${encodeURIComponent(n)}`:r}function ns(e,t){let n=ts(t);try{let t=new URL(e);return t.searchParams.delete(`token`),t.hash=n,t.toString()}catch{return`${e.split(`#`)[0]??e}${n}`}}function rs(e){if(!e)return null;let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);if(!t)return null;let n=t.split(`/`),r=n[n.length-1]??``;if(!r)return null;if(r===`session.jsonl`)return(n[n.length-2]?.trim()??``)||null;let i=r.endsWith(`.jsonl`)?r.slice(0,-6):r;if(!i)return null;let a=i.lastIndexOf(`_`);return(a>=0?i.slice(a+1).trim():i.trim())||null}function is(e,t){let n=t?.trim()??``;if(!n||e.length===0)return null;let r=e.find(e=>e.id===n);if(r)return r.id;let i=/^([a-z]+-\d+)-\d+$/.exec(n);if(i){let t=`${i[1]}-`,n=e.find(e=>e.id.startsWith(t));if(n)return n.id}return null}function as(e,t,n,r,i){return e.find(e=>t(e)===n)??e.find(e=>!r.has(t(e))&&i(e))}function os(e,t,n){if(n)return e.filter(e=>e.id!==n);if(!t)return e;let r=e.findIndex(e=>e.id===t.id);return r<0?[...e,t]:e.map((e,n)=>n===r?t:e)}var ss=`pi:canvas-list-result`,cs=new Set([`canvas`,`canvases`,`画布`,`工作流`,`workflow`,`workflows`]);function ls(e,t,n,r=10){let i=t.toLowerCase();return e.filter(e=>!i||cs.has(i)||e.name.toLowerCase().includes(i)||e.id.toLowerCase().includes(i)).slice(0,Math.max(0,r)).map(e=>({providerId:`host:canvases`,providerLabel:n,title:`${n} · ${e.name}`,text:e.name,hint:e.id,attachments:[{path:e.id,name:e.name,mode:`canvas`}]}))}function us(e,t=1800){return new Promise(n=>{let r=e=>{clearTimeout(a),window.removeEventListener(ss,i),n(e)},i=e=>{let t=e.detail;r(t.graphs)},a=setTimeout(()=>r([]),t);window.addEventListener(ss,i);try{e()||r([])}catch{r([])}})}function ds(){let e=new Map,t=new Map,n=(e,t,n)=>JSON.stringify([n??`legacy`,n===`client`?``:e,t]),r=(e,t)=>[...e].filter(e=>{let[n,,r]=JSON.parse(e);return n===`legacy`&&r===t}),i=(e,t,n)=>{try{if(n){if(!e.reset)return;e.reset()}e.write(t)}catch{}};return{write(a,o,s,c=!1,l){let u=n(a,o,l),d=l||e.get(u)?.size?[u]:r(e.keys(),o);for(let t of d)for(let n of e.get(t)??[])i(n,s,c);let f=t.get(u)??(l?void 0:t.get(r(t.keys(),o)[0]));if(!l)for(let e of r(t.keys(),o))t.delete(e);t.set(u,{data:(c?s:(f?.data??``)+s).slice(-2e5),reset:c||(f?.reset??!1)})},register(a,o,s,c){let l=n(a,o,c),u=e.get(l);u||e.set(l,u=new Set),u.add(s);let d=t.get(l)??(c?void 0:t.get(r(t.keys(),o)[0]));return d&&i(s,d.data,d.reset),()=>{let t=e.get(l);t?.delete(s),t?.size||e.delete(l)}},reconcile(e,r){let i=new Set(r.map(t=>n(e,t.id,t.ownerKind??`client`)));for(let n of t.keys()){let[r,a]=JSON.parse(n);(r===`client`||a===e)&&!i.has(n)&&t.delete(n)}},clear(){t.clear()}}}function fs(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.text!=`string`||!t.text.trim()||typeof t.messageId!=`string`||!t.messageId||typeof t.role!=`string`||!t.role?null:{text:t.text,messageId:t.messageId,role:t.role,...typeof t.sessionId==`string`&&t.sessionId?{sessionId:t.sessionId}:{}}}function ps(e){return`<quoted-text>\n${JSON.stringify(e)}\n</quoted-text>`}function ms(e){let t=/^<quoted-text>\n([^\n]*)\n<\/quoted-text>$/.exec(e);if(!t)return null;try{return fs(JSON.parse(t[1]))}catch{return null}}function hs(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function gs(e,t=[],n=[],r=[]){let i=[],a=(e??``).trim();a&&i.push(a);for(let e of r)e&&i.push(`<attached-image name="${hs(e)}" />`);for(let e of t){let t=(e??``).trim();t&&i.push(t)}for(let e of n)i.push(ps(e));return i.join(`
|
|
3
3
|
|
|
4
|
-
`)}function hs(e){let t=e,n=[];for(;;){let e=/(?:^|\n\n)(<quoted-text>\n[^\n]*\n<\/quoted-text>)$/.exec(t),r=e?fs(e[1]):null;if(!e||!r)break;n.unshift(r),t=t.slice(0,e.index)}let r=[];return t=t.replace(/(?:^|\n\n)?<attached-image name="([^"]*)"\s*\/>/g,(e,t)=>(r.push({type:`image`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<file path="([^"]*)"(?:\s+size="[^"]*")?(?:\s+lines="(\d+)-(\d+)")?\s*\/>/g,(e,t,n,i)=>{let a=t.split(/[\\/]/).pop()??t,o=n&&i?{start:Number(n),end:Number(i)}:void 0;return r.push({type:`file`,name:a,path:t,lines:o}),``}),t=t.replace(/(?:^|\n\n)?<folder path="([^"]*)"\s*\/>/g,(e,t)=>{let n=t.split(/[\\/]/).pop()??t;return r.push({type:`folder`,name:n,path:t}),``}),t=t.replace(/(?:^|\n\n)?<browser-page url="([^"]*)" title="([^"]*)">[\s\S]*?<\/browser-page>/g,(e,t,n)=>(r.push({type:`page`,name:n||t,url:t}),``)),t=t.replace(/(?:^|\n\n)?<conversation-ref[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/conversation-ref>/g,(e,t)=>(r.push({type:`conversation`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<canvas-ref id="([^"]*)" title="([^"]*)">[\s\S]*?<\/canvas-ref>/g,(e,t,n)=>{let i=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`);return r.push({type:`canvas`,path:i(t),name:i(n)||i(t)}),``}),t=t.replace(/(?:^|\n\n)?<vision-bridge>[\s\S]*?<\/vision-bridge>/g,()=>(r.push({type:`vision-bridge`,name:`视觉转写`}),``)),r.length>0&&(t=t.trim()),{text:t,quotes:n,...r.length?{attachments:r}:{}}}var gs=[{id:`builtin.bash.rm-rf`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\brm\\s+((-[a-zA-Z0-9]*[rf][a-zA-Z0-9]*|--recursive|--force)\\s+)+(((\\/)|(~)|(\\.\\.)|(\\*)|(\\.\\/))|[a-zA-Z]:[\\\\/])`,action:`ask`,label:`递归/强制删除 (rm -rf)`,labelEn:`Recursive/force delete (rm -rf)`,reason:`检测到高风险的递归/强制删除大范围路径命令 (rm -rf)`,reasonEn:`Detected high-risk recursive/force deletion of wide paths (rm -rf)`,categoryId:`bash.rm-rf`,builtin:!0},{id:`builtin.bash.win-del`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(del|rmdir|rd)\\s+[/\\-][fsq]`,action:`ask`,label:`Windows 强制删除 (del/rmdir/rd)`,labelEn:`Windows force delete (del/rmdir/rd)`,reason:`检测到高风险的 Windows 强制/递归删除目录命令 (del/rmdir/rd /s /q)`,reasonEn:`Detected high-risk Windows force/recursive deletion command (del/rmdir/rd /s /q)`,categoryId:`bash.win-del`,builtin:!0},{id:`builtin.bash.disk`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(mkfs|format\\s+[a-zA-Z]:|dd\\s+if=)`,action:`ask`,label:`磁盘格式化/底层写入`,labelEn:`Disk format / raw block write`,reason:`检测到磁盘格式化或底层块写入危险命令 (format/mkfs/dd)`,reasonEn:`Detected dangerous disk formatting or raw block write command (format/mkfs/dd)`,categoryId:`bash.disk`,builtin:!0},{id:`builtin.bash.git-destructive`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+(?:push\\s+(?:[^;&|\\n]*?\\s)?(?:--force|-[a-zA-Z0-9]*f)\\b|push\\s+(?:[^;&|\\n]*?\\s)?(?:\\+\\S+|:[^\\s/]\\S*)|reset\\s+--hard|clean\\s+(?:-[a-zA-Z]+\\s+)*-[a-zA-Z0-9]*f[a-zA-Z0-9]*|branch\\s+-[dD]\\b|checkout\\s+(?:--\\s+)?\\.(?=\\s|$|[;&|])|restore\\s+(?:--(?!staged\\b)\\S+\\s+)*\\.(?=\\s|$|[;&|])|stash\\s+(?:drop|clear)\\b)`,action:`ask`,label:`破坏性 Git 操作`,labelEn:`Destructive git operation`,reason:`检测到不可逆的破坏性 Git 操作 (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,reasonEn:`Detected irreversible destructive Git operation (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,categoryId:`bash.git-destructive`,builtin:!0},{id:`builtin.bash.git-worktree`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+worktree\\s+(add|remove|prune)\\b`,action:`ask`,label:`Git 工作树操作 (git worktree)`,labelEn:`Git worktree operation (git worktree)`,reason:`检测到通过 Bash 执行 git worktree 操作;建议使用专门的 worktree 工具以确保界面感知与工作区同步`,reasonEn:`Detected git worktree via Bash; prefer using the dedicated worktree tool to keep the UI synchronized`,categoryId:`bash.git-worktree`,builtin:!0},{id:`builtin.bash.chmod`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bchmod\\s+(-R\\s+)?(777|000)\\b`,action:`ask`,label:`危险权限修改 (chmod)`,labelEn:`Dangerous permission change (chmod)`,reason:`检测到过度开放或全局破坏性的文件权限修改 (chmod 777/000)`,reasonEn:`Detected overly permissive or globally destructive file permission change (chmod 777/000)`,categoryId:`bash.chmod`,builtin:!0},{id:`builtin.bash.system-redirect`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`>\\s*(\\/etc\\/|\\/boot\\/|C:\\\\Windows)`,action:`ask`,label:`写入系统关键目录`,labelEn:`Write into system directories`,reason:`检测到重定向写入系统关键目录的危险操作`,reasonEn:`Detected dangerous redirection writing into critical system directories`,categoryId:`bash.system-redirect`,builtin:!0},{id:`builtin.file.sensitive.env`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$`,action:`ask`,label:`敏感配置 (.env)`,labelEn:`Sensitive config (.env)`,reason:`尝试修改敏感环境变量/密钥配置文件 (.env)`,reasonEn:`Attempting to modify sensitive environment/secret configuration (.env)`,categoryId:`file.sensitive.env`,builtin:!0},{id:`builtin.file.sensitive.ssh`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$`,action:`ask`,label:`SSH 密钥/凭据`,labelEn:`SSH keys / credentials`,reason:`尝试修改 SSH 密钥或认证凭据文件`,reasonEn:`Attempting to modify SSH keys or authentication credentials`,categoryId:`file.sensitive.ssh`,builtin:!0},{id:`builtin.file.sensitive.shell`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$`,action:`ask`,label:`Shell 启动配置`,labelEn:`Shell profile`,reason:`尝试修改用户全局 Shell 启动配置文件`,reasonEn:`Attempting to modify user global Shell profile configuration`,categoryId:`file.sensitive.shell`,builtin:!0},{id:`builtin.file.outside-workspace`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`outside_workspace`,value:``,action:`ask`,label:`工作区外写入`,labelEn:`Write outside workspace`,reason:`尝试在工作区外部写入/修改文件`,reasonEn:`Attempting to write/modify file outside the workspace`,categoryId:`file.outside-workspace`,builtin:!0}].filter(e=>e.enabled&&e.field===`command`&&e.match===`regex`&&e.tools.some(e=>e.trim().toLowerCase()===`bash`));function _s(e){if(e.length<=1)return e;let t=[...e].sort((e,t)=>e.start-t.start),n=[t[0]];for(let e=1;e<t.length;e++){let r=t[e],i=n[n.length-1];r.start<=i.end?(i.end=Math.max(i.end,r.end),r.label&&(!i.label||!i.label.includes(r.label))&&(i.label=i.label?`${i.label} / ${r.label}`:r.label)):n.push(r)}return n}function vs(e,t){if(!e||typeof e!=`string`)return[];if(t&&t.length>0){let n=[];for(let r of t)if(r.field===`command`&&r.length>0){let t=Math.max(0,r.index),i=Math.min(e.length,t+r.length);i>t&&n.push({start:t,end:i,label:r.label})}if(n.length>0)return _s(n)}let n=[];for(let t of gs){let r;try{r=new RegExp(t.value,`gi`)}catch{continue}for(let i of e.matchAll(r)){let e=i.index??0;i[0].length>0&&n.push({start:e,end:e+i[0].length,label:t.label})}}return _s(n)}function ys(e,t){let n=vs(e,t);if(n.length===0)return e;let r=[],i=0;return n.forEach((t,n)=>{t.start>i&&r.push(e.slice(i,t.start));let a=e.slice(t.start,t.end);r.push((0,$.jsx)(`mark`,{className:`bash-danger-hit`,title:t.label??`高危命令片段`,children:a},n)),i=t.end}),i<e.length&&r.push(e.slice(i)),(0,$.jsx)($.Fragment,{children:r})}function bs({quote:e,onRemove:t,forceOpen:n=!1}){let r=V(),[i,a]=(0,Q.useState)(!1),o=e.role===`user`?`role.user`:e.role===`assistant`?`role.assistant`:e.role===`toolResult`?`role.tool`:e.role===`bashExecution`?`role.bash`:`attachment`;return(0,$.jsxs)(`div`,{className:`quote-card`,children:[(0,$.jsxs)(`details`,{open:i||n,onToggle:e=>a(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{title:r(`quoteSource`,{id:e.messageId}),children:[(0,$.jsxs)(`span`,{className:`quote-source`,children:[`↪ `,r(`quoteText`),` · `,r(o)]}),(0,$.jsx)(`span`,{className:`quote-preview`,children:e.text.replace(/\s+/g,` `).slice(0,80)})]}),(0,$.jsx)(`pre`,{className:`quote-content`,children:e.text})]}),t&&(0,$.jsx)(`button`,{type:`button`,className:`quote-remove`,"aria-label":r(`removeQuote`),title:r(`removeQuote`),onClick:t,children:`×`})]})}var xs=function(){let e=this.data();(e.micromarkExtensions??=[]).push({flow:{92:Ss(!0)},text:{92:Ss(!1)}});let t={enter:{backslashMathInline:Cs,backslashMathDisplay:Cs,backslashMathBlock:Cs},exit:{backslashMathInline:ws,backslashMathDisplay:ws,backslashMathBlock:ws}};(e.fromMarkdownExtensions??=[]).push(t)};function Ss(e){return{tokenize:function(t,n,r){let i=this,a=93,o=e?`backslashMathBlock`:`backslashMathDisplay`,s;return c;function c(e){return e===92?(s=t.enter(o),t.consume(e),l):r(e)}function l(n){return n!==91&&(e||n!==40)?r(n):(a=n===91?93:41,!e&&n===40&&(s.type=o=`backslashMathInline`),t.consume(n),u)}function u(n){return n===null||e&&i.parser.lazy[i.now().line]?r(n):n===-5||n===-4||n===-3?(t.enter(`lineEnding`),t.consume(n),t.exit(`lineEnding`),u):(f(n),n===92?d:u)}function d(i){return i===a?(f(i),t.exit(o),e?p:n):i===null?r(i):i===-5||i===-4||i===-3?u(i):(f(i),u)}function f(e){t.enter(`backslashMathData`),t.consume(e),t.exit(`backslashMathData`)}function p(e){return e===null||e===-5||e===-4||e===-3?n(e):e===32||e===-2||e===-1?(t.enter(`whitespace`),t.consume(e),t.exit(`whitespace`),p):r(e)}},concrete:e,name:e?`backslashMathBlock`:`backslashMathText`}}var Cs=function(e){let t=e.type===`backslashMathBlock`,n=e.type!==`backslashMathInline`,r=this.sliceSerialize(e).slice(2,-2).trim(),i={type:`element`,tagName:`code`,properties:{className:[`language-math`,n?`math-display`:`math-inline`]},children:[{type:`text`,value:r}]},a=t?{type:`math`,meta:null,value:r,data:{hName:`pre`,hChildren:[i]}}:{type:`inlineMath`,value:r,data:{hName:`code`,hProperties:i.properties,hChildren:i.children}};this.enter(a,e)},ws=function(e){this.exit(e)},Ts=`modulepreload`,Es=function(e,t){return new URL(e,t).href},Ds={},Os=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Es(t,n),t=s(t),t in Ds)return;Ds[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Ts,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ks,As,js=new Set,Ms={load:()=>Os(()=>import(`./math-1uRJCsA9.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)};function Ns(){return ks}function Ps(e){return js.add(e),()=>{js.delete(e)}}function Fs(){return ks?Promise.resolve():(As||=Ms.load().then(e=>{ks=e.default,As=void 0;for(let e of js)e()},()=>{As=void 0}),As)}var Is=[`ariaDescribedBy`,`ariaLabel`,`ariaLabelledBy`],Ls={ancestors:{tbody:[`table`],td:[`table`],th:[`table`],thead:[`table`],tfoot:[`table`],tr:[`table`]},attributes:{a:[...Is,`dataFootnoteBackref`,`dataFootnoteRef`,[`className`,`data-footnote-backref`],`href`],blockquote:[`cite`],code:[[`className`,/^language-./]],del:[`cite`],div:[`itemScope`,`itemType`],dl:[...Is],h2:[[`className`,`sr-only`]],img:[...Is,`longDesc`,`src`],input:[[`disabled`,!0],[`type`,`checkbox`]],ins:[`cite`],li:[[`className`,`task-list-item`]],ol:[...Is,[`className`,`contains-task-list`]],q:[`cite`],section:[`dataFootnotes`,[`className`,`footnotes`]],source:[`srcSet`],summary:[...Is],table:[...Is],ul:[...Is,[`className`,`contains-task-list`]],"*":`abbr.accept.acceptCharset.accessKey.action.align.alt.axis.border.cellPadding.cellSpacing.char.charOff.charSet.checked.clear.colSpan.color.cols.compact.coords.dateTime.dir.encType.frame.hSpace.headers.height.hrefLang.htmlFor.id.isMap.itemProp.label.lang.maxLength.media.method.multiple.name.noHref.noShade.noWrap.open.prompt.readOnly.rev.rowSpan.rows.rules.scope.selected.shape.size.span.start.summary.tabIndex.title.useMap.vAlign.value.width`.split(`.`)},clobber:[`ariaDescribedBy`,`ariaLabelledBy`,`id`,`name`],clobberPrefix:`user-content-`,protocols:{cite:[`http`,`https`],href:[`http`,`https`,`irc`,`ircs`,`mailto`,`xmpp`],longDesc:[`http`,`https`],src:[`http`,`https`]},required:{input:{disabled:!0,type:`checkbox`}},strip:[`script`],tagNames:`a.b.blockquote.br.code.dd.del.details.div.dl.dt.em.h1.h2.h3.h4.h5.h6.hr.i.img.input.ins.kbd.li.ol.p.picture.pre.q.rp.rt.ruby.s.samp.section.source.span.strike.strong.sub.summary.sup.table.tbody.td.tfoot.th.thead.tr.tt.ul.var`.split(`.`)},Rs={}.hasOwnProperty;function zs(e,t){let n={type:`root`,children:[]},r=Bs({schema:t?{...Ls,...t}:Ls,stack:[]},e);return r&&(Array.isArray(r)?r.length===1?n=r[0]:n.children=r:n=r),n}function Bs(e,t){if(t&&typeof t==`object`){let n=t;switch(typeof n.type==`string`?n.type:``){case`comment`:return Vs(e,n);case`doctype`:return Hs(e,n);case`element`:return Us(e,n);case`root`:return Ws(e,n);case`text`:return Gs(e,n)}}}function Vs(e,t){if(e.schema.allowComments){let e=typeof t.value==`string`?t.value:``,n=e.indexOf(`-->`),r={type:`comment`,value:n<0?e:e.slice(0,n)};return Qs(r,t),r}}function Hs(e,t){if(e.schema.allowDoctypes){let e={type:`doctype`};return Qs(e,t),e}}function Us(e,t){let n=typeof t.tagName==`string`?t.tagName:``;e.stack.push(n);let r=Ks(e,t.children),i=qs(e,t.properties);e.stack.pop();let a=!1;if(n&&n!==`*`&&(!e.schema.tagNames||e.schema.tagNames.includes(n))&&(a=!0,e.schema.ancestors&&Rs.call(e.schema.ancestors,n))){let t=e.schema.ancestors[n],r=-1;for(a=!1;++r<t.length;)e.stack.includes(t[r])&&(a=!0)}if(!a)return e.schema.strip&&!e.schema.strip.includes(n)?r:void 0;let o={type:`element`,tagName:n,properties:i,children:r};return Qs(o,t),o}function Ws(e,t){let n={type:`root`,children:Ks(e,t.children)};return Qs(n,t),n}function Gs(e,t){let n={type:`text`,value:typeof t.value==`string`?t.value:``};return Qs(n,t),n}function Ks(e,t){let n=[];if(Array.isArray(t)){let r=t,i=-1;for(;++i<r.length;){let t=Bs(e,r[i]);t&&(Array.isArray(t)?n.push(...t):n.push(t))}}return n}function qs(e,t){let n=e.stack[e.stack.length-1],r=e.schema.attributes,i=e.schema.required,a=r&&Rs.call(r,n)?r[n]:void 0,o=r&&Rs.call(r,`*`)?r[`*`]:void 0,s=t&&typeof t==`object`?t:{},c={},l;for(l in s)if(Rs.call(s,l)){let t=s[l],n=Js(e,$s(a,l),l,t);n??=Js(e,$s(o,l),l,t),n!=null&&(c[l]=n)}if(i&&Rs.call(i,n)){let e=i[n];for(l in e)Rs.call(e,l)&&!Rs.call(c,l)&&(c[l]=e[l])}return c}function Js(e,t,n,r){return t?Array.isArray(r)?Ys(e,t,n,r):Xs(e,t,n,r):void 0}function Ys(e,t,n,r){let i=-1,a=[];for(;++i<r.length;){let o=Xs(e,t,n,r[i]);(typeof o==`number`||typeof o==`string`)&&a.push(o)}return a}function Xs(e,t,n,r){if((typeof r==`boolean`||typeof r==`number`||typeof r==`string`)&&Zs(e,n,r)){if(typeof t==`object`&&t.length>1){let e=!1,n=0;for(;++n<t.length;){let i=t[n];if(i&&typeof i==`object`&&`flags`in i){if(i.test(String(r))){e=!0;break}}else if(i===r){e=!0;break}}if(!e)return}return e.schema.clobber&&e.schema.clobberPrefix&&e.schema.clobber.includes(n)?e.schema.clobberPrefix+r:r}}function Zs(e,t,n){let r=e.schema.protocols&&Rs.call(e.schema.protocols,t)?e.schema.protocols[t]:void 0;if(!r||r.length===0)return!0;let i=String(n),a=i.indexOf(`:`),o=i.indexOf(`?`),s=i.indexOf(`#`),c=i.indexOf(`/`);if(a<0||c>-1&&a>c||o>-1&&a>o||s>-1&&a>s)return!0;let l=-1;for(;++l<r.length;){let e=r[l];if(a===e.length&&i.slice(0,e.length)===e)return!0}return!1}function Qs(e,t){let n=dn(t);t.data&&(e.data=pn(t.data)),n&&(e.position=n)}function $s(e,t){let n,r=-1;if(e)for(;++r<e.length;){let i=e[r],a=typeof i==`string`?i:i[0];if(a===t)return i;a===`data*`&&(n=i)}if(t.length>4&&t.slice(0,4).toLowerCase()===`data`)return n}function ec(e){return function(t){return zs(t,e)}}function tc(e){if(typeof document>`u`)return!1;try{let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.setAttribute(`readonly`,``),document.body.appendChild(t),t.select();let n=document.execCommand(`copy`);return document.body.removeChild(t),n}catch{return!1}}async function nc(e){if(typeof navigator<`u`&&navigator.clipboard&&typeof navigator.clipboard.writeText==`function`)try{return await navigator.clipboard.writeText(e),!0}catch{return tc(e)}return tc(e)}function rc(e={}){let{duration:t=2e3,onSuccess:n,onError:r}=e,[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null),s=(0,Q.useCallback)(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,Q.useCallback)(()=>{s(),a(!1)},[s]);return(0,Q.useEffect)(()=>()=>{s()},[s]),{copied:i,copy:(0,Q.useCallback)(async e=>{let i=!1;try{i=await nc(e)}catch(e){i=!1,r&&r(e)}return i?(a(!0),s(),o.current=setTimeout(()=>{a(!1),o.current=null},t),n?.(e)):r&&!i&&r(Error(`Copy failed`)),i},[t,n,r,s]),reset:c}}var ic=(0,Q.memo)(function({text:e}){let t=V(),{copied:n,copy:r}=rc({duration:1200});return e?(0,$.jsx)(`button`,{type:`button`,className:`copy-btn`,title:t(`copy`),onClick:()=>void r(e),children:n?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}):null});function ac(e){let t=e=>{if(typeof e==`string`||typeof e==`number`){let t=String(e);return t===``?[[]]:t.split(`
|
|
5
|
-
`).map(e=>e===``?[]:[e])}if(Array.isArray(e)){let n=[];for(let r of e){let e=t(r);if(n.length===0)n=e;else{let t=e[0]??[];n[n.length-1].push(...t),n.push(...e.slice(1))}}return n}if(e&&typeof e==`object`&&`props`in e){let n=e,r=n.props?.children,i={...n.props,children:void 0},a=r==null?[]:t(r);return a.length===0?[[(0,Q.createElement)(n.type,i)]]:a.map(e=>[(0,Q.createElement)(n.type,i,...e)])}return[[e]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function oc(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(oc).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return oc(t?.children)}return``}function sc(e){let t=Array.isArray(e)?e[0]:e;return!t||typeof t!=`object`||!(`props`in t)?null:t}function cc(e){let t=sc(e)?.props?.className;if(typeof t!=`string`)return null;let n=t.match(/(?:^|\s)language-([A-Za-z0-9_+-]+)(?:\s|$)/);return n?n[1]:null}var lc=`pi-web-ui:plugin-data`,uc=new Map,dc=new Map,fc=new Set,pc=-1,mc=0,hc=new Set;function gc(){mc++;for(let e of hc)e()}function _c(e){return hc.add(e),()=>{hc.delete(e)}}function vc(){return mc}var yc=null;function bc(e){yc=e}function xc(e,t){t!==pc&&(pc=t,dc.clear(),fc.clear());let n=new Map;for(let t of e)if(!t.error&&t.renderers)for(let e of t.renderers)n.has(e)||n.set(e,t.id);let r=n.size!==uc.size;if(!r){for(let[e,t]of n)if(uc.get(e)!==t){r=!0;break}}if(r){for(let e of dc.keys())n.has(e)||dc.delete(e);for(let e of fc)n.has(e)||fc.delete(e);uc=n,gc()}}async function Sc(e,t){let n=uc.get(e);if(!n)return null;let r=dc.get(e);if(!r&&!fc.has(e))try{let t=(await Os(()=>import(q(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${pc}`)),[],import.meta.url)).default?.renderers?.[e];typeof t==`function`?(r={pluginId:n,renderer:t},dc.set(e,r)):(fc.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(t){fc.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,t)}if(!r)return null;let i={pluginId:r.pluginId,send:e=>{yc?.({type:`plugin_message`,pluginId:r.pluginId,payload:e})},onData:e=>{let t=t=>{let n=t.detail;n.pluginId===r.pluginId&&e(n.payload)};return window.addEventListener(lc,t),()=>window.removeEventListener(lc,t)}};try{let e=await r.renderer(t,i);return e instanceof HTMLElement?e:null}catch(t){return console.error(`[plugin:${r.pluginId}] renderer("${e}") 执行失败:`,t),null}}function Cc(e){return uc.has(e)}var wc=new Map,Tc=new Map,Ec=new Set,Dc=-1;function Oc(e,t){t!==Dc&&(Dc=t,Tc.clear(),Ec.clear());let n=new Map;for(let t of e){if(t.error)continue;let e=t.messageWidgets;if(Array.isArray(e))for(let r of e)typeof r==`string`&&r&&(n.has(r)||n.set(r,t.id))}for(let e of Array.from(wc.keys()))n.has(e)||wc.delete(e);for(let[e,t]of n)wc.set(e,t);for(let e of Tc.keys())n.has(e)||Tc.delete(e);for(let e of Ec)n.has(e)||Ec.delete(e)}function kc(e){return wc.has(e)}async function Ac(e){let t=wc.get(e);if(!t)return null;let n=Tc.get(e);if(!n&&!Ec.has(e))try{let r=(await Os(()=>import(q(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${Dc}`)),[],import.meta.url)).default?.messageWidgets?.[e];typeof r==`function`?(n={pluginId:t,renderer:r},Tc.set(e,n)):(Ec.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(n){Ec.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,n)}return n?.renderer??null}function jc({lang:e,code:t}){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),i=(0,Q.useRef)(0),a=(0,Q.useRef)(new WeakMap),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=()=>{let e=++i.current,t=r.current;t&&(t.dispatchEvent(new CustomEvent(xt)),a.current.set(t,e))};return window.addEventListener(xt,e),()=>window.removeEventListener(xt,e)},[]),(0,Q.useEffect)(()=>{let n=!1,r=i.current;return s(null),Sc(e,t).then(e=>{n||(e&&a.current.set(e,r),s(e))}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{r.current=o;let e=n.current;return e&&(e.replaceChildren(),o&&(e.appendChild(o),(a.current.get(o)??i.current)<i.current&&(o.dispatchEvent(new CustomEvent(xt)),a.current.set(o,i.current)))),()=>{r.current===o&&(r.current=null)}},[o]),o?(0,$.jsx)(`div`,{className:`plugin-fence`,ref:n}):(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsx)(ic,{text:t}),(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:t})})]})}var Mc=null,Nc=new Set;function Pc(){for(let e of Nc)e()}function Fc(e){Mc=e,Pc()}function Ic(){Mc!==null&&(Mc=null,Pc())}function Lc(){return Mc}function Rc(e){return Nc.add(e),()=>{Nc.delete(e)}}function zc(){return(0,Q.useSyncExternalStore)(Rc,Lc,Lc)}function Bc(e){if(typeof document>`u`)return!1;let t=document.documentElement.dataset.theme||``;if(t===`flow`||t===`flow-light`||t===`wallpaper-flow`||t.includes(`flow`)||(document.getElementById(`theme-stylesheet`)?.getAttribute(`href`)||``).includes(`flow`))return!0;if(e){let t=e.closest(`.turn-tools-trail`);if(t){let e=window.getComputedStyle(t);if(e.flexDirection===`row`||e.flexWrap===`wrap`)return!0}let n=window.getComputedStyle(e);if(n.display===`inline-flex`&&parseInt(n.height,10)<=30)return!0}return!1}typeof window<`u`&&(window.__piToolInspectorActive=!0);var Vc=null,Hc=null;function Uc(e){Vc=e?.open??null,Hc=e?.isOpen??null}function Wc(){return Hc?Hc():!1}function Gc(e){return!Vc||!e?.path?!1:(Ic(),Vc(e),!0)}function Kc(e=typeof window<`u`?window.location.hostname:``){if(!e)return!1;let t=e.toLowerCase().trim();return!!(t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t===`[::1]`||t.startsWith(`127.`))}function qc(e){if(!e)return!0;let t=e.trim();return!t||t.startsWith(`#`)||t.startsWith(`?`)||t.startsWith(`//`)||t.startsWith(`pi-file://`)?!0:/^[a-z]:[\\/]/i.test(t)||/^file:\/\//i.test(t)?!1:/^[a-z][a-z\d+.-]*:/i.test(t)}function Jc(e,t){return(t===`href`||t===`src`)&&/^(?:[a-z]:[\\/]|file:\/\/|pi-file:\/\/)/i.test(e)?e:un(e)}function Yc(e,t){let n=e.trim();n=n.replace(/^file:\/\/(?:localhost(?=\/))?/i,``);try{n=decodeURIComponent(n)}catch{}if(n=n.replace(/\\/g,`/`).replace(/^\/([a-z]:\/)/i,`$1`),n=n.replace(/:\d+(?::\d+)?$/,``),t){let e=t.replace(/\\/g,`/`).replace(/\/+$/,``),r=/^[a-z]:\//i.test(e);(r?n.toLowerCase():n).startsWith((r?e.toLowerCase():e)+`/`)&&(n=n.slice(e.length+1))}return n}function Xc(e){let t=e.split(`?`)[0]?.split(`#`)[0]?.toLowerCase()??``;return t.endsWith(`.html`)||t.endsWith(`.htm`)||t.endsWith(`.xhtml`)}function Zc(e,t){let n=Yc(e,t),r=yh();if(Xc(n)){let e=/^[A-Za-z]:\//.test(n)||n.startsWith(`/`),t=n.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),i=e?`/api/preview/__abs__/${t}`:`/api/preview/${t}`;return Qe(q(`${i}?clientId=${encodeURIComponent(r)}&allowJs=1`))}let i=new URLSearchParams({clientId:r,path:n});return Qe(q(`/api/file?${i}`))}var Qc=[fn,mn,xs],$c=[fn],el=[fn,ln,mn,xs],tl=[fn,ln],nl=[[cn,{detect:!1,ignoreMissing:!0}]];function rl(e){if(!e||!e.includes(`@`))return e;let t=e.split(RegExp("(```[\\s\\S]*?```|`[^`\\r\\n]+`)",`g`)),n=/(^|[\s((“"'[])@((?:[\w.-]+\/)*[\w.-]+\.(?:[a-zA-Z0-9]{1,10}))(?=[)\s\],.;:!?,。!?’”"']|$)/g;for(let e=0;e<t.length;e+=2)t[e]&&(t[e]=t[e].replace(n,(e,t,n)=>t+`[@`+n+`](pi-file://`+encodeURIComponent(n)+`)`));return t.join(``)}function il({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){let i=(0,Q.useSyncExternalStore)(Ps,Ns,Ns),a=!r&&(t||/[$\\\\]|math/i.test(e));(0,Q.useEffect)(()=>{a&&!i&&Fs()},[a,i]);let o=!r&&i?[[i,{strict:!1,throwOnError:!1}],...nl]:nl,s=t?[hn,ec,...o]:o,c=(0,Q.useMemo)(()=>rl(e),[e]);return(0,$.jsx)(gn,{remarkPlugins:r?n?tl:$c:n?el:Qc,rehypePlugins:s,urlTransform:Jc,components:{pre:cl,a:ol,img:sl},children:c})}var al=(0,Q.memo)(function({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){return(0,$.jsx)(`div`,{className:`md`,children:(0,$.jsx)(il,{text:e,rawHtml:t,hardBreaks:n,disableMath:r})})});function ol({node:e,href:t,children:n,...r}){let i=String(t??``),a=H(Se()),o=en(`cwd`);if(i.startsWith(`pi-file://`)){let e=i.slice(10),t=e;try{t=decodeURIComponent(e)}catch{t=e}let r=typeof n==`string`&&n.trim()?n.trim():t.split(`/`).pop()??t;return(0,$.jsxs)(`button`,{type:`button`,className:`file-pill`,title:(a?`点击预览文件: `:`Click to preview file: `)+t,onClick:e=>{e.preventDefault(),e.stopPropagation(),Gc({path:t,name:r.replace(/^@/,``)})},children:[(0,$.jsx)(`span`,{className:`file-pill-icon`,"aria-hidden":`true`,children:`📄`}),(0,$.jsx)(`span`,{className:`file-pill-name`,children:r})]})}if(!qc(i)){let e=Yc(i,o),t=e.split(`/`).pop()||e,s=Zc(i,o);return(0,$.jsx)(`a`,{...r,href:s,onClick:n=>{n.button===0&&!n.ctrlKey&&!n.metaKey&&!n.shiftKey&&!n.altKey&&Gc({path:e,name:t})&&(n.preventDefault(),n.stopPropagation())},target:`_blank`,rel:`noreferrer noopener`,title:(a?`点击预览: `:`Click to preview: `)+e,children:n})}return/^(https?:|mailto:|tel:)/i.test(i)?(0,$.jsx)(`a`,{...r,href:t,target:`_blank`,rel:`noreferrer noopener`,children:n}):(0,$.jsx)(`a`,{href:t,...r,children:n})}function sl({node:e,src:t,alt:n,...r}){let i=String(t??``),a=en(`cwd`),o=i;return i&&!qc(i)&&!i.startsWith(`data:`)&&!i.startsWith(`blob:`)&&(o=Zc(i,a)),(0,$.jsx)(`img`,{...r,src:o,alt:n,loading:`lazy`})}function cl({children:e,...t}){(0,Q.useSyncExternalStore)(_c,vc,vc);let n=cc(e);return n&&Cc(n)?(0,$.jsx)(jc,{lang:n,code:oc(e)}):(0,$.jsx)(ll,{children:e,...t})}function ll({children:e,...t}){let n=ac(e&&typeof e==`object`&&`props`in e?e.props?.children:e),r=n.length>1,i=r?`${String(n.length).length+1}ch`:void 0;return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsx)(ic,{text:ul(e)}),(0,$.jsx)(`pre`,{...t,children:n.map((e,t)=>(0,$.jsxs)(`div`,{className:`code-line`,children:[r&&(0,$.jsx)(`span`,{className:`code-num`,style:i?{width:i}:void 0,children:t+1}),(0,$.jsx)(`code`,{className:`code-line-body`,children:e})]},t))})]})}function ul(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(ul).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return ul(t?.children)}return``}function dl({type:e,code:t,children:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let n=!1;if(a(null),kc(e))return Ac(e).then(async r=>{if(!n&&r)try{let i=await r(t,{pluginId:wc.get(e)??e,send:()=>void 0,onData:()=>()=>void 0});!n&&i instanceof HTMLElement&&a(i)}catch(t){console.error(`[plugin-widget:${e}] 渲染失败:`,t)}}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{let e=r.current;e&&(e.replaceChildren(),i&&e.appendChild(i))},[i]),i?(0,$.jsx)(`div`,{className:`plugin-widget`,ref:r}):(0,$.jsx)($.Fragment,{children:n})}var fl=/^\s{0,3}(`{3,}|~{3,})/,pl=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function ml(e){return e.trim()===``}function hl(e){let t=fl.exec(e);return t?t[1]:null}function gl(e){let t=e.split(`
|
|
6
|
-
`),n=[],r=[],i=null;for(let e=0;e<t.length;e++){let a=t[e];if(i!==null){let e=
|
|
4
|
+
`)}function _s(e){let t=e,n=[];for(;;){let e=/(?:^|\n\n)(<quoted-text>\n[^\n]*\n<\/quoted-text>)$/.exec(t),r=e?ms(e[1]):null;if(!e||!r)break;n.unshift(r),t=t.slice(0,e.index)}let r=[];return t=t.replace(/(?:^|\n\n)?<attached-image name="([^"]*)"\s*\/>/g,(e,t)=>(r.push({type:`image`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<file path="([^"]*)"(?:\s+size="[^"]*")?(?:\s+lines="(\d+)-(\d+)")?\s*\/>/g,(e,t,n,i)=>{let a=t.split(/[\\/]/).pop()??t,o=n&&i?{start:Number(n),end:Number(i)}:void 0;return r.push({type:`file`,name:a,path:t,lines:o}),``}),t=t.replace(/(?:^|\n\n)?<folder path="([^"]*)"\s*\/>/g,(e,t)=>{let n=t.split(/[\\/]/).pop()??t;return r.push({type:`folder`,name:n,path:t}),``}),t=t.replace(/(?:^|\n\n)?<browser-page url="([^"]*)" title="([^"]*)">[\s\S]*?<\/browser-page>/g,(e,t,n)=>(r.push({type:`page`,name:n||t,url:t}),``)),t=t.replace(/(?:^|\n\n)?<conversation-ref[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/conversation-ref>/g,(e,t)=>(r.push({type:`conversation`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<canvas-ref id="([^"]*)" title="([^"]*)">[\s\S]*?<\/canvas-ref>/g,(e,t,n)=>{let i=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`);return r.push({type:`canvas`,path:i(t),name:i(n)||i(t)}),``}),t=t.replace(/(?:^|\n\n)?<vision-bridge>[\s\S]*?<\/vision-bridge>/g,()=>(r.push({type:`vision-bridge`,name:`视觉转写`}),``)),r.length>0&&(t=t.trim()),{text:t,quotes:n,...r.length?{attachments:r}:{}}}var vs=[{id:`builtin.bash.rm-rf`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\brm\\s+((-[a-zA-Z0-9]*[rf][a-zA-Z0-9]*|--recursive|--force)\\s+)+(((\\/)|(~)|(\\.\\.)|(\\*)|(\\.\\/))|[a-zA-Z]:[\\\\/])`,action:`ask`,label:`递归/强制删除 (rm -rf)`,labelEn:`Recursive/force delete (rm -rf)`,reason:`检测到高风险的递归/强制删除大范围路径命令 (rm -rf)`,reasonEn:`Detected high-risk recursive/force deletion of wide paths (rm -rf)`,categoryId:`bash.rm-rf`,builtin:!0},{id:`builtin.bash.win-del`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(del|rmdir|rd)\\s+[/\\-][fsq]`,action:`ask`,label:`Windows 强制删除 (del/rmdir/rd)`,labelEn:`Windows force delete (del/rmdir/rd)`,reason:`检测到高风险的 Windows 强制/递归删除目录命令 (del/rmdir/rd /s /q)`,reasonEn:`Detected high-risk Windows force/recursive deletion command (del/rmdir/rd /s /q)`,categoryId:`bash.win-del`,builtin:!0},{id:`builtin.bash.disk`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(mkfs|format\\s+[a-zA-Z]:|dd\\s+if=)`,action:`ask`,label:`磁盘格式化/底层写入`,labelEn:`Disk format / raw block write`,reason:`检测到磁盘格式化或底层块写入危险命令 (format/mkfs/dd)`,reasonEn:`Detected dangerous disk formatting or raw block write command (format/mkfs/dd)`,categoryId:`bash.disk`,builtin:!0},{id:`builtin.bash.git-destructive`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+(?:push\\s+(?:[^;&|\\n]*?\\s)?(?:--force|-[a-zA-Z0-9]*f)\\b|push\\s+(?:[^;&|\\n]*?\\s)?(?:\\+\\S+|:[^\\s/]\\S*)|reset\\s+--hard|clean\\s+(?:-[a-zA-Z]+\\s+)*-[a-zA-Z0-9]*f[a-zA-Z0-9]*|branch\\s+-[dD]\\b|checkout\\s+(?:--\\s+)?\\.(?=\\s|$|[;&|])|restore\\s+(?:--(?!staged\\b)\\S+\\s+)*\\.(?=\\s|$|[;&|])|stash\\s+(?:drop|clear)\\b)`,action:`ask`,label:`破坏性 Git 操作`,labelEn:`Destructive git operation`,reason:`检测到不可逆的破坏性 Git 操作 (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,reasonEn:`Detected irreversible destructive Git operation (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,categoryId:`bash.git-destructive`,builtin:!0},{id:`builtin.bash.git-worktree`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+worktree\\s+(add|remove|prune)\\b`,action:`ask`,label:`Git 工作树操作 (git worktree)`,labelEn:`Git worktree operation (git worktree)`,reason:`检测到通过 Bash 执行 git worktree 操作;建议使用专门的 worktree 工具以确保界面感知与工作区同步`,reasonEn:`Detected git worktree via Bash; prefer using the dedicated worktree tool to keep the UI synchronized`,categoryId:`bash.git-worktree`,builtin:!0},{id:`builtin.bash.chmod`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bchmod\\s+(-R\\s+)?(777|000)\\b`,action:`ask`,label:`危险权限修改 (chmod)`,labelEn:`Dangerous permission change (chmod)`,reason:`检测到过度开放或全局破坏性的文件权限修改 (chmod 777/000)`,reasonEn:`Detected overly permissive or globally destructive file permission change (chmod 777/000)`,categoryId:`bash.chmod`,builtin:!0},{id:`builtin.bash.system-redirect`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`>\\s*(\\/etc\\/|\\/boot\\/|C:\\\\Windows)`,action:`ask`,label:`写入系统关键目录`,labelEn:`Write into system directories`,reason:`检测到重定向写入系统关键目录的危险操作`,reasonEn:`Detected dangerous redirection writing into critical system directories`,categoryId:`bash.system-redirect`,builtin:!0},{id:`builtin.file.sensitive.env`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$`,action:`ask`,label:`敏感配置 (.env)`,labelEn:`Sensitive config (.env)`,reason:`尝试修改敏感环境变量/密钥配置文件 (.env)`,reasonEn:`Attempting to modify sensitive environment/secret configuration (.env)`,categoryId:`file.sensitive.env`,builtin:!0},{id:`builtin.file.sensitive.ssh`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$`,action:`ask`,label:`SSH 密钥/凭据`,labelEn:`SSH keys / credentials`,reason:`尝试修改 SSH 密钥或认证凭据文件`,reasonEn:`Attempting to modify SSH keys or authentication credentials`,categoryId:`file.sensitive.ssh`,builtin:!0},{id:`builtin.file.sensitive.shell`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$`,action:`ask`,label:`Shell 启动配置`,labelEn:`Shell profile`,reason:`尝试修改用户全局 Shell 启动配置文件`,reasonEn:`Attempting to modify user global Shell profile configuration`,categoryId:`file.sensitive.shell`,builtin:!0},{id:`builtin.file.outside-workspace`,enabled:!0,tools:[`write`,`edit`,`edit_soft`,`patch`],field:`path`,match:`outside_workspace`,value:``,action:`ask`,label:`工作区外写入`,labelEn:`Write outside workspace`,reason:`尝试在工作区外部写入/修改文件`,reasonEn:`Attempting to write/modify file outside the workspace`,categoryId:`file.outside-workspace`,builtin:!0}].filter(e=>e.enabled&&e.field===`command`&&e.match===`regex`&&e.tools.some(e=>e.trim().toLowerCase()===`bash`));function ys(e){if(e.length<=1)return e;let t=[...e].sort((e,t)=>e.start-t.start),n=[t[0]];for(let e=1;e<t.length;e++){let r=t[e],i=n[n.length-1];r.start<=i.end?(i.end=Math.max(i.end,r.end),r.label&&(!i.label||!i.label.includes(r.label))&&(i.label=i.label?`${i.label} / ${r.label}`:r.label)):n.push(r)}return n}function bs(e,t){if(!e||typeof e!=`string`)return[];if(t&&t.length>0){let n=[];for(let r of t)if(r.field===`command`&&r.length>0){let t=Math.max(0,r.index),i=Math.min(e.length,t+r.length);i>t&&n.push({start:t,end:i,label:r.label})}if(n.length>0)return ys(n)}let n=[];for(let t of vs){let r;try{r=new RegExp(t.value,`gi`)}catch{continue}for(let i of e.matchAll(r)){let e=i.index??0;i[0].length>0&&n.push({start:e,end:e+i[0].length,label:t.label})}}return ys(n)}function xs(e,t){let n=bs(e,t);if(n.length===0)return e;let r=[],i=0;return n.forEach((t,n)=>{t.start>i&&r.push(e.slice(i,t.start));let a=e.slice(t.start,t.end);r.push((0,$.jsx)(`mark`,{className:`bash-danger-hit`,title:t.label??`高危命令片段`,children:a},n)),i=t.end}),i<e.length&&r.push(e.slice(i)),(0,$.jsx)($.Fragment,{children:r})}function Ss({quote:e,onRemove:t,forceOpen:n=!1}){let r=V(),[i,a]=(0,Q.useState)(!1),o=e.role===`user`?`role.user`:e.role===`assistant`?`role.assistant`:e.role===`toolResult`?`role.tool`:e.role===`bashExecution`?`role.bash`:`attachment`;return(0,$.jsxs)(`div`,{className:`quote-card`,children:[(0,$.jsxs)(`details`,{open:i||n,onToggle:e=>a(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{title:r(`quoteSource`,{id:e.messageId}),children:[(0,$.jsxs)(`span`,{className:`quote-source`,children:[`↪ `,r(`quoteText`),` · `,r(o)]}),(0,$.jsx)(`span`,{className:`quote-preview`,children:e.text.replace(/\s+/g,` `).slice(0,80)})]}),(0,$.jsx)(`pre`,{className:`quote-content`,children:e.text})]}),t&&(0,$.jsx)(`button`,{type:`button`,className:`quote-remove`,"aria-label":r(`removeQuote`),title:r(`removeQuote`),onClick:t,children:`×`})]})}var Cs=function(){let e=this.data();(e.micromarkExtensions??=[]).push({flow:{92:ws(!0)},text:{92:ws(!1)}});let t={enter:{backslashMathInline:Ts,backslashMathDisplay:Ts,backslashMathBlock:Ts},exit:{backslashMathInline:Es,backslashMathDisplay:Es,backslashMathBlock:Es}};(e.fromMarkdownExtensions??=[]).push(t)};function ws(e){return{tokenize:function(t,n,r){let i=this,a=93,o=e?`backslashMathBlock`:`backslashMathDisplay`,s;return c;function c(e){return e===92?(s=t.enter(o),t.consume(e),l):r(e)}function l(n){return n!==91&&(e||n!==40)?r(n):(a=n===91?93:41,!e&&n===40&&(s.type=o=`backslashMathInline`),t.consume(n),u)}function u(n){return n===null||e&&i.parser.lazy[i.now().line]?r(n):n===-5||n===-4||n===-3?(t.enter(`lineEnding`),t.consume(n),t.exit(`lineEnding`),u):(f(n),n===92?d:u)}function d(i){return i===a?(f(i),t.exit(o),e?p:n):i===null?r(i):i===-5||i===-4||i===-3?u(i):(f(i),u)}function f(e){t.enter(`backslashMathData`),t.consume(e),t.exit(`backslashMathData`)}function p(e){return e===null||e===-5||e===-4||e===-3?n(e):e===32||e===-2||e===-1?(t.enter(`whitespace`),t.consume(e),t.exit(`whitespace`),p):r(e)}},concrete:e,name:e?`backslashMathBlock`:`backslashMathText`}}var Ts=function(e){let t=e.type===`backslashMathBlock`,n=e.type!==`backslashMathInline`,r=this.sliceSerialize(e).slice(2,-2).trim(),i={type:`element`,tagName:`code`,properties:{className:[`language-math`,n?`math-display`:`math-inline`]},children:[{type:`text`,value:r}]},a=t?{type:`math`,meta:null,value:r,data:{hName:`pre`,hChildren:[i]}}:{type:`inlineMath`,value:r,data:{hName:`code`,hProperties:i.properties,hChildren:i.children}};this.enter(a,e)},Es=function(e){this.exit(e)},Ds=`modulepreload`,Os=function(e,t){return new URL(e,t).href},ks={},As=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Os(t,n),t=s(t),t in ks)return;ks[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Ds,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},js,Ms,Ns=new Set,Ps={load:()=>As(()=>import(`./math-1uRJCsA9.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)};function Fs(){return js}function Is(e){return Ns.add(e),()=>{Ns.delete(e)}}function Ls(){return js?Promise.resolve():(Ms||=Ps.load().then(e=>{js=e.default,Ms=void 0;for(let e of Ns)e()},()=>{Ms=void 0}),Ms)}var Rs=[`ariaDescribedBy`,`ariaLabel`,`ariaLabelledBy`],zs={ancestors:{tbody:[`table`],td:[`table`],th:[`table`],thead:[`table`],tfoot:[`table`],tr:[`table`]},attributes:{a:[...Rs,`dataFootnoteBackref`,`dataFootnoteRef`,[`className`,`data-footnote-backref`],`href`],blockquote:[`cite`],code:[[`className`,/^language-./]],del:[`cite`],div:[`itemScope`,`itemType`],dl:[...Rs],h2:[[`className`,`sr-only`]],img:[...Rs,`longDesc`,`src`],input:[[`disabled`,!0],[`type`,`checkbox`]],ins:[`cite`],li:[[`className`,`task-list-item`]],ol:[...Rs,[`className`,`contains-task-list`]],q:[`cite`],section:[`dataFootnotes`,[`className`,`footnotes`]],source:[`srcSet`],summary:[...Rs],table:[...Rs],ul:[...Rs,[`className`,`contains-task-list`]],"*":`abbr.accept.acceptCharset.accessKey.action.align.alt.axis.border.cellPadding.cellSpacing.char.charOff.charSet.checked.clear.colSpan.color.cols.compact.coords.dateTime.dir.encType.frame.hSpace.headers.height.hrefLang.htmlFor.id.isMap.itemProp.label.lang.maxLength.media.method.multiple.name.noHref.noShade.noWrap.open.prompt.readOnly.rev.rowSpan.rows.rules.scope.selected.shape.size.span.start.summary.tabIndex.title.useMap.vAlign.value.width`.split(`.`)},clobber:[`ariaDescribedBy`,`ariaLabelledBy`,`id`,`name`],clobberPrefix:`user-content-`,protocols:{cite:[`http`,`https`],href:[`http`,`https`,`irc`,`ircs`,`mailto`,`xmpp`],longDesc:[`http`,`https`],src:[`http`,`https`]},required:{input:{disabled:!0,type:`checkbox`}},strip:[`script`],tagNames:`a.b.blockquote.br.code.dd.del.details.div.dl.dt.em.h1.h2.h3.h4.h5.h6.hr.i.img.input.ins.kbd.li.ol.p.picture.pre.q.rp.rt.ruby.s.samp.section.source.span.strike.strong.sub.summary.sup.table.tbody.td.tfoot.th.thead.tr.tt.ul.var`.split(`.`)},Bs={}.hasOwnProperty;function Vs(e,t){let n={type:`root`,children:[]},r=Hs({schema:t?{...zs,...t}:zs,stack:[]},e);return r&&(Array.isArray(r)?r.length===1?n=r[0]:n.children=r:n=r),n}function Hs(e,t){if(t&&typeof t==`object`){let n=t;switch(typeof n.type==`string`?n.type:``){case`comment`:return Us(e,n);case`doctype`:return Ws(e,n);case`element`:return Gs(e,n);case`root`:return Ks(e,n);case`text`:return qs(e,n)}}}function Us(e,t){if(e.schema.allowComments){let e=typeof t.value==`string`?t.value:``,n=e.indexOf(`-->`),r={type:`comment`,value:n<0?e:e.slice(0,n)};return ec(r,t),r}}function Ws(e,t){if(e.schema.allowDoctypes){let e={type:`doctype`};return ec(e,t),e}}function Gs(e,t){let n=typeof t.tagName==`string`?t.tagName:``;e.stack.push(n);let r=Js(e,t.children),i=Ys(e,t.properties);e.stack.pop();let a=!1;if(n&&n!==`*`&&(!e.schema.tagNames||e.schema.tagNames.includes(n))&&(a=!0,e.schema.ancestors&&Bs.call(e.schema.ancestors,n))){let t=e.schema.ancestors[n],r=-1;for(a=!1;++r<t.length;)e.stack.includes(t[r])&&(a=!0)}if(!a)return e.schema.strip&&!e.schema.strip.includes(n)?r:void 0;let o={type:`element`,tagName:n,properties:i,children:r};return ec(o,t),o}function Ks(e,t){let n={type:`root`,children:Js(e,t.children)};return ec(n,t),n}function qs(e,t){let n={type:`text`,value:typeof t.value==`string`?t.value:``};return ec(n,t),n}function Js(e,t){let n=[];if(Array.isArray(t)){let r=t,i=-1;for(;++i<r.length;){let t=Hs(e,r[i]);t&&(Array.isArray(t)?n.push(...t):n.push(t))}}return n}function Ys(e,t){let n=e.stack[e.stack.length-1],r=e.schema.attributes,i=e.schema.required,a=r&&Bs.call(r,n)?r[n]:void 0,o=r&&Bs.call(r,`*`)?r[`*`]:void 0,s=t&&typeof t==`object`?t:{},c={},l;for(l in s)if(Bs.call(s,l)){let t=s[l],n=Xs(e,tc(a,l),l,t);n??=Xs(e,tc(o,l),l,t),n!=null&&(c[l]=n)}if(i&&Bs.call(i,n)){let e=i[n];for(l in e)Bs.call(e,l)&&!Bs.call(c,l)&&(c[l]=e[l])}return c}function Xs(e,t,n,r){return t?Array.isArray(r)?Zs(e,t,n,r):Qs(e,t,n,r):void 0}function Zs(e,t,n,r){let i=-1,a=[];for(;++i<r.length;){let o=Qs(e,t,n,r[i]);(typeof o==`number`||typeof o==`string`)&&a.push(o)}return a}function Qs(e,t,n,r){if((typeof r==`boolean`||typeof r==`number`||typeof r==`string`)&&$s(e,n,r)){if(typeof t==`object`&&t.length>1){let e=!1,n=0;for(;++n<t.length;){let i=t[n];if(i&&typeof i==`object`&&`flags`in i){if(i.test(String(r))){e=!0;break}}else if(i===r){e=!0;break}}if(!e)return}return e.schema.clobber&&e.schema.clobberPrefix&&e.schema.clobber.includes(n)?e.schema.clobberPrefix+r:r}}function $s(e,t,n){let r=e.schema.protocols&&Bs.call(e.schema.protocols,t)?e.schema.protocols[t]:void 0;if(!r||r.length===0)return!0;let i=String(n),a=i.indexOf(`:`),o=i.indexOf(`?`),s=i.indexOf(`#`),c=i.indexOf(`/`);if(a<0||c>-1&&a>c||o>-1&&a>o||s>-1&&a>s)return!0;let l=-1;for(;++l<r.length;){let e=r[l];if(a===e.length&&i.slice(0,e.length)===e)return!0}return!1}function ec(e,t){let n=dn(t);t.data&&(e.data=pn(t.data)),n&&(e.position=n)}function tc(e,t){let n,r=-1;if(e)for(;++r<e.length;){let i=e[r],a=typeof i==`string`?i:i[0];if(a===t)return i;a===`data*`&&(n=i)}if(t.length>4&&t.slice(0,4).toLowerCase()===`data`)return n}function nc(e){return function(t){return Vs(t,e)}}function rc(e){if(typeof document>`u`)return!1;try{let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`-9999px`,t.setAttribute(`readonly`,``),document.body.appendChild(t),t.select();let n=document.execCommand(`copy`);return document.body.removeChild(t),n}catch{return!1}}async function ic(e){if(typeof navigator<`u`&&navigator.clipboard&&typeof navigator.clipboard.writeText==`function`)try{return await navigator.clipboard.writeText(e),!0}catch{return rc(e)}return rc(e)}function ac(e={}){let{duration:t=2e3,onSuccess:n,onError:r}=e,[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null),s=(0,Q.useCallback)(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),c=(0,Q.useCallback)(()=>{s(),a(!1)},[s]);return(0,Q.useEffect)(()=>()=>{s()},[s]),{copied:i,copy:(0,Q.useCallback)(async e=>{let i=!1;try{i=await ic(e)}catch(e){i=!1,r&&r(e)}return i?(a(!0),s(),o.current=setTimeout(()=>{a(!1),o.current=null},t),n?.(e)):r&&!i&&r(Error(`Copy failed`)),i},[t,n,r,s]),reset:c}}var oc=(0,Q.memo)(function({text:e}){let t=V(),{copied:n,copy:r}=ac({duration:1200});return e?(0,$.jsx)(`button`,{type:`button`,className:`copy-btn`,title:t(`copy`),onClick:()=>void r(e),children:n?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}):null});function sc(e){let t=e=>{if(typeof e==`string`||typeof e==`number`){let t=String(e);return t===``?[[]]:t.split(`
|
|
5
|
+
`).map(e=>e===``?[]:[e])}if(Array.isArray(e)){let n=[];for(let r of e){let e=t(r);if(n.length===0)n=e;else{let t=e[0]??[];n[n.length-1].push(...t),n.push(...e.slice(1))}}return n}if(e&&typeof e==`object`&&`props`in e){let n=e,r=n.props?.children,i={...n.props,children:void 0},a=r==null?[]:t(r);return a.length===0?[[(0,Q.createElement)(n.type,i)]]:a.map(e=>[(0,Q.createElement)(n.type,i,...e)])}return[[e]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function cc(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(cc).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return cc(t?.children)}return``}function lc(e){let t=Array.isArray(e)?e[0]:e;return!t||typeof t!=`object`||!(`props`in t)?null:t}function uc(e){let t=lc(e)?.props?.className;if(typeof t!=`string`)return null;let n=t.match(/(?:^|\s)language-([A-Za-z0-9_+-]+)(?:\s|$)/);return n?n[1]:null}var dc=`pi-web-ui:plugin-data`,fc=new Map,pc=new Map,mc=new Set,hc=-1,gc=0,_c=new Set;function vc(){gc++;for(let e of _c)e()}function yc(e){return _c.add(e),()=>{_c.delete(e)}}function bc(){return gc}var xc=null;function Sc(e){xc=e}function Cc(e,t){t!==hc&&(hc=t,pc.clear(),mc.clear());let n=new Map;for(let t of e)if(!t.error&&t.renderers)for(let e of t.renderers)n.has(e)||n.set(e,t.id);let r=n.size!==fc.size;if(!r){for(let[e,t]of n)if(fc.get(e)!==t){r=!0;break}}if(r){for(let e of pc.keys())n.has(e)||pc.delete(e);for(let e of mc)n.has(e)||mc.delete(e);fc=n,vc()}}async function wc(e,t){let n=fc.get(e);if(!n)return null;let r=pc.get(e);if(!r&&!mc.has(e))try{let t=(await As(()=>import(q(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${hc}`)),[],import.meta.url)).default?.renderers?.[e];typeof t==`function`?(r={pluginId:n,renderer:t},pc.set(e,r)):(mc.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(t){mc.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,t)}if(!r)return null;let i={pluginId:r.pluginId,send:e=>{xc?.({type:`plugin_message`,pluginId:r.pluginId,payload:e})},onData:e=>{let t=t=>{let n=t.detail;n.pluginId===r.pluginId&&e(n.payload)};return window.addEventListener(dc,t),()=>window.removeEventListener(dc,t)}};try{let e=await r.renderer(t,i);return e instanceof HTMLElement?e:null}catch(t){return console.error(`[plugin:${r.pluginId}] renderer("${e}") 执行失败:`,t),null}}function Tc(e){return fc.has(e)}var Ec=new Map,Dc=new Map,Oc=new Set,kc=-1;function Ac(e,t){t!==kc&&(kc=t,Dc.clear(),Oc.clear());let n=new Map;for(let t of e){if(t.error)continue;let e=t.messageWidgets;if(Array.isArray(e))for(let r of e)typeof r==`string`&&r&&(n.has(r)||n.set(r,t.id))}for(let e of Array.from(Ec.keys()))n.has(e)||Ec.delete(e);for(let[e,t]of n)Ec.set(e,t);for(let e of Dc.keys())n.has(e)||Dc.delete(e);for(let e of Oc)n.has(e)||Oc.delete(e)}function jc(e){return Ec.has(e)}async function Mc(e){let t=Ec.get(e);if(!t)return null;let n=Dc.get(e);if(!n&&!Oc.has(e))try{let r=(await As(()=>import(q(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${kc}`)),[],import.meta.url)).default?.messageWidgets?.[e];typeof r==`function`?(n={pluginId:t,renderer:r},Dc.set(e,n)):(Oc.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(n){Oc.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,n)}return n?.renderer??null}function Nc({lang:e,code:t}){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),i=(0,Q.useRef)(0),a=(0,Q.useRef)(new WeakMap),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=()=>{let e=++i.current,t=r.current;t&&(t.dispatchEvent(new CustomEvent(xt)),a.current.set(t,e))};return window.addEventListener(xt,e),()=>window.removeEventListener(xt,e)},[]),(0,Q.useEffect)(()=>{let n=!1,r=i.current;return s(null),wc(e,t).then(e=>{n||(e&&a.current.set(e,r),s(e))}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{r.current=o;let e=n.current;return e&&(e.replaceChildren(),o&&(e.appendChild(o),(a.current.get(o)??i.current)<i.current&&(o.dispatchEvent(new CustomEvent(xt)),a.current.set(o,i.current)))),()=>{r.current===o&&(r.current=null)}},[o]),o?(0,$.jsx)(`div`,{className:`plugin-fence`,ref:n}):(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsx)(oc,{text:t}),(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:t})})]})}var Pc=null,Fc=new Set;function Ic(){for(let e of Fc)e()}function Lc(e){Pc=e,Ic()}function Rc(){Pc!==null&&(Pc=null,Ic())}function zc(){return Pc}function Bc(e){return Fc.add(e),()=>{Fc.delete(e)}}function Vc(){return(0,Q.useSyncExternalStore)(Bc,zc,zc)}function Hc(e){if(typeof document>`u`)return!1;let t=document.documentElement.dataset.theme||``;if(t===`flow`||t===`flow-light`||t===`wallpaper-flow`||t.includes(`flow`)||(document.getElementById(`theme-stylesheet`)?.getAttribute(`href`)||``).includes(`flow`))return!0;if(e){let t=e.closest(`.turn-tools-trail`);if(t){let e=window.getComputedStyle(t);if(e.flexDirection===`row`||e.flexWrap===`wrap`)return!0}let n=window.getComputedStyle(e);if(n.display===`inline-flex`&&parseInt(n.height,10)<=30)return!0}return!1}typeof window<`u`&&(window.__piToolInspectorActive=!0);var Uc=null,Wc=null;function Gc(e){Uc=e?.open??null,Wc=e?.isOpen??null}function Kc(){return Wc?Wc():!1}function qc(e){return!Uc||!e?.path?!1:(Rc(),Uc(e),!0)}function Jc(e=typeof window<`u`?window.location.hostname:``){if(!e)return!1;let t=e.toLowerCase().trim();return!!(t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t===`[::1]`||t.startsWith(`127.`))}function Yc(e){if(!e)return!0;let t=e.trim();return!t||t.startsWith(`#`)||t.startsWith(`?`)||t.startsWith(`//`)||t.startsWith(`pi-file://`)?!0:/^[a-z]:[\\/]/i.test(t)||/^file:\/\//i.test(t)?!1:/^[a-z][a-z\d+.-]*:/i.test(t)}function Xc(e,t){return(t===`href`||t===`src`)&&/^(?:[a-z]:[\\/]|file:\/\/|pi-file:\/\/)/i.test(e)?e:un(e)}function Zc(e,t){let n=e.trim();n=n.replace(/^file:\/\/(?:localhost(?=\/))?/i,``);try{n=decodeURIComponent(n)}catch{}if(n=n.replace(/\\/g,`/`).replace(/^\/([a-z]:\/)/i,`$1`),n=n.replace(/:\d+(?::\d+)?$/,``),t){let e=t.replace(/\\/g,`/`).replace(/\/+$/,``),r=/^[a-z]:\//i.test(e);(r?n.toLowerCase():n).startsWith((r?e.toLowerCase():e)+`/`)&&(n=n.slice(e.length+1))}return n}function Qc(e){let t=e.split(`?`)[0]?.split(`#`)[0]?.toLowerCase()??``;return t.endsWith(`.html`)||t.endsWith(`.htm`)||t.endsWith(`.xhtml`)}function $c(e,t){let n=Zc(e,t),r=xh();if(Qc(n)){let e=/^[A-Za-z]:\//.test(n)||n.startsWith(`/`),t=n.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),i=e?`/api/preview/__abs__/${t}`:`/api/preview/${t}`;return Qe(q(`${i}?clientId=${encodeURIComponent(r)}&allowJs=1`))}let i=new URLSearchParams({clientId:r,path:n});return Qe(q(`/api/file?${i}`))}var el=[fn,mn,Cs],tl=[fn],nl=[fn,ln,mn,Cs],rl=[fn,ln],il=[[cn,{detect:!1,ignoreMissing:!0}]];function al(e){if(!e||!e.includes(`@`))return e;let t=e.split(RegExp("(```[\\s\\S]*?```|`[^`\\r\\n]+`)",`g`)),n=/(^|[\s((“"'[])@((?:[\w.-]+\/)*[\w.-]+\.(?:[a-zA-Z0-9]{1,10}))(?=[)\s\],.;:!?,。!?’”"']|$)/g;for(let e=0;e<t.length;e+=2)t[e]&&(t[e]=t[e].replace(n,(e,t,n)=>t+`[@`+n+`](pi-file://`+encodeURIComponent(n)+`)`));return t.join(``)}function ol({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){let i=(0,Q.useSyncExternalStore)(Is,Fs,Fs),a=!r&&(t||/[$\\\\]|math/i.test(e));(0,Q.useEffect)(()=>{a&&!i&&Ls()},[a,i]);let o=!r&&i?[[i,{strict:!1,throwOnError:!1}],...il]:il,s=t?[hn,nc,...o]:o,c=(0,Q.useMemo)(()=>al(e),[e]);return(0,$.jsx)(gn,{remarkPlugins:r?n?rl:tl:n?nl:el,rehypePlugins:s,urlTransform:Xc,components:{pre:ul,a:cl,img:ll},children:c})}var sl=(0,Q.memo)(function({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){return(0,$.jsx)(`div`,{className:`md`,children:(0,$.jsx)(ol,{text:e,rawHtml:t,hardBreaks:n,disableMath:r})})});function cl({node:e,href:t,children:n,...r}){let i=String(t??``),a=H(Se()),o=en(`cwd`);if(i.startsWith(`pi-file://`)){let e=i.slice(10),t=e;try{t=decodeURIComponent(e)}catch{t=e}let r=typeof n==`string`&&n.trim()?n.trim():t.split(`/`).pop()??t;return(0,$.jsxs)(`button`,{type:`button`,className:`file-pill`,title:(a?`点击预览文件: `:`Click to preview file: `)+t,onClick:e=>{e.preventDefault(),e.stopPropagation(),qc({path:t,name:r.replace(/^@/,``)})},children:[(0,$.jsx)(`span`,{className:`file-pill-icon`,"aria-hidden":`true`,children:`📄`}),(0,$.jsx)(`span`,{className:`file-pill-name`,children:r})]})}if(!Yc(i)){let e=Zc(i,o),t=e.split(`/`).pop()||e,s=$c(i,o);return(0,$.jsx)(`a`,{...r,href:s,onClick:n=>{n.button===0&&!n.ctrlKey&&!n.metaKey&&!n.shiftKey&&!n.altKey&&qc({path:e,name:t})&&(n.preventDefault(),n.stopPropagation())},target:`_blank`,rel:`noreferrer noopener`,title:(a?`点击预览: `:`Click to preview: `)+e,children:n})}return/^(https?:|mailto:|tel:)/i.test(i)?(0,$.jsx)(`a`,{...r,href:t,target:`_blank`,rel:`noreferrer noopener`,children:n}):(0,$.jsx)(`a`,{href:t,...r,children:n})}function ll({node:e,src:t,alt:n,...r}){let i=String(t??``),a=en(`cwd`),o=i;return i&&!Yc(i)&&!i.startsWith(`data:`)&&!i.startsWith(`blob:`)&&(o=$c(i,a)),(0,$.jsx)(`img`,{...r,src:o,alt:n,loading:`lazy`})}function ul({children:e,...t}){(0,Q.useSyncExternalStore)(yc,bc,bc);let n=uc(e);return n&&Tc(n)?(0,$.jsx)(Nc,{lang:n,code:cc(e)}):(0,$.jsx)(dl,{children:e,...t})}function dl({children:e,...t}){let n=sc(e&&typeof e==`object`&&`props`in e?e.props?.children:e),r=n.length>1,i=r?`${String(n.length).length+1}ch`:void 0;return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsx)(oc,{text:fl(e)}),(0,$.jsx)(`pre`,{...t,children:n.map((e,t)=>(0,$.jsxs)(`div`,{className:`code-line`,children:[r&&(0,$.jsx)(`span`,{className:`code-num`,style:i?{width:i}:void 0,children:t+1}),(0,$.jsx)(`code`,{className:`code-line-body`,children:e})]},t))})]})}function fl(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(fl).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return fl(t?.children)}return``}function pl({type:e,code:t,children:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let n=!1;if(a(null),jc(e))return Mc(e).then(async r=>{if(!n&&r)try{let i=await r(t,{pluginId:Ec.get(e)??e,send:()=>void 0,onData:()=>()=>void 0});!n&&i instanceof HTMLElement&&a(i)}catch(t){console.error(`[plugin-widget:${e}] 渲染失败:`,t)}}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{let e=r.current;e&&(e.replaceChildren(),i&&e.appendChild(i))},[i]),i?(0,$.jsx)(`div`,{className:`plugin-widget`,ref:r}):(0,$.jsx)($.Fragment,{children:n})}var ml=/^\s{0,3}(`{3,}|~{3,})/,hl=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function gl(e){return e.trim()===``}function _l(e){let t=ml.exec(e);return t?t[1]:null}function vl(e){let t=e.split(`
|
|
6
|
+
`),n=[],r=[],i=null;for(let e=0;e<t.length;e++){let a=t[e];if(i!==null){let e=_l(a);e&&e[0]===i[0]&&e.length>=i.length&&(i=null),r.push(a);continue}let o=_l(a);if(o&&!gl(a)){i=o,r.push(a);continue}if(gl(a)){let i=e;for(;i<t.length&&gl(t[i]);)i++;if(!(i<t.length&&hl.test(t[i]))&&r.length>0){n.push(r.join(`
|
|
7
7
|
`)),r=[];continue}r.push(a);continue}r.push(a)}return{frozen:n,active:r.join(`
|
|
8
|
-
`),inFence:i!==null}}function
|
|
8
|
+
`),inFence:i!==null}}function yl(e,t,n=!1){let r=e.length;if(t>=r)return r;t<0&&(t=0);let i=r-t,a;a=n?i<=16?Math.max(2,Math.ceil(i/6)):Math.ceil(i/8):i<=32?1:i<=90?2:Math.ceil(i<=240?i/28:i/18);let o=Math.min(r,t+a);if(o<r){let t=e.charCodeAt(o-1);t>=55296&&t<=56319&&(o=Math.min(r,o+1))}return o}var bl=22,xl=14,Sl=()=>typeof document<`u`&&document.hidden;function Cl(e,t=!0,n=!1,r){let[i,a]=(0,Q.useState)(()=>!t||Sl()||e.length>1500?e.length:0),o=(0,Q.useRef)(e);o.current=e;let s=(0,Q.useRef)(i);s.current=i;let c=(0,Q.useRef)(t);c.current=t;let l=(0,Q.useRef)(n);l.current=n;let u=(0,Q.useRef)(r);u.current=r;let d=(0,Q.useRef)(0),f=(0,Q.useRef)(0);return(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{document.hidden,d.current&&=(cancelAnimationFrame(d.current),0),s.current=o.current.length,a(o.current.length),(l.current||!c.current)&&u.current?.()};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),(0,Q.useEffect)(()=>{if(!t){d.current&&=(cancelAnimationFrame(d.current),0),s.current!==e.length&&(s.current=e.length,a(e.length));return}if(Sl()){d.current&&=(cancelAnimationFrame(d.current),0),s.current!==e.length&&(s.current=e.length,a(e.length)),(n||s.current>=e.length)&&u.current?.();return}if(e.length<s.current){d.current&&=(cancelAnimationFrame(d.current),0),s.current=e.length,a(e.length),u.current?.();return}if(s.current>=e.length){d.current||u.current?.();return}if(d.current)return;let r=e=>{if(d.current=0,!c.current)return;let t=l.current?xl:bl;if(f.current>0&&e-f.current<t){d.current=requestAnimationFrame(r);return}f.current=e;let n=o.current,i=yl(n,s.current,l.current);i!==s.current&&(s.current=i,a(i)),i<o.current.length?d.current=requestAnimationFrame(r):u.current?.()};d.current=requestAnimationFrame(r)},[e,t,n]),(0,Q.useEffect)(()=>()=>{d.current&&=(cancelAnimationFrame(d.current),0)},[]),!t||i>=e.length?e:e.slice(0,i)}var wl=600,Tl=32,El=(0,Q.memo)(function({text:e,active:t,inFence:n}){let r=t&&!n&&e.length>=wl,[i,a]=(0,Q.useState)(e),o=(0,Q.useRef)(0),s=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!r)return;let t=Date.now()-o.current,n=()=>{o.current=Date.now(),a(e)};if(t>=Tl){n();return}return s.current=setTimeout(n,Tl-t),()=>{s.current&&clearTimeout(s.current)}},[e,r]),t&&n?(0,$.jsx)(`div`,{className:`codeblock`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:e})})}):(0,$.jsx)(ol,{text:r?i:e})}),Dl=(0,Q.memo)(function({text:e,finishing:t=!1,onSettled:n}){let r=Cl(e,!0,t,n),{frozen:i,active:a,inFence:o}=(0,Q.useMemo)(()=>vl(r),[r]);return(0,$.jsx)(`div`,{className:`md`,children:[...i,...a.length>0?[a]:[]].map((e,t)=>(0,$.jsx)(El,{text:e,active:t===i.length,inFence:t===i.length&&o},t))})});function Ol({open:e,onToggle:t,headClassName:n,titleText:r,icon:i,iconClassName:a,titleClassName:o,toggleClassName:s,toggle:c,onHeadContextMenu:l,children:u,after:d}){return(0,$.jsxs)(`div`,{className:`chead ${n}`,role:`button`,tabIndex:0,"aria-expanded":e,title:r,onClick:t,onContextMenu:l,onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),t())},children:[c===void 0?(0,$.jsx)(`button`,{type:`button`,className:s?`chead-toggle ${s}`:`chead-toggle`,title:r,"aria-label":r,"aria-expanded":e,onClick:e=>{e.stopPropagation(),t()},children:e?(0,$.jsx)(pe,{}):(0,$.jsx)(P,{})}):c,(0,$.jsx)(`span`,{className:a?`chead-icon ${a}`:`chead-icon`,children:i}),(0,$.jsx)(`span`,{className:o?`chead-title ${o}`:`chead-title`,children:u}),d]})}var kl=300;function Al(e){let t=e.split(`
|
|
9
9
|
`),n=0;for(;n<t.length;){let e=t[n].trim();if(!e){n++;continue}let r=e.replace(/^[#*>\s]+/,``).toLowerCase();if(r===`thinking`||r===`thinking:`||r===`thinking process`||r===`thinking process:`||r===`思考`||r===`思考过程`||r===`思考过程:`||r===`思路`||r===`思路:`){n++;continue}break}return t.slice(n).join(`
|
|
10
|
-
`)}function
|
|
10
|
+
`)}function jl(e){return!e||!e.includes(`[[`)?e:e.replace(/\[\[(?:conv|todo|action|suggest|notify|goal):[\s\S]*?\]\]/gu,``).replace(/\[\[(?:conv|todo|action|suggest|notify|goal):[^\]]*$/u,``)}function Ml(e){let t=jl(e).replace(/\r\n/g,`
|
|
11
11
|
`).replace(/[ \t]+\n/g,`
|
|
12
|
-
`),n=
|
|
12
|
+
`),n=Al(t).trim()||t.trim();return n?n.replace(/\n{3,}/g,`
|
|
13
13
|
|
|
14
|
-
`):``}function
|
|
15
|
-
`),n=t[0].replace(/\s+/g,` `).trim();if(!n)return;let r=t.length-1,i=n.length>80?`${n.slice(0,80)}…`:n;return r>0?`${i} +${r}`:i}function
|
|
16
|
-
`),i=r===-1?t.trim():t.slice(0,r).trim(),a;if(i.startsWith(`// @options:`))try{a=JSON.parse(i.slice(12).trim())}catch{}return{code:t,options:a}}function
|
|
17
|
-
`).length;return n>0?n:void 0}var
|
|
18
|
-
`).filter(e=>e.trim());for(let t of e){let e=t.indexOf(`:`);if(e===-1)continue;let r=t.slice(0,e).trim(),i=t.slice(e+1).trim(),a=[],o,s=/\s*\(wrote:\s*(.*?)\)$/i.exec(i),c=i;s&&(o=s[1],c=i.slice(0,s.index).trim()),c&&c!==`(no selection)`&&(a=c.split(`,`).map(e=>e.trim()).filter(Boolean)),n.set(r,{id:r,selected:a,custom:o})}}return n}function
|
|
19
|
-
`;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`\\`:return`\\`;case`/`:return`/`;case`"`:return`"`;default:if(t.startsWith(`u`))try{return String.fromCharCode(parseInt(t.slice(1),16))}catch{return`\\${t}`}return`\\${t}`}}):``}function
|
|
20
|
-
`),c=[],l=[],u=()=>{if(c.length===1&&l.length===1){let{oldTokens:e,newTokens:t}=
|
|
14
|
+
`):``}function Nl(e){let t=jl(e),n=Al(t).trim()||t.trim();return n?n.split(/\n+/).map(e=>e.trim()).filter(Boolean).join(` `):``}function Pl(e,t){let n=Nl(e);return n?t?n.slice(-300):n.slice(0,kl):``}function Fl({thinking:e,streaming:t,wrap:n=!0,forceOpen:r=!1}){let i=V(),[a,o]=(0,Q.useState)(null),s=a??n,c=s||r,l=!!t,u=(0,Q.useRef)(l);u.current=l;let d=()=>typeof document<`u`&&document.hidden,[f,p]=(0,Q.useState)(()=>l&&!d());(0,Q.useEffect)(()=>{l&&!d()?p(!0):!l&&d()&&p(!1)},[l]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{u.current||p(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let m=(0,Q.useCallback)(()=>{u.current||p(!1)},[]),h=l||f,g=Cl(e,h,!l&&f,m),_=Ml(g),v=Pl(g,h),{copied:y,copy:b}=ac({duration:1200}),x=()=>{b(e)},S=c?i(`collapseMsg`):v?`${i(`expandMsg`)} · ${v}`:i(`expandMsg`),C=(0,Q.useRef)(null),w=Hc(C.current),T=()=>{Lc({isThinking:!0,title:i(`toolInspectorThinkingTitle`),status:i(h?`thinkingNow`:`done`),statusClass:h?`run`:`ok`,output:_||e,thinking:e,streaming:h})};return w?(0,$.jsx)(`div`,{ref:C,className:`thinking ${h?`live run`:`ok`}`,"data-thinking":e,onClick:e=>{e.preventDefault(),e.stopPropagation(),T()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),T())},role:`button`,tabIndex:0,title:i(`toolInspectorThinkingTitle`),children:(0,$.jsxs)(`div`,{className:`thinking-head chead`,children:[(0,$.jsx)(`span`,{className:`thinking-icon chead-icon`,children:(0,$.jsx)(E,{})}),(0,$.jsx)(`span`,{className:`thinking-name chead-title`,children:`think`}),(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:i(h?`thinkingNow`:`done`),"aria-label":i(h?`thinkingNow`:`done`),children:h?(0,$.jsx)($o,{className:`spin`}):(0,$.jsx)(z,{})})]})}):(0,$.jsxs)(`div`,{ref:C,className:`thinking ${c?`open`:``} ${h?`live`:``} ${h?`run`:`ok`}`,"data-thinking":e,onClick:e=>{Hc(C.current)&&(e.target?.closest(`.chead-copy, .toolcall-copy, .thinking-copy, a`)||(e.preventDefault(),e.stopPropagation(),T()))},children:[(0,$.jsxs)(Ol,{open:!w&&c,headClassName:`thinking-head${h?` thinking-live`:``}`,toggleClassName:`thinking-toggle`,titleText:S,onToggle:()=>{if(Hc(C.current)){T();return}o(!s)},icon:(0,$.jsx)(E,{}),iconClassName:`thinking-icon`,titleClassName:`thinking-label`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:i(h?`thinkingNow`:`done`),"aria-label":i(h?`thinkingNow`:`done`),children:h?(0,$.jsx)($o,{className:`spin`}):(0,$.jsx)(z,{})}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy thinking-copy${y?` copied`:``}`,title:i(y?`copied`:`copyMessage`),"aria-label":i(`copyMessage`),onClick:e=>{e.stopPropagation(),x()},children:y?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})})]}),children:[(0,$.jsx)(`span`,{className:`thinking-name`,children:`think`}),h&&c?(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[i(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):h?v?(0,$.jsxs)(`span`,{className:`thinking-preview-live`,children:[(0,$.jsx)(`span`,{className:`thinking-preview-prefix`,children:` · `}),(0,$.jsx)(`span`,{className:`thinking-preview-viewport`,children:(0,$.jsxs)(`span`,{className:`thinking-preview-track`,children:[v,(0,$.jsx)(`span`,{className:`stream-cursor`})]})})]}):(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[i(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):v?(0,$.jsxs)(`span`,{className:`thinking-summary-text`,children:[` · `,v]}):null]}),!w&&c&&(0,$.jsxs)(`div`,{className:`thinking-body`,children:[_,h&&(0,$.jsx)(`span`,{className:`stream-cursor`})]})]})}function Il(e){let t=typeof e.name==`string`?e.name:``;if(e.unsupported===!0)return{name:t,status:`unsupported`};if(e.found!==!0)return{name:t,status:`missing`};let n={name:t,status:`ready`};return e.label&&(n.label=e.label),e.description&&(n.description=e.description),e.promptSnippet&&(n.promptSnippet=e.promptSnippet),Array.isArray(e.promptGuidelines)&&e.promptGuidelines.length>0&&(n.promptGuidelines=e.promptGuidelines),e.parameters!==void 0&&(n.parameters=e.parameters),e.parametersDropped===!0&&(n.parametersDropped=!0),(e.active===!0||e.active===!1)&&(n.active=e.active),e.source&&(n.source=e.source),e.scope&&(n.scope=e.scope),n}var Ll=null,Rl=new Set;function zl(){for(let e of Rl)e()}function Bl(e){let t=(e??``).trim();t&&(Ll={name:t,status:`loading`},zl(),Z({type:`get_tool_info`,name:t}))}function Vl(){Ll!==null&&(Ll=null,zl())}function Hl(e){Ll!==null&&Ll.name===e.name&&(Ll=Il(e),zl())}function Ul(e){return Rl.add(e),()=>{Rl.delete(e)}}function Wl(){return Ll}function Gl(){return(0,Q.useSyncExternalStore)(Ul,Wl,Wl)}var Kl=262144,ql=300,Jl=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,Yl=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,Xl=/"(?:name|skill)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,Zl=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,Ql=/"(query|q|search|pattern)"\s*:\s*"((?:[^"\\\n]|\\.){0,400})"/,$l=1e9;function eu(e){let t=e.split(`
|
|
15
|
+
`),n=t[0].replace(/\s+/g,` `).trim();if(!n)return;let r=t.length-1,i=n.length>80?`${n.slice(0,80)}…`:n;return r>0?`${i} +${r}`:i}function tu(e){let{name:t,argumentsText:n,isCollapsed:r=!1}=e,i=e.hints??nu(n);switch(t){case`bash`:{if(!r||!i.command)return null;let e=eu(i.command);return e?{text:e,title:i.command,prefix:`$ `,className:`toolcall-cmd`}:null}case`read`:case`write`:case`edit`:case`edit_soft`:case`patch`:case`ls`:return i.path?{text:su(i.path),title:i.path,className:`toolcall-path`}:null;case`skill`:return i.skillName?{text:i.skillName,title:i.skillName,className:`toolcall-skill`}:null;case`delegate_task`:return i.agent?{text:i.agent,title:i.agent,prefix:`◈ `,className:`toolcall-agent`}:null;case`codemode`:case`eval`:return i.codeLines?{text:`${i.codeLines}L`,title:`${i.codeLines} lines`,prefix:`λ `,className:`toolcall-timeout`}:null;case`tool_search`:case`grep`:return i.query?{text:i.query,title:i.query,className:`toolcall-query`}:null;case`ask_user_question`:return i.questionTitle?{text:i.questionTitle,title:i.questionTitle,className:`toolcall-query`}:null;default:return i.path?{text:su(i.path),title:i.path,className:`toolcall-path`}:i.query?{text:i.query,title:i.query,className:`toolcall-query`}:null}}function nu(e){if(!e)return{};let t=e.length>Kl?e.slice(0,Kl):e;return{path:cu(t),timeout:lu(t),command:du(e),agent:ru(t),skillName:iu(t),codeLines:mu(e),query:uu(t),questionTitle:gu(t)}}function ru(e){let t=Yl.exec(e);if(!t)return;let n=t[1].replace(/[\u0000-\u001f\u007f]/g,``).trim();if(n)return n.length>ql?`${n.slice(0,ql)}…`:n}function iu(e){let t=Xl.exec(e);if(!t)return;let n=fu(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>ql?`${n.slice(0,299)}…`:n}var au=[`task`,`expected_outcome`,`required_tools`,`must_do`,`must_not_do`,`context`];function ou(e){if(!e||e.length>Kl)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r={};for(let e of[...au,`agent`,`model`])typeof n[e]==`string`&&n[e].trim()&&(r[e]=n[e]);return r}catch{return{}}}function su(e,t=56){if(e.length<=t)return e;let n=e.split(/[\\/]+/).filter(Boolean),r=n[n.length-1];if(!r||n.length<=1)return`…${e.slice(-(t-1))}`;let i=r;for(let e=n.length-2;e>=0;e--){let r=`${n[e]}/${i}`;if(r.length+2>t)break;i=r}return`…/${i}`}function cu(e){let t=Jl.exec(e);if(!t)return;let n=fu(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>ql?`${n.slice(0,299)}…`:n}function lu(e){let t=Zl.exec(e);if(!t)return;let n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>$l)return;let r=t[1].toLowerCase();return!r.endsWith(`ms`)&&!r.endsWith(`milliseconds`)?`${n}s`:n<1e3?`${n}ms`:`${Math.round(n/100)/10}s`}function uu(e){let t=Ql.exec(e);if(!t)return;let n=fu(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>60?`${n.slice(0,57)}…`:n}function du(e){if(!(e.length>Kl))try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:typeof t.command==`string`&&t.command.trim()?t.command:void 0}catch{return}}function fu(e){try{let t=JSON.parse(`"${e}"`);return typeof t==`string`?t:e}catch{return e}}function pu(e){if(!e)return{};let t,n=e.trim();if(n.startsWith(`{`))try{let e=JSON.parse(n);typeof e?.code==`string`&&(t=e.code)}catch{let e=/"code"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(n);e&&(t=fu(e[1]))}else n&&(t=e);if(!t)return{};let r=t.indexOf(`
|
|
16
|
+
`),i=r===-1?t.trim():t.slice(0,r).trim(),a;if(i.startsWith(`// @options:`))try{a=JSON.parse(i.slice(12).trim())}catch{}return{code:t,options:a}}function mu(e){let t=pu(e);if(!t.code)return;let n=t.code.split(`
|
|
17
|
+
`).length;return n>0?n:void 0}var hu=/"(?:header|question)"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/;function gu(e){let t=hu.exec(e);if(!t)return;let n=fu(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>40?`${n.slice(0,38)}…`:n}function _u(e){if(!e||e.length>Kl)return null;try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.questions;return Array.isArray(n)&&n.length>0?{questions:n}:null}catch{return null}}var vu=new Set([`image`,`video`,`audio`,`markdown`,`html`,`pdf`,`text`,`binary`,`dir`,`missing`]);function yu(e){let t=String(e??``).trim().replace(/\\/g,`/`);return t.length>1?t.replace(/\/+$/,``):t}function bu(e){let t=yu(e).split(`/`);return(t[t.length-1]??``)||String(e??``)}function xu(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Su(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function Cu(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=xu(t);if(!n)return null;let r=Array.isArray(n.items)?n.items:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push({path:t});continue}let t=xu(e),n=t?Su(t.path):void 0;if(!n)continue;let r={path:n},a=Su(t?.caption);a&&(r.caption=a),t?.focus===!0&&(r.focus=!0),i.push(r)}if(i.length===0)return null;let a={items:i},o=Su(n.title);o&&(a.title=o);let s=Su(n.note);return s&&(a.note=s),a}function wu(e,t){let n=xu(t),r=Array.isArray(n?.items)?n.items.map(xu):[],i=new Map;for(let e of r){if(!e)continue;let t=yu(String(e.path??e.abs??``));t&&!i.has(t)&&i.set(t,e)}return e.items.map((e,t)=>{let n=i.get(yu(e.path))??r[t]??null,a=Su(n?.kind),o={path:e.path,target:Su(n?.abs)??e.path,name:bu(Su(n?.name)??e.path),kind:a&&vu.has(a)?a:`unknown`,focus:e.focus===!0};e.caption&&(o.caption=e.caption),typeof n?.size==`number`&&Number.isFinite(n.size)&&(o.size=n.size),typeof n?.mtime==`number`&&Number.isFinite(n.mtime)&&(o.mtime=n.mtime);let s=Su(n?.excerpt);return s&&(o.excerpt=s),n?.excerptTruncated===!0&&(o.excerptTruncated=!0),o})}function Tu(e,t){return Su(xu(t)?.title)??e.title}function Eu(e,t){return Su(xu(t)?.note)??e.note}function Du(e){return e===`image`||e===`video`||e===`audio`?e:null}function Ou(e){return e!==`dir`&&e!==`missing`}function ku(e){switch(e){case`image`:return`🖼`;case`video`:return`🎬`;case`audio`:return`🎵`;case`markdown`:return`📝`;case`html`:return`🌐`;case`pdf`:return`📕`;case`text`:return`📄`;case`dir`:return`📁`;case`missing`:return`⚠`;default:return`📦`}}function Au(e){if(!(e===void 0||!Number.isFinite(e)||e<0))return e<1024?`${Math.round(e)} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(1)} GB`}function ju(e){return e.find(e=>e.focus&&Ou(e.kind))}function Mu(e){return ju(e)??e.find(e=>Ou(e.kind))}function Nu(e){if(!e.enabled||e.seen||typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp))return!1;let t=e.now-e.timestamp;return t>=0&&t<=e.maxAgeMs}var Pu=209715200,Fu=/windows/i.test(navigator.userAgent),Iu=/[<>:"/\\|?*\u0000-\u001f]/g,Lu=/[. ]+$/,Ru=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function zu(e){let t=e.replace(Iu,`_`).replace(Lu,``);return t?Ru.test(t)?`_${t}`:t:`_`}function Bu(e,t=!0){let n=new URLSearchParams({clientId:xh(),path:e,...t?{download:`1`}:{}});return Qe(q(`/api/file?${n}`))}async function Vu(e,t){let n=Fu?zu(t):t;try{let t=await fetch(Bu(e));if(!t.ok)return{ok:!1,cancelled:!1,error:await t.text().catch(()=>``)||(t.status===404?`FILE_NOT_FOUND`:`HTTP ${t.status}`)};if(Number(t.headers.get(`content-length`)??`0`)>Pu)return window.location.assign(Bu(e)),{ok:!0};let r=await t.blob();return window.showSaveFilePicker&&window.isSecureContext?Uu(r,n):Wu(r,n)}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}async function Hu(e,t){let n=Fu?zu(t):t;return window.showSaveFilePicker&&window.isSecureContext?Uu(e,n):Wu(e,n)}async function Uu(e,t){let n,r=window.showSaveFilePicker;if(!r)return Wu(e,t);try{n=await r({suggestedName:t})}catch(n){return n instanceof DOMException&&n.name===`AbortError`?{ok:!1,cancelled:!0}:Wu(e,t)}try{let t=await n.createWritable();return await t.write(e),await t.close(),{ok:!0}}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}function Wu(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);return r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}var Gu=`pi-web-ui:present-auto-open`,Ku=3e4,qu=`pi-web-ui:present-auto-opened`;function Ju(){try{return localStorage.getItem(Gu)===`1`}catch{return!1}}function Yu(e){try{localStorage.setItem(Gu,e?`1`:`0`)}catch{}$u=e,Zu()}var Xu=new Set;function Zu(){for(let e of Xu)e()}function Qu(e){return Xu.add(e),()=>{Xu.delete(e)}}var $u=null;function ed(){return $u===null&&($u=Ju()),$u}function td(){return(0,Q.useSyncExternalStore)(Qu,ed)}function nd(){try{let e=sessionStorage.getItem(qu);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function rd(e){if(!e)return!1;let t=nd();if(t.includes(e))return!1;let n=[...t,e].slice(-200);try{sessionStorage.setItem(qu,JSON.stringify(n))}catch{}return!0}function id(e,t,n=Date.now()){return Nu({enabled:Ju(),seen:!1,timestamp:t,now:n,maxAgeMs:Ku})?rd(e):!1}var ad=(0,Q.memo)(function({args:e,details:t,toolCallId:n,resultTimestamp:r}){let i=V(),a=td(),o=(0,Q.useMemo)(()=>wu(e,t),[e,t]),s=Tu(e,t),c=Eu(e,t),l=(0,Q.useMemo)(()=>ju(o),[o]);return(0,Q.useEffect)(()=>{a&&l&&n&&(Kc()||id(n,r)&&qc({path:l.target,name:l.name}))},[a,l,n,r]),o.length===0?(0,$.jsx)(`div`,{className:`present-empty`,children:i(`presentEmpty`)}):(0,$.jsxs)(`div`,{className:`present-card`,children:[s&&(0,$.jsx)(`div`,{className:`present-title`,children:s}),c&&(0,$.jsx)(`div`,{className:`present-note`,children:(0,$.jsx)(sl,{text:c,rawHtml:!0})}),(0,$.jsx)(`div`,{className:`present-items`,children:o.map(e=>(0,$.jsx)(sd,{item:e},`${e.target}\u0000${e.path}`))})]})});function od(e){return typeof e.mtime==`number`?`${e.path}\n${new Date(e.mtime).toLocaleString()}`:e.path}function sd({item:e}){let t=V(),{copied:n,copy:r}=ac({duration:1200}),[i,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=i?null:Du(e.kind),u=Au(e.size),d=e.kind===`missing`,f={path:e.target,name:e.name},p=!Jc(),m=$c(e.target);return(0,$.jsxs)(`div`,{className:`present-item${d?` missing`:``}`,children:[(0,$.jsxs)(`div`,{className:`present-item-head`,children:[(0,$.jsx)(`span`,{className:`present-item-icon`,"aria-hidden":`true`,children:ku(e.kind)}),(0,$.jsx)(`span`,{className:`present-item-name`,title:od(e),children:e.name}),e.caption&&(0,$.jsx)(`span`,{className:`present-item-caption`,children:e.caption}),u&&!d&&(0,$.jsx)(`span`,{className:`present-item-meta`,children:u}),(0,$.jsx)(`span`,{className:`present-item-spacer`}),!d&&(0,$.jsxs)($.Fragment,{children:[Ou(e.kind)&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:t(`previewFile`),"aria-label":t(`previewFile`),onClick:()=>qc(f),children:(0,$.jsx)(I,{})}),p?(0,$.jsxs)(`a`,{className:`present-btn labeled`,href:m,target:`_blank`,rel:`noreferrer noopener`,title:t(`openInNewTab`),children:[(0,$.jsx)(a,{}),(0,$.jsx)(`span`,{children:t(`openInNewTab`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`present-btn labeled`,title:t(`fileOpenDefault`),onClick:()=>Z({type:`file_open_default`,path:e.target}),children:[(0,$.jsx)(a,{}),(0,$.jsx)(`span`,{children:t(`presentOpenLocal`)})]}),!p&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:t(`fileReveal`),"aria-label":t(`fileReveal`),onClick:()=>Z({type:`file_reveal`,path:e.target}),children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:t(`downloadFile`),"aria-label":t(`downloadFile`),onClick:()=>{c(``),Vu(e.target,e.name).then(e=>{e.ok||e.cancelled||c(e.error===`FILE_NOT_FOUND`?t(`fileNotFoundShort`):e.error)})},children:(0,$.jsx)(S,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn${n?` on`:``}`,title:t(`copyPath`),"aria-label":t(`copyPath`),onClick:()=>{r(e.path)},children:(0,$.jsx)(Te,{})})]})]}),d&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:t(`presentMissing`)}),s&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:t(`downloadFailed`,{error:s})}),l===`image`&&(0,$.jsx)(`button`,{type:`button`,className:`present-media`,title:t(`previewFile`),onClick:()=>qc(f),children:(0,$.jsx)(`img`,{src:Bu(e.target,!1),alt:e.name,loading:`lazy`,onError:()=>o(!0)})}),l===`video`&&(0,$.jsx)(`video`,{className:`present-media-video`,src:Bu(e.target,!1),controls:!0,preload:`metadata`,onError:()=>o(!0)}),l===`audio`&&(0,$.jsx)(`audio`,{className:`present-media-audio`,src:Bu(e.target,!1),controls:!0,preload:`metadata`,onError:()=>o(!0)}),e.excerpt&&(0,$.jsxs)(`pre`,{className:`present-excerpt`,children:[e.excerpt,e.excerptTruncated?`…`:``]})]})}function cd(e,t){let n=new Map,r=e?.answers;if(Array.isArray(r)){for(let e of r)e&&typeof e.id==`string`&&n.set(e.id,{id:e.id,selected:Array.isArray(e.selected)?e.selected:[],custom:typeof e.custom==`string`?e.custom:void 0});if(n.size>0)return n}if(t&&!t.includes(`User cancelled`)){let e=t.split(`
|
|
18
|
+
`).filter(e=>e.trim());for(let t of e){let e=t.indexOf(`:`);if(e===-1)continue;let r=t.slice(0,e).trim(),i=t.slice(e+1).trim(),a=[],o,s=/\s*\(wrote:\s*(.*?)\)$/i.exec(i),c=i;s&&(o=s[1],c=i.slice(0,s.index).trim()),c&&c!==`(no selection)`&&(a=c.split(`,`).map(e=>e.trim()).filter(Boolean)),n.set(r,{id:r,selected:a,custom:o})}}return n}function ld(e){if(!e)return;let t=/(?:User note \/ 附言|附言)[::]\s*([^\n\r]+)/.exec(e);return t?t[1].trim():void 0}var ud=(0,Q.memo)(function({questions:e,details:t,output:n,isError:r=!1,waiting:i=!1}){let a=V(),o=(0,Q.useMemo)(()=>cd(t,n),[t,n]),s=(0,Q.useMemo)(()=>r?ld(n):void 0,[r,n]);return(0,$.jsxs)(`div`,{className:`qcard-wrap`,children:[r&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-cancelled`,children:[(0,$.jsx)(`span`,{className:`qcard-status-icon`,children:(0,$.jsx)(R,{})}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:a(`questionCardCancelled`)}),s&&(0,$.jsxs)(`div`,{className:`qcard-reject-reason`,children:[(0,$.jsx)(Ce,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{children:[(0,$.jsxs)(`strong`,{children:[a(`questionCardRejectReason`),`:`]}),` `,s]})]})]}),i&&!r&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:a(`questionCardWaiting`)})]}),(0,$.jsx)(`div`,{className:`qcard-items`,children:e.map((e,t)=>{let n=o.get(e.id)??o.get(e.header??``),r=new Set(n?.selected??[]),i=n!==void 0,s=e.options??[];return(0,$.jsxs)(`div`,{className:`qcard-item`,children:[(0,$.jsxs)(`div`,{className:`qcard-header`,children:[(0,$.jsx)(`span`,{className:`qcard-idx`,children:t+1}),(0,$.jsx)(`span`,{className:`qcard-title`,children:e.header??`${a(`modelQuestion`)} ${t+1}`})]}),(0,$.jsx)(`div`,{className:`qcard-question`,children:(0,$.jsx)(sl,{text:e.question,rawHtml:!0})}),e.detail&&(0,$.jsx)(`div`,{className:`qcard-detail`,children:(0,$.jsx)(sl,{text:e.detail,rawHtml:!0})}),s.length>0&&(0,$.jsx)(`div`,{className:`qcard-options`,children:s.map((t,n)=>{let o=r.has(t.label),c=t.recommended??(n===0&&s.length>1);return(0,$.jsxs)(`div`,{className:`qcard-option${o?` selected`:``}${i&&!o?` dimmed`:``}`,children:[(0,$.jsx)(`span`,{className:`qcard-opt-mark`,children:e.multiSelect?o?(0,$.jsx)(z,{className:`qcard-check-icon`}):`☐`:o?`●`:`○`}),(0,$.jsxs)(`div`,{className:`qcard-opt-content`,children:[(0,$.jsxs)(`div`,{className:`qcard-opt-label`,children:[(0,$.jsx)(sl,{text:t.label,rawHtml:!0}),c&&(0,$.jsx)(`span`,{className:`question-recommended-badge`,children:a(`recommended`)})]}),t.description&&(0,$.jsx)(`div`,{className:`qcard-opt-desc`,children:(0,$.jsx)(sl,{text:t.description,rawHtml:!0})})]})]},t.label)})}),i&&r.size===0&&!n.custom&&(0,$.jsx)(`div`,{className:`qcard-empty-sel`,children:a(`questionCardNoSelection`)}),n?.custom&&(0,$.jsxs)(`div`,{className:`qcard-custom-note`,children:[(0,$.jsx)(Ae,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{className:`qcard-custom-label`,children:[a(`questionCardUserCustom`),`:`]}),(0,$.jsx)(`span`,{className:`qcard-custom-text`,children:n.custom})]})]},e.id)})})]})}),dd={ts:`typescript`,tsx:`tsx`,js:`javascript`,jsx:`jsx`,mjs:`javascript`,cjs:`javascript`,json:`json`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,py:`python`,rs:`rust`,go:`go`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,hpp:`cpp`,sh:`bash`,bash:`bash`,zsh:`bash`,yml:`yaml`,yaml:`yaml`,toml:`toml`,md:`markdown`,sql:`sql`,xml:`xml`,svg:`svg`};function fd(e){if(!e)return`plaintext`;let t=e.split(`.`).pop()?.toLowerCase();return t&&dd[t]||`plaintext`}var pd=/\s+|[a-zA-Z0-9_$]+|[^\s\w]/g;function md(e){return e?e.replace(/\\([nrtbfv\\/"]|u[0-9a-fA-F]{4})/g,(e,t)=>{switch(t){case`n`:return`
|
|
19
|
+
`;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`\\`:return`\\`;case`/`:return`/`;case`"`:return`"`;default:if(t.startsWith(`u`))try{return String.fromCharCode(parseInt(t.slice(1),16))}catch{return`\\${t}`}return`\\${t}`}}):``}function hd(e,t){if(!e||!t||e.length>800||t.length>800)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let n=e.match(pd)||[e],r=t.match(pd)||[t],i=n.length,a=r.length;if(i*a>4e3)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let o=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let e=1;e<=i;e++)for(let t=1;t<=a;t++)n[e-1]===r[t-1]?o[e][t]=o[e-1][t-1]+1:o[e][t]=Math.max(o[e-1][t],o[e][t-1]);let s=o[i][a],c=Math.max(i,a);if(c>0&&s/c<.25)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let l=[],u=[],d=i,f=a,p=[],m=[];for(;d>0||f>0;)d>0&&f>0&&n[d-1]===r[f-1]?(p.push({type:`same`,text:n[d-1]}),m.push({type:`same`,text:r[f-1]}),d--,f--):f>0&&(d===0||o[d][f-1]>=o[d-1][f])?(m.push({type:`add`,text:r[f-1]}),f--):d>0&&(p.push({type:`del`,text:n[d-1]}),d--);p.reverse(),m.reverse();for(let e of p){let t=l[l.length-1];t&&t.type===e.type?t.text+=e.text:l.push({...e})}for(let e of m){let t=u[u.length-1];t&&t.type===e.type?t.text+=e.text:u.push({...e})}return{oldTokens:l,newTokens:u}}var gd=/^([+\- ])(\s*\d+)?\s(.*)$/;function _d(e){let t=[],n=null,r=0,i=0,a=1,o=1,s=e.split(`
|
|
20
|
+
`),c=[],l=[],u=()=>{if(c.length===1&&l.length===1){let{oldTokens:e,newTokens:t}=hd(c[0].content,l[0].content);c[0].tokens=e,l[0].tokens=t}c=[],l=[]},d=(e=`@@ Changes @@`)=>(n||(n={header:e,lines:[]},t.push(n)),n);for(let e of s){if(e.startsWith(`---`)||e.startsWith(`+++`)||e.startsWith(`===`)||e.startsWith(`Index:`))continue;if(e.startsWith(`@@`)){u();let r=/@@\s*-(\d+)(?:,\d+)?\s*\+(\d+)(?:,\d+)?\s*@@(.*)/.exec(e);r&&(a=parseInt(r[1],10),o=parseInt(r[2],10)),n={header:e.trim(),lines:[]},t.push(n);continue}if(/^\s+\.\.\.\s*$/.test(e)){u(),n={header:`@@ ... @@`,lines:[]},t.push(n);continue}let s=gd.exec(e);if(s){let e=s[1],t=s[2]?s[2].trim():void 0,n=t?parseInt(t,10):void 0,f=s[3],p=d();if(e===`+`){r++;let e={type:`add`,newLineNum:n??o++,content:f};p.lines.push(e),l.push(e)}else if(e===`-`){i++;let e={type:`del`,oldLineNum:n??a++,content:f};p.lines.push(e),c.push(e)}else{u();let e=n??a++;n||o++;let t={type:`context`,oldLineNum:e,newLineNum:e,content:f};p.lines.push(t)}continue}if(e.length>0){let t=e[0],n=e.slice(1),s=d();if(t===`+`){r++;let e={type:`add`,newLineNum:o++,content:n};s.lines.push(e),l.push(e)}else if(t===`-`){i++;let e={type:`del`,oldLineNum:a++,content:n};s.lines.push(e),c.push(e)}else if(t===` `){u();let e={type:`context`,oldLineNum:a++,newLineNum:o++,content:n};s.lines.push(e)}}}return u(),{hunks:t,stats:{additions:r,deletions:i}}}function vd(e){let t=[],n=0,r=0;return e.forEach((e,i)=>{let a=typeof e.oldText==`string`?e.oldText:``,o=typeof e.newText==`string`?e.newText:``,s=a?a.split(`
|
|
21
21
|
`):[],c=o?o.split(`
|
|
22
|
-
`):[];r+=s.length,n+=c.length;let l=[];if(s.length===1&&c.length===1){let{oldTokens:e,newTokens:t}=
|
|
23
|
-
`).length:0;return{filePath:a,toolName:e,isWrite:!0,language:c,content:n,isStreamingPartial:o,stats:{additions:r,deletions:0,totalLines:r,isNewFile:!0},hunks:[]}}let l=n&&typeof n==`object`&&typeof n.patch==`string`?n.patch:void 0;if(l){let t=
|
|
24
|
-
`):[],[e]);return(0,$.jsx)(`div`,{className:`diff-code-table`,children:n.map((e,n)=>(0,$.jsxs)(`div`,{className:`diff-code-row`,children:[(0,$.jsx)(`span`,{className:`diff-line-num`,children:t+n}),(0,$.jsx)(`span`,{className:`diff-line-text`,children:e||` `})]},n))})}function bd({hunks:e,isStreaming:t,fallbackText:n}){let r=V();return e.length===0?t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)}):(0,$.jsx)(`div`,{className:`diff-unified-view`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-hunk-section`,children:[(0,$.jsx)(`div`,{className:`diff-hunk-header`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.lines.map((e,t)=>(0,$.jsx)(xd,{line:e},t))]},t))})}function xd({line:e}){let t=e.type===`add`?`+`:e.type===`del`?`-`:` `,n=e.type===`del`?e.oldLineNum:e.newLineNum;return(0,$.jsxs)(`div`,{className:`diff-line-row ${e.type}`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:n??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:t}),(0,$.jsx)(`span`,{className:`diff-line-content`,children:e.tokens&&e.tokens.length>0?e.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.content||` `})]})}function Sd({hunks:e,isStreaming:t,fallbackText:n}){let r=V(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null);if(e.length===0)return t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)});let s=e=>{o.current!==`right`&&(o.current=`left`,a.current&&(a.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},c=e=>{o.current!==`left`&&(o.current=`right`,i.current&&(i.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},l=(0,Q.useMemo)(()=>e.map(e=>{let t=[],n=0;for(;n<e.lines.length;){let r=e.lines[n];if(r.type===`context`)t.push({left:r,right:r}),n++;else if(r.type===`del`){let i=e.lines[n+1];i&&i.type===`add`?(t.push({left:r,right:i}),n+=2):(t.push({left:r,right:void 0}),n++)}else r.type===`add`&&t.push({left:void 0,right:r}),n++}return{header:e.header,pairs:t}}),[e]);return(0,$.jsxs)(`div`,{className:`diff-split-container`,children:[(0,$.jsxs)(`div`,{ref:i,className:`diff-split-column left`,onScroll:s,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`BEFORE (ORIGINAL)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.left?` ${e.left.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.left?.oldLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.left?.type===`del`?`-`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.left?.tokens&&e.left.tokens.length>0?e.left.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.left?.content||` `})]},t))]},t))})]}),(0,$.jsx)(`div`,{className:`diff-split-divider`}),(0,$.jsxs)(`div`,{ref:a,className:`diff-split-column right`,onScroll:c,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`AFTER (MODIFIED)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.right?` ${e.right.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.right?.newLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.right?.type===`add`?`+`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.right?.tokens&&e.right.tokens.length>0?e.right.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:void 0,children:e.text},t)):e.right?.content||` `})]},t))]},t))})]})]})}var Cd={bash:(0,$.jsx)(o,{}),delegate_task:(0,$.jsx)(fe,{}),conversation:(0,$.jsx)(Ve,{}),subagent:(0,$.jsx)(Ve,{}),read:(0,$.jsx)(x,{}),write:(0,$.jsx)(ct,{}),edit:(0,$.jsx)(M,{}),edit_soft:(0,$.jsx)(M,{}),patch:(0,$.jsx)(p,{}),grep:(0,$.jsx)(Ee,{}),find:(0,$.jsx)(D,{}),ls:(0,$.jsx)(Be,{}),codemode:(0,$.jsx)(se,{}),eval:(0,$.jsx)(c,{}),lsp:(0,$.jsx)(c,{}),tool_search:(0,$.jsx)(Ee,{}),load_tools:(0,$.jsx)(at,{}),ask_user_question:(0,$.jsx)(K,{}),[sr]:(0,$.jsx)(Ne,{}),browser_page:(0,$.jsx)(le,{}),conversation_read:(0,$.jsx)(Ae,{}),claim_files:(0,$.jsx)(Oe,{}),plan_update:(0,$.jsx)(ot,{}),skill:(0,$.jsx)(Le,{}),schedule:(0,$.jsx)(u,{}),compact_context:(0,$.jsx)(Pe,{}),mcp_manage:(0,$.jsx)(ye,{}),sandbox:(0,$.jsx)(ye,{}),worktree:(0,$.jsx)(ce,{}),sftp:(0,$.jsx)(we,{}),mail:(0,$.jsx)($e,{}),obs_recall:(0,$.jsx)(f,{})},wd=(0,$.jsx)(L,{}),Td={bash:`toolcall-icon tc-tone-exec`,sftp:`toolcall-icon tc-tone-exec`,read:`toolcall-icon tc-tone-read`,ls:`toolcall-icon tc-tone-read`,conversation_read:`toolcall-icon tc-tone-read`,obs_recall:`toolcall-icon tc-tone-read`,write:`toolcall-icon tc-tone-edit`,edit:`toolcall-icon tc-tone-edit`,edit_soft:`toolcall-icon tc-tone-edit`,patch:`toolcall-icon tc-tone-edit`,claim_files:`toolcall-icon tc-tone-edit`,grep:`toolcall-icon tc-tone-search`,find:`toolcall-icon tc-tone-search`,tool_search:`toolcall-icon tc-tone-search`,load_tools:`toolcall-icon tc-tone-search`,codemode:`toolcall-icon tc-tone-code`,eval:`toolcall-icon tc-tone-code`,lsp:`toolcall-icon tc-tone-code`,skill:`toolcall-icon tc-tone-code`,compact_context:`toolcall-icon tc-tone-code`,delegate_task:`toolcall-icon tc-tone-agent`,conversation:`toolcall-icon tc-tone-agent`,subagent:`toolcall-icon tc-tone-agent`,worktree:`toolcall-icon tc-tone-agent`,plan_update:`toolcall-icon tc-tone-agent`,schedule:`toolcall-icon tc-tone-agent`,ask_user_question:`toolcall-icon tc-tone-ui`,[sr]:`toolcall-icon tc-tone-ui`,browser_page:`toolcall-icon tc-tone-ui`,mail:`toolcall-icon tc-tone-ui`,mcp_manage:`toolcall-icon tc-tone-ui`,sandbox:`toolcall-icon tc-tone-ui`},Ed=`toolcall-icon tc-tone-default`;function Dd(e){return Cd[e]??wd}function Od(e){return Td[e]??Ed}function kd(e,t){let n=xu(e);if(!n)return!1;let r=Au(Su(n,t));return r?Gc({path:r.target,name:r.name}):!1}var Ad=(0,Q.memo)(function({block:e,view:t,uiContextToolCall:n,onUiAction:r,rootRef:i}){let a=V(),o=H(Se()),s=e.name===sr,c=!t.result&&t.streaming&&!t.status,l=t.result!==void 0,u=!t.result&&!!t.status,d=t.result?.isError??t.status?.isError??!1,f=t.status?.durationMs,p=t.result?.durationMs,m=typeof p==`number`?p:f,h=d?`err`:l?`ok`:c||u?`run`:`idle`,g=a(d?`error`:l?`done`:c?`running`:u?`toolDoneWaitingModel`:`toolQueued`),_=(u||l)&&m!==void 0?Ld(m):``;(u||l)&&_&&(g=`${g} · ${_}`);let v=u&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,y=eu(e.argumentsText),b=$l({name:e.name,argumentsText:e.argumentsText,hints:y}),S=b?`${e.name}(${b.text})`:`${e.name}()`,C=(0,Q.useMemo)(()=>{let e=t.result?.content;return Array.isArray(e)?e.some(e=>e.type===`image`):!1},[t.result?.content]),w=(0,Q.useMemo)(()=>{let e=t.result?.content;if(!Array.isArray(e))return!1;for(let t of e)if(t.type===`text`&&typeof t.text==`string`){let e=t.text;if(/(?:```|#\s+|\|\s*[-:]+\s*\|)/m.test(e.slice(0,500)))return!0}return!1},[t.result?.content]),T=(n??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`),E=t=>{T&&(t.preventDefault(),t.stopPropagation(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.id,kind:`toolcall`,label:e.name},entries:n??[],onHostAction:t=>{if(t.id===`host:tool-info`){Rl(e.name);return}r?.(t)}}))},D=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,r=n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>a(`liveOutputOmitted`,{n:t})),i=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),o=s?xu(e.argumentsText):null;Fc({isThinking:!1,name:e.name,title:S,status:g,statusClass:h,duration:_,durationMs:m,exitHint:v,hints:y,args:e.argumentsText||``,rawOutput:n,output:r,details:t.result?.details,images:i,isError:d,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,presentData:s&&o?{title:o.title,note:o.note,items:o.items}:null})},O=n=>{s&&!n?.altKey&&kd(e.argumentsText,t.result?.details)||D()};return(0,$.jsx)(`div`,{ref:i,className:`toolcall ${h}`,onClick:e=>{e.preventDefault(),e.stopPropagation(),O(e)},onContextMenu:E,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O(e))},role:`button`,tabIndex:0,title:`${e.name}(${b?b.text:``}) · ${g}`,children:(0,$.jsxs)(`div`,{className:`toolcall-head chead`,children:[(0,$.jsx)(`span`,{className:`toolcall-icon chead-icon ${Od(e.name)}`,children:Dd(e.name)}),(0,$.jsx)(`span`,{className:`toolcall-name chead-title`,children:e.name}),(0,$.jsx)(`span`,{className:`toolcall-status`,title:v?`${g} · ${v}`:g,"aria-label":v?`${g} · ${v}`:g,children:d?(0,$.jsx)(R,{}):l?(0,$.jsx)(z,{}):c||u?(0,$.jsx)(Zo,{}):(0,$.jsx)(tt,{})}),C&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:a(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ne,{})}),w&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:o?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(x,{})})]})})}),jd=(0,Q.memo)(function({block:e,view:t,onKillBash:n,wrap:r=!0,showImages:i=!0,forceOpen:a=!1,uiContextToolCall:o,uiToolCardFooter:s,onUiAction:c,rootRef:l}){let u=V(),d=H(Se()),[f,p]=(0,Q.useState)(null),m=e.name===sr,h=f??(m?!0:r),g=h||a,{copied:_,copy:v}=rc({duration:1200}),y=!t.result&&t.streaming&&!t.status,b=e.name===`bash`&&y,S=t.result!==void 0,w=!t.result&&!!t.status,T=t.result?.isError??t.status?.isError??!1,E=(0,Q.useRef)(null),D=(0,Q.useRef)(!0),O=(0,Q.useMemo)(()=>g?t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``:``,[g,t.result,t.liveOutput]),k=(0,Q.useMemo)(()=>!g||!O?``:O.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>u(`liveOutputOmitted`,{n:t})),[g,O,u]);(0,Q.useEffect)(()=>{g&&(y||w)&&D.current&&E.current&&(E.current.scrollTop=E.current.scrollHeight)},[g,k,y,w]);let A=(0,Q.useMemo)(()=>i?(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))):[],[i,t.result]),[j,M]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!j)return;let e=e=>{e.key===`Escape`&&M(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[j]);let N=e.name===`delegate_task`,P=(0,Q.useMemo)(()=>!N||!g?{}:iu(e.argumentsText),[N,g,e.argumentsText]),ee=e.name===`codemode`,F=(0,Q.useMemo)(()=>ee&&g?du(e.argumentsText):null,[ee,g,e.argumentsText]),te=e.name===`ask_user_question`,ne=(0,Q.useMemo)(()=>te&&g?hu(e.argumentsText):null,[te,g,e.argumentsText]),re=e.name===`edit`||e.name===`write`||e.name===`edit_soft`||e.name===`patch`,I=(0,Q.useMemo)(()=>re?_d(e.name,e.argumentsText,t.result?.details,k):null,[re,e.name,e.argumentsText,t.result?.details,k]),L=A.length>0,ie=(0,Q.useMemo)(()=>{let e=t.result?.content;if(!Array.isArray(e))return!1;for(let t of e)if(t.type===`text`&&typeof t.text==`string`){let e=t.text;if(/(?:```|#\s+|\|\s*[-:]+\s*\|)/m.test(e.slice(0,500)))return!0}return!1},[t.result?.content]),ae=(0,Q.useMemo)(()=>m&&g?xu(e.argumentsText):null,[m,g,e.argumentsText]),oe=N&&t.result&&typeof t.result.details==`object`&&t.result.details!==null?t.result.details.convId:void 0,se=(0,Q.useMemo)(()=>{if(!N)return;if(oe)return oe;let e=t.result?.content?.[0];if(e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`)return/sa-[0-9a-f]{8}/.exec(e.text)?.[0]},[N,oe,t.result?.content]),ce=(0,Q.useRef)(void 0),le=t.status?.durationMs,ue=t.result?.durationMs;(0,Q.useEffect)(()=>{le!==void 0&&(ce.current=le),typeof ue==`number`&&(ce.current=ue)},[le,ue]);let de=typeof ue==`number`?ue:le??ce.current,B=T?`err`:S?`ok`:y||w?`run`:`idle`,fe=u(T?`error`:S?`done`:y?`running`:w?`toolDoneWaitingModel`:`toolQueued`),pe=(w||S)&&de!==void 0?Ld(de):``;(w||S)&&pe&&(fe=`${fe} · ${pe}`);let me=w&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,ge=eu(e.argumentsText),U=e.name===`bash`?ge.command:void 0,W=$l({name:e.name,argumentsText:e.argumentsText,hints:ge,isCollapsed:!g}),G=W?`${e.name}(${W.text})`:`${e.name}()`,_e=()=>{e.argumentsText&&v(e.argumentsText)},K=(o??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`),J=t=>{if(!K)return;let n=t.target;if(n instanceof Element&&n.closest(`pre, code, a, input, textarea, [contenteditable='true']`))return;let r=window.getSelection?.();r&&!r.isCollapsed&&r.toString().trim().length>0||(t.preventDefault(),t.stopPropagation(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.id,kind:`toolcall`,label:e.name},entries:o??[],onHostAction:t=>{if(t.id===`host:tool-info`){Rl(e.name);return}c?.(t)}}))},ve=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,r=n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>u(`liveOutputOmitted`,{n:t})),i=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),a=m?xu(e.argumentsText):null;Fc({isThinking:!1,name:e.name,title:G,status:fe,statusClass:B,duration:pe,durationMs:de,exitHint:me,hints:ge,args:e.argumentsText||``,rawOutput:n,output:r,details:t.result?.details,images:i,isError:T,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,presentData:m&&a?{title:a.title,note:a.note,items:a.items}:null})},Y=n=>{m&&!n?.altKey&&kd(e.argumentsText,t.result?.details)||ve()};return(0,$.jsxs)(`div`,{ref:l,className:`toolcall ${B}${A.length>0?` has-images`:``}`,onClick:e=>{Bc(l.current)&&(e.target?.closest(`button, a, .toolcall-kill, .toolcall-open, .toolcall-image, .file-diff-action-btn, .btn-tag`)||(e.preventDefault(),e.stopPropagation(),Y(e)))},children:[(0,$.jsx)(El,{open:g,headClassName:`toolcall-head`,toggleClassName:`toolcall-toggle`,titleText:u(g?`collapseMsg`:`expandMsg`),onToggle:()=>{if(Bc(l.current)){Y();return}p(!h)},onHeadContextMenu:J,icon:Dd(e.name),iconClassName:Od(e.name),titleClassName:`toolcall-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`toolcall-status`,title:me?`${fe} · ${me}`:fe,"aria-label":me?`${fe} · ${me}`:fe,children:T?(0,$.jsx)(R,{}):S?(0,$.jsx)(z,{}):y||w?(0,$.jsx)(Zo,{}):(0,$.jsx)(tt,{})}),L&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:u(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ne,{})}),ie&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:d?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(x,{})}),pe&&(0,$.jsx)(`span`,{className:`toolcall-duration toolcall-timeout`,style:{marginLeft:-2,fontFamily:`var(--mono)`},title:me?`${fe} · ${me}`:fe,children:pe}),W&&(0,$.jsxs)(`span`,{className:W.className,title:W.title??W.text,children:[W.prefix,W.text]}),I&&(I.stats.additions>0||I.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`toolcall-diff-badge`,title:`+${I.stats.additions} -${I.stats.deletions}`,children:[I.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,I.stats.additions]}),I.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,I.stats.deletions]})]}),ge.timeout&&(0,$.jsxs)(`span`,{className:`toolcall-timeout`,children:[`⏱ `,ge.timeout]}),(0,$.jsx)(`span`,{className:`toolcall-spacer`}),b&&n&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-kill`,title:u(`stopBashTip`),onClick:e=>{e.stopPropagation(),n?.()},children:[(0,$.jsx)(C,{}),(0,$.jsx)(`span`,{children:u(`stopBash`)})]}),N&&S&&se&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-open`,title:u(`delegateOpenSubagent`),onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:se}))},children:[(0,$.jsx)(he,{}),(0,$.jsx)(`span`,{children:u(`delegateOpenSubagent`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy${_?` copied`:``}`,title:u(`copyArgs`),"aria-label":u(`copyArgs`),onClick:e=>{e.stopPropagation(),_e()},children:_?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})})]}),children:e.name}),A.length>0&&(0,$.jsx)(`div`,{className:`toolcall-images`,children:A.map((e,t)=>{let n=e.dataUrl.startsWith(`/`)?q(e.dataUrl):e.dataUrl;return(0,$.jsx)(`button`,{type:`button`,className:`toolcall-image`,title:u(`toolImageZoom`),"aria-label":u(`toolImageZoom`),onClick:e=>{e.stopPropagation(),M(n)},children:(0,$.jsx)(`img`,{src:n,loading:`lazy`,decoding:`async`,alt:`tool result image ${t+1}`})},t)})}),j&&(0,bn.createPortal)((0,$.jsxs)(`div`,{className:`img-lightbox`,role:`dialog`,"aria-label":u(`toolImageZoom`),onClick:()=>M(null),children:[(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-close`,title:u(`close`),"aria-label":u(`close`),onClick:e=>{e.stopPropagation(),M(null)},children:(0,$.jsx)(R,{})}),(0,$.jsx)(`img`,{src:j,alt:`tool result preview`})]}),document.body),g&&(0,$.jsxs)(`div`,{className:`toolcall-body`,children:[m&&ae?(0,$.jsx)(rd,{args:ae,details:t.result?.details,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp}):N?(0,$.jsx)(Fd,{args:P}):ee&&F?.code?(0,$.jsx)(Id,{code:F.code,options:F.options,details:t.result?.details,output:k}):te&&ne?(0,$.jsx)(cd,{questions:ne.questions,details:t.result?.details,output:k,isError:T,waiting:y||w}):re?(0,$.jsx)(vd,{toolName:e.name,argumentsText:e.argumentsText,details:t.result?.details,output:k,isError:T,onOpenInspector:ve}):e.argumentsText&&(0,$.jsx)(`div`,{className:`toolcall-args`,children:U?(0,$.jsx)(Nd,{command:U}):(0,$.jsx)(`pre`,{children:e.argumentsText})}),e.name===`tool_search`&&(0,$.jsx)(Pd,{details:t.result?.details}),k.length>0&&!(te&&ne)&&(0,$.jsxs)(`div`,{className:`toolcall-output`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[u(T?`errorOutput`:`output`),(y||w)&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{ref:E,onWheel:e=>{if(e.deltaY<0)D.current=!1;else if(e.deltaY>0&&E.current){let e=E.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(D.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(D.current=!0)},children:k})]}),y&&k.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,u(`waitingOutput`)]}),w&&k.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,u(`waitingModel`)]}),s&&s.length>0&&(0,$.jsx)(`div`,{className:`toolcall-footer`,children:s.filter(e=>e&&e.hidden!==!0).map((e,t)=>{let n=e.label||e.id;return e.kind===`badge`?(0,$.jsx)(`span`,{className:`toolcall-footer-badge`,title:n,children:e.badge??n},`${e.id}#${t}`):(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-footer-item`,title:n,onClick:()=>c?.(e),children:[e.icon&&dp(e.icon),(0,$.jsx)(`span`,{children:n})]},`${e.id}#${t}`)})})]})]})}),Md=(0,Q.memo)(function(e){let t=(0,Q.useRef)(null);return Bc(t.current)?(0,$.jsx)(Ad,{block:e.block,view:e.view,uiContextToolCall:e.uiContextToolCall,onUiAction:e.onUiAction,rootRef:t}):(0,$.jsx)(jd,{...e,rootRef:t})});function Nd({command:e}){return(0,$.jsxs)(`div`,{className:`termline`,children:[(0,$.jsx)(o,{className:`termline-icon`}),(0,$.jsx)(`code`,{children:ys(e)})]})}function Pd({details:e}){let t=V(),n=Array.isArray(e?.loaded)?e.loaded:[];return n.length===0?null:(0,$.jsxs)(`div`,{className:`tool-search-loaded-box`,children:[(0,$.jsxs)(`span`,{className:`tool-search-loaded-label`,children:[t(`toolSearchLoaded`),`:`]}),(0,$.jsx)(`div`,{className:`tool-search-tags`,children:n.map(e=>(0,$.jsx)(`span`,{className:`tool-search-tag`,children:e},e))})]})}function Fd({args:e}){let t=V(),n=[{field:`task`,label:t(`delegateSecTask`)},{field:`expected_outcome`,label:t(`delegateSecExpected`)},{field:`required_tools`,label:t(`delegateSecTools`)},{field:`must_do`,label:t(`delegateSecMustDo`)},{field:`must_not_do`,label:t(`delegateSecMustNotDo`)},{field:`context`,label:t(`delegateSecContext`)}].filter(({field:t})=>e[t]?.trim());return n.length===0?null:(0,$.jsx)(`div`,{className:`delegate-brief`,children:n.map(({field:t,label:n})=>(0,$.jsxs)(`div`,{className:`delegate-sec`,children:[(0,$.jsx)(`div`,{className:`delegate-sec-label`,children:n}),(0,$.jsx)(`div`,{className:`delegate-sec-text`,children:e[t]})]},t))})}function Id({code:e,options:t,details:n,output:r}){let i=V(),a=n,o=Array.isArray(a?.calls)?a.calls:[],s=typeof a?.fullOutputPath==`string`?a.fullOutputPath:void 0,c=(0,Q.useMemo)(()=>{if(!r)return[];let e=/\[Image saved to (.*?) \((.*?)\)\]/g,t=[],n;for(;(n=e.exec(r))!==null;)t.push({path:n[1],info:n[2]});return t},[r]);return(0,$.jsxs)(`div`,{className:`codemode-card`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeScript`)}),t&&Object.keys(t).length>0&&(0,$.jsx)(`span`,{className:`codemode-options-badge`,children:JSON.stringify(t)})]}),(0,$.jsx)(`pre`,{className:`codemode-code`,children:(0,$.jsx)(`code`,{children:e})})]}),o.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-calls-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeNestedCalls`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:o.length})]}),(0,$.jsx)(`div`,{className:`codemode-calls-list`,children:o.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-call-item status-${e.status}`,children:[(0,$.jsx)(`span`,{className:`codemode-call-status`,children:e.status===`ok`?`✓`:e.status===`error`?`✗`:e.status===`running`?`…`:`⊘`}),(0,$.jsx)(`span`,{className:`codemode-call-name`,children:e.name}),e.args&&(0,$.jsx)(`span`,{className:`codemode-call-args`,children:e.args}),typeof e.durationMs==`number`&&(0,$.jsx)(`span`,{className:`codemode-call-duration`,children:Ld(e.durationMs)}),e.error&&(0,$.jsx)(`div`,{className:`codemode-call-error`,children:e.error})]},e.id||t))})]}),c.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-images-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeSavedImages`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:c.length})]}),(0,$.jsx)(`div`,{className:`codemode-images-list`,children:c.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-image-item`,children:[(0,$.jsx)(Ne,{className:`codemode-image-icon`}),(0,$.jsx)(`code`,{className:`codemode-image-path`,title:e.path,children:e.path}),(0,$.jsx)(`span`,{className:`codemode-image-info`,children:e.info}),(0,$.jsx)(`button`,{type:`button`,className:`btn-ghost codemode-image-copy`,title:i(`copy`),onClick:t=>{t.stopPropagation(),navigator.clipboard.writeText(e.path)},children:(0,$.jsx)(Te,{})})]},t))})]}),s&&(0,$.jsxs)(`div`,{className:`codemode-full-output`,children:[(0,$.jsxs)(`span`,{className:`codemode-sec-title`,children:[i(`codemodeFullOutput`),`:`]}),(0,$.jsx)(`code`,{children:s})]})]})}function Ld(e){if(e===void 0||e<0||!Number.isFinite(e))return``;if(e<1e3)return`${Math.round(e)}ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${String(r).padStart(2,`0`)}s`}var Rd=Object.freeze({status:`idle`,messages:[]}),zd=new Map,Bd=new Set,Vd=16;function Hd(){for(;zd.size>Vd;){let e=zd.keys().next().value;if(e===void 0)break;zd.delete(e)}}function Ud(){for(let e of Bd)e()}function Wd(e,t){let n=(e??``).trim();if(!n)return;let r=zd.get(n);(!r||r.status!==`loading`&&r.status!==`ready`)&&(zd.set(n,{status:`loading`,messages:r?.messages??[]}),Hd(),Ud(),Z({type:`get_compacted_messages`,compactionMessageId:n,conversationId:t}))}function Gd(e){let t=e.compactionMessageId;t&&(e.error?zd.set(t,{status:`error`,messages:[],error:e.error}):zd.set(t,{status:`ready`,messages:e.messages??[]}),Hd(),Ud())}function Kd(e){let t=zd.get(e);return t?(zd.delete(e),zd.set(e,t),t):Rd}function qd(e){return Bd.add(e),()=>{Bd.delete(e)}}function Jd(e){return(0,Q.useSyncExternalStore)(qd,()=>Kd(e),()=>Rd)}var Yd=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Xd(e){let t=e.match(Yd);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}var Zd=1568,Qd=2097152;function $d(e){return e.startsWith(`image/`)&&e!==`image/svg+xml`&&e!==`image/svg`}async function ef(e){if(!e.type.startsWith(`image/`))return null;let t;try{t=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{return null}try{let n=Math.min(1,Zd/Math.max(t.width,t.height)),r=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),a=e.type===`image/jpeg`||e.type===`image/jpg`?[[`image/jpeg`,.85],[`image/jpeg`,.6],[`image/webp`,.8]]:[[`image/png`,1],[`image/jpeg`,.85],[`image/jpeg`,.6]],o=null;for(let[n,s]of a){let a=document.createElement(`canvas`);a.width=r,a.height=i;let c=a.getContext(`2d`);if(!c)continue;n!==`image/png`&&(c.fillStyle=`#ffffff`,c.fillRect(0,0,r,i)),c.drawImage(t,0,0,r,i);let l=a.toDataURL(n,s),u=l.match(/^data:([^;]+);base64,/),d=u?u[1]:n,f=l.replace(/^data:[^;]*;base64,/,``),p=Math.floor(f.length*3/4);if(o={data:f,mimeType:d,name:e.name,size:p},p<=Qd)return o}return o}finally{t.close()}}function tf(e){let t=[];for(let n of e)n?.type===`text`&&typeof n.text==`string`&&n.text.length>0&&t.push(n.text);return t}function nf(e){return tf(e).join(`
|
|
22
|
+
`):[];r+=s.length,n+=c.length;let l=[];if(s.length===1&&c.length===1){let{oldTokens:e,newTokens:t}=hd(s[0],c[0]);l.push({type:`del`,content:s[0],tokens:e}),l.push({type:`add`,content:c[0],tokens:t})}else{for(let e of s)l.push({type:`del`,content:e});for(let e of c)l.push({type:`add`,content:e})}t.push({header:`@@ Hunk #${i+1} (${s.length} lines -> ${c.length} lines) @@`,lines:l})}),{hunks:t,stats:{additions:n,deletions:r}}}function yd(e,t,n,r){let i=e===`write`;if(!i&&e!==`edit`&&e!==`edit_soft`&&e!==`patch`)return null;let a=``,o=!1,s=null;if(t)try{s=JSON.parse(t),typeof s.path==`string`?a=s.path:typeof s.file_path==`string`&&(a=s.file_path)}catch{o=!0;let e=/"(?:path|file_path|filePath)"\s*:\s*"((?:[^"\\\n]|\\.){0,2000})"/.exec(t);if(e)try{a=JSON.parse(`"${e[1]}"`)}catch{a=e[1]}}if(!a&&r){let e=/(?:Successfully (?:wrote to|replaced \d+ block\(s\) in)|written to|Created)\s+([^\s\n\r"']+)/i.exec(r);e&&(a=e[1].trim())}let c=fd(a);if(i){let n=``;if(s&&typeof s.content==`string`)n=s.content;else if(t){let e=/"content"\s*:\s*"/i.exec(t);if(e){let r=e.index+e[0].length,i=t.slice(r),a=/",\s*"(?:path|file_path|filePath)"/i.exec(i);i=a?i.slice(0,a.index):i.replace(/\s*(?:\.\.\.\s*\[truncated\])?\s*"?\s*}?\s*$/,``),n=md(i)}else n=md(t)}let r=n?n.split(`
|
|
23
|
+
`).length:0;return{filePath:a,toolName:e,isWrite:!0,language:c,content:n,isStreamingPartial:o,stats:{additions:r,deletions:0,totalLines:r,isNewFile:!0},hunks:[]}}let l=n&&typeof n==`object`&&typeof n.patch==`string`?n.patch:void 0;if(l){let t=_d(l);if(t.hunks.length>0&&t.hunks.some(e=>e.lines.length>0))return{filePath:a,toolName:e,isWrite:!1,language:c,stats:t.stats,hunks:t.hunks,isStreamingPartial:!1}}let u=n&&typeof n==`object`&&typeof n.diff==`string`?n.diff:void 0;if(u){let t=_d(u);if(t.hunks.length>0&&t.hunks.some(e=>e.lines.length>0))return{filePath:a,toolName:e,isWrite:!1,language:c,stats:t.stats,hunks:t.hunks,isStreamingPartial:!1}}let d=[];if(s&&Array.isArray(s.edits)&&(d=s.edits),d.length>0){let{hunks:t,stats:n}=vd(d);return{filePath:a,toolName:e,isWrite:!1,language:c,stats:n,hunks:t,isStreamingPartial:o}}return{filePath:a,toolName:e,isWrite:!1,language:c,stats:{additions:0,deletions:0},hunks:[],isStreamingPartial:!0}}var bd=(0,Q.memo)(function({toolName:e,argumentsText:t,details:n,output:r,isError:i,onOpenInspector:o}){let s=V(),[c,l]=(0,Q.useState)(`unified`),[u,d]=(0,Q.useState)(!1),{copied:f,copy:p}=ac({duration:1200}),m=(0,Q.useMemo)(()=>yd(e,t,n,r),[e,t,n,r]),h=(0,Q.useMemo)(()=>{if(!n||typeof n!=`object`)return``;try{return JSON.stringify(n,null,2)}catch{return``}},[n]);(0,Q.useEffect)(()=>{if(!u)return;let e=e=>{e.key===`Escape`&&(e.stopPropagation(),d(!1))};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},[u]);let g=e=>{e.stopPropagation(),m?.isWrite&&m.content?p(m.content):t&&p(t)},_=e=>{if(e.stopPropagation(),!m?.filePath)return;let t=m.filePath.split(`/`).pop()||m.filePath;qc({path:m.filePath,name:t})},v=e=>{e.stopPropagation(),d(e=>!e),o?.()};if(!m||c===`raw`)return(0,$.jsxs)(`div`,{className:`file-diff-raw-wrap`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsx)(`span`,{className:`file-diff-path`,children:m?.filePath||e}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`unified`)},children:s(`diffViewUnified`)}),!m?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`split`)},children:s(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:s(`diffViewRaw`)}),o&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:s(`diffFullscreen`),"aria-label":s(`diffFullscreen`),onClick:v,children:(0,$.jsx)(J,{})})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,s(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:t||`(无入参参数 / No arguments)`})]}),h&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,s(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[Object.keys(n).length,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:h})]})]})]});let y=()=>m.isWrite?(0,$.jsx)(xd,{content:m.content||``}):c===`split`?(0,$.jsx)(wd,{hunks:m.hunks,isStreaming:m.isStreamingPartial,fallbackText:t}):(0,$.jsx)(Sd,{hunks:m.hunks,isStreaming:m.isStreamingPartial,fallbackText:t});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`file-diff-card${i?` is-err`:``}`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(x,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:m.filePath,children:m.filePath||e}),m.language&&m.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:m.language}),m.isStreamingPartial&&(0,$.jsx)(`span`,{className:`file-diff-streaming-badge`,children:s(`diffStreaming`)}),m.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:s(`diffNewFile`)}):(m.stats.additions>0||m.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[m.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,m.stats.additions]}),m.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,m.stats.deletions]})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`unified`)},children:s(`diffViewUnified`)}),!m.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`split`)},children:s(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:s(`diffViewRaw`)})]}),m.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:s(`diffOpenFile`),"aria-label":s(`diffOpenFile`),onClick:_,children:(0,$.jsx)(a,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:s(`diffFullscreen`),"aria-label":s(`diffFullscreen`),onClick:v,children:(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${f?` copied`:``}`,title:m.isWrite?s(`diffCopyContent`):s(`diffCopyPatch`),"aria-label":m.isWrite?s(`diffCopyContent`):s(`diffCopyPatch`),onClick:g,children:f?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-body`,children:y()})]}),u&&(0,bn.createPortal)((0,$.jsx)(`div`,{className:`file-diff-fullscreen-backdrop`,role:`dialog`,"aria-modal":`true`,onClick:e=>{e.target===e.currentTarget&&d(!1)},children:(0,$.jsxs)(`div`,{className:`file-diff-fullscreen-dialog`,children:[(0,$.jsxs)(`div`,{className:`file-diff-fullscreen-header`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(x,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:m.filePath,children:m.filePath||e}),m.language&&m.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:m.language}),m.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:s(`diffNewFile`)}):(m.stats.additions>0||m.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[m.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,m.stats.additions]}),m.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,m.stats.deletions]})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`unified`)},children:s(`diffViewUnified`)}),!m.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`split`)},children:s(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${c===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:s(`diffViewRaw`)})]}),m.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:s(`diffOpenFile`),"aria-label":s(`diffOpenFile`),onClick:_,children:(0,$.jsx)(a,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${f?` copied`:``}`,title:m.isWrite?s(`diffCopyContent`):s(`diffCopyPatch`),"aria-label":m.isWrite?s(`diffCopyContent`):s(`diffCopyPatch`),onClick:g,children:f?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${s(`diffRestoreScreen`)} (ESC)`,"aria-label":s(`diffRestoreScreen`),onClick:e=>{e.stopPropagation(),d(!1)},children:(0,$.jsx)(de,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${s(`close`)} (ESC)`,"aria-label":s(`close`),onClick:e=>{e.stopPropagation(),d(!1)},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-fullscreen-body`,children:y()})]})}),document.body)]})});function xd({content:e,startLine:t=1}){let n=(0,Q.useMemo)(()=>e?e.split(`
|
|
24
|
+
`):[],[e]);return(0,$.jsx)(`div`,{className:`diff-code-table`,children:n.map((e,n)=>(0,$.jsxs)(`div`,{className:`diff-code-row`,children:[(0,$.jsx)(`span`,{className:`diff-line-num`,children:t+n}),(0,$.jsx)(`span`,{className:`diff-line-text`,children:e||` `})]},n))})}function Sd({hunks:e,isStreaming:t,fallbackText:n}){let r=V();return e.length===0?t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)}):(0,$.jsx)(`div`,{className:`diff-unified-view`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-hunk-section`,children:[(0,$.jsx)(`div`,{className:`diff-hunk-header`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.lines.map((e,t)=>(0,$.jsx)(Cd,{line:e},t))]},t))})}function Cd({line:e}){let t=e.type===`add`?`+`:e.type===`del`?`-`:` `,n=e.type===`del`?e.oldLineNum:e.newLineNum;return(0,$.jsxs)(`div`,{className:`diff-line-row ${e.type}`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:n??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:t}),(0,$.jsx)(`span`,{className:`diff-line-content`,children:e.tokens&&e.tokens.length>0?e.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.content||` `})]})}function wd({hunks:e,isStreaming:t,fallbackText:n}){let r=V(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null);if(e.length===0)return t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)});let s=e=>{o.current!==`right`&&(o.current=`left`,a.current&&(a.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},c=e=>{o.current!==`left`&&(o.current=`right`,i.current&&(i.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},l=(0,Q.useMemo)(()=>e.map(e=>{let t=[],n=0;for(;n<e.lines.length;){let r=e.lines[n];if(r.type===`context`)t.push({left:r,right:r}),n++;else if(r.type===`del`){let i=e.lines[n+1];i&&i.type===`add`?(t.push({left:r,right:i}),n+=2):(t.push({left:r,right:void 0}),n++)}else r.type===`add`&&t.push({left:void 0,right:r}),n++}return{header:e.header,pairs:t}}),[e]);return(0,$.jsxs)(`div`,{className:`diff-split-container`,children:[(0,$.jsxs)(`div`,{ref:i,className:`diff-split-column left`,onScroll:s,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`BEFORE (ORIGINAL)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.left?` ${e.left.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.left?.oldLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.left?.type===`del`?`-`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.left?.tokens&&e.left.tokens.length>0?e.left.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.left?.content||` `})]},t))]},t))})]}),(0,$.jsx)(`div`,{className:`diff-split-divider`}),(0,$.jsxs)(`div`,{ref:a,className:`diff-split-column right`,onScroll:c,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`AFTER (MODIFIED)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.right?` ${e.right.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.right?.newLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.right?.type===`add`?`+`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.right?.tokens&&e.right.tokens.length>0?e.right.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:void 0,children:e.text},t)):e.right?.content||` `})]},t))]},t))})]})]})}var Td={bash:(0,$.jsx)(o,{}),delegate_task:(0,$.jsx)(fe,{}),conversation:(0,$.jsx)(Ve,{}),subagent:(0,$.jsx)(Ve,{}),read:(0,$.jsx)(x,{}),write:(0,$.jsx)(ct,{}),edit:(0,$.jsx)(M,{}),edit_soft:(0,$.jsx)(M,{}),patch:(0,$.jsx)(p,{}),grep:(0,$.jsx)(Ee,{}),find:(0,$.jsx)(D,{}),ls:(0,$.jsx)(Be,{}),codemode:(0,$.jsx)(se,{}),eval:(0,$.jsx)(c,{}),lsp:(0,$.jsx)(c,{}),tool_search:(0,$.jsx)(Ee,{}),load_tools:(0,$.jsx)(at,{}),ask_user_question:(0,$.jsx)(K,{}),[sr]:(0,$.jsx)(Ne,{}),browser_page:(0,$.jsx)(le,{}),conversation_read:(0,$.jsx)(Ae,{}),claim_files:(0,$.jsx)(Oe,{}),plan_update:(0,$.jsx)(ot,{}),skill:(0,$.jsx)(Le,{}),schedule:(0,$.jsx)(u,{}),compact_context:(0,$.jsx)(Pe,{}),mcp_manage:(0,$.jsx)(ye,{}),sandbox:(0,$.jsx)(ye,{}),worktree:(0,$.jsx)(ce,{}),sftp:(0,$.jsx)(we,{}),mail:(0,$.jsx)($e,{}),obs_recall:(0,$.jsx)(f,{})},Ed=(0,$.jsx)(L,{}),Dd={bash:`toolcall-icon tc-tone-exec`,sftp:`toolcall-icon tc-tone-exec`,read:`toolcall-icon tc-tone-read`,ls:`toolcall-icon tc-tone-read`,conversation_read:`toolcall-icon tc-tone-read`,obs_recall:`toolcall-icon tc-tone-read`,write:`toolcall-icon tc-tone-edit`,edit:`toolcall-icon tc-tone-edit`,edit_soft:`toolcall-icon tc-tone-edit`,patch:`toolcall-icon tc-tone-edit`,claim_files:`toolcall-icon tc-tone-edit`,grep:`toolcall-icon tc-tone-search`,find:`toolcall-icon tc-tone-search`,tool_search:`toolcall-icon tc-tone-search`,load_tools:`toolcall-icon tc-tone-search`,codemode:`toolcall-icon tc-tone-code`,eval:`toolcall-icon tc-tone-code`,lsp:`toolcall-icon tc-tone-code`,skill:`toolcall-icon tc-tone-code`,compact_context:`toolcall-icon tc-tone-code`,delegate_task:`toolcall-icon tc-tone-agent`,conversation:`toolcall-icon tc-tone-agent`,subagent:`toolcall-icon tc-tone-agent`,worktree:`toolcall-icon tc-tone-agent`,plan_update:`toolcall-icon tc-tone-agent`,schedule:`toolcall-icon tc-tone-agent`,ask_user_question:`toolcall-icon tc-tone-ui`,[sr]:`toolcall-icon tc-tone-ui`,browser_page:`toolcall-icon tc-tone-ui`,mail:`toolcall-icon tc-tone-ui`,mcp_manage:`toolcall-icon tc-tone-ui`,sandbox:`toolcall-icon tc-tone-ui`},Od=`toolcall-icon tc-tone-default`;function kd(e){return Td[e]??Ed}function Ad(e){return Dd[e]??Od}function jd(e,t){let n=Cu(e);if(!n)return!1;let r=Mu(wu(n,t));return r?qc({path:r.target,name:r.name}):!1}var Md=(0,Q.memo)(function({block:e,view:t,uiContextToolCall:n,onUiAction:r,rootRef:i}){let a=V(),o=H(Se()),s=e.name===sr,c=!t.result&&t.streaming&&!t.status,l=t.result!==void 0,u=!t.result&&!!t.status,d=t.result?.isError??t.status?.isError??!1,f=t.status?.durationMs,p=t.result?.durationMs,m=typeof p==`number`?p:f,h=d?`err`:l?`ok`:c||u?`run`:`idle`,g=a(d?`error`:l?`done`:c?`running`:u?`toolDoneWaitingModel`:`toolQueued`),_=(u||l)&&m!==void 0?zd(m):``;(u||l)&&_&&(g=`${g} · ${_}`);let v=u&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,y=nu(e.argumentsText),b=tu({name:e.name,argumentsText:e.argumentsText,hints:y}),S=b?`${e.name}(${b.text})`:`${e.name}()`,C=(0,Q.useMemo)(()=>{let e=t.result?.content;return Array.isArray(e)?e.some(e=>e.type===`image`):!1},[t.result?.content]),w=(0,Q.useMemo)(()=>{let e=t.result?.content;if(!Array.isArray(e))return!1;for(let t of e)if(t.type===`text`&&typeof t.text==`string`){let e=t.text;if(/(?:```|#\s+|\|\s*[-:]+\s*\|)/m.test(e.slice(0,500)))return!0}return!1},[t.result?.content]),T=(n??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`),E=t=>{T&&(t.preventDefault(),t.stopPropagation(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.id,kind:`toolcall`,label:e.name},entries:n??[],onHostAction:t=>{if(t.id===`host:tool-info`){Bl(e.name);return}r?.(t)}}))},D=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,r=n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>a(`liveOutputOmitted`,{n:t})),i=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),o=s?Cu(e.argumentsText):null;Lc({isThinking:!1,name:e.name,title:S,status:g,statusClass:h,duration:_,durationMs:m,exitHint:v,hints:y,args:e.argumentsText||``,rawOutput:n,output:r,details:t.result?.details,images:i,isError:d,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,presentData:s&&o?{title:o.title,note:o.note,items:o.items}:null})},O=n=>{s&&!n?.altKey&&jd(e.argumentsText,t.result?.details)||D()};return(0,$.jsx)(`div`,{ref:i,className:`toolcall ${h}`,onClick:e=>{e.preventDefault(),e.stopPropagation(),O(e)},onContextMenu:E,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O(e))},role:`button`,tabIndex:0,title:`${e.name}(${b?b.text:``}) · ${g}`,children:(0,$.jsxs)(`div`,{className:`toolcall-head chead`,children:[(0,$.jsx)(`span`,{className:`toolcall-icon chead-icon ${Ad(e.name)}`,children:kd(e.name)}),(0,$.jsx)(`span`,{className:`toolcall-name chead-title`,children:e.name}),(0,$.jsx)(`span`,{className:`toolcall-status`,title:v?`${g} · ${v}`:g,"aria-label":v?`${g} · ${v}`:g,children:d?(0,$.jsx)(R,{}):l?(0,$.jsx)(z,{}):c||u?(0,$.jsx)($o,{}):(0,$.jsx)(tt,{})}),C&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:a(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ne,{})}),w&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:o?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(x,{})})]})})}),Nd=(0,Q.memo)(function({block:e,view:t,onKillBash:n,wrap:r=!0,showImages:i=!0,forceOpen:a=!1,uiContextToolCall:o,uiToolCardFooter:s,onUiAction:c,rootRef:l}){let u=V(),d=H(Se()),[f,p]=(0,Q.useState)(null),m=e.name===sr,h=f??(m?!0:r),g=h||a,{copied:_,copy:v}=ac({duration:1200}),y=!t.result&&t.streaming&&!t.status,b=e.name===`bash`&&y,S=t.result!==void 0,w=!t.result&&!!t.status,T=t.result?.isError??t.status?.isError??!1,E=(0,Q.useRef)(null),D=(0,Q.useRef)(!0),O=(0,Q.useMemo)(()=>g?t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``:``,[g,t.result,t.liveOutput]),k=(0,Q.useMemo)(()=>!g||!O?``:O.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>u(`liveOutputOmitted`,{n:t})),[g,O,u]);(0,Q.useEffect)(()=>{g&&(y||w)&&D.current&&E.current&&(E.current.scrollTop=E.current.scrollHeight)},[g,k,y,w]);let A=(0,Q.useMemo)(()=>i?(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))):[],[i,t.result]),[j,M]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!j)return;let e=e=>{e.key===`Escape`&&M(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[j]);let N=e.name===`delegate_task`,P=(0,Q.useMemo)(()=>!N||!g?{}:ou(e.argumentsText),[N,g,e.argumentsText]),ee=e.name===`codemode`,F=(0,Q.useMemo)(()=>ee&&g?pu(e.argumentsText):null,[ee,g,e.argumentsText]),te=e.name===`ask_user_question`,ne=(0,Q.useMemo)(()=>te&&g?_u(e.argumentsText):null,[te,g,e.argumentsText]),re=e.name===`edit`||e.name===`write`||e.name===`edit_soft`||e.name===`patch`,I=(0,Q.useMemo)(()=>re?yd(e.name,e.argumentsText,t.result?.details,k):null,[re,e.name,e.argumentsText,t.result?.details,k]),L=A.length>0,ie=(0,Q.useMemo)(()=>{let e=t.result?.content;if(!Array.isArray(e))return!1;for(let t of e)if(t.type===`text`&&typeof t.text==`string`){let e=t.text;if(/(?:```|#\s+|\|\s*[-:]+\s*\|)/m.test(e.slice(0,500)))return!0}return!1},[t.result?.content]),ae=(0,Q.useMemo)(()=>m&&g?Cu(e.argumentsText):null,[m,g,e.argumentsText]),oe=N&&t.result&&typeof t.result.details==`object`&&t.result.details!==null?t.result.details.convId:void 0,se=(0,Q.useMemo)(()=>{if(!N)return;if(oe)return oe;let e=t.result?.content?.[0];if(e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`)return/sa-[0-9a-f]{8}/.exec(e.text)?.[0]},[N,oe,t.result?.content]),ce=(0,Q.useRef)(void 0),le=t.status?.durationMs,ue=t.result?.durationMs;(0,Q.useEffect)(()=>{le!==void 0&&(ce.current=le),typeof ue==`number`&&(ce.current=ue)},[le,ue]);let de=typeof ue==`number`?ue:le??ce.current,B=T?`err`:S?`ok`:y||w?`run`:`idle`,fe=u(T?`error`:S?`done`:y?`running`:w?`toolDoneWaitingModel`:`toolQueued`),pe=(w||S)&&de!==void 0?zd(de):``;(w||S)&&pe&&(fe=`${fe} · ${pe}`);let me=w&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,ge=nu(e.argumentsText),U=e.name===`bash`?ge.command:void 0,W=tu({name:e.name,argumentsText:e.argumentsText,hints:ge,isCollapsed:!g}),G=W?`${e.name}(${W.text})`:`${e.name}()`,_e=()=>{e.argumentsText&&v(e.argumentsText)},K=(o??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`),J=t=>{if(!K)return;let n=t.target;if(n instanceof Element&&n.closest(`pre, code, a, input, textarea, [contenteditable='true']`))return;let r=window.getSelection?.();r&&!r.isCollapsed&&r.toString().trim().length>0||(t.preventDefault(),t.stopPropagation(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.id,kind:`toolcall`,label:e.name},entries:o??[],onHostAction:t=>{if(t.id===`host:tool-info`){Bl(e.name);return}c?.(t)}}))},ve=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,r=n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>u(`liveOutputOmitted`,{n:t})),i=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),a=m?Cu(e.argumentsText):null;Lc({isThinking:!1,name:e.name,title:G,status:fe,statusClass:B,duration:pe,durationMs:de,exitHint:me,hints:ge,args:e.argumentsText||``,rawOutput:n,output:r,details:t.result?.details,images:i,isError:T,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,presentData:m&&a?{title:a.title,note:a.note,items:a.items}:null})},Y=n=>{m&&!n?.altKey&&jd(e.argumentsText,t.result?.details)||ve()};return(0,$.jsxs)(`div`,{ref:l,className:`toolcall ${B}${A.length>0?` has-images`:``}`,onClick:e=>{Hc(l.current)&&(e.target?.closest(`button, a, .toolcall-kill, .toolcall-open, .toolcall-image, .file-diff-action-btn, .btn-tag`)||(e.preventDefault(),e.stopPropagation(),Y(e)))},children:[(0,$.jsx)(Ol,{open:g,headClassName:`toolcall-head`,toggleClassName:`toolcall-toggle`,titleText:u(g?`collapseMsg`:`expandMsg`),onToggle:()=>{if(Hc(l.current)){Y();return}p(!h)},onHeadContextMenu:J,icon:kd(e.name),iconClassName:Ad(e.name),titleClassName:`toolcall-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`toolcall-status`,title:me?`${fe} · ${me}`:fe,"aria-label":me?`${fe} · ${me}`:fe,children:T?(0,$.jsx)(R,{}):S?(0,$.jsx)(z,{}):y||w?(0,$.jsx)($o,{}):(0,$.jsx)(tt,{})}),L&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:u(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ne,{})}),ie&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:d?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(x,{})}),pe&&(0,$.jsx)(`span`,{className:`toolcall-duration toolcall-timeout`,style:{marginLeft:-2,fontFamily:`var(--mono)`},title:me?`${fe} · ${me}`:fe,children:pe}),W&&(0,$.jsxs)(`span`,{className:W.className,title:W.title??W.text,children:[W.prefix,W.text]}),I&&(I.stats.additions>0||I.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`toolcall-diff-badge`,title:`+${I.stats.additions} -${I.stats.deletions}`,children:[I.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,I.stats.additions]}),I.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,I.stats.deletions]})]}),ge.timeout&&(0,$.jsxs)(`span`,{className:`toolcall-timeout`,children:[`⏱ `,ge.timeout]}),(0,$.jsx)(`span`,{className:`toolcall-spacer`}),b&&n&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-kill`,title:u(`stopBashTip`),onClick:e=>{e.stopPropagation(),n?.()},children:[(0,$.jsx)(C,{}),(0,$.jsx)(`span`,{children:u(`stopBash`)})]}),N&&S&&se&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-open`,title:u(`delegateOpenSubagent`),onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:se}))},children:[(0,$.jsx)(he,{}),(0,$.jsx)(`span`,{children:u(`delegateOpenSubagent`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy${_?` copied`:``}`,title:u(`copyArgs`),"aria-label":u(`copyArgs`),onClick:e=>{e.stopPropagation(),_e()},children:_?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})})]}),children:e.name}),A.length>0&&(0,$.jsx)(`div`,{className:`toolcall-images`,children:A.map((e,t)=>{let n=e.dataUrl.startsWith(`/`)?q(e.dataUrl):e.dataUrl;return(0,$.jsx)(`button`,{type:`button`,className:`toolcall-image`,title:u(`toolImageZoom`),"aria-label":u(`toolImageZoom`),onClick:e=>{e.stopPropagation(),M(n)},children:(0,$.jsx)(`img`,{src:n,loading:`lazy`,decoding:`async`,alt:`tool result image ${t+1}`})},t)})}),j&&(0,bn.createPortal)((0,$.jsxs)(`div`,{className:`img-lightbox`,role:`dialog`,"aria-label":u(`toolImageZoom`),onClick:()=>M(null),children:[(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-close`,title:u(`close`),"aria-label":u(`close`),onClick:e=>{e.stopPropagation(),M(null)},children:(0,$.jsx)(R,{})}),(0,$.jsx)(`img`,{src:j,alt:`tool result preview`})]}),document.body),g&&(0,$.jsxs)(`div`,{className:`toolcall-body`,children:[m&&ae?(0,$.jsx)(ad,{args:ae,details:t.result?.details,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp}):N?(0,$.jsx)(Ld,{args:P}):ee&&F?.code?(0,$.jsx)(Rd,{code:F.code,options:F.options,details:t.result?.details,output:k}):te&&ne?(0,$.jsx)(ud,{questions:ne.questions,details:t.result?.details,output:k,isError:T,waiting:y||w}):re?(0,$.jsx)(bd,{toolName:e.name,argumentsText:e.argumentsText,details:t.result?.details,output:k,isError:T,onOpenInspector:ve}):e.argumentsText&&(0,$.jsx)(`div`,{className:`toolcall-args`,children:U?(0,$.jsx)(Fd,{command:U}):(0,$.jsx)(`pre`,{children:e.argumentsText})}),e.name===`tool_search`&&(0,$.jsx)(Id,{details:t.result?.details}),k.length>0&&!(te&&ne)&&(0,$.jsxs)(`div`,{className:`toolcall-output`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[u(T?`errorOutput`:`output`),(y||w)&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{ref:E,onWheel:e=>{if(e.deltaY<0)D.current=!1;else if(e.deltaY>0&&E.current){let e=E.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(D.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(D.current=!0)},children:k})]}),y&&k.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,u(`waitingOutput`)]}),w&&k.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,u(`waitingModel`)]}),s&&s.length>0&&(0,$.jsx)(`div`,{className:`toolcall-footer`,children:s.filter(e=>e&&e.hidden!==!0).map((e,t)=>{let n=e.label||e.id;return e.kind===`badge`?(0,$.jsx)(`span`,{className:`toolcall-footer-badge`,title:n,children:e.badge??n},`${e.id}#${t}`):(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-footer-item`,title:n,onClick:()=>c?.(e),children:[e.icon&&pp(e.icon),(0,$.jsx)(`span`,{children:n})]},`${e.id}#${t}`)})})]})]})}),Pd=(0,Q.memo)(function(e){let t=(0,Q.useRef)(null);return Hc(t.current)?(0,$.jsx)(Md,{block:e.block,view:e.view,uiContextToolCall:e.uiContextToolCall,onUiAction:e.onUiAction,rootRef:t}):(0,$.jsx)(Nd,{...e,rootRef:t})});function Fd({command:e}){return(0,$.jsxs)(`div`,{className:`termline`,children:[(0,$.jsx)(o,{className:`termline-icon`}),(0,$.jsx)(`code`,{children:xs(e)})]})}function Id({details:e}){let t=V(),n=Array.isArray(e?.loaded)?e.loaded:[];return n.length===0?null:(0,$.jsxs)(`div`,{className:`tool-search-loaded-box`,children:[(0,$.jsxs)(`span`,{className:`tool-search-loaded-label`,children:[t(`toolSearchLoaded`),`:`]}),(0,$.jsx)(`div`,{className:`tool-search-tags`,children:n.map(e=>(0,$.jsx)(`span`,{className:`tool-search-tag`,children:e},e))})]})}function Ld({args:e}){let t=V(),n=[{field:`task`,label:t(`delegateSecTask`)},{field:`expected_outcome`,label:t(`delegateSecExpected`)},{field:`required_tools`,label:t(`delegateSecTools`)},{field:`must_do`,label:t(`delegateSecMustDo`)},{field:`must_not_do`,label:t(`delegateSecMustNotDo`)},{field:`context`,label:t(`delegateSecContext`)}].filter(({field:t})=>e[t]?.trim());return n.length===0?null:(0,$.jsx)(`div`,{className:`delegate-brief`,children:n.map(({field:t,label:n})=>(0,$.jsxs)(`div`,{className:`delegate-sec`,children:[(0,$.jsx)(`div`,{className:`delegate-sec-label`,children:n}),(0,$.jsx)(`div`,{className:`delegate-sec-text`,children:e[t]})]},t))})}function Rd({code:e,options:t,details:n,output:r}){let i=V(),a=n,o=Array.isArray(a?.calls)?a.calls:[],s=typeof a?.fullOutputPath==`string`?a.fullOutputPath:void 0,c=(0,Q.useMemo)(()=>{if(!r)return[];let e=/\[Image saved to (.*?) \((.*?)\)\]/g,t=[],n;for(;(n=e.exec(r))!==null;)t.push({path:n[1],info:n[2]});return t},[r]);return(0,$.jsxs)(`div`,{className:`codemode-card`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeScript`)}),t&&Object.keys(t).length>0&&(0,$.jsx)(`span`,{className:`codemode-options-badge`,children:JSON.stringify(t)})]}),(0,$.jsx)(`pre`,{className:`codemode-code`,children:(0,$.jsx)(`code`,{children:e})})]}),o.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-calls-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeNestedCalls`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:o.length})]}),(0,$.jsx)(`div`,{className:`codemode-calls-list`,children:o.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-call-item status-${e.status}`,children:[(0,$.jsx)(`span`,{className:`codemode-call-status`,children:e.status===`ok`?`✓`:e.status===`error`?`✗`:e.status===`running`?`…`:`⊘`}),(0,$.jsx)(`span`,{className:`codemode-call-name`,children:e.name}),e.args&&(0,$.jsx)(`span`,{className:`codemode-call-args`,children:e.args}),typeof e.durationMs==`number`&&(0,$.jsx)(`span`,{className:`codemode-call-duration`,children:zd(e.durationMs)}),e.error&&(0,$.jsx)(`div`,{className:`codemode-call-error`,children:e.error})]},e.id||t))})]}),c.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-images-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeSavedImages`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:c.length})]}),(0,$.jsx)(`div`,{className:`codemode-images-list`,children:c.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-image-item`,children:[(0,$.jsx)(Ne,{className:`codemode-image-icon`}),(0,$.jsx)(`code`,{className:`codemode-image-path`,title:e.path,children:e.path}),(0,$.jsx)(`span`,{className:`codemode-image-info`,children:e.info}),(0,$.jsx)(`button`,{type:`button`,className:`btn-ghost codemode-image-copy`,title:i(`copy`),onClick:t=>{t.stopPropagation(),navigator.clipboard.writeText(e.path)},children:(0,$.jsx)(Te,{})})]},t))})]}),s&&(0,$.jsxs)(`div`,{className:`codemode-full-output`,children:[(0,$.jsxs)(`span`,{className:`codemode-sec-title`,children:[i(`codemodeFullOutput`),`:`]}),(0,$.jsx)(`code`,{children:s})]})]})}function zd(e){if(e===void 0||e<0||!Number.isFinite(e))return``;if(e<1e3)return`${Math.round(e)}ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${String(r).padStart(2,`0`)}s`}var Bd=Object.freeze({status:`idle`,messages:[]}),Vd=new Map,Hd=new Set,Ud=16;function Wd(){for(;Vd.size>Ud;){let e=Vd.keys().next().value;if(e===void 0)break;Vd.delete(e)}}function Gd(){for(let e of Hd)e()}function Kd(e,t){let n=(e??``).trim();if(!n)return;let r=Vd.get(n);(!r||r.status!==`loading`&&r.status!==`ready`)&&(Vd.set(n,{status:`loading`,messages:r?.messages??[]}),Wd(),Gd(),Z({type:`get_compacted_messages`,compactionMessageId:n,conversationId:t}))}function qd(e){let t=e.compactionMessageId;t&&(e.error?Vd.set(t,{status:`error`,messages:[],error:e.error}):Vd.set(t,{status:`ready`,messages:e.messages??[]}),Wd(),Gd())}function Jd(e){let t=Vd.get(e);return t?(Vd.delete(e),Vd.set(e,t),t):Bd}function Yd(e){return Hd.add(e),()=>{Hd.delete(e)}}function Xd(e){return(0,Q.useSyncExternalStore)(Yd,()=>Jd(e),()=>Bd)}var Zd=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Qd(e){let t=e.match(Zd);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}var $d=1568,ef=2097152;function tf(e){return e.startsWith(`image/`)&&e!==`image/svg+xml`&&e!==`image/svg`}async function nf(e){if(!e.type.startsWith(`image/`))return null;let t;try{t=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{return null}try{let n=Math.min(1,$d/Math.max(t.width,t.height)),r=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),a=e.type===`image/jpeg`||e.type===`image/jpg`?[[`image/jpeg`,.85],[`image/jpeg`,.6],[`image/webp`,.8]]:[[`image/png`,1],[`image/jpeg`,.85],[`image/jpeg`,.6]],o=null;for(let[n,s]of a){let a=document.createElement(`canvas`);a.width=r,a.height=i;let c=a.getContext(`2d`);if(!c)continue;n!==`image/png`&&(c.fillStyle=`#ffffff`,c.fillRect(0,0,r,i)),c.drawImage(t,0,0,r,i);let l=a.toDataURL(n,s),u=l.match(/^data:([^;]+);base64,/),d=u?u[1]:n,f=l.replace(/^data:[^;]*;base64,/,``),p=Math.floor(f.length*3/4);if(o={data:f,mimeType:d,name:e.name,size:p},p<=ef)return o}return o}finally{t.close()}}function rf(e){let t=[];for(let n of e)n?.type===`text`&&typeof n.text==`string`&&n.text.length>0&&t.push(n.text);return t}function af(e){return rf(e).join(`
|
|
25
25
|
|
|
26
|
-
`)}function
|
|
26
|
+
`)}function of(e){return sf(af(e))}function sf(e){let t=e.split(`
|
|
27
27
|
`),n=[],r=!1;for(let e of t){if(/^\s*```/.test(e)){r=!r;continue}if(r){n.push(e);continue}e=e.replace(/^\s{0,3}#{1,6}\s+/,``).replace(/^\s*(>\s*)+/,``).replace(/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/,``).replace(/^\s*\[[ xX]\]\s+/,``),!(/^\s*\|?\s*[:-]+\s*(\|\s*[:-]+\s*)*\|?\s*$/.test(e)&&/[-:]/.test(e))&&n.push(e)}return n.join(`
|
|
28
28
|
`).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/`([^`]*)`/g,`$1`).replace(/(\*\*|__)(.+?)\1/g,`$2`).replace(/(^|\W)\*([^*\n]+)\*(?=\W|$)/g,`$1$2`).replace(/(^|\W)_([^_\n]+)_(?=\W|$)/g,`$1$2`).replace(/~~(.+?)~~/g,`$1`).replace(/^\s*\|/gm,``).replace(/\|\s*$/gm,``).replace(/\|/g,` `).replace(/<[^>]+>/g,``).replace(/\s+#+\s*$/gm,``).split(`
|
|
29
29
|
`).map(e=>e.replace(/[ \t]+/g,` `).replace(/^\s+|\s+$/g,``)).join(`
|
|
30
30
|
`).replace(/\n{3,}/g,`
|
|
31
31
|
|
|
32
|
-
`).trim()}function
|
|
33
|
-
`))}return``}var
|
|
32
|
+
`).trim()}function cf(e,t=1){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(t)} KB`:e<1073741824?`${(e/1048576).toFixed(t)} MB`:`${(e/1073741824).toFixed(t)} GB`}function lf(e){return e==null||!Number.isFinite(e)?``:e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}var uf=`pi-web-tts`,df={enabled:!1,announce:!0,readReplies:!1,streamReplies:!0,rate:1,voiceURI:``,engine:`builtin`};function ff(){try{let e=localStorage.getItem(uf);if(!e)return{...df};let t={...df,...JSON.parse(e)};for(let e of[`enabled`,`announce`,`readReplies`,`streamReplies`])typeof t[e]!=`boolean`&&(t[e]=df[e]);return t.rate=typeof t.rate!=`number`||!Number.isFinite(t.rate)?df.rate:Math.round(Math.max(.5,Math.min(2,t.rate))*10)/10,typeof t.voiceURI!=`string`&&(t.voiceURI=df.voiceURI),typeof t.engine!=`string`&&(t.engine=df.engine),t}catch{return{...df}}}function pf(e){try{localStorage.setItem(uf,JSON.stringify(e))}catch{}}function mf(){return typeof window<`u`&&`speechSynthesis`in window}function hf(e,t,n){if(e){let n=t.find(t=>t.voiceURI===e);if(n)return n}let r=n.split(`-`)[0]?.toLowerCase();return r?t.find(e=>e.lang.toLowerCase().startsWith(r))??null:null}function gf(e,t=600){let n=e??``;return n=n.replace(/```[\s\S]*?(?:```|$)/g,` `),n=n.replace(/`([^`]+)`/g,`$1`),n=n.replace(/!\[[^\]]*\]\([^)]*\)/g,` `),n=n.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),n=n.replace(/^\s{0,3}#{1,6}\s+/gm,``),n=n.replace(/^\s{0,3}>\s?/gm,``),n=n.replace(/^\s*[-*+]\s+/gm,``),n=n.replace(/^\s*\|?[\s:|-]*\|[\s:|-]*$/gm,``),n=n.replace(/\|/g,` `),n=n.replace(/(\*\*\*|\*\*|__)(.*?)\1/g,`$2`),n=n.replace(/(\*|_)([^*_\n]+)\1/g,`$2`),n=n.replace(/<[^>]+>/g,` `),n=n.replace(/\r/g,``),n=n.replace(/[ \t]+/g,` `),n=n.replace(/\s*\n+\s*/g,` `),n=n.trim(),t>0&&n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}var _f=class{cursor=0;onSentence;constructor(e){this.onSentence=e}feed(e){if(e.length<=this.cursor)return;let t=e.slice(this.cursor),n=t.match(/(?:[。!?!?;;\n]|(?<=.{25,})[,,])/);if(n&&typeof n.index==`number`){let e=n.index+n[0].length,r=t.slice(0,e);this.cursor+=e;let i=gf(r,0);i&&this.onSentence(i)}}flush(e){if(e.length>this.cursor){let t=gf(e.slice(this.cursor),0);t&&this.onSentence(t),this.cursor=e.length}}reset(){this.cursor=0}};function vf(e){if(!Array.isArray(e))return``;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.role===`assistant`)return gf((n.content??[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
33
|
+
`))}return``}var yf=!1,bf=null,xf=null,Sf=null,Cf=null,wf=new Set;function Tf(e,t=null){let n=!!e,r=n?t:null;if(yf!==n||bf!==r){yf=n,bf=r;for(let e of wf)try{e(n)}catch{}}}function Ef(){return yf}function Df(){return yf?bf:null}function Of(e){return wf.add(e),()=>wf.delete(e)}function kf(e,t=ff(),n){if(!e)return;Af();let r=(t.engine||`builtin`).trim(),i=r===`builtin`?void 0:It(r);if(i&&typeof i.play==`function`){let r=!1;Tf(!0,n??null);try{let a=i.play({text:e,rate:t.rate,voiceURI:t.voiceURI,onStart:()=>{r||Tf(!0,n??null)},onEnd:()=>{r||(r=!0,xf=null,Tf(!1))},onError:()=>{r||(r=!0,xf=null,Tf(!1))}});xf=()=>{r=!0;try{a?.()}catch{}}}catch{Tf(!1)}return}if(mf())try{let r=window.speechSynthesis,i=new SpeechSynthesisUtterance(e);i.rate=t.rate;let a=hf(t.voiceURI,r.getVoices(),navigator.language);a&&(i.voice=a),i.onend=()=>{Cf===i&&Tf(!1)},i.onerror=()=>{Cf===i&&Tf(!1)},Cf=i,Tf(!0,n??null),r.speak(i)}catch{Cf=null,Tf(!1)}}function Af(){if(Sf&&=(Sf.stop(),null),xf){try{xf()}catch{}xf=null}if(mf())try{window.speechSynthesis.cancel()}catch{}Cf=null,Tf(!1)}var jf=class{queue=[];playing=!1;stopped=!1;stopCurrentAudio=null;settings;sourceId;finishedPushing=!1;constructor(e,t){this.settings=e,this.sourceId=t}push(e){if(this.stopped)return;let t=e.trim();t&&(this.queue.push(t),this.playing||this.playNext())}finish(){this.finishedPushing=!0,!this.playing&&this.queue.length===0&&this.stop()}async playNext(){if(this.stopped)return;if(this.queue.length===0){this.playing=!1,this.finishedPushing&&this.stop();return}this.playing=!0;let e=this.queue.shift();Tf(!0,this.sourceId??null),await new Promise(t=>{let n=(this.settings.engine||`builtin`).trim(),r=n===`builtin`?void 0:It(n);if(r&&typeof r.play==`function`){let n=!1,i=r.play({text:e,rate:this.settings.rate,voiceURI:this.settings.voiceURI,onEnd:()=>{n||(n=!0,t())},onError:()=>{n||(n=!0,t())}});this.stopCurrentAudio=()=>{if(!n){n=!0;try{i?.()}catch{}t()}}}else if(mf()){let n=window.speechSynthesis,r=new SpeechSynthesisUtterance(e);r.rate=this.settings.rate;let i=hf(this.settings.voiceURI,n.getVoices(),navigator.language);i&&(r.voice=i),r.onend=()=>t(),r.onerror=()=>t(),this.stopCurrentAudio=()=>{try{n.cancel()}catch{}t()},n.speak(r)}else t()}),this.stopCurrentAudio=null,this.stopped||this.playNext()}stop(){if(this.stopped=!0,this.queue=[],this.stopCurrentAudio){try{this.stopCurrentAudio()}catch{}this.stopCurrentAudio=null}this.playing=!1,Sf===this&&(Sf=null),Tf(!1)}};function Mf(e=ff(),t){Af();let n=new jf(e,t);return Sf=n,n}var Nf={open:!1,triggerId:``,selectedIds:[],includeTools:!1,includeThinking:!1},Pf=Nf,Ff=[],If=new Set;function Lf(){for(let e of If)e()}function Rf(e){return(e.role===`user`||e.role===`assistant`)&&af(e.content).length>0}function zf(e,t=Ff){let n=new Map(t.map((e,t)=>[e.id,t]));return[...new Set(e)].filter(e=>n.has(e)).sort((e,t)=>(n.get(e)??0)-(n.get(t)??0))}function Bf(e){if(Ff=e,Pf.open){let e=zf(Pf.selectedIds,Ff);e.join(`\0`)!==Pf.selectedIds.join(`\0`)&&(Pf={...Pf,selectedIds:e},Lf())}}function Vf(){return Pf}function Hf(e){return If.add(e),()=>{If.delete(e)}}function Uf(){return(0,Q.useSyncExternalStore)(Hf,Vf,Vf)}function Wf(){Pf.open&&(Pf=Nf,Lf())}function Gf(e){let t=Ff.find(t=>t.id===e);if(t&&Rf(t)){if(Pf.open){Pf={...Pf,selectedIds:zf([...Pf.selectedIds,e])},Lf();return}Pf={open:!0,triggerId:e,selectedIds:[e],includeTools:!1,includeThinking:!1},Lf()}}function Kf(e){Pf.open&&(Pf={...Pf,includeTools:e.includeTools??Pf.includeTools,includeThinking:e.includeThinking??Pf.includeThinking},Lf())}function qf(e){if(!Pf.open||!Ff.filter(Rf).map(e=>e.id).includes(e))return;let t=Pf.selectedIds.includes(e)?Pf.selectedIds.filter(t=>t!==e):zf([...Pf.selectedIds,e]);Pf={...Pf,selectedIds:t},Lf()}function Jf({title:e,children:t,...n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(!1),o=(0,Q.useId)(),s=Cn({open:i,anchor:r,side:`top`,onClose:()=>a(!1)});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{...n,ref:r,"aria-label":n[`aria-label`]??e,"aria-describedby":i&&e?o:void 0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:e=>{a(!1),n.onClick?.(e)},children:t}),i&&e&&(0,bn.createPortal)((0,$.jsx)(`div`,{ref:s.panelRef,id:o,role:`tooltip`,className:`msg-action-tooltip`,style:s.style,children:e}),document.body)]})}var Yf=/^(This operation was aborted|Request aborted)$/;function Xf(e){return e.stopReason===`aborted`||e.stopReason===`error`&&Yf.test((e.errorMessage??``).trim())}var Zf=/\[\[\s*([A-Za-z][A-Za-z0-9_-]*)\s*:\s*([A-Za-z][A-Za-z0-9_-]*)\s*:(.*?)\s*\]\]/g,Qf=new Set([`todo`,`notify`,`conv`,`rename`,`title`,`action`,`suggest`]),$f=new Set(Qf);function ep(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function tp(e){let t=[...e].map(ep).join(`|`);return RegExp(`[ \\t]*\\[\\[\\s*(?:${t})(?:\\s*:[^\\]]*)?$`,`i`)}var np=tp($f);function rp(e){let t=new Set(Qf);for(let n of e)n&&t.add(n.toLowerCase());$f.clear();for(let e of t)$f.add(e);np=tp($f)}function ip(e,t=!1){if(!e||!e.includes(`[[`))return e;let n=e.replace(Zf,(e,t,n,r)=>r.includes(`[[`)||!$f.has(t.toLowerCase())?e:``);return t&&(n=n.replace(np,``)),n===e?e:n.replace(/^[ \t]+\n/gm,`
|
|
34
34
|
`).replace(/\n{3,}/g,`
|
|
35
35
|
|
|
36
|
-
`).trim()}function
|
|
37
|
-
`),_e=e.role===`user`?
|
|
38
|
-
`).join(` `).trim(),q=i&&a&&e.role===`assistant`&&e.content.length===0,J=!N&&e.role===`user`&&!i&&!q&&!!o,ve=async e=>{let t=[];for(let n of e){if(
|
|
39
|
-
`)).trim(),n=!!(f&&f.length>0);(t||n)&&o?.(e.id,t,n?f:void 0)},xe=()=>{re(_e?`/skill:${_e.name}${_e.userMessage?` ${_e.userMessage}`:``}`:e.content.map(e=>
|
|
40
|
-
`)),L(f??[]),F(!0)};(0,Q.useEffect)(()=>{g&&J&&xe()},[g]);let Se=()=>{J?xe():m?.(e.id)},Ce=!N&&!i&&!ee&&(J||h),we=()=>{let t=ne.trim();(t||I.some(e=>e.mode===`quote`&&us(e.quote)))&&(o?.(e.id,t,I.length>0?I:void 0),F(!1))},Ee=!O||O.some(e=>e?.id===`host:msg-copy`&&e.hidden!==!0),De=(0,Q.useRef)(null),[X,Oe]=(0,Q.useState)(null),ke=Vf(),Ae=(0,Q.useRef)(0),je=nf(e.content),Me=(e.role===`assistant`||e.role===`user`)&&je.length>0,Pe=async t=>{try{let n=!1;if(t===`host:msg-copy-text`)n=await nc(rf(e.content));else if(t===`host:msg-copy-markdown`)n=await nc(je);else{Uf(e.id);return}window.clearTimeout(Ae.current),Oe({id:t,ok:n}),Ae.current=window.setTimeout(()=>Oe(null),1600)}catch{window.clearTimeout(Ae.current),Oe({id:t,ok:!1}),Ae.current=window.setTimeout(()=>Oe(null),1600)}},Fe=fp(rf(e.content),40)||bp(e.role,P),[Ie,Le]=(0,Q.useState)(wf());(0,Q.useEffect)(()=>Ef(Le),[]);let Re=e.role===`assistant`&&rf(e.content).trim().length>0&&!i&&ff(),ze=Re&&Tf()===e.id,Be=()=>{if(ze){Of();return}Df(mf(rf(e.content),5e3),{...uf(),enabled:!0},e.id)},[Ve,He]=(0,Q.useState)(!1),Ue=(0,Q.useRef)(null),We=Cn({open:Ve,anchor:Ue,onClose:()=>He(!1)}),Ge=e=>Re?(0,$.jsxs)(Kf,{type:`button`,className:`msg-action${ze?` msg-action-speaking`:``}`,title:P(ze?`stopSpeakingMsg`:`speakMsg`),"aria-label":P(ze?`stopSpeakingMsg`:`speakMsg`),onClick:Be,children:[ze?(0,$.jsx)(C,{}):(0,$.jsx)(b,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(ze?`stopSpeakingMsg`:`speakMsg`)})]},e):null,Ke=()=>$r.filter(e=>e.slot===`contextmenu.message`).map(e=>({id:e.id,slot:e.slot,source:`host`,label:P(e.labelKey),labelKey:e.labelKey,icon:e.icon,kind:e.kind,group:e.group,order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[]})),qe=t=>{let n=t.target;if(n instanceof Element&&n.closest(`a, input, textarea, [contenteditable='true']`))return;let r=window.getSelection?.();if(r&&!r.isCollapsed&&r.toString().trim().length>0)return;let a=(k&&k.length>0?k:Ke()).map(t=>{if(t.source!==`host`)return N?{...t,hidden:!0}:t;switch(t.id){case`host:msg-ctx-copy-markdown`:case`host:msg-ctx-copy-text`:return Me?t:{...t,hidden:!0};case`host:msg-ctx-copy-image`:return Me?t:{...t,hidden:!0};case`host:msg-ctx-copy-link`:{let n=Qo(window.location.hash)?.sessionId;return!N&&!i&&n&&e.id?t:{...t,hidden:!0}}case`host:msg-ctx-reask`:case`host:msg-ctx-edit-reask`:return J?t:{...t,hidden:!0};case`host:msg-ctx-rollback`:return Ce?t:{...t,hidden:!0};case`host:msg-ctx-fork`:return!N&&!i&&!ee?t:{...t,hidden:!0};case`host:msg-ctx-speak`:return Re?ze?{...t,label:P(`stopSpeakingMsg`),icon:`square`}:t:{...t,hidden:!0};default:return t}});Gi(a).length!==0&&(t.preventDefault(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.message`,target:{id:e.id,kind:`message`,label:Fe},entries:a,onHostAction:t=>{switch(t.id){case`host:msg-ctx-copy-markdown`:Pe(`host:msg-copy-markdown`);return;case`host:msg-ctx-copy-text`:Pe(`host:msg-copy-text`);return;case`host:msg-ctx-copy-image`:Pe(`host:msg-copy-image`);return;case`host:msg-ctx-copy-link`:{let t=Qo(window.location.hash)?.sessionId;t&&e.id&&nc(es(window.location.href,{sessionId:t,messageId:e.id}));return}case`host:msg-ctx-reask`:be();return;case`host:msg-ctx-edit-reask`:xe();return;case`host:msg-ctx-fork`:Z({type:`fork_session`,messageId:e.id,position:`at`});return;case`host:msg-ctx-rollback`:Se();return;case`host:msg-ctx-speak`:Be();return;default:M?.(t);return}}}))},Je=(e,t)=>{if(!Me)return null;let n=[{id:`host:msg-copy-markdown`,label:P(`copyMarkdown`),icon:(0,$.jsx)(c,{})},{id:`host:msg-copy-text`,label:P(`copyText`),icon:(0,$.jsx)(x,{})},{id:`host:msg-copy-image`,label:P(`copyImage`),icon:(0,$.jsx)(Ne,{})}].filter(e=>{if(!t)return!0;let n=t.find(t=>t.id===e.id);return!n||n.hidden!==!0});if(n.length===0)return null;let r=X!==null,i=X?.ok;return(0,$.jsxs)(`div`,{ref:Ue,className:`msg-copy-group${Ve?` has-open-dropdown`:``}`,children:[(0,$.jsxs)(Kf,{type:`button`,className:`msg-action msg-copy-main-btn${i?` msg-copy-success`:``}`,title:P(i?`copied`:r&&!i?`copyFailed`:`copyMarkdown`),"aria-label":P(`copyMarkdown`),onClick:()=>void Pe(`host:msg-copy-markdown`),children:[i?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(i?`copied`:`copy`)})]}),(0,$.jsx)(Kf,{type:`button`,className:`msg-action msg-copy-caret-btn${Ve?` active`:``}`,title:P(`moreCopyOptions`),"aria-label":P(`moreCopyOptions`),"aria-expanded":Ve,onClick:e=>{e.stopPropagation(),He(e=>!e)},children:(0,$.jsx)(pe,{className:`msg-copy-caret-icon${Ve?` open`:``}`})}),Ve&&(0,bn.createPortal)((0,$.jsx)(`div`,{ref:We.panelRef,style:We.style,className:`msg-copy-dropdown`,role:`menu`,children:n.map(e=>(0,$.jsxs)(Kf,{type:`button`,className:`msg-copy-menu-item`,title:e.label,role:`menuitem`,onClick:()=>{He(!1),Pe(e.id)},children:[e.icon,(0,$.jsx)(`span`,{children:e.label})]},e.id))}),document.body)]},e)},Ye=()=>{if(!O){let e=Je(`fb-copy`),t=Ge(`fb-speak`);if(!J&&!e&&!t)return null;let n=[];return J&&n.push((0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":P(`reaskDirectly`),onClick:be,children:[(0,$.jsx)(te,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(`reaskDirectly`)})]}),(0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),"aria-label":P(`editReask`),onClick:xe,children:[(0,$.jsx)(ct,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(`editReask`)})]})]},`fb-reask`)),e&&n.push(e),t&&n.push(t),n}let t=[],n=!1;return O.forEach((r,a)=>{if(!r||r.hidden===!0||r.id===`host:msg-copy`)return;let o=`${r.id}#${a}`,s=r.label||r.id;if(r.id===`host:msg-copy-text`||r.id===`host:msg-copy-markdown`||r.id===`host:msg-copy-image`){if(!n){n=!0;let e=Je(`copy-dropdown`,O);e&&t.push(e)}return}if(r.id===`host:msg-speak`){let e=Ge(o);e&&t.push(e);return}if(r.id===`host:msg-reask`){if(!J)return;t.push((0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":s,onClick:be,children:[dp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-edit-reask`){if(!J)return;t.push((0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),onClick:xe,children:[dp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-fork`){if(N||i||ee)return;t.push((0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`forkSessionTip`),"aria-label":s,onClick:()=>Z({type:`fork_session`,messageId:e.id,position:`at`}),children:[dp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-rollback`){if(!Ce)return;t.push((0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:P(`rollbackSessionTip`),"aria-label":s,onClick:()=>{Se()},children:[dp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(!N){if(r.kind===`divider`){t.push((0,$.jsx)(`span`,{className:`msg-action-divider`,"aria-hidden":`true`},o));return}if(r.kind===`badge`){t.push((0,$.jsx)(`span`,{className:`msg-action-badge`,title:s,children:r.badge??s},o));return}if(r.kind===`select`&&r.options?.length){t.push((0,$.jsx)(`select`,{className:`msg-action msg-action-select`,title:s,"aria-label":s,value:r.options.some(e=>e.value===r.value)?r.value:r.options[0].value,onChange:e=>M?.(r,e.target.value),children:r.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},o));return}t.push((0,$.jsxs)(Kf,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:()=>M?.(r),children:[dp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s}),r.badge?(0,$.jsx)(`span`,{className:`msg-action-count`,children:r.badge}):null]},o))}}),t.length===0?null:t},Xe=()=>{let e=Ye();return e?(0,$.jsx)(`div`,{className:`msg-actions${Ve?` has-open-dropdown`:``}`,children:e}):null},Ze=e.role===`custom`&&(e.customType===`goal-review`||e.customType===`goal-wizard`),Qe=e.role===`custom`&&e.customType===`goal-wizard`,$e=e.role===`custom`&&!!e.customType&&e.customType!==`file`&&!Ze&&kc(e.customType),tt=$e?JSON.stringify({customType:e.customType,details:e.details??{}}):``,nt=ke.open&&ke.selectedIds.includes(e.id),rt=ke.open&&Me,it=nt&&ke.includeThinking,at=nt&&ke.includeTools,ot=!ee&&(e.role===`user`||Me),st=(0,Q.useMemo)(()=>{if(e.role!==`assistant`)return-1;for(let t=e.content.length-1;t>=0;t--)if(rp(e.content[t]))return t;return-1},[e.role,e.content]);return(0,$.jsxs)(`div`,{ref:De,className:`msg msg-${e.role}${Ze?` msg-goal-review`:``}${nt?` msg-export-selected`:``}${N?` msg-readonly`:``}${p&&e.id.startsWith(`group-`)?` msg-group`:``}`,"data-role":e.role,"data-msg-id":e.id,onContextMenu:qe,children:[rt&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:nt,title:P(`copyImage`),"aria-label":P(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>Gf(e.id)}),(0,$.jsxs)(`div`,{className:`msg-meta`,children:[d&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-collapse-btn`,title:P(`collapseMsg`),onClick:()=>d(e.id),children:[(0,$.jsx)(s,{}),` `,P(`collapseMsg`)]}),(0,$.jsx)(`span`,{className:`msg-role`,children:e.role===`custom`?Qe?P(`goalWizardCard`):Ze?P(`goalBarTitle`):e.customType===`file`?P(`attachment`):`${P(`plugin`)} · ${e.customType??P(`unknown`)}`:bp(e.role,P)}),p&&(0,$.jsx)(`span`,{className:`msg-sender`,"data-initial":Array.from(p)[0],children:p}),e.model&&(0,$.jsx)(`span`,{className:`msg-model`,children:e.model}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:xp(e.timestamp)}),_!==void 0&&y&&(0,$.jsxs)(`button`,{type:`button`,className:`qn-tag ${v?`active`:``}`,title:`${_+1}. ${K}`,"aria-label":`${_+1}. ${K}`,onClick:()=>y(e.id),children:[(0,$.jsx)(`span`,{className:`qn-tag-bar`}),(0,$.jsx)(`span`,{className:`qn-tag-idx`,children:_+1})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:ee?(0,$.jsxs)(`div`,{className:`msg-editor${ie?` drag-over`:``}`,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),ae(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||ae(!1)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),ae(!1),ye(Array.from(e.dataTransfer?.files??[]))},children:[I.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-images`,children:I.map((e,t)=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(bs,{quote:e.quote,onRemove:()=>L(e=>e.filter((e,n)=>n!==t))},`quote-${t}`);let n=cp(e);return(0,$.jsxs)(`span`,{className:`msg-editor-img ${n===`image`?``:`file-chip`}`,title:lp(e,P),children:[n===`image`?(0,$.jsx)(`img`,{src:`data:${e.mimeType??`image/png`};base64,${e.imageData}`,alt:e.name}):(0,$.jsxs)(`span`,{className:`msg-editor-file`,children:[(0,$.jsx)(`span`,{className:`msg-editor-file-icon`,children:n===`path`?e.mode===`page`?`🌐`:e.mode===`reference`?`🔗`:`📎`:`📄`}),(0,$.jsx)(`span`,{className:`msg-editor-file-name`,children:e.name??e.path?.split(`/`).pop()})]}),(0,$.jsx)(`button`,{type:`button`,className:`msg-editor-img-remove`,title:P(`removeAttachment`),onClick:()=>L(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(R,{})})]},`${e.name??e.path??`att`}-${t}`)})}),ce.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:ce.map(({id:e,name:t,percent:n})=>(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:6,minWidth:0},children:[(0,$.jsx)(`progress`,{max:100,value:n??void 0,"aria-label":n===null?P(`uploadPreparing`,{name:t}):P(`uploadReading`,{name:t,percent:n}),style:{width:64,flexShrink:0}}),(0,$.jsx)(`span`,{style:{overflowWrap:`anywhere`,minWidth:0},children:n===null?P(`uploadPreparing`,{name:t}):P(`uploadReading`,{name:t,percent:n})})]},e))}),z&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,children:z}),(0,$.jsx)(`textarea`,{className:`msg-editor-input`,value:ne,autoFocus:!0,placeholder:P(`editPlaceholder`),rows:Math.max(2,Math.min(10,ne.split(`
|
|
41
|
-
`).length+1)),onChange:e=>re(e.target.value),onPaste:e=>{let t=[];for(let n of e.clipboardData?.items??[])if(n.kind===`file
|
|
36
|
+
`).trim()}function ap(e){return e.type===`text`&&typeof e.text==`string`?e:null}function op(e){return e.type===`thinking`&&typeof e.thinking==`string`?e:null}function sp(e){return e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`?e:null}function cp(e){return e.type===`image`&&typeof e.dataUrl==`string`?e:null}function lp(e){return e.type===`bash`&&typeof e.command==`string`?e:null}function up(e){return e.imageData?`image`:e.uploadPath?`upload`:e.fileData?`file`:`path`}function dp(e,t){if(e.mode===`quote`&&e.quote)return e.quote.text;if(e.imageData)return t(`attachImage`,{name:e.name??`image`});if(e.uploadPath)return t(`attachFile`,{name:e.name??e.uploadPath});if(e.fileData)return t(`attachFile`,{name:e.name??`file`});let n=e.path.split(`/`).pop()??e.path;return e.mode===`lines`&&e.lines?t(`attachLines`,{path:n,start:e.lines.start,end:e.lines.end}):e.mode===`page`?t(`attachPage`,{name:e.name??e.path}):e.mode===`conversation`?t(`attachConversation`,{name:e.name??e.path}):e.mode===`reference`?t(`refOnly`,{path:n}):t(`attachContent`,{path:n})}var fp={edit:(0,$.jsx)(ct,{}),copy:(0,$.jsx)(Te,{}),branch:(0,$.jsx)(ce,{}),text:(0,$.jsx)(x,{}),markdown:(0,$.jsx)(c,{}),image:(0,$.jsx)(Ne,{}),undo:(0,$.jsx)(d,{}),volume:(0,$.jsx)(b,{}),refresh:(0,$.jsx)(te,{}),x:(0,$.jsx)(R,{})};function pp(e){let t=(e??``).trim();return t?fp[t.toLowerCase()]||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?(0,$.jsx)(`span`,{className:`msg-action-glyph`,children:t}):(0,$.jsx)(se,{})):(0,$.jsx)(se,{})}function mp(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}var hp=(0,Q.memo)(function({message:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,onEdit:o,onKillBash:l,onRetry:u,onCollapse:d,questionAttachments:f,messageLabel:p,onRollbackEdit:m,canRollbackEdit:h=!1,editRequest:g,qnIndex:_,qnActive:v,onJump:y,thinkingWrap:S,toolsWrap:w,toolImages:T,searchActive:E,autoExpand:D,uiMessageActions:O,uiContextMessage:k,uiContextToolCall:A,uiToolCardFooter:j,onUiAction:M,readOnly:N=!1}){let P=V(),[ee,F]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(``),[I,L]=(0,Q.useState)([]),[ie,ae]=(0,Q.useState)(!1),oe=en(`chatUploadMaxMb`),se=(0,Q.useRef)(0),[ce,le]=(0,Q.useState)([]),ue=e=>le(t=>t.filter(t=>t.id!==e)),[z,de]=(0,Q.useState)(null),B=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{B.current&&clearTimeout(B.current)},[]);let fe=e=>{de(e),B.current&&clearTimeout(B.current),B.current=setTimeout(()=>de(t=>t===e?null:t),4e3)};if(e.role===`toolResult`||e.role===`system`)return null;if(e.role===`compactionSummary`)return(0,$.jsx)(vp,{message:e,forceOpen:E,autoExpand:D});let me=e.role===`custom`&&e.customType===`file`,he=me&&e.details?.mode===`quote`?fs(e.details.quote):null,H=e.details?.quotes,ge=e.role===`user`&&Array.isArray(H)?H.map(fs).filter(e=>e!==null):[],U=e.details?.attachments,W=e.role===`user`&&Array.isArray(U)?U.filter(t=>t.type!==`image`||!e.content.some(e=>e.type===`image`)):[],G=e.content.map(e=>ap(e)?.text??``).filter(Boolean).join(`
|
|
37
|
+
`),_e=e.role===`user`?Qd(G):null,K=_e?_e.userMessage??`skill:${_e.name}`:G.split(`
|
|
38
|
+
`).join(` `).trim(),q=i&&a&&e.role===`assistant`&&e.content.length===0,J=!N&&e.role===`user`&&!i&&!q&&!!o,ve=async e=>{let t=[];for(let n of e){if(!tf(n.type))continue;if(n.size>oe*1024*1024){fe(P(`fileTooLarge`,{name:n.name,size:oe}));continue}let e=++se.current;le(t=>[...t,{id:e,name:n.name,percent:null}]);try{let e=await nf(n);if(!e){fe(P(`fileLoadFailed`,{name:n.name}));continue}t.push({path:``,imageData:e.data,mimeType:e.mimeType,name:e.name})}catch{fe(P(`fileLoadFailed`,{name:n.name}))}finally{ue(e)}}t.length>0&&L(e=>[...e,...t])},Y=async e=>{if(e.size>oe*1024*1024){fe(P(`fileTooLarge`,{name:e.name,size:oe}));return}let t=++se.current;le(n=>[...n,{id:t,name:e.name,percent:0}]);let n;try{n=(await new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(i.result),i.onerror=()=>r(i.error??Error(`read failed`)),i.onabort=()=>r(Error(`read aborted`)),i.onprogress=e=>{let n=e.lengthComputable&&e.total>0?Math.min(100,Math.round(e.loaded/e.total*100)):null;le(e=>e.map(e=>e.id===t?{...e,percent:n}:e))},i.readAsDataURL(e)})).replace(/^data:[^;]*;base64,/,``)}catch{fe(P(`fileLoadFailed`,{name:e.name}));return}finally{ue(t)}L(t=>[...t,{path:``,fileData:n,name:e.name,size:e.size,mimeType:e.type||void 0}])},ye=async e=>{let t=[];for(let n of e)tf(n.type)?t.push(n):Y(n);t.length>0&&await ve(t)},be=()=>{let t=(_e?`/skill:`+_e.name+(_e.userMessage?` `+_e.userMessage:``):e.content.map(e=>ap(e)?.text??``).filter(Boolean).join(`
|
|
39
|
+
`)).trim(),n=!!(f&&f.length>0);(t||n)&&o?.(e.id,t,n?f:void 0)},xe=()=>{re(_e?`/skill:${_e.name}${_e.userMessage?` ${_e.userMessage}`:``}`:e.content.map(e=>ap(e)?.text??``).filter(Boolean).join(`
|
|
40
|
+
`)),L(f??[]),F(!0)};(0,Q.useEffect)(()=>{g&&J&&xe()},[g]);let Se=()=>{J?xe():m?.(e.id)},Ce=!N&&!i&&!ee&&(J||h),we=()=>{let t=ne.trim();(t||I.some(e=>e.mode===`quote`&&fs(e.quote)))&&(o?.(e.id,t,I.length>0?I:void 0),F(!1))},Ee=!O||O.some(e=>e?.id===`host:msg-copy`&&e.hidden!==!0),De=(0,Q.useRef)(null),[X,Oe]=(0,Q.useState)(null),ke=Uf(),Ae=(0,Q.useRef)(0),je=af(e.content),Me=(e.role===`assistant`||e.role===`user`)&&je.length>0,Pe=async t=>{try{let n=!1;if(t===`host:msg-copy-text`)n=await ic(of(e.content));else if(t===`host:msg-copy-markdown`)n=await ic(je);else{Gf(e.id);return}window.clearTimeout(Ae.current),Oe({id:t,ok:n}),Ae.current=window.setTimeout(()=>Oe(null),1600)}catch{window.clearTimeout(Ae.current),Oe({id:t,ok:!1}),Ae.current=window.setTimeout(()=>Oe(null),1600)}},Fe=mp(of(e.content),40)||Sp(e.role,P),[Ie,Le]=(0,Q.useState)(Ef());(0,Q.useEffect)(()=>Of(Le),[]);let Re=e.role===`assistant`&&of(e.content).trim().length>0&&!i&&mf(),ze=Re&&Df()===e.id,Be=()=>{if(ze){Af();return}kf(gf(of(e.content),5e3),{...ff(),enabled:!0},e.id)},[Ve,He]=(0,Q.useState)(!1),Ue=(0,Q.useRef)(null),We=Cn({open:Ve,anchor:Ue,onClose:()=>He(!1)}),Ge=e=>Re?(0,$.jsxs)(Jf,{type:`button`,className:`msg-action${ze?` msg-action-speaking`:``}`,title:P(ze?`stopSpeakingMsg`:`speakMsg`),"aria-label":P(ze?`stopSpeakingMsg`:`speakMsg`),onClick:Be,children:[ze?(0,$.jsx)(C,{}):(0,$.jsx)(b,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(ze?`stopSpeakingMsg`:`speakMsg`)})]},e):null,Ke=()=>$r.filter(e=>e.slot===`contextmenu.message`).map(e=>({id:e.id,slot:e.slot,source:`host`,label:P(e.labelKey),labelKey:e.labelKey,icon:e.icon,kind:e.kind,group:e.group,order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[]})),qe=t=>{let n=t.target;if(n instanceof Element&&n.closest(`a, input, textarea, [contenteditable='true']`))return;let r=window.getSelection?.();if(r&&!r.isCollapsed&&r.toString().trim().length>0)return;let a=(k&&k.length>0?k:Ke()).map(t=>{if(t.source!==`host`)return N?{...t,hidden:!0}:t;switch(t.id){case`host:msg-ctx-copy-markdown`:case`host:msg-ctx-copy-text`:return Me?t:{...t,hidden:!0};case`host:msg-ctx-copy-image`:return Me?t:{...t,hidden:!0};case`host:msg-ctx-copy-link`:{let n=es(window.location.hash)?.sessionId;return!N&&!i&&n&&e.id?t:{...t,hidden:!0}}case`host:msg-ctx-reask`:case`host:msg-ctx-edit-reask`:return J?t:{...t,hidden:!0};case`host:msg-ctx-rollback`:return Ce?t:{...t,hidden:!0};case`host:msg-ctx-fork`:return!N&&!i&&!ee?t:{...t,hidden:!0};case`host:msg-ctx-speak`:return Re?ze?{...t,label:P(`stopSpeakingMsg`),icon:`square`}:t:{...t,hidden:!0};default:return t}});Gi(a).length!==0&&(t.preventDefault(),Pi({x:t.clientX,y:t.clientY,slot:`contextmenu.message`,target:{id:e.id,kind:`message`,label:Fe},entries:a,onHostAction:t=>{switch(t.id){case`host:msg-ctx-copy-markdown`:Pe(`host:msg-copy-markdown`);return;case`host:msg-ctx-copy-text`:Pe(`host:msg-copy-text`);return;case`host:msg-ctx-copy-image`:Pe(`host:msg-copy-image`);return;case`host:msg-ctx-copy-link`:{let t=es(window.location.hash)?.sessionId;t&&e.id&&ic(ns(window.location.href,{sessionId:t,messageId:e.id}));return}case`host:msg-ctx-reask`:be();return;case`host:msg-ctx-edit-reask`:xe();return;case`host:msg-ctx-fork`:Z({type:`fork_session`,messageId:e.id,position:`at`});return;case`host:msg-ctx-rollback`:Se();return;case`host:msg-ctx-speak`:Be();return;default:M?.(t);return}}}))},Je=(e,t)=>{if(!Me)return null;let n=[{id:`host:msg-copy-markdown`,label:P(`copyMarkdown`),icon:(0,$.jsx)(c,{})},{id:`host:msg-copy-text`,label:P(`copyText`),icon:(0,$.jsx)(x,{})},{id:`host:msg-copy-image`,label:P(`copyImage`),icon:(0,$.jsx)(Ne,{})}].filter(e=>{if(!t)return!0;let n=t.find(t=>t.id===e.id);return!n||n.hidden!==!0});if(n.length===0)return null;let r=X!==null,i=X?.ok;return(0,$.jsxs)(`div`,{ref:Ue,className:`msg-copy-group${Ve?` has-open-dropdown`:``}`,children:[(0,$.jsxs)(Jf,{type:`button`,className:`msg-action msg-copy-main-btn${i?` msg-copy-success`:``}`,title:P(i?`copied`:r&&!i?`copyFailed`:`copyMarkdown`),"aria-label":P(`copyMarkdown`),onClick:()=>void Pe(`host:msg-copy-markdown`),children:[i?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(i?`copied`:`copy`)})]}),(0,$.jsx)(Jf,{type:`button`,className:`msg-action msg-copy-caret-btn${Ve?` active`:``}`,title:P(`moreCopyOptions`),"aria-label":P(`moreCopyOptions`),"aria-expanded":Ve,onClick:e=>{e.stopPropagation(),He(e=>!e)},children:(0,$.jsx)(pe,{className:`msg-copy-caret-icon${Ve?` open`:``}`})}),Ve&&(0,bn.createPortal)((0,$.jsx)(`div`,{ref:We.panelRef,style:We.style,className:`msg-copy-dropdown`,role:`menu`,children:n.map(e=>(0,$.jsxs)(Jf,{type:`button`,className:`msg-copy-menu-item`,title:e.label,role:`menuitem`,onClick:()=>{He(!1),Pe(e.id)},children:[e.icon,(0,$.jsx)(`span`,{children:e.label})]},e.id))}),document.body)]},e)},Ye=()=>{if(!O){let e=Je(`fb-copy`),t=Ge(`fb-speak`);if(!J&&!e&&!t)return null;let n=[];return J&&n.push((0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":P(`reaskDirectly`),onClick:be,children:[(0,$.jsx)(te,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(`reaskDirectly`)})]}),(0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),"aria-label":P(`editReask`),onClick:xe,children:[(0,$.jsx)(ct,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(`editReask`)})]})]},`fb-reask`)),e&&n.push(e),t&&n.push(t),n}let t=[],n=!1;return O.forEach((r,a)=>{if(!r||r.hidden===!0||r.id===`host:msg-copy`)return;let o=`${r.id}#${a}`,s=r.label||r.id;if(r.id===`host:msg-copy-text`||r.id===`host:msg-copy-markdown`||r.id===`host:msg-copy-image`){if(!n){n=!0;let e=Je(`copy-dropdown`,O);e&&t.push(e)}return}if(r.id===`host:msg-speak`){let e=Ge(o);e&&t.push(e);return}if(r.id===`host:msg-reask`){if(!J)return;t.push((0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":s,onClick:be,children:[pp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-edit-reask`){if(!J)return;t.push((0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),onClick:xe,children:[pp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-fork`){if(N||i||ee)return;t.push((0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`forkSessionTip`),"aria-label":s,onClick:()=>Z({type:`fork_session`,messageId:e.id,position:`at`}),children:[pp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-rollback`){if(!Ce)return;t.push((0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:P(`rollbackSessionTip`),"aria-label":s,onClick:()=>{Se()},children:[pp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(!N){if(r.kind===`divider`){t.push((0,$.jsx)(`span`,{className:`msg-action-divider`,"aria-hidden":`true`},o));return}if(r.kind===`badge`){t.push((0,$.jsx)(`span`,{className:`msg-action-badge`,title:s,children:r.badge??s},o));return}if(r.kind===`select`&&r.options?.length){t.push((0,$.jsx)(`select`,{className:`msg-action msg-action-select`,title:s,"aria-label":s,value:r.options.some(e=>e.value===r.value)?r.value:r.options[0].value,onChange:e=>M?.(r,e.target.value),children:r.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},o));return}t.push((0,$.jsxs)(Jf,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:()=>M?.(r),children:[pp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s}),r.badge?(0,$.jsx)(`span`,{className:`msg-action-count`,children:r.badge}):null]},o))}}),t.length===0?null:t},Xe=()=>{let e=Ye();return e?(0,$.jsx)(`div`,{className:`msg-actions${Ve?` has-open-dropdown`:``}`,children:e}):null},Ze=e.role===`custom`&&(e.customType===`goal-review`||e.customType===`goal-wizard`),Qe=e.role===`custom`&&e.customType===`goal-wizard`,$e=e.role===`custom`&&!!e.customType&&e.customType!==`file`&&!Ze&&jc(e.customType),tt=$e?JSON.stringify({customType:e.customType,details:e.details??{}}):``,nt=ke.open&&ke.selectedIds.includes(e.id),rt=ke.open&&Me,it=nt&&ke.includeThinking,at=nt&&ke.includeTools,ot=!ee&&(e.role===`user`||Me),st=(0,Q.useMemo)(()=>{if(e.role!==`assistant`)return-1;for(let t=e.content.length-1;t>=0;t--)if(ap(e.content[t]))return t;return-1},[e.role,e.content]);return(0,$.jsxs)(`div`,{ref:De,className:`msg msg-${e.role}${Ze?` msg-goal-review`:``}${nt?` msg-export-selected`:``}${N?` msg-readonly`:``}${p&&e.id.startsWith(`group-`)?` msg-group`:``}`,"data-role":e.role,"data-msg-id":e.id,onContextMenu:qe,children:[rt&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:nt,title:P(`copyImage`),"aria-label":P(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>qf(e.id)}),(0,$.jsxs)(`div`,{className:`msg-meta`,children:[d&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-collapse-btn`,title:P(`collapseMsg`),onClick:()=>d(e.id),children:[(0,$.jsx)(s,{}),` `,P(`collapseMsg`)]}),(0,$.jsx)(`span`,{className:`msg-role`,children:e.role===`custom`?Qe?P(`goalWizardCard`):Ze?P(`goalBarTitle`):e.customType===`file`?P(`attachment`):`${P(`plugin`)} · ${e.customType??P(`unknown`)}`:Sp(e.role,P)}),p&&(0,$.jsx)(`span`,{className:`msg-sender`,"data-initial":Array.from(p)[0],children:p}),e.model&&(0,$.jsx)(`span`,{className:`msg-model`,children:e.model}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:Cp(e.timestamp)}),_!==void 0&&y&&(0,$.jsxs)(`button`,{type:`button`,className:`qn-tag ${v?`active`:``}`,title:`${_+1}. ${K}`,"aria-label":`${_+1}. ${K}`,onClick:()=>y(e.id),children:[(0,$.jsx)(`span`,{className:`qn-tag-bar`}),(0,$.jsx)(`span`,{className:`qn-tag-idx`,children:_+1})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:ee?(0,$.jsxs)(`div`,{className:`msg-editor${ie?` drag-over`:``}`,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),ae(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||ae(!1)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),ae(!1),ye(Array.from(e.dataTransfer?.files??[]))},children:[I.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-images`,children:I.map((e,t)=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(Ss,{quote:e.quote,onRemove:()=>L(e=>e.filter((e,n)=>n!==t))},`quote-${t}`);let n=up(e);return(0,$.jsxs)(`span`,{className:`msg-editor-img ${n===`image`?``:`file-chip`}`,title:dp(e,P),children:[n===`image`?(0,$.jsx)(`img`,{src:`data:${e.mimeType??`image/png`};base64,${e.imageData}`,alt:e.name}):(0,$.jsxs)(`span`,{className:`msg-editor-file`,children:[(0,$.jsx)(`span`,{className:`msg-editor-file-icon`,children:n===`path`?e.mode===`page`?`🌐`:e.mode===`reference`?`🔗`:`📎`:`📄`}),(0,$.jsx)(`span`,{className:`msg-editor-file-name`,children:e.name??e.path?.split(`/`).pop()})]}),(0,$.jsx)(`button`,{type:`button`,className:`msg-editor-img-remove`,title:P(`removeAttachment`),onClick:()=>L(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(R,{})})]},`${e.name??e.path??`att`}-${t}`)})}),ce.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:ce.map(({id:e,name:t,percent:n})=>(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:6,minWidth:0},children:[(0,$.jsx)(`progress`,{max:100,value:n??void 0,"aria-label":n===null?P(`uploadPreparing`,{name:t}):P(`uploadReading`,{name:t,percent:n}),style:{width:64,flexShrink:0}}),(0,$.jsx)(`span`,{style:{overflowWrap:`anywhere`,minWidth:0},children:n===null?P(`uploadPreparing`,{name:t}):P(`uploadReading`,{name:t,percent:n})})]},e))}),z&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,children:z}),(0,$.jsx)(`textarea`,{className:`msg-editor-input`,value:ne,autoFocus:!0,placeholder:P(`editPlaceholder`),rows:Math.max(2,Math.min(10,ne.split(`
|
|
41
|
+
`).length+1)),onChange:e=>re(e.target.value),onPaste:e=>{let t=[];for(let n of e.clipboardData?.items??[])if(n.kind===`file`&&tf(n.type)){let e=n.getAsFile();e&&t.push(e)}t.length!==0&&(e.preventDefault(),ve(t))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),we()):e.key===`Escape`&&F(!1)}}),(0,$.jsxs)(`div`,{className:`msg-editor-actions`,children:[(0,$.jsxs)(`span`,{className:`msg-editor-hint`,children:[(0,$.jsx)(Ne,{}),` `,P(`editAttachmentHint`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn sm`,onClick:()=>F(!1),children:P(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary sm`,disabled:!ne.trim()&&!I.some(e=>e.mode===`quote`&&fs(e.quote)),title:P(`reaskFromHere`),onClick:we,children:[(0,$.jsx)(ct,{}),` `,P(`reaskFromHere`)]})]})]}):(0,$.jsxs)($.Fragment,{children:[Xf(e)?(0,$.jsx)(`div`,{className:`msg-stopped`,role:`status`,children:P(`turnStopped`)}):e.errorMessage&&(0,$.jsxs)(`div`,{className:`msg-error`,children:[(0,$.jsx)(`span`,{className:`msg-error-text`,children:e.errorMessage}),a&&!i&&u&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-retry-btn`,title:P(`retryLastTip`),onClick:u,children:[(0,$.jsx)(te,{}),` `,P(`retryNow`)]})]}),ge.map((e,t)=>(0,$.jsx)(Ss,{quote:e,forceOpen:E},`quote-${t}`)),W.length>0&&(0,$.jsx)(`div`,{className:`msg-queued-atts-bar`,children:W.map((e,t)=>(0,$.jsxs)(`span`,{className:`queued-att-chip`,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:e.type===`image`||e.type===`vision-bridge`?`🖼️`:e.type===`folder`?`📁`:e.type===`page`?`🌐`:e.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:e.name})]},`qatt-${t}`))}),he?(0,$.jsx)(Ss,{quote:he,forceOpen:E}):me?(0,$.jsx)(gp,{message:e,forceOpen:E}):_e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(bp,{block:_e,forceOpen:E}),_e.userMessage&&(0,$.jsx)(`div`,{className:`msg-text`,children:(0,$.jsx)(sl,{text:_e.userMessage,hardBreaks:!0})}),e.content.map((o,s)=>o.type===`text`?null:(0,$.jsx)(xp,{block:o,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:s===e.content.length-1,onKillBash:l,toolsWrap:w,toolImages:T,thinkingWrap:S,searchActive:E,forceThinking:it,forceTools:at,role:e.role,showCopy:Ee,uiContextToolCall:A,uiToolCardFooter:j,onUiAction:M},s))]}):$e?(0,$.jsx)(pl,{type:e.customType??``,code:tt,children:e.content.map((o,s)=>(0,$.jsx)(xp,{block:o,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:s===e.content.length-1,onKillBash:l,toolsWrap:w,toolImages:T,thinkingWrap:S,searchActive:E,forceThinking:it,forceTools:at,role:e.role,showCopy:Ee,uiContextToolCall:A,uiToolCardFooter:j,onUiAction:M},s))}):e.content.map((o,s)=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(xp,{block:o,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:s===e.content.length-1,onKillBash:l,toolsWrap:w,toolImages:T,thinkingWrap:S,searchActive:E,forceThinking:it,forceTools:at,role:e.role,showCopy:Ee,uiContextToolCall:A,uiToolCardFooter:j,onUiAction:M}),s===st&&ot&&Xe()]},s)),q&&(0,$.jsx)(`div`,{className:`thinking-wait minimal`,title:P(`thinkingWait`),"aria-label":P(`thinkingWait`),role:`status`,children:(0,$.jsx)(`span`,{className:`dot`})})]})}),ot&&st<0&&Xe()]})});function gp({message:e,forceOpen:t=!1}){let n=V(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=ac({duration:1200}),s=r||t,c=e.details??{},l=c.name??c.path??n(`attachment`),u=c.type===`folder`,d=c.mode===`canvas`,f=c.mode===`reference`||d,p=c.mode===`bridged`,m=c.mode===`page`,h=c.mode===`conversation`,g=c.path&&/^https?:\/\//i.test(c.path.trim())?c.path.trim():null,_=_p(e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
42
42
|
`)),v=e.content.find(e=>e.type===`image`),y=_.split(`
|
|
43
|
-
`).length,b=!f&&!m&&!h&&_.length>0;return(0,$.jsxs)(`div`,{className:`attachcard ${f?`reference`:``}${m?` page`:``}${h?` conversation`:``}`,children:[(0,$.jsx)(
|
|
44
|
-
`),_=typeof e.tokensBefore==`number`?e.tokensBefore.toLocaleString():null;return(0,$.jsxs)(`div`,{className:`msg msg-compactionSummary`,"data-role":e.role,"data-msg-id":e.id,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:r(`role.compaction`)}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:
|
|
45
|
-
`)&&!t.truncated,i=m===`user`?(0,$.jsx)(al,{text:t.text,hardBreaks:!0}):w||O||E.current?(0,$.jsx)(Tl,{text:t.text,finishing:!w&&O,onSettled:A}):(0,$.jsx)(al,{text:t.text}),a=n?(0,$.jsx)(`button`,{type:`button`,className:`msg-text-copy${b?` copied`:``}`,title:y(b?`copied`:`copyMessage`),"aria-label":y(`copyMessage`),onClick:()=>{x(t.text)},children:b?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})},`msg-text-copy`):null;return(0,$.jsx)(`div`,{className:`msg-text${r?` single`:``}`,children:r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`msg-text-main`,children:i}),a]}):(0,$.jsxs)($.Fragment,{children:[a,i,t.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:y(`truncated`)})]})})}let j=ip(e);if(j)return(0,$.jsx)(Nl,{thinking:j.thinking,streaming:i&&a&&S,wrap:c,forceOpen:d||f});let M=ap(e);if(M){let e={result:t.get(M.id),liveOutput:n.get(M.id)?.text,streaming:i,status:r.get(M.id)};return(0,$.jsx)(Md,{block:M,view:e,onKillBash:s,wrap:l,showImages:u??!0,forceOpen:d||p,uiContextToolCall:g,uiToolCardFooter:_,onUiAction:v})}let N=op(e);if(N&&N.dataUrl){let e=N.dataUrl.startsWith(`/`)?q(N.dataUrl):N.dataUrl;return(0,$.jsx)(`div`,{className:`msg-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:`attachment`})})}let P=sp(e);return P?(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:ys(P.command)}),P.exitCode!==void 0&&(0,$.jsx)(`span`,{className:`bashblock-exit ${P.exitCode===0?`ok`:`err`}`,children:y(`exitCode`,{code:P.exitCode})}),P.cancelled&&(0,$.jsx)(`span`,{className:`bashblock-exit err`,children:y(`cancelled`)})]}),P.output&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:P.output}),P.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:y(`outputTruncated`)})]}):null}function bp(e,t){switch(e){case`user`:return t(`role.user`);case`assistant`:return t(`role.assistant`);case`toolResult`:return t(`role.tool`);case`bashExecution`:return t(`role.bash`);case`branchSummary`:return t(`role.branch`);case`compactionSummary`:return t(`role.compaction`);default:return e}}function xp(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function Sp(e,t){let n=t.assistantMessageEvent,r=e.stats.tokens,i=t.usage===null?r:{...r,...t.usage},a=i===r?e.stats:{...e.stats,tokens:i};if(n.type!==`text_delta`&&n.type!==`thinking_delta`)return a===e.stats?e:{...e,stats:a};let o=n.delta??``;if(!o)return a===e.stats?e:{...e,stats:a};let s=e.streamingMessage??null,c=s&&s.id===t.messageId?{...s,role:s.role??`assistant`}:{id:t.messageId,role:`assistant`,content:[]},l=[...c.content],u=n.type===`thinking_delta`?`thinking`:`text`,d=n.contentIndex??l.length-1;return d>=0&&d<l.length&&l[d].type===u?l[d]=u===`thinking`?{type:`thinking`,thinking:(l[d].thinking??``)+o}:{type:`text`,text:(l[d].text??``)+o}:l.push(u===`thinking`?{type:`thinking`,thinking:o}:{type:`text`,text:o}),{...e,stats:a,streamingMessage:{...c,id:t.messageId,role:`assistant`,content:l}}}function Cp(e,t){let n=e.indexOf(t);return n<0?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function wp(e,t,n){return typeof n==`number`&&Number.isInteger(n)&&n>=0&&n<e.length&&e[n]===t?[...e.slice(0,n),...e.slice(n+1)]:Cp(e,t)}var Tp=`echo-`;function Ep(e){return`${Tp}${e}`}function Dp(e){return typeof e==`string`&&e.startsWith(`echo-`)}function Op(){return{adds:[],removes:[],echoes:[]}}function kp(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Ap(e,t){let n=(t??[]).filter(e=>e.mode===`quote`).map(e=>us(e.quote)).filter(e=>e!==null),r=[],i=[];for(let e of t??[])if(e.mode!==`quote`){if(e.imageData){r.push(e.name||`image.png`);continue}if(e.fileData){let t=e.name||`file`;i.push(`<file path="${kp(t)}" />`);continue}if(e.mode===`page`){let t=e.path||``,n=e.name||t;i.push(`<browser-page url="${kp(t)}" title="${kp(n)}"></browser-page>`);continue}if(e.mode===`canvas`){i.push(`<canvas-ref id="${kp(e.path)}" title="${kp(e.name||e.path)}"></canvas-ref>`);continue}if(e.mode===`conversation`){let t=e.name||e.conversationId||e.sessionPath||`conversation`;i.push(`<conversation-ref title="${kp(t)}"></conversation-ref>`);continue}if(e.path){let t=e.lines?` lines="${e.lines.start}-${e.lines.end}"`:``;i.push(`<file path="${kp(e.path)}"${t} />`)}}return ms(e,i,n,r)}function jp(e){let t=hs(e);return`${t.text.trim()}\u0000${t.quotes.map(e=>`${e.role}:${e.messageId}:${e.text.trim()}`).join(`|`)}`}function Mp(e,t){return e===t||jp(e)===jp(t)}function Np(e,t){let n=0;for(let r of e)Mp(r,t)&&(n+=1);return n}function Pp(e,t){let n=t.trim(),r=0;for(let t of e)t.role===`user`&&(Dp(t.id)||(t.content.find(e=>e.type===`text`)?.text??``).trim()===n&&(r+=1));return r}function Fp(e){let{state:t,text:n,attachments:r,queue:i=!1,goalReviewing:a=!1}=e;if(!t||!t.isStreaming||t.delegateMode===!0)return!1;let o=(n??``).trim(),s=!!(r&&r.length>0);return!(!o&&!s||o.startsWith(`/`)||a&&!i)}function Ip(e){let{state:t,text:n,attachments:r}=e;if(!t||t.isStreaming||t.delegateMode===!0)return!1;let i=(n??``).trim(),a=!!(r&&r.length>0);return!(!i&&!a||i.startsWith(`/`))}function Lp(e,t,n){let r=n.now??Date.now();if(!t||!Ip({state:t,text:n.text,attachments:n.attachments}))return{tracker:e,state:t};let i=(n.text??``).trim(),a=zp(e),o={conversationId:t.conversationId,rawText:i,messageId:Bp(a),baselineUserMsgMatches:Pp(t.messages,i),createdAt:r},s=Vp(o,r);return{tracker:{...e,echoes:[...Rp(e),o]},state:{...t,messages:[...t.messages,s]}}}function Rp(e){return e.echoes??[]}function zp(e){let t=0;for(let n of Rp(e)){let e=Number.parseInt(n.messageId.slice(5),10);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function Bp(e){return Ep(e)}function Vp(e,t){let n=[];return e.rawText&&n.push({type:`text`,text:e.rawText}),{id:e.messageId,role:`user`,content:n,timestamp:t}}function Hp(e,t,n){let r=n.now??Date.now();if(!Fp({state:t,text:n.text,attachments:n.attachments,queue:n.queue,goalReviewing:n.goalReviewing})||!t)return{tracker:e,state:t};let i=t?.engineCapabilities?.steer!==!1&&n.engine!==`dsh`,a=n.queue||!i?`followUp`:`steer`,o=Ap(n.text,n.attachments),s=hs(o).text.trim(),c=a===`steer`?t.queue.steering:t.queue.followUp,l=e.adds.filter(e=>e.conversationId===t.conversationId&&e.kind===a&&Mp(e.formattedText,o)).length,u=Np(c,o),d=Math.max(0,u-l),f=Pp(t.messages,s),p={conversationId:t.conversationId,kind:a,rawText:s,formattedText:o,baselineQueueMatches:d,baselineUserMsgMatches:f,createdAt:r},m=a===`steer`?{...t.queue,steering:[...t.queue.steering,o]}:{...t.queue,followUp:[...t.queue.followUp,o]};return{tracker:{adds:[...e.adds,p],removes:e.removes,echoes:Rp(e)},state:{...t,queue:m}}}function Up(e,t,n){if(!t)return{tracker:e,state:t};let r=n.now??Date.now(),{kind:i,text:a,index:o}=n,s=wp(i===`steer`?t.queue.steering:t.queue.followUp,a,o),c=e.adds,l=c.findIndex(e=>e.conversationId===t.conversationId&&e.kind===i&&Mp(e.formattedText,a));l>=0&&(c=[...c.slice(0,l),...c.slice(l+1)]);let u=Np(s,a),d={conversationId:t.conversationId,kind:i,text:a,index:o,expectedRemainingMatches:u,createdAt:r},f=i===`steer`?{...t.queue,steering:s}:{...t.queue,followUp:s};return{tracker:{adds:c,removes:[...e.removes,d],echoes:Rp(e)},state:{...t,queue:f}}}function Wp(e,t,n=Date.now()){if(e.adds.length===0&&e.removes.length===0)return{tracker:e,state:t};let r=t.conversationId;if(!t.isStreaming){let i=e.adds.filter(e=>e.conversationId!==r&&n-e.createdAt<15e3),a=e.removes.filter(e=>e.conversationId!==r&&n-e.createdAt<3e3);return i.length===e.adds.length&&a.length===e.removes.length?{tracker:e,state:t}:{tracker:{...e,adds:i,removes:a},state:t}}let i=[...t.queue.steering],a=[...t.queue.followUp],o=!1,s=[];for(let t of e.removes){if(n-t.createdAt>=3e3)continue;if(t.conversationId!==r){s.push(t);continue}let e=t.kind===`steer`?i:a;if(Np(e,t.text)>t.expectedRemainingMatches){let n=wp(e,t.text,t.index);if(n.length===e.length){let r=e.findIndex(e=>Mp(e,t.text));r>=0&&(n=[...e.slice(0,r),...e.slice(r+1)])}t.kind===`steer`?i=n:a=n,o=!0,s.push(t)}}let c=[],l=new Map;for(let s of e.adds){if(n-s.createdAt>=15e3)continue;if(s.conversationId!==r){c.push(s);continue}let e=s.kind===`steer`?i:a,u=`${s.kind}:${jp(s.formattedText)}`,d=l.get(u)??0,f=Np(e,s.formattedText),p=Pp(t.messages,s.rawText),m=f>s.baselineQueueMatches+d,h=p>s.baselineUserMsgMatches;if(m){l.set(u,d+1);continue}h||(s.kind===`steer`?i.push(s.formattedText):a.push(s.formattedText),l.set(u,d+1),o=!0,c.push(s))}let u=c.length===e.adds.length&&s.length===e.removes.length?e:{...e,adds:c,removes:s};return o?{tracker:u,state:{...t,queue:{steering:i,followUp:a}}}:{tracker:u,state:t}}function Gp(e,t){if(!t)return{tracker:e,state:t};let n=t.conversationId,r=e.adds.filter(e=>e.conversationId===n),i=Rp(e).filter(e=>e.conversationId===n);if(r.length===0&&i.length===0)return{tracker:e,state:t};let a=[...t.queue.steering],o=[...t.queue.followUp];for(let e of r)e.kind===`steer`?a=wp(a,e.formattedText):o=wp(o,e.formattedText);let s=new Set(i.map(e=>e.messageId)),c=s.size>0?t.messages.filter(e=>!s.has(e.id)):t.messages;return{tracker:{adds:e.adds.filter(e=>e.conversationId!==n),removes:e.removes,echoes:Rp(e).filter(e=>e.conversationId!==n)},state:{...t,queue:{steering:a,followUp:o},messages:c}}}function Kp(e,t,n=Date.now()){if(Rp(e).length===0)return{tracker:e,state:t};if(t.isStreaming){let r=new Set,i=[];for(let a of Rp(e)){if(n-a.createdAt>=15e3){a.conversationId===t.conversationId&&r.add(a.messageId);continue}a.conversationId===t.conversationId?r.add(a.messageId):i.push(a)}let a=i.length===Rp(e).length?e:{...e,echoes:i};return r.size===0?{tracker:a,state:t}:{tracker:a,state:{...t,messages:t.messages.filter(e=>!r.has(e.id))}}}let r=t.conversationId,i=[],a=new Set,o=[];for(let s of Rp(e)){if(n-s.createdAt>=15e3){s.conversationId===r&&a.add(s.messageId);continue}if(s.conversationId!==r){i.push(s);continue}if(Pp(t.messages,s.rawText)>s.baselineUserMsgMatches){a.add(s.messageId);continue}i.push(s),t.messages.some(e=>e.id===s.messageId)||o.push(Vp(s,s.createdAt))}let s=i.length===Rp(e).length?e:{adds:e.adds,removes:e.removes,echoes:i};if(a.size===0&&o.length===0)return{tracker:s,state:t};let c=a.size>0?t.messages.filter(e=>!a.has(e.id)):[...t.messages];return{tracker:s,state:{...t,messages:o.length>0?[...c,...o]:c}}}function qp(e){let{current:t,source:n,snapshot:r,answered:i,activeConversationId:a}=e,o=!!(r?.conversationId&&a&&r.conversationId!==a);return r&&r.id&&!i.has(r.id)&&!o?t?.id===r.id?{changed:!1,question:t,source:n}:{changed:!0,question:r,source:`snapshot`}:t&&t.conversationId&&a&&t.conversationId!==a||!r&&t&&n===`snapshot`&&!o?{changed:!0,question:null,source:`live`}:{changed:!1,question:t,source:n}}var Jp=new Set,Yp=1048576,Xp=null,Zp=[],Qp=0;function $p(e=null){Xp=e,Zp=[],Qp=0}function em(e){if(Jp.add(e),Xp!==null&&Zp.length){let t=Xp,n=Zp;Zp=[],Qp=0;for(let r of n)e(t,r)}return()=>{Jp.delete(e)}}function tm(e,t){if(e===Xp){if(!Jp.size){Qp+t.length>Yp&&(Zp=[],Qp=0),t.length<=Yp&&(Zp.push(t),Qp+=t.length);return}for(let n of Jp)try{n(e,t)}catch(e){console.error(`[tui-overlay-bridge] listener error:`,e)}}}function nm(e){let t=typeof e.name==`string`?e.name:``;if(e.unsupported===!0)return{name:t,status:`unsupported`};if(e.found!==!0)return{name:t,status:`missing`};let n={name:t,status:`ready`};return e.defaultDescription&&(n.defaultDescription=e.defaultDescription),e.defaultPromptSnippet&&(n.defaultPromptSnippet=e.defaultPromptSnippet),Array.isArray(e.defaultPromptGuidelines)&&e.defaultPromptGuidelines.length>0&&(n.defaultPromptGuidelines=e.defaultPromptGuidelines),e.override&&(n.override=e.override),n}var rm={},im=new Set;function am(){for(let e of im)e()}function om(e){let t=(e??``).trim();t&&(rm[t]&&rm[t].status!==`loading`||(rm={...rm,[t]:{name:t,status:`loading`}},am(),Z({type:`get_tool_prompt`,name:t})))}function sm(e){let t=typeof e.name==`string`?e.name:``;t&&rm[t]&&(rm={...rm,[t]:nm(e)},am())}function cm(e){if(!rm[e])return;let t={...rm};delete t[e],rm=t,am()}function lm(e){return im.add(e),()=>im.delete(e)}function um(e){return(0,Q.useSyncExternalStore)(lm,()=>e?rm[e]??null:null)}function dm(e,t){if(!t?.isolated)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};let n=e.shadowRoot;if(!n)try{n=e.attachShadow({mode:`open`})}catch{n=e.shadowRoot}if(!n)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};n.replaceChildren();let r=document.createElement(`style`);r.textContent=`
|
|
43
|
+
`).length,b=!f&&!m&&!h&&_.length>0;return(0,$.jsxs)(`div`,{className:`attachcard ${f?`reference`:``}${m?` page`:``}${h?` conversation`:``}`,children:[(0,$.jsx)(Ol,{open:s,headClassName:`attachcard-head`,titleText:n(s?`collapseMsg`:`expandMsg`),onToggle:()=>i(e=>t?!0:!e),toggle:!f&&!m&&!h?(0,$.jsx)(`span`,{className:`chead-toggle`,children:s?(0,$.jsx)(pe,{}):(0,$.jsx)(P,{})}):null,icon:d?`◈`:u?`📁`:m?`🌐`:h?`💬`:`📎`,iconClassName:`attachcard-icon`,titleClassName:`attachcard-name`,after:(0,$.jsxs)($.Fragment,{children:[c.path&&(m&&g?(0,$.jsx)(`a`,{className:`attachcard-path attachcard-link`,href:g,target:`_blank`,rel:`noreferrer`,children:c.path}):(0,$.jsx)(`span`,{className:`attachcard-path`,children:c.path})),(0,$.jsx)(`span`,{className:`attachcard-mode ${c.mode===`lines`?`lines`:f?`ref`:m?`page`:h?`conversation`:p?`bridged`:`inline`}`,children:d?n(`canvasTab`):m?n(`attachPageShort`):h?n(`attachConversationShort`):f?u?n(`folderRefShort`):`${n(`refOnlyShort`)} · ${lf(c.size)}`:p?n(`bridgedVision`):v?n(`image`):c.mode===`lines`?n(`inlineLinesRange`,{start:c.startLine??1,end:c.endLine??c.lines??1}):n(`inlineLines`,{n:c.lines??y})}),b&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(a?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:e=>{e.stopPropagation(),o(_)},children:a?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})})]}),children:l}),!f&&s&&(()=>{let e=v?.dataUrl?v.dataUrl.startsWith(`/`)?q(v.dataUrl):v.dataUrl:void 0;return p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`attachcard-bridgenote`,children:n(`bridgedVisionDetail`)}),e&&(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:l})}),_&&(0,$.jsx)(`pre`,{className:`attachcard-content`,children:_})]}):e?(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:l})}):(0,$.jsx)(`pre`,{className:`attachcard-content`,children:_})})(),f&&(0,$.jsx)(`div`,{className:`attachcard-refnote`,children:u?n(`folderNotExpanded`):n(`fileNotExpanded`,{size:lf(c.size)})})]})}function _p(e){let t=e.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(t)return t[1].trim();let n=e.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():e.trim()}function vp({message:e,forceOpen:t=!1,autoExpand:n=!1}){let r=V(),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=ac({duration:1200}),[c,l]=(0,Q.useState)(n);n!==c&&(l(n),n&&a(!0));let d=i||t,f=Xd(e.id),[p,m]=(0,Q.useState)(!1),h=()=>{p?m(!1):(m(!0),f.status===`idle`&&Kd(e.id))},g=e.content.map(e=>ap(e)?.text??``).filter(Boolean).join(`
|
|
44
|
+
`),_=typeof e.tokensBefore==`number`?e.tokensBefore.toLocaleString():null;return(0,$.jsxs)(`div`,{className:`msg msg-compactionSummary`,"data-role":e.role,"data-msg-id":e.id,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:r(`role.compaction`)}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:Cp(e.timestamp)})]}),(0,$.jsxs)(`div`,{className:`compaction-card${i?` expanded`:``}`,children:[(0,$.jsx)(Ol,{open:d,headClassName:`compaction-head`,titleText:r(d?`collapseMsg`:`expandMsg`),onToggle:()=>a(e=>t?!0:!e),toggle:(0,$.jsx)(`span`,{className:`chead-toggle`,children:d?(0,$.jsx)(pe,{}):(0,$.jsx)(P,{})}),icon:(0,$.jsx)(Pe,{}),iconClassName:`compaction-icon`,titleClassName:`compaction-title`,after:g&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:r(o?`copied`:`copyMessage`),"aria-label":r(`copyMessage`),onClick:e=>{e.stopPropagation(),s(g)},children:o?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})}),children:_?r(`compactionFrom`,{tokens:_}):r(`role.compaction`)}),d&&(0,$.jsxs)(`div`,{className:`compaction-body`,children:[(0,$.jsx)(sl,{text:g}),(0,$.jsx)(`div`,{className:`compaction-hint`,children:r(`compactionKeptHint`)}),(0,$.jsx)(`div`,{className:`compacted-history-action`,children:(0,$.jsxs)(`button`,{type:`button`,className:`compacted-history-toggle-btn`,onClick:h,"aria-expanded":p,children:[(0,$.jsx)(`span`,{className:`compacted-history-chevron`,children:p?(0,$.jsx)(pe,{}):(0,$.jsx)(P,{})}),(0,$.jsx)(u,{className:`compacted-history-clock-icon`}),(0,$.jsx)(`span`,{className:`compacted-history-btn-text`,children:r(p?`hideCompactedHistory`:`viewCompactedHistory`)}),f.status===`ready`&&f.messages.length>0&&(0,$.jsx)(`span`,{className:`compacted-history-count-pill`,children:r(`compactedHistoryTurns`,{count:f.messages.length})})]})}),p&&(0,$.jsxs)(`div`,{className:`compacted-history-panel`,children:[f.status===`loading`&&(0,$.jsxs)(`div`,{className:`compacted-history-loading`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsx)(`span`,{children:r(`compactedHistoryLoading`)})]}),f.status===`error`&&(0,$.jsx)(`div`,{className:`compacted-history-error`,children:(0,$.jsx)(`span`,{children:f.error===`compactedHistoryNotFound`||f.error===`Compaction entry not found`?r(`compactedHistoryNotFound`):f.error||r(`compactedHistoryEmpty`)})}),f.status===`ready`&&f.messages.length===0&&(0,$.jsx)(`div`,{className:`compacted-history-empty`,children:r(`compactedHistoryEmpty`)}),f.status===`ready`&&f.messages.length>0&&(0,$.jsx)(yp,{messages:f.messages})]})]})]})]})}function yp({messages:e}){let t=V(),n=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e)n.role===`toolResult`&&n.toolCallId&&t.set(n.toolCallId,n);return t},[e]),r=(0,Q.useMemo)(()=>new Map,[]);return(0,$.jsxs)(`div`,{className:`compacted-history-stream`,children:[(0,$.jsxs)(`div`,{className:`compacted-history-stream-header`,children:[(0,$.jsxs)(`span`,{className:`compacted-history-badge`,children:[(0,$.jsx)(Pe,{}),` `,t(`compactedHistoryBadge`)]}),(0,$.jsx)(`span`,{className:`compacted-history-count`,children:t(`compactedHistoryTurns`,{count:e.length})})]}),(0,$.jsx)(`div`,{className:`compacted-history-messages`,children:e.map(e=>(0,$.jsx)(hp,{message:e,toolResults:n,liveOutputs:r,toolStatuses:r,streaming:!1,isLast:!1,readOnly:!0},e.id))})]})}function bp({block:e,forceOpen:t=!1}){let n=V(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=ac({duration:1200}),s=r||t;return(0,$.jsxs)(`div`,{className:`skillcard${r?` expanded`:``}`,children:[(0,$.jsx)(Ol,{open:s,headClassName:`skillcard-head`,titleText:e.location,onToggle:()=>i(e=>t?!0:!e),toggle:(0,$.jsx)(`span`,{className:`chead-toggle`,children:s?(0,$.jsx)(pe,{}):(0,$.jsx)(P,{})}),icon:(0,$.jsx)(Le,{}),iconClassName:`skillcard-icon`,titleClassName:`skillcard-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`skillcard-path`,children:e.location}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(a?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:t=>{t.stopPropagation(),o(e.content)},children:a?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})})]}),children:e.name}),s&&(0,$.jsx)(`div`,{className:`skillcard-body`,children:(0,$.jsx)(sl,{text:e.content})})]})}function xp({block:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:o,onKillBash:s,thinkingWrap:c,toolsWrap:l,toolImages:u,searchActive:d,forceThinking:f,forceTools:p,role:m,showCopy:h,uiContextToolCall:g,uiToolCardFooter:_,onUiAction:v}){let y=V(),{copied:b,copy:x}=ac({duration:1200}),S=o??!0,C=ap(e),w=!!(C&&i&&a&&S),T=(0,Q.useRef)(w);T.current=w;let E=(0,Q.useRef)(w);w&&(E.current=!0);let D=()=>typeof document<`u`&&document.hidden,[O,k]=(0,Q.useState)(()=>w&&!D());(0,Q.useEffect)(()=>{w&&!D()?k(!0):!w&&D()&&k(!1)},[w]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{T.current||k(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let A=(0,Q.useCallback)(()=>{T.current||k(!1)},[]);if(C){let e=m===`user`?C.text:ip(C.text,w);if(!e.trim())return null;let t=e===C.text?C:{...C,text:e},n=(m===`assistant`||m===`user`)&&h!==!1,r=n&&!t.text.includes(`
|
|
45
|
+
`)&&!t.truncated,i=m===`user`?(0,$.jsx)(sl,{text:t.text,hardBreaks:!0}):w||O||E.current?(0,$.jsx)(Dl,{text:t.text,finishing:!w&&O,onSettled:A}):(0,$.jsx)(sl,{text:t.text}),a=n?(0,$.jsx)(`button`,{type:`button`,className:`msg-text-copy${b?` copied`:``}`,title:y(b?`copied`:`copyMessage`),"aria-label":y(`copyMessage`),onClick:()=>{x(t.text)},children:b?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{})},`msg-text-copy`):null;return(0,$.jsx)(`div`,{className:`msg-text${r?` single`:``}`,children:r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`msg-text-main`,children:i}),a]}):(0,$.jsxs)($.Fragment,{children:[a,i,t.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:y(`truncated`)})]})})}let j=op(e);if(j)return(0,$.jsx)(Fl,{thinking:j.thinking,streaming:i&&a&&S,wrap:c,forceOpen:d||f});let M=sp(e);if(M){let e={result:t.get(M.id),liveOutput:n.get(M.id)?.text,streaming:i,status:r.get(M.id)};return(0,$.jsx)(Pd,{block:M,view:e,onKillBash:s,wrap:l,showImages:u??!0,forceOpen:d||p,uiContextToolCall:g,uiToolCardFooter:_,onUiAction:v})}let N=cp(e);if(N&&N.dataUrl){let e=N.dataUrl.startsWith(`/`)?q(N.dataUrl):N.dataUrl;return(0,$.jsx)(`div`,{className:`msg-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:`attachment`})})}let P=lp(e);return P?(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:xs(P.command)}),P.exitCode!==void 0&&(0,$.jsx)(`span`,{className:`bashblock-exit ${P.exitCode===0?`ok`:`err`}`,children:y(`exitCode`,{code:P.exitCode})}),P.cancelled&&(0,$.jsx)(`span`,{className:`bashblock-exit err`,children:y(`cancelled`)})]}),P.output&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:P.output}),P.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:y(`outputTruncated`)})]}):null}function Sp(e,t){switch(e){case`user`:return t(`role.user`);case`assistant`:return t(`role.assistant`);case`toolResult`:return t(`role.tool`);case`bashExecution`:return t(`role.bash`);case`branchSummary`:return t(`role.branch`);case`compactionSummary`:return t(`role.compaction`);default:return e}}function Cp(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function wp(e,t){let n=t.assistantMessageEvent,r=e.stats.tokens,i=t.usage===null?r:{...r,...t.usage},a=i===r?e.stats:{...e.stats,tokens:i};if(n.type!==`text_delta`&&n.type!==`thinking_delta`)return a===e.stats?e:{...e,stats:a};let o=n.delta??``;if(!o)return a===e.stats?e:{...e,stats:a};let s=e.streamingMessage??null,c=s&&s.id===t.messageId?{...s,role:s.role??`assistant`}:{id:t.messageId,role:`assistant`,content:[]},l=[...c.content],u=n.type===`thinking_delta`?`thinking`:`text`,d=n.contentIndex??l.length-1;return d>=0&&d<l.length&&l[d].type===u?l[d]=u===`thinking`?{type:`thinking`,thinking:(l[d].thinking??``)+o}:{type:`text`,text:(l[d].text??``)+o}:l.push(u===`thinking`?{type:`thinking`,thinking:o}:{type:`text`,text:o}),{...e,stats:a,streamingMessage:{...c,id:t.messageId,role:`assistant`,content:l}}}function Tp(e,t){let n=e.indexOf(t);return n<0?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function Ep(e,t,n){return typeof n==`number`&&Number.isInteger(n)&&n>=0&&n<e.length&&e[n]===t?[...e.slice(0,n),...e.slice(n+1)]:Tp(e,t)}var Dp=`echo-`;function Op(e){return`${Dp}${e}`}function kp(e){return typeof e==`string`&&e.startsWith(`echo-`)}function Ap(){return{adds:[],removes:[],echoes:[]}}function jp(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Mp(e,t){let n=(t??[]).filter(e=>e.mode===`quote`).map(e=>fs(e.quote)).filter(e=>e!==null),r=[],i=[];for(let e of t??[])if(e.mode!==`quote`){if(e.imageData){r.push(e.name||`image.png`);continue}if(e.fileData){let t=e.name||`file`;i.push(`<file path="${jp(t)}" />`);continue}if(e.mode===`page`){let t=e.path||``,n=e.name||t;i.push(`<browser-page url="${jp(t)}" title="${jp(n)}"></browser-page>`);continue}if(e.mode===`canvas`){i.push(`<canvas-ref id="${jp(e.path)}" title="${jp(e.name||e.path)}"></canvas-ref>`);continue}if(e.mode===`conversation`){let t=e.name||e.conversationId||e.sessionPath||`conversation`;i.push(`<conversation-ref title="${jp(t)}"></conversation-ref>`);continue}if(e.path){let t=e.lines?` lines="${e.lines.start}-${e.lines.end}"`:``;i.push(`<file path="${jp(e.path)}"${t} />`)}}return gs(e,i,n,r)}function Np(e){let t=_s(e);return`${t.text.trim()}\u0000${t.quotes.map(e=>`${e.role}:${e.messageId}:${e.text.trim()}`).join(`|`)}`}function Pp(e,t){return e===t||Np(e)===Np(t)}function Fp(e,t){let n=0;for(let r of e)Pp(r,t)&&(n+=1);return n}function Ip(e,t){let n=t.trim(),r=0;for(let t of e)t.role===`user`&&(kp(t.id)||(t.content.find(e=>e.type===`text`)?.text??``).trim()===n&&(r+=1));return r}function Lp(e){let{state:t,text:n,attachments:r,queue:i=!1,goalReviewing:a=!1}=e;if(!t||!t.isStreaming||t.delegateMode===!0)return!1;let o=(n??``).trim(),s=!!(r&&r.length>0);return!(!o&&!s||o.startsWith(`/`)||a&&!i)}function Rp(e){let{state:t,text:n,attachments:r}=e;if(!t||t.isStreaming||t.delegateMode===!0)return!1;let i=(n??``).trim(),a=!!(r&&r.length>0);return!(!i&&!a||i.startsWith(`/`))}function zp(e,t,n){let r=n.now??Date.now();if(!t||!Rp({state:t,text:n.text,attachments:n.attachments}))return{tracker:e,state:t};let i=(n.text??``).trim(),a=Vp(e),o={conversationId:t.conversationId,rawText:i,messageId:Hp(a),baselineUserMsgMatches:Ip(t.messages,i),createdAt:r},s=Up(o,r);return{tracker:{...e,echoes:[...Bp(e),o]},state:{...t,messages:[...t.messages,s]}}}function Bp(e){return e.echoes??[]}function Vp(e){let t=0;for(let n of Bp(e)){let e=Number.parseInt(n.messageId.slice(5),10);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function Hp(e){return Op(e)}function Up(e,t){let n=[];return e.rawText&&n.push({type:`text`,text:e.rawText}),{id:e.messageId,role:`user`,content:n,timestamp:t}}function Wp(e,t,n){let r=n.now??Date.now();if(!Lp({state:t,text:n.text,attachments:n.attachments,queue:n.queue,goalReviewing:n.goalReviewing})||!t)return{tracker:e,state:t};let i=t?.engineCapabilities?.steer!==!1&&n.engine!==`dsh`,a=n.queue||!i?`followUp`:`steer`,o=Mp(n.text,n.attachments),s=_s(o).text.trim(),c=a===`steer`?t.queue.steering:t.queue.followUp,l=e.adds.filter(e=>e.conversationId===t.conversationId&&e.kind===a&&Pp(e.formattedText,o)).length,u=Fp(c,o),d=Math.max(0,u-l),f=Ip(t.messages,s),p={conversationId:t.conversationId,kind:a,rawText:s,formattedText:o,baselineQueueMatches:d,baselineUserMsgMatches:f,createdAt:r},m=a===`steer`?{...t.queue,steering:[...t.queue.steering,o]}:{...t.queue,followUp:[...t.queue.followUp,o]};return{tracker:{adds:[...e.adds,p],removes:e.removes,echoes:Bp(e)},state:{...t,queue:m}}}function Gp(e,t,n){if(!t)return{tracker:e,state:t};let r=n.now??Date.now(),{kind:i,text:a,index:o}=n,s=Ep(i===`steer`?t.queue.steering:t.queue.followUp,a,o),c=e.adds,l=c.findIndex(e=>e.conversationId===t.conversationId&&e.kind===i&&Pp(e.formattedText,a));l>=0&&(c=[...c.slice(0,l),...c.slice(l+1)]);let u=Fp(s,a),d={conversationId:t.conversationId,kind:i,text:a,index:o,expectedRemainingMatches:u,createdAt:r},f=i===`steer`?{...t.queue,steering:s}:{...t.queue,followUp:s};return{tracker:{adds:c,removes:[...e.removes,d],echoes:Bp(e)},state:{...t,queue:f}}}function Kp(e,t,n=Date.now()){if(e.adds.length===0&&e.removes.length===0)return{tracker:e,state:t};let r=t.conversationId;if(!t.isStreaming){let i=e.adds.filter(e=>e.conversationId!==r&&n-e.createdAt<15e3),a=e.removes.filter(e=>e.conversationId!==r&&n-e.createdAt<3e3);return i.length===e.adds.length&&a.length===e.removes.length?{tracker:e,state:t}:{tracker:{...e,adds:i,removes:a},state:t}}let i=[...t.queue.steering],a=[...t.queue.followUp],o=!1,s=[];for(let t of e.removes){if(n-t.createdAt>=3e3)continue;if(t.conversationId!==r){s.push(t);continue}let e=t.kind===`steer`?i:a;if(Fp(e,t.text)>t.expectedRemainingMatches){let n=Ep(e,t.text,t.index);if(n.length===e.length){let r=e.findIndex(e=>Pp(e,t.text));r>=0&&(n=[...e.slice(0,r),...e.slice(r+1)])}t.kind===`steer`?i=n:a=n,o=!0,s.push(t)}}let c=[],l=new Map;for(let s of e.adds){if(n-s.createdAt>=15e3)continue;if(s.conversationId!==r){c.push(s);continue}let e=s.kind===`steer`?i:a,u=`${s.kind}:${Np(s.formattedText)}`,d=l.get(u)??0,f=Fp(e,s.formattedText),p=Ip(t.messages,s.rawText),m=f>s.baselineQueueMatches+d,h=p>s.baselineUserMsgMatches;if(m){l.set(u,d+1);continue}h||(s.kind===`steer`?i.push(s.formattedText):a.push(s.formattedText),l.set(u,d+1),o=!0,c.push(s))}let u=c.length===e.adds.length&&s.length===e.removes.length?e:{...e,adds:c,removes:s};return o?{tracker:u,state:{...t,queue:{steering:i,followUp:a}}}:{tracker:u,state:t}}function qp(e,t){if(!t)return{tracker:e,state:t};let n=t.conversationId,r=e.adds.filter(e=>e.conversationId===n),i=Bp(e).filter(e=>e.conversationId===n);if(r.length===0&&i.length===0)return{tracker:e,state:t};let a=[...t.queue.steering],o=[...t.queue.followUp];for(let e of r)e.kind===`steer`?a=Ep(a,e.formattedText):o=Ep(o,e.formattedText);let s=new Set(i.map(e=>e.messageId)),c=s.size>0?t.messages.filter(e=>!s.has(e.id)):t.messages;return{tracker:{adds:e.adds.filter(e=>e.conversationId!==n),removes:e.removes,echoes:Bp(e).filter(e=>e.conversationId!==n)},state:{...t,queue:{steering:a,followUp:o},messages:c}}}function Jp(e,t,n=Date.now()){if(Bp(e).length===0)return{tracker:e,state:t};if(t.isStreaming){let r=new Set,i=[];for(let a of Bp(e)){if(n-a.createdAt>=15e3){a.conversationId===t.conversationId&&r.add(a.messageId);continue}a.conversationId===t.conversationId?r.add(a.messageId):i.push(a)}let a=i.length===Bp(e).length?e:{...e,echoes:i};return r.size===0?{tracker:a,state:t}:{tracker:a,state:{...t,messages:t.messages.filter(e=>!r.has(e.id))}}}let r=t.conversationId,i=[],a=new Set,o=[];for(let s of Bp(e)){if(n-s.createdAt>=15e3){s.conversationId===r&&a.add(s.messageId);continue}if(s.conversationId!==r){i.push(s);continue}if(Ip(t.messages,s.rawText)>s.baselineUserMsgMatches){a.add(s.messageId);continue}i.push(s),t.messages.some(e=>e.id===s.messageId)||o.push(Up(s,s.createdAt))}let s=i.length===Bp(e).length?e:{adds:e.adds,removes:e.removes,echoes:i};if(a.size===0&&o.length===0)return{tracker:s,state:t};let c=a.size>0?t.messages.filter(e=>!a.has(e.id)):[...t.messages];return{tracker:s,state:{...t,messages:o.length>0?[...c,...o]:c}}}function Yp(e){let{current:t,source:n,snapshot:r,answered:i,activeConversationId:a}=e,o=!!(r?.conversationId&&a&&r.conversationId!==a);return r&&r.id&&!i.has(r.id)&&!o?t?.id===r.id?{changed:!1,question:t,source:n}:{changed:!0,question:r,source:`snapshot`}:t&&t.conversationId&&a&&t.conversationId!==a||!r&&t&&n===`snapshot`&&!o?{changed:!0,question:null,source:`live`}:{changed:!1,question:t,source:n}}var Xp=new Set,Zp=1048576,Qp=null,$p=[],em=0;function tm(e=null){Qp=e,$p=[],em=0}function nm(e){if(Xp.add(e),Qp!==null&&$p.length){let t=Qp,n=$p;$p=[],em=0;for(let r of n)e(t,r)}return()=>{Xp.delete(e)}}function rm(e,t){if(e===Qp){if(!Xp.size){em+t.length>Zp&&($p=[],em=0),t.length<=Zp&&($p.push(t),em+=t.length);return}for(let n of Xp)try{n(e,t)}catch(e){console.error(`[tui-overlay-bridge] listener error:`,e)}}}function im(e){let t=typeof e.name==`string`?e.name:``;if(e.unsupported===!0)return{name:t,status:`unsupported`};if(e.found!==!0)return{name:t,status:`missing`};let n={name:t,status:`ready`};return e.defaultDescription&&(n.defaultDescription=e.defaultDescription),e.defaultPromptSnippet&&(n.defaultPromptSnippet=e.defaultPromptSnippet),Array.isArray(e.defaultPromptGuidelines)&&e.defaultPromptGuidelines.length>0&&(n.defaultPromptGuidelines=e.defaultPromptGuidelines),e.override&&(n.override=e.override),n}var am={},om=new Set;function sm(){for(let e of om)e()}function cm(e){let t=(e??``).trim();t&&(am[t]&&am[t].status!==`loading`||(am={...am,[t]:{name:t,status:`loading`}},sm(),Z({type:`get_tool_prompt`,name:t})))}function lm(e){let t=typeof e.name==`string`?e.name:``;t&&am[t]&&(am={...am,[t]:im(e)},sm())}function um(e){if(!am[e])return;let t={...am};delete t[e],am=t,sm()}function dm(e){return om.add(e),()=>om.delete(e)}function fm(e){return(0,Q.useSyncExternalStore)(dm,()=>e?am[e]??null:null)}function pm(e,t){if(!t?.isolated)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};let n=e.shadowRoot;if(!n)try{n=e.attachShadow({mode:`open`})}catch{n=e.shadowRoot}if(!n)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};n.replaceChildren();let r=document.createElement(`style`);r.textContent=`
|
|
46
46
|
:host {
|
|
47
47
|
display: block;
|
|
48
48
|
width: 100%;
|
|
@@ -56,30 +56,30 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,$t as n,A as r,
|
|
|
56
56
|
*, *::before, *::after {
|
|
57
57
|
box-sizing: inherit;
|
|
58
58
|
}
|
|
59
|
-
`,n.appendChild(r);let i=document.createElement(`div`);return i.className=`plugin-isolated-root`,i.style.cssText=`width:100%;height:100%;display:flex;flex-direction:column;`,n.appendChild(i),{container:i,isShadow:!0,cleanup:()=>{i.replaceChildren(),n?.replaceChildren()}}}var fm=`pi-web-ui:plugin-data`;function pm(e,t){window.dispatchEvent(new CustomEvent(fm,{detail:{pluginId:e,payload:t}}))}function mm(e){let t=t=>{let n=t.detail;e(n.pluginId,n.payload)};return window.addEventListener(fm,t),()=>window.removeEventListener(fm,t)}var hm=new Map,gm=new Set,_m=new Set,vm=new Set,ym=new Set,bm=-1;function xm(){return[...hm.values()]}function Sm(){let e=xm();for(let t of _m)t(e)}function Cm(){let e=[...vm];for(let t of ym)t(e)}function wm(e){return ym.add(e),e([...vm]),()=>ym.delete(e)}async function Tm(e,t){vm.delete(e.id),Dm.set(e.id,(Dm.get(e.id)??0)+1),Cm();let n=await Mm(e,t);return Sm(),n}function Em(e){return _m.add(e),e(xm()),()=>_m.delete(e)}var Dm=new Map;function Om(e,t){let n=Dm.get(e)??0;return q(`/plugins/${encodeURIComponent(e)}/client/entry.mjs?e=${t}${n>0?`&r=${n}`:``}`)}function km(e){let t=Promise.resolve();return(n,r)=>{let i=t.then(()=>Lt(n,()=>e(r)));return t=i.then(()=>void 0,()=>void 0),i}}var Am=km(e=>Os(()=>import(e),[],import.meta.url));async function jm(e,t){if(!e.hasClient||e.error)return null;try{let n=await Am(e.id,Om(e.id,t)),r=n.default??n;return{...r,fileHandlers:r.fileHandlers??n.fileHandlers}}catch(t){return console.error(`[plugin:${e.id}] 客户端 bundle 加载失败:`,t),null}}async function Mm(e,t){try{let n=(await Am(e.id,Om(e.id,t))).default;return n&&typeof n.mount==`function`?(hm.set(e.id,{info:e,module:n}),!0):e.preload?(gm.add(e.id),!0):(vm.add(e.id),Cm(),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(t){return vm.add(e.id),Cm(),console.error(`[plugin:${e.id}] 客户端加载失败:`,t),!1}}async function Nm(e,t){if(hm.has(e.id)||gm.has(e.id))return!0;if(vm.has(e.id)||!e.hasClient)return!1;let n=await Mm(e,t);return Sm(),n}async function Pm(e,t){t!==bm&&(bm=t,hm.clear(),gm.clear(),vm.clear(),Dm.clear(),Cm());let n=new Set(e.map(e=>e.id));for(let e of[...hm.keys()])n.has(e)||hm.delete(e);for(let e of[...gm])n.has(e)||gm.delete(e);for(let e of[...vm])n.has(e)||vm.delete(e);Cm(),await Promise.all(e.filter(e=>e.hasClient&&(e.view!==!1||e.preload)&&!e.error&&!hm.has(e.id)&&!gm.has(e.id)&&!vm.has(e.id)).map(e=>Mm(e,t))),Sm()}function Fm(e,t){return{pluginId:e,send:n=>t({type:`plugin_message`,pluginId:e,payload:n}),onData:t=>mm((n,r)=>{n===e&&t(r)})}}var Im=[`debug`,`info`,`warn`,`error`];function Lm(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`get`}}}function Rm(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`clear`}}}function zm(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.__host!==`logs`||!Array.isArray(t.logs)?!1:t.logs.every(e=>!!e&&typeof e==`object`&&typeof e.ts==`number`&&typeof e.text==`string`&&Im.includes(String(e.level)))}var Bm=new Map,Vm=new Set;function Hm(){for(let e of[...Vm])try{e()}catch{}}function Um(e){return Vm.add(e),()=>Vm.delete(e)}function Wm(e){return(Bm.get(e)??[]).map(e=>({...e}))}function Gm(e,t){return zm(t)?(Bm.set(e,t.logs.map(e=>({ts:e.ts,level:e.level,text:e.text}))),Hm(),!0):!1}function Km(e,t){let n=e.historyStart??0;return t.resyncRequired===!0||t.historyGeneration!==e.historyGeneration||t.historyStart+t.messages.length!==n||t.before!==void 0&&t.before!==n||t.historyGeneration!==void 0&&(t.before!==n||t.beforeId!==e.messages[0]?.id)}function qm(e,t){if(Km(e,t))return null;let n=e.historyStart??0,r=e.historyTotal??e.messages.length;return t.messages.length===0?t.historyStart===n&&t.historyTotal===r?null:{...e,historyStart:t.historyStart,historyTotal:t.historyTotal}:{...e,messages:[...t.messages,...e.messages],historyStart:t.historyStart,historyTotal:t.historyTotal}}function Jm(e){let t=Math.max(0,e.historyStart??0);return e.isPagingActive?Math.max(0,e.totalMessages-Math.min(e.totalMessages,e.visibleCount))+t:t}function Ym(e){switch(e){case`error`:return 6500;case`warning`:return 4200;default:return 2400}}var Xm=[/^(已在工作目录|正在切换到工作目录|已切换到工作目录)[::]/,/^(Already in directory|Switching to directory|Switched to directory):/i,/该项目最近的对话.*(为你停在了空白新对话|为你停在了新对话)/,/The most recent conversation .* landed on a (blank|new) chat/i,/^分层上下文预算裁剪生效/,/^Tiered context budget pruning/i,/^发现 \d+ 个内置插件有更新可用/,/^\d+ built-in plugin\(s\) have updates available/i,/^已(创建文件|创建文件夹|重命名|删除|移动|复制)[::]/,/^(Created file|Created folder|Renamed|Deleted|Moved|Copied):/i,/^已重命名当前会话为/,/^Renamed current session to/i,/的消息正在投递,已为你保留该对话$/,/is still sending your message — kept in the running list$/i,/^(计划模式已开启|计划模式已关闭|已进入计划模式|已退出计划模式|审查者模式已开启|审查者模式已关闭)/,/^(Plan mode (enabled|disabled)|Entered plan mode|Exited plan mode|Delegate mode (enabled|disabled))/i,/^已切换(智能体预设|权限预设)/,/^Switched (agent|permission) preset/i];function Zm(e){if(e.level!==`info`)return!1;let t=(e.text??``).trim(),n=(e.textEn??``).trim();return Xm.some(e=>t&&e.test(t)||n&&e.test(n))}function Qm(e,t,n=2){if(Zm(t))return e;let r=`${t.level}:${(t.text??``).trim()}`,i=[...e.filter(e=>`${e.level}:${(e.text??``).trim()}`!==r),t];for(;i.length>n;){let e=i.findIndex(e=>e.level!==`error`);e>=0?i.splice(e,1):i.shift()}return i}function $m(){return{flows:[],results:{}}}function eh(e,t){let n=e.findIndex(e=>e.flowId===t.flowId);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)}function th(e,t){switch(t.type){case`provider_oauth_started`:{let n={...e.results};return delete n[t.provider],{flows:[...e.flows.filter(e=>e.provider!==t.provider),{flowId:t.flowId,provider:t.provider}],results:n}}case`provider_oauth_flows`:return{...e,flows:t.flows.map(e=>({...e}))};case`provider_oauth_prompt`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:eh(e.flows,{...n,flowId:t.flowId,provider:t.provider,promptId:t.promptId,prompt:t.prompt})}}case`provider_oauth_event`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:eh(e.flows,{...n,flowId:t.flowId,provider:t.provider,event:t.event,promptId:void 0,prompt:void 0})}}case`provider_oauth_result`:return{flows:e.flows.filter(e=>e.flowId!==t.flowId),results:{...e.results,[t.provider]:{ok:t.ok,...t.cancelled===void 0?{}:{cancelled:t.cancelled},...t.error===void 0?{}:{error:t.error}}}};case`provider_oauth_logout_result`:return{...e,results:{...e.results,[t.provider]:{ok:t.ok,...t.error===void 0?{}:{error:t.error}}}}}}function nh(){return Ke()}var rh=typeof WebSocket<`u`&&WebSocket.OPEN!==void 0?WebSocket.OPEN:1,ih=typeof WebSocket<`u`&&WebSocket.CLOSING!==void 0?WebSocket.CLOSING:2,ah=typeof WebSocket<`u`&&WebSocket.CLOSED!==void 0?WebSocket.CLOSED:3,oh=e=>!!(e&&e.readyState===rh),sh=2e5,ch=`LIVE_OMIT`,lh={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 uh(e,t){let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId),e.role===`bashExecution`&&n.add(`bash-${e.id}`);let r=!1;for(let t of e.keys())n.has(t)&&(e.delete(t),r=!0);return r?new Map(e):e}function dh(e,t){if(e.size===0)return e;let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId);let r=!1;for(let t of e.keys())n.has(t)&&(e.delete(t),r=!0);return r?new Map(e):e}function fh(e,t){switch(t.type){case`status`:return{...e,status:t.status,ready:t.status===`open`&&e.ready,terminals:t.status===`closed`?[]:e.terminals,hostMetrics:t.status===`closed`?null:e.hostMetrics,latencyMs:t.status===`open`?e.latencyMs:null};case`sync_cached_sessions`:return{...e,sessions:t.sessions};case`host_metrics`:return{...e,...t.metrics===void 0?{}:{hostMetrics:t.metrics},...t.latencyMs===void 0?{}:{latencyMs:t.latencyMs}};case`ready`:{let n=!!(e.engine&&t.engine&&e.engine!==t.engine);return{...e,serverVersion:t.serverVersion,engine:t.engine,appVersion:t.appVersion,managed:t.managed===!0,tabs:t.tabs,ready:!0,...t.engines?{engines:t.engines}:{},...n?{state:null,models:[],sessions:Ah(e.state?.cwd,t.engine),conversations:[],terminals:[],dsh:null,dshPatches:null,dshMarket:null,dshPresets:null,dshPermission:null}:{},...typeof t.latencyMs==`number`&&e.latencyMs==null?{latencyMs:t.latencyMs}:{},protocolMismatch:t.protocolVersion!==void 0&&t.protocolVersion!==39}}case`snapshot`:{let n=e.state?.cwd,r=e.state?.conversationId,i=t.state.cwd,a=e.sessions;i&&i!==n&&(a=Ah(i,e.engine));let o=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),s=e.transition;if(s){let e=o(s.target),n=o(t.state.sessionFile),i=o(t.state.conversationId),a=o(t.state.sessionId);(s.phase===`done`||s.phase===`error`||s.kind===`cwd`&&o(t.state.cwd)===e||s.kind===`session`&&(n===e||a===e||i===e||n&&(n.endsWith(`/`+e)||e.endsWith(`/`+n)))||s.kind===`conversation`&&i===e||s.kind===`new_chat`&&(!r||t.state.conversationId!==r||t.state.messages.length===0))&&(s=null)}let c=Kp(e.optimisticQueue,t.state),l=Wp(c.tracker,c.state);return{...e,ready:!0,state:l.state,optimisticQueue:l.tracker,transition:s,sessions:a,approval:l.state.pendingApproval??null,approvals:l.state.pendingApprovals??(l.state.pendingApproval?[l.state.pendingApproval]:[]),activeConversationId:l.state.conversationId,liveOutputs:uh(e.liveOutputs,l.state),toolStatuses:dh(e.toolStatuses,l.state)}}case`earlier_messages`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId)return e;let i=qm(n,r);return i?{...e,state:i}:e}case`snapshot_delta`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId||n.rev!==r.baseRev)return e;let i={...n,...r.state,messages:r.appended.length>0?[...n.messages,...r.appended]:n.messages},a=Kp(e.optimisticQueue,i),o=Wp(a.tracker,a.state),s=o.state;return{...e,ready:!0,state:s,optimisticQueue:o.tracker,approval:s.pendingApproval===void 0?e.approval:s.pendingApproval??null,approvals:s.pendingApprovals??e.approvals,activeConversationId:s.conversationId,liveOutputs:uh(e.liveOutputs,s),toolStatuses:dh(e.toolStatuses,s)}}case`optimistic_queue_add`:{let n=e.goal.reviewing&&!!(e.state?.conversationId&&e.goal.conversationId===e.state.conversationId),r=Hp(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments,queue:t.queue,engine:e.engine,goalReviewing:n});return r.tracker===e.optimisticQueue&&r.state===e.state?e:{...e,optimisticQueue:r.tracker,state:r.state}}case`optimistic_queue_remove`:{let n=Up(e.optimisticQueue,e.state,{kind:t.kind,text:t.text,index:t.index});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`optimistic_prompt_echo`:{let n=Lp(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`tool_approval`:return{...e,approval:t.approval,approvals:is(e.approvals,t.approval,t.resolvedId)};case`tool_delta`:{let n=e.liveOutputs.get(t.toolCallId)?.text??``,r;r=t.mode===`replace`||n.length>0&&t.delta.startsWith(n)?t.delta:n+t.delta;let i=r.length>sh?`…[${ch}:${r.length-sh}]…\n`+r.slice(r.length-sh):r,a=new Map(e.liveOutputs);return a.set(t.toolCallId,{toolName:t.toolName,text:i}),{...e,liveOutputs:a}}case`message_delta`:{let n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:Sp(n,t.msg)}}case`tool_status`:return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case`notice`:{let n=Qm(e.notices,t.notice),r=(t.notice.level===`error`||t.notice.level===`warning`)&&e.optimisticQueue.adds.length>0?Gp(e.optimisticQueue,e.state):{tracker:e.optimisticQueue,state:e.state};return n===e.notices&&r.tracker===e.optimisticQueue?e:{...e,notices:n,optimisticQueue:r.tracker,state:r.state}}case`dismiss_notice`:return{...e,notices:e.notices.filter(e=>e.id!==t.id)};case`engines_status`:return{...e,engines:t.engines};case`sessions`:return jh(e.state?.cwd,t.sessions,e.engine),{...e,sessions:t.sessions};case`conversations`:return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case`projects`:return Eh(t.projects),{...e,projects:t.projects};case`sandbox_diff`:return{...e,sandboxDiff:t.diff};case`files`:return{...e,files:t.files};case`file_changed`:return{...e,fileChanged:{path:t.path}};case`file_content`:return{...e,fileContent:t.content};case`models`:return{...e,models:t.models,modelsLoading:t.loading};case`models_config`:return{...e,modelsConfig:t.providers};case`providers_status`:return{...e,providers:t.providers};case`provider_keys`:return{...e,providerKeys:t.keys};case`default_model`:return{...e,defaultModel:t.modelId};case`provider_oauth`:{let n=th({flows:e.providerOAuthFlows,results:e.providerOAuthResults},t.message);return{...e,providerOAuthFlows:n.flows,providerOAuthResults:n.results}}case`fetch_models_result`:return{...e,fetchModelsResult:t.result};case`test_model_connection_result`:return{...e,testModelConnectionResult:t.result};case`enrich_models_progress`:return{...e,enrichModelsProgress:t.progress};case`enrich_models_result`:return{...e,enrichModelsResult:t.result,enrichModelsProgress:null};case`refresh_provider_result`:return{...e,refreshProviderResult:t.result};case`refresh_builtin_result`:return{...e,refreshBuiltinResult:t.result};case`append_builtin_result`:return{...e,appendBuiltinResult:t.result};case`clone_provider_result`:return{...e,cloneProviderResult:t.result};case`install_result`:return{...e,installResult:t.result};case`scm_data`:return{...e,scmData:t.data};case`file_search_result`:return{...e,fileSearch:t.result};case`session_search_result`:return{...e,sessionSearch:t.result};case`scm_changed`:return{...e,scmDirty:e.scmDirty+1};case`path_completions`:return{...e,pathCompletions:t.completions};case`update_status`:return{...e,update:t.status};case`update_status_all`:return{...e,updatesAll:t.items,updatesSdk:t.piSdk??null};case`updates_check_started`:return{...e,updatesAll:null};case`widgets`:return{...e,widgets:t.widgets};case`statuses`:return{...e,statuses:t.statuses};case`dialog`:return{...e,dialog:t.dialog};case`tui_overlay`:return{...e,tuiOverlay:t.overlay};case`question`:return{...e,question:t.question};case`remote_question`:return{...e,remoteQuestion:e.questionQueue===null?t.question:null};case`question_queue`:return{...e,questionQueue:t.questions,remoteQuestion:null};case`question_queue_answered`:return{...e,questionQueue:e.questionQueue?.filter(e=>e.id!==t.id||e.owner!==t.owner)??null};case`commands`:return{...e,commands:t.commands,commandsPath:t.path};case`slash_commands`:return{...e,slashCommands:t.commands};case`goal_status`:return{...e,goal:t.status};case`plan_updated`:{let n=e.state;if(!n)return e;let r=e.activeConversationId||n.conversationId;if(!t.conversationId||t.conversationId!==r)return e;let i={...n,plan:t.plan};return{...e,state:i}}case`settings`:return{...e,settings:t.settings};case`mcp_servers`:return e.settings?{...e,settings:{...e.settings,mcpServers:t.servers,mcpGlobalConfigPath:t.globalConfigPath??e.settings.mcpGlobalConfigPath,mcpProjectConfigPath:t.projectConfigPath??e.settings.mcpProjectConfigPath}}:e;case`mcp_oauth_result`:return{...e,mcpOAuthResult:e.mcpOAuthResult?.reqId===t.result.reqId?{...e.mcpOAuthResult,...t.result,error:t.result.error}:t.result};case`mcp_market_result`:return{...e,mcpMarketResult:t.result};case`skill_market_result`:return{...e,skillMarketResult:t.result};case`skill_content_result`:return{...e,skillContentResult:t.result};case`bg_servers`:return{...e,bgServers:t.servers};case`scheduler_tasks`:return{...e,schedulerTasks:t.tasks};case`plugin_panel_items`:return{...e,pluginPanelGroups:t.groups};case`plugins`:return{...e,plugins:t.plugins,pluginsEpoch:t.epoch};case`plugin_updates_check_started`:return{...e,checkingPluginUpdates:!0};case`plugin_updates`:{let n={};for(let e of t.updates)n[e.id]=e;return{...e,pluginUpdates:n,checkingPluginUpdates:!1}}case`plugin_catalog`:return{...e,pluginCatalog:t.entries,pluginCatalogEpoch:t.epoch};case`plugin_grants`:return{...e,pluginGrants:t.grants};case`plugin_permissions`:return{...e,pluginPermissions:t.grants};case`plugin_path_request`:return{...e,pathRequests:[...e.pathRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_path_resolved`:return{...e,pathRequests:e.pathRequests.filter(e=>e.id!==t.id)};case`plugin_permission_request`:return{...e,permRequests:[...e.permRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_permission_resolved`:return{...e,permRequests:e.permRequests.filter(e=>e.id!==t.id)};case`plugin_job`:{let{pluginId:n,phase:r,ok:i,action:a}=t.job,o=e.pluginUpdates;a===`update`&&r===`done`&&i&&e.pluginUpdates?.[n]&&(o={...e.pluginUpdates,[n]:{...e.pluginUpdates[n],updatable:!1}});let s=e.pluginJobs[t.job.jobId],c=t.line?[...s?.lines??[],t.line].slice(-40):s?.lines??[],l={...s,...t.job,lines:c,startedAt:s?.startedAt??Date.now()};return{...e,pluginUpdates:o,pluginJobs:{...e.pluginJobs,[t.job.jobId]:l}}}case`plugin_catalog_sync_result`:return{...e,catalogSync:{...t.result,receivedAt:Date.now()}};case`preset_export_result`:return{...e,presetExport:{...t.result,receivedAt:Date.now()}};case`preset_import_result`:return{...e,presetImport:{...t.result,source:t.source,receivedAt:Date.now()}};case`preset_catalog_result`:return{...e,presetCatalog:{...t.result,receivedAt:Date.now()}};case`preset_share_result`:return{...e,presetShare:{...t.result,receivedAt:Date.now()}};case`plugin_install_inspect_result`:return{...e,installInspect:t.result};case`dsh_patches`:{let n={patchDir:t.patchDir,files:t.files};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},patches:n},dshPatches:n}}case`dsh_market_data`:{let n={count:t.count,updated:t.updated,categories:t.categories,plugins:t.plugins};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},market:n},dshMarket:n}}case`dsh_presets`:{let n={presets:t.presets,defaultPreset:t.defaultPreset};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},presets:n},dshPresets:n}}case`dsh_permission`:{let n={options:t.options,defaultPreset:t.defaultPreset};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},permission:n},dshPermission:n}}case`terminal_add`:return{...e,terminals:[...e.terminals,t.meta]};case`terminal_remove`:return{...e,terminals:e.terminals.filter(e=>e.id!==t.id||(e.ownerKind??`client`)!==(t.ownerKind??`client`)||(e.ownerKind??`client`)!==`client`&&e.conversationId!==t.conversationId)};case`terminal_exit`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!1,exitCode:t.exitCode}:e)};case`terminal_restart`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!0,exitCode:null}:e)};case`terminal_list`:{let n=e.activeConversationId||e.state?.conversationId||``,r=t.conversationId??n,i=t.terminals.filter(e=>(e.ownerKind??`client`)===`client`||r===n).map(e=>({...e,ownerKind:e.ownerKind??`client`,conversationId:r}));return{...e,terminals:i}}case`terminal_active`:return{...e,terminalActiveId:t.id};case`transition_start`:{let n=t.kind===`cwd`?Ah(t.target,e.engine):null;return{...e,...n&&n.length>0?{sessions:n}:{},transition:{kind:t.kind,target:t.target,phase:`start`,progress:t.progress,text:t.text,textEn:t.textEn,startedAt:Date.now()}}}case`transition_progress`:{let n=t.msg;if(n.phase===`done`||n.phase===`error`)return{...e,transition:e.transition?{...e.transition,phase:n.phase,progress:100,text:n.text,textEn:n.textEn}:null};let r=e.transition;return{...e,transition:{kind:n.kind,target:n.target,phase:n.phase,progress:Math.max(r?.target===n.target?r.progress:0,n.progress),text:n.text,textEn:n.textEn,totalMessages:n.totalMessages??r?.totalMessages,previewMessages:n.previewMessages??r?.previewMessages,startedAt:r?.startedAt??Date.now()}}}case`transition_tick`:{let t=e.transition;if(!t||t.phase===`done`||t.phase===`error`)return e;let n=t.phase===`start`?26:t.phase===`fs`?56:92;if(t.progress>=n)return e;let r=Math.max(1,Math.round((n-t.progress)*.16));return{...e,transition:{...t,progress:Math.min(n,t.progress+r)}}}case`transition_clear`:return e.transition?{...e,transition:null}:e;default:return e}}var ph=`pi-web-client-id`,mh=`pi-web-client-id:`,hh=`__PI_CID__:`,gh=null;function _h(){try{if(typeof window<`u`&&typeof window.name==`string`&&window.name){let e=window.name;if(e.startsWith(mh)){let t=e.slice(17).trim();if(t)return t}let t=e.indexOf(hh);if(t!==-1){let n=e.slice(t+11).trim();if(n)return n}}}catch{}try{if(typeof sessionStorage<`u`){let e=sessionStorage.getItem(ph);if(e)return e}}catch{}return null}function vh(e){try{if(typeof window<`u`){let t=typeof window.name==`string`?window.name:``;if(!t||t.startsWith(mh))window.name=`${mh}${e}`;else{let n=t.indexOf(hh),r=n===-1?t:t.slice(0,n);window.name=`${r}${hh}${e}`}}}catch{}try{typeof sessionStorage<`u`&&sessionStorage.setItem(ph,e)}catch{}}function yh(){if(gh)return gh;let e=_h();return e||=ht(),vh(e),gh=e,e}var bh=`pi-web-last-cwd`;function xh(){try{return localStorage.getItem(bh)}catch{return null}}function Sh(e){try{localStorage.setItem(bh,e)}catch{}}function Ch(e){try{let t=localStorage.getItem(bh);if(!t)return;let n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase();(t===e||n(t)===n(e))&&localStorage.removeItem(bh)}catch{}}var wh=`pi-web-recent-projects`;function Th(){try{let e=localStorage.getItem(wh);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Eh(e){try{localStorage.setItem(wh,JSON.stringify(e.slice(0,20)))}catch{}}function Dh(e){try{let t=Th(),n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),r=n(e);Eh(t.filter(e=>n(e.path)!==r))}catch{}}var Oh=`pi-web-recent-sessions:`;function kh(e,t){let n=t??`pi`;return e?`${Oh}${n}:${e.trim().replace(/[\\/]+$/,``).toLowerCase()}`:`pi-web-recent-sessions:${n}:default`}function Ah(e,t){try{let n=kh(e??xh(),t),r=localStorage.getItem(n);if(!r)return[];let i=JSON.parse(r);return Array.isArray(i)?i:[]}catch{return[]}}function jh(e,t,n){try{let r=kh(e??xh(),n);localStorage.setItem(r,JSON.stringify(t.slice(0,50)))}catch{}}function Mh(e,t,n){try{let r=Ah(t,n),i=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),a=i(e);jh(t,r.filter(e=>i(e.path)!==a),n)}catch{}}function Nh(){let e=location.protocol===`https:`?`wss:`:`ws:`;return Qe(`${e}//${location.host}${q(`/ws`)}`)}function Ph(){let[e,t]=(0,Q.useReducer)(fh,{status:`connecting`,ready:!1,state:null,hostMetrics:null,latencyMs:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:Ah(),conversations:[],elsewhere:[],activeConversationId:``,projects:Th(),files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},defaultModel:null,providerOAuthFlows:[],providerOAuthResults:$m().results,installResult:null,pathCompletions:[],update:null,updatesAll:null,updatesSdk:null,widgets:[],statuses:[],dialog:null,tuiOverlay:null,approval:null,approvals:[],question:null,questionQueue:null,remoteQuestion:null,commands:[],commandsPath:``,slashCommands:[],terminals:[],terminalActiveId:null,goal:lh,bgServers:[],schedulerTasks:[],pluginPanelGroups:[],settings:null,fetchModelsResult:null,testModelConnectionResult:null,enrichModelsResult:null,enrichModelsProgress:null,refreshProviderResult:null,refreshBuiltinResult:null,appendBuiltinResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginUpdates:null,checkingPluginUpdates:!1,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},catalogSync:null,presetExport:null,presetImport:null,presetCatalog:null,presetShare:null,installInspect:null,pluginGrants:[],pluginPermissions:[],pathRequests:[],permRequests:[],dsh:null,dshPatches:null,dshMarket:null,mcpOAuthResult:null,mcpMarketResult:null,skillMarketResult:null,skillContentResult:null,dshPresets:null,dshPermission:null,protocolMismatch:!1,transition:null,sandboxDiff:null,optimisticQueue:Op()}),n=(0,Q.useRef)(null),r=(0,Q.useRef)(ls()),i=(0,Q.useRef)(0),a=(0,Q.useRef)(null),o=(0,Q.useRef)(!0),s=(0,Q.useRef)(0),c=(0,Q.useRef)(0),l=(0,Q.useRef)(new Map),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=(0,Q.useRef)(null),p=(0,Q.useRef)(new Set),m=(0,Q.useRef)(`live`),h=()=>{u.current||=setTimeout(()=>{u.current=null;let e=n.current;oh(e)&&e.send(JSON.stringify({type:`get_state`}))},300)},g=(e,t)=>{let n=l.current,r=n.get(e);if(r!==void 0&&t!==r+1){let t=D.current.chat;e===(t.activeConversationId||t.state?.conversationId)&&h()}n.set(e,t)},_=(0,Q.useCallback)((e,n)=>{let r=++c.current;t({type:`notice`,notice:{id:r,level:e,text:n}})},[]);(0,Q.useEffect)(()=>{if(!e.transition)return;if(e.transition.phase===`done`||e.transition.phase===`error`){let e=setTimeout(()=>t({type:`transition_clear`}),180);return()=>clearTimeout(e)}let n=setInterval(()=>{if(Date.now()-(e.transition?.startedAt??0)>2e4){t({type:`transition_clear`});return}t({type:`transition_tick`})},160);return()=>clearInterval(n)},[e.transition]);let v=(0,Q.useCallback)(e=>{let r=n.current;if(!oh(r))return!1;let i=D.current.chat;(e.type===`terminal_input`||e.type===`terminal_resize`||e.type===`terminal_kill`||e.type===`rename_terminal`||e.type===`terminal_attach`)&&!e.ownerKind&&(e={...e,ownerKind:`client`});let a=i.state;if(e.type===`load_earlier_messages`&&a&&(!e.conversationId||e.conversationId===a.conversationId)&&(e={...e,conversationId:a.conversationId,historyGeneration:e.historyGeneration??a.historyGeneration,beforeId:e.beforeId??a.messages[0]?.id,before:e.before??a.historyStart}),e.type===`set_cwd`&&e.path){let n=(a?.cwd??``).trim().replace(/[\\/]+$/,``).toLowerCase(),r=e.path.trim().replace(/[\\/]+$/,``).toLowerCase();r&&r!==n&&t({type:`transition_start`,kind:`cwd`,target:e.path,progress:14,text:`正在切换到工作目录:${e.path}`,textEn:`Switching to workspace: ${e.path}`})}else if(e.type===`switch_session`&&(e.path||e.sessionId)){Yt();let n=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),r=n(a?.sessionFile),i=n(a?.sessionId),o=n(a?.conversationId),s=n(e.path||e.sessionId);s&&s!==r&&s!==i&&s!==o&&t({type:`transition_start`,kind:`session`,target:e.path||e.sessionId||``,progress:14,text:`正在流式载入历史会话…`,textEn:`Streaming session history…`})}else e.type===`new_chat`?(Yt(),a&&(a.messages.length>0||a.isStreaming)&&t({type:`transition_start`,kind:`new_chat`,target:a.cwd,progress:22,text:`正在初始化新对话…`,textEn:`Initializing new chat…`})):e.type===`switch_conversation`&&e.id&&(Yt(),a&&e.id!==a.conversationId&&t({type:`transition_start`,kind:`conversation`,target:e.id,progress:35,text:`正在切换对话…`,textEn:`Switching conversation…`}));if(oh(r)){if(e.type===`check_updates_all`&&e.force===!0&&t({type:`updates_check_started`}),e.type===`check_plugin_updates`&&t({type:`plugin_updates_check_started`}),r.send(JSON.stringify(e)),e.type===`prompt`?(t({type:`optimistic_queue_add`,text:e.text,attachments:e.attachments,queue:e.queue}),t({type:`optimistic_prompt_echo`,text:e.text,attachments:e.attachments})):e.type===`queue_remove`&&t({type:`optimistic_queue_remove`,kind:e.kind,text:e.text,index:e.index}),e.type===`question_answer`){if(t({type:`question_queue_answered`,id:e.id,owner:e.owner}),e.owner){D.current.chat.question?.id===e.id&&D.current.chat.questionQueue?.some(t=>t.id===e.id&&t.owner===e.owner)&&(p.current.add(e.id),t({type:`question`,question:null}));let n=D.current.chat.remoteQuestion;n&&n.id===e.id&&n.owner===e.owner&&t({type:`remote_question`,question:null})}else{if(p.current.add(e.id),p.current.size>64){let e=p.current.values().next().value;e!==void 0&&p.current.delete(e)}m.current=`live`,t({type:`question`,question:null})}}return!0}return!1},[]),y=(0,Q.useCallback)((e,n)=>{let r=qp({current:D.current.chat.question,source:m.current,snapshot:e,answered:p.current,activeConversationId:n});r.changed&&(m.current=r.source,t({type:`question`,question:r.question}))},[]);an(v);let b=(0,Q.useCallback)(()=>{if(!o.current)return;t({type:`status`,status:`connecting`});let e=new WebSocket(Nh());n.current=e;let u=0;e.onopen=()=>{n.current===e&&(t({type:`status`,status:`open`}),i.current=0,s.current=Date.now(),u=performance.now(),e.send(JSON.stringify({type:`hello`,clientId:yh(),locale:nh()})))};let d=new Set([`snapshot_delta`,`message_delta`,`tool_delta`,`earlier_messages`,`terminal_output`,`terminal_exit`,`terminal_list`]);e.onmessage=i=>{if(n.current!==e)return;s.current=Date.now();let a;try{a=JSON.parse(i.data)}catch{return}if(`conversationId`in a&&typeof a.conversationId==`string`&&d.has(a.type)){let e=D.current.chat.activeConversationId||D.current.chat.state?.conversationId;if(e&&a.conversationId!==e)return}switch(a.type){case`ready`:{if((D.current.chat.settings?.autoReload??!0)&&a.buildId&&a.buildId!==`20261031T04314`){let e=`pi-web-ui-reloaded-${a.buildId}`;if(!sessionStorage.getItem(e)){sessionStorage.setItem(e,`1`),location.reload();return}}let n=D.current.chat.engine;n&&a.engine&&n!==a.engine&&r.current.clear(),nn({engine:a.engine??`pi`,managed:!!a.managed,tabs:a.tabs,appVersion:a.appVersion,serverVersion:a.serverVersion,service:a.service,...a.engineCapabilities?{engineCapabilities:a.engineCapabilities}:{},...a.engines?{engines:a.engines}:{}});let i=u>0?Math.max(0,Math.round(performance.now()-u)):null;t({type:`ready`,serverVersion:a.serverVersion,protocolVersion:a.protocolVersion,engine:a.engine,appVersion:a.appVersion,managed:a.managed,tabs:a.tabs,service:a.service,latencyMs:i,engines:a.engines}),p.current.clear(),t({type:`question`,question:null}),e.send(JSON.stringify({type:`get_state`})),e.send(JSON.stringify({type:`list_files`})),e.send(JSON.stringify({type:`list_models`})),e.send(JSON.stringify({type:`list_commands`})),e.send(JSON.stringify({type:`get_commands`})),a.managed||(e.send(JSON.stringify({type:`check_update`})),e.send(JSON.stringify({type:`check_updates_all`})));break}case`snapshot`:l.current=new Map,t({type:`snapshot`,state:a.state}),y(a.state.pendingQuestion,a.state.conversationId);break;case`snapshot_delta`:{let e=D.current.chat.state;if(e)(e.conversationId!==a.conversationId||e.rev!==a.baseRev)&&h();else{let e=n.current;oh(e)&&e.send(JSON.stringify({type:`get_state`}))}let r=D.current.chat.activeConversationId||e?.conversationId;if(r&&a.conversationId!==r)break;t({type:`snapshot_delta`,msg:a}),y(a.state.pendingQuestion,r||a.conversationId);break}case`earlier_messages`:{let e=D.current.chat.state;if(e?.conversationId!==a.conversationId)break;if(Km(e,a)){h();break}t({type:`earlier_messages`,msg:a});break}case`tool_delta`:g(a.conversationId,a.seq),t({type:`tool_delta`,toolCallId:a.toolCallId,toolName:a.toolName,delta:a.delta,...a.mode?{mode:a.mode}:{}});break;case`tool_status`:t({type:`tool_status`,status:a});break;case`message_delta`:g(a.conversationId,a.seq),t({type:`message_delta`,msg:a});break;case`subagent_handoff`:break;case`notice`:{let e=++c.current;(a.level===`error`||a.level===`warning`)&&t({type:`transition_clear`}),t({type:`notice`,notice:{id:e,level:a.level,text:a.text,textEn:a.textEn}});break}case`transition_progress`:t({type:`transition_progress`,msg:a});break;case`engines_status`:nn({engines:a.engines}),t({type:`engines_status`,engines:a.engines});break;case`sessions`:t({type:`sessions`,sessions:a.sessions});break;case`conversations`:t({type:`conversations`,conversations:a.conversations,activeId:a.activeId,elsewhere:a.elsewhere});break;case`projects`:t({type:`projects`,projects:a.projects});break;case`sandbox_diff`:t({type:`sandbox_diff`,diff:a.diff});break;case`files`:t({type:`files`,files:a});break;case`canvas_list_result`:window.dispatchEvent(new CustomEvent(as,{detail:a}));break;case`file_upload_result`:window.dispatchEvent(new CustomEvent(`pi:file-upload-result`,{detail:a}));break;case`file_changed`:t({type:`file_changed`,path:a.path});break;case`file_content`:t({type:`file_content`,content:a});break;case`models`:t({type:`models`,models:a.models,loading:!1});break;case`models_config`:t({type:`models_config`,providers:a.providers});break;case`providers_status`:t({type:`providers_status`,providers:a.providers});break;case`provider_keys`:t({type:`provider_keys`,keys:a.keys});break;case`default_model`:t({type:`default_model`,modelId:a.modelId});break;case`provider_oauth_started`:case`provider_oauth_flows`:case`provider_oauth_prompt`:case`provider_oauth_event`:case`provider_oauth_result`:case`provider_oauth_logout_result`:t({type:`provider_oauth`,message:a});break;case`fetch_models_result`:t({type:`fetch_models_result`,result:{reqId:a.reqId,ok:a.ok,models:a.models,error:a.error}});break;case`test_model_connection_result`:t({type:`test_model_connection_result`,result:{reqId:a.reqId,ok:a.ok,latencyMs:a.latencyMs,error:a.error}});break;case`enrich_models_progress`:t({type:`enrich_models_progress`,progress:{reqId:a.reqId,phase:a.phase,current:a.current,total:a.total,message:a.message}});break;case`enrich_models_result`:t({type:`enrich_models_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,error:a.error}});break;case`refresh_provider_result`:t({type:`refresh_provider_result`,result:{reqId:a.reqId,ok:a.ok,added:a.added,total:a.total,error:a.error}});break;case`refresh_builtin_result`:t({type:`refresh_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`append_builtin_result`:t({type:`append_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`clone_provider_result`:t({type:`clone_provider_result`,result:{reqId:a.reqId,ok:a.ok,config:a.config,configs:a.configs,error:a.error}});break;case`scm_data`:t({type:`scm_data`,data:a});break;case`search_files_result`:t({type:`file_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,truncated:a.truncated}});break;case`session_search_results`:t({type:`session_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results}});break;case`scm_changed`:t({type:`scm_changed`});break;case`tool_info`:Bl(a);break;case`tool_prompt`:sm(a);break;case`compacted_messages_result`:Gd(a);break;case`heartbeat`:(a.hostMetrics||typeof a.latencyMs==`number`)&&t({type:`host_metrics`,metrics:a.hostMetrics,latencyMs:typeof a.latencyMs==`number`?a.latencyMs:void 0});break;case`install_result`:t({type:`install_result`,result:a});break;case`path_completions`:t({type:`path_completions`,completions:a.completions});break;case`update_status`:t({type:`update_status`,status:a});break;case`update_status_all`:t({type:`update_status_all`,items:a.items,piSdk:a.piSdk});break;case`widgets`:t({type:`widgets`,widgets:a.widgets});break;case`statuses`:t({type:`statuses`,statuses:a.statuses});break;case`dialog`:t({type:`dialog`,dialog:{id:a.id,kind:a.kind,title:a.title,args:a.args,code:a.code}});break;case`dialog_closed`:t({type:`dialog`,dialog:null});break;case`tui_overlay_open`:$p(a.id),t({type:`tui_overlay`,overlay:{id:a.id,title:a.title,cols:a.cols,rows:a.rows,initialAnsi:a.initialAnsi}});break;case`tui_overlay_render`:tm(a.id,a.ansi);break;case`tui_overlay_close`:$p(),t({type:`tui_overlay`,overlay:null});break;case`question_pending`:m.current=`live`,t({type:`question`,question:{id:a.id,...a.deadline===void 0?{}:{deadline:a.deadline},questions:a.questions,...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`tool_approval_pending`:t({type:`tool_approval`,approval:{id:a.id,toolCallId:a.toolCallId,toolName:a.toolName,params:a.params,reason:a.reason,reasonEn:a.reasonEn,...a.category?{category:a.category}:{},...a.hits?{hits:a.hits}:{},...a.parentTool?{parentTool:a.parentTool}:{},...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`tool_approval_resolved`:t({type:`tool_approval`,approval:null,resolvedId:a.id});break;case`question_retracted`:{D.current.chat.remoteQuestion?.id===a.id&&t({type:`remote_question`,question:null});let e=D.current.chat.question;if(e&&e.id===a.id){if(p.current.add(a.id),p.current.size>64){let e=p.current.values().next().value;e!==void 0&&p.current.delete(e)}m.current=`live`,t({type:`question`,question:null})}break}case`question_queue`:t({type:`question_queue`,questions:a.questions});break;case`elsewhere_question`:t({type:`remote_question`,question:{owner:a.owner,convId:a.convId,id:a.id,questions:a.questions,...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`page_request`:(async()=>{let e=window.__piWebUiHost,t;if(!e?.pageCall)t={ok:!1,error:`宿主页面桥不可用(页面版本过旧?)—— 刷新本页后再试`};else try{t=await e.pageCall({op:a.op,...a.args===void 0?{}:{args:a.args},...a.target?{target:a.target}:{},timeoutMs:a.timeoutMs})}catch(e){t={ok:!1,error:e instanceof Error?e.message:String(e)}}v({type:`page_response`,id:a.id,ok:t.ok===!0,...t.ok===!0?t.result===void 0?{}:{result:t.result}:{error:t.error??`页面操作失败`}})})();break;case`terminal_output`:r.current.write(a.conversationId??``,a.terminalId,a.data,a.reset,a.ownerKind??`client`);break;case`terminal_exit`:t({type:`terminal_exit`,conversationId:a.conversationId,ownerKind:a.ownerKind,terminalId:a.terminalId,exitCode:a.exitCode});break;case`terminal_list`:r.current.reconcile(a.conversationId??D.current.chat.activeConversationId,a.terminals),t({type:`terminal_list`,conversationId:a.conversationId,terminals:a.terminals});break;case`commands`:t({type:`commands`,commands:a.commands,path:a.path});break;case`slash_commands`:t({type:`slash_commands`,commands:a.commands});break;case`goal_status`:t({type:`goal_status`,status:a.status});break;case`plan_updated`:t({type:`plan_updated`,conversationId:a.conversationId,plan:a.plan});break;case`settings_state`:a.settings?.markers&&tp(a.settings.markers.map(e=>e.name)),t({type:`settings`,settings:a.settings});break;case`mcp_servers`:t({type:`mcp_servers`,servers:a.servers,globalConfigPath:a.globalConfigPath,projectConfigPath:a.projectConfigPath});break;case`mcp_oauth_result`:t({type:`mcp_oauth_result`,result:a});break;case`mcp_market_result`:t({type:`mcp_market_result`,result:a});break;case`skill_market_result`:t({type:`skill_market_result`,result:a});break;case`skill_content_result`:t({type:`skill_content_result`,result:a});break;case`bg_servers`:t({type:`bg_servers`,servers:a.servers});break;case`scheduler_tasks`:t({type:`scheduler_tasks`,tasks:a.tasks});break;case`plugin_panel_items`:t({type:`plugin_panel_items`,groups:a.groups});break;case`plugins`:t({type:`plugins`,plugins:a.plugins,epoch:a.epoch});break;case`plugin_updates`:t({type:`plugin_updates`,updates:a.updates});break;case`plugin_catalog`:t({type:`plugin_catalog`,entries:a.entries,epoch:a.epoch});break;case`plugin_grants`:t({type:`plugin_grants`,grants:a.grants});break;case`plugin_permissions`:t({type:`plugin_permissions`,grants:a.grants});break;case`plugin_permission_request`:t({type:`plugin_permission_request`,req:{id:a.id,pluginId:a.pluginId,family:a.family,...a.hosts?{hosts:a.hosts}:{},...a.models?{models:a.models}:{},...a.reason?{reason:a.reason}:{}}});break;case`plugin_permission_resolved`:t({type:`plugin_permission_resolved`,id:a.id});break;case`plugin_path_request`:t({type:`plugin_path_request`,req:{id:a.id,pluginId:a.pluginId,path:a.path,...a.reason?{reason:a.reason}:{}}});break;case`plugin_dom_consent_request`:a.from===yh()&&e.send(JSON.stringify({type:`plugin_dom_consent_response`,id:a.id,ok:!0}));break;case`plugin_job`:t({type:`plugin_job`,job:{jobId:a.jobId,action:a.action,pluginId:a.pluginId,phase:a.phase,...a.ok===void 0?{}:{ok:a.ok},...a.error?{error:a.error}:{},...a.output?{output:a.output}:{}},...a.line?{line:a.line}:{}});break;case`plugin_install_inspect_result`:t({type:`plugin_install_inspect_result`,result:{requestId:String(a.requestId??``),source:String(a.source??``),kind:a.kind,suggestedId:String(a.suggestedId??``),installed:a.installed===!0,...a.problem?{problem:a.problem}:{},...a.detail?{detail:a.detail}:{},...a.manifest?{manifest:a.manifest}:{}}});break;case`new_chat_result`:Nt(a);break;case`plugin_catalog_sync_result`:Ht(a),t({type:`plugin_catalog_sync_result`,result:{requestId:String(a.requestId??``),ok:a.ok===!0,...a.error?{error:a.error}:{},...a.entries?{entryCount:a.entries.length}:{},...a.installed?{installed:a.installed}:{}}});break;case`preset_export_result`:t({type:`preset_export_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.name?{name:a.name}:{},...a.fileName?{fileName:a.fileName}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`preset_import_result`:{let e=String(a.requestId??``),n=e.startsWith(`url:`)?`url`:e.startsWith(`file:`)?`file`:`paste`;t({type:`preset_import_result`,source:n,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,dryRun:a.dryRun===!0,...a.preview?{preview:a.preview}:{},...a.applied===void 0?{}:{applied:a.applied},...a.applyError?{applyError:a.applyError}:{},...a.applyDeferred?{applyDeferred:!0}:{},...a.error?{error:a.error}:{}}});break}case`preset_catalog_result`:t({type:`preset_catalog_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,entries:a.entries??[],source:a.source??``,cached:a.cached===!0,fetchedAt:a.fetchedAt??0,...a.error?{error:a.error}:{}}});break;case`preset_share_result`:t({type:`preset_share_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.method?{method:a.method}:{},...a.url?{url:a.url}:{},...a.name?{name:a.name}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`dsh_patches`:t({type:`dsh_patches`,patchDir:a.patchDir,files:a.files});break;case`dsh_market_data`:t(a);break;case`dsh_presets`:t({type:`dsh_presets`,presets:a.presets,defaultPreset:a.defaultPreset});break;case`dsh_permission`:t({type:`dsh_permission`,options:a.options,defaultPreset:a.defaultPreset});break;case`plugin_data`:Gm(a.pluginId,a.payload)||pm(a.pluginId,a.payload);break;case`remote_ssh_probe_result`:case`remote_ssh_list_dir_result`:case`remote_ssh_install_result`:case`remote_ssh_profiles_result`:ia(a)}},e.onclose=()=>{if(n.current!==e||(n.current=null,r.current.clear(),!o.current))return;t({type:`status`,status:`closed`});let s=Math.min(1e3*2**i.current,1e4);i.current+=1,a.current=setTimeout(()=>{a.current=null,b()},s)},e.onerror=()=>{}},[]);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail??nh();t&&v({type:`set_locale`,locale:t})};return window.addEventListener(Fe,e),()=>window.removeEventListener(Fe,e)},[v]),(0,Q.useEffect)(()=>{let n=n=>{let r=e.state?.cwd;r&&n.key&&n.key===kh(r,e.engine)&&t({type:`sync_cached_sessions`,sessions:Ah(r,e.engine)})};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)},[e.state?.cwd,e.engine]),(0,Q.useEffect)(()=>{o.current=!0,b();let e=setInterval(()=>{if(!o.current)return;let e=n.current;oh(e)&&Date.now()-s.current>3e4&&e.close()},5e3),t=()=>{if(!o.current||typeof document<`u`&&document.visibilityState===`hidden`)return;let e=n.current;if(!e||e.readyState===ah||e.readyState===ih){a.current&&=(clearTimeout(a.current),null),b();return}oh(e)&&(Date.now()-s.current>15e3||!D.current.chat.state)&&e.send(JSON.stringify({type:`get_state`}))};return typeof document<`u`&&document.addEventListener(`visibilitychange`,t),typeof window<`u`&&(window.addEventListener(`pageshow`,t),window.addEventListener(`online`,t)),()=>{o.current=!1,clearInterval(e),a.current&&=(clearTimeout(a.current),null),typeof document<`u`&&document.removeEventListener(`visibilitychange`,t),typeof window<`u`&&(window.removeEventListener(`pageshow`,t),window.removeEventListener(`online`,t)),n.current?.close(),n.current=null,r.current.clear()}},[b]),(0,Q.useEffect)(()=>{let t=e.state?.cwd;if(t){if(!d.current){d.current=!0;let e=xh();if(e&&e!==t){v({type:`set_cwd`,path:e});return}}f.current!==t&&(f.current=t,Sh(t))}},[e.state?.cwd,v]),(0,Q.useEffect)(()=>{nn({ready:e.ready,status:e.status,cwd:e.state?.cwd??``,workspaceRoots:e.state?.workspaceRoots??[],homeDir:e.state?.homeDir??``,desktopDir:e.state?.desktopDir??``,chatUploadMaxMb:e.settings?.chatUploadMaxMb??20,workspaceUploadMaxMb:e.settings?.workspaceUploadMaxMb??100,folderUploadMaxMb:e.settings?.folderUploadMaxMb??32,...e.state?.engineCapabilities?{engineCapabilities:e.state.engineCapabilities}:{}})},[e.ready,e.status,e.state?.cwd,e.state?.workspaceRoots,e.state?.homeDir,e.state?.desktopDir,e.settings?.chatUploadMaxMb,e.settings?.workspaceUploadMaxMb,e.settings?.folderUploadMaxMb,e.state?.engineCapabilities]);let x=(0,Q.useCallback)(e=>t({type:`dismiss_notice`,id:e}),[]),S=(0,Q.useCallback)(e=>{let n=D.current.chat;if(!n.ready||n.terminals.some(t=>t.id===e.id&&(t.ownerKind??`client`)===(e.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||t.conversationId===e.conversationId)))return;let r=e.ownerKind??`client`,i={terminalId:e.id,conversationId:e.conversationId,ownerKind:r,cols:e.cols,rows:e.rows};(e.command?v({type:`run_command`,...i,command:e.command}):v({type:`terminal_create`,...i,title:e.title,cwd:e.cwd,agentBash:e.agentBash,locale:nh()}))&&t({type:`terminal_add`,meta:{...e,ownerKind:r}})},[v]),C=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_remove`,id:e,ownerKind:n,conversationId:r}),[]),w=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_restart`,terminalId:e,ownerKind:n,conversationId:r}),[]),T=(0,Q.useCallback)(e=>t({type:`terminal_active`,id:e}),[]),E=(0,Q.useCallback)((e,t,n,i=`client`)=>r.current.register(e,t,n,i),[]),D=(0,Q.useRef)({chat:e,send:v,pushNotice:_,dismissNotice:x,terminal:{create:S,close:C,register:E,restart:w,select:T}});return D.current={chat:e,send:v,pushNotice:_,dismissNotice:x,terminal:{create:S,close:C,register:E,restart:w,select:T}},D.current}function Fh(e){let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`:`${t.getMonth()+1}/${t.getDate()}`}function Ih(e){let t=e instanceof HTMLElement?e:null;if(!t)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable}var Lh=`pi-web-ui:lp-collapse-projects`,Rh=`pi-web-ui:lp-collapse-convs`,zh=`pi-web-ui:lp-collapse-sessions`,Bh=`pi-web-ui:lp-collapse-subagents`;function Vh(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Bh);if(e)return new Set(JSON.parse(e))}catch{}return new Set});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(Bh,JSON.stringify([...n]))}catch{}return n})},[])]}function Hh(e,t=!1){let[n,r]=(0,Q.useState)(()=>{try{let t=localStorage.getItem(e);if(t===`1`)return!0;if(t===`0`)return!1}catch{}return t});return[n,(0,Q.useCallback)(()=>{r(t=>{let n=!t;try{localStorage.setItem(e,n?`1`:`0`)}catch{}return n})},[e])]}var Uh=`pi-web-ui:lp-collapse-plugin-sections`;function Wh(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Uh),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(Uh,JSON.stringify([...n]))}catch{}return n})},[])]}var Gh=`pi-web-ui:lp-sizes`,Kh={projects:1,groups:1,convs:1,sessions:1},qh=32,Jh={running:`pluginRunStatusRunning`,done:`pluginRunStatusDone`,error:`pluginRunStatusError`},Yh=72;function Xh(){try{return Kr(localStorage.getItem(Gh),Kh)}catch{return{...Kh}}}var Zh=(0,Q.memo)(function({sessionFile:e,conversations:t,elsewhere:n,sessions:r,projects:i,activeConversationId:a,activeGroupId:o,panelSend:c,active:l,collapsible:u,onToggleCollapse:d,pathCompletions:f,uiContextSession:p,uiLeftSessions:m,uiContextProject:h,uiProjectsActions:_,uiLeftProject:v,uiRunningActions:b,uiHistoryActions:x,uiSections:S,renderPluginSectionBody:C,uiPluginRunning:w,onPluginRunningAction:T,uiLeftRunning:E,uiLeftHistory:D,onUiAction:O,presetNames:k,transition:A,onOpenSandboxModal:j}){let N=V(),ee=rn(),F=e,te=en(`ready`),ne=en(`status`),re=en(`cwd`),I=en(`workspaceRoots`),L=re,[ie,ae]=(0,Q.useState)(!1),[oe,se]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(null),[de,B]=(0,Q.useState)(null),[fe,he]=(0,Q.useState)(``),[H,ge]=Hh(Lh,!1),[U,W]=Hh(Rh,!1),[G,_e]=Hh(zh,!1),[K,q]=Wh(),[J,ve]=(0,Q.useState)(!1),[Y,ye]=Vh(),[be,xe]=(0,Q.useState)(60);(0,Q.useEffect)(()=>{xe(60)},[L]);let Se=(0,Q.useMemo)(()=>{if(r.length<=be)return r;let e=F?r.findIndex(e=>e.path===F):-1,t=e>=be?e+10:be;return r.slice(0,t)},[r,be,F]),Ce=(0,Q.useCallback)((e,t)=>{if(!t)return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==a).length;let n=new Map(e.map(e=>[e.id,e])),r=e=>{if(e.id===t)return(n.get(t)?.isSubagent??!1)&&!e.isStreaming&&e.id!==a;let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==a&&r(e)).length},[a]),we=(0,Q.useCallback)((e,t)=>{if(!t)return e.filter(e=>e.isSubagent).length;let n=new Map(e.map(e=>[e.id,e])),r=e=>{if(e.id===t)return n.get(t)?.isSubagent??!1;let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&r(e)).length},[]),Te=(0,Q.useCallback)((e,t)=>{if(!t)return 0;let n=new Map(e.map(e=>[e.id,e])),r=e=>{let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&e.isStreaming&&r(e)).length},[]),Ee=(0,Q.useRef)(null),De=(0,Q.useRef)(null),X=(0,Q.useRef)(()=>{}),Oe=Gi(p??[]).length>0,ke=(0,Q.useCallback)((e,n,i)=>{Ee.current={x:e,y:n,target:i};let a=i.kind===`running`?i.id:void 0,o=i.kind===`elsewhere`,s=a??(o&&i.id||void 0),c=Ce(t,a),l=c===0?N(`noFinishedSubagents`):N(a?`dismissFinishedSubagentsScoped`:`dismissFinishedSubagents`,{n:c}),u=!!a&&De.current===a;Pi({x:e,y:n,slot:`contextmenu.session`,target:i,entries:(p??[]).map(e=>{if(e.source!==`host`)return e;if(e.id===`host:conv-rename`)return i.kind===`running`||i.kind===`history`?e:{...e,hidden:!0};if(e.id===`host:conv-takeover`){let t=!!(i.pseudo&&i.owner?.startsWith(`scheduler:`));return o&&s&&i.owner&&!t?e:{...e,hidden:!0}}if(o&&(e.id===`host:conv-dismiss-subagents`||e.id===`host:conv-force-dismiss`))return{...e,hidden:!0};if(e.id===`host:conv-dismiss-subagents`)return{...e,label:l,...c===0?{when:[...e.when??[],`disabled`]}:{}};if(e.id===`host:conv-force-dismiss`)return a?{...e,...u?{label:N(`forceDismissConfirm`)}:{}}:{...e,hidden:!0};if(e.id===`host:conv-pin`){if(i.kind===`history`)return r.find(e=>e.path===i.id)?.pinned?{...e,label:N(`unpinConversation`)}:e;if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return!n||n.isSubagent?{...e,hidden:!0}:n.pinned?{...e,label:N(`unpinConversation`)}:e}if(e.id===`host:conv-persist`){if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return!n||!n.isSubagent&&n.sessionFile?{...e,hidden:!0}:n?.isEphemeral?{...e,label:N(`saveEphemeral`)}:e}if(e.id===`host:conv-copy-id`)return s?e:{...e,hidden:!0};if(e.id===`host:conv-copy-path`)return i.kind===`history`?e:a?t.some(e=>e.id===a&&e.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}:{...e,hidden:!0};if(e.id===`host:conv-copy-link`){if(i.kind===`history`)return r.find(e=>e.path===i.id)?.sessionId||ts(i.id)?e:{...e,hidden:!0};if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return n?.sessionId||ts(n?.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}}return e.id===`host:conv-quote`?ee.conversationRef&&(s||i.kind===`history`)?e:{...e,hidden:!0}:e}),onHostAction:(e,t)=>X.current(e,t)})},[p,t,Ce,N,ee.conversationRef]);X.current=(0,Q.useCallback)((e,n)=>{let i=n.kind===`running`?n.id:void 0,a=i??(n.kind===`elsewhere`&&n.id||void 0);if(e.id===`host:conv-takeover`){n.kind===`elsewhere`&&a&&n.owner&&c({type:`take_over_conversation`,owner:n.owner,id:a});return}if(e.id===`host:conv-dismiss-subagents`){c(i?{type:`dismiss_finished_subagents`,parentId:i}:{type:`dismiss_finished_subagents`});return}if(e.id===`host:conv-force-dismiss`){let e=Ee.current;if(!i||!e)return;if(De.current!==i)return De.current=i,ke(e.x,e.y,e.target),!0;De.current=null,c({type:`dismiss_conversation`,id:i,force:!0});return}if(e.id===`host:conv-persist`){i&&c({type:`persist_conversation`,id:i});return}if(e.id===`host:conv-pin`){if(n.kind===`history`){let e=r.find(e=>e.path===n.id);c({type:`pin_session`,path:n.id,pinned:!e?.pinned});return}i&&c({type:`pin_conversation`,id:i,pinned:!t.find(e=>e.id===i)?.pinned});return}if(e.id===`host:conv-copy-id`&&a){navigator.clipboard?.writeText(a).catch(()=>{});return}if(e.id===`host:conv-copy-path`){let e=n.kind===`history`?n.id:i&&t.find(e=>e.id===i)?.sessionFile||void 0;e&&navigator.clipboard?.writeText(e).catch(()=>{});return}if(e.id===`host:conv-copy-link`){let e=n.kind===`history`?r.find(e=>e.path===n.id)?.sessionId||ts(n.id):i?t.find(e=>e.id===i)?.sessionId||ts(t.find(e=>e.id===i)?.sessionFile):null;if(e){let t=es(window.location.href,{sessionId:e});navigator.clipboard?.writeText(t).catch(()=>{})}return}if(e.id===`host:conv-quote`){n.kind===`history`&&n.id?Ft({attachments:[{path:``,key:`conv||${n.id}`,name:n.label||n.id,mode:`conversation`,sessionPath:n.id}]}):a&&Ft({attachments:[{path:``,key:`conv|${a}|`,name:n.label||a,mode:`conversation`,conversationId:a}]});return}if(e.id===`host:conv-rename`){if(se(null),i){let e=t.find(e=>e.id===i);he(e?.title??n.label??``),B(`conv:${i}`)}else if(n.kind===`history`&&n.id){let e=r.find(e=>e.path===n.id);he(e?.name??n.label??``),B(n.id)}return}},[c,ke,t,r]);let je=(e,t,n)=>!e||e.length===0?null:(0,$.jsx)(`span`,{className:t,children:e.map((e,t)=>{let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`lp-slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`lp-slot-badge`,title:a,children:e.badge??i},r):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`lp-slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onClick:e=>e.stopPropagation(),onChange:t=>{t.stopPropagation(),O?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsx)(`button`,{type:`button`,className:`lp-slot-btn`,title:a,"aria-label":i,onClick:t=>{t.stopPropagation(),n?O?.(e,void 0,n):O?.(e)},children:e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):(0,$.jsx)(`span`,{children:i})},r)})}),Me=(0,Q.useCallback)((e,t)=>{Ih(e.target)||Oe&&(e.preventDefault(),e.stopPropagation(),De.current=null,ke(e.clientX,e.clientY,t))},[Oe,ke]),Ne=(0,Q.useRef)(null),[Pe,Fe]=(0,Q.useState)(()=>Xh());(0,Q.useEffect)(()=>{try{localStorage.setItem(Gh,JSON.stringify(Pe))}catch{}},[Pe]);let Ie=(0,Q.useMemo)(()=>{let e=new Set,r=new Set;for(let n of t)n.sessionFile&&e.add(n.sessionFile),r.add(`${n.cwd}\0${n.title}`);let i=[],a=new Set;for(let t of n){if(t.sessionFile&&e.has(t.sessionFile)||r.has(`${t.cwd}\0${t.title}`))continue;let n=t.sessionFile?`file:${t.sessionFile}`:`title:${t.cwd}\0${t.title}`;a.has(n)||(a.add(n),i.push({id:t.sessionFile?`elsewhere:${t.cwd}:${t.sessionFile}`:`elsewhere:${t.cwd}:${t.title}${t.owner?`:${t.owner}`:``}`,title:t.title,cwd:t.cwd,messageCount:0,isStreaming:t.isStreaming,isSubagent:!1,elsewhere:!0,pseudo:!!t.pseudo,ownerOffline:!!t.ownerOffline,sessionFile:t.sessionFile,...t.owner&&t.convId?{owner:t.owner,convId:t.convId}:{},...t.hasQuestion?{hasQuestion:!0}:{}}))}return[...t,...i]},[t,n]),Le=Ur(Hr(S)),Re=Le.filter(e=>e.shown),ze=e=>e===`projects`?H:e===`convs`?U:e===`sessions`?G:e===`groups`?J:K.has(e),Ve=(w??[]).reduce((e,t)=>e+t.items.length,0),He=Ie.length+Ve,Ue=Wr(Le,e=>e===`projects`?i.length>0:e!==`convs`||He>0),We=()=>{let e=w??[];return e.length===0?null:e.map(e=>(0,$.jsxs)(`div`,{className:`panel-conv-group lp-plugin-group`,children:[(0,$.jsxs)(`div`,{className:`panel-conv-group-title`,title:e.pluginId,children:[N(`leftPanelPluginGroup`),` · `,e.pluginName]}),e.items.map(t=>(0,$.jsx)(`div`,{className:`lp-row lp-plugin-row`,children:(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-plugin-item${t.action?``:` is-static`}`,title:t.hint?`${t.title} — ${t.hint}`:t.title,onClick:()=>T?.(e,t),children:[(0,$.jsx)(`span`,{className:`lp-plugin-dot st-${t.status}`,title:N(Jh[t.status])}),t.icon?(0,$.jsx)(`span`,{className:`lp-plugin-icon`,"aria-hidden":!0,children:t.icon}):null,(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsx)(`span`,{className:`session-title`,children:t.title}),t.hint?(0,$.jsx)(`span`,{className:`session-sub`,children:t.hint}):null]})]})},t.id))]},`plugin:${e.pluginId}`))},Ge=(0,Q.useMemo)(()=>[...m??[],...E??[]],[m,E]),Ke=(0,Q.useMemo)(()=>[...m??[],...D??[]],[m,D]),qe=(0,Q.useCallback)((e,t)=>n=>{n.preventDefault();let r=n.currentTarget,i=n.clientY,a={...Pe},o=Ne.current;if(!o)return;let s=Ue.filter(e=>ze(e)).length,c=Ue.filter(e=>!ze(e)).reduce((e,t)=>e+(a[t]??1),0)||1,l=Math.max(120,o.clientHeight-s*qh);r.classList.add(`dragging`),document.body.classList.add(`lp-resizing`);let u=n=>{let{above:r,below:o}=Jo({start:{above:a[e]??1,below:a[t]??1},deltaPx:n.clientY-i,availablePx:l,totalWeight:c,minAbovePx:Yh,minBelowPx:Yh});Fe(n=>({...n,[e]:r,[t]:o}))},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),r.classList.remove(`dragging`),document.body.classList.remove(`lp-resizing`)};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d)},[Pe,Ue,H,U,G,J,K]);(0,Q.useEffect)(()=>{l&&te&&ne===`open`&&re&&(c({type:`list_sessions`}),c({type:`list_projects`}))},[l,te,ne,re,c]);let Je=e=>{let t=e.displayName||e.name||e.firstMessage?.trim();return t&&t.length>0?t:N(`emptyChat`)},Ye=e=>e.split(/[\\/]/).pop()||e,Xe=Gi(h??[]).length>0,Ze=(0,Q.useCallback)((e,t)=>{Ih(e.target)||Xe&&(e.preventDefault(),e.stopPropagation(),Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.path,kind:`project`,label:Ye(t.path)},entries:h??[]}))},[Xe,h]),Qe=(e,t,n,r,i)=>{let a=oe===e;return(0,$.jsx)(`button`,{type:`button`,className:`lp-del ${a?`confirm`:``}`,title:a?n:t,onClick:t=>{t.stopPropagation(),a?(se(null),r()):se(e)},children:a?(0,$.jsx)(z,{}):i??(0,$.jsx)(g,{})})},$e=(e,t,n,r,i,a)=>(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,onClick:n,title:N(t?`expandSection`:`collapseSection`),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[e,r===void 0?``:` (${r})`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:t?(0,$.jsx)(pe,{}):(0,$.jsx)(s,{})})]}),i||a?(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[i,a]}):null]}),et=Ue.filter(e=>!ze(e)),tt=et.reduce((e,t)=>e+(Pe[t]??1),0)||1,nt=e=>et.length<=1?1:(Pe[e]??1)/tt*et.length,at=new Map(Gr(Ue,ze).map(([e,t])=>[e,(0,$.jsx)(`div`,{className:`lp-sash`,onPointerDown:qe(e,t),onDoubleClick:()=>Fe({...Kh}),title:N(`dragToResize`)},`sash-${e}`)])),ot=(0,Q.useCallback)(e=>{let t=e.target;t&&(t.closest(`.lp-row`)||t.closest(`button, input, select, textarea, a`)||(c({type:`new_chat`}),Xt()))},[c]),st={projects:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section panel-projects ${H||i.length===0?`collapsed`:``}`,style:i.length>0&&!H?{flex:`${nt(`projects`)} 1 0px`}:void 0,children:[$e(N(`recentProjects`),H,ge,i.length,(0,$.jsxs)($.Fragment,{children:[j&&(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action lp-sandbox-action`,title:N(`sandboxNewBtn`),"aria-label":N(`sandboxNewBtn`),onClick:()=>j(),children:(0,$.jsx)(An,{})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action`,title:N(`manageProjects`),"aria-label":N(`manageProjects`),onClick:()=>ae(!0),children:(0,$.jsx)(y,{})})]}),je(_,`lp-slot-section`)),i.length>0&&!H&&(0,$.jsx)(`div`,{className:`lp-section-body projects-scroll`,onDoubleClick:ot,children:i.map(e=>{let t=e=>(e??``).trim().replace(/[\\/]+$/,``).toLowerCase(),n=L===e.path,r=A?.kind===`cwd`&&t(A.target)===t(e.path),i=e.sandbox,a=i?i.name:Ye(e.path);return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>se(t=>t===`proj:${e.path}`?null:t),onContextMenu:t=>Ze(t,e),children:[(0,$.jsxs)(`button`,{type:`button`,className:`project-item ${n?`active`:``} ${r?`switching`:``}`,title:i?.sourcePath?`${a}\n${N(`sandboxSourceLabel`)}: ${i.sourcePath}\n${e.path}`:e.path,disabled:r,onClick:()=>{!n&&!r&&c({type:`set_cwd`,path:e.path})},onDoubleClick:t=>{t.stopPropagation(),!r&&(n||c({type:`set_cwd`,path:e.path}),c({type:`new_chat`}),Xt())},children:[r?(0,$.jsx)(Zo,{className:`project-icon spin`}):i?(0,$.jsx)(An,{className:`project-icon sandbox-icon`}):(0,$.jsx)(Be,{className:`project-icon`}),(0,$.jsxs)(`span`,{className:`project-info`,children:[(0,$.jsxs)(`span`,{className:`project-name`,children:[a,i&&(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${i.ephemeral?`ephemeral`:`permanent`}`,children:i.ephemeral?N(`sandboxBadgeEphemeral`):N(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`project-path`,children:i?.sourcePath?`← ${Ye(i.sourcePath)} · ${e.path}`:e.path})]}),(0,$.jsx)(`span`,{className:`project-time ${r?`switching-pct`:``}`,children:r?`${A.progress}%`:Fh(e.lastUsed)})]}),Qe(`proj:${e.path}`,N(i?`sandboxActionDestroyTip`:`deleteProject`),N(i?`sandboxActionDestroy`:`deleteProjectConfirm`),()=>{Ch(e.path),Dh(e.path),c(i?{type:`destroy_sandbox`,path:e.path}:{type:`remove_project`,path:e.path})}),je(v,`lp-slot-project`,{id:e.path,kind:`project`,label:a})]},e.path)})})]})}),convs:(0,$.jsx)($.Fragment,{children:He>0&&(0,$.jsxs)(`div`,{className:`lp-section lp-section-convs panel-convs ${U?`collapsed`:``}`,style:U?void 0:{flex:`${nt(`convs`)} 1 0px`},onContextMenu:e=>Me(e,{id:``,kind:`section`,label:N(`runningConversations`)}),children:[$e(N(`runningConversations`),U,W,He,void 0,je(b,`lp-slot-section`)),!U&&(0,$.jsxs)(`div`,{className:`lp-section-body convs-scroll`,onDoubleClick:ot,children:[Yo(Ie,re,a).map(e=>(0,$.jsxs)(`div`,{className:`panel-conv-group`,children:[!e.isCurrent&&(0,$.jsx)(`div`,{className:`panel-conv-group-title`,title:e.cwd,onContextMenu:t=>Ze(t,{path:e.cwd,lastUsed:0}),onDoubleClick:t=>{t.stopPropagation(),c({type:`set_cwd`,path:e.cwd}),c({type:`new_chat`}),Xt()},children:Ye(e.cwd)}),Xo(e.convs,Y).map(({c:n,depth:r,hasKids:i,isCollapsed:o,descendantCount:s,hasStreaming:l,hasError:u,hasQuestion:d})=>{if(n.elsewhere){let e=n.owner,t=n.convId,r=!!n.pseudo,i=!!n.ownerOffline&&!r,a=r&&typeof e==`string`&&e.startsWith(`scheduler:`),o=!!(e&&t)&&!a,s=le===n.id,l=s?N(`takeoverConfirm`):a?`${N(`elsewherePseudoTip`)}\n${n.cwd}`:r?`点击直接在电脑端打开此对话\n${n.cwd}`:`${N(i?`elsewhereOfflineTip`:`elsewhereTip`)}\n${n.cwd}`;return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>ue(e=>e===n.id?null:e),onContextMenu:i=>Me(i,{id:t??n.id,kind:`elsewhere`,label:n.title,...e?{owner:e}:{},...r?{pseudo:!0}:{}}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item elsewhere-item${o?``:` elsewhere-static`}${s?` confirm`:``}`,title:l,tabIndex:o?0:-1,onClick:o?()=>{if(r){c({type:`take_over_conversation`,owner:e,id:t});return}if(!s){ue(n.id);return}ue(null),c({type:`take_over_conversation`,owner:e,id:t})}:void 0,children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:n.isStreaming?(0,$.jsx)(`span`,{className:`conv-streaming`,title:N(`streaming`)}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsxs)(`span`,{className:`session-title`,children:[(0,$.jsx)(`span`,{className:`elsewhere-badge`,children:N(r?`elsewherePseudoBadge`:`elsewhereBadge`)}),i&&(0,$.jsx)(`span`,{className:`elsewhere-badge offline`,title:N(`elsewhereOfflineTip`),children:N(`elsewhereOfflineBadge`)}),n.hasQuestion&&e&&t&&!r&&(0,$.jsx)(`span`,{className:`question-badge clickable`,title:N(`takeoverHasQuestion`),onClick:n=>{n.stopPropagation(),c({type:`peek_elsewhere_question`,owner:e,id:t})},children:`?`}),s?N(`takeoverConfirm`):n.title]}),(0,$.jsx)(`span`,{className:`session-sub`,children:Ye(n.cwd)})]})]}),Oe&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-elsewhere-act`,title:N(`elsewhereActions`),onClick:i=>{i.stopPropagation(),De.current=null;let a=i.currentTarget.getBoundingClientRect();ke(a.left,a.bottom+4,{id:t??n.id,kind:`elsewhere`,label:n.title,...e?{owner:e}:{},...r?{pseudo:!0}:{}})},children:(0,$.jsx)(me,{})})]},n.id)}let f=a===n.id;return(0,$.jsxs)(`div`,{className:`lp-row${r>0?` lp-sub`:``}${i?` lp-has-kids`:``}`,style:r>0?{"--depth":Math.min(r,4)}:void 0,onMouseLeave:()=>se(e=>e===`conv:${n.id}`?null:e),onContextMenu:e=>Me(e,{id:n.id,kind:`running`,label:n.title}),children:[i&&(0,$.jsx)(`button`,{type:`button`,className:`lp-tree-caret${o?` collapsed`:` expanded`}`,title:N(o?`expandSubagents`:`collapseSubagents`),"aria-label":N(o?`expandSubagents`:`collapseSubagents`),onClick:e=>{e.stopPropagation(),ye(n.id)},children:o?(0,$.jsx)(P,{}):(0,$.jsx)(pe,{})}),(0,$.jsxs)(`button`,{type:`button`,className:`session-item ${f?`active`:``}`,title:`${n.title}${e.isCurrent?``:` — ${e.cwd}`}`,onClick:()=>{f||c({type:`switch_conversation`,id:n.id})},children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:i?(0,$.jsx)(`span`,{className:`session-icon-placeholder`}):n.isStreaming?(0,$.jsx)(`span`,{className:`conv-streaming`,title:N(`streaming`)}):n.isSubagent?(0,$.jsx)(ce,{className:`session-icon subagent-icon`}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[de===`conv:${n.id}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:fe,placeholder:N(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>he(e.target.value),onKeyDown:e=>{if(e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing){let e=fe.trim();e&&c({type:`rename_conversation`,id:n.id,name:e}),B(null)}else e.key===`Escape`&&B(null)},onBlur:()=>B(null)}):(0,$.jsxs)(`span`,{className:`session-title`,children:[n.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:N(`pinnedConversation`),children:`📌`}),i&&n.isStreaming&&(0,$.jsx)(`span`,{className:`conv-streaming-dot`,title:N(`streaming`)}),n.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,children:N(`ephemeralBadge`)}),n.forkFrom&&(0,$.jsxs)(`span`,{className:`preset-badge fork-badge`,title:`${N(`forkBadgeTip`)}: ${n.forkFrom.title??n.forkFrom.conversationId}`,children:[`🌿 `,N(`forkBadge`)]}),n.agentPreset&&n.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`preset-badge`,title:n.agentPreset,children:k?.[n.agentPreset]??n.agentPreset}),n.title,n.error&&(0,$.jsx)(`span`,{className:`conv-error-badge`,title:N(`convErrorBadge`,{error:n.error})}),n.hasQuestion&&(0,$.jsx)(`span`,{className:`question-badge`,title:N(`waitingQuestionBadge`),children:`?`}),i&&o&&(0,$.jsxs)(`span`,{className:`subagents-collapsed-badge${l?` has-streaming`:d?` has-question`:u?` has-error`:``}`,title:N(l?`subagentsStreamingTip`:d?`subagentsQuestionTip`:u?`subagentsErrorTip`:`subagentsCountTip`,{n:s}),onClick:e=>{e.stopPropagation(),ye(n.id)},children:[l&&(0,$.jsx)(`span`,{className:`subagent-dot streaming`}),d&&(0,$.jsx)(`span`,{className:`subagent-dot question`,children:`?`}),u&&(0,$.jsx)(`span`,{className:`subagent-dot error`}),(0,$.jsx)(`span`,{className:`subagents-count-text`,children:N(`subagentBadgeCount`,{n:s})})]})]}),de===`conv:${n.id}`?null:(0,$.jsxs)(`span`,{className:`session-sub`,children:[n.isSubagent&&(0,$.jsx)(`span`,{className:`subagent-tag`,children:N(`subagentBadge`)}),n.isSubagent?` · `:null,f?N(`current`):N(`messageCount`,{n:n.messageCount})]})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:N(`renameSession`),onClick:e=>{e.stopPropagation(),se(null),he(n.title),B(`conv:${n.id}`)},children:(0,$.jsx)(M,{})}),(()=>{let e=`conv:${n.id}`,r=oe===e,i=Ce(t,n.id),a=Te(t,n.id),o=we(t,n.id);return o===0&&!n.isStreaming?n.hasUserTerminals?Qe(e,N(`dismissConversation`),N(`dismissTerminalsConfirm`),()=>c({type:`dismiss_conversation`,id:n.id,force:!0}),(0,$.jsx)(R,{})):Qe(e,N(`dismissConversation`),N(`dismissConversationConfirm`),()=>c({type:`dismiss_conversation`,id:n.id}),(0,$.jsx)(R,{})):o===0?Qe(e,N(`dismissConversation`),N(`dismissStreamingConfirm`),()=>c({type:`dismiss_conversation`,id:n.id,force:!0}),(0,$.jsx)(R,{})):r?(0,$.jsxs)(`span`,{className:`lp-del-group`,children:[i>0&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt`,title:N(`dismissFinishedSubagentsScoped`,{n:i}),onClick:e=>{e.stopPropagation(),se(null),c({type:`dismiss_finished_subagents`,parentId:n.id})},children:N(`dismissFinishedOnly`,{n:i})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt danger`,title:N(`forceDismissTitle`,{n:o,m:a}),onClick:e=>{e.stopPropagation(),se(null),c({type:`dismiss_conversation`,id:n.id,force:!0})},children:N(`dismissForceAll`,{n:o})})]}):(0,$.jsx)(`button`,{type:`button`,className:`lp-del`,title:N(`dismissConversation`),onClick:t=>{t.stopPropagation(),se(e)},children:(0,$.jsx)(R,{})})})(),je(Ge,`lp-slot-sessions`)]},n.id)})]},e.cwd)),We()]})]})}),sessions:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section lp-section-sessions panel-sessions ${G?`collapsed`:``}`,style:G?void 0:{flex:`${nt(`sessions`)} 1 0px`},children:[$e(N(`historySessions`),G,_e,r.length,(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-new-chat-action`,title:N(`newChatTip`),"aria-label":N(`newChat`),onClick:()=>{c({type:`new_chat`}),Xt()},children:(0,$.jsx)(rt,{})}),je(x,`lp-slot-section`)),!G&&(0,$.jsxs)(`div`,{className:`lp-section-body sessions-scroll`,onDoubleClick:ot,onScroll:e=>{if(Se.length>=r.length)return;let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<180&&xe(e=>Math.min(r.length,e+60))},children:[r.length===0&&(0,$.jsx)(`div`,{className:`panel-empty`,children:N(`noHistory`)}),Se.map(e=>{let t=e=>(e??``).trim().replace(/[\\/]+$/,``).toLowerCase(),n=F===e.path,i=A?.kind===`session`&&t(A.target)===t(e.path);return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>se(t=>t===`sess:${e.path}`?null:t),onContextMenu:t=>Me(t,{id:e.path,kind:`history`,label:Je(e)}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item ${n?`active`:``} ${i?`switching`:``}`,title:e.path,disabled:i,onClick:()=>{de||i||n||c({type:`switch_session`,path:e.path})},children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:i?(0,$.jsx)(Zo,{className:`session-icon spin`}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[de===e.path?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:fe,placeholder:N(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>he(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=fe.trim();t&&c({type:`rename_session`,path:e.path,name:t}),B(null)}else t.key===`Escape`&&B(null)},onBlur:()=>B(null)}):(0,$.jsxs)(`span`,{className:`session-title`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:N(`pinnedConversation`),children:`📌`}),Je(e)]}),de===e.path?null:(0,$.jsxs)(`span`,{className:`session-sub`,children:[n?N(`current`):N(`messageCount`,{n:e.messageCount}),e.source===`tui`&&(0,$.jsx)(`span`,{className:`session-src`,title:N(`tuiTip`),children:`TUI`}),e.parentSessionPath&&(0,$.jsx)(`span`,{className:`session-src session-fork-badge`,title:N(`forkedSessionTip`,{parent:(()=>{let n=t(e.parentSessionPath).replace(/\\/g,`/`),i=r.find(e=>t(e.path).replace(/\\/g,`/`)===n);return i?Je(i):(e.parentSessionPath.replace(/\\/g,`/`).split(`/`).pop()??e.parentSessionPath).replace(/\.jsonl$/i,``)})()}),children:N(`forkedSessionBadge`)})]})]}),(0,$.jsx)(`span`,{className:`session-time ${i?`switching-pct`:``}`,children:i?`${A.progress}%`:Fh(e.modified)})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:N(`renameSession`),onClick:t=>{t.stopPropagation(),se(null),he(e.name??``),B(e.path)},children:(0,$.jsx)(M,{})}),Qe(`sess:${e.path}`,N(`deleteSession`),N(`deleteSessionConfirm`),()=>{Mh(e.path,L),c({type:`delete_session`,path:e.path})}),je(Ke,`lp-slot-sessions`)]},e.path)})]})]})})},ct=e=>{let t=Re.find(t=>t.key===e)?.entry;if(!t)return null;let n=ze(e);return(0,$.jsxs)(`div`,{className:`lp-section lp-section-plugin ${n?`collapsed`:``}`,style:n?void 0:{flex:`${nt(e)} 1 0px`},children:[$e(t.label,n,()=>q(e)),!n&&(0,$.jsx)(`div`,{className:`lp-section-body lp-plugin-section-body`,children:C?.(t)??null})]})},lt=e=>e===`groups`?(0,$.jsx)(Ko,{active:l,selectedRoomId:o,flex:nt(`groups`),onCollapsedChange:ve}):e===`projects`||e===`convs`||e===`sessions`?st[e]:ct(e);return(0,$.jsxs)(`aside`,{ref:Ne,className:`panel panel-left lp-panel`,children:[u&&d&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:N(`collapsePanel`),onClick:d,children:(0,$.jsx)(it,{})}),Re.map(({key:e})=>(0,$.jsxs)(Q.Fragment,{children:[lt(e),at.get(e)??null]},e)),(0,$.jsx)(ba,{open:ie,currentCwd:L,pathCompletions:f??[],workspaceRoots:I,onClose:()=>ae(!1),onSelectDirectory:e=>c({type:`set_cwd`,path:e}),onCreateProject:e=>c({type:`make_dir`,path:e,setAsCwd:!0})})]})}),Qh=e=>/\.(zip|tar|tar\.gz|tgz|gz)$/i.test(e);function $h(e,t={}){let n={archive:q(`/api/file-transfer/archive`),upload:q(`/api/file-transfer/upload`)},r=new URL(Qe(`${n[e]}?${new URLSearchParams({clientId:yh(),...t})}`),window.location.href);if(r.origin!==window.location.origin||r.pathname!==new URL(n[e],window.location.href).pathname)throw Error(`File transfers must use an allowlisted same-origin endpoint`);return r}async function eg(e,t,n){let r=await fetch($h(`archive`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-File-Operation":`1`},body:JSON.stringify({action:e,path:t,...n})});if(!r.ok)throw Error(await r.text());if(e===`download`){let e=r.headers.get(`content-disposition`)??``,t=/filename\*=UTF-8''([^;]+)/i.exec(e)?.[1],n=/filename="([^"]+)"/i.exec(e)?.[1],i=t?decodeURIComponent(t):n??`archive.tar.gz`,a=await Bu(await r.blob(),i);if(!a.ok&&!a.cancelled)throw Error(a.error)}}async function tg(){let e=window.showDirectoryPicker;if(!e)return null;let t=await e.call(window),n=[];async function r(e,t){if(n.length>=2e4)throw Error(`Folder exceeds 20,000 entries`);if(n.push(e.kind===`file`?{path:t,file:await e.getFile()}:{path:t}),e.kind===`directory`)for await(let n of e.values())await r(n,`${t}/${n.name}`)}return await r(t,t.name),n}async function ng(e,t,n,r=32){if(t.length>2e4)throw Error(`Folder exceeds 20,000 entries`);for(let e of t)if(e.file&&e.file.size>r*1024*1024)throw Error(`File exceeds ${r} MiB: ${e.path}`);let i=t.reduce((e,t)=>e+(t.file?.size??0),0),a=0,o=0;for(let r of t){let t=$h(`upload`,{dir:e,name:r.path,kind:r.file?`file`:`directory`}),s=r.file??new Blob;await new Promise((e,c)=>{let l=new XMLHttpRequest,u=0,d=e=>n?.({done:a,uploadedBytes:o+u,totalBytes:i,path:r.path,phase:e});l.open(`POST`,t.href),l.setRequestHeader(`Content-Type`,`application/octet-stream`),l.setRequestHeader(`X-File-Operation`,`1`),l.upload.onprogress=e=>{u=Math.min(e.loaded,s.size),d(u===s.size?`waiting`:`uploading`)},l.upload.onload=()=>{u=s.size,d(`waiting`)},l.onload=()=>{if(l.status<200||l.status>=300){c(Error(`${r.path}: ${l.responseText||`HTTP ${l.status}`}`));return}a++,o+=s.size,u=0,d(`confirmed`),e()},l.onerror=()=>c(Error(`${r.path}: Network error`)),l.onabort=()=>c(Error(`${r.path}: Upload aborted`)),l.ontimeout=()=>c(Error(`${r.path}: Upload timed out`)),d(s.size===0?`waiting`:`uploading`),l.send(s)})}}function rg({request:e,onClose:t,onComplete:n}){let r=V(),i=en(`folderUploadMaxMb`),[a,o]=(0,Q.useState)(e.dir),[s,c]=(0,Q.useState)(`skip`),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{v.current?.showModal()},[]);let y=r(e.action===`upload`?`fileUploadFolder`:e.action===`extract`?`fileExtract`:e.action===`download`?`fileCompressDownload`:`fileCompress`);async function b(){try{let e=await tg();e?(u(e),f(null)):p.current?.click()}catch(e){e instanceof DOMException&&e.name===`AbortError`||_(String(e))}}async function x(){f(null),h(!0),_(``);try{e.action===`upload`?await ng(e.dir,l,f,i):await eg(e.action,e.path,{destination:a,policy:s}),n(),t()}catch(e){_(e instanceof Error?e.message:String(e)),n()}finally{h(!1)}}return(0,bn.createPortal)((0,$.jsx)(`dialog`,{ref:v,className:`file-transfer-dialog`,"aria-labelledby":`file-transfer-title`,onCancel:e=>{e.preventDefault(),m||t()},children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),x()},children:[(0,$.jsxs)(`div`,{className:`file-transfer-head`,children:[(0,$.jsx)(`h3`,{id:`file-transfer-title`,children:y}),(0,$.jsx)(`button`,{type:`button`,className:`file-transfer-close`,title:r(`close`),"aria-label":r(`close`),disabled:m,onClick:t,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`p`,{className:`file-transfer-path`,children:(e.action===`upload`?e.dir:e.path)||`.`}),(0,$.jsx)(`p`,{children:r(`fileArchiveLimits`)}),e.action===`extract`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[r(`fileExtractDestination`),(0,$.jsx)(`input`,{value:a,disabled:m,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{children:[r(`fileConflictPolicy`),(0,$.jsxs)(`select`,{value:s,disabled:m,onChange:e=>c(e.target.value),children:[(0,$.jsx)(`option`,{value:`skip`,children:r(`fileConflictSkip`)}),(0,$.jsx)(`option`,{value:`overwrite`,children:r(`fileConflictOverwrite`)}),(0,$.jsx)(`option`,{value:`error`,children:r(`fileConflictError`)})]})]})]}),e.action===`upload`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:r(`fileFolderUploadHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:()=>void b(),children:r(`fileChooseFolder`)}),(0,$.jsx)(`input`,{type:`file`,"aria-label":y,multiple:!0,hidden:!0,disabled:m,ref:e=>{p.current=e,e?.setAttribute(`webkitdirectory`,``)},onChange:e=>{u(Array.from(e.target.files??[],e=>({path:e.webkitRelativePath||e.name,file:e}))),f(null)}}),(0,$.jsxs)(`p`,{"aria-live":`polite`,children:[d?.done??0,` / `,l.length]}),d&&(0,$.jsxs)($.Fragment,{children:[d.totalBytes>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`progress`,{"aria-label":y,value:d.uploadedBytes,max:d.totalBytes}),(0,$.jsxs)(`p`,{children:[d.uploadedBytes.toLocaleString(),` / `,d.totalBytes.toLocaleString(),` B`]})]}),m&&d.phase!==`confirmed`&&(0,$.jsx)(`p`,{className:`file-transfer-path`,role:`status`,children:d.phase===`waiting`?r(`folderUploadWaiting`,{name:d.path}):r(`folderUploadSending`,{name:d.path,percent:Math.floor(d.uploadedBytes/d.totalBytes*100)})})]})]}),g&&(0,$.jsx)(`p`,{role:`alert`,children:r(`fileTransferFailed`,{error:g})}),(0,$.jsxs)(`div`,{className:`file-transfer-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:t,children:r(`cancel`)}),(0,$.jsx)(`button`,{type:`submit`,className:`btn primary`,disabled:m||e.action===`upload`&&l.length===0,children:m?r(`fileTransferBusy`):y})]})]})}),document.body)}function ig(e){return e.startsWith(`.`)&&e!==`..`}function ag(e,t){return t?e:e.filter(e=>!ig(e.name))}function og(e){return e instanceof Error?e.message:String(e)}function sg(e,t,n,r){let i=H(n);switch(e.kind){case`no-client`:return i?`插件 ${t} 没有客户端脚本(client/entry.mjs),无法显示这一页。`:`Plugin ${t} ships no client bundle (client/entry.mjs), so this page cannot be shown.`;case`load`:return i?`插件 ${t} 的页面脚本加载失败:${e.detail}`:`Failed to load plugin ${t}'s page bundle: ${e.detail}`;case`mount`:return`${r(`pluginMountFailed`,{name:t})}:${e.detail}`}}function cg({plugin:e,epoch:t,send:n,className:r}){let i=(0,Q.useRef)(null),{locale:a}=Ue(),o=V(),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{l.current=n},[n]),(0,Q.useEffect)(()=>{let n=i.current;if(!n)return;let r=!1,a,o=!1;if(c(null),!e.hasClient){c({kind:`no-client`});return}return(async()=>{try{if(await Nm(e,t),r)return;let i=await Lt(e.id,()=>Os(()=>import(Om(e.id,t)),[],import.meta.url));if(r)return;let s=i.default;if(!s||typeof s.mount!=`function`)throw Error(`client/entry.mjs 没有导出 default.mount()`);o=!0;let c=!!(e.isolated||s.isolated||s.shadow),{container:u}=dm(n,{isolated:c});a=s.mount(u,Fm(e.id,e=>l.current(e)))}catch(t){if(r)return;console.error(`[plugin:${e.id}] 页面${o?`挂载`:`加载`}失败:`,t),c({kind:o?`mount`:`load`,detail:og(t)})}})(),()=>{if(r=!0,typeof a==`function`)try{a()}catch(t){console.error(`[plugin:${e.id}] cleanup 失败:`,t)}n.replaceChildren()}},[e.id,e.hasClient,t]);let u=r?`plugin-page ${r}`:`plugin-page`;return(0,$.jsxs)(`div`,{className:u,children:[(0,$.jsx)(`div`,{className:`plugin-page-host`,ref:i}),s&&(0,$.jsx)(`div`,{className:`plugin-page-error`,role:`alert`,children:sg(s,e.name,a,o)})]})}function lg(e){return`pi-web-ui:${e}:tab`}function ug(e,t){try{let n=localStorage.getItem(lg(e));return n&&t.some(e=>e.id===n)?n:null}catch{return null}}function dg(e,t){try{localStorage.setItem(lg(e),t)}catch{}}function fg(e){return e.length>0&&!/[a-z]/i.test(e)}function pg(e){if(e.label)return e.label;let t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function mg({storageKey:e,tabs:t,epoch:n,send:r,extra:i,className:a}){let o=(0,Q.useId)(),[s,c]=(0,Q.useState)(()=>ug(e,t)??t[0]?.id??``),l=(0,Q.useRef)([]),u=(0,Q.useRef)(``),d=t.findIndex(e=>e.id===s),f=d>=0?t[d]:t[0],p=f?t.indexOf(f):-1;(0,Q.useEffect)(()=>{if(!f)return;s!==f.id&&c(f.id);let t=`${e}:${f.id}`;u.current!==t&&(u.current=t,dg(e,f.id))},[f,s,e]);let m=t=>{c(t.id),u.current=`${e}:${t.id}`,dg(e,t.id)},h=(e,n)=>{let r=t.length,i=-1;if(e.key===`ArrowRight`)i=(n+1)%r;else if(e.key===`ArrowLeft`)i=(n-1+r)%r;else if(e.key===`Home`)i=0;else if(e.key===`End`)i=r-1;else return;let a=t[i];a&&(e.preventDefault(),m(a),l.current[i]?.focus())};if(!f)return null;let g=`${o}-panel-${p}`,_=a?`slot-tabs ${a}`:`slot-tabs`;return(0,$.jsxs)(`div`,{className:_,children:[(0,$.jsxs)(`div`,{className:`slot-tabs-bar`,role:`tablist`,children:[t.map((e,t)=>{let n=t===p;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${o}-tab-${t}`,className:n?`slot-tab active`:`slot-tab`,title:e.hint??pg(e),"aria-selected":n,"aria-controls":`${o}-panel-${t}`,tabIndex:n?0:-1,ref:e=>{l.current[t]=e},onClick:()=>m(e),onKeyDown:e=>h(e,t),children:[e.iconSvg?(0,$.jsx)(Ir,{iconSvg:e.iconSvg,className:`slot-tab-icon`}):e.icon&&fg(e.icon)?(0,$.jsx)(`span`,{className:`slot-tab-icon`,children:e.icon}):null,(0,$.jsx)(`span`,{className:`slot-tab-label`,children:pg(e)})]},e.id)}),i?(0,$.jsx)(`div`,{className:`slot-tabs-extra`,children:i}):null]}),(0,$.jsx)(`div`,{className:`slot-tabs-body`,id:g,role:`tabpanel`,"aria-labelledby":`${o}-tab-${p}`,children:f.pluginPage?(0,$.jsx)(cg,{plugin:f.pluginPage.plugin,epoch:n,send:r}):f.element??null})]})}var hg=`@root`,gg=`pi-web-ui:rp-sizes`,_g=`pi-web-ui:files-show-hidden`,vg={files:4,widgets:1},yg=120,bg=56;function xg(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}var Sg=`files`,Cg=[],wg=()=>{};function Tg(e){let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n<0?``:n===0?`/`:t.slice(0,n)}function Eg(e){return e===hg||e===`/`||/^[A-Za-z]:$/.test(e)}function Dg(e){return e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)}var Og=(0,Q.memo)(function({files:e,fileChanged:n,widgets:r,panelSend:i,onAttach:a,onPreview:o,onNotice:s,collapsible:c,onToggleCollapse:l,uiRightPanelTabs:u,uiContextFile:d,plugins:f,pluginsEpoch:p,send:m}){let g=V(),_=f??Cg,v=en(`cwd`),y=en(`workspaceRoots`),b=en(`homeDir`),x=en(`desktopDir`),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(null),A=(0,Q.useRef)(null),[j,M]=(0,Q.useState)(()=>{try{return qo(localStorage.getItem(gg),vg)}catch{return{...vg}}});(0,Q.useEffect)(()=>{try{localStorage.setItem(gg,JSON.stringify(j))}catch{}},[j]);let[N,ee]=(0,Q.useState)(()=>{try{return localStorage.getItem(_g)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{localStorage.setItem(_g,N?`1`:`0`)}catch{}},[N]);let te=r.some(e=>e.lines.length>0),ne=(0,Q.useCallback)(e=>{e.preventDefault();let t=k.current;if(!t)return;let n=e.currentTarget,r=e.clientY,i={above:j.files,below:j.widgets},a=Math.max(120,t.clientHeight-xg(t,A.current));n.classList.add(`dragging`),document.body.classList.add(`rp-resizing`);let o=e=>{let{above:t,below:n}=Jo({start:i,deltaPx:e.clientY-r,availablePx:a,totalWeight:i.above+i.below,minAbovePx:yg,minBelowPx:bg});M({files:t,widgets:n})},s=()=>{window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),n.classList.remove(`dragging`),document.body.classList.remove(`rp-resizing`)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},[j.files,j.widgets]),re=(0,Q.useRef)(null),L=(0,Q.useRef)(0),ae=(0,Q.useCallback)(e=>{re.current=e,e&&(e.scrollTop=L.current)},[]),[oe,se]=(0,Q.useState)(null),ce=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current)},[]);let le=(0,Q.useCallback)(e=>{se(e),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>se(null),1200)},[]),ue=(0,Q.useCallback)((e,t)=>{e&&nc(e).then(e=>{e?le(t):s(`error`,g(`slashCopyFailed`))})},[le,s,g]),de=(0,Q.useCallback)(e=>{if(!e)return v;if(/^[A-Za-z]:$/.test(e))return`${e}/`;if(e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e))return e;let t=v.replace(/\\/g,`/`).replace(/\/+$/,``);return t?`${t}/${e}`:e},[v]),B=(0,Q.useCallback)(e=>{if(oa(v)){let t=sa(v),n=t?t.remotePath:`/`;if(!e)return n;if(e.startsWith(`/`))return e;let r=n.replace(/\/+$/,``)||`/`;return r===`/`?`/${e}`:`${r}/${e}`}return de(e)},[v,de]),fe=(0,Q.useCallback)(e=>!e||e===hg?null:e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)?e:`${v.replace(/\\/g,`/`).replace(/\/+$/,``)}/${e}`,[v]),pe=en(`workspaceUploadMaxMb`)*1024*1024,[me,he]=(0,Q.useState)([]),H=en(`status`);(0,Q.useEffect)(()=>{H!==`open`&&he(e=>e.some(e=>e.phase===`waiting`)?e.map(e=>e.phase===`waiting`?{...e,phase:`unknown`}:e):e)},[H]);let ge=(0,Q.useRef)(new Map);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(!t||typeof t!=`object`)return;let{uploadId:n,ok:r,error:i}=t;typeof n==`string`&&typeof r==`boolean`&&he(e=>e.map(e=>e.id===n&&(e.phase===`waiting`||e.phase===`unknown`)?{...e,phase:r?`success`:`error`,error:typeof i==`string`?i:void 0}:e))};window.addEventListener(`pi:file-upload-result`,e);let t=ge.current;return()=>{window.removeEventListener(`pi:file-upload-result`,e);for(let e of t.values())e.onload=e.onprogress=e.onerror=e.onabort=null,e.abort();t.clear()}},[]);let U=(0,Q.useCallback)((e,t)=>{for(let n of t){if(n.size>pe){s(`warning`,g(`fileTooLarge`,{name:n.name,size:pe/1024/1024}));continue}let t=crypto.randomUUID(),r=e=>he(n=>n.map(n=>n.id===t?{...n,...e}:n));he(r=>[...r,{id:t,name:n.name,dir:e,phase:`reading`,percent:0}]);let a=new FileReader;ge.current.set(t,a);let o=()=>{ge.current.delete(t),r({phase:`error`,error:g(`fileUploadReadFailed`,{name:n.name})})};a.onprogress=e=>{e.lengthComputable&&e.total>0&&r({percent:Math.min(100,Math.floor(e.loaded/e.total*100))})},a.onerror=o,a.onabort=o,a.onload=()=>{if(ge.current.delete(t),typeof a.result!=`string`||!a.result.includes(`,`)){o();return}let s=a.result.slice(a.result.indexOf(`,`)+1);r({phase:`waiting`,percent:100});try{if(i({type:`upload_file`,dirPath:e,name:n.name,data:s,uploadId:t}))return}catch{}r({phase:`error`,error:g(`fileUploadSendFailed`,{name:n.name})})};try{a.readAsDataURL(n)}catch{o()}}},[i,s,g,pe]),W=(0,Q.useRef)(null),[G,_e]=(0,Q.useState)(null),K=(0,Q.useRef)(null),q=(0,Q.useCallback)(()=>{let e=W.current?.project;e&&i({type:`set_cwd`,path:e.path})},[i]),ve=(0,Q.useCallback)(()=>{K.current&&(K.current.value=``),K.current?.click()},[]),[Y,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(null),[Se,Ce]=(0,Q.useState)(``),[we,Ee]=(0,Q.useState)(null),[De,X]=(0,Q.useState)(``),Oe=(0,Q.useCallback)((e,t)=>{zu(e,t).then(e=>{e.ok||e.cancelled||s(`error`,g(`downloadFailed`,{error:e.error===`FILE_NOT_FOUND`?g(`fileNotFoundShort`):e.error}))})},[s,g]),ke=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Eg(e.id)&&(Ee(null),Ce(e.label),xe(e.id))},[]),Ae=(0,Q.useCallback)(()=>{if(!be)return;let e=Se.trim();xe(null),e&&i({type:`file_rename`,path:be,newName:e})},[be,Se,i]),je=(0,Q.useCallback)(e=>{let t=W.current?.dir??C;xe(null),X(``),Ee({dir:t,kind:e})},[C]),Me=(0,Q.useCallback)(()=>{if(!we)return;let e=De.trim();Ee(null),e&&i({type:`file_create`,dir:we.dir,name:e,kind:we.kind})},[we,De,i]),Ne=(e,t,n,r)=>(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:e,placeholder:g(`fileNamePlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>t(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing?n():e.key===`Escape`&&r()},onBlur:r}),Pe=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Eg(e.id)&&window.confirm(g(`fileDeleteConfirm`,{name:e.label}))&&(Y?.src===e.id&&ye(null),be===e.id&&xe(null),i({type:`file_delete`,path:e.id}))},[i,g,Y,be]),Fe=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Eg(e.id)&&i({type:`file_copy`,src:e.id,destDir:Tg(e.id)})},[i]),Ie=(0,Q.useCallback)(e=>{let t=W.current?.target;t&&t.kind!==`list`&&!Eg(t.id)&&ye({src:t.id,cut:e})},[]),Le=(0,Q.useCallback)(()=>{if(!Y)return;let e=W.current?.dir??C;Y.cut?(i({type:`file_copy`,src:Y.src,destDir:e,move:!0}),ye(null)):i({type:`file_copy`,src:Y.src,destDir:e})},[Y,i,C]),Re=(0,Q.useCallback)(()=>{i({type:`list_files`,path:C===``?void 0:C})},[i,C]),[ze,Ve]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!ze)return;let e=e=>{e.target?.closest(`.root-picker`)||Ve(!1)},t=e=>{e.key===`Escape`&&Ve(!1)};return window.addEventListener(`mousedown`,e,!0),window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`mousedown`,e,!0),window.removeEventListener(`keydown`,t)}},[ze]);let He=(0,Q.useCallback)(e=>{i({type:`set_workspace_roots`,roots:e})},[i]),Ue=(0,Q.useCallback)(()=>{let e=W.current?.target;if(!e||e.kind!==`dir`)return;let t=fe(e.id);t&&!y.includes(t)&&He([...y,t])},[y,fe,He]),We=(0,Q.useCallback)(e=>{U(W.current?.dir??C,Array.from(e.target.files??[]))},[U,C]),Ge=(0,Q.useCallback)(e=>{let t=W.current?.target;switch(e.id){case`host:file-compress`:case`host:file-extract`:case`host:file-compress-download`:case`host:file-upload-folder`:{if(!t)break;let n=e.id===`host:file-compress`?`compress`:e.id===`host:file-extract`?`extract`:e.id===`host:file-compress-download`?`download`:`upload`;_e({action:n,path:B(t.id),dir:B(n===`upload`?W.current?.dir??C:Tg(t.id))});break}case`host:file-open-project`:q();break;case`host:file-upload`:ve();break;case`host:file-add-root`:Ue();break;case`host:file-open`:t?.kind===`file`&&o(t.id,t.label);break;case`host:file-enter`:t?.kind===`dir`&&it(t.id);break;case`host:file-download`:t?.kind===`file`&&Oe(t.id,t.label);break;case`host:file-reveal`:t&&i({type:`file_reveal`,path:t.id});break;case`host:file-open-default`:t?.kind===`file`&&i({type:`file_open_default`,path:t.id});break;case`host:file-attach-ref`:t?.kind===`file`&&a(t.id,t.label,`reference`);break;case`host:file-attach-folder`:t?.kind===`dir`&&a(t.id,t.label,`reference`,!0);break;case`host:file-new-file`:je(`file`);break;case`host:file-new-dir`:je(`dir`);break;case`host:file-paste`:Le();break;case`host:file-rename`:ke();break;case`host:file-duplicate`:Fe();break;case`host:file-cut`:Ie(!0);break;case`host:file-copy`:Ie(!1);break;case`host:file-copy-name`:t&&t.kind!==`list`&&ue(t.label,`name:${t.id}`);break;case`host:file-copy-path`:t&&t.kind!==`list`&&ue(de(t.id),`path:${t.id}`);break;case`host:file-copy-rel`:t&&t.kind!==`list`&&ue(t.id,`rel:${t.id}`);break;case`host:file-refresh`:Re();break;case`host:file-delete`:Pe()}},[q,C,ve,Ue,o,a,ue,de,Oe,je,Le,ke,Fe,Ie,Re,Pe]),Ke=(0,Q.useCallback)((e,t)=>{let n=t.kind===`dir`?fe(t.id):null,r={target:t,dir:t.kind===`dir`?t.id:C,project:n?{path:n,name:t.label}:null},i=t.kind,a=i===`file`,o=i===`dir`,s=i===`list`,c=!s&&Eg(t.id),l=!s&&Dg(t.id),u=C===hg,f=(d??[]).map(e=>{if(e.source!==`host`)return e;switch(e.id){case`host:file-upload-folder`:return u?{...e,hidden:!0}:e;case`host:file-compress`:case`host:file-compress-download`:return!s&&!c?e:{...e,hidden:!0};case`host:file-extract`:return a&&Qh(t.label)?e:{...e,hidden:!0};case`host:file-upload`:return u?{...e,hidden:!0}:{...e,label:r.dir===C?g(`uploadToCurrentDir`):g(`uploadToFolder`)};case`host:file-open-project`:return n?e:{...e,hidden:!0};case`host:file-add-root`:return n&&n!==v&&!y.includes(n)?e:{...e,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:case`host:file-attach-ref`:return a?e:{...e,hidden:!0};case`host:file-reveal`:return!u&&t.id!==hg?e:{...e,hidden:!0};case`host:file-enter`:case`host:file-attach-folder`:return o?e:{...e,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:return!a&&!u?e:{...e,hidden:!0};case`host:file-paste`:return!a&&!u&&Y?e:{...e,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!s&&!c?e:{...e,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:return s?{...e,hidden:!0}:e;case`host:file-copy-rel`:return!s&&!l?e:{...e,hidden:!0};case`host:file-refresh`:return s?e:{...e,hidden:!0};default:return e}});Gi(f).length!==0&&(e.preventDefault(),e.stopPropagation(),W.current=r,Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.file`,target:t,entries:f,onHostAction:Ge}))},[d,C,fe,g,Ge,v,y,Y]),Je=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),Ye=(0,Q.useCallback)(()=>{re.current?.querySelectorAll(`.file-item.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),re.current?.classList.remove(`drop-root`)},[]),Ze=(0,Q.useCallback)(e=>{if(Ye(),e==null)return;let t=re.current?.querySelector(`.file-item[data-path="${CSS.escape(e)}"]`);t?t.classList.add(`drop-target`):re.current?.classList.add(`drop-root`)},[Ye]),Qe=e=>{let t=e instanceof Element?e.closest(`.file-item`):null;return t?.dataset.type===`dir`?t.dataset.path??C:C},$e=(0,Q.useCallback)(()=>{let e=document.querySelector(`.app`);e&&e.dispatchEvent(new DragEvent(`dragleave`,{bubbles:!0}))},[]),et=(0,Q.useRef)(0),tt=(0,Q.useRef)(void 0),nt=(0,Q.useCallback)((e,t)=>{let n=++et.current;w(e),t?.silent||O(!0),i({type:`list_files`,path:e===``?void 0:e})||et.current===n&&O(!1)},[i]),rt=(0,Q.useCallback)(e=>{let t=y.filter(t=>t!==e);He(t),(C===e||C.startsWith(`${e}/`))&&nt(``)},[y,He,C,nt]);(0,Q.useEffect)(()=>{e&&e.path===C&&O(!1)},[e,C]),(0,Q.useEffect)(()=>{if(v!==tt.current){let e=tt.current===void 0;tt.current=v,e?nt(``,{silent:!0}):w(``);return}let e=setInterval(()=>{document.visibilityState!==`hidden`&&nt(C,{silent:!0})},1e4);return()=>clearInterval(e)},[v,C,nt]),(0,Q.useEffect)(()=>{n&&n.path===C&&nt(C,{silent:!0})},[n,C,nt]);let it=e=>nt(e),at=()=>{e?.parent!==null&&e?.parent!==void 0&&nt(e.parent)},ot=(()=>{if(C===``||C===hg)return[];let e=C.split(`/`).filter(e=>!!e&&e!==hg);return C.startsWith(`/`)?[{label:`/`,path:`/`},...e.map((t,n)=>({label:t,path:`/`+e.slice(0,n+1).join(`/`)}))]:e.map((t,n)=>({label:e[n],path:e.slice(0,n+1).join(`/`)}))})(),ct=[];for(let e of u??[]){if(e.source===`host`||e.hidden||e.kind===`divider`)continue;let t=_.find(t=>t.id===e.source.slice(7));t&&ct.push({id:e.id,label:e.label,icon:e.icon,...e.iconSvg?{iconSvg:e.iconSvg}:{},hint:e.hint,pluginPage:{plugin:t,entry:e}})}let lt=(u??[]).some(e=>e.id===`host:right-files`&&e.hidden);return(0,$.jsxs)(`aside`,{className:`panel panel-right`,ref:k,children:[c&&l&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:g(`collapsePanel`),onClick:l,children:(0,$.jsx)(P,{})}),(0,$.jsx)(`div`,{ref:A,style:{display:`flex`,flexDirection:`column`,flex:te?`${j.files} 1 0`:`1 1 0`,minHeight:te?yg:0},children:(0,$.jsx)(mg,{storageKey:`rightpanel`,epoch:p??0,send:m??wg,tabs:(e=>{let t=(u??[]).filter(e=>!e.hidden);if(t.length===0)return e;let n=new Map(t.map((e,t)=>[e.id,t])),r=e=>n.get(e===Sg?`host:right-files`:e)??1e9;return[...e].sort((e,t)=>r(e.id)-r(t.id))})([...lt?[]:[{id:Sg,label:g(`openFiles`),element:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`panel-crumbs`,children:[(0,$.jsx)(`button`,{type:`button`,className:`crumb ${C===``?`active`:``}`,onClick:()=>nt(``),children:g(`rootDir`)}),(0,$.jsx)(ta,{className:`crumb ${C===hg?`active`:``}`,tip:g(`computer`),onClick:()=>nt(hg),children:(0,$.jsx)(t,{})}),b!==``&&(0,$.jsx)(ta,{className:`crumb ${C===b||C.startsWith(`${b}/`)?`active`:``}`,tip:g(`homeDir`),onClick:()=>nt(b),children:(0,$.jsx)(Xe,{})}),x!==``&&(0,$.jsx)(ta,{className:`crumb ${C===x||C.startsWith(`${x}/`)?`active`:``}`,tip:g(`desktopDir`),onClick:()=>nt(x),children:(0,$.jsx)(st,{})}),(0,$.jsx)(ta,{className:`crumb ${N?`active`:``}`,tip:g(N?`filesHideHidden`:`filesShowHidden`),"aria-pressed":N,onClick:()=>ee(e=>!e),children:N?(0,$.jsx)(I,{}):(0,$.jsx)(h,{})}),(0,$.jsx)(ea,{text:g(`filesHelp`)}),y.length>0&&(0,$.jsxs)(`div`,{className:`root-picker`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`crumb root-picker-trigger`,"aria-haspopup":`menu`,"aria-expanded":ze,title:g(`workspaceRoots`),onClick:()=>Ve(e=>!e),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`root-picker-label`,children:g(`workspaceRoots`)}),(0,$.jsx)(`span`,{className:`set-count`,children:y.length+1}),`▾`]}),ze&&(0,$.jsxs)(`div`,{className:`root-picker-menu`,role:`menu`,children:[(0,$.jsx)(`div`,{className:`root-picker-row`,children:(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:C===``?`root-picker-item active`:`root-picker-item`,title:v,onClick:()=>{Ve(!1),nt(``)},children:[g(`rootDir`),(0,$.jsx)(`span`,{className:`root-picker-path`,children:v})]})}),y.map(e=>(0,$.jsxs)(`div`,{className:`root-picker-row`,children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:C===e?`root-picker-item active`:`root-picker-item`,title:e,onClick:()=>{Ve(!1),nt(e)},children:(0,$.jsx)(`span`,{className:`root-picker-path`,children:e})}),(0,$.jsx)(`button`,{type:`button`,className:`root-picker-remove`,title:g(`removeWorkspaceRoot`),"aria-label":g(`removeWorkspaceRoot`),onClick:()=>rt(e),children:(0,$.jsx)(R,{})})]},e)),(0,$.jsx)(`div`,{className:`root-picker-hint`,children:g(`workspaceRootsHint`)})]})]}),ot.map(e=>(0,$.jsxs)(`span`,{className:`crumb-seg`,children:[(0,$.jsx)(P,{}),(0,$.jsx)(`button`,{type:`button`,className:`crumb ${e.path===C?`active`:``}`,onClick:()=>nt(e.path),children:e.label})]},e.path))]}),(0,$.jsxs)(`div`,{ref:ae,className:`panel-body`,onScroll:e=>{L.current=e.currentTarget.scrollTop},onContextMenu:e=>Ke(e,{id:C,kind:`list`,label:C===``?g(`rootDir`):C===hg?g(`computer`):C}),onDragOver:e=>{Je(e)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,$e(),Ze(Qe(e.target)))},onDragLeave:e=>{e.relatedTarget&&e.currentTarget.contains(e.relatedTarget)||Ye()},onDrop:e=>{if(Ye(),!Je(e))return;e.preventDefault(),e.stopPropagation(),$e();let t=Array.from(e.dataTransfer?.files??[]);if(t.length===0){s(`warning`,g(`foldersNotSupported`));return}U(Qe(e.target),t)},onDragEnd:Ye,children:[(0,$.jsx)(`input`,{ref:K,type:`file`,multiple:!0,hidden:!0,onChange:We}),me.length>0&&(0,$.jsx)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`4px 8px`},children:me.map(e=>{let t=e.phase===`reading`?g(`fileUploadReading`,{name:e.name,percent:e.percent}):e.phase===`waiting`?g(`fileUploadWaiting`,{name:e.name}):e.phase===`success`?g(`fileUploadConfirmed`):e.phase===`unknown`?g(`fileUploadOutcomeUnknown`):g(`fileUploadFailed`,{error:e.error||e.name});return(0,$.jsxs)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`3px 0`,fontSize:12},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,minWidth:0,maxWidth:`100%`},children:[(0,$.jsx)(`span`,{title:`${e.dir}/${e.name}`,style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,flex:1},children:e.name}),e.phase!==`reading`&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":`${g(`fileUploadDismiss`)}: ${e.name}`,title:g(`fileUploadDismiss`),onClick:()=>he(t=>t.filter(t=>t.id!==e.id)),style:{flex:`none`,padding:2},children:(0,$.jsx)(R,{"aria-hidden":`true`})})]}),e.phase===`reading`&&(0,$.jsx)(`progress`,{max:100,value:e.percent,"aria-label":g(`fileUploadReading`,{name:e.name,percent:e.percent}),style:{width:`100%`,height:4,display:`block`}}),(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,style:{overflowWrap:`anywhere`,wordBreak:`break-word`,color:e.phase===`error`?`var(--err-text)`:`var(--text-dim)`},children:t})]},e.id)})}),G&&(0,$.jsx)(rg,{request:G,onClose:()=>_e(null),onComplete:Re}),we&&(0,$.jsxs)(`div`,{className:`file-item dir`,children:[we.kind===`dir`?(0,$.jsx)(Be,{className:`file-icon`}):(0,$.jsx)(ie,{className:`file-icon`}),Ne(De,X,Me,()=>Ee(null))]}),D&&(0,$.jsx)(`div`,{className:`panel-empty`,children:g(`loading`)}),!D&&e&&e.path===C&&(0,$.jsxs)($.Fragment,{children:[e.parent!=null&&(0,$.jsxs)(`button`,{type:`button`,className:`file-item dir`,onClick:at,children:[(0,$.jsx)(Be,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:`..`})]}),ag(e.entries,N).map(e=>e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir${Y?.cut&&Y.src===e.path?` cut`:``}`,"data-type":`dir`,"data-path":e.path,onClick:t=>{be!==e.path&&(t.target.closest(`.file-attach`)||it(e.path))},onContextMenu:t=>Ke(t,{id:e.path,kind:`dir`,label:e.name}),children:[be===e.path?Ne(Se,Ce,Ae,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:t=>{t.stopPropagation(),it(e.path)},children:[(0,$.jsx)(Be,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":g(`linkFolderTip`),"aria-label":g(`linkFolderTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`,!0)},children:(0,$.jsx)(qe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":g(`copyName`),"aria-label":g(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":g(`copyPath`),"aria-label":g(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(F,{})})]},e.path):(0,$.jsxs)(`div`,{className:`file-item file${Y?.cut&&Y.src===e.path?` cut`:``}`,"data-type":`file`,"data-path":e.path,onClick:t=>{be!==e.path&&(t.target.closest(`.file-attach`)||o(e.path,e.name))},onContextMenu:t=>Ke(t,{id:e.path,kind:`file`,label:e.name}),children:[be===e.path?Ne(Se,Ce,Ae,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-name`,title:`${e.path} — ${g(`previewFile`)}`,onClick:t=>{t.stopPropagation(),o(e.path,e.name)},children:[(0,$.jsx)(ie,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name-text`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach download`,"data-tip":g(`downloadFile`),onClick:t=>{t.stopPropagation(),Oe(e.path,e.name)},children:(0,$.jsx)(S,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":g(`referenceTip`),"aria-label":g(`referenceTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`)},children:(0,$.jsx)(qe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":g(`copyName`),"aria-label":g(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":g(`copyPath`),"aria-label":g(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(F,{})})]},e.path)),e.truncated&&(0,$.jsx)(`div`,{className:`panel-empty files-truncated`,children:g(`filesTruncated`)})]}),!D&&!e&&(0,$.jsx)(`div`,{className:`panel-empty`,children:g(`noFiles`)})]})]})}],...ct])})}),te&&(0,$.jsx)(`div`,{className:`rp-sash`,onPointerDown:ne,onDoubleClick:()=>M({...vg}),title:g(`dragToResize`)}),te&&(0,$.jsx)(`div`,{className:`panel-widgets`,style:{flexGrow:j.widgets,minHeight:bg},children:r.filter(e=>e.lines.length>0).map(e=>(0,$.jsxs)(`div`,{className:`widget`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`widget-title widget-title-btn`,title:g(`widgetExpand`),onClick:()=>E(e.key),children:[(0,$.jsx)(`span`,{children:e.key}),(0,$.jsx)(J,{})]}),(0,$.jsx)(`pre`,{className:`widget-lines`,children:e.lines.join(`
|
|
59
|
+
`,n.appendChild(r);let i=document.createElement(`div`);return i.className=`plugin-isolated-root`,i.style.cssText=`width:100%;height:100%;display:flex;flex-direction:column;`,n.appendChild(i),{container:i,isShadow:!0,cleanup:()=>{i.replaceChildren(),n?.replaceChildren()}}}var mm=`pi-web-ui:plugin-data`;function hm(e,t){window.dispatchEvent(new CustomEvent(mm,{detail:{pluginId:e,payload:t}}))}function gm(e){let t=t=>{let n=t.detail;e(n.pluginId,n.payload)};return window.addEventListener(mm,t),()=>window.removeEventListener(mm,t)}var _m=new Map,vm=new Set,ym=new Set,bm=new Set,xm=new Set,Sm=-1;function Cm(){return[..._m.values()]}function wm(){let e=Cm();for(let t of ym)t(e)}function Tm(){let e=[...bm];for(let t of xm)t(e)}function Em(e){return xm.add(e),e([...bm]),()=>xm.delete(e)}async function Dm(e,t){bm.delete(e.id),km.set(e.id,(km.get(e.id)??0)+1),Tm();let n=await Pm(e,t);return wm(),n}function Om(e){return ym.add(e),e(Cm()),()=>ym.delete(e)}var km=new Map;function Am(e,t){let n=km.get(e)??0;return q(`/plugins/${encodeURIComponent(e)}/client/entry.mjs?e=${t}${n>0?`&r=${n}`:``}`)}function jm(e){let t=Promise.resolve();return(n,r)=>{let i=t.then(()=>Lt(n,()=>e(r)));return t=i.then(()=>void 0,()=>void 0),i}}var Mm=jm(e=>As(()=>import(e),[],import.meta.url));async function Nm(e,t){if(!e.hasClient||e.error)return null;try{let n=await Mm(e.id,Am(e.id,t)),r=n.default??n;return{...r,fileHandlers:r.fileHandlers??n.fileHandlers}}catch(t){return console.error(`[plugin:${e.id}] 客户端 bundle 加载失败:`,t),null}}async function Pm(e,t){try{let n=(await Mm(e.id,Am(e.id,t))).default;return n&&typeof n.mount==`function`?(_m.set(e.id,{info:e,module:n}),!0):e.preload?(vm.add(e.id),!0):(bm.add(e.id),Tm(),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(t){return bm.add(e.id),Tm(),console.error(`[plugin:${e.id}] 客户端加载失败:`,t),!1}}async function Fm(e,t){if(_m.has(e.id)||vm.has(e.id))return!0;if(bm.has(e.id)||!e.hasClient)return!1;let n=await Pm(e,t);return wm(),n}async function Im(e,t){t!==Sm&&(Sm=t,_m.clear(),vm.clear(),bm.clear(),km.clear(),Tm());let n=new Set(e.map(e=>e.id));for(let e of[..._m.keys()])n.has(e)||_m.delete(e);for(let e of[...vm])n.has(e)||vm.delete(e);for(let e of[...bm])n.has(e)||bm.delete(e);Tm(),await Promise.all(e.filter(e=>e.hasClient&&(e.view!==!1||e.preload)&&!e.error&&!_m.has(e.id)&&!vm.has(e.id)&&!bm.has(e.id)).map(e=>Pm(e,t))),wm()}function Lm(e,t){return{pluginId:e,send:n=>t({type:`plugin_message`,pluginId:e,payload:n}),onData:t=>gm((n,r)=>{n===e&&t(r)})}}var Rm=[`debug`,`info`,`warn`,`error`];function zm(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`get`}}}function Bm(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`clear`}}}function Vm(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.__host!==`logs`||!Array.isArray(t.logs)?!1:t.logs.every(e=>!!e&&typeof e==`object`&&typeof e.ts==`number`&&typeof e.text==`string`&&Rm.includes(String(e.level)))}var Hm=new Map,Um=new Set;function Wm(){for(let e of[...Um])try{e()}catch{}}function Gm(e){return Um.add(e),()=>Um.delete(e)}function Km(e){return(Hm.get(e)??[]).map(e=>({...e}))}function qm(e,t){return Vm(t)?(Hm.set(e,t.logs.map(e=>({ts:e.ts,level:e.level,text:e.text}))),Wm(),!0):!1}function Jm(e,t){let n=e.historyStart??0;return t.resyncRequired===!0||t.historyGeneration!==e.historyGeneration||t.historyStart+t.messages.length!==n||t.before!==void 0&&t.before!==n||t.historyGeneration!==void 0&&(t.before!==n||t.beforeId!==e.messages[0]?.id)}function Ym(e,t){if(Jm(e,t))return null;let n=e.historyStart??0,r=e.historyTotal??e.messages.length;return t.messages.length===0?t.historyStart===n&&t.historyTotal===r?null:{...e,historyStart:t.historyStart,historyTotal:t.historyTotal}:{...e,messages:[...t.messages,...e.messages],historyStart:t.historyStart,historyTotal:t.historyTotal}}function Xm(e){let t=Math.max(0,e.historyStart??0);return e.isPagingActive?Math.max(0,e.totalMessages-Math.min(e.totalMessages,e.visibleCount))+t:t}function Zm(e){switch(e){case`error`:return 6500;case`warning`:return 4200;default:return 2400}}var Qm=[/^(已在工作目录|正在切换到工作目录|已切换到工作目录)[::]/,/^(Already in directory|Switching to directory|Switched to directory):/i,/该项目最近的对话.*(为你停在了空白新对话|为你停在了新对话)/,/The most recent conversation .* landed on a (blank|new) chat/i,/^分层上下文预算裁剪生效/,/^Tiered context budget pruning/i,/^发现 \d+ 个内置插件有更新可用/,/^\d+ built-in plugin\(s\) have updates available/i,/^已(创建文件|创建文件夹|重命名|删除|移动|复制)[::]/,/^(Created file|Created folder|Renamed|Deleted|Moved|Copied):/i,/^已重命名当前会话为/,/^Renamed current session to/i,/的消息正在投递,已为你保留该对话$/,/is still sending your message — kept in the running list$/i,/^(计划模式已开启|计划模式已关闭|已进入计划模式|已退出计划模式|审查者模式已开启|审查者模式已关闭)/,/^(Plan mode (enabled|disabled)|Entered plan mode|Exited plan mode|Delegate mode (enabled|disabled))/i,/^已切换(智能体预设|权限预设)/,/^Switched (agent|permission) preset/i];function $m(e){if(e.level!==`info`)return!1;let t=(e.text??``).trim(),n=(e.textEn??``).trim();return Qm.some(e=>t&&e.test(t)||n&&e.test(n))}function eh(e,t,n=2){if($m(t))return e;let r=`${t.level}:${(t.text??``).trim()}`,i=[...e.filter(e=>`${e.level}:${(e.text??``).trim()}`!==r),t];for(;i.length>n;){let e=i.findIndex(e=>e.level!==`error`);e>=0?i.splice(e,1):i.shift()}return i}function th(){return{flows:[],results:{}}}function nh(e,t){let n=e.findIndex(e=>e.flowId===t.flowId);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)}function rh(e,t){switch(t.type){case`provider_oauth_started`:{let n={...e.results};return delete n[t.provider],{flows:[...e.flows.filter(e=>e.provider!==t.provider),{flowId:t.flowId,provider:t.provider}],results:n}}case`provider_oauth_flows`:return{...e,flows:t.flows.map(e=>({...e}))};case`provider_oauth_prompt`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:nh(e.flows,{...n,flowId:t.flowId,provider:t.provider,promptId:t.promptId,prompt:t.prompt})}}case`provider_oauth_event`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:nh(e.flows,{...n,flowId:t.flowId,provider:t.provider,event:t.event,promptId:void 0,prompt:void 0})}}case`provider_oauth_result`:return{flows:e.flows.filter(e=>e.flowId!==t.flowId),results:{...e.results,[t.provider]:{ok:t.ok,...t.cancelled===void 0?{}:{cancelled:t.cancelled},...t.error===void 0?{}:{error:t.error}}}};case`provider_oauth_logout_result`:return{...e,results:{...e.results,[t.provider]:{ok:t.ok,...t.error===void 0?{}:{error:t.error}}}}}}function ih(){return Ke()}var ah=typeof WebSocket<`u`&&WebSocket.OPEN!==void 0?WebSocket.OPEN:1,oh=typeof WebSocket<`u`&&WebSocket.CLOSING!==void 0?WebSocket.CLOSING:2,sh=typeof WebSocket<`u`&&WebSocket.CLOSED!==void 0?WebSocket.CLOSED:3,ch=e=>!!(e&&e.readyState===ah),lh=2e5,uh=`LIVE_OMIT`,dh={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 fh(e,t){let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId),e.role===`bashExecution`&&n.add(`bash-${e.id}`);let r=!1;for(let t of e.keys())n.has(t)&&(e.delete(t),r=!0);return r?new Map(e):e}function ph(e,t){if(e.size===0)return e;let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId);let r=!1;for(let t of e.keys())n.has(t)&&(e.delete(t),r=!0);return r?new Map(e):e}function mh(e,t){switch(t.type){case`status`:return{...e,status:t.status,ready:t.status===`open`&&e.ready,terminals:t.status===`closed`?[]:e.terminals,hostMetrics:t.status===`closed`?null:e.hostMetrics,latencyMs:t.status===`open`?e.latencyMs:null};case`sync_cached_sessions`:return{...e,sessions:t.sessions};case`host_metrics`:return{...e,...t.metrics===void 0?{}:{hostMetrics:t.metrics},...t.latencyMs===void 0?{}:{latencyMs:t.latencyMs}};case`ready`:{let n=!!(e.engine&&t.engine&&e.engine!==t.engine);return{...e,serverVersion:t.serverVersion,engine:t.engine,appVersion:t.appVersion,managed:t.managed===!0,tabs:t.tabs,ready:!0,...t.engines?{engines:t.engines}:{},...n?{state:null,models:[],sessions:Mh(e.state?.cwd,t.engine),conversations:[],terminals:[],dsh:null,dshPatches:null,dshMarket:null,dshPresets:null,dshPermission:null}:{},...typeof t.latencyMs==`number`&&e.latencyMs==null?{latencyMs:t.latencyMs}:{},protocolMismatch:t.protocolVersion!==void 0&&t.protocolVersion!==40}}case`snapshot`:{let n=e.state?.cwd,r=e.state?.conversationId,i=t.state.cwd,a=e.sessions;i&&i!==n&&(a=Mh(i,e.engine));let o=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),s=e.transition;if(s){let e=o(s.target),n=o(t.state.sessionFile),i=o(t.state.conversationId),a=o(t.state.sessionId);(s.phase===`done`||s.phase===`error`||s.kind===`cwd`&&o(t.state.cwd)===e||s.kind===`session`&&(n===e||a===e||i===e||n&&(n.endsWith(`/`+e)||e.endsWith(`/`+n)))||s.kind===`conversation`&&i===e||s.kind===`new_chat`&&(!r||t.state.conversationId!==r||t.state.messages.length===0))&&(s=null)}let c=Jp(e.optimisticQueue,t.state),l=Kp(c.tracker,c.state);return{...e,ready:!0,state:l.state,optimisticQueue:l.tracker,transition:s,sessions:a,approval:l.state.pendingApproval??null,approvals:l.state.pendingApprovals??(l.state.pendingApproval?[l.state.pendingApproval]:[]),activeConversationId:l.state.conversationId,liveOutputs:fh(e.liveOutputs,l.state),toolStatuses:ph(e.toolStatuses,l.state)}}case`earlier_messages`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId)return e;let i=Ym(n,r);return i?{...e,state:i}:e}case`snapshot_delta`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId||n.rev!==r.baseRev)return e;let i={...n,...r.state,messages:r.appended.length>0?[...n.messages,...r.appended]:n.messages},a=Jp(e.optimisticQueue,i),o=Kp(a.tracker,a.state),s=o.state;return{...e,ready:!0,state:s,optimisticQueue:o.tracker,approval:s.pendingApproval===void 0?e.approval:s.pendingApproval??null,approvals:s.pendingApprovals??e.approvals,activeConversationId:s.conversationId,liveOutputs:fh(e.liveOutputs,s),toolStatuses:ph(e.toolStatuses,s)}}case`optimistic_queue_add`:{let n=e.goal.reviewing&&!!(e.state?.conversationId&&e.goal.conversationId===e.state.conversationId),r=Wp(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments,queue:t.queue,engine:e.engine,goalReviewing:n});return r.tracker===e.optimisticQueue&&r.state===e.state?e:{...e,optimisticQueue:r.tracker,state:r.state}}case`optimistic_queue_remove`:{let n=Gp(e.optimisticQueue,e.state,{kind:t.kind,text:t.text,index:t.index});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`optimistic_prompt_echo`:{let n=zp(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`tool_approval`:return{...e,approval:t.approval,approvals:os(e.approvals,t.approval,t.resolvedId)};case`tool_delta`:{let n=e.liveOutputs.get(t.toolCallId)?.text??``,r;r=t.mode===`replace`||n.length>0&&t.delta.startsWith(n)?t.delta:n+t.delta;let i=r.length>lh?`…[${uh}:${r.length-lh}]…\n`+r.slice(r.length-lh):r,a=new Map(e.liveOutputs);return a.set(t.toolCallId,{toolName:t.toolName,text:i}),{...e,liveOutputs:a}}case`message_delta`:{let n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:wp(n,t.msg)}}case`tool_status`:return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case`notice`:{let n=eh(e.notices,t.notice),r=(t.notice.level===`error`||t.notice.level===`warning`)&&e.optimisticQueue.adds.length>0?qp(e.optimisticQueue,e.state):{tracker:e.optimisticQueue,state:e.state};return n===e.notices&&r.tracker===e.optimisticQueue?e:{...e,notices:n,optimisticQueue:r.tracker,state:r.state}}case`dismiss_notice`:return{...e,notices:e.notices.filter(e=>e.id!==t.id)};case`engines_status`:return{...e,engines:t.engines};case`sessions`:return Nh(e.state?.cwd,t.sessions,e.engine),{...e,sessions:t.sessions};case`conversations`:return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case`projects`:return Oh(t.projects),{...e,projects:t.projects};case`sandbox_diff`:return{...e,sandboxDiff:t.diff};case`files`:return{...e,files:t.files};case`file_changed`:return{...e,fileChanged:{path:t.path}};case`file_content`:return{...e,fileContent:t.content};case`models`:return{...e,models:t.models,modelsLoading:t.loading};case`models_config`:return{...e,modelsConfig:t.providers};case`providers_status`:return{...e,providers:t.providers};case`provider_keys`:return{...e,providerKeys:t.keys};case`default_model`:return{...e,defaultModel:t.modelId};case`provider_oauth`:{let n=rh({flows:e.providerOAuthFlows,results:e.providerOAuthResults},t.message);return{...e,providerOAuthFlows:n.flows,providerOAuthResults:n.results}}case`fetch_models_result`:return{...e,fetchModelsResult:t.result};case`test_model_connection_result`:return{...e,testModelConnectionResult:t.result};case`enrich_models_progress`:return{...e,enrichModelsProgress:t.progress};case`enrich_models_result`:return{...e,enrichModelsResult:t.result,enrichModelsProgress:null};case`refresh_provider_result`:return{...e,refreshProviderResult:t.result};case`refresh_builtin_result`:return{...e,refreshBuiltinResult:t.result};case`append_builtin_result`:return{...e,appendBuiltinResult:t.result};case`clone_provider_result`:return{...e,cloneProviderResult:t.result};case`install_result`:return{...e,installResult:t.result};case`scm_data`:return{...e,scmData:t.data};case`file_search_result`:return{...e,fileSearch:t.result};case`session_search_result`:return{...e,sessionSearch:t.result};case`scm_changed`:return{...e,scmDirty:e.scmDirty+1};case`path_completions`:return{...e,pathCompletions:t.completions};case`update_status`:return{...e,update:t.status};case`update_status_all`:return{...e,updatesAll:t.items,updatesSdk:t.piSdk??null};case`updates_check_started`:return{...e,updatesAll:null};case`widgets`:return{...e,widgets:t.widgets};case`statuses`:return{...e,statuses:t.statuses};case`dialog`:return{...e,dialog:t.dialog};case`tui_overlay`:return{...e,tuiOverlay:t.overlay};case`question`:return{...e,question:t.question};case`remote_question`:return{...e,remoteQuestion:e.questionQueue===null?t.question:null};case`question_queue`:return{...e,questionQueue:t.questions,remoteQuestion:null};case`question_queue_answered`:return{...e,questionQueue:e.questionQueue?.filter(e=>e.id!==t.id||e.owner!==t.owner)??null};case`commands`:return{...e,commands:t.commands,commandsPath:t.path};case`slash_commands`:return{...e,slashCommands:t.commands};case`goal_status`:return{...e,goal:t.status};case`plan_updated`:{let n=e.state;if(!n)return e;let r=e.activeConversationId||n.conversationId;if(!t.conversationId||t.conversationId!==r)return e;let i={...n,plan:t.plan};return{...e,state:i}}case`settings`:return{...e,settings:t.settings};case`mcp_servers`:return e.settings?{...e,settings:{...e.settings,mcpServers:t.servers,mcpGlobalConfigPath:t.globalConfigPath??e.settings.mcpGlobalConfigPath,mcpProjectConfigPath:t.projectConfigPath??e.settings.mcpProjectConfigPath}}:e;case`mcp_oauth_result`:return{...e,mcpOAuthResult:e.mcpOAuthResult?.reqId===t.result.reqId?{...e.mcpOAuthResult,...t.result,error:t.result.error}:t.result};case`mcp_market_result`:return{...e,mcpMarketResult:t.result};case`skill_market_result`:return{...e,skillMarketResult:t.result};case`skill_content_result`:return{...e,skillContentResult:t.result};case`bg_servers`:return{...e,bgServers:t.servers};case`scheduler_tasks`:return{...e,schedulerTasks:t.tasks};case`plugin_panel_items`:return{...e,pluginPanelGroups:t.groups};case`plugins`:return{...e,plugins:t.plugins,pluginsEpoch:t.epoch};case`plugin_updates_check_started`:return{...e,checkingPluginUpdates:!0};case`plugin_updates`:{let n={};for(let e of t.updates)n[e.id]=e;return{...e,pluginUpdates:n,checkingPluginUpdates:!1}}case`plugin_catalog`:return{...e,pluginCatalog:t.entries,pluginCatalogEpoch:t.epoch};case`plugin_grants`:return{...e,pluginGrants:t.grants};case`plugin_permissions`:return{...e,pluginPermissions:t.grants};case`plugin_path_request`:return{...e,pathRequests:[...e.pathRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_path_resolved`:return{...e,pathRequests:e.pathRequests.filter(e=>e.id!==t.id)};case`plugin_permission_request`:return{...e,permRequests:[...e.permRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_permission_resolved`:return{...e,permRequests:e.permRequests.filter(e=>e.id!==t.id)};case`plugin_job`:{let{pluginId:n,phase:r,ok:i,action:a}=t.job,o=e.pluginUpdates;a===`update`&&r===`done`&&i&&e.pluginUpdates?.[n]&&(o={...e.pluginUpdates,[n]:{...e.pluginUpdates[n],updatable:!1}});let s=e.pluginJobs[t.job.jobId],c=t.line?[...s?.lines??[],t.line].slice(-40):s?.lines??[],l={...s,...t.job,lines:c,startedAt:s?.startedAt??Date.now()};return{...e,pluginUpdates:o,pluginJobs:{...e.pluginJobs,[t.job.jobId]:l}}}case`plugin_catalog_sync_result`:return{...e,catalogSync:{...t.result,receivedAt:Date.now()}};case`preset_export_result`:return{...e,presetExport:{...t.result,receivedAt:Date.now()}};case`preset_import_result`:return{...e,presetImport:{...t.result,source:t.source,receivedAt:Date.now()}};case`preset_catalog_result`:return{...e,presetCatalog:{...t.result,receivedAt:Date.now()}};case`preset_share_result`:return{...e,presetShare:{...t.result,receivedAt:Date.now()}};case`plugin_install_inspect_result`:return{...e,installInspect:t.result};case`dsh_patches`:{let n={patchDir:t.patchDir,files:t.files};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},patches:n},dshPatches:n}}case`dsh_market_data`:{let n={count:t.count,updated:t.updated,categories:t.categories,plugins:t.plugins};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},market:n},dshMarket:n}}case`dsh_presets`:{let n={presets:t.presets,defaultPreset:t.defaultPreset};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},presets:n},dshPresets:n}}case`dsh_permission`:{let n={options:t.options,defaultPreset:t.defaultPreset};return{...e,dsh:{...e.dsh??{patches:null,market:null,presets:null,permission:null},permission:n},dshPermission:n}}case`terminal_add`:return{...e,terminals:[...e.terminals,t.meta]};case`terminal_remove`:return{...e,terminals:e.terminals.filter(e=>e.id!==t.id||(e.ownerKind??`client`)!==(t.ownerKind??`client`)||(e.ownerKind??`client`)!==`client`&&e.conversationId!==t.conversationId)};case`terminal_exit`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!1,exitCode:t.exitCode}:e)};case`terminal_restart`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!0,exitCode:null}:e)};case`terminal_list`:{let n=e.activeConversationId||e.state?.conversationId||``,r=t.conversationId??n,i=t.terminals.filter(e=>(e.ownerKind??`client`)===`client`||r===n).map(e=>({...e,ownerKind:e.ownerKind??`client`,conversationId:r}));return{...e,terminals:i}}case`terminal_active`:return{...e,terminalActiveId:t.id};case`transition_start`:{let n=t.kind===`cwd`?Mh(t.target,e.engine):null;return{...e,...n&&n.length>0?{sessions:n}:{},transition:{kind:t.kind,target:t.target,phase:`start`,progress:t.progress,text:t.text,textEn:t.textEn,startedAt:Date.now()}}}case`transition_progress`:{let n=t.msg;if(n.phase===`done`||n.phase===`error`)return{...e,transition:e.transition?{...e.transition,phase:n.phase,progress:100,text:n.text,textEn:n.textEn}:null};let r=e.transition;return{...e,transition:{kind:n.kind,target:n.target,phase:n.phase,progress:Math.max(r?.target===n.target?r.progress:0,n.progress),text:n.text,textEn:n.textEn,totalMessages:n.totalMessages??r?.totalMessages,previewMessages:n.previewMessages??r?.previewMessages,startedAt:r?.startedAt??Date.now()}}}case`transition_tick`:{let t=e.transition;if(!t||t.phase===`done`||t.phase===`error`)return e;let n=t.phase===`start`?26:t.phase===`fs`?56:92;if(t.progress>=n)return e;let r=Math.max(1,Math.round((n-t.progress)*.16));return{...e,transition:{...t,progress:Math.min(n,t.progress+r)}}}case`transition_clear`:return e.transition?{...e,transition:null}:e;default:return e}}var hh=`pi-web-client-id`,gh=`pi-web-client-id:`,_h=`__PI_CID__:`,vh=null;function yh(){try{if(typeof window<`u`&&typeof window.name==`string`&&window.name){let e=window.name;if(e.startsWith(gh)){let t=e.slice(17).trim();if(t)return t}let t=e.indexOf(_h);if(t!==-1){let n=e.slice(t+11).trim();if(n)return n}}}catch{}try{if(typeof sessionStorage<`u`){let e=sessionStorage.getItem(hh);if(e)return e}}catch{}return null}function bh(e){try{if(typeof window<`u`){let t=typeof window.name==`string`?window.name:``;if(!t||t.startsWith(gh))window.name=`${gh}${e}`;else{let n=t.indexOf(_h),r=n===-1?t:t.slice(0,n);window.name=`${r}${_h}${e}`}}}catch{}try{typeof sessionStorage<`u`&&sessionStorage.setItem(hh,e)}catch{}}function xh(){if(vh)return vh;let e=yh();return e||=ht(),bh(e),vh=e,e}var Sh=`pi-web-last-cwd`;function Ch(){try{return localStorage.getItem(Sh)}catch{return null}}function wh(e){try{localStorage.setItem(Sh,e)}catch{}}function Th(e){try{let t=localStorage.getItem(Sh);if(!t)return;let n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase();(t===e||n(t)===n(e))&&localStorage.removeItem(Sh)}catch{}}var Eh=`pi-web-recent-projects`;function Dh(){try{let e=localStorage.getItem(Eh);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Oh(e){try{localStorage.setItem(Eh,JSON.stringify(e.slice(0,20)))}catch{}}function kh(e){try{let t=Dh(),n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),r=n(e);Oh(t.filter(e=>n(e.path)!==r))}catch{}}var Ah=`pi-web-recent-sessions:`;function jh(e,t){let n=t??`pi`;return e?`${Ah}${n}:${e.trim().replace(/[\\/]+$/,``).toLowerCase()}`:`pi-web-recent-sessions:${n}:default`}function Mh(e,t){try{let n=jh(e??Ch(),t),r=localStorage.getItem(n);if(!r)return[];let i=JSON.parse(r);return Array.isArray(i)?i:[]}catch{return[]}}function Nh(e,t,n){try{let r=jh(e??Ch(),n);localStorage.setItem(r,JSON.stringify(t.slice(0,50)))}catch{}}function Ph(e,t,n){try{let r=Mh(t,n),i=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),a=i(e);Nh(t,r.filter(e=>i(e.path)!==a),n)}catch{}}function Fh(){let e=location.protocol===`https:`?`wss:`:`ws:`;return Qe(`${e}//${location.host}${q(`/ws`)}`)}function Ih(){let[e,t]=(0,Q.useReducer)(mh,{status:`connecting`,ready:!1,state:null,hostMetrics:null,latencyMs:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:Mh(),conversations:[],elsewhere:[],activeConversationId:``,projects:Dh(),files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},defaultModel:null,providerOAuthFlows:[],providerOAuthResults:th().results,installResult:null,pathCompletions:[],update:null,updatesAll:null,updatesSdk:null,widgets:[],statuses:[],dialog:null,tuiOverlay:null,approval:null,approvals:[],question:null,questionQueue:null,remoteQuestion:null,commands:[],commandsPath:``,slashCommands:[],terminals:[],terminalActiveId:null,goal:dh,bgServers:[],schedulerTasks:[],pluginPanelGroups:[],settings:null,fetchModelsResult:null,testModelConnectionResult:null,enrichModelsResult:null,enrichModelsProgress:null,refreshProviderResult:null,refreshBuiltinResult:null,appendBuiltinResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginUpdates:null,checkingPluginUpdates:!1,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},catalogSync:null,presetExport:null,presetImport:null,presetCatalog:null,presetShare:null,installInspect:null,pluginGrants:[],pluginPermissions:[],pathRequests:[],permRequests:[],dsh:null,dshPatches:null,dshMarket:null,mcpOAuthResult:null,mcpMarketResult:null,skillMarketResult:null,skillContentResult:null,dshPresets:null,dshPermission:null,protocolMismatch:!1,transition:null,sandboxDiff:null,optimisticQueue:Ap()}),n=(0,Q.useRef)(null),r=(0,Q.useRef)(ds()),i=(0,Q.useRef)(0),a=(0,Q.useRef)(null),o=(0,Q.useRef)(!0),s=(0,Q.useRef)(0),c=(0,Q.useRef)(0),l=(0,Q.useRef)(new Map),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=(0,Q.useRef)(null),p=(0,Q.useRef)(new Set),m=(0,Q.useRef)(`live`),h=()=>{u.current||=setTimeout(()=>{u.current=null;let e=n.current;ch(e)&&e.send(JSON.stringify({type:`get_state`}))},300)},g=(e,t)=>{let n=l.current,r=n.get(e);if(r!==void 0&&t!==r+1){let t=D.current.chat;e===(t.activeConversationId||t.state?.conversationId)&&h()}n.set(e,t)},_=(0,Q.useCallback)((e,n)=>{let r=++c.current;t({type:`notice`,notice:{id:r,level:e,text:n}})},[]);(0,Q.useEffect)(()=>{if(!e.transition)return;if(e.transition.phase===`done`||e.transition.phase===`error`){let e=setTimeout(()=>t({type:`transition_clear`}),180);return()=>clearTimeout(e)}let n=setInterval(()=>{if(Date.now()-(e.transition?.startedAt??0)>2e4){t({type:`transition_clear`});return}t({type:`transition_tick`})},160);return()=>clearInterval(n)},[e.transition]);let v=(0,Q.useCallback)(e=>{let r=n.current;if(!ch(r))return!1;let i=D.current.chat;(e.type===`terminal_input`||e.type===`terminal_resize`||e.type===`terminal_kill`||e.type===`rename_terminal`||e.type===`terminal_attach`)&&!e.ownerKind&&(e={...e,ownerKind:`client`});let a=i.state;if(e.type===`load_earlier_messages`&&a&&(!e.conversationId||e.conversationId===a.conversationId)&&(e={...e,conversationId:a.conversationId,historyGeneration:e.historyGeneration??a.historyGeneration,beforeId:e.beforeId??a.messages[0]?.id,before:e.before??a.historyStart}),e.type===`set_cwd`&&e.path){let n=(a?.cwd??``).trim().replace(/[\\/]+$/,``).toLowerCase(),r=e.path.trim().replace(/[\\/]+$/,``).toLowerCase();r&&r!==n&&t({type:`transition_start`,kind:`cwd`,target:e.path,progress:14,text:`正在切换到工作目录:${e.path}`,textEn:`Switching to workspace: ${e.path}`})}else if(e.type===`switch_session`&&(e.path||e.sessionId)){Yt();let n=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),r=n(a?.sessionFile),i=n(a?.sessionId),o=n(a?.conversationId),s=n(e.path||e.sessionId);s&&s!==r&&s!==i&&s!==o&&t({type:`transition_start`,kind:`session`,target:e.path||e.sessionId||``,progress:14,text:`正在流式载入历史会话…`,textEn:`Streaming session history…`})}else e.type===`new_chat`?(Yt(),a&&(a.messages.length>0||a.isStreaming)&&t({type:`transition_start`,kind:`new_chat`,target:a.cwd,progress:22,text:`正在初始化新对话…`,textEn:`Initializing new chat…`})):e.type===`switch_conversation`&&e.id&&(Yt(),a&&e.id!==a.conversationId&&t({type:`transition_start`,kind:`conversation`,target:e.id,progress:35,text:`正在切换对话…`,textEn:`Switching conversation…`}));if(ch(r)){if(e.type===`check_updates_all`&&e.force===!0&&t({type:`updates_check_started`}),e.type===`check_plugin_updates`&&t({type:`plugin_updates_check_started`}),r.send(JSON.stringify(e)),e.type===`prompt`?(t({type:`optimistic_queue_add`,text:e.text,attachments:e.attachments,queue:e.queue}),t({type:`optimistic_prompt_echo`,text:e.text,attachments:e.attachments})):e.type===`queue_remove`&&t({type:`optimistic_queue_remove`,kind:e.kind,text:e.text,index:e.index}),e.type===`question_answer`){if(t({type:`question_queue_answered`,id:e.id,owner:e.owner}),e.owner){D.current.chat.question?.id===e.id&&D.current.chat.questionQueue?.some(t=>t.id===e.id&&t.owner===e.owner)&&(p.current.add(e.id),t({type:`question`,question:null}));let n=D.current.chat.remoteQuestion;n&&n.id===e.id&&n.owner===e.owner&&t({type:`remote_question`,question:null})}else{if(p.current.add(e.id),p.current.size>64){let e=p.current.values().next().value;e!==void 0&&p.current.delete(e)}m.current=`live`,t({type:`question`,question:null})}}return!0}return!1},[]),y=(0,Q.useCallback)((e,n)=>{let r=Yp({current:D.current.chat.question,source:m.current,snapshot:e,answered:p.current,activeConversationId:n});r.changed&&(m.current=r.source,t({type:`question`,question:r.question}))},[]);an(v);let b=(0,Q.useCallback)(()=>{if(!o.current)return;t({type:`status`,status:`connecting`});let e=new WebSocket(Fh());n.current=e;let u=0;e.onopen=()=>{n.current===e&&(t({type:`status`,status:`open`}),i.current=0,s.current=Date.now(),u=performance.now(),e.send(JSON.stringify({type:`hello`,clientId:xh(),locale:ih()})))};let d=new Set([`snapshot_delta`,`message_delta`,`tool_delta`,`earlier_messages`,`terminal_output`,`terminal_exit`,`terminal_list`]);e.onmessage=i=>{if(n.current!==e)return;s.current=Date.now();let a;try{a=JSON.parse(i.data)}catch{return}if(`conversationId`in a&&typeof a.conversationId==`string`&&d.has(a.type)){let e=D.current.chat.activeConversationId||D.current.chat.state?.conversationId;if(e&&a.conversationId!==e)return}switch(a.type){case`ready`:{if((D.current.chat.settings?.autoReload??!0)&&a.buildId&&a.buildId!==`20261031T05280`){let e=`pi-web-ui-reloaded-${a.buildId}`;if(!sessionStorage.getItem(e)){sessionStorage.setItem(e,`1`),location.reload();return}}let n=D.current.chat.engine;n&&a.engine&&n!==a.engine&&r.current.clear(),nn({engine:a.engine??`pi`,managed:!!a.managed,tabs:a.tabs,appVersion:a.appVersion,serverVersion:a.serverVersion,service:a.service,...a.engineCapabilities?{engineCapabilities:a.engineCapabilities}:{},...a.engines?{engines:a.engines}:{}});let i=u>0?Math.max(0,Math.round(performance.now()-u)):null;t({type:`ready`,serverVersion:a.serverVersion,protocolVersion:a.protocolVersion,engine:a.engine,appVersion:a.appVersion,managed:a.managed,tabs:a.tabs,service:a.service,latencyMs:i,engines:a.engines}),p.current.clear(),t({type:`question`,question:null}),e.send(JSON.stringify({type:`get_state`})),e.send(JSON.stringify({type:`list_files`})),e.send(JSON.stringify({type:`list_models`})),e.send(JSON.stringify({type:`list_commands`})),e.send(JSON.stringify({type:`get_commands`})),a.managed||(e.send(JSON.stringify({type:`check_update`})),e.send(JSON.stringify({type:`check_updates_all`})));break}case`snapshot`:l.current=new Map,t({type:`snapshot`,state:a.state}),y(a.state.pendingQuestion,a.state.conversationId);break;case`snapshot_delta`:{let e=D.current.chat.state;if(e)(e.conversationId!==a.conversationId||e.rev!==a.baseRev)&&h();else{let e=n.current;ch(e)&&e.send(JSON.stringify({type:`get_state`}))}let r=D.current.chat.activeConversationId||e?.conversationId;if(r&&a.conversationId!==r)break;t({type:`snapshot_delta`,msg:a}),y(a.state.pendingQuestion,r||a.conversationId);break}case`earlier_messages`:{let e=D.current.chat.state;if(e?.conversationId!==a.conversationId)break;if(Jm(e,a)){h();break}t({type:`earlier_messages`,msg:a});break}case`tool_delta`:g(a.conversationId,a.seq),t({type:`tool_delta`,toolCallId:a.toolCallId,toolName:a.toolName,delta:a.delta,...a.mode?{mode:a.mode}:{}});break;case`tool_status`:t({type:`tool_status`,status:a});break;case`message_delta`:g(a.conversationId,a.seq),t({type:`message_delta`,msg:a});break;case`subagent_handoff`:break;case`notice`:{let e=++c.current;(a.level===`error`||a.level===`warning`)&&t({type:`transition_clear`}),t({type:`notice`,notice:{id:e,level:a.level,text:a.text,textEn:a.textEn}});break}case`transition_progress`:t({type:`transition_progress`,msg:a});break;case`engines_status`:nn({engines:a.engines}),t({type:`engines_status`,engines:a.engines});break;case`sessions`:t({type:`sessions`,sessions:a.sessions});break;case`conversations`:t({type:`conversations`,conversations:a.conversations,activeId:a.activeId,elsewhere:a.elsewhere});break;case`projects`:t({type:`projects`,projects:a.projects});break;case`sandbox_diff`:t({type:`sandbox_diff`,diff:a.diff});break;case`files`:t({type:`files`,files:a});break;case`canvas_list_result`:window.dispatchEvent(new CustomEvent(ss,{detail:a}));break;case`file_upload_result`:window.dispatchEvent(new CustomEvent(`pi:file-upload-result`,{detail:a}));break;case`file_changed`:t({type:`file_changed`,path:a.path});break;case`file_content`:t({type:`file_content`,content:a});break;case`models`:t({type:`models`,models:a.models,loading:!1});break;case`models_config`:t({type:`models_config`,providers:a.providers});break;case`providers_status`:t({type:`providers_status`,providers:a.providers});break;case`provider_keys`:t({type:`provider_keys`,keys:a.keys});break;case`default_model`:t({type:`default_model`,modelId:a.modelId});break;case`provider_oauth_started`:case`provider_oauth_flows`:case`provider_oauth_prompt`:case`provider_oauth_event`:case`provider_oauth_result`:case`provider_oauth_logout_result`:t({type:`provider_oauth`,message:a});break;case`fetch_models_result`:t({type:`fetch_models_result`,result:{reqId:a.reqId,ok:a.ok,models:a.models,error:a.error}});break;case`test_model_connection_result`:t({type:`test_model_connection_result`,result:{reqId:a.reqId,ok:a.ok,latencyMs:a.latencyMs,error:a.error}});break;case`enrich_models_progress`:t({type:`enrich_models_progress`,progress:{reqId:a.reqId,phase:a.phase,current:a.current,total:a.total,message:a.message}});break;case`enrich_models_result`:t({type:`enrich_models_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,error:a.error}});break;case`refresh_provider_result`:t({type:`refresh_provider_result`,result:{reqId:a.reqId,ok:a.ok,added:a.added,total:a.total,error:a.error}});break;case`refresh_builtin_result`:t({type:`refresh_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`append_builtin_result`:t({type:`append_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`clone_provider_result`:t({type:`clone_provider_result`,result:{reqId:a.reqId,ok:a.ok,config:a.config,configs:a.configs,error:a.error}});break;case`scm_data`:t({type:`scm_data`,data:a});break;case`search_files_result`:t({type:`file_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,truncated:a.truncated}});break;case`session_search_results`:t({type:`session_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results}});break;case`scm_changed`:t({type:`scm_changed`});break;case`tool_info`:Hl(a);break;case`tool_prompt`:lm(a);break;case`compacted_messages_result`:qd(a);break;case`heartbeat`:(a.hostMetrics||typeof a.latencyMs==`number`)&&t({type:`host_metrics`,metrics:a.hostMetrics,latencyMs:typeof a.latencyMs==`number`?a.latencyMs:void 0});break;case`install_result`:t({type:`install_result`,result:a});break;case`path_completions`:t({type:`path_completions`,completions:a.completions});break;case`update_status`:t({type:`update_status`,status:a});break;case`update_status_all`:t({type:`update_status_all`,items:a.items,piSdk:a.piSdk});break;case`widgets`:t({type:`widgets`,widgets:a.widgets});break;case`statuses`:t({type:`statuses`,statuses:a.statuses});break;case`dialog`:t({type:`dialog`,dialog:{id:a.id,kind:a.kind,title:a.title,args:a.args,code:a.code}});break;case`dialog_closed`:t({type:`dialog`,dialog:null});break;case`tui_overlay_open`:tm(a.id),t({type:`tui_overlay`,overlay:{id:a.id,title:a.title,cols:a.cols,rows:a.rows,initialAnsi:a.initialAnsi}});break;case`tui_overlay_render`:rm(a.id,a.ansi);break;case`tui_overlay_close`:tm(),t({type:`tui_overlay`,overlay:null});break;case`question_pending`:m.current=`live`,t({type:`question`,question:{id:a.id,...a.deadline===void 0?{}:{deadline:a.deadline},questions:a.questions,...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`tool_approval_pending`:t({type:`tool_approval`,approval:{id:a.id,toolCallId:a.toolCallId,toolName:a.toolName,params:a.params,reason:a.reason,reasonEn:a.reasonEn,...a.category?{category:a.category}:{},...a.hits?{hits:a.hits}:{},...a.parentTool?{parentTool:a.parentTool}:{},...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`tool_approval_resolved`:t({type:`tool_approval`,approval:null,resolvedId:a.id});break;case`question_retracted`:{D.current.chat.remoteQuestion?.id===a.id&&t({type:`remote_question`,question:null});let e=D.current.chat.question;if(e&&e.id===a.id){if(p.current.add(a.id),p.current.size>64){let e=p.current.values().next().value;e!==void 0&&p.current.delete(e)}m.current=`live`,t({type:`question`,question:null})}break}case`question_queue`:t({type:`question_queue`,questions:a.questions});break;case`elsewhere_question`:t({type:`remote_question`,question:{owner:a.owner,convId:a.convId,id:a.id,questions:a.questions,...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`page_request`:(async()=>{let e=window.__piWebUiHost,t;if(!e?.pageCall)t={ok:!1,error:`宿主页面桥不可用(页面版本过旧?)—— 刷新本页后再试`};else try{t=await e.pageCall({op:a.op,...a.args===void 0?{}:{args:a.args},...a.target?{target:a.target}:{},timeoutMs:a.timeoutMs})}catch(e){t={ok:!1,error:e instanceof Error?e.message:String(e)}}v({type:`page_response`,id:a.id,ok:t.ok===!0,...t.ok===!0?t.result===void 0?{}:{result:t.result}:{error:t.error??`页面操作失败`}})})();break;case`terminal_output`:r.current.write(a.conversationId??``,a.terminalId,a.data,a.reset,a.ownerKind??`client`);break;case`terminal_exit`:t({type:`terminal_exit`,conversationId:a.conversationId,ownerKind:a.ownerKind,terminalId:a.terminalId,exitCode:a.exitCode});break;case`terminal_list`:r.current.reconcile(a.conversationId??D.current.chat.activeConversationId,a.terminals),t({type:`terminal_list`,conversationId:a.conversationId,terminals:a.terminals});break;case`commands`:t({type:`commands`,commands:a.commands,path:a.path});break;case`slash_commands`:t({type:`slash_commands`,commands:a.commands});break;case`goal_status`:t({type:`goal_status`,status:a.status});break;case`plan_updated`:t({type:`plan_updated`,conversationId:a.conversationId,plan:a.plan});break;case`settings_state`:a.settings?.markers&&rp(a.settings.markers.map(e=>e.name)),t({type:`settings`,settings:a.settings});break;case`mcp_servers`:t({type:`mcp_servers`,servers:a.servers,globalConfigPath:a.globalConfigPath,projectConfigPath:a.projectConfigPath});break;case`mcp_oauth_result`:t({type:`mcp_oauth_result`,result:a});break;case`mcp_market_result`:t({type:`mcp_market_result`,result:a});break;case`skill_market_result`:t({type:`skill_market_result`,result:a});break;case`skill_content_result`:t({type:`skill_content_result`,result:a});break;case`bg_servers`:t({type:`bg_servers`,servers:a.servers});break;case`scheduler_tasks`:t({type:`scheduler_tasks`,tasks:a.tasks});break;case`plugin_panel_items`:t({type:`plugin_panel_items`,groups:a.groups});break;case`plugins`:t({type:`plugins`,plugins:a.plugins,epoch:a.epoch});break;case`plugin_updates`:t({type:`plugin_updates`,updates:a.updates});break;case`plugin_catalog`:t({type:`plugin_catalog`,entries:a.entries,epoch:a.epoch});break;case`plugin_grants`:t({type:`plugin_grants`,grants:a.grants});break;case`plugin_permissions`:t({type:`plugin_permissions`,grants:a.grants});break;case`plugin_permission_request`:t({type:`plugin_permission_request`,req:{id:a.id,pluginId:a.pluginId,family:a.family,...a.hosts?{hosts:a.hosts}:{},...a.models?{models:a.models}:{},...a.reason?{reason:a.reason}:{}}});break;case`plugin_permission_resolved`:t({type:`plugin_permission_resolved`,id:a.id});break;case`plugin_path_request`:t({type:`plugin_path_request`,req:{id:a.id,pluginId:a.pluginId,path:a.path,...a.reason?{reason:a.reason}:{}}});break;case`plugin_dom_consent_request`:a.from===xh()&&e.send(JSON.stringify({type:`plugin_dom_consent_response`,id:a.id,ok:!0}));break;case`plugin_job`:t({type:`plugin_job`,job:{jobId:a.jobId,action:a.action,pluginId:a.pluginId,phase:a.phase,...a.ok===void 0?{}:{ok:a.ok},...a.error?{error:a.error}:{},...a.output?{output:a.output}:{}},...a.line?{line:a.line}:{}});break;case`plugin_install_inspect_result`:t({type:`plugin_install_inspect_result`,result:{requestId:String(a.requestId??``),source:String(a.source??``),kind:a.kind,suggestedId:String(a.suggestedId??``),installed:a.installed===!0,...a.problem?{problem:a.problem}:{},...a.detail?{detail:a.detail}:{},...a.manifest?{manifest:a.manifest}:{}}});break;case`new_chat_result`:Nt(a);break;case`plugin_catalog_sync_result`:Ht(a),t({type:`plugin_catalog_sync_result`,result:{requestId:String(a.requestId??``),ok:a.ok===!0,...a.error?{error:a.error}:{},...a.entries?{entryCount:a.entries.length}:{},...a.installed?{installed:a.installed}:{}}});break;case`preset_export_result`:t({type:`preset_export_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.name?{name:a.name}:{},...a.fileName?{fileName:a.fileName}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`preset_import_result`:{let e=String(a.requestId??``),n=e.startsWith(`url:`)?`url`:e.startsWith(`file:`)?`file`:`paste`;t({type:`preset_import_result`,source:n,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,dryRun:a.dryRun===!0,...a.preview?{preview:a.preview}:{},...a.applied===void 0?{}:{applied:a.applied},...a.applyError?{applyError:a.applyError}:{},...a.applyDeferred?{applyDeferred:!0}:{},...a.error?{error:a.error}:{}}});break}case`preset_catalog_result`:t({type:`preset_catalog_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,entries:a.entries??[],source:a.source??``,cached:a.cached===!0,fetchedAt:a.fetchedAt??0,...a.error?{error:a.error}:{}}});break;case`preset_share_result`:t({type:`preset_share_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.method?{method:a.method}:{},...a.url?{url:a.url}:{},...a.name?{name:a.name}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`dsh_patches`:t({type:`dsh_patches`,patchDir:a.patchDir,files:a.files});break;case`dsh_market_data`:t(a);break;case`dsh_presets`:t({type:`dsh_presets`,presets:a.presets,defaultPreset:a.defaultPreset});break;case`dsh_permission`:t({type:`dsh_permission`,options:a.options,defaultPreset:a.defaultPreset});break;case`plugin_data`:qm(a.pluginId,a.payload)||hm(a.pluginId,a.payload);break;case`remote_ssh_probe_result`:case`remote_ssh_list_dir_result`:case`remote_ssh_install_result`:case`remote_ssh_profiles_result`:ia(a)}},e.onclose=()=>{if(n.current!==e||(n.current=null,r.current.clear(),!o.current))return;t({type:`status`,status:`closed`});let s=Math.min(1e3*2**i.current,1e4);i.current+=1,a.current=setTimeout(()=>{a.current=null,b()},s)},e.onerror=()=>{}},[]);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail??ih();t&&v({type:`set_locale`,locale:t})};return window.addEventListener(Fe,e),()=>window.removeEventListener(Fe,e)},[v]),(0,Q.useEffect)(()=>{let n=n=>{let r=e.state?.cwd;r&&n.key&&n.key===jh(r,e.engine)&&t({type:`sync_cached_sessions`,sessions:Mh(r,e.engine)})};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)},[e.state?.cwd,e.engine]),(0,Q.useEffect)(()=>{o.current=!0,b();let e=setInterval(()=>{if(!o.current)return;let e=n.current;ch(e)&&Date.now()-s.current>3e4&&e.close()},5e3),t=()=>{if(!o.current||typeof document<`u`&&document.visibilityState===`hidden`)return;let e=n.current;if(!e||e.readyState===sh||e.readyState===oh){a.current&&=(clearTimeout(a.current),null),b();return}ch(e)&&(Date.now()-s.current>15e3||!D.current.chat.state)&&e.send(JSON.stringify({type:`get_state`}))};return typeof document<`u`&&document.addEventListener(`visibilitychange`,t),typeof window<`u`&&(window.addEventListener(`pageshow`,t),window.addEventListener(`online`,t)),()=>{o.current=!1,clearInterval(e),a.current&&=(clearTimeout(a.current),null),typeof document<`u`&&document.removeEventListener(`visibilitychange`,t),typeof window<`u`&&(window.removeEventListener(`pageshow`,t),window.removeEventListener(`online`,t)),n.current?.close(),n.current=null,r.current.clear()}},[b]),(0,Q.useEffect)(()=>{let t=e.state?.cwd;if(t){if(!d.current){d.current=!0;let e=Ch();if(e&&e!==t){v({type:`set_cwd`,path:e});return}}f.current!==t&&(f.current=t,wh(t))}},[e.state?.cwd,v]),(0,Q.useEffect)(()=>{nn({ready:e.ready,status:e.status,cwd:e.state?.cwd??``,workspaceRoots:e.state?.workspaceRoots??[],homeDir:e.state?.homeDir??``,desktopDir:e.state?.desktopDir??``,chatUploadMaxMb:e.settings?.chatUploadMaxMb??20,workspaceUploadMaxMb:e.settings?.workspaceUploadMaxMb??100,folderUploadMaxMb:e.settings?.folderUploadMaxMb??32,...e.state?.engineCapabilities?{engineCapabilities:e.state.engineCapabilities}:{}})},[e.ready,e.status,e.state?.cwd,e.state?.workspaceRoots,e.state?.homeDir,e.state?.desktopDir,e.settings?.chatUploadMaxMb,e.settings?.workspaceUploadMaxMb,e.settings?.folderUploadMaxMb,e.state?.engineCapabilities]);let x=(0,Q.useCallback)(e=>t({type:`dismiss_notice`,id:e}),[]),S=(0,Q.useCallback)(e=>{let n=D.current.chat;if(!n.ready||n.terminals.some(t=>t.id===e.id&&(t.ownerKind??`client`)===(e.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||t.conversationId===e.conversationId)))return;let r=e.ownerKind??`client`,i={terminalId:e.id,conversationId:e.conversationId,ownerKind:r,cols:e.cols,rows:e.rows};(e.command?v({type:`run_command`,...i,command:e.command}):v({type:`terminal_create`,...i,title:e.title,cwd:e.cwd,agentBash:e.agentBash,locale:ih()}))&&t({type:`terminal_add`,meta:{...e,ownerKind:r}})},[v]),C=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_remove`,id:e,ownerKind:n,conversationId:r}),[]),w=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_restart`,terminalId:e,ownerKind:n,conversationId:r}),[]),T=(0,Q.useCallback)(e=>t({type:`terminal_active`,id:e}),[]),E=(0,Q.useCallback)((e,t,n,i=`client`)=>r.current.register(e,t,n,i),[]),D=(0,Q.useRef)({chat:e,send:v,pushNotice:_,dismissNotice:x,terminal:{create:S,close:C,register:E,restart:w,select:T}});return D.current={chat:e,send:v,pushNotice:_,dismissNotice:x,terminal:{create:S,close:C,register:E,restart:w,select:T}},D.current}function Lh(e){let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`:`${t.getMonth()+1}/${t.getDate()}`}function Rh(e){let t=e instanceof HTMLElement?e:null;if(!t)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable}var zh=`pi-web-ui:lp-collapse-projects`,Bh=`pi-web-ui:lp-collapse-convs`,Vh=`pi-web-ui:lp-collapse-sessions`,Hh=`pi-web-ui:lp-collapse-subagents`;function Uh(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Hh);if(e)return new Set(JSON.parse(e))}catch{}return new Set});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(Hh,JSON.stringify([...n]))}catch{}return n})},[])]}function Wh(e,t=!1){let[n,r]=(0,Q.useState)(()=>{try{let t=localStorage.getItem(e);if(t===`1`)return!0;if(t===`0`)return!1}catch{}return t});return[n,(0,Q.useCallback)(()=>{r(t=>{let n=!t;try{localStorage.setItem(e,n?`1`:`0`)}catch{}return n})},[e])]}var Gh=`pi-web-ui:lp-collapse-plugin-sections`;function Kh(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Gh),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(Gh,JSON.stringify([...n]))}catch{}return n})},[])]}var qh=`pi-web-ui:lp-sizes`,Jh={projects:1,groups:1,convs:1,sessions:1},Yh=32,Xh={running:`pluginRunStatusRunning`,done:`pluginRunStatusDone`,error:`pluginRunStatusError`},Zh=72;function Qh(){try{return Kr(localStorage.getItem(qh),Jh)}catch{return{...Jh}}}var $h=(0,Q.memo)(function({sessionFile:e,conversations:t,elsewhere:n,sessions:r,projects:i,activeConversationId:a,activeGroupId:o,panelSend:c,active:l,collapsible:u,onToggleCollapse:d,pathCompletions:f,uiContextSession:p,uiLeftSessions:m,uiContextProject:h,uiProjectsActions:_,uiLeftProject:v,uiRunningActions:b,uiHistoryActions:x,uiSections:S,renderPluginSectionBody:C,uiPluginRunning:w,onPluginRunningAction:T,uiLeftRunning:E,uiLeftHistory:D,onUiAction:O,presetNames:k,transition:A,onOpenSandboxModal:j}){let N=V(),ee=rn(),F=e,te=en(`ready`),ne=en(`status`),re=en(`cwd`),I=en(`workspaceRoots`),L=re,[ie,ae]=(0,Q.useState)(!1),[oe,se]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(null),[de,B]=(0,Q.useState)(null),[fe,he]=(0,Q.useState)(``),[H,ge]=Wh(zh,!1),[U,W]=Wh(Bh,!1),[G,_e]=Wh(Vh,!1),[K,q]=Kh(),[J,ve]=(0,Q.useState)(!1),[Y,ye]=Uh(),[be,xe]=(0,Q.useState)(60);(0,Q.useEffect)(()=>{xe(60)},[L]);let Se=(0,Q.useMemo)(()=>{if(r.length<=be)return r;let e=F?r.findIndex(e=>e.path===F):-1,t=e>=be?e+10:be;return r.slice(0,t)},[r,be,F]),Ce=(0,Q.useCallback)((e,t)=>{if(!t)return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==a).length;let n=new Map(e.map(e=>[e.id,e])),r=e=>{if(e.id===t)return(n.get(t)?.isSubagent??!1)&&!e.isStreaming&&e.id!==a;let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==a&&r(e)).length},[a]),we=(0,Q.useCallback)((e,t)=>{if(!t)return e.filter(e=>e.isSubagent).length;let n=new Map(e.map(e=>[e.id,e])),r=e=>{if(e.id===t)return n.get(t)?.isSubagent??!1;let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&r(e)).length},[]),Te=(0,Q.useCallback)((e,t)=>{if(!t)return 0;let n=new Map(e.map(e=>[e.id,e])),r=e=>{let r=e,i=new Set;for(;r?.parentId;){if(r.parentId===t)return!0;if(i.has(r.parentId)||(i.add(r.parentId),r=n.get(r.parentId),!r))return!1}return!1};return e.filter(e=>e.isSubagent&&e.isStreaming&&r(e)).length},[]),Ee=(0,Q.useRef)(null),De=(0,Q.useRef)(null),X=(0,Q.useRef)(()=>{}),Oe=Gi(p??[]).length>0,ke=(0,Q.useCallback)((e,n,i)=>{Ee.current={x:e,y:n,target:i};let a=i.kind===`running`?i.id:void 0,o=i.kind===`elsewhere`,s=a??(o&&i.id||void 0),c=Ce(t,a),l=c===0?N(`noFinishedSubagents`):N(a?`dismissFinishedSubagentsScoped`:`dismissFinishedSubagents`,{n:c}),u=!!a&&De.current===a;Pi({x:e,y:n,slot:`contextmenu.session`,target:i,entries:(p??[]).map(e=>{if(e.source!==`host`)return e;if(e.id===`host:conv-rename`)return i.kind===`running`||i.kind===`history`?e:{...e,hidden:!0};if(e.id===`host:conv-takeover`){let t=!!(i.pseudo&&i.owner?.startsWith(`scheduler:`));return o&&s&&i.owner&&!t?e:{...e,hidden:!0}}if(o&&(e.id===`host:conv-dismiss-subagents`||e.id===`host:conv-force-dismiss`))return{...e,hidden:!0};if(e.id===`host:conv-dismiss-subagents`)return{...e,label:l,...c===0?{when:[...e.when??[],`disabled`]}:{}};if(e.id===`host:conv-force-dismiss`)return a?{...e,...u?{label:N(`forceDismissConfirm`)}:{}}:{...e,hidden:!0};if(e.id===`host:conv-pin`){if(i.kind===`history`)return r.find(e=>e.path===i.id)?.pinned?{...e,label:N(`unpinConversation`)}:e;if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return!n||n.isSubagent?{...e,hidden:!0}:n.pinned?{...e,label:N(`unpinConversation`)}:e}if(e.id===`host:conv-persist`){if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return!n||!n.isSubagent&&n.sessionFile?{...e,hidden:!0}:n?.isEphemeral?{...e,label:N(`saveEphemeral`)}:e}if(e.id===`host:conv-copy-id`)return s?e:{...e,hidden:!0};if(e.id===`host:conv-copy-path`)return i.kind===`history`?e:a?t.some(e=>e.id===a&&e.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}:{...e,hidden:!0};if(e.id===`host:conv-copy-link`){if(i.kind===`history`)return r.find(e=>e.path===i.id)?.sessionId||rs(i.id)?e:{...e,hidden:!0};if(!a)return{...e,hidden:!0};let n=t.find(e=>e.id===a);return n?.sessionId||rs(n?.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}}return e.id===`host:conv-quote`?ee.conversationRef&&(s||i.kind===`history`)?e:{...e,hidden:!0}:e}),onHostAction:(e,t)=>X.current(e,t)})},[p,t,Ce,N,ee.conversationRef]);X.current=(0,Q.useCallback)((e,n)=>{let i=n.kind===`running`?n.id:void 0,a=i??(n.kind===`elsewhere`&&n.id||void 0);if(e.id===`host:conv-takeover`){n.kind===`elsewhere`&&a&&n.owner&&c({type:`take_over_conversation`,owner:n.owner,id:a});return}if(e.id===`host:conv-dismiss-subagents`){c(i?{type:`dismiss_finished_subagents`,parentId:i}:{type:`dismiss_finished_subagents`});return}if(e.id===`host:conv-force-dismiss`){let e=Ee.current;if(!i||!e)return;if(De.current!==i)return De.current=i,ke(e.x,e.y,e.target),!0;De.current=null,c({type:`dismiss_conversation`,id:i,force:!0});return}if(e.id===`host:conv-persist`){i&&c({type:`persist_conversation`,id:i});return}if(e.id===`host:conv-pin`){if(n.kind===`history`){let e=r.find(e=>e.path===n.id);c({type:`pin_session`,path:n.id,pinned:!e?.pinned});return}i&&c({type:`pin_conversation`,id:i,pinned:!t.find(e=>e.id===i)?.pinned});return}if(e.id===`host:conv-copy-id`&&a){navigator.clipboard?.writeText(a).catch(()=>{});return}if(e.id===`host:conv-copy-path`){let e=n.kind===`history`?n.id:i&&t.find(e=>e.id===i)?.sessionFile||void 0;e&&navigator.clipboard?.writeText(e).catch(()=>{});return}if(e.id===`host:conv-copy-link`){let e=n.kind===`history`?r.find(e=>e.path===n.id)?.sessionId||rs(n.id):i?t.find(e=>e.id===i)?.sessionId||rs(t.find(e=>e.id===i)?.sessionFile):null;if(e){let t=ns(window.location.href,{sessionId:e});navigator.clipboard?.writeText(t).catch(()=>{})}return}if(e.id===`host:conv-quote`){n.kind===`history`&&n.id?Ft({attachments:[{path:``,key:`conv||${n.id}`,name:n.label||n.id,mode:`conversation`,sessionPath:n.id}]}):a&&Ft({attachments:[{path:``,key:`conv|${a}|`,name:n.label||a,mode:`conversation`,conversationId:a}]});return}if(e.id===`host:conv-rename`){if(se(null),i){let e=t.find(e=>e.id===i);he(e?.title??n.label??``),B(`conv:${i}`)}else if(n.kind===`history`&&n.id){let e=r.find(e=>e.path===n.id);he(e?.name??n.label??``),B(n.id)}return}},[c,ke,t,r]);let je=(e,t,n)=>!e||e.length===0?null:(0,$.jsx)(`span`,{className:t,children:e.map((e,t)=>{let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`lp-slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`lp-slot-badge`,title:a,children:e.badge??i},r):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`lp-slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onClick:e=>e.stopPropagation(),onChange:t=>{t.stopPropagation(),O?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsx)(`button`,{type:`button`,className:`lp-slot-btn`,title:a,"aria-label":i,onClick:t=>{t.stopPropagation(),n?O?.(e,void 0,n):O?.(e)},children:e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):(0,$.jsx)(`span`,{children:i})},r)})}),Me=(0,Q.useCallback)((e,t)=>{Rh(e.target)||Oe&&(e.preventDefault(),e.stopPropagation(),De.current=null,ke(e.clientX,e.clientY,t))},[Oe,ke]),Ne=(0,Q.useRef)(null),[Pe,Fe]=(0,Q.useState)(()=>Qh());(0,Q.useEffect)(()=>{try{localStorage.setItem(qh,JSON.stringify(Pe))}catch{}},[Pe]);let Ie=(0,Q.useMemo)(()=>{let e=new Set,r=new Set;for(let n of t)n.sessionFile&&e.add(n.sessionFile),r.add(`${n.cwd}\0${n.title}`);let i=[],a=new Set;for(let t of n){if(t.sessionFile&&e.has(t.sessionFile)||r.has(`${t.cwd}\0${t.title}`))continue;let n=t.sessionFile?`file:${t.sessionFile}`:`title:${t.cwd}\0${t.title}`;a.has(n)||(a.add(n),i.push({id:t.sessionFile?`elsewhere:${t.cwd}:${t.sessionFile}`:`elsewhere:${t.cwd}:${t.title}${t.owner?`:${t.owner}`:``}`,title:t.title,cwd:t.cwd,messageCount:0,isStreaming:t.isStreaming,isSubagent:!1,elsewhere:!0,pseudo:!!t.pseudo,ownerOffline:!!t.ownerOffline,sessionFile:t.sessionFile,...t.owner&&t.convId?{owner:t.owner,convId:t.convId}:{},...t.hasQuestion?{hasQuestion:!0}:{}}))}return[...t,...i]},[t,n]),Le=Ur(Hr(S)),Re=Le.filter(e=>e.shown),ze=e=>e===`projects`?H:e===`convs`?U:e===`sessions`?G:e===`groups`?J:K.has(e),Ve=(w??[]).reduce((e,t)=>e+t.items.length,0),He=Ie.length+Ve,Ue=Wr(Le,e=>e===`projects`?i.length>0:e!==`convs`||He>0),We=()=>{let e=w??[];return e.length===0?null:e.map(e=>(0,$.jsxs)(`div`,{className:`panel-conv-group lp-plugin-group`,children:[(0,$.jsxs)(`div`,{className:`panel-conv-group-title`,title:e.pluginId,children:[N(`leftPanelPluginGroup`),` · `,e.pluginName]}),e.items.map(t=>(0,$.jsx)(`div`,{className:`lp-row lp-plugin-row`,children:(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-plugin-item${t.action?``:` is-static`}`,title:t.hint?`${t.title} — ${t.hint}`:t.title,onClick:()=>T?.(e,t),children:[(0,$.jsx)(`span`,{className:`lp-plugin-dot st-${t.status}`,title:N(Xh[t.status])}),t.icon?(0,$.jsx)(`span`,{className:`lp-plugin-icon`,"aria-hidden":!0,children:t.icon}):null,(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsx)(`span`,{className:`session-title`,children:t.title}),t.hint?(0,$.jsx)(`span`,{className:`session-sub`,children:t.hint}):null]})]})},t.id))]},`plugin:${e.pluginId}`))},Ge=(0,Q.useMemo)(()=>[...m??[],...E??[]],[m,E]),Ke=(0,Q.useMemo)(()=>[...m??[],...D??[]],[m,D]),qe=(0,Q.useCallback)((e,t)=>n=>{n.preventDefault();let r=n.currentTarget,i=n.clientY,a={...Pe},o=Ne.current;if(!o)return;let s=Ue.filter(e=>ze(e)).length,c=Ue.filter(e=>!ze(e)).reduce((e,t)=>e+(a[t]??1),0)||1,l=Math.max(120,o.clientHeight-s*Yh);r.classList.add(`dragging`),document.body.classList.add(`lp-resizing`);let u=n=>{let{above:r,below:o}=Xo({start:{above:a[e]??1,below:a[t]??1},deltaPx:n.clientY-i,availablePx:l,totalWeight:c,minAbovePx:Zh,minBelowPx:Zh});Fe(n=>({...n,[e]:r,[t]:o}))},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),r.classList.remove(`dragging`),document.body.classList.remove(`lp-resizing`)};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d)},[Pe,Ue,H,U,G,J,K]);(0,Q.useEffect)(()=>{l&&te&&ne===`open`&&re&&(c({type:`list_sessions`}),c({type:`list_projects`}))},[l,te,ne,re,c]);let Je=e=>{let t=e.displayName||e.name||e.firstMessage?.trim();return t&&t.length>0?t:N(`emptyChat`)},Ye=e=>e.split(/[\\/]/).pop()||e,Xe=Gi(h??[]).length>0,Ze=(0,Q.useCallback)((e,t)=>{Rh(e.target)||Xe&&(e.preventDefault(),e.stopPropagation(),Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.path,kind:`project`,label:Ye(t.path)},entries:h??[]}))},[Xe,h]),Qe=(e,t,n,r,i)=>{let a=oe===e;return(0,$.jsx)(`button`,{type:`button`,className:`lp-del ${a?`confirm`:``}`,title:a?n:t,onClick:t=>{t.stopPropagation(),a?(se(null),r()):se(e)},children:a?(0,$.jsx)(z,{}):i??(0,$.jsx)(g,{})})},$e=(e,t,n,r,i,a)=>(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,onClick:n,title:N(t?`expandSection`:`collapseSection`),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[e,r===void 0?``:` (${r})`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:t?(0,$.jsx)(pe,{}):(0,$.jsx)(s,{})})]}),i||a?(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[i,a]}):null]}),et=Ue.filter(e=>!ze(e)),tt=et.reduce((e,t)=>e+(Pe[t]??1),0)||1,nt=e=>et.length<=1?1:(Pe[e]??1)/tt*et.length,at=new Map(Gr(Ue,ze).map(([e,t])=>[e,(0,$.jsx)(`div`,{className:`lp-sash`,onPointerDown:qe(e,t),onDoubleClick:()=>Fe({...Jh}),title:N(`dragToResize`)},`sash-${e}`)])),ot=(0,Q.useCallback)(e=>{let t=e.target;t&&(t.closest(`.lp-row`)||t.closest(`button, input, select, textarea, a`)||(c({type:`new_chat`}),Xt()))},[c]),st={projects:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section panel-projects ${H||i.length===0?`collapsed`:``}`,style:i.length>0&&!H?{flex:`${nt(`projects`)} 1 0px`}:void 0,children:[$e(N(`recentProjects`),H,ge,i.length,(0,$.jsxs)($.Fragment,{children:[j&&(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action lp-sandbox-action`,title:N(`sandboxNewBtn`),"aria-label":N(`sandboxNewBtn`),onClick:()=>j(),children:(0,$.jsx)(An,{})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action`,title:N(`manageProjects`),"aria-label":N(`manageProjects`),onClick:()=>ae(!0),children:(0,$.jsx)(y,{})})]}),je(_,`lp-slot-section`)),i.length>0&&!H&&(0,$.jsx)(`div`,{className:`lp-section-body projects-scroll`,onDoubleClick:ot,children:i.map(e=>{let t=e=>(e??``).trim().replace(/[\\/]+$/,``).toLowerCase(),n=L===e.path,r=A?.kind===`cwd`&&t(A.target)===t(e.path),i=e.sandbox,a=i?i.name:Ye(e.path);return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>se(t=>t===`proj:${e.path}`?null:t),onContextMenu:t=>Ze(t,e),children:[(0,$.jsxs)(`button`,{type:`button`,className:`project-item ${n?`active`:``} ${r?`switching`:``}`,title:i?.sourcePath?`${a}\n${N(`sandboxSourceLabel`)}: ${i.sourcePath}\n${e.path}`:e.path,disabled:r,onClick:()=>{!n&&!r&&c({type:`set_cwd`,path:e.path})},onDoubleClick:t=>{t.stopPropagation(),!r&&(n||c({type:`set_cwd`,path:e.path}),c({type:`new_chat`}),Xt())},children:[r?(0,$.jsx)($o,{className:`project-icon spin`}):i?(0,$.jsx)(An,{className:`project-icon sandbox-icon`}):(0,$.jsx)(Be,{className:`project-icon`}),(0,$.jsxs)(`span`,{className:`project-info`,children:[(0,$.jsxs)(`span`,{className:`project-name`,children:[a,i&&(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${i.ephemeral?`ephemeral`:`permanent`}`,children:i.ephemeral?N(`sandboxBadgeEphemeral`):N(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`project-path`,children:i?.sourcePath?`← ${Ye(i.sourcePath)} · ${e.path}`:e.path})]}),(0,$.jsx)(`span`,{className:`project-time ${r?`switching-pct`:``}`,children:r?`${A.progress}%`:Lh(e.lastUsed)})]}),Qe(`proj:${e.path}`,N(i?`sandboxActionDestroyTip`:`deleteProject`),N(i?`sandboxActionDestroy`:`deleteProjectConfirm`),()=>{Th(e.path),kh(e.path),c(i?{type:`destroy_sandbox`,path:e.path}:{type:`remove_project`,path:e.path})}),je(v,`lp-slot-project`,{id:e.path,kind:`project`,label:a})]},e.path)})})]})}),convs:(0,$.jsx)($.Fragment,{children:He>0&&(0,$.jsxs)(`div`,{className:`lp-section lp-section-convs panel-convs ${U?`collapsed`:``}`,style:U?void 0:{flex:`${nt(`convs`)} 1 0px`},onContextMenu:e=>Me(e,{id:``,kind:`section`,label:N(`runningConversations`)}),children:[$e(N(`runningConversations`),U,W,He,void 0,je(b,`lp-slot-section`)),!U&&(0,$.jsxs)(`div`,{className:`lp-section-body convs-scroll`,onDoubleClick:ot,children:[Zo(Ie,re,a).map(e=>(0,$.jsxs)(`div`,{className:`panel-conv-group`,children:[!e.isCurrent&&(0,$.jsx)(`div`,{className:`panel-conv-group-title`,title:e.cwd,onContextMenu:t=>Ze(t,{path:e.cwd,lastUsed:0}),onDoubleClick:t=>{t.stopPropagation(),c({type:`set_cwd`,path:e.cwd}),c({type:`new_chat`}),Xt()},children:Ye(e.cwd)}),Qo(e.convs,Y).map(({c:n,depth:r,hasKids:i,isCollapsed:o,descendantCount:s,hasStreaming:l,hasError:u,hasQuestion:d})=>{if(n.elsewhere){let e=n.owner,t=n.convId,r=!!n.pseudo,i=!!n.ownerOffline&&!r,a=r&&typeof e==`string`&&e.startsWith(`scheduler:`),o=!!(e&&t)&&!a,s=le===n.id,l=s?N(`takeoverConfirm`):a?`${N(`elsewherePseudoTip`)}\n${n.cwd}`:r?`点击直接在电脑端打开此对话\n${n.cwd}`:`${N(i?`elsewhereOfflineTip`:`elsewhereTip`)}\n${n.cwd}`;return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>ue(e=>e===n.id?null:e),onContextMenu:i=>Me(i,{id:t??n.id,kind:`elsewhere`,label:n.title,...e?{owner:e}:{},...r?{pseudo:!0}:{}}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item elsewhere-item${o?``:` elsewhere-static`}${s?` confirm`:``}`,title:l,tabIndex:o?0:-1,onClick:o?()=>{if(r){c({type:`take_over_conversation`,owner:e,id:t});return}if(!s){ue(n.id);return}ue(null),c({type:`take_over_conversation`,owner:e,id:t})}:void 0,children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:n.isStreaming?(0,$.jsx)(`span`,{className:`conv-streaming`,title:N(`streaming`)}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsxs)(`span`,{className:`session-title`,children:[(0,$.jsx)(`span`,{className:`elsewhere-badge`,children:N(r?`elsewherePseudoBadge`:`elsewhereBadge`)}),i&&(0,$.jsx)(`span`,{className:`elsewhere-badge offline`,title:N(`elsewhereOfflineTip`),children:N(`elsewhereOfflineBadge`)}),n.hasQuestion&&e&&t&&!r&&(0,$.jsx)(`span`,{className:`question-badge clickable`,title:N(`takeoverHasQuestion`),onClick:n=>{n.stopPropagation(),c({type:`peek_elsewhere_question`,owner:e,id:t})},children:`?`}),s?N(`takeoverConfirm`):n.title]}),(0,$.jsx)(`span`,{className:`session-sub`,children:Ye(n.cwd)})]})]}),Oe&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-elsewhere-act`,title:N(`elsewhereActions`),onClick:i=>{i.stopPropagation(),De.current=null;let a=i.currentTarget.getBoundingClientRect();ke(a.left,a.bottom+4,{id:t??n.id,kind:`elsewhere`,label:n.title,...e?{owner:e}:{},...r?{pseudo:!0}:{}})},children:(0,$.jsx)(me,{})})]},n.id)}let f=a===n.id;return(0,$.jsxs)(`div`,{className:`lp-row${r>0?` lp-sub`:``}${i?` lp-has-kids`:``}`,style:r>0?{"--depth":Math.min(r,4)}:void 0,onMouseLeave:()=>se(e=>e===`conv:${n.id}`?null:e),onContextMenu:e=>Me(e,{id:n.id,kind:`running`,label:n.title}),children:[i&&(0,$.jsx)(`button`,{type:`button`,className:`lp-tree-caret${o?` collapsed`:` expanded`}`,title:N(o?`expandSubagents`:`collapseSubagents`),"aria-label":N(o?`expandSubagents`:`collapseSubagents`),onClick:e=>{e.stopPropagation(),ye(n.id)},children:o?(0,$.jsx)(P,{}):(0,$.jsx)(pe,{})}),(0,$.jsxs)(`button`,{type:`button`,className:`session-item ${f?`active`:``}`,title:`${n.title}${e.isCurrent?``:` — ${e.cwd}`}`,onClick:()=>{f||c({type:`switch_conversation`,id:n.id})},children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:i?(0,$.jsx)(`span`,{className:`session-icon-placeholder`}):n.isStreaming?(0,$.jsx)(`span`,{className:`conv-streaming`,title:N(`streaming`)}):n.isSubagent?(0,$.jsx)(ce,{className:`session-icon subagent-icon`}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[de===`conv:${n.id}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:fe,placeholder:N(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>he(e.target.value),onKeyDown:e=>{if(e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing){let e=fe.trim();e&&c({type:`rename_conversation`,id:n.id,name:e}),B(null)}else e.key===`Escape`&&B(null)},onBlur:()=>B(null)}):(0,$.jsxs)(`span`,{className:`session-title`,children:[n.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:N(`pinnedConversation`),children:`📌`}),i&&n.isStreaming&&(0,$.jsx)(`span`,{className:`conv-streaming-dot`,title:N(`streaming`)}),n.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,children:N(`ephemeralBadge`)}),n.forkFrom&&(0,$.jsxs)(`span`,{className:`preset-badge fork-badge`,title:`${N(`forkBadgeTip`)}: ${n.forkFrom.title??n.forkFrom.conversationId}`,children:[`🌿 `,N(`forkBadge`)]}),n.agentPreset&&n.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`preset-badge`,title:n.agentPreset,children:k?.[n.agentPreset]??n.agentPreset}),n.title,n.error&&(0,$.jsx)(`span`,{className:`conv-error-badge`,title:N(`convErrorBadge`,{error:n.error})}),n.hasQuestion&&(0,$.jsx)(`span`,{className:`question-badge`,title:N(`waitingQuestionBadge`),children:`?`}),i&&o&&(0,$.jsxs)(`span`,{className:`subagents-collapsed-badge${l?` has-streaming`:d?` has-question`:u?` has-error`:``}`,title:N(l?`subagentsStreamingTip`:d?`subagentsQuestionTip`:u?`subagentsErrorTip`:`subagentsCountTip`,{n:s}),onClick:e=>{e.stopPropagation(),ye(n.id)},children:[l&&(0,$.jsx)(`span`,{className:`subagent-dot streaming`}),d&&(0,$.jsx)(`span`,{className:`subagent-dot question`,children:`?`}),u&&(0,$.jsx)(`span`,{className:`subagent-dot error`}),(0,$.jsx)(`span`,{className:`subagents-count-text`,children:N(`subagentBadgeCount`,{n:s})})]})]}),de===`conv:${n.id}`?null:(0,$.jsxs)(`span`,{className:`session-sub`,children:[n.isSubagent&&(0,$.jsx)(`span`,{className:`subagent-tag`,children:N(`subagentBadge`)}),n.isSubagent?` · `:null,f?N(`current`):N(`messageCount`,{n:n.messageCount})]})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:N(`renameSession`),onClick:e=>{e.stopPropagation(),se(null),he(n.title),B(`conv:${n.id}`)},children:(0,$.jsx)(M,{})}),(()=>{let e=`conv:${n.id}`,r=oe===e,i=Ce(t,n.id),a=Te(t,n.id),o=we(t,n.id);return o===0&&!n.isStreaming?n.hasUserTerminals?Qe(e,N(`dismissConversation`),N(`dismissTerminalsConfirm`),()=>c({type:`dismiss_conversation`,id:n.id,force:!0}),(0,$.jsx)(R,{})):Qe(e,N(`dismissConversation`),N(`dismissConversationConfirm`),()=>c({type:`dismiss_conversation`,id:n.id}),(0,$.jsx)(R,{})):o===0?Qe(e,N(`dismissConversation`),N(`dismissStreamingConfirm`),()=>c({type:`dismiss_conversation`,id:n.id,force:!0}),(0,$.jsx)(R,{})):r?(0,$.jsxs)(`span`,{className:`lp-del-group`,children:[i>0&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt`,title:N(`dismissFinishedSubagentsScoped`,{n:i}),onClick:e=>{e.stopPropagation(),se(null),c({type:`dismiss_finished_subagents`,parentId:n.id})},children:N(`dismissFinishedOnly`,{n:i})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt danger`,title:N(`forceDismissTitle`,{n:o,m:a}),onClick:e=>{e.stopPropagation(),se(null),c({type:`dismiss_conversation`,id:n.id,force:!0})},children:N(`dismissForceAll`,{n:o})})]}):(0,$.jsx)(`button`,{type:`button`,className:`lp-del`,title:N(`dismissConversation`),onClick:t=>{t.stopPropagation(),se(e)},children:(0,$.jsx)(R,{})})})(),je(Ge,`lp-slot-sessions`)]},n.id)})]},e.cwd)),We()]})]})}),sessions:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section lp-section-sessions panel-sessions ${G?`collapsed`:``}`,style:G?void 0:{flex:`${nt(`sessions`)} 1 0px`},children:[$e(N(`historySessions`),G,_e,r.length,(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-new-chat-action`,title:N(`newChatTip`),"aria-label":N(`newChat`),onClick:()=>{c({type:`new_chat`}),Xt()},children:(0,$.jsx)(rt,{})}),je(x,`lp-slot-section`)),!G&&(0,$.jsxs)(`div`,{className:`lp-section-body sessions-scroll`,onDoubleClick:ot,onScroll:e=>{if(Se.length>=r.length)return;let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<180&&xe(e=>Math.min(r.length,e+60))},children:[r.length===0&&(0,$.jsx)(`div`,{className:`panel-empty`,children:N(`noHistory`)}),Se.map(e=>{let t=e=>(e??``).trim().replace(/[\\/]+$/,``).toLowerCase(),n=F===e.path,i=A?.kind===`session`&&t(A.target)===t(e.path);return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>se(t=>t===`sess:${e.path}`?null:t),onContextMenu:t=>Me(t,{id:e.path,kind:`history`,label:Je(e)}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item ${n?`active`:``} ${i?`switching`:``}`,title:e.path,disabled:i,onClick:()=>{de||i||n||c({type:`switch_session`,path:e.path})},children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:i?(0,$.jsx)($o,{className:`session-icon spin`}):(0,$.jsx)(Ae,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[de===e.path?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:fe,placeholder:N(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>he(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=fe.trim();t&&c({type:`rename_session`,path:e.path,name:t}),B(null)}else t.key===`Escape`&&B(null)},onBlur:()=>B(null)}):(0,$.jsxs)(`span`,{className:`session-title`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:N(`pinnedConversation`),children:`📌`}),Je(e)]}),de===e.path?null:(0,$.jsxs)(`span`,{className:`session-sub`,children:[n?N(`current`):N(`messageCount`,{n:e.messageCount}),e.source===`tui`&&(0,$.jsx)(`span`,{className:`session-src`,title:N(`tuiTip`),children:`TUI`}),e.parentSessionPath&&(0,$.jsx)(`span`,{className:`session-src session-fork-badge`,title:N(`forkedSessionTip`,{parent:(()=>{let n=t(e.parentSessionPath).replace(/\\/g,`/`),i=r.find(e=>t(e.path).replace(/\\/g,`/`)===n);return i?Je(i):(e.parentSessionPath.replace(/\\/g,`/`).split(`/`).pop()??e.parentSessionPath).replace(/\.jsonl$/i,``)})()}),children:N(`forkedSessionBadge`)})]})]}),(0,$.jsx)(`span`,{className:`session-time ${i?`switching-pct`:``}`,children:i?`${A.progress}%`:Lh(e.modified)})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:N(`renameSession`),onClick:t=>{t.stopPropagation(),se(null),he(e.name??``),B(e.path)},children:(0,$.jsx)(M,{})}),Qe(`sess:${e.path}`,N(`deleteSession`),N(`deleteSessionConfirm`),()=>{Ph(e.path,L),c({type:`delete_session`,path:e.path})}),je(Ke,`lp-slot-sessions`)]},e.path)})]})]})})},ct=e=>{let t=Re.find(t=>t.key===e)?.entry;if(!t)return null;let n=ze(e);return(0,$.jsxs)(`div`,{className:`lp-section lp-section-plugin ${n?`collapsed`:``}`,style:n?void 0:{flex:`${nt(e)} 1 0px`},children:[$e(t.label,n,()=>q(e)),!n&&(0,$.jsx)(`div`,{className:`lp-section-body lp-plugin-section-body`,children:C?.(t)??null})]})},lt=e=>e===`groups`?(0,$.jsx)(Jo,{active:l,selectedRoomId:o,flex:nt(`groups`),onCollapsedChange:ve}):e===`projects`||e===`convs`||e===`sessions`?st[e]:ct(e);return(0,$.jsxs)(`aside`,{ref:Ne,className:`panel panel-left lp-panel`,children:[u&&d&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:N(`collapsePanel`),onClick:d,children:(0,$.jsx)(it,{})}),Re.map(({key:e})=>(0,$.jsxs)(Q.Fragment,{children:[lt(e),at.get(e)??null]},e)),(0,$.jsx)(ba,{open:ie,currentCwd:L,pathCompletions:f??[],workspaceRoots:I,onClose:()=>ae(!1),onSelectDirectory:e=>c({type:`set_cwd`,path:e}),onCreateProject:e=>c({type:`make_dir`,path:e,setAsCwd:!0})})]})}),eg=e=>/\.(zip|tar|tar\.gz|tgz|gz)$/i.test(e);function tg(e,t={}){let n={archive:q(`/api/file-transfer/archive`),upload:q(`/api/file-transfer/upload`)},r=new URL(Qe(`${n[e]}?${new URLSearchParams({clientId:xh(),...t})}`),window.location.href);if(r.origin!==window.location.origin||r.pathname!==new URL(n[e],window.location.href).pathname)throw Error(`File transfers must use an allowlisted same-origin endpoint`);return r}async function ng(e,t,n){let r=await fetch(tg(`archive`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-File-Operation":`1`},body:JSON.stringify({action:e,path:t,...n})});if(!r.ok)throw Error(await r.text());if(e===`download`){let e=r.headers.get(`content-disposition`)??``,t=/filename\*=UTF-8''([^;]+)/i.exec(e)?.[1],n=/filename="([^"]+)"/i.exec(e)?.[1],i=t?decodeURIComponent(t):n??`archive.tar.gz`,a=await Hu(await r.blob(),i);if(!a.ok&&!a.cancelled)throw Error(a.error)}}async function rg(){let e=window.showDirectoryPicker;if(!e)return null;let t=await e.call(window),n=[];async function r(e,t){if(n.length>=2e4)throw Error(`Folder exceeds 20,000 entries`);if(n.push(e.kind===`file`?{path:t,file:await e.getFile()}:{path:t}),e.kind===`directory`)for await(let n of e.values())await r(n,`${t}/${n.name}`)}return await r(t,t.name),n}async function ig(e,t,n,r=32){if(t.length>2e4)throw Error(`Folder exceeds 20,000 entries`);for(let e of t)if(e.file&&e.file.size>r*1024*1024)throw Error(`File exceeds ${r} MiB: ${e.path}`);let i=t.reduce((e,t)=>e+(t.file?.size??0),0),a=0,o=0;for(let r of t){let t=tg(`upload`,{dir:e,name:r.path,kind:r.file?`file`:`directory`}),s=r.file??new Blob;await new Promise((e,c)=>{let l=new XMLHttpRequest,u=0,d=e=>n?.({done:a,uploadedBytes:o+u,totalBytes:i,path:r.path,phase:e});l.open(`POST`,t.href),l.setRequestHeader(`Content-Type`,`application/octet-stream`),l.setRequestHeader(`X-File-Operation`,`1`),l.upload.onprogress=e=>{u=Math.min(e.loaded,s.size),d(u===s.size?`waiting`:`uploading`)},l.upload.onload=()=>{u=s.size,d(`waiting`)},l.onload=()=>{if(l.status<200||l.status>=300){c(Error(`${r.path}: ${l.responseText||`HTTP ${l.status}`}`));return}a++,o+=s.size,u=0,d(`confirmed`),e()},l.onerror=()=>c(Error(`${r.path}: Network error`)),l.onabort=()=>c(Error(`${r.path}: Upload aborted`)),l.ontimeout=()=>c(Error(`${r.path}: Upload timed out`)),d(s.size===0?`waiting`:`uploading`),l.send(s)})}}function ag({request:e,onClose:t,onComplete:n}){let r=V(),i=en(`folderUploadMaxMb`),[a,o]=(0,Q.useState)(e.dir),[s,c]=(0,Q.useState)(`skip`),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{v.current?.showModal()},[]);let y=r(e.action===`upload`?`fileUploadFolder`:e.action===`extract`?`fileExtract`:e.action===`download`?`fileCompressDownload`:`fileCompress`);async function b(){try{let e=await rg();e?(u(e),f(null)):p.current?.click()}catch(e){e instanceof DOMException&&e.name===`AbortError`||_(String(e))}}async function x(){f(null),h(!0),_(``);try{e.action===`upload`?await ig(e.dir,l,f,i):await ng(e.action,e.path,{destination:a,policy:s}),n(),t()}catch(e){_(e instanceof Error?e.message:String(e)),n()}finally{h(!1)}}return(0,bn.createPortal)((0,$.jsx)(`dialog`,{ref:v,className:`file-transfer-dialog`,"aria-labelledby":`file-transfer-title`,onCancel:e=>{e.preventDefault(),m||t()},children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),x()},children:[(0,$.jsxs)(`div`,{className:`file-transfer-head`,children:[(0,$.jsx)(`h3`,{id:`file-transfer-title`,children:y}),(0,$.jsx)(`button`,{type:`button`,className:`file-transfer-close`,title:r(`close`),"aria-label":r(`close`),disabled:m,onClick:t,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`p`,{className:`file-transfer-path`,children:(e.action===`upload`?e.dir:e.path)||`.`}),(0,$.jsx)(`p`,{children:r(`fileArchiveLimits`)}),e.action===`extract`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[r(`fileExtractDestination`),(0,$.jsx)(`input`,{value:a,disabled:m,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{children:[r(`fileConflictPolicy`),(0,$.jsxs)(`select`,{value:s,disabled:m,onChange:e=>c(e.target.value),children:[(0,$.jsx)(`option`,{value:`skip`,children:r(`fileConflictSkip`)}),(0,$.jsx)(`option`,{value:`overwrite`,children:r(`fileConflictOverwrite`)}),(0,$.jsx)(`option`,{value:`error`,children:r(`fileConflictError`)})]})]})]}),e.action===`upload`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:r(`fileFolderUploadHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:()=>void b(),children:r(`fileChooseFolder`)}),(0,$.jsx)(`input`,{type:`file`,"aria-label":y,multiple:!0,hidden:!0,disabled:m,ref:e=>{p.current=e,e?.setAttribute(`webkitdirectory`,``)},onChange:e=>{u(Array.from(e.target.files??[],e=>({path:e.webkitRelativePath||e.name,file:e}))),f(null)}}),(0,$.jsxs)(`p`,{"aria-live":`polite`,children:[d?.done??0,` / `,l.length]}),d&&(0,$.jsxs)($.Fragment,{children:[d.totalBytes>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`progress`,{"aria-label":y,value:d.uploadedBytes,max:d.totalBytes}),(0,$.jsxs)(`p`,{children:[d.uploadedBytes.toLocaleString(),` / `,d.totalBytes.toLocaleString(),` B`]})]}),m&&d.phase!==`confirmed`&&(0,$.jsx)(`p`,{className:`file-transfer-path`,role:`status`,children:d.phase===`waiting`?r(`folderUploadWaiting`,{name:d.path}):r(`folderUploadSending`,{name:d.path,percent:Math.floor(d.uploadedBytes/d.totalBytes*100)})})]})]}),g&&(0,$.jsx)(`p`,{role:`alert`,children:r(`fileTransferFailed`,{error:g})}),(0,$.jsxs)(`div`,{className:`file-transfer-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:t,children:r(`cancel`)}),(0,$.jsx)(`button`,{type:`submit`,className:`btn primary`,disabled:m||e.action===`upload`&&l.length===0,children:m?r(`fileTransferBusy`):y})]})]})}),document.body)}function og(e){return e.startsWith(`.`)&&e!==`..`}function sg(e,t){return t?e:e.filter(e=>!og(e.name))}function cg(e){return e instanceof Error?e.message:String(e)}function lg(e,t,n,r){let i=H(n);switch(e.kind){case`no-client`:return i?`插件 ${t} 没有客户端脚本(client/entry.mjs),无法显示这一页。`:`Plugin ${t} ships no client bundle (client/entry.mjs), so this page cannot be shown.`;case`load`:return i?`插件 ${t} 的页面脚本加载失败:${e.detail}`:`Failed to load plugin ${t}'s page bundle: ${e.detail}`;case`mount`:return`${r(`pluginMountFailed`,{name:t})}:${e.detail}`}}function ug({plugin:e,epoch:t,send:n,className:r}){let i=(0,Q.useRef)(null),{locale:a}=Ue(),o=V(),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{l.current=n},[n]),(0,Q.useEffect)(()=>{let n=i.current;if(!n)return;let r=!1,a,o=!1;if(c(null),!e.hasClient){c({kind:`no-client`});return}return(async()=>{try{if(await Fm(e,t),r)return;let i=await Lt(e.id,()=>As(()=>import(Am(e.id,t)),[],import.meta.url));if(r)return;let s=i.default;if(!s||typeof s.mount!=`function`)throw Error(`client/entry.mjs 没有导出 default.mount()`);o=!0;let c=!!(e.isolated||s.isolated||s.shadow),{container:u}=pm(n,{isolated:c});a=s.mount(u,Lm(e.id,e=>l.current(e)))}catch(t){if(r)return;console.error(`[plugin:${e.id}] 页面${o?`挂载`:`加载`}失败:`,t),c({kind:o?`mount`:`load`,detail:cg(t)})}})(),()=>{if(r=!0,typeof a==`function`)try{a()}catch(t){console.error(`[plugin:${e.id}] cleanup 失败:`,t)}n.replaceChildren()}},[e.id,e.hasClient,t]);let u=r?`plugin-page ${r}`:`plugin-page`;return(0,$.jsxs)(`div`,{className:u,children:[(0,$.jsx)(`div`,{className:`plugin-page-host`,ref:i}),s&&(0,$.jsx)(`div`,{className:`plugin-page-error`,role:`alert`,children:lg(s,e.name,a,o)})]})}function dg(e){return`pi-web-ui:${e}:tab`}function fg(e,t){try{let n=localStorage.getItem(dg(e));return n&&t.some(e=>e.id===n)?n:null}catch{return null}}function pg(e,t){try{localStorage.setItem(dg(e),t)}catch{}}function mg(e){return e.length>0&&!/[a-z]/i.test(e)}function hg(e){if(e.label)return e.label;let t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function gg({storageKey:e,tabs:t,epoch:n,send:r,extra:i,className:a}){let o=(0,Q.useId)(),[s,c]=(0,Q.useState)(()=>fg(e,t)??t[0]?.id??``),l=(0,Q.useRef)([]),u=(0,Q.useRef)(``),d=t.findIndex(e=>e.id===s),f=d>=0?t[d]:t[0],p=f?t.indexOf(f):-1;(0,Q.useEffect)(()=>{if(!f)return;s!==f.id&&c(f.id);let t=`${e}:${f.id}`;u.current!==t&&(u.current=t,pg(e,f.id))},[f,s,e]);let m=t=>{c(t.id),u.current=`${e}:${t.id}`,pg(e,t.id)},h=(e,n)=>{let r=t.length,i=-1;if(e.key===`ArrowRight`)i=(n+1)%r;else if(e.key===`ArrowLeft`)i=(n-1+r)%r;else if(e.key===`Home`)i=0;else if(e.key===`End`)i=r-1;else return;let a=t[i];a&&(e.preventDefault(),m(a),l.current[i]?.focus())};if(!f)return null;let g=`${o}-panel-${p}`,_=a?`slot-tabs ${a}`:`slot-tabs`;return(0,$.jsxs)(`div`,{className:_,children:[(0,$.jsxs)(`div`,{className:`slot-tabs-bar`,role:`tablist`,children:[t.map((e,t)=>{let n=t===p;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${o}-tab-${t}`,className:n?`slot-tab active`:`slot-tab`,title:e.hint??hg(e),"aria-selected":n,"aria-controls":`${o}-panel-${t}`,tabIndex:n?0:-1,ref:e=>{l.current[t]=e},onClick:()=>m(e),onKeyDown:e=>h(e,t),children:[e.iconSvg?(0,$.jsx)(Ir,{iconSvg:e.iconSvg,className:`slot-tab-icon`}):e.icon&&mg(e.icon)?(0,$.jsx)(`span`,{className:`slot-tab-icon`,children:e.icon}):null,(0,$.jsx)(`span`,{className:`slot-tab-label`,children:hg(e)})]},e.id)}),i?(0,$.jsx)(`div`,{className:`slot-tabs-extra`,children:i}):null]}),(0,$.jsx)(`div`,{className:`slot-tabs-body`,id:g,role:`tabpanel`,"aria-labelledby":`${o}-tab-${p}`,children:f.pluginPage?(0,$.jsx)(ug,{plugin:f.pluginPage.plugin,epoch:n,send:r}):f.element??null})]})}var _g=`@root`,vg=`pi-web-ui:rp-sizes`,yg=`pi-web-ui:files-show-hidden`,bg={files:4,widgets:1},xg=120,Sg=56;function Cg(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}var wg=`files`,Tg=[],Eg=()=>{};function Dg(e){let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n<0?``:n===0?`/`:t.slice(0,n)}function Og(e){return e===_g||e===`/`||/^[A-Za-z]:$/.test(e)}function kg(e){return e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)}var Ag=(0,Q.memo)(function({files:e,fileChanged:n,widgets:r,panelSend:i,onAttach:a,onPreview:o,onNotice:s,collapsible:c,onToggleCollapse:l,uiRightPanelTabs:u,uiContextFile:d,plugins:f,pluginsEpoch:p,send:m}){let g=V(),_=f??Tg,v=en(`cwd`),y=en(`workspaceRoots`),b=en(`homeDir`),x=en(`desktopDir`),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(null),A=(0,Q.useRef)(null),[j,M]=(0,Q.useState)(()=>{try{return Yo(localStorage.getItem(vg),bg)}catch{return{...bg}}});(0,Q.useEffect)(()=>{try{localStorage.setItem(vg,JSON.stringify(j))}catch{}},[j]);let[N,ee]=(0,Q.useState)(()=>{try{return localStorage.getItem(yg)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{localStorage.setItem(yg,N?`1`:`0`)}catch{}},[N]);let te=r.some(e=>e.lines.length>0),ne=(0,Q.useCallback)(e=>{e.preventDefault();let t=k.current;if(!t)return;let n=e.currentTarget,r=e.clientY,i={above:j.files,below:j.widgets},a=Math.max(120,t.clientHeight-Cg(t,A.current));n.classList.add(`dragging`),document.body.classList.add(`rp-resizing`);let o=e=>{let{above:t,below:n}=Xo({start:i,deltaPx:e.clientY-r,availablePx:a,totalWeight:i.above+i.below,minAbovePx:xg,minBelowPx:Sg});M({files:t,widgets:n})},s=()=>{window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),n.classList.remove(`dragging`),document.body.classList.remove(`rp-resizing`)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},[j.files,j.widgets]),re=(0,Q.useRef)(null),L=(0,Q.useRef)(0),ae=(0,Q.useCallback)(e=>{re.current=e,e&&(e.scrollTop=L.current)},[]),[oe,se]=(0,Q.useState)(null),ce=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current)},[]);let le=(0,Q.useCallback)(e=>{se(e),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>se(null),1200)},[]),ue=(0,Q.useCallback)((e,t)=>{e&&ic(e).then(e=>{e?le(t):s(`error`,g(`slashCopyFailed`))})},[le,s,g]),de=(0,Q.useCallback)(e=>{if(!e)return v;if(/^[A-Za-z]:$/.test(e))return`${e}/`;if(e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e))return e;let t=v.replace(/\\/g,`/`).replace(/\/+$/,``);return t?`${t}/${e}`:e},[v]),B=(0,Q.useCallback)(e=>{if(oa(v)){let t=sa(v),n=t?t.remotePath:`/`;if(!e)return n;if(e.startsWith(`/`))return e;let r=n.replace(/\/+$/,``)||`/`;return r===`/`?`/${e}`:`${r}/${e}`}return de(e)},[v,de]),fe=(0,Q.useCallback)(e=>!e||e===_g?null:e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)?e:`${v.replace(/\\/g,`/`).replace(/\/+$/,``)}/${e}`,[v]),pe=en(`workspaceUploadMaxMb`)*1024*1024,[me,he]=(0,Q.useState)([]),H=en(`status`);(0,Q.useEffect)(()=>{H!==`open`&&he(e=>e.some(e=>e.phase===`waiting`)?e.map(e=>e.phase===`waiting`?{...e,phase:`unknown`}:e):e)},[H]);let ge=(0,Q.useRef)(new Map);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(!t||typeof t!=`object`)return;let{uploadId:n,ok:r,error:i}=t;typeof n==`string`&&typeof r==`boolean`&&he(e=>e.map(e=>e.id===n&&(e.phase===`waiting`||e.phase===`unknown`)?{...e,phase:r?`success`:`error`,error:typeof i==`string`?i:void 0}:e))};window.addEventListener(`pi:file-upload-result`,e);let t=ge.current;return()=>{window.removeEventListener(`pi:file-upload-result`,e);for(let e of t.values())e.onload=e.onprogress=e.onerror=e.onabort=null,e.abort();t.clear()}},[]);let U=(0,Q.useCallback)((e,t)=>{for(let n of t){if(n.size>pe){s(`warning`,g(`fileTooLarge`,{name:n.name,size:pe/1024/1024}));continue}let t=crypto.randomUUID(),r=e=>he(n=>n.map(n=>n.id===t?{...n,...e}:n));he(r=>[...r,{id:t,name:n.name,dir:e,phase:`reading`,percent:0}]);let a=new FileReader;ge.current.set(t,a);let o=()=>{ge.current.delete(t),r({phase:`error`,error:g(`fileUploadReadFailed`,{name:n.name})})};a.onprogress=e=>{e.lengthComputable&&e.total>0&&r({percent:Math.min(100,Math.floor(e.loaded/e.total*100))})},a.onerror=o,a.onabort=o,a.onload=()=>{if(ge.current.delete(t),typeof a.result!=`string`||!a.result.includes(`,`)){o();return}let s=a.result.slice(a.result.indexOf(`,`)+1);r({phase:`waiting`,percent:100});try{if(i({type:`upload_file`,dirPath:e,name:n.name,data:s,uploadId:t}))return}catch{}r({phase:`error`,error:g(`fileUploadSendFailed`,{name:n.name})})};try{a.readAsDataURL(n)}catch{o()}}},[i,s,g,pe]),W=(0,Q.useRef)(null),[G,_e]=(0,Q.useState)(null),K=(0,Q.useRef)(null),q=(0,Q.useCallback)(()=>{let e=W.current?.project;e&&i({type:`set_cwd`,path:e.path})},[i]),ve=(0,Q.useCallback)(()=>{K.current&&(K.current.value=``),K.current?.click()},[]),[Y,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(null),[Se,Ce]=(0,Q.useState)(``),[we,Ee]=(0,Q.useState)(null),[De,X]=(0,Q.useState)(``),Oe=(0,Q.useCallback)((e,t)=>{Vu(e,t).then(e=>{e.ok||e.cancelled||s(`error`,g(`downloadFailed`,{error:e.error===`FILE_NOT_FOUND`?g(`fileNotFoundShort`):e.error}))})},[s,g]),ke=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Og(e.id)&&(Ee(null),Ce(e.label),xe(e.id))},[]),Ae=(0,Q.useCallback)(()=>{if(!be)return;let e=Se.trim();xe(null),e&&i({type:`file_rename`,path:be,newName:e})},[be,Se,i]),je=(0,Q.useCallback)(e=>{let t=W.current?.dir??C;xe(null),X(``),Ee({dir:t,kind:e})},[C]),Me=(0,Q.useCallback)(()=>{if(!we)return;let e=De.trim();Ee(null),e&&i({type:`file_create`,dir:we.dir,name:e,kind:we.kind})},[we,De,i]),Ne=(e,t,n,r)=>(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:e,placeholder:g(`fileNamePlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>t(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing?n():e.key===`Escape`&&r()},onBlur:r}),Pe=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Og(e.id)&&window.confirm(g(`fileDeleteConfirm`,{name:e.label}))&&(Y?.src===e.id&&ye(null),be===e.id&&xe(null),i({type:`file_delete`,path:e.id}))},[i,g,Y,be]),Fe=(0,Q.useCallback)(()=>{let e=W.current?.target;e&&e.kind!==`list`&&!Og(e.id)&&i({type:`file_copy`,src:e.id,destDir:Dg(e.id)})},[i]),Ie=(0,Q.useCallback)(e=>{let t=W.current?.target;t&&t.kind!==`list`&&!Og(t.id)&&ye({src:t.id,cut:e})},[]),Le=(0,Q.useCallback)(()=>{if(!Y)return;let e=W.current?.dir??C;Y.cut?(i({type:`file_copy`,src:Y.src,destDir:e,move:!0}),ye(null)):i({type:`file_copy`,src:Y.src,destDir:e})},[Y,i,C]),Re=(0,Q.useCallback)(()=>{i({type:`list_files`,path:C===``?void 0:C})},[i,C]),[ze,Ve]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!ze)return;let e=e=>{e.target?.closest(`.root-picker`)||Ve(!1)},t=e=>{e.key===`Escape`&&Ve(!1)};return window.addEventListener(`mousedown`,e,!0),window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`mousedown`,e,!0),window.removeEventListener(`keydown`,t)}},[ze]);let He=(0,Q.useCallback)(e=>{i({type:`set_workspace_roots`,roots:e})},[i]),Ue=(0,Q.useCallback)(()=>{let e=W.current?.target;if(!e||e.kind!==`dir`)return;let t=fe(e.id);t&&!y.includes(t)&&He([...y,t])},[y,fe,He]),We=(0,Q.useCallback)(e=>{U(W.current?.dir??C,Array.from(e.target.files??[]))},[U,C]),Ge=(0,Q.useCallback)(e=>{let t=W.current?.target;switch(e.id){case`host:file-compress`:case`host:file-extract`:case`host:file-compress-download`:case`host:file-upload-folder`:{if(!t)break;let n=e.id===`host:file-compress`?`compress`:e.id===`host:file-extract`?`extract`:e.id===`host:file-compress-download`?`download`:`upload`;_e({action:n,path:B(t.id),dir:B(n===`upload`?W.current?.dir??C:Dg(t.id))});break}case`host:file-open-project`:q();break;case`host:file-upload`:ve();break;case`host:file-add-root`:Ue();break;case`host:file-open`:t?.kind===`file`&&o(t.id,t.label);break;case`host:file-enter`:t?.kind===`dir`&&it(t.id);break;case`host:file-download`:t?.kind===`file`&&Oe(t.id,t.label);break;case`host:file-reveal`:t&&i({type:`file_reveal`,path:t.id});break;case`host:file-open-default`:t?.kind===`file`&&i({type:`file_open_default`,path:t.id});break;case`host:file-attach-ref`:t?.kind===`file`&&a(t.id,t.label,`reference`);break;case`host:file-attach-folder`:t?.kind===`dir`&&a(t.id,t.label,`reference`,!0);break;case`host:file-new-file`:je(`file`);break;case`host:file-new-dir`:je(`dir`);break;case`host:file-paste`:Le();break;case`host:file-rename`:ke();break;case`host:file-duplicate`:Fe();break;case`host:file-cut`:Ie(!0);break;case`host:file-copy`:Ie(!1);break;case`host:file-copy-name`:t&&t.kind!==`list`&&ue(t.label,`name:${t.id}`);break;case`host:file-copy-path`:t&&t.kind!==`list`&&ue(de(t.id),`path:${t.id}`);break;case`host:file-copy-rel`:t&&t.kind!==`list`&&ue(t.id,`rel:${t.id}`);break;case`host:file-refresh`:Re();break;case`host:file-delete`:Pe()}},[q,C,ve,Ue,o,a,ue,de,Oe,je,Le,ke,Fe,Ie,Re,Pe]),Ke=(0,Q.useCallback)((e,t)=>{let n=t.kind===`dir`?fe(t.id):null,r={target:t,dir:t.kind===`dir`?t.id:C,project:n?{path:n,name:t.label}:null},i=t.kind,a=i===`file`,o=i===`dir`,s=i===`list`,c=!s&&Og(t.id),l=!s&&kg(t.id),u=C===_g,f=(d??[]).map(e=>{if(e.source!==`host`)return e;switch(e.id){case`host:file-upload-folder`:return u?{...e,hidden:!0}:e;case`host:file-compress`:case`host:file-compress-download`:return!s&&!c?e:{...e,hidden:!0};case`host:file-extract`:return a&&eg(t.label)?e:{...e,hidden:!0};case`host:file-upload`:return u?{...e,hidden:!0}:{...e,label:r.dir===C?g(`uploadToCurrentDir`):g(`uploadToFolder`)};case`host:file-open-project`:return n?e:{...e,hidden:!0};case`host:file-add-root`:return n&&n!==v&&!y.includes(n)?e:{...e,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:case`host:file-attach-ref`:return a?e:{...e,hidden:!0};case`host:file-reveal`:return!u&&t.id!==_g?e:{...e,hidden:!0};case`host:file-enter`:case`host:file-attach-folder`:return o?e:{...e,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:return!a&&!u?e:{...e,hidden:!0};case`host:file-paste`:return!a&&!u&&Y?e:{...e,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!s&&!c?e:{...e,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:return s?{...e,hidden:!0}:e;case`host:file-copy-rel`:return!s&&!l?e:{...e,hidden:!0};case`host:file-refresh`:return s?e:{...e,hidden:!0};default:return e}});Gi(f).length!==0&&(e.preventDefault(),e.stopPropagation(),W.current=r,Pi({x:e.clientX,y:e.clientY,slot:`contextmenu.file`,target:t,entries:f,onHostAction:Ge}))},[d,C,fe,g,Ge,v,y,Y]),Je=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),Ye=(0,Q.useCallback)(()=>{re.current?.querySelectorAll(`.file-item.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),re.current?.classList.remove(`drop-root`)},[]),Ze=(0,Q.useCallback)(e=>{if(Ye(),e==null)return;let t=re.current?.querySelector(`.file-item[data-path="${CSS.escape(e)}"]`);t?t.classList.add(`drop-target`):re.current?.classList.add(`drop-root`)},[Ye]),Qe=e=>{let t=e instanceof Element?e.closest(`.file-item`):null;return t?.dataset.type===`dir`?t.dataset.path??C:C},$e=(0,Q.useCallback)(()=>{let e=document.querySelector(`.app`);e&&e.dispatchEvent(new DragEvent(`dragleave`,{bubbles:!0}))},[]),et=(0,Q.useRef)(0),tt=(0,Q.useRef)(void 0),nt=(0,Q.useCallback)((e,t)=>{let n=++et.current;w(e),t?.silent||O(!0),i({type:`list_files`,path:e===``?void 0:e})||et.current===n&&O(!1)},[i]),rt=(0,Q.useCallback)(e=>{let t=y.filter(t=>t!==e);He(t),(C===e||C.startsWith(`${e}/`))&&nt(``)},[y,He,C,nt]);(0,Q.useEffect)(()=>{e&&e.path===C&&O(!1)},[e,C]),(0,Q.useEffect)(()=>{if(v!==tt.current){let e=tt.current===void 0;tt.current=v,e?nt(``,{silent:!0}):w(``);return}let e=setInterval(()=>{document.visibilityState!==`hidden`&&nt(C,{silent:!0})},1e4);return()=>clearInterval(e)},[v,C,nt]),(0,Q.useEffect)(()=>{n&&n.path===C&&nt(C,{silent:!0})},[n,C,nt]);let it=e=>nt(e),at=()=>{e?.parent!==null&&e?.parent!==void 0&&nt(e.parent)},ot=(()=>{if(C===``||C===_g)return[];let e=C.split(`/`).filter(e=>!!e&&e!==_g);return C.startsWith(`/`)?[{label:`/`,path:`/`},...e.map((t,n)=>({label:t,path:`/`+e.slice(0,n+1).join(`/`)}))]:e.map((t,n)=>({label:e[n],path:e.slice(0,n+1).join(`/`)}))})(),ct=[];for(let e of u??[]){if(e.source===`host`||e.hidden||e.kind===`divider`)continue;let t=_.find(t=>t.id===e.source.slice(7));t&&ct.push({id:e.id,label:e.label,icon:e.icon,...e.iconSvg?{iconSvg:e.iconSvg}:{},hint:e.hint,pluginPage:{plugin:t,entry:e}})}let lt=(u??[]).some(e=>e.id===`host:right-files`&&e.hidden);return(0,$.jsxs)(`aside`,{className:`panel panel-right`,ref:k,children:[c&&l&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:g(`collapsePanel`),onClick:l,children:(0,$.jsx)(P,{})}),(0,$.jsx)(`div`,{ref:A,style:{display:`flex`,flexDirection:`column`,flex:te?`${j.files} 1 0`:`1 1 0`,minHeight:te?xg:0},children:(0,$.jsx)(gg,{storageKey:`rightpanel`,epoch:p??0,send:m??Eg,tabs:(e=>{let t=(u??[]).filter(e=>!e.hidden);if(t.length===0)return e;let n=new Map(t.map((e,t)=>[e.id,t])),r=e=>n.get(e===wg?`host:right-files`:e)??1e9;return[...e].sort((e,t)=>r(e.id)-r(t.id))})([...lt?[]:[{id:wg,label:g(`openFiles`),element:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`panel-crumbs`,children:[(0,$.jsx)(`button`,{type:`button`,className:`crumb ${C===``?`active`:``}`,onClick:()=>nt(``),children:g(`rootDir`)}),(0,$.jsx)(ta,{className:`crumb ${C===_g?`active`:``}`,tip:g(`computer`),onClick:()=>nt(_g),children:(0,$.jsx)(t,{})}),b!==``&&(0,$.jsx)(ta,{className:`crumb ${C===b||C.startsWith(`${b}/`)?`active`:``}`,tip:g(`homeDir`),onClick:()=>nt(b),children:(0,$.jsx)(Xe,{})}),x!==``&&(0,$.jsx)(ta,{className:`crumb ${C===x||C.startsWith(`${x}/`)?`active`:``}`,tip:g(`desktopDir`),onClick:()=>nt(x),children:(0,$.jsx)(st,{})}),(0,$.jsx)(ta,{className:`crumb ${N?`active`:``}`,tip:g(N?`filesHideHidden`:`filesShowHidden`),"aria-pressed":N,onClick:()=>ee(e=>!e),children:N?(0,$.jsx)(I,{}):(0,$.jsx)(h,{})}),(0,$.jsx)(ea,{text:g(`filesHelp`)}),y.length>0&&(0,$.jsxs)(`div`,{className:`root-picker`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`crumb root-picker-trigger`,"aria-haspopup":`menu`,"aria-expanded":ze,title:g(`workspaceRoots`),onClick:()=>Ve(e=>!e),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{className:`root-picker-label`,children:g(`workspaceRoots`)}),(0,$.jsx)(`span`,{className:`set-count`,children:y.length+1}),`▾`]}),ze&&(0,$.jsxs)(`div`,{className:`root-picker-menu`,role:`menu`,children:[(0,$.jsx)(`div`,{className:`root-picker-row`,children:(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:C===``?`root-picker-item active`:`root-picker-item`,title:v,onClick:()=>{Ve(!1),nt(``)},children:[g(`rootDir`),(0,$.jsx)(`span`,{className:`root-picker-path`,children:v})]})}),y.map(e=>(0,$.jsxs)(`div`,{className:`root-picker-row`,children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:C===e?`root-picker-item active`:`root-picker-item`,title:e,onClick:()=>{Ve(!1),nt(e)},children:(0,$.jsx)(`span`,{className:`root-picker-path`,children:e})}),(0,$.jsx)(`button`,{type:`button`,className:`root-picker-remove`,title:g(`removeWorkspaceRoot`),"aria-label":g(`removeWorkspaceRoot`),onClick:()=>rt(e),children:(0,$.jsx)(R,{})})]},e)),(0,$.jsx)(`div`,{className:`root-picker-hint`,children:g(`workspaceRootsHint`)})]})]}),ot.map(e=>(0,$.jsxs)(`span`,{className:`crumb-seg`,children:[(0,$.jsx)(P,{}),(0,$.jsx)(`button`,{type:`button`,className:`crumb ${e.path===C?`active`:``}`,onClick:()=>nt(e.path),children:e.label})]},e.path))]}),(0,$.jsxs)(`div`,{ref:ae,className:`panel-body`,onScroll:e=>{L.current=e.currentTarget.scrollTop},onContextMenu:e=>Ke(e,{id:C,kind:`list`,label:C===``?g(`rootDir`):C===_g?g(`computer`):C}),onDragOver:e=>{Je(e)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,$e(),Ze(Qe(e.target)))},onDragLeave:e=>{e.relatedTarget&&e.currentTarget.contains(e.relatedTarget)||Ye()},onDrop:e=>{if(Ye(),!Je(e))return;e.preventDefault(),e.stopPropagation(),$e();let t=Array.from(e.dataTransfer?.files??[]);if(t.length===0){s(`warning`,g(`foldersNotSupported`));return}U(Qe(e.target),t)},onDragEnd:Ye,children:[(0,$.jsx)(`input`,{ref:K,type:`file`,multiple:!0,hidden:!0,onChange:We}),me.length>0&&(0,$.jsx)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`4px 8px`},children:me.map(e=>{let t=e.phase===`reading`?g(`fileUploadReading`,{name:e.name,percent:e.percent}):e.phase===`waiting`?g(`fileUploadWaiting`,{name:e.name}):e.phase===`success`?g(`fileUploadConfirmed`):e.phase===`unknown`?g(`fileUploadOutcomeUnknown`):g(`fileUploadFailed`,{error:e.error||e.name});return(0,$.jsxs)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`3px 0`,fontSize:12},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,minWidth:0,maxWidth:`100%`},children:[(0,$.jsx)(`span`,{title:`${e.dir}/${e.name}`,style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,flex:1},children:e.name}),e.phase!==`reading`&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":`${g(`fileUploadDismiss`)}: ${e.name}`,title:g(`fileUploadDismiss`),onClick:()=>he(t=>t.filter(t=>t.id!==e.id)),style:{flex:`none`,padding:2},children:(0,$.jsx)(R,{"aria-hidden":`true`})})]}),e.phase===`reading`&&(0,$.jsx)(`progress`,{max:100,value:e.percent,"aria-label":g(`fileUploadReading`,{name:e.name,percent:e.percent}),style:{width:`100%`,height:4,display:`block`}}),(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,style:{overflowWrap:`anywhere`,wordBreak:`break-word`,color:e.phase===`error`?`var(--err-text)`:`var(--text-dim)`},children:t})]},e.id)})}),G&&(0,$.jsx)(ag,{request:G,onClose:()=>_e(null),onComplete:Re}),we&&(0,$.jsxs)(`div`,{className:`file-item dir`,children:[we.kind===`dir`?(0,$.jsx)(Be,{className:`file-icon`}):(0,$.jsx)(ie,{className:`file-icon`}),Ne(De,X,Me,()=>Ee(null))]}),D&&(0,$.jsx)(`div`,{className:`panel-empty`,children:g(`loading`)}),!D&&e&&e.path===C&&(0,$.jsxs)($.Fragment,{children:[e.parent!=null&&(0,$.jsxs)(`button`,{type:`button`,className:`file-item dir`,onClick:at,children:[(0,$.jsx)(Be,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:`..`})]}),sg(e.entries,N).map(e=>e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir${Y?.cut&&Y.src===e.path?` cut`:``}`,"data-type":`dir`,"data-path":e.path,onClick:t=>{be!==e.path&&(t.target.closest(`.file-attach`)||it(e.path))},onContextMenu:t=>Ke(t,{id:e.path,kind:`dir`,label:e.name}),children:[be===e.path?Ne(Se,Ce,Ae,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:t=>{t.stopPropagation(),it(e.path)},children:[(0,$.jsx)(Be,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":g(`linkFolderTip`),"aria-label":g(`linkFolderTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`,!0)},children:(0,$.jsx)(qe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":g(`copyName`),"aria-label":g(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":g(`copyPath`),"aria-label":g(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(F,{})})]},e.path):(0,$.jsxs)(`div`,{className:`file-item file${Y?.cut&&Y.src===e.path?` cut`:``}`,"data-type":`file`,"data-path":e.path,onClick:t=>{be!==e.path&&(t.target.closest(`.file-attach`)||o(e.path,e.name))},onContextMenu:t=>Ke(t,{id:e.path,kind:`file`,label:e.name}),children:[be===e.path?Ne(Se,Ce,Ae,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-name`,title:`${e.path} — ${g(`previewFile`)}`,onClick:t=>{t.stopPropagation(),o(e.path,e.name)},children:[(0,$.jsx)(ie,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name-text`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach download`,"data-tip":g(`downloadFile`),onClick:t=>{t.stopPropagation(),Oe(e.path,e.name)},children:(0,$.jsx)(S,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":g(`referenceTip`),"aria-label":g(`referenceTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`)},children:(0,$.jsx)(qe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":g(`copyName`),"aria-label":g(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":g(`copyPath`),"aria-label":g(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(F,{})})]},e.path)),e.truncated&&(0,$.jsx)(`div`,{className:`panel-empty files-truncated`,children:g(`filesTruncated`)})]}),!D&&!e&&(0,$.jsx)(`div`,{className:`panel-empty`,children:g(`noFiles`)})]})]})}],...ct])})}),te&&(0,$.jsx)(`div`,{className:`rp-sash`,onPointerDown:ne,onDoubleClick:()=>M({...bg}),title:g(`dragToResize`)}),te&&(0,$.jsx)(`div`,{className:`panel-widgets`,style:{flexGrow:j.widgets,minHeight:Sg},children:r.filter(e=>e.lines.length>0).map(e=>(0,$.jsxs)(`div`,{className:`widget`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`widget-title widget-title-btn`,title:g(`widgetExpand`),onClick:()=>E(e.key),children:[(0,$.jsx)(`span`,{children:e.key}),(0,$.jsx)(J,{})]}),(0,$.jsx)(`pre`,{className:`widget-lines`,children:e.lines.join(`
|
|
60
60
|
`)})]},e.key))}),T&&(()=>{let e=r.find(e=>e.key===T);return e?(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>E(null),children:(0,$.jsxs)(`div`,{className:`widget-expand`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`widget-expand-head`,children:[(0,$.jsx)(`span`,{className:`widget-expand-title`,children:e.key}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:g(`close`),onClick:()=>E(null),children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`pre`,{className:`widget-expand-lines`,children:e.lines.join(`
|
|
61
|
-
`)})]})}):null})()]})});function
|
|
62
|
-
`)}function
|
|
63
|
-
`)}function e_(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function t_(e,t,n,r){let i=new Map,a=n.toLowerCase();if(!a)return i;for(let n of e){if(!t.has(n.id))continue;let e=e_($g(n,r).toLowerCase(),a);e>0&&i.set(n.id,e)}return i}function n_(e,t){let n=[],r=t.toLowerCase();if(!r)return n;let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(e){let t=e.parentElement;return!t||t.closest(`.search-bar`)||t.closest(`.msg-collapsed`)?NodeFilter.FILTER_REJECT:(e.textContent??``).toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let e=i.nextNode();e;e=i.nextNode()){let t=(e.textContent??``).toLowerCase();if(!e.parentElement?.closest(`[data-msg-id]`))continue;let i=t.indexOf(r);for(;i!==-1;){let a=document.createRange();a.setStart(e,i),a.setEnd(e,i+r.length),n.push(a),i=t.indexOf(r,i+r.length)}}return n}function r_(e,t,n,r,i){let a=t_(n,r,t,i),o=new Map;for(let n of n_(e,t)){let e=n.startContainer.parentElement?.closest(`[data-msg-id]`);if(!e?.dataset.msgId)continue;let t=o.get(e.dataset.msgId);t?t.push(n):o.set(e.dataset.msgId,[n])}let s=[];for(let e of n){let t=o.get(e.id);if(t)for(let n=0;n<t.length;n++)s.push({kind:`dom`,range:t[n],msgId:e.id,k:n});let n=a.get(e.id);if(n)for(let t=0;t<n;t++)s.push({kind:`folded`,msgId:e.id,k:t})}return s}function i_(e,t){return e.findIndex(e=>e.msgId===t.msgId&&e.k===t.k)}function a_(e,t){let n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}let r=window.Highlight;r&&n.highlights.set(e,new r(...t))}function o_(e,t){let n=[],r=e;for(;r&&r!==t;){let e=getComputedStyle(r);/(auto|scroll|hidden)/.test(e.overflowY+e.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function s_(e,t){let n=t.startContainer.parentElement;for(let r of o_(n,e)){let e=t.getBoundingClientRect(),n=r.getBoundingClientRect();if(e.height<=0||e.width<=0)return;e.top>=n.top+4&&e.bottom<=n.bottom-4||(r.scrollTop+=e.top-n.top-(r.clientHeight-e.height)/2),e.left>=n.left+4&&e.right<=n.right-4||(r.scrollLeft+=e.left-n.left-(r.clientWidth-e.width)/2)}let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(r.height<=0||r.width<=0)return;let a=r.top>=i.top+6&&r.bottom<=i.bottom-6,o=r.left>=i.left+6&&r.right<=i.right-6;a&&o||(a||(e.scrollTop+=r.top-i.top-(i.height-r.height)/2),o||(e.scrollLeft+=r.left-i.left-(i.width-r.width)/2))}function c_({containerRef:e,messages:t,collapsedIds:n,toolResults:r,onExpand:i,onProgrammaticScroll:a,open:o,onClose:c}){let l=V(),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[,_]=(0,Q.useState)(0),v=(0,Q.useDeferredValue)(d),y=o?v.trim():``,b=(0,Q.useRef)(null);b.current=p;let x=(0,Q.useRef)([]),S=(0,Q.useRef)({key:null}),C=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{o&&(m(null),requestAnimationFrame(()=>u.current?.select()))},[o]),(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),c())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[o,c]),(0,Q.useEffect)(()=>(o||(a_(`msg-search`,[]),a_(`msg-search-active`,[])),()=>{a_(`msg-search`,[]),a_(`msg-search-active`,[])}),[o]),(0,Q.useLayoutEffect)(()=>{let s=()=>{g(0),m(null),_(0),x.current=[],a_(`msg-search`,[]),a_(`msg-search-active`,[]),S.current={key:null},C.current=``};if(!o||!y){s();return}let c=e.current;if(!c)return;let l=!1,u=0;return u=requestAnimationFrame(()=>{if(l)return;let e=r_(c,y,t,n,r);x.current=e;let o=e.length;if(g(o),o===0){m(null),_(0),a_(`msg-search`,[]),a_(`msg-search-active`,[]),S.current={key:null},C.current=y;return}let s=b.current,u;if(s){if(u=i_(e,s),u===-1){let t=[];for(let n=0;n<e.length;n++)e[n].msgId===s.msgId&&t.push(n);u=t.length>0?t[Math.min(s.k,t.length-1)]:0}}else u=0;u<0&&(u=0),u>=o&&(u=o-1),(!s||s.msgId!==e[u].msgId||s.k!==e[u].k)&&m({msgId:e[u].msgId,k:e[u].k}),_(u);let d=e[u],f=S.current,p=f.key?.msgId!==d.msgId||f.key?.k!==d.k||f.kind===`folded`&&d.kind===`dom`||y!==C.current;if(S.current={key:{msgId:d.msgId,k:d.k},kind:d.kind},C.current=y,a_(`msg-search`,e.filter(e=>e.kind===`dom`).map(e=>e.range)),d.kind===`folded`){a_(`msg-search-active`,[]),p&&i(d.msgId);return}a_(`msg-search-active`,[d.range]),p&&(a?.(),s_(c,d.range))}),()=>{l=!0,cancelAnimationFrame(u)}},[o,y,t,e,p,n,r,i,a]);let w=(0,Q.useCallback)(e=>{let t=x.current,n=t.length;if(n===0)return;let r=b.current,i=t[((r?i_(t,r):0)+e+n)%n];m(i.kind===`dom`||i.kind===`folded`?{msgId:i.msgId,k:i.k}:null)},[]);if(!o)return null;let T=p?(()=>{let e=i_(x.current,p);return e===-1?0:e})():0;return(0,$.jsxs)(`div`,{className:`search-bar`,role:`search`,children:[(0,$.jsx)(`input`,{ref:u,className:`search-input`,type:`text`,value:d,placeholder:l(`searchPlaceholder`),onChange:e=>{f(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w(e.shiftKey?-1:1))}}),(0,$.jsx)(`span`,{className:`search-count ${h===0?`empty`:``}`,children:h===0?l(`searchNoResults`):`${Math.min(T+1,h)}/${h}`}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchPrev`),disabled:h===0,onClick:()=>w(-1),children:(0,$.jsx)(s,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchNext`),disabled:h===0,onClick:()=>w(1),children:(0,$.jsx)(pe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchClose`),onClick:c,children:(0,$.jsx)(R,{})})]})}function l_(e){let{dSt:t,dSh:n,escaped:r,graceActive:i,stuck:a}=e;return i||t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:a&&!r}:{flipEscape:!0,reassert:!1}}function u_(e){let{decisionFlipEscape:t,hasUserUpwardIntent:n,stuck:r,escaped:i}=e;return t?n?{shouldEscape:!0,shouldReassert:!1}:{shouldEscape:!1,shouldReassert:r&&!i}:{shouldEscape:!1,shouldReassert:!1}}function d_(e){let{wasStreaming:t,isStreaming:n,escaped:r,hasJumpTarget:i}=e;return i?!1:!t&&n?!r:!1}function f_(e){let{convChanged:t,lastQuestionId:n,prevLastQuestionId:r,escaped:i,nearBottom:a=!0,hasJumpTarget:o}=e;return o?{shouldScroll:!1,reason:`none`}:t?{shouldScroll:!0,reason:`conv_changed`}:n!==null&&r!==null&&n!==r?{shouldScroll:!i&&a,reason:`question_added`}:r===null&&n!==null?{shouldScroll:!i&&a,reason:`initial_load`}:{shouldScroll:!1,reason:`none`}}function p_(e){let{scrollTop:t,scrollHeight:n,clientHeight:r,hasEarlier:i,isMovingUp:a}=e;return!i||!a?!1:t<=Math.max(r*2,n*.5,800)}function m_(e){let{messages:t,isStreaming:n,liveOutputs:r,toolStatuses:i,queue:a,conversationId:o,sessionFile:s,questions:c,jumpTarget:l,urlJumpMessageId:u,hasEarlier:d,loadEarlier:f,scheduleActiveFromScroll:p,scheduleSweep:m}=e,h=(0,Q.useRef)(null),g=e.scrollRef??h,_=(0,Q.useRef)(null),[v,y]=(0,Q.useState)(!0),b=(0,Q.useRef)(!0),x=e.stickRef??b,S=(0,Q.useRef)(!1),C=e.escapedRef??S,w=(0,Q.useRef)(0),T=(0,Q.useRef)(0),E=(0,Q.useRef)(0),D=(0,Q.useRef)(0),O=(0,Q.useRef)(!1),k=(0,Q.useRef)(!1),A=(0,Q.useRef)(0),j=(0,Q.useRef)([]),M=(0,Q.useCallback)(()=>{for(let e of j.current)clearTimeout(e);j.current=[]},[]),N=(0,Q.useCallback)(()=>{M(),C.current=!0,x.current=!1,y(!1)},[M]),P=(0,Q.useCallback)(()=>{M(),D.current=Date.now(),E.current=0,C.current=!0,x.current=!1,y(!1)},[M]),ee=(0,Q.useCallback)(()=>{let e=g.current;e&&(C.current||!x.current||Date.now()-D.current<500||(E.current=Date.now()+250,e.scrollTop=e.scrollHeight,w.current=e.scrollTop,T.current=e.scrollHeight))},[g]),F=(0,Q.useCallback)(()=>{g.current&&(M(),D.current=0,x.current=!0,C.current=!1,y(!0),ee(),requestAnimationFrame(()=>requestAnimationFrame(ee)),j.current.push(setTimeout(ee,120)),j.current.push(setTimeout(ee,300)),j.current.push(setTimeout(ee,600)))},[ee,M,g]),te=(0,Q.useRef)(d);te.current=d;let ne=(0,Q.useRef)(f);ne.current=f;let re=(0,Q.useCallback)(e=>{let t=g.current;t&&p_({scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,hasEarlier:te.current,isMovingUp:e})&&ne.current()},[g]),I=(0,Q.useCallback)(e=>{if(e.deltaY<0){let t=(e.target instanceof Element?e.target:null)?.closest(`.toolcall-output pre, .toolcall-args pre, .codemode-code`);if(t&&t.scrollHeight>t.clientHeight&&t.scrollTop>0)return;D.current=Date.now(),P(),re(!0)}else if(e.deltaY>0){D.current=0;let e=g.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))}},[P,re,g]),L=(0,Q.useCallback)(e=>{e.touches.length>0&&(A.current=e.touches[0].clientY)},[]),ie=(0,Q.useCallback)(e=>{if(e.touches.length>0){let t=e.touches[0].clientY-A.current;if(t>8)P(),re(!0);else if(t<-8){D.current=0;let e=g.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))}}},[P,re,g]),ae=(0,Q.useCallback)(e=>{if(e.button===1){D.current=Date.now(),P();return}if(e.button!==0)return;let t=e.currentTarget;e.target===t&&e.clientX>=t.getBoundingClientRect().left+t.clientWidth&&(O.current=!0)},[P]);(0,Q.useEffect)(()=>{let e=e=>{O.current=!1,(!e||e.button===1)&&(k.current=!1)},t=e=>{e.button===1&&(k.current=!0,D.current=Date.now(),P())},n=e=>{let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.key===`PageUp`||e.key===`ArrowUp`||e.key===`Home`?P():e.key===`End`&&(D.current=0))};return window.addEventListener(`pointerup`,e),window.addEventListener(`pointercancel`,e),window.addEventListener(`pointerdown`,t,{capture:!0}),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e),window.removeEventListener(`pointerdown`,t,{capture:!0}),window.removeEventListener(`keydown`,n)}},[P]);let oe=(0,Q.useCallback)(()=>{let e=g.current;if(!e)return;let t=e.scrollTop-w.current,n=e.scrollHeight-T.current;w.current=e.scrollTop,T.current=e.scrollHeight;let r=e.scrollHeight-e.scrollTop-e.clientHeight<36,i=Date.now()<E.current;k.current&&t<0&&(D.current=Date.now(),P());let a=Date.now()-D.current<800||O.current&&t<0||k.current,o=l_({dSt:t,dSh:n,escaped:C.current,graceActive:i,stuck:x.current});o.reassert&&!a&&ee();let{shouldEscape:s,shouldReassert:c}=u_({decisionFlipEscape:o.flipEscape,hasUserUpwardIntent:a,stuck:x.current,escaped:C.current});s?(C.current=!0,x.current=!1):c&&ee(),!i&&!a&&(t<0||r&&(t>0||!C.current)&&(x.current=!0,C.current=!1));let l=t<0||Date.now()-D.current<800;re(l),y(e=>e===x.current?e:x.current),p(),m()},[p,m,ee,P,re,g]),se=(0,Q.useRef)(!!n);(0,Q.useEffect)(()=>{let e=se.current;if(se.current=!!n,d_({wasStreaming:e,isStreaming:!!n,escaped:C.current,hasJumpTarget:!!(l||u)})){F();return}if(e&&!n&&!C.current){let e=()=>{g.current&&!C.current&&(x.current=!0,y(!0),ee())};requestAnimationFrame(()=>requestAnimationFrame(e))}},[n,l,u,F,ee,g]);let ce=c.length>0?c[c.length-1].id:null,R=(0,Q.useRef)(`${o??``}:${s??``}`),le=(0,Q.useRef)(ce);(0,Q.useEffect)(()=>{let e=`${o??``}:${s??``}`,t=e!==R.current,n=g.current,r=!n||n.scrollHeight-n.scrollTop-n.clientHeight<36,{shouldScroll:i}=f_({convChanged:t,lastQuestionId:ce,prevLastQuestionId:le.current,escaped:C.current,nearBottom:r,hasJumpTarget:!!(l||u)});R.current=e,le.current=ce,i&&F()},[o,s,ce,l,u,F]),(0,Q.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<36;x.current&&!C.current&&t&&ee()},[t,n,r,i,ee,g]);let ue=a?a.steering.join(`\0`)+``+a.followUp.join(`\0`):``,z=a?a.steering.length+a.followUp.length:0,de=(0,Q.useRef)(z);return(0,Q.useLayoutEffect)(()=>{let e=z>de.current;if(de.current=z,e){F();return}g.current&&x.current&&!C.current&&ee()},[ue,z,F,ee,g]),(0,Q.useEffect)(()=>{let e=g.current;if(!e||typeof ResizeObserver>`u`)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=n-t;t=n,r>0&&(e.scrollTop=Math.min(e.scrollTop,e.scrollHeight-e.clientHeight))});return n.observe(e),()=>n.disconnect()},[g]),(0,Q.useEffect)(()=>{let e=g.current;if(!e||typeof MutationObserver>`u`)return;let t=!1,n=new MutationObserver(()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1,g.current&&x.current&&!C.current&&(ee(),y(!0))}))});return n.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()},[ee,g]),(0,Q.useEffect)(()=>{let e=_.current,t=g.current;if(!e||!t)return;let n=n=>{n.preventDefault();let r=e.querySelector(`.qn-list`);if(r&&r.contains(n.target)&&r.scrollHeight>r.clientHeight){r.scrollTop+=n.deltaY;return}n.deltaY<0?P():n.deltaY>0&&(D.current=0,t.scrollHeight-t.scrollTop-t.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))),t.scrollTop+=n.deltaY};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)},[P,g]),(0,Q.useEffect)(()=>()=>M(),[M]),{scrollRef:g,railRef:_,stickBottom:v,escapedRef:C,stickRef:x,scrollToBottom:F,pinToBottom:ee,disengageStick:P,pauseForSelection:N,handleWheel:I,handleTouchStart:L,handleTouchMove:ie,handlePointerDown:ae,onScroll:oe}}function h_(e){return e.trim().replace(/^\//,``).toLowerCase()}function g_(e){return/^[a-z][a-z0-9_-]*$/.test(e)}function __(e,t){let n=new Set([`help`,`copy`,...t.map(e=>e.name.toLowerCase())]);return e.filter(e=>{let t=h_(e.command??``);return!g_(t)||n.has(t)?!1:(n.add(t),!0)})}function v_(e,t){let n=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return e;let r=t.find(e=>h_(e.command??``)===n[1].toLowerCase());if(!r)return e;let i=n[2]??``;return r.prompt.includes(`{{input}}`)?r.prompt.replaceAll(`{{input}}`,()=>i):[r.prompt,i].filter(Boolean).join(`
|
|
61
|
+
`)})]})}):null})()]})});function jg(e,t,n){let r=!1;for(let i of t){let t=i;if(t.type!==`image`||typeof t.dataUrl!=`string`||!t.dataUrl.startsWith(`data:`))continue;let a=t.dataUrl.match(/^data:([^;]*);base64,(.+)$/);a&&(r=!0,e.push({path:``,imageData:a[2],mimeType:a[1]||`image/png`,name:n??`image.${(a[1]||`image/png`).split(`/`)[1]??`png`}`}))}return r}function Mg(e){let t=e.details??{};if(t.mode===`quote`){let e=fs(t.quote);return e?{path:``,mode:`quote`,quote:e}:null}let n=[];if(jg(n,e.content,t.name))return n[0]??null;if(t.upload&&t.path)return{path:``,uploadPath:t.path,name:t.name??t.path,size:t.size};if((t.mode===`page`||t.mode===`canvas`)&&t.path)return{path:t.path,mode:t.mode,name:t.name??t.path};if(t.mode===`conversation`){let e=t,n=typeof e.conversationId==`string`&&e.conversationId?e.conversationId:void 0,r=typeof e.sessionPath==`string`&&e.sessionPath?e.sessionPath:void 0;return n||r?{path:``,mode:`conversation`,name:t.name??n??r,...n?{conversationId:n}:{},...r?{sessionPath:r}:{}}:null}if(t.path&&t.mode){let e=t.mode===`lines`?`lines`:`reference`,n={path:t.path,mode:e};return t.mode===`lines`&&typeof t.startLine==`number`&&typeof t.endLine==`number`&&(n.lines={start:t.startLine,end:t.endLine}),n}return null}function Ng(e){if(e.mode===`quote`&&e.quote)return`quote:${e.quote.messageId??``}:${e.quote.text}`;if(e.mode===`conversation`)return`conv:${e.conversationId??``}:${e.sessionPath??``}:${e.name??``}`;if(e.mode===`page`)return`page:${e.path}`;if(e.imageData)return`img:${e.name??``}:${e.imageData.length}:${e.imageData.slice(0,64)}`;if(e.uploadPath)return`upload:${e.uploadPath}`;if(e.path){let t=e.lines?`${e.lines.start}-${e.lines.end}`:``;return`path:${e.mode??`ref`}:${e.path}:${t}`}return`unknown:${JSON.stringify(e)}`}function Pg(e){let t=new Set,n=[];for(let r of e){let e=Ng(r);t.has(e)||(t.add(e),n.push(r))}return n}function Fg(e){let t=new Map;for(let n=0;n<e.length;n++){let r=e[n];if(r.role!==`user`||!r.id)continue;let i=[];jg(i,r.content);let a=r.details?.quotes;for(let e of Array.isArray(a)?a:[]){let t=fs(e);t&&i.push({path:``,mode:`quote`,quote:t})}let o=[];for(let t=n-1;t>=0&&e[t].role===`custom`&&e[t].customType===`file`;t--){let n=Mg(e[t]);n&&o.unshift(n)}i.push(...o);for(let t=n+1;t<e.length&&e[t].role===`custom`&&e[t].customType===`file`;t++){let n=Mg(e[t]);n&&i.push(n)}let s=Pg(i);s.length>0&&t.set(r.id,s)}return t}function Ig(e,t,n){let r=Math.max(0,t),i=Math.floor((r+4)/7),a=Math.min(e,i),o=Array.from({length:a},(t,r)=>{let i=Math.floor(r*e/a),o=Math.floor((r+1)*e/a)-1;return n>=i&&n<=o?n:r===a-1?o:i}),s=a>1?Math.min(27,(r-a*3)/(a-1)):0;return{indices:o,gap:s,many:e>a||a>1&&s<20}}var Lg=(0,Q.memo)(function({message:e,onExpand:t,summary:n}){let r=V(),i=Uf(),a=Rf(e),o=i.open&&i.selectedIds.includes(e.id),s=i.open&&a,c=n??``;if(!c)for(let t of e.content){let e=ap(t);if(e&&e.text.trim()){let t=Qd(e.text);c=t?`skill:${t.name}`+(t.userMessage?` · ${t.userMessage.replace(/\s+/g,` `).trim()}`:``):e.text.replace(/\s+/g,` `).trim();break}}if(!c&&e.role===`custom`&&e.customType===`file`){let t=e.details??{};c=t.name??t.path??``}c.length>90&&(c=`${c.slice(0,90)}…`);let l=0,u=0,d=0,f=0;for(let t of e.content)op(t)?l++:sp(t)?u++:lp(t)?d++:cp(t)&&f++;let p=[];return l&&p.push(`${r(`thinking`)} ${l}`),u&&p.push(`${r(`toolCalls`)} ${u}`),d&&p.push(`${r(`bashRuns`)} ${d}`),f&&p.push(`${r(`images`)} ${f}`),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`msg-collapsed${o?` msg-export-selected`:``}`,"data-msg-id":e.id,title:`${r(`expandMsg`)} · ${c||p.join(` · `)||e.role}`,onClick:()=>t(e.id),onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e.id))},children:[s&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:o,title:r(`copyImage`),"aria-label":r(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>qf(e.id)}),(0,$.jsx)(`span`,{className:`msg-collapsed-role role-${e.role}`,children:e.role===`custom`&&e.customType===`file`?r(`attachment`):Sp(e.role,r)}),(0,$.jsxs)(`span`,{className:`msg-collapsed-body`,children:[c&&(0,$.jsx)(`span`,{className:`msg-collapsed-preview`,children:c}),p.length>0&&(0,$.jsx)(`span`,{className:`msg-collapsed-chips`,children:p.map((e,t)=>(0,$.jsx)(`span`,{className:`msg-collapsed-chip`,children:e},t))})]}),e.timestamp?(0,$.jsx)(`span`,{className:`msg-collapsed-time`,children:Rg(e.timestamp)}):null,(0,$.jsx)(`span`,{className:`msg-collapsed-action`,children:r(`expandMsg`)})]})});function Rg(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}var zg=`[goal-review]`;function Bg(e){for(let t of e.content??[]){let e=ap(t);if(e&&e.text.trim())return e.text}return``}function Vg(e){if(e.role!==`assistant`)return;let t=Bg(e).trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&(e.verdict===`pass`||e.verdict===`fail`))return e.verdict}catch{}let n=t.match(/^\{\s*"verdict"\s*:\s*"(pass|fail)"[^}]*\}$/);return n?n[1]:void 0}function Hg(e){if(e.role===`user`&&Bg(e).includes(zg))return{kind:`prompt`};let t=Vg(e);if(t)return{kind:`verdict`,verdict:t}}var Ug=`--flow-inline-stream`;function Wg(){if(typeof window>`u`||typeof document>`u`)return!1;let e=getComputedStyle(document.documentElement).getPropertyValue(Ug).trim();return e===`1`||e===`true`}function Gg(){let[e,t]=(0,Q.useState)(Wg);return(0,Q.useEffect)(()=>{let e=()=>t(Wg());return e(),window.addEventListener(xt,e),()=>window.removeEventListener(xt,e)},[]),e}var Kg=(0,Q.memo)(function({id:e,show:t,height:n,containerRef:r,onMeasured:i,lazyRef:a,children:o}){let s=(0,Q.useRef)(null);return(0,Q.useLayoutEffect)(()=>{if(!t)return;let n=s.current;if(!n)return;let r=n.offsetHeight;r>0&&i?.(e,r)},[t,e,i]),t?(0,$.jsx)(`div`,{ref:a,"data-lazy-id":e,children:(0,$.jsx)(`div`,{ref:s,children:o})}):(0,$.jsx)(`div`,{ref:a,className:`msg-lazy-ph`,"data-msg-id":e,"data-lazy-id":e,style:{height:n},"aria-hidden":`true`})});function qg(e,t,n,r,i){let a=i??t,o=[],s=[],c=0;for(let i of e)n.has(i.id)||(r.has(i.id)?i.top<t.bottom&&i.bottom>t.top&&o.push(i.id):i.top<a.bottom&&i.bottom>a.top||(s.push(i.id),i.bottom<=a.top&&(c+=i.bottom-i.top)));return{show:o,hide:s,shrinkAbove:c}}function Jg(e,t){if(t.show.length===0&&t.hide.length===0)return e;let n=new Set(e);for(let e of t.show)n.delete(e);for(let e of t.hide)n.add(e);return n}function Yg(e,t,n){let r=new Set,i=0;for(let a=e.length-1;a>=0&&!(a<e.length-1&&i>=n);a--){let n=e[a];r.add(n.id),i+=t.get(n.id)??Xg(n.role,n.customType)}return r}function Xg(e,t){switch(e){case`user`:return 72;case`assistant`:return 280;case`toolResult`:return 8;case`custom`:return t===`file`?96:72;default:return 60}}var Zg=[`text`,`thinking`,`argumentsText`,`output`,`command`];function Qg(e){let t=0;for(let n of e.content){n.type===`image`&&(t+=1);for(let e of Zg){let r=n[e];typeof r==`string`&&(t+=r.length)}}return t}function $g(e,t,n,r){let i=n.get(e);return i&&i.len===t?i.h:r}function e_(e){let t=[];for(let n of e.content)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
|
|
62
|
+
`)}function t_(e,t){let n=[];for(let r of e.content)if(r.type===`text`&&typeof r.text==`string`)n.push(r.text);else if(r.type===`thinking`&&typeof r.thinking==`string`)n.push(r.thinking);else if(r.type===`toolCall`){if(typeof r.name==`string`&&n.push(r.name),typeof r.argumentsText==`string`&&n.push(r.argumentsText),typeof r.id==`string`){let e=t.get(r.id);if(e){let t=e_(e);t&&n.push(t)}}}else r.type===`bash`&&(typeof r.command==`string`&&n.push(r.command),typeof r.output==`string`&&n.push(r.output));return n.join(`
|
|
63
|
+
`)}function n_(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function r_(e,t,n,r){let i=new Map,a=n.toLowerCase();if(!a)return i;for(let n of e){if(!t.has(n.id))continue;let e=n_(t_(n,r).toLowerCase(),a);e>0&&i.set(n.id,e)}return i}function i_(e,t){let n=[],r=t.toLowerCase();if(!r)return n;let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(e){let t=e.parentElement;return!t||t.closest(`.search-bar`)||t.closest(`.msg-collapsed`)?NodeFilter.FILTER_REJECT:(e.textContent??``).toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let e=i.nextNode();e;e=i.nextNode()){let t=(e.textContent??``).toLowerCase();if(!e.parentElement?.closest(`[data-msg-id]`))continue;let i=t.indexOf(r);for(;i!==-1;){let a=document.createRange();a.setStart(e,i),a.setEnd(e,i+r.length),n.push(a),i=t.indexOf(r,i+r.length)}}return n}function a_(e,t,n,r,i){let a=r_(n,r,t,i),o=new Map;for(let n of i_(e,t)){let e=n.startContainer.parentElement?.closest(`[data-msg-id]`);if(!e?.dataset.msgId)continue;let t=o.get(e.dataset.msgId);t?t.push(n):o.set(e.dataset.msgId,[n])}let s=[];for(let e of n){let t=o.get(e.id);if(t)for(let n=0;n<t.length;n++)s.push({kind:`dom`,range:t[n],msgId:e.id,k:n});let n=a.get(e.id);if(n)for(let t=0;t<n;t++)s.push({kind:`folded`,msgId:e.id,k:t})}return s}function o_(e,t){return e.findIndex(e=>e.msgId===t.msgId&&e.k===t.k)}function s_(e,t){let n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}let r=window.Highlight;r&&n.highlights.set(e,new r(...t))}function c_(e,t){let n=[],r=e;for(;r&&r!==t;){let e=getComputedStyle(r);/(auto|scroll|hidden)/.test(e.overflowY+e.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function l_(e,t){let n=t.startContainer.parentElement;for(let r of c_(n,e)){let e=t.getBoundingClientRect(),n=r.getBoundingClientRect();if(e.height<=0||e.width<=0)return;e.top>=n.top+4&&e.bottom<=n.bottom-4||(r.scrollTop+=e.top-n.top-(r.clientHeight-e.height)/2),e.left>=n.left+4&&e.right<=n.right-4||(r.scrollLeft+=e.left-n.left-(r.clientWidth-e.width)/2)}let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(r.height<=0||r.width<=0)return;let a=r.top>=i.top+6&&r.bottom<=i.bottom-6,o=r.left>=i.left+6&&r.right<=i.right-6;a&&o||(a||(e.scrollTop+=r.top-i.top-(i.height-r.height)/2),o||(e.scrollLeft+=r.left-i.left-(i.width-r.width)/2))}function u_({containerRef:e,messages:t,collapsedIds:n,toolResults:r,onExpand:i,onProgrammaticScroll:a,open:o,onClose:c}){let l=V(),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[,_]=(0,Q.useState)(0),v=(0,Q.useDeferredValue)(d),y=o?v.trim():``,b=(0,Q.useRef)(null);b.current=p;let x=(0,Q.useRef)([]),S=(0,Q.useRef)({key:null}),C=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{o&&(m(null),requestAnimationFrame(()=>u.current?.select()))},[o]),(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),c())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[o,c]),(0,Q.useEffect)(()=>(o||(s_(`msg-search`,[]),s_(`msg-search-active`,[])),()=>{s_(`msg-search`,[]),s_(`msg-search-active`,[])}),[o]),(0,Q.useLayoutEffect)(()=>{let s=()=>{g(0),m(null),_(0),x.current=[],s_(`msg-search`,[]),s_(`msg-search-active`,[]),S.current={key:null},C.current=``};if(!o||!y){s();return}let c=e.current;if(!c)return;let l=!1,u=0;return u=requestAnimationFrame(()=>{if(l)return;let e=a_(c,y,t,n,r);x.current=e;let o=e.length;if(g(o),o===0){m(null),_(0),s_(`msg-search`,[]),s_(`msg-search-active`,[]),S.current={key:null},C.current=y;return}let s=b.current,u;if(s){if(u=o_(e,s),u===-1){let t=[];for(let n=0;n<e.length;n++)e[n].msgId===s.msgId&&t.push(n);u=t.length>0?t[Math.min(s.k,t.length-1)]:0}}else u=0;u<0&&(u=0),u>=o&&(u=o-1),(!s||s.msgId!==e[u].msgId||s.k!==e[u].k)&&m({msgId:e[u].msgId,k:e[u].k}),_(u);let d=e[u],f=S.current,p=f.key?.msgId!==d.msgId||f.key?.k!==d.k||f.kind===`folded`&&d.kind===`dom`||y!==C.current;if(S.current={key:{msgId:d.msgId,k:d.k},kind:d.kind},C.current=y,s_(`msg-search`,e.filter(e=>e.kind===`dom`).map(e=>e.range)),d.kind===`folded`){s_(`msg-search-active`,[]),p&&i(d.msgId);return}s_(`msg-search-active`,[d.range]),p&&(a?.(),l_(c,d.range))}),()=>{l=!0,cancelAnimationFrame(u)}},[o,y,t,e,p,n,r,i,a]);let w=(0,Q.useCallback)(e=>{let t=x.current,n=t.length;if(n===0)return;let r=b.current,i=t[((r?o_(t,r):0)+e+n)%n];m(i.kind===`dom`||i.kind===`folded`?{msgId:i.msgId,k:i.k}:null)},[]);if(!o)return null;let T=p?(()=>{let e=o_(x.current,p);return e===-1?0:e})():0;return(0,$.jsxs)(`div`,{className:`search-bar`,role:`search`,children:[(0,$.jsx)(`input`,{ref:u,className:`search-input`,type:`text`,value:d,placeholder:l(`searchPlaceholder`),onChange:e=>{f(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w(e.shiftKey?-1:1))}}),(0,$.jsx)(`span`,{className:`search-count ${h===0?`empty`:``}`,children:h===0?l(`searchNoResults`):`${Math.min(T+1,h)}/${h}`}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchPrev`),disabled:h===0,onClick:()=>w(-1),children:(0,$.jsx)(s,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchNext`),disabled:h===0,onClick:()=>w(1),children:(0,$.jsx)(pe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchClose`),onClick:c,children:(0,$.jsx)(R,{})})]})}function d_(e){let{dSt:t,dSh:n,escaped:r,graceActive:i,stuck:a}=e;return i||t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:a&&!r}:{flipEscape:!0,reassert:!1}}function f_(e){let{decisionFlipEscape:t,hasUserUpwardIntent:n,stuck:r,escaped:i}=e;return t?n?{shouldEscape:!0,shouldReassert:!1}:{shouldEscape:!1,shouldReassert:r&&!i}:{shouldEscape:!1,shouldReassert:!1}}function p_(e){let{wasStreaming:t,isStreaming:n,escaped:r,hasJumpTarget:i}=e;return i?!1:!t&&n?!r:!1}function m_(e){let{convChanged:t,lastQuestionId:n,prevLastQuestionId:r,escaped:i,nearBottom:a=!0,hasJumpTarget:o}=e;return o?{shouldScroll:!1,reason:`none`}:t?{shouldScroll:!0,reason:`conv_changed`}:n!==null&&r!==null&&n!==r?{shouldScroll:!i&&a,reason:`question_added`}:r===null&&n!==null?{shouldScroll:!i&&a,reason:`initial_load`}:{shouldScroll:!1,reason:`none`}}function h_(e){let{scrollTop:t,scrollHeight:n,clientHeight:r,hasEarlier:i,isMovingUp:a}=e;return!i||!a?!1:t<=Math.max(r*2,n*.5,800)}function g_(e){let{messages:t,isStreaming:n,liveOutputs:r,toolStatuses:i,queue:a,conversationId:o,sessionFile:s,questions:c,jumpTarget:l,urlJumpMessageId:u,hasEarlier:d,loadEarlier:f,scheduleActiveFromScroll:p,scheduleSweep:m}=e,h=(0,Q.useRef)(null),g=e.scrollRef??h,_=(0,Q.useRef)(null),[v,y]=(0,Q.useState)(!0),b=(0,Q.useRef)(!0),x=e.stickRef??b,S=(0,Q.useRef)(!1),C=e.escapedRef??S,w=(0,Q.useRef)(0),T=(0,Q.useRef)(0),E=(0,Q.useRef)(0),D=(0,Q.useRef)(0),O=(0,Q.useRef)(!1),k=(0,Q.useRef)(!1),A=(0,Q.useRef)(0),j=(0,Q.useRef)([]),M=(0,Q.useCallback)(()=>{for(let e of j.current)clearTimeout(e);j.current=[]},[]),N=(0,Q.useCallback)(()=>{M(),C.current=!0,x.current=!1,y(!1)},[M]),P=(0,Q.useCallback)(()=>{M(),D.current=Date.now(),E.current=0,C.current=!0,x.current=!1,y(!1)},[M]),ee=(0,Q.useCallback)(()=>{let e=g.current;e&&(C.current||!x.current||Date.now()-D.current<500||(E.current=Date.now()+250,e.scrollTop=e.scrollHeight,w.current=e.scrollTop,T.current=e.scrollHeight))},[g]),F=(0,Q.useCallback)(()=>{g.current&&(M(),D.current=0,x.current=!0,C.current=!1,y(!0),ee(),requestAnimationFrame(()=>requestAnimationFrame(ee)),j.current.push(setTimeout(ee,120)),j.current.push(setTimeout(ee,300)),j.current.push(setTimeout(ee,600)))},[ee,M,g]),te=(0,Q.useRef)(d);te.current=d;let ne=(0,Q.useRef)(f);ne.current=f;let re=(0,Q.useCallback)(e=>{let t=g.current;t&&h_({scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,hasEarlier:te.current,isMovingUp:e})&&ne.current()},[g]),I=(0,Q.useCallback)(e=>{if(e.deltaY<0){let t=(e.target instanceof Element?e.target:null)?.closest(`.toolcall-output pre, .toolcall-args pre, .codemode-code`);if(t&&t.scrollHeight>t.clientHeight&&t.scrollTop>0)return;D.current=Date.now(),P(),re(!0)}else if(e.deltaY>0){D.current=0;let e=g.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))}},[P,re,g]),L=(0,Q.useCallback)(e=>{e.touches.length>0&&(A.current=e.touches[0].clientY)},[]),ie=(0,Q.useCallback)(e=>{if(e.touches.length>0){let t=e.touches[0].clientY-A.current;if(t>8)P(),re(!0);else if(t<-8){D.current=0;let e=g.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))}}},[P,re,g]),ae=(0,Q.useCallback)(e=>{if(e.button===1){D.current=Date.now(),P();return}if(e.button!==0)return;let t=e.currentTarget;e.target===t&&e.clientX>=t.getBoundingClientRect().left+t.clientWidth&&(O.current=!0)},[P]);(0,Q.useEffect)(()=>{let e=e=>{O.current=!1,(!e||e.button===1)&&(k.current=!1)},t=e=>{e.button===1&&(k.current=!0,D.current=Date.now(),P())},n=e=>{let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.key===`PageUp`||e.key===`ArrowUp`||e.key===`Home`?P():e.key===`End`&&(D.current=0))};return window.addEventListener(`pointerup`,e),window.addEventListener(`pointercancel`,e),window.addEventListener(`pointerdown`,t,{capture:!0}),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e),window.removeEventListener(`pointerdown`,t,{capture:!0}),window.removeEventListener(`keydown`,n)}},[P]);let oe=(0,Q.useCallback)(()=>{let e=g.current;if(!e)return;let t=e.scrollTop-w.current,n=e.scrollHeight-T.current;w.current=e.scrollTop,T.current=e.scrollHeight;let r=e.scrollHeight-e.scrollTop-e.clientHeight<36,i=Date.now()<E.current;k.current&&t<0&&(D.current=Date.now(),P());let a=Date.now()-D.current<800||O.current&&t<0||k.current,o=d_({dSt:t,dSh:n,escaped:C.current,graceActive:i,stuck:x.current});o.reassert&&!a&&ee();let{shouldEscape:s,shouldReassert:c}=f_({decisionFlipEscape:o.flipEscape,hasUserUpwardIntent:a,stuck:x.current,escaped:C.current});s?(C.current=!0,x.current=!1):c&&ee(),!i&&!a&&(t<0||r&&(t>0||!C.current)&&(x.current=!0,C.current=!1));let l=t<0||Date.now()-D.current<800;re(l),y(e=>e===x.current?e:x.current),p(),m()},[p,m,ee,P,re,g]),se=(0,Q.useRef)(!!n);(0,Q.useEffect)(()=>{let e=se.current;if(se.current=!!n,p_({wasStreaming:e,isStreaming:!!n,escaped:C.current,hasJumpTarget:!!(l||u)})){F();return}if(e&&!n&&!C.current){let e=()=>{g.current&&!C.current&&(x.current=!0,y(!0),ee())};requestAnimationFrame(()=>requestAnimationFrame(e))}},[n,l,u,F,ee,g]);let ce=c.length>0?c[c.length-1].id:null,R=(0,Q.useRef)(`${o??``}:${s??``}`),le=(0,Q.useRef)(ce);(0,Q.useEffect)(()=>{let e=`${o??``}:${s??``}`,t=e!==R.current,n=g.current,r=!n||n.scrollHeight-n.scrollTop-n.clientHeight<36,{shouldScroll:i}=m_({convChanged:t,lastQuestionId:ce,prevLastQuestionId:le.current,escaped:C.current,nearBottom:r,hasJumpTarget:!!(l||u)});R.current=e,le.current=ce,i&&F()},[o,s,ce,l,u,F]),(0,Q.useLayoutEffect)(()=>{let e=g.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<36;x.current&&!C.current&&t&&ee()},[t,n,r,i,ee,g]);let ue=a?a.steering.join(`\0`)+``+a.followUp.join(`\0`):``,z=a?a.steering.length+a.followUp.length:0,de=(0,Q.useRef)(z);return(0,Q.useLayoutEffect)(()=>{let e=z>de.current;if(de.current=z,e){F();return}g.current&&x.current&&!C.current&&ee()},[ue,z,F,ee,g]),(0,Q.useEffect)(()=>{let e=g.current;if(!e||typeof ResizeObserver>`u`)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=n-t;t=n,r>0&&(e.scrollTop=Math.min(e.scrollTop,e.scrollHeight-e.clientHeight))});return n.observe(e),()=>n.disconnect()},[g]),(0,Q.useEffect)(()=>{let e=g.current;if(!e||typeof MutationObserver>`u`)return;let t=!1,n=new MutationObserver(()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1,g.current&&x.current&&!C.current&&(ee(),y(!0))}))});return n.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()},[ee,g]),(0,Q.useEffect)(()=>{let e=_.current,t=g.current;if(!e||!t)return;let n=n=>{n.preventDefault();let r=e.querySelector(`.qn-list`);if(r&&r.contains(n.target)&&r.scrollHeight>r.clientHeight){r.scrollTop+=n.deltaY;return}n.deltaY<0?P():n.deltaY>0&&(D.current=0,t.scrollHeight-t.scrollTop-t.clientHeight<96&&(C.current=!1,x.current=!0,y(!0))),t.scrollTop+=n.deltaY};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)},[P,g]),(0,Q.useEffect)(()=>()=>M(),[M]),{scrollRef:g,railRef:_,stickBottom:v,escapedRef:C,stickRef:x,scrollToBottom:F,pinToBottom:ee,disengageStick:P,pauseForSelection:N,handleWheel:I,handleTouchStart:L,handleTouchMove:ie,handlePointerDown:ae,onScroll:oe}}function __(e){return e.trim().replace(/^\//,``).toLowerCase()}function v_(e){return/^[a-z][a-z0-9_-]*$/.test(e)}function y_(e,t){let n=new Set([`help`,`copy`,...t.map(e=>e.name.toLowerCase())]);return e.filter(e=>{let t=__(e.command??``);return!v_(t)||n.has(t)?!1:(n.add(t),!0)})}function b_(e,t){let n=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return e;let r=t.find(e=>__(e.command??``)===n[1].toLowerCase());if(!r)return e;let i=n[2]??``;return r.prompt.includes(`{{input}}`)?r.prompt.replaceAll(`{{input}}`,()=>i):[r.prompt,i].filter(Boolean).join(`
|
|
64
64
|
|
|
65
|
-
`)}var y_=[{id:`setup-matt-pocock-skills`,icon:`🛠`,titleKey:`tpl.sk.setup`,descKey:`tpl.sk.setup.desc`,promptKey:`tpl.sk.setup.prompt`},{id:`ask-matt`,icon:`🧭`,titleKey:`tpl.sk.ask`,descKey:`tpl.sk.ask.desc`,promptKey:`tpl.sk.ask.prompt`},{id:`grill-with-docs`,icon:`🗣`,titleKey:`tpl.sk.grilldocs`,descKey:`tpl.sk.grilldocs.desc`,promptKey:`tpl.sk.grilldocs.prompt`},{id:`to-spec`,icon:`📝`,titleKey:`tpl.sk.tospec`,descKey:`tpl.sk.tospec.desc`,promptKey:`tpl.sk.tospec.prompt`},{id:`to-tickets`,icon:`🎫`,titleKey:`tpl.sk.totickets`,descKey:`tpl.sk.totickets.desc`,promptKey:`tpl.sk.totickets.prompt`},{id:`implement`,icon:`🏗`,titleKey:`tpl.sk.implement`,descKey:`tpl.sk.implement.desc`,promptKey:`tpl.sk.implement.prompt`},{id:`code-review`,icon:`🧹`,titleKey:`tpl.sk.codeview`,descKey:`tpl.sk.codeview.desc`,promptKey:`tpl.sk.codeview.prompt`},{id:`wayfinder`,icon:`🗺`,titleKey:`tpl.sk.wayfinder`,descKey:`tpl.sk.wayfinder.desc`,promptKey:`tpl.sk.wayfinder.prompt`},{id:`prototype`,icon:`🔬`,titleKey:`tpl.sk.prototype`,descKey:`tpl.sk.prototype.desc`,promptKey:`tpl.sk.prototype.prompt`},{id:`research`,icon:`📚`,titleKey:`tpl.sk.research`,descKey:`tpl.sk.research.desc`,promptKey:`tpl.sk.research.prompt`},{id:`improve-codebase-architecture`,icon:`🏛`,titleKey:`tpl.sk.arch`,descKey:`tpl.sk.arch.desc`,promptKey:`tpl.sk.arch.prompt`},{id:`diagnosing-bugs`,icon:`🐛`,titleKey:`tpl.sk.debug`,descKey:`tpl.sk.debug.desc`,promptKey:`tpl.sk.debug.prompt`},{id:`resolving-merge-conflicts`,icon:`🔀`,titleKey:`tpl.sk.merge`,descKey:`tpl.sk.merge.desc`,promptKey:`tpl.sk.merge.prompt`},{id:`triage`,icon:`🗂`,titleKey:`tpl.sk.triage`,descKey:`tpl.sk.triage.desc`,promptKey:`tpl.sk.triage.prompt`},{id:`wizard`,icon:`✨`,titleKey:`tpl.sk.wizard`,descKey:`tpl.sk.wizard.desc`,promptKey:`tpl.sk.wizard.prompt`},{id:`grill-me`,icon:`🔍`,titleKey:`tpl.sk.grillme`,descKey:`tpl.sk.grillme.desc`,promptKey:`tpl.sk.grillme.prompt`},{id:`handoff`,icon:`🤝`,titleKey:`tpl.sk.handoff`,descKey:`tpl.sk.handoff.desc`,promptKey:`tpl.sk.handoff.prompt`},{id:`to-questionnaire`,icon:`📋`,titleKey:`tpl.sk.questionnaire`,descKey:`tpl.sk.questionnaire.desc`,promptKey:`tpl.sk.questionnaire.prompt`},{id:`teach`,icon:`🎓`,titleKey:`tpl.sk.teach`,descKey:`tpl.sk.teach.desc`,promptKey:`tpl.sk.teach.prompt`},{id:`wait-what`,icon:`💬`,titleKey:`tpl.sk.ww`,descKey:`tpl.sk.ww.desc`,promptKey:`tpl.sk.ww.prompt`},{id:`writing-for-agents`,icon:`📄`,titleKey:`tpl.sk.wfa`,descKey:`tpl.sk.wfa.desc`,promptKey:`tpl.sk.wfa.prompt`},{id:`codebase-design`,icon:`🧱`,titleKey:`tpl.sk.codesign`,descKey:`tpl.sk.codesign.desc`,promptKey:`tpl.sk.codesign.prompt`},{id:`domain-modeling`,icon:`🏷`,titleKey:`tpl.sk.domain`,descKey:`tpl.sk.domain.desc`,promptKey:`tpl.sk.domain.prompt`},{id:`grilling`,icon:`🔥`,titleKey:`tpl.sk.grilling`,descKey:`tpl.sk.grilling.desc`,promptKey:`tpl.sk.grilling.prompt`},{id:`tdd`,icon:`🧪`,titleKey:`tpl.sk.tdd`,descKey:`tpl.sk.tdd.desc`,promptKey:`tpl.sk.tdd.prompt`}],b_=`pi-web-ui:prompt-templates`;function x_(){try{let e=localStorage.getItem(b_);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[]}catch{return[]}}function S_(e){return y_.some(t=>t.id===e)}function C_(e){return typeof e.title==`string`}var w_=(0,Q.createContext)(null);function T_(){let e=(0,Q.useContext)(w_);if(!e)throw Error(`useTemplates must be used within TemplateProvider`);return e}function E_({children:e,currentModelId:t}){let n=V(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(``),s=(0,Q.useRef)(!1),c=(0,Q.useRef)(0),l=(0,Q.useCallback)(async e=>{if(s.current)return!1;s.current=!0,c.current++;try{let t=await fetch(q(`/api/prompt-templates`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),n=await t.json();if(!t.ok)throw Error(n.error||t.statusText);if(!Array.isArray(n.templates))throw Error(`Invalid prompt templates response`);return i(n.templates),o(``),!0}catch(e){return o(String(e)),!1}finally{s.current=!1}},[]),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t=async()=>{if(s.current)return;let t=++c.current;try{let n=await fetch(q(`/api/prompt-templates`)),r=await n.json();if(!n.ok)throw Error(r.error||n.statusText);if(!Array.isArray(r.templates))throw Error(`Invalid prompt templates response`);!e&&!s.current&&t===c.current&&i(r.templates)}catch(t){e||o(String(t))}};return(async()=>{let e=x_();if(e.length&&await l({action:`migrate`,templates:e}))try{localStorage.removeItem(b_)}catch{}await t()})(),window.addEventListener(`focus`,t),()=>{e=!0,window.removeEventListener(`focus`,t)}},[l]);let b=(0,Q.useMemo)(()=>{let e=new Map,t=new Set;for(let n of r)n.hidden?t.add(n.id):(C_(n)&&!S_(n.id)||C_(n))&&e.set(n.id,n);let i=y_.filter(e=>!t.has(e.id)).map(t=>{let r=e.get(t.id);return{id:t.id,icon:r?.icon??t.icon,title:r?.title??n(t.titleKey),desc:r?.desc??n(t.descKey),command:typeof r?.command==`string`?r.command:``,prompt:r?.prompt??n(t.promptKey),builtin:!0}}),a=r.filter(e=>C_(e)&&!S_(e.id)).map(e=>({id:e.id,icon:e.icon??`📌`,title:e.title??``,desc:e.desc??``,command:typeof e.command==`string`?e.command:``,prompt:e.prompt??``}));return[...i,...a]},[r,n]),x=(0,Q.useCallback)(()=>d(!0),[]),S=(0,Q.useCallback)(e=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:e}))},[]),C=(0,Q.useCallback)((e,t=!1)=>{y(t),e?(h(!1),p({...e})):(h(!0),p({id:ht(),icon:`📌`,title:``,desc:``,prompt:``}))},[]),w=(0,Q.useCallback)(()=>{d(!1),p(null),y(!1)},[]),T=(0,Q.useCallback)(()=>{g?(l({action:`reset`}),_(!1)):_(!0)},[g,l]);(0,Q.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>_(!1),5e3);return()=>clearTimeout(e)},[g]);let E=(0,Q.useCallback)(e=>{d(!1),S(e.prompt)},[S]),D=(0,Q.useCallback)(e=>{d(!1),C(e,!0)},[C]),O=(0,Q.useCallback)(()=>{d(!1),C(void 0,!0)},[C]),k=(0,Q.useCallback)(async e=>{await l({action:`upsert`,template:e})&&(p(null),v&&(d(!0),y(!1)))},[v]),A=(0,Q.useCallback)(async e=>{await l(e.builtin?{action:`upsert`,template:{id:e.id,hidden:!0}}:{action:`remove`,id:e.id})&&(p(null),v&&(d(!0),y(!1)))},[v]),j=(0,Q.useCallback)(async e=>{await l({action:`remove`,id:e.id})&&(p(null),v&&(d(!0),y(!1)))},[v]),M=(0,Q.useMemo)(()=>({templates:b,fill:S,openPicker:x,openEdit:C,resetConfirm:g,toggleReset:T}),[b,S,x,C,g,T]),N=f?r.some(e=>e.id===f.id&&!e.hidden&&C_(e)):!1;return(0,$.jsxs)(w_.Provider,{value:M,children:[e,a&&(0,$.jsxs)(`div`,{className:`template-error`,role:`alert`,children:[n(`tpl.storageError`),`: `,a]}),u&&(0,$.jsx)(k_,{templates:b,resetConfirm:g,onFill:E,onEditTpl:D,onNew:O,onResetToggle:T,onClose:w}),f&&(0,$.jsx)(A_,{editing:f,isNew:m,hasOverride:N,storageError:a,templates:b,onDraft:p,onSave:k,onRestore:()=>j(f),onRemove:()=>A(f),onFill:()=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:f.prompt})),w()},onSend:()=>{let e=f.prompt.trim();e&&Z({type:`prompt`,text:e,queue:!1})&&(t&&Ao(t),w())},onClose:w})]})}function D_(){let e=V(),{templates:t,fill:n,openEdit:r,toggleReset:i,resetConfirm:a}=T_();return(0,$.jsxs)(`div`,{className:`empty-templates`,children:[(0,$.jsxs)(`div`,{className:`empty-templates-head`,children:[(0,$.jsx)(`span`,{className:`empty-templates-title`,children:e(`tpl.title`)}),(0,$.jsx)(`span`,{className:`empty-templates-hint`,children:e(`tpl.hint`)})]}),(0,$.jsxs)(`div`,{className:`empty-templates-grid`,children:[t.map(t=>(0,$.jsx)(O_,{tpl:t,title:e(`tpl.clickCard`),onFill:()=>n(t.prompt),onEdit:()=>r(t),editTitle:e(`tpl.editTpl`)},t.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:()=>r(),title:e(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(rt,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e(`tpl.addDesc`)})]})]})]}),(0,$.jsx)(`div`,{className:`empty-templates-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:i,children:[(0,$.jsx)(d,{}),e(a?`tpl.resetConfirm`:`tpl.reset`)]})})]})}function O_({tpl:e,title:t,onFill:n,onEdit:r,editTitle:i}){let a=V();return(0,$.jsxs)(`button`,{type:`button`,className:`empty-template`,title:t,onClick:n,children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:e.icon}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e.title}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e.desc})]}),(0,$.jsx)(`span`,{className:`template-card-ops`,role:`button`,title:i??a(`tpl.editTpl`),onClick:e=>{e.stopPropagation(),r()},children:(0,$.jsx)(M,{})})]})}function k_({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:i,onResetToggle:a,onClose:o}){let s=V();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal template-picker`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-picker-top`,children:[(0,$.jsxs)(`div`,{className:`template-picker-head`,children:[(0,$.jsx)(`span`,{className:`template-picker-title`,children:s(`tpl.pickerTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:s(`close`),onClick:o,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`div`,{className:`template-picker-hint`,children:s(`tpl.pickerHint`)})]}),(0,$.jsx)(`div`,{className:`template-picker-scroll`,children:(0,$.jsxs)(`div`,{className:`template-picker-grid`,children:[e.map(e=>(0,$.jsx)(O_,{tpl:e,title:s(`tpl.clickCard`),onFill:()=>n(e),onEdit:()=>r(e),editTitle:s(`tpl.editTpl`)},e.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:i,title:s(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(rt,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:s(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:s(`tpl.addDesc`)})]})]})]})}),(0,$.jsx)(`div`,{className:`template-picker-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:a,children:[(0,$.jsx)(d,{}),s(t?`tpl.resetConfirm`:`tpl.reset`)]})})]})})}function A_({storageError:e,templates:t,editing:n,isNew:r,hasOverride:a,onDraft:o,onSave:s,onRestore:c,onRemove:l,onFill:u,onSend:d,onClose:f}){let p=V(),m=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&f()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f]),(0,Q.useEffect)(()=>{let e=m.current;if(!e)return;e.style.height=`auto`;let t=e.scrollHeight>300;e.style.height=`${Math.min(e.scrollHeight,300)}px`,e.style.overflowY=t?`auto`:`hidden`},[n.prompt]);let h=()=>{let e=n.title.trim(),r=n.prompt.trim();if(!e||!r){o({...n,error:p(`tpl.required`)});return}let i=h_(n.command??``);if(i&&!g_(i)){o({...n,error:p(`tpl.commandInvalid`)});return}if(i&&t.some(e=>e.id!==n.id&&h_(e.command??``)===i)){o({...n,error:p(`tpl.commandDuplicate`)});return}s({id:n.id,command:i,icon:n.icon.trim()||`📌`,title:e,desc:n.desc.trim(),prompt:r})},_=!!n.builtin&&!r;return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:f,children:(0,$.jsxs)(`div`,{className:`modal template-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-modal-head`,children:[(0,$.jsx)(`span`,{className:`template-modal-icon`,children:n.icon}),(0,$.jsx)(`span`,{className:`template-modal-badge`,children:p(_?`tpl.builtin`:`tpl.custom`)}),(0,$.jsx)(`span`,{className:`template-modal-title`,children:p(r?`tpl.newTitle`:`tpl.editTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:p(`close`),onClick:f,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`template-modal-body`,children:[(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldIcon`)}),(0,$.jsx)(`input`,{className:`template-field-input icon`,value:n.icon,maxLength:4,onChange:e=>o({...n,icon:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldTitle`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.title,placeholder:p(`tpl.fieldTitlePh`),onChange:e=>o({...n,title:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldDesc`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.desc,placeholder:p(`tpl.fieldDescPh`),onChange:e=>o({...n,desc:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldCommand`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.command??``,placeholder:`/pr`,onChange:e=>o({...n,command:e.target.value,error:void 0})}),(0,$.jsx)(`span`,{className:`template-picker-hint`,children:p(`tpl.commandHint`)})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldPrompt`)}),(0,$.jsx)(`textarea`,{ref:m,className:`template-field-prompt`,value:n.prompt,placeholder:p(`tpl.fieldPromptPh`),onChange:e=>o({...n,prompt:e.target.value})})]})]}),(n.error||e)&&(0,$.jsx)(`div`,{className:`template-error`,role:`alert`,children:n.error||`${p(`tpl.storageError`)}: ${e}`}),(0,$.jsxs)(`div`,{className:`template-modal-actions`,children:[(0,$.jsxs)(`div`,{className:`template-modal-actions-left`,children:[!r&&_&&a&&(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn ghost`,title:p(`tpl.restoreTip`),onClick:c,children:p(`tpl.restore`)}),!r&&_&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:p(`tpl.removeTip`),onClick:l,children:[(0,$.jsx)(g,{}),` `,p(`tpl.remove`)]}),!r&&!_&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:p(`tpl.deleteTip`),onClick:l,children:[(0,$.jsx)(g,{}),` `,p(`tpl.delete`)]})]}),(0,$.jsxs)(`div`,{className:`template-modal-actions-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn`,onClick:h,children:p(`tpl.save`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn fill`,onClick:u,title:p(`tpl.fillTip`),children:p(`tpl.fill`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn send`,onClick:d,title:p(`tpl.sendTip`),children:[(0,$.jsx)(i,{}),` `,p(`tpl.sendNow`)]})]})]})]})})}var j_=class extends Q.Component{state={message:null};static getDerivedStateFromError(e){return{message:e instanceof Error?e.message:String(e)}}componentDidCatch(e,t){console.error(`[ui-slot] entry "${this.props.entryId??this.props.label}" in slot "${this.props.slot??`?`}" crashed:`,e,t.componentStack)}render(){if(this.state.message===null)return this.props.children;let e=`slot=${this.props.slot??`?`} entry=${this.props.entryId??this.props.label}: ${this.state.message}`;return(0,$.jsxs)(`button`,{type:`button`,className:`slot-error`,title:e,"aria-label":this.props.label,onClick:()=>console.error(`[ui-slot] ${e}`),children:[(0,$.jsx)(`span`,{"aria-hidden":!0,children:`⚠`}),(0,$.jsx)(`span`,{children:this.props.label})]})}};function M_(e,t){return!e||e.length===0?null:(0,$.jsx)(`span`,{className:`slot-toolbar`,children:e.map((e,n)=>(0,$.jsx)(j_,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:N_(e,n,t)},`${e.id}#${n}`))})}function N_(e,t,n){let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`slot-badge`,title:a,children:e.badge??i},r):e.kind===`toggle`?(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn${e.checked?` on`:``}`,title:a,"aria-label":i,"aria-pressed":!!e.checked,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r):e.kind===`progress`?(0,$.jsx)(`span`,{className:`slot-progress`,title:`${a} ${e.progress??0}%`,children:(0,$.jsx)(`progress`,{value:e.progress??0,max:100})},r):e.kind===`input`?(0,$.jsx)(`input`,{className:`slot-input`,defaultValue:e.value??``,placeholder:i,title:a,"aria-label":i,onKeyDown:t=>{t.key===`Enter`&&!t.nativeEvent.isComposing&&n?.(e,t.target.value)}},`${r}:${e.value??``}`):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>n?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn`,title:a,"aria-label":i,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r)}function P_(e,t,n){let r=[],i=[],a=!1,o=e=>{i.length!==0&&(a=!0,r.push((0,$.jsx)(`span`,{className:`slot-toolbar`,children:i.map((e,t)=>(0,$.jsx)(j_,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:N_(e,t,n)},`${e.id}#${t}`))},e)),i=[])};return e.forEach((e,n)=>{if(e.source===`host`){o(`gap${n}`);let i=t[e.id]??null;i&&(a=!0),r.push((0,$.jsx)(Q.Fragment,{children:i},e.id))}else i.push(e)}),o(`tail`),a?(0,$.jsx)($.Fragment,{children:r}):null}var F_=`#ffffff`,I_=`#1e1e1e`,L_=`.msg-actions, .msg-text-copy, .chead-copy, .stream-cursor, .msg-editor, .msg-collapse-btn, .msg-export-check, .toolcall-kill, .toolcall-open`,R_=16384;function z_(e,t=800,n=2){let r=Math.max(e,t,1);return r*n<=R_?n:+(r<=R_)}function B_(e){let t=e.trim().toLowerCase();if(!t)return null;if(t===`transparent`)return{r:0,g:0,b:0,a:0};if(t.startsWith(`#`)){let e=t.slice(1);if(e.length===3||e.length===4){let t=Number.parseInt(e[0]+e[0],16),n=Number.parseInt(e[1]+e[1],16),r=Number.parseInt(e[2]+e[2],16),i=e.length===4?Number.parseInt(e[3]+e[3],16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}if(e.length===6||e.length===8){let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16),r=Number.parseInt(e.slice(4,6),16),i=e.length===8?Number.parseInt(e.slice(6,8),16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}return null}let n=t.match(/^rgba?\(\s*([\s\S]+)\)$/);if(!n)return null;let r=n[1].trim(),i,a=1;if(r.includes(`/`)){let[e,t]=r.split(`/`);i=e.trim().split(/[\s,]+/).filter(Boolean),a=H_(t.trim())}else if(r.includes(`,`)){let e=r.split(`,`).map(e=>e.trim());e.length===4&&(a=H_(e.pop())),i=e}else i=r.split(/\s+/).filter(Boolean),i.length===4&&(a=H_(i.pop()));if(i.length!==3)return null;let o=V_(i[0]),s=V_(i[1]),c=V_(i[2]);return[o,s,c,a].some(e=>Number.isNaN(e))?null:{r:o,g:s,b:c,a}}function V_(e){return e.endsWith(`%`)?Math.round(U_(Number.parseFloat(e),0,100)*2.55):Math.round(U_(Number.parseFloat(e),0,255))}function H_(e){return e.endsWith(`%`)?U_(Number.parseFloat(e)/100,0,1):U_(Number.parseFloat(e),0,1)}function U_(e,t,n){return Math.min(n,Math.max(t,e))}function W_(e){let t=U_(Math.round(e.r),0,255),n=U_(Math.round(e.g),0,255),r=U_(Math.round(e.b),0,255);return e.a<.996?`rgba(${t}, ${n}, ${r}, ${Math.round(U_(e.a,0,1)*1e3)/1e3})`:`rgb(${t}, ${n}, ${r})`}function G_(e,t){let n=U_(e.a,0,1);return n<=0?{r:t.r,g:t.g,b:t.b,a:t.a}:n>=1?{r:e.r,g:e.g,b:e.b,a:1}:{r:e.r*n+t.r*(1-n),g:e.g*n+t.g*(1-n),b:e.b*n+t.b*(1-n),a:1}}function K_(e,t){let n=B_(t)??{r:255,g:255,b:255,a:1},r=B_(e);return!r||r.a<=.004?W_({...n,a:1}):W_(G_(r,{...n,a:1}))}function q_(e){let t=e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b)}function J_(e){return q_(e)>.45}function Y_(e){let t=document.createElement(`div`);t.style.cssText=`position:fixed;left:-99999px;top:0;width:8px;height:8px;pointer-events:none;background:${e}`,document.body.appendChild(t);let n=getComputedStyle(t).backgroundColor;return t.remove(),n}function X_(){return getComputedStyle(document.documentElement).colorScheme.split(/\s+/).includes(`light`)?F_:I_}function Z_(e){let t=X_(),n=t;try{n=K_(Y_(`var(--bg)`),t)}catch{n=t}try{let e=K_(Y_(`var(--card-bg, var(--msgs-bg, var(--bg)))`),n),t=B_(e);if(t&&q_(t)+t.a>0)return e}catch{}let r=e??null;for(;r;){let e=getComputedStyle(r).backgroundColor;if(e&&e!==`transparent`&&e!==`rgba(0, 0, 0, 0)`){let t=K_(e,n),r=B_(e);if(r&&r.a>.04)return t}r=r.parentElement}return n}function Q_(e){return e instanceof HTMLElement||e instanceof SVGElement?e.style:null}function $_(e,t){let n=B_(e);return n?n.a<=.004?`transparent`:n.a>=.996?W_({...n,a:1}):W_(G_(n,{...B_(t)??{r:255,g:255,b:255,a:1},a:1})):null}function ev(e,t,n){let r=getComputedStyle(e),i=Q_(t),a=n;if(i){let e=$_(r.backgroundColor,n);e===`transparent`?i.backgroundColor=`transparent`:e&&(i.backgroundColor=e,a=e);let t=$_(r.color,a);t&&t!==`transparent`&&(i.color=t);for(let[e]of[[`borderTopColor`,`border-top-color`],[`borderRightColor`,`border-right-color`],[`borderBottomColor`,`border-bottom-color`],[`borderLeftColor`,`border-left-color`],[`outlineColor`,`outline-color`],[`textDecorationColor`,`text-decoration-color`]]){let t=$_(r[e],a);t&&t!==`transparent`&&(i[e]=t)}let o=$_(r.fill,a);o&&o!==`transparent`&&r.fill!==`none`&&(i.fill=o);let s=$_(r.stroke,a);s&&s!==`transparent`&&r.stroke!==`none`&&(i.stroke=s),i.backdropFilter=`none`,i.setProperty(`-webkit-backdrop-filter`,`none`),r.mixBlendMode&&r.mixBlendMode!==`normal`&&(i.mixBlendMode=`normal`),i.caretColor=`transparent`}let o=Array.from(e.children),s=Array.from(t.children),c=Math.min(o.length,s.length);for(let e=0;e<c;e++)ev(o[e],s[e],a)}function tv(e){e.querySelectorAll(L_).forEach(e=>e.remove())}function nv(e,t={}){t.includeThinking||e.querySelectorAll(`.thinking`).forEach(e=>e.remove()),t.includeTools||e.querySelectorAll(`.toolcall`).forEach(e=>e.remove())}function rv(e,t,n={}){let r=e.cloneNode(!0);return ev(e,r,t),nv(r,n),tv(r),r.classList.remove(`msg-export-selected`),r.style.margin=`0`,r.style.paddingLeft=``,r.removeAttribute(`id`),r.querySelectorAll(`[id]`).forEach(e=>e.removeAttribute(`id`)),r}async function iv(e,t={}){let{toBlob:n}=await Os(async()=>{let{toBlob:e}=await import(`./es-DWMIuDU2.js`);return{toBlob:e}},[],import.meta.url),r=t.backgroundColor??Z_(e),i=B_(r),a=await n(e,{pixelRatio:t.pixelRatio??2,backgroundColor:r,cacheBust:!1,style:{colorScheme:i&&!J_(i)?`dark`:`light`}});if(!a)throw Error(`toBlob returned null`);return a}function av(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function ov(e){return document.querySelector(`.msg[data-msg-id="${av(e)}"]`)??document.querySelector(`[data-msg-id="${av(e)}"]`)}function sv(){let e=V(),t=Vf(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`pi-web-ui`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),b=(0,Q.useRef)(`#ffffff`);if((0,Q.useEffect)(()=>{t.open&&(d(!1),h(!1),_(``))},[t.open]),mt(()=>{Hf()},t.open),(0,Q.useLayoutEffect)(()=>{if(!t.open)return;let e=!1,n=0;p(!0);let r=()=>{if(e||!y.current)return;let i=[],a=!1;for(let e of t.selectedIds){let t=ov(e);t?i.push(t):a=!0}let o=t.includeThinking&&i.some(e=>e.querySelector(`.thinking`)&&!e.querySelector(`.thinking-body`))||t.includeTools&&i.some(e=>e.querySelector(`.toolcall`)&&!e.querySelector(`.toolcall-body`));if((a||o)&&n<12){n+=1,requestAnimationFrame(r);return}let s=i[0],c=Z_(s??void 0);b.current=c;let l=document.createDocumentFragment();for(let e of i)l.appendChild(rv(e,c,{includeThinking:t.includeThinking,includeTools:t.includeTools}));y.current.replaceChildren(l);let u=v.current;if(u){u.style.backgroundColor=c;let e=B_(c);if(u.style.colorScheme=e&&!J_(e)?`dark`:`light`,s){let e=getComputedStyle(s).color;e&&(u.style.color=e)}}p(!1)},i=requestAnimationFrame(()=>requestAnimationFrame(r));return()=>{e=!0,cancelAnimationFrame(i),y.current?.replaceChildren()}},[t.open,t.selectedIds,t.includeThinking,t.includeTools]),!t.open)return null;let x=async()=>{let n=v.current;if(n&&!u&&t.selectedIds.length!==0){d(!0),_(``);try{let t=z_(n.scrollHeight,n.scrollWidth);if(t===0){_(e(`exportTooLong`));return}let r=await iv(n,{backgroundColor:b.current,pixelRatio:t});await navigator.clipboard.write([new ClipboardItem({"image/png":r})]),h(!0),window.setTimeout(()=>h(!1),1500)}catch(t){let n=t instanceof Error?t.message:String(t);_(`${e(`copyFailed`)}: ${n}`)}finally{d(!1)}}};return(0,$.jsxs)(`aside`,{className:`saveimg-dock`,role:`dialog`,"aria-label":e(`saveAsImage`),children:[(0,$.jsxs)(`div`,{className:`saveimg-head`,children:[(0,$.jsx)(`span`,{className:`saveimg-title`,children:e(`saveAsImage`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),"aria-label":e(`close`),onClick:()=>Hf(),children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`p`,{className:`saveimg-hint`,children:e(`exportSelectHint`)}),(0,$.jsxs)(`div`,{className:`saveimg-body`,children:[(0,$.jsx)(`div`,{className:`saveimg-preview`,children:(0,$.jsxs)(`div`,{ref:v,className:`saveimg-card${i?` saveimg-card--border`:``}`,children:[n.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-title`,children:n.trim()}):null,(0,$.jsx)(`div`,{ref:y,className:`saveimg-card-md`}),o&&c.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-wm`,children:c.trim()}):null]})}),(0,$.jsxs)(`div`,{className:`saveimg-options`,children:[(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeTools,onChange:e=>Wf({includeTools:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeTools`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeThinking,onChange:e=>Wf({includeThinking:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeThinking`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt`,children:[(0,$.jsx)(`span`,{children:e(`imageTitle`)}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:n,onChange:e=>r(e.target.value),placeholder:e(`imageTitlePlaceholder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageBorder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageWatermark`)})]}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:c,disabled:!o,onChange:e=>l(e.target.value),placeholder:e(`imageWatermarkPlaceholder`)}),(0,$.jsxs)(`div`,{className:`saveimg-copy-row`,children:[(0,$.jsx)(`span`,{className:`saveimg-count`,children:e(`exportSelectedCount`,{n:t.selectedIds.length})}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary saveimg-copy`,onClick:()=>void x(),disabled:u||f||t.selectedIds.length===0,title:e(`copyImageBtn`),children:[u||f?(0,$.jsx)(Zo,{className:`saveimg-spin`}):m?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{children:e(u||f?`savingImage`:m?`copied`:`copyImageBtn`)})]})]})]}),g?(0,$.jsx)(`div`,{className:`saveimg-error`,children:g}):null]})]})}var cv=`.msg-text, .attachcard-content, .toolcall-output pre, .bashblock-output, .quote-content`,lv=`button, input, textarea, [contenteditable], .msg-meta, .msg-actions, .chead, .toolcall-output-label`;function uv(e){return e.nodeType===1?e:e.parentElement}function dv(e,t,n){if(!t||t.isCollapsed||t.rangeCount!==1)return null;let r=t.getRangeAt(0),i=uv(r.startContainer),a=uv(r.endContainer);if(!i||!a||!e.contains(i)||!e.contains(a)||!i.closest(cv)||!a.closest(cv)||i.closest(lv)||a.closest(lv))return null;let o=i.closest(`.msg[data-msg-id]`);if(!o||o!==a.closest(`.msg[data-msg-id]`))return null;for(let e of o.querySelectorAll(lv))if(r.intersectsNode(e))return null;let s=t.toString(),c=o.dataset.msgId,l=o.dataset.role;return!s.trim()||!c||!l?null:{text:s,messageId:c,role:l,...n?{sessionId:n}:{}}}function fv({rootRef:e,sessionId:t,enabled:n=!0,onSelect:r}){let i=V(),[a,o]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{o(null);let i=e.current;if(!i||!n)return;let a=!1,s=0,c=()=>{cancelAnimationFrame(s),o(null)},l=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let e=window.getSelection(),n=dv(i,e,t);if(!n||!e){o(null);return}let a=e.getRangeAt(0).getBoundingClientRect();if(!a.width&&!a.height){o(null);return}r?.(),o({quote:n,left:Math.max(8,Math.min(a.right-88,window.innerWidth-96)),top:Math.max(8,Math.min(a.top>=44?a.top-40:a.bottom+8,window.innerHeight-42))})})},u=e=>{e.target?.closest?.(`.quote-selection-button`)||(a=e.button===0&&i.contains(e.target),c())},d=e=>{a=!1,e.button===0&&l()},f=()=>{a||l()},p=e=>{e.key===`Escape`&&c()};return document.addEventListener(`mousedown`,u),document.addEventListener(`mouseup`,d),document.addEventListener(`selectionchange`,f),document.addEventListener(`keydown`,p),window.addEventListener(`scroll`,c,!0),window.addEventListener(`resize`,c),window.addEventListener(`blur`,c),()=>{cancelAnimationFrame(s),document.removeEventListener(`mousedown`,u),document.removeEventListener(`mouseup`,d),document.removeEventListener(`selectionchange`,f),document.removeEventListener(`keydown`,p),window.removeEventListener(`scroll`,c,!0),window.removeEventListener(`resize`,c),window.removeEventListener(`blur`,c)}},[e,t,n,r]),!a||!n||a.quote.sessionId!==t?null:(0,bn.createPortal)((0,$.jsxs)(`button`,{type:`button`,className:`quote-selection-button`,style:{left:a.left,top:a.top},onMouseDown:e=>e.preventDefault(),onClick:()=>{Ft({attachments:[{path:``,name:i(`quoteText`),mode:`quote`,quote:a.quote,key:ht()}]})&&(o(null),window.getSelection()?.removeAllRanges(),Xt())},children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),` `,i(`quoteSelection`)]}),document.body)}var pv=new Map,mv=new Set,hv=new Map,gv=15,_v=5,vv=100,yv=30,bv=1200,xv=2400,Sv=1600;function Cv({kind:e,text:t,index:n,id:r,onRemoveQueued:i,onRecallQueued:a}){let o=V(),s=hs(t);return(0,$.jsxs)(`div`,{className:`msg msg-user msg-queued`,"data-role":`user`,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:o(`role.user`)}),(0,$.jsx)(`span`,{className:`queued-tag ${e===`steer`?`steer`:`follow`}`,children:o(e===`steer`?`queueSteerTag`:`queueFollowTag`)}),(0,$.jsxs)(`div`,{className:`msg-queued-actions`,children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-recall`,title:o(`queueRecallTip`),"aria-label":o(`queueRecallTip`),onClick:()=>a(e,t,n,r),children:`↩`}),i&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-remove`,title:o(`queueRemoveTip`),"aria-label":o(`queueRemoveTip`),onClick:()=>i(e,t,n,r),children:`✕`})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:(0,$.jsxs)(`div`,{className:`msg-text`,children:[s.quotes.map((e,t)=>(0,$.jsx)(bs,{quote:e},`quote-${t}`)),s.attachments&&s.attachments.length>0&&(0,$.jsx)(`div`,{className:`queued-attachments`,children:s.attachments.map((e,t)=>(0,$.jsxs)(`span`,{className:`queued-att-chip`,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:e.type===`image`||e.type===`vision-bridge`?`🖼️`:e.type===`folder`?`📁`:e.type===`page`?`🌐`:e.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:e.name})]},`att-${t}`))}),s.text?(0,$.jsx)(al,{text:s.text,hardBreaks:!0}):null]})})]})}function wv({compaction:e}){let t=V(),[,n]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let e=setInterval(()=>n(e=>e+1),1e3);return()=>clearInterval(e)},[]);let r=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),i=e.reason===`manual`?t(`compactingReasonManual`):e.reason===`overflow`?t(`compactingReasonOverflow`):t(`compactingReasonThreshold`);return(0,$.jsxs)(`div`,{className:`compact-notice`,role:`status`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsxs)(`span`,{className:`compact-text`,children:[t(`compactingContext`),` · `,r,`s`]}),(0,$.jsx)(`span`,{className:`compact-reason`,children:i})]})}function Tv(e){return e.content.some(e=>e.type===`toolCall`)}function Ev(e,t,n,r,i){if(e.convKey!==t&&(e.convKey=t,e.pending=null,e.finalizedMap.clear()),e.pending&&r?.id!==e.pending.streamKey){let{index:t,streamKey:r}=e.pending;for(let a=Math.max(0,t);a<n.length;a++){let t=n[a];if(t.role===`assistant`&&!e.finalizedMap.has(t.id)){e.finalizedMap.set(t.id,r),i?.(r,t.id);break}}e.pending=null}return r&&e.pending?.streamKey!==r.id&&(e.pending={index:n.length,streamKey:r.id}),e.finalizedMap}function Dv(e){return Array.isArray(e.content)?e.content.some(e=>{let t=rp(e);return t&&t.text.trim().length>0}):!1}function Ov(e){return e.role&&e.role!==`assistant`||e.customType||!Array.isArray(e.content)||e.content.length===0||Dv(e)?!1:e.content.some(e=>e.type===`toolCall`||e.type===`thinking`)}function kv(e){return e.customType?!1:e.role===`assistant`||!e.role}function Av(e,t){let n=!!t?.mergeTurns,r=[],i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a.role===`system`||a.role===`toolResult`)continue;let o=Bg(a),s=kv(a),c=Ov(a),l=!c&&!!i&&s&&!o&&t===e.length-1&&!Dv(a);!o&&(n?s:c||l)?i?i.messages.push(a):(i={type:`tool_cluster`,id:`cluster-${a.id}`,messages:[a]},r.push(i)):(i=null,r.push({type:`single`,message:a}))}return r}function jv(e,t=!1){return t?Math.max(48,Math.ceil(e.length/4)*30):Math.max(48,e.length*52)}var Mv=(0,Q.memo)(function({id:e,show:t,placeholderHeight:n,attachEl:r,onMeasured:i,variant:a=`trail`,children:o}){let s=(0,Q.useRef)(null);return(0,Q.useLayoutEffect)(()=>{if(!t)return;let n=s.current;if(!n)return;let r=Array.from(n.children,e=>e.getBoundingClientRect()),o=a===`contents`&&r.length?Math.max(...r.map(e=>e.bottom))-Math.min(...r.map(e=>e.top)):n.offsetHeight;o>0&&i?.(e,o)},[t,e,i,a]),t?(0,$.jsx)(`div`,{ref:e=>{s.current=e,r(e)},className:a===`flow`?`flow-turn`:a===`trail`?`turn-tools-trail`:void 0,style:a===`contents`?{display:`contents`}:void 0,"data-cluster-id":e,"data-lazy-id":e,children:o}):(0,$.jsx)(`div`,{ref:r,className:`msg-lazy-ph msg-lazy-ph-cluster`,"data-cluster-id":e,"data-lazy-id":e,style:{height:n},"aria-hidden":`true`})});function Nv({state:e,liveOutputs:t,toolStatuses:n,onEdit:r,onKillBash:i,onRetry:a,onRemoveQueued:o,onRecallQueued:s,thinkingWrap:c,toolsWrap:l,toolImages:u,keepRecent:d,reversePagination:f=!1,minimalNewChat:p=!1,jumpTarget:m,onJumpDone:h,urlJumpMessageId:g,onUrlJumpDone:_,preview:v=!1,messageLabels:y,readOnly:b=!1,uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,uiChatEmpty:T,onUiAction:E}){let D=V(),O=Vf(),k=(0,Q.useRef)(null),A=(0,Q.useRef)(!0),j=(0,Q.useRef)(!1),[M,N]=(0,Q.useState)(()=>new Set),[P,ee]=(0,Q.useState)(!1),F=(0,Q.useMemo)(()=>e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,[e.messages,e.streamingMessage]),te=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e.messages)n.role===`toolResult`&&n.toolCallId&&t.set(n.toolCallId,n);return t},[e.messages]),ne=(0,Q.useMemo)(()=>Ng(e.messages),[e.messages]),re=(0,Q.useMemo)(()=>{let t=new Map,n;for(let r of e.messages)r.role===`user`&&(n=r.id),n&&t.set(r.id,n);return t},[e.messages]),[I,L]=(0,Q.useState)(null),ie=(0,Q.useMemo)(()=>{for(let e=F.length-1;e>=0;e--)if(F[e].role!==`system`)return F[e].id;return null},[F]),ae=Math.min(vv,Math.max(_v,Math.floor(Number(d)||gv))),oe=(0,Q.useMemo)(()=>{let t=new Set;for(let n of e.messages)n.role!==`toolResult`&&Bg(n)&&!M.has(n.id)&&t.add(n.id);return t},[e.messages,M]),se=Ug(),ce=(0,Q.useMemo)(()=>({mergeTurns:!0}),[]),[R,le]=(0,Q.useState)(()=>{if(f||e.messages.length<=yv)return new Set;let t=qg(e.messages,new Map,Math.max(Sv,ae*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Av(e.messages,ce))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);return n}),[ue,z]=(0,Q.useState)(()=>new Set),de=(0,Q.useRef)(new Map),B=(0,Q.useRef)(new Map),fe=(0,Q.useRef)(new Map),pe=(0,Q.useRef)(0),me=(0,Q.useRef)(0),he=(0,Q.useRef)(0),H=(0,Q.useRef)(null),ge=Math.max(se?240:60,ae*2),U=se?120:30,W=Math.min(ge,10),[G,_e]=(0,Q.useState)(()=>W),K=`${e.conversationId??``}:${e.sessionFile??``}`,q=(0,Q.useRef)(K),J=(0,Q.useRef)(F.length),ve=(0,Q.useRef)(F[0]?.id),Y=(0,Q.useRef)(null),ye=(0,Q.useRef)(null),be=(0,Q.useRef)(!1),[xe,Se]=(0,Q.useState)(!1),Ce=(0,Q.useRef)(!1),we=(0,Q.useCallback)(e=>{Ce.current=e,Se(e)},[]),Te=(0,Q.useRef)(0),Ee=(0,Q.useRef)(null),De=(0,Q.useCallback)(()=>{let e=k.current;if(!e)return null;let t=e.getBoundingClientRect().top,n=e.querySelectorAll(`[data-lazy-id]`);for(let e=0;e<n.length;e++){let r=n[e],i=r.getBoundingClientRect();if(i.bottom>t+2)return{id:r.dataset.lazyId??null,top:i.top-t}}return null},[]),X=(0,Q.useCallback)(()=>{Te.current&&=(cancelAnimationFrame(Te.current),0),Ee.current=null},[]),Oe=(0,Q.useCallback)(()=>{let e=k.current,t=De();ye.current={sh:e?e.scrollHeight:0,st:e?e.scrollTop:0,id:t?.id??null,top:t?.top??0,msgLen:F.length,firstId:F[0]?.id}},[De,F]),ke=(0,Q.useCallback)(e=>{let t=k.current;if(t){if(e.id){let n=null;try{n=t.querySelector(`[data-lazy-id="`+CSS.escape(e.id)+`"]`)}catch{n=null}if(n){let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top-e.top;r!==0&&(t.scrollTop+=r);return}}t.scrollTop=e.st+(t.scrollHeight-e.sh)}},[]),Ae=(0,Q.useCallback)(()=>{let e=ye.current,t=k.current;if(!t||!e)return;X(),we(!0),ke(e);let n=De();Ee.current={id:n?.id??null,top:n?.top??0,sh:t.scrollHeight,st:t.scrollTop};let r=0,i=0,a=()=>{Te.current=0;let e=k.current,t=Ee.current;if(!e||!t){we(!1);return}if(Math.abs(e.scrollTop-t.st)>2){let t=De();Ee.current={id:t?.id??null,top:t?.top??0,sh:e.scrollHeight,st:e.scrollTop},i=0}else{let n=0,r=!1;if(t.id){let i=null;try{i=e.querySelector(`[data-lazy-id="`+CSS.escape(t.id)+`"]`)}catch{i=null}i&&(r=!0,n=i.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top)}if(r)n!==0&&(e.scrollTop+=n),Ee.current={...t,sh:e.scrollHeight,st:e.scrollTop};else{n=e.scrollHeight-t.sh;let r=De();n!==0&&(e.scrollTop+=n),Ee.current={id:r?.id??null,top:r?.top??0,sh:e.scrollHeight,st:e.scrollTop}}i=n===0?i+1:0}if(r++,i>=3&&r>=4||r>=30){Ee.current=null,we(!1);return}Te.current=requestAnimationFrame(a)};Te.current=requestAnimationFrame(a)},[X,De,ke,we]);q.current!==K&&(q.current=K,Y.current=null,_e(W),J.current=F.length,ve.current=F[0]?.id,ye.current=null,X(),Ce.current&&we(!1),be.current=!1),(0,Q.useLayoutEffect)(()=>{let e=F.length-J.current;J.current=F.length;let t=F[0]?.id,n=t!==ve.current;ve.current=t,!(e<=0)&&(_e(t=>t+e),n&&(be.current=!1))},[F.length]),(0,Q.useLayoutEffect)(()=>{let e=ye.current;if(!e)return;let t=F[0]?.id!==e.firstId,n=F.length===e.msgLen&&!t;if(t||n){if(be.current&&n){Ae(),Oe();return}ye.current=null,Ae()}},[G]);let je=!!f&&!O.open&&!P;(0,Q.useEffect)(()=>{if(!je||G>=ge)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{(0,Q.startTransition)(()=>_e(e=>e<ge?ge:e))})});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[je,G,ge,K]);let Me=je?Math.min(F.length,G):F.length;(0,Q.useEffect)(()=>{be.current=!1},[e.historyStart,e.historyTotal]);let Ne=Math.max(0,e.historyStart??0),Pe=(0,Q.useRef)(Ne);Pe.current=Ne;let Fe=Jm({isPagingActive:je,totalMessages:F.length,visibleCount:G,historyStart:Ne}),Ie=!v&&!O.open&&!P&&Fe>0,Le=je&&Me<F.length?F.slice(-Me):F,Re=(0,Q.useCallback)(t=>{if(v||b||be.current)return;be.current=!0,X(),Oe();let n=F[0]?.id,r=Pe.current;Z(t.all?{type:`load_earlier_messages`,all:!0,conversationId:e.conversationId??void 0,beforeId:n,before:r}:{type:`load_earlier_messages`,count:t.count??U,conversationId:e.conversationId??void 0,beforeId:n,before:r}),setTimeout(()=>{be.current=!1},3e3)},[v,b,F,U,X,Oe,e.conversationId]),ze=(0,Q.useCallback)(e=>{if(v)return;let t=e??U;if(X(),je&&F.length-G>=t){Oe(),_e(e=>Math.min(F.length,e+t));return}je&&F.length>G&&(Oe(),_e(F.length)),Pe.current>0&&Re({count:t})},[je,F,G,Re,U,X,Oe]),Be=(0,Q.useRef)(Ie);Be.current=Ie;let Ve=(0,Q.useRef)(ze);Ve.current=ze,(0,Q.useEffect)(()=>{let t=e.conversationId;if(!t||Y.current===t||!Ie||v)return;let n=setTimeout(()=>{Y.current!==t&&(Y.current=t,Be.current&&ze())},150);return()=>clearTimeout(n)},[e.conversationId,Ie,v,ze]);let He=!v&&(P||O.open);(0,Q.useEffect)(()=>{He&&Pe.current>0&&Re({all:!0})},[He,Re]);let Ue=(0,Q.useMemo)(()=>Av(Le,ce),[Le,ce]),We=!f&&e.messages.length>yv&&!P,Ke=(0,Q.useRef)(We);Ke.current=We;let qe=(0,Q.useMemo)(()=>We?qg(F,de.current,Math.max(Sv,ae*120)):mv,[We,F,ae]),Je=(0,Q.useMemo)(()=>{let e=new Set(qe);for(let t of Ue)t.type===`tool_cluster`&&t.messages.some(e=>qe.has(e.id))&&e.add(t.id);return e},[qe,Ue]),Ye=(0,Q.useRef)(Je);Ye.current=Je;let Xe=(0,Q.useMemo)(()=>{if(!We)return hv;let t=new Map;for(let n of e.messages)t.set(n.id,Xg(n));for(let e of Ue)if(e.type===`tool_cluster`){let n=0;for(let r of e.messages)n+=t.get(r.id)??0;t.set(e.id,n)}return t},[We,e.messages,Ue]),Ze=(0,Q.useRef)(R),Qe=R,$e=(0,Q.useRef)(K);if($e.current!==K){if($e.current=K,fe.current.clear(),!f&&e.messages.length>yv){let t=qg(e.messages,de.current,Math.max(Sv,ae*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Av(e.messages,ce))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);Qe=n,le(n),Ze.current=n}else if(R.size>0){let e=new Set;Qe=e,le(e),Ze.current=e}}Ze.current=Qe;let et=(0,Q.useRef)(Xe);et.current=Xe;let tt=Ev((0,Q.useRef)({convKey:K,pending:null,finalizedMap:new Map}).current,K,e.messages,e.streamingMessage,(e,t)=>{let n=de.current.get(e);n!==void 0&&!de.current.has(t)&&de.current.set(t,n)}),nt=(0,Q.useCallback)((e,t,n)=>{n!==void 0&&(B.current.set(e,{h:t,len:n}),de.current.set(e,t))},[]),rt=(0,Q.useCallback)((e,t)=>{nt(e,t,et.current.get(e))},[nt]),it=(0,Q.useCallback)((t=!1)=>{let n=k.current;if(!n)return;if(!Ke.current){le(e=>e.size?new Set:e);return}if(!t&&Math.abs(n.scrollTop-me.current)<200&&e.messages.length===he.current)return;me.current=n.scrollTop,he.current=e.messages.length;let r=n.getBoundingClientRect(),i={top:r.top-bv,bottom:r.bottom+bv},a={top:r.top-xv,bottom:r.bottom+xv},o=[];for(let[e,t]of fe.current){let n=t.getBoundingClientRect();o.push({id:e,top:n.top,bottom:n.bottom}),Ze.current.has(e)||nt(e,n.bottom-n.top,et.current.get(e))}let s=Gg(o,i,Ye.current,Ze.current,a);for(let e of s.hide){let t=fe.current.get(e);t&&nt(e,t.offsetHeight,et.current.get(e))}le(e=>Kg(e,s))},[nt,e.messages.length]),at=(0,Q.useCallback)(()=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,it(!0)},120),!pe.current&&(pe.current=requestAnimationFrame(()=>{pe.current=0,it(!1)}))},[it]);(0,Q.useEffect)(()=>{at()},[at,e.conversationId,e.sessionFile,e.messages.length]);let ot=(0,Q.useRef)(P);(0,Q.useLayoutEffect)(()=>{ot.current&&!P&&it(!0),ot.current=P},[P,it]);let st=(0,Q.useCallback)(e=>{e&&fe.current.set(e.dataset.lazyId??``,e)},[]);(0,Q.useEffect)(()=>{let t=new Set(e.messages.map(e=>e.id));for(let e of Ue)e.type===`tool_cluster`&&t.add(e.id);for(let e of fe.current.keys())t.has(e)||(fe.current.delete(e),de.current.delete(e),B.current.delete(e));le(e=>{let n=!1,r=new Set;for(let i of e)t.has(i)?r.add(i):n=!0;return n?r:e})},[e.messages,Ue,M]),(0,Q.useEffect)(()=>()=>{cancelAnimationFrame(pe.current),X(),H.current&&clearTimeout(H.current)},[]);let ct=(0,Q.useMemo)(()=>{let t=[];for(let n of e.messages){if(n.role!==`user`)continue;let e=n.content.map(e=>rp(e)?.text??``).filter(Boolean).join(` `),r=Xd(e),i=r?r.userMessage??`skill:${r.name}`:e.trim();i&&t.push({id:n.id,text:i})}return t},[e.messages]),lt=(0,Q.useMemo)(()=>{let e=new Map;return ct.forEach((t,n)=>e.set(t.id,n)),e},[ct]),[ut,dt]=(0,Q.useState)(-1),ft=(0,Q.useRef)(-1),pt=(0,Q.useRef)(0),mt=(0,Q.useRef)(ct);(0,Q.useEffect)(()=>{mt.current=ct},[ct]);let ht=(0,Q.useCallback)(()=>{let e=k.current,t=mt.current;if(!e||t.length===0)return;if(A.current&&!j.current){let e=t.length-1;e!==ft.current&&(ft.current=e,dt(e));return}let n=e.getBoundingClientRect().top,r=-1;for(let i=0;i<t.length;i++){let a=fe.current.get(t[i].id)??e.querySelector(`[data-msg-id="${t[i].id}"]`);if(a){if(a.getBoundingClientRect().top<=n+140)r=i;else break}}r!==ft.current&&(ft.current=r,dt(r))},[]),gt=(0,Q.useCallback)(()=>{pt.current||=requestAnimationFrame(()=>{pt.current=0,ht()})},[ht]);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(pt.current),[]),(0,Q.useEffect)(()=>{ht()},[ct,ht]);let _t=(0,Q.useCallback)(e=>{N(t=>t.has(e)?t:new Set(t).add(e))},[]);(0,Q.useLayoutEffect)(()=>{Rf(e.messages.filter(If).map(e=>({id:e.id,role:e.role,content:e.content})))},[e.messages]),(0,Q.useEffect)(()=>{if(O.open){for(let e of O.selectedIds)_t(e);z(e=>{let t=!1,n=new Set(e);for(let e of O.selectedIds)n.has(e)||(n.add(e),t=!0);return t?n:e})}},[O.open,O.selectedIds,_t]),(0,Q.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.key.toLowerCase()!==`f`)return;let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.preventDefault(),ee(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let vt=(0,Q.useCallback)(e=>{N(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),yt=(0,Q.useCallback)(e=>{if(je){let t=F.findIndex(t=>t.id===e);t!==-1&&t<F.length-G&&(0,bn.flushSync)(()=>{_e(F.length-t+5)})}(0,bn.flushSync)(()=>{_t(e),z(t=>t.has(e)?t:new Set(t).add(e))});let t=mt.current.findIndex(t=>t.id===e);ft.current=t,dt(t),requestAnimationFrame(()=>{let t=k.current?.querySelector(`[data-msg-id="${e}"]`);t&&(k.current?.querySelectorAll(`.msg-flash`).forEach(e=>e.classList.remove(`msg-flash`)),t.scrollIntoView({block:`start`}),t.classList.remove(`msg-flash`),t.offsetWidth,t.classList.add(`msg-flash`),t!==k.current?.lastElementChild&&(j.current=!0))})},[_t]),bt=(0,Q.useCallback)(t=>{let n=re.get(t);n&&r&&(yt(n),L({id:n,session:e.sessionFile}))},[re,r,yt,e.sessionFile]),[xt,St]=(0,Q.useState)(null),Ct=(0,Q.useRef)(null),wt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let t=Ct.current;if(!t||t.convId!==e.conversationId){Ct.current={convId:e.conversationId,ids:new Set(e.messages.filter(e=>e.role===`compactionSummary`).map(e=>e.id))},wt.current=null,St(null);return}for(let n of e.messages)if(n.role===`compactionSummary`&&!t.ids.has(n.id)){t.ids.add(n.id),St(n.id);break}},[e.messages,e.conversationId]),(0,Q.useEffect)(()=>{xt&&wt.current!==xt&&(wt.current=xt,yt(xt))},[xt,yt]);let Tt=(0,Q.useMemo)(()=>m?e.messages.find(e=>e.role===m.role&&e.timestamp===m.timestamp)?.id??null:null,[e.messages,m]);(0,Q.useEffect)(()=>{if(m){if(Tt){yt(Tt),h?.();return}e.sessionFile===m.path&&e.messages.length>0&&h?.()}},[Tt,yt,h,m,e.sessionFile,e.messages.length]),(0,Q.useEffect)(()=>{if(!g)return;let t=ns(e.messages,g);if(t){yt(t),_?.();return}e.messages.length>0&&_?.()},[g,e.messages,yt,_]);let{railRef:Et,stickBottom:Dt,scrollToBottom:Ot,pauseForSelection:kt,handleWheel:At,handleTouchStart:jt,handleTouchMove:Mt,handlePointerDown:Nt,onScroll:Pt}=m_({scrollRef:k,stickRef:A,escapedRef:j,messages:F,isStreaming:e.isStreaming,liveOutputs:t,toolStatuses:n,queue:e.queue,conversationId:e.conversationId,sessionFile:e.sessionFile,questions:ct,jumpTarget:m,urlJumpMessageId:g,hasEarlier:Ie,loadEarlier:ze,scheduleActiveFromScroll:gt,scheduleSweep:at}),[Ft,It]=(0,Q.useState)(0),Lt=ct.length>0;(0,Q.useLayoutEffect)(()=>{let e=Et.current;if(!e)return;let t=()=>It(e.clientHeight);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[Lt,Et]),(0,Q.useEffect)(()=>(window.addEventListener(`resize`,at),()=>window.removeEventListener(`resize`,at)),[at]);let{indices:Rt,gap:zt,many:Bt}=(0,Q.useMemo)(()=>Pg(ct.length,Ft,ut),[ct.length,Ft,ut]);return(0,$.jsxs)(`div`,{className:`messages-wrap${O.open?` messages-exporting`:``}`,children:[(0,$.jsx)(fv,{rootRef:k,sessionId:e.sessionId,enabled:!O.open,onSelect:kt}),(0,$.jsxs)(`div`,{className:`messages${P||xe||Dt&&!j.current?``:` anchor-live`}`,ref:k,onScroll:Pt,onWheel:At,onTouchStart:jt,onTouchMove:Mt,onPointerDown:Nt,children:[e.messages.length===0&&!e.streamingMessage&&!p&&(0,$.jsxs)(`div`,{className:`empty-state`,children:[(0,$.jsx)(D_,{}),!b&&T&&T.length>0&&(0,$.jsx)(`div`,{className:`chat-empty-slots`,children:M_(T,E)})]}),Ue.map(o=>{if(o.type===`tool_cluster`){let s=e.streamingMessage?.id,d=(s?o.messages.some(e=>e.id===s):!1)||e.isStreaming&&o.messages.some(e=>e.id===ie),f=o.messages.some(e=>ue.has(e.id)),p=o.messages.some(e=>Je.has(e.id)),m=Qe.has(o.id),h=!se&&!o.messages.every(Ov),g=!We||d||f||p||!m,_=o.messages.filter(Ov).length>=4;return(0,$.jsx)(Mv,{id:o.id,show:g,placeholderHeight:Zg(o.id,Xe.get(o.id)??-1,B.current,jv(o.messages,se)),attachEl:st,onMeasured:rt,variant:se?`flow`:h?`contents`:`trail`,children:o.messages.map(o=>{let s=(e.streamingMessage?o.id===e.streamingMessage.id:e.isStreaming&&o.id===ie)&&(o.role===`assistant`||!o.role),d=tt.get(o.id)??o.id,f=_?s?l:!1:l;return(0,$.jsx)(pp,{uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,onUiAction:b?void 0:E,message:o,toolResults:te,liveOutputs:Tv(o)?t:pv,toolStatuses:n,streaming:s,onKillBash:b?void 0:i,onRetry:!b&&o.id===ie?a:void 0,toolsWrap:f,toolImages:u,thinkingWrap:c,isLast:o.id===ie,onEdit:b?void 0:r,readOnly:b,messageLabel:y?.get(o.id),onRollbackEdit:bt,canRollbackEdit:!b&&!!r&&re.has(o.id),questionAttachments:ne.get(o.id),editRequest:I&&I.session===e.sessionFile&&I.id===o.id?I:void 0,searchActive:P},d)})},`cluster-${tt.get(o.messages[0].id)??o.messages[0].id}`)}let s=o.message,d=Bg(s);if(d&&!M.has(s.id))return(0,$.jsx)(Fg,{message:s,onExpand:_t,summary:d.kind===`prompt`?D(`goalBarReviewing`):d.verdict===`pass`?D(`goalBarPassed`):D(`goalBarFailed`)},s.id);let f=s.role===`user`?lt.get(s.id):void 0,p=!We||Je.has(s.id)||ue.has(s.id)||!Qe.has(s.id),m=(e.streamingMessage?s.id===e.streamingMessage.id:e.isStreaming&&s.id===ie)&&(s.role===`assistant`||!s.role),h=tt.get(s.id)??s.id;return(0,$.jsx)(Wg,{id:s.id,show:p,height:Zg(s.id,Xe.get(s.id)??-1,B.current,Jg(s.role,s.customType)),containerRef:k,onMeasured:rt,lazyRef:st,children:(0,$.jsx)(pp,{uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,onUiAction:b?void 0:E,message:s,qnIndex:f,qnActive:f===void 0?void 0:f===ut,onJump:yt,toolResults:te,liveOutputs:Tv(s)?t:pv,toolStatuses:n,streaming:m,onKillBash:b?void 0:i,onRetry:!b&&s.id===ie?a:void 0,toolsWrap:l,toolImages:u,thinkingWrap:c,isLast:s.id===ie,onEdit:b?void 0:r,readOnly:b,messageLabel:y?.get(s.id),onRollbackEdit:bt,canRollbackEdit:!b&&!!r&&re.has(s.id),editRequest:I&&I.session===e.sessionFile&&I.id===s.id?I:void 0,questionAttachments:ne.get(s.id),onCollapse:d?vt:void 0,searchActive:P,autoExpand:s.id===xt},h)},h)}),e.retry&&e.isStreaming&&(0,$.jsxs)(`div`,{className:`retry-notice`,role:`status`,title:e.retry.errorMessage||void 0,children:[(0,$.jsx)(`span`,{className:`retry-pulse`}),(0,$.jsx)(`span`,{className:`retry-text`,children:e.retry.maxAttempts>0?D(`retryingApi`,{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):D(`retryingApiSoon`,{error:e.retry.errorMessage})})]}),e.compaction&&(0,$.jsx)(wv,{compaction:e.compaction}),e.isStreaming&&F.length===0&&(0,$.jsx)(`div`,{className:`streaming-wait`,children:D(`waitingResponse`)}),(e.queue.entries?.steering??e.queue.steering).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(Cv,{kind:`steer`,text:r,index:t,id:i,onRemoveQueued:b?void 0:o,onRecallQueued:b?void 0:s},i||`q-steer-${t}`)}),(e.queue.entries?.followUp??e.queue.followUp).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(Cv,{kind:`followUp`,text:r,index:t,id:i,onRemoveQueued:b?void 0:o,onRecallQueued:b?void 0:s},i||`q-fu-${t}`)}),!b&&e.actionSuggestions&&e.actionSuggestions.length>0&&(0,$.jsx)(`div`,{className:`action-suggestions`,"aria-label":D(`actionSuggestions`),children:(0,$.jsx)(`div`,{className:`action-suggestions-list`,children:e.actionSuggestions.map(t=>(0,$.jsxs)(`button`,{type:`button`,className:`action-suggestion-chip`,title:t.prompt===t.label?t.label:D(`actionSuggestionsTip`,{prompt:t.prompt}),disabled:e.isStreaming,onClick:()=>{Ot(),Z({type:`prompt`,text:t.prompt})},children:[(0,$.jsx)(`span`,{className:`action-suggestion-label`,children:t.label}),(0,$.jsx)(`span`,{className:`action-suggestion-icon`,"aria-hidden":`true`,children:`↵`})]},t.id))})})]}),!Dt&&(0,$.jsxs)(`button`,{type:`button`,className:`scroll-bottom`,title:D(`backToBottom`),"aria-label":D(`backToBottom`),onClick:Ot,children:[(0,$.jsx)(Ge,{}),(0,$.jsx)(`span`,{className:`scroll-bottom-label`,children:D(`backToBottom`)})]}),(0,$.jsx)(c_,{containerRef:k,messages:F,collapsedIds:oe,toolResults:te,onExpand:_t,onProgrammaticScroll:()=>{kt()},open:P,onClose:()=>ee(!1)}),ct.length>0&&(0,$.jsxs)(`div`,{className:`qn-rail ${Bt?`many`:``}`,ref:Et,"aria-label":D(`questionNavTitle`),style:{"--rail-gap":`${zt}px`},children:[Rt.map(e=>{let t=ct[e];return(0,$.jsx)(`button`,{type:`button`,className:`qn-bar ${e===ut?`active`:``}`,"aria-label":`${e+1}. ${t.text}`,onClick:()=>yt(t.id),children:(0,$.jsxs)(`span`,{className:`qn-bar-text`,children:[e+1,`. `,t.text]})},t.id)}),Bt&&(0,$.jsx)(`div`,{className:`qn-list`,children:ct.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`qn-list-item ${t===ut?`active`:``}`,"aria-label":`${t+1}. ${e.text}`,onClick:()=>yt(e.id),children:[(0,$.jsx)(`span`,{className:`qn-list-idx`,children:t+1}),(0,$.jsx)(`span`,{className:`qn-list-text`,children:e.text})]},e.id))})]}),(0,$.jsx)(sv,{})]})}function Pv(e,t){return t?e.trim()?`${e.replace(/\s+$/,``)}\n${t}`:t:e}function Fv(e,t,n){let r=null;return e&&e.text&&e.ts>0&&(r={text:e.text,ts:e.ts}),t&&t.text&&t.ts>(r?.ts??0)&&(r=t),!r||r.ts<=n?null:r}function Iv(e){return e.mode===`quote`&&e.quote?`quote:${JSON.stringify([e.quote.sessionId??``,e.quote.messageId,e.quote.role,e.quote.text])}`:e.key?`key:${e.key}`:e.mode===`conversation`?e.conversationId?`conv:id:${e.conversationId}`:e.sessionPath?`conv:path:${e.sessionPath}`:null:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`:null}function Lv(e,t){return t?e?{key:t,clear:e!==t}:{key:t,clear:!1}:{key:e,clear:!1}}function Rv(e,t){if(t.length===0)return e;if(e.length===0)return[...t];let n=new Set(e.map(Iv).filter(e=>e!==null)),r=[...e];for(let e of t){let t=Iv(e);if(t!==null){if(n.has(t))continue;n.add(t)}r.push(e)}return r}function zv(e,t,n,r,i=!1){return!e||!e.trim()?!1:!!(t||i)}function Bv(e,t){if(!t||!t.trim())return!1;let n=e.trim();return!(!n||n===t.trim())}function Vv(e,t,n){switch(n){case`cancel`:return null;case`append`:return Pv(e,t);case`overwrite`:return t}}function Hv(e){let t=Number.parseFloat(getComputedStyle(e).lineHeight)||0;return t>0?Math.max(2,t/2):2}var Uv=``;function Wv(e,t,n=1){return{first:e<=n,last:Math.abs(t-e)<=n}}function Gv(e,t){return{first:!e.slice(0,t).includes(`
|
|
65
|
+
`)}var x_=[{id:`setup-matt-pocock-skills`,icon:`🛠`,titleKey:`tpl.sk.setup`,descKey:`tpl.sk.setup.desc`,promptKey:`tpl.sk.setup.prompt`},{id:`ask-matt`,icon:`🧭`,titleKey:`tpl.sk.ask`,descKey:`tpl.sk.ask.desc`,promptKey:`tpl.sk.ask.prompt`},{id:`grill-with-docs`,icon:`🗣`,titleKey:`tpl.sk.grilldocs`,descKey:`tpl.sk.grilldocs.desc`,promptKey:`tpl.sk.grilldocs.prompt`},{id:`to-spec`,icon:`📝`,titleKey:`tpl.sk.tospec`,descKey:`tpl.sk.tospec.desc`,promptKey:`tpl.sk.tospec.prompt`},{id:`to-tickets`,icon:`🎫`,titleKey:`tpl.sk.totickets`,descKey:`tpl.sk.totickets.desc`,promptKey:`tpl.sk.totickets.prompt`},{id:`implement`,icon:`🏗`,titleKey:`tpl.sk.implement`,descKey:`tpl.sk.implement.desc`,promptKey:`tpl.sk.implement.prompt`},{id:`code-review`,icon:`🧹`,titleKey:`tpl.sk.codeview`,descKey:`tpl.sk.codeview.desc`,promptKey:`tpl.sk.codeview.prompt`},{id:`wayfinder`,icon:`🗺`,titleKey:`tpl.sk.wayfinder`,descKey:`tpl.sk.wayfinder.desc`,promptKey:`tpl.sk.wayfinder.prompt`},{id:`prototype`,icon:`🔬`,titleKey:`tpl.sk.prototype`,descKey:`tpl.sk.prototype.desc`,promptKey:`tpl.sk.prototype.prompt`},{id:`research`,icon:`📚`,titleKey:`tpl.sk.research`,descKey:`tpl.sk.research.desc`,promptKey:`tpl.sk.research.prompt`},{id:`improve-codebase-architecture`,icon:`🏛`,titleKey:`tpl.sk.arch`,descKey:`tpl.sk.arch.desc`,promptKey:`tpl.sk.arch.prompt`},{id:`diagnosing-bugs`,icon:`🐛`,titleKey:`tpl.sk.debug`,descKey:`tpl.sk.debug.desc`,promptKey:`tpl.sk.debug.prompt`},{id:`resolving-merge-conflicts`,icon:`🔀`,titleKey:`tpl.sk.merge`,descKey:`tpl.sk.merge.desc`,promptKey:`tpl.sk.merge.prompt`},{id:`triage`,icon:`🗂`,titleKey:`tpl.sk.triage`,descKey:`tpl.sk.triage.desc`,promptKey:`tpl.sk.triage.prompt`},{id:`wizard`,icon:`✨`,titleKey:`tpl.sk.wizard`,descKey:`tpl.sk.wizard.desc`,promptKey:`tpl.sk.wizard.prompt`},{id:`grill-me`,icon:`🔍`,titleKey:`tpl.sk.grillme`,descKey:`tpl.sk.grillme.desc`,promptKey:`tpl.sk.grillme.prompt`},{id:`handoff`,icon:`🤝`,titleKey:`tpl.sk.handoff`,descKey:`tpl.sk.handoff.desc`,promptKey:`tpl.sk.handoff.prompt`},{id:`to-questionnaire`,icon:`📋`,titleKey:`tpl.sk.questionnaire`,descKey:`tpl.sk.questionnaire.desc`,promptKey:`tpl.sk.questionnaire.prompt`},{id:`teach`,icon:`🎓`,titleKey:`tpl.sk.teach`,descKey:`tpl.sk.teach.desc`,promptKey:`tpl.sk.teach.prompt`},{id:`wait-what`,icon:`💬`,titleKey:`tpl.sk.ww`,descKey:`tpl.sk.ww.desc`,promptKey:`tpl.sk.ww.prompt`},{id:`writing-for-agents`,icon:`📄`,titleKey:`tpl.sk.wfa`,descKey:`tpl.sk.wfa.desc`,promptKey:`tpl.sk.wfa.prompt`},{id:`codebase-design`,icon:`🧱`,titleKey:`tpl.sk.codesign`,descKey:`tpl.sk.codesign.desc`,promptKey:`tpl.sk.codesign.prompt`},{id:`domain-modeling`,icon:`🏷`,titleKey:`tpl.sk.domain`,descKey:`tpl.sk.domain.desc`,promptKey:`tpl.sk.domain.prompt`},{id:`grilling`,icon:`🔥`,titleKey:`tpl.sk.grilling`,descKey:`tpl.sk.grilling.desc`,promptKey:`tpl.sk.grilling.prompt`},{id:`tdd`,icon:`🧪`,titleKey:`tpl.sk.tdd`,descKey:`tpl.sk.tdd.desc`,promptKey:`tpl.sk.tdd.prompt`}],S_=`pi-web-ui:prompt-templates`;function C_(){try{let e=localStorage.getItem(S_);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[]}catch{return[]}}function w_(e){return x_.some(t=>t.id===e)}function T_(e){return typeof e.title==`string`}var E_=(0,Q.createContext)(null);function D_(){let e=(0,Q.useContext)(E_);if(!e)throw Error(`useTemplates must be used within TemplateProvider`);return e}function O_({children:e,currentModelId:t}){let n=V(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(``),s=(0,Q.useRef)(!1),c=(0,Q.useRef)(0),l=(0,Q.useCallback)(async e=>{if(s.current)return!1;s.current=!0,c.current++;try{let t=await fetch(q(`/api/prompt-templates`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),n=await t.json();if(!t.ok)throw Error(n.error||t.statusText);if(!Array.isArray(n.templates))throw Error(`Invalid prompt templates response`);return i(n.templates),o(``),!0}catch(e){return o(String(e)),!1}finally{s.current=!1}},[]),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t=async()=>{if(s.current)return;let t=++c.current;try{let n=await fetch(q(`/api/prompt-templates`)),r=await n.json();if(!n.ok)throw Error(r.error||n.statusText);if(!Array.isArray(r.templates))throw Error(`Invalid prompt templates response`);!e&&!s.current&&t===c.current&&i(r.templates)}catch(t){e||o(String(t))}};return(async()=>{let e=C_();if(e.length&&await l({action:`migrate`,templates:e}))try{localStorage.removeItem(S_)}catch{}await t()})(),window.addEventListener(`focus`,t),()=>{e=!0,window.removeEventListener(`focus`,t)}},[l]);let b=(0,Q.useMemo)(()=>{let e=new Map,t=new Set;for(let n of r)n.hidden?t.add(n.id):(T_(n)&&!w_(n.id)||T_(n))&&e.set(n.id,n);let i=x_.filter(e=>!t.has(e.id)).map(t=>{let r=e.get(t.id);return{id:t.id,icon:r?.icon??t.icon,title:r?.title??n(t.titleKey),desc:r?.desc??n(t.descKey),command:typeof r?.command==`string`?r.command:``,prompt:r?.prompt??n(t.promptKey),builtin:!0}}),a=r.filter(e=>T_(e)&&!w_(e.id)).map(e=>({id:e.id,icon:e.icon??`📌`,title:e.title??``,desc:e.desc??``,command:typeof e.command==`string`?e.command:``,prompt:e.prompt??``}));return[...i,...a]},[r,n]),x=(0,Q.useCallback)(()=>d(!0),[]),S=(0,Q.useCallback)(e=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:e}))},[]),C=(0,Q.useCallback)((e,t=!1)=>{y(t),e?(h(!1),p({...e})):(h(!0),p({id:ht(),icon:`📌`,title:``,desc:``,prompt:``}))},[]),w=(0,Q.useCallback)(()=>{d(!1),p(null),y(!1)},[]),T=(0,Q.useCallback)(()=>{g?(l({action:`reset`}),_(!1)):_(!0)},[g,l]);(0,Q.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>_(!1),5e3);return()=>clearTimeout(e)},[g]);let E=(0,Q.useCallback)(e=>{d(!1),S(e.prompt)},[S]),D=(0,Q.useCallback)(e=>{d(!1),C(e,!0)},[C]),O=(0,Q.useCallback)(()=>{d(!1),C(void 0,!0)},[C]),k=(0,Q.useCallback)(async e=>{await l({action:`upsert`,template:e})&&(p(null),v&&(d(!0),y(!1)))},[v]),A=(0,Q.useCallback)(async e=>{await l(e.builtin?{action:`upsert`,template:{id:e.id,hidden:!0}}:{action:`remove`,id:e.id})&&(p(null),v&&(d(!0),y(!1)))},[v]),j=(0,Q.useCallback)(async e=>{await l({action:`remove`,id:e.id})&&(p(null),v&&(d(!0),y(!1)))},[v]),M=(0,Q.useMemo)(()=>({templates:b,fill:S,openPicker:x,openEdit:C,resetConfirm:g,toggleReset:T}),[b,S,x,C,g,T]),N=f?r.some(e=>e.id===f.id&&!e.hidden&&T_(e)):!1;return(0,$.jsxs)(E_.Provider,{value:M,children:[e,a&&(0,$.jsxs)(`div`,{className:`template-error`,role:`alert`,children:[n(`tpl.storageError`),`: `,a]}),u&&(0,$.jsx)(j_,{templates:b,resetConfirm:g,onFill:E,onEditTpl:D,onNew:O,onResetToggle:T,onClose:w}),f&&(0,$.jsx)(M_,{editing:f,isNew:m,hasOverride:N,storageError:a,templates:b,onDraft:p,onSave:k,onRestore:()=>j(f),onRemove:()=>A(f),onFill:()=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:f.prompt})),w()},onSend:()=>{let e=f.prompt.trim();e&&Z({type:`prompt`,text:e,queue:!1})&&(t&&Mo(t),w())},onClose:w})]})}function k_(){let e=V(),{templates:t,fill:n,openEdit:r,toggleReset:i,resetConfirm:a}=D_();return(0,$.jsxs)(`div`,{className:`empty-templates`,children:[(0,$.jsxs)(`div`,{className:`empty-templates-head`,children:[(0,$.jsx)(`span`,{className:`empty-templates-title`,children:e(`tpl.title`)}),(0,$.jsx)(`span`,{className:`empty-templates-hint`,children:e(`tpl.hint`)})]}),(0,$.jsxs)(`div`,{className:`empty-templates-grid`,children:[t.map(t=>(0,$.jsx)(A_,{tpl:t,title:e(`tpl.clickCard`),onFill:()=>n(t.prompt),onEdit:()=>r(t),editTitle:e(`tpl.editTpl`)},t.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:()=>r(),title:e(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(rt,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e(`tpl.addDesc`)})]})]})]}),(0,$.jsx)(`div`,{className:`empty-templates-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:i,children:[(0,$.jsx)(d,{}),e(a?`tpl.resetConfirm`:`tpl.reset`)]})})]})}function A_({tpl:e,title:t,onFill:n,onEdit:r,editTitle:i}){let a=V();return(0,$.jsxs)(`button`,{type:`button`,className:`empty-template`,title:t,onClick:n,children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:e.icon}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e.title}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e.desc})]}),(0,$.jsx)(`span`,{className:`template-card-ops`,role:`button`,title:i??a(`tpl.editTpl`),onClick:e=>{e.stopPropagation(),r()},children:(0,$.jsx)(M,{})})]})}function j_({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:i,onResetToggle:a,onClose:o}){let s=V();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal template-picker`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-picker-top`,children:[(0,$.jsxs)(`div`,{className:`template-picker-head`,children:[(0,$.jsx)(`span`,{className:`template-picker-title`,children:s(`tpl.pickerTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:s(`close`),onClick:o,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`div`,{className:`template-picker-hint`,children:s(`tpl.pickerHint`)})]}),(0,$.jsx)(`div`,{className:`template-picker-scroll`,children:(0,$.jsxs)(`div`,{className:`template-picker-grid`,children:[e.map(e=>(0,$.jsx)(A_,{tpl:e,title:s(`tpl.clickCard`),onFill:()=>n(e),onEdit:()=>r(e),editTitle:s(`tpl.editTpl`)},e.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:i,title:s(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(rt,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:s(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:s(`tpl.addDesc`)})]})]})]})}),(0,$.jsx)(`div`,{className:`template-picker-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:a,children:[(0,$.jsx)(d,{}),s(t?`tpl.resetConfirm`:`tpl.reset`)]})})]})})}function M_({storageError:e,templates:t,editing:n,isNew:r,hasOverride:a,onDraft:o,onSave:s,onRestore:c,onRemove:l,onFill:u,onSend:d,onClose:f}){let p=V(),m=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&f()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f]),(0,Q.useEffect)(()=>{let e=m.current;if(!e)return;e.style.height=`auto`;let t=e.scrollHeight>300;e.style.height=`${Math.min(e.scrollHeight,300)}px`,e.style.overflowY=t?`auto`:`hidden`},[n.prompt]);let h=()=>{let e=n.title.trim(),r=n.prompt.trim();if(!e||!r){o({...n,error:p(`tpl.required`)});return}let i=__(n.command??``);if(i&&!v_(i)){o({...n,error:p(`tpl.commandInvalid`)});return}if(i&&t.some(e=>e.id!==n.id&&__(e.command??``)===i)){o({...n,error:p(`tpl.commandDuplicate`)});return}s({id:n.id,command:i,icon:n.icon.trim()||`📌`,title:e,desc:n.desc.trim(),prompt:r})},_=!!n.builtin&&!r;return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:f,children:(0,$.jsxs)(`div`,{className:`modal template-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-modal-head`,children:[(0,$.jsx)(`span`,{className:`template-modal-icon`,children:n.icon}),(0,$.jsx)(`span`,{className:`template-modal-badge`,children:p(_?`tpl.builtin`:`tpl.custom`)}),(0,$.jsx)(`span`,{className:`template-modal-title`,children:p(r?`tpl.newTitle`:`tpl.editTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:p(`close`),onClick:f,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`template-modal-body`,children:[(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldIcon`)}),(0,$.jsx)(`input`,{className:`template-field-input icon`,value:n.icon,maxLength:4,onChange:e=>o({...n,icon:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldTitle`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.title,placeholder:p(`tpl.fieldTitlePh`),onChange:e=>o({...n,title:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldDesc`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.desc,placeholder:p(`tpl.fieldDescPh`),onChange:e=>o({...n,desc:e.target.value})})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldCommand`)}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.command??``,placeholder:`/pr`,onChange:e=>o({...n,command:e.target.value,error:void 0})}),(0,$.jsx)(`span`,{className:`template-picker-hint`,children:p(`tpl.commandHint`)})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:p(`tpl.fieldPrompt`)}),(0,$.jsx)(`textarea`,{ref:m,className:`template-field-prompt`,value:n.prompt,placeholder:p(`tpl.fieldPromptPh`),onChange:e=>o({...n,prompt:e.target.value})})]})]}),(n.error||e)&&(0,$.jsx)(`div`,{className:`template-error`,role:`alert`,children:n.error||`${p(`tpl.storageError`)}: ${e}`}),(0,$.jsxs)(`div`,{className:`template-modal-actions`,children:[(0,$.jsxs)(`div`,{className:`template-modal-actions-left`,children:[!r&&_&&a&&(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn ghost`,title:p(`tpl.restoreTip`),onClick:c,children:p(`tpl.restore`)}),!r&&_&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:p(`tpl.removeTip`),onClick:l,children:[(0,$.jsx)(g,{}),` `,p(`tpl.remove`)]}),!r&&!_&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:p(`tpl.deleteTip`),onClick:l,children:[(0,$.jsx)(g,{}),` `,p(`tpl.delete`)]})]}),(0,$.jsxs)(`div`,{className:`template-modal-actions-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn`,onClick:h,children:p(`tpl.save`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn fill`,onClick:u,title:p(`tpl.fillTip`),children:p(`tpl.fill`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn send`,onClick:d,title:p(`tpl.sendTip`),children:[(0,$.jsx)(i,{}),` `,p(`tpl.sendNow`)]})]})]})]})})}var N_=class extends Q.Component{state={message:null};static getDerivedStateFromError(e){return{message:e instanceof Error?e.message:String(e)}}componentDidCatch(e,t){console.error(`[ui-slot] entry "${this.props.entryId??this.props.label}" in slot "${this.props.slot??`?`}" crashed:`,e,t.componentStack)}render(){if(this.state.message===null)return this.props.children;let e=`slot=${this.props.slot??`?`} entry=${this.props.entryId??this.props.label}: ${this.state.message}`;return(0,$.jsxs)(`button`,{type:`button`,className:`slot-error`,title:e,"aria-label":this.props.label,onClick:()=>console.error(`[ui-slot] ${e}`),children:[(0,$.jsx)(`span`,{"aria-hidden":!0,children:`⚠`}),(0,$.jsx)(`span`,{children:this.props.label})]})}};function P_(e,t){return!e||e.length===0?null:(0,$.jsx)(`span`,{className:`slot-toolbar`,children:e.map((e,n)=>(0,$.jsx)(N_,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:F_(e,n,t)},`${e.id}#${n}`))})}function F_(e,t,n){let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`slot-badge`,title:a,children:e.badge??i},r):e.kind===`toggle`?(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn${e.checked?` on`:``}`,title:a,"aria-label":i,"aria-pressed":!!e.checked,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r):e.kind===`progress`?(0,$.jsx)(`span`,{className:`slot-progress`,title:`${a} ${e.progress??0}%`,children:(0,$.jsx)(`progress`,{value:e.progress??0,max:100})},r):e.kind===`input`?(0,$.jsx)(`input`,{className:`slot-input`,defaultValue:e.value??``,placeholder:i,title:a,"aria-label":i,onKeyDown:t=>{t.key===`Enter`&&!t.nativeEvent.isComposing&&n?.(e,t.target.value)}},`${r}:${e.value??``}`):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>n?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn`,title:a,"aria-label":i,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r)}function I_(e,t,n){let r=[],i=[],a=!1,o=e=>{i.length!==0&&(a=!0,r.push((0,$.jsx)(`span`,{className:`slot-toolbar`,children:i.map((e,t)=>(0,$.jsx)(N_,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:F_(e,t,n)},`${e.id}#${t}`))},e)),i=[])};return e.forEach((e,n)=>{if(e.source===`host`){o(`gap${n}`);let i=t[e.id]??null;i&&(a=!0),r.push((0,$.jsx)(Q.Fragment,{children:i},e.id))}else i.push(e)}),o(`tail`),a?(0,$.jsx)($.Fragment,{children:r}):null}var L_=`#ffffff`,R_=`#1e1e1e`,z_=`.msg-actions, .msg-text-copy, .chead-copy, .stream-cursor, .msg-editor, .msg-collapse-btn, .msg-export-check, .toolcall-kill, .toolcall-open`,B_=16384;function V_(e,t=800,n=2){let r=Math.max(e,t,1);return r*n<=B_?n:+(r<=B_)}function H_(e){let t=e.trim().toLowerCase();if(!t)return null;if(t===`transparent`)return{r:0,g:0,b:0,a:0};if(t.startsWith(`#`)){let e=t.slice(1);if(e.length===3||e.length===4){let t=Number.parseInt(e[0]+e[0],16),n=Number.parseInt(e[1]+e[1],16),r=Number.parseInt(e[2]+e[2],16),i=e.length===4?Number.parseInt(e[3]+e[3],16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}if(e.length===6||e.length===8){let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16),r=Number.parseInt(e.slice(4,6),16),i=e.length===8?Number.parseInt(e.slice(6,8),16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}return null}let n=t.match(/^rgba?\(\s*([\s\S]+)\)$/);if(!n)return null;let r=n[1].trim(),i,a=1;if(r.includes(`/`)){let[e,t]=r.split(`/`);i=e.trim().split(/[\s,]+/).filter(Boolean),a=W_(t.trim())}else if(r.includes(`,`)){let e=r.split(`,`).map(e=>e.trim());e.length===4&&(a=W_(e.pop())),i=e}else i=r.split(/\s+/).filter(Boolean),i.length===4&&(a=W_(i.pop()));if(i.length!==3)return null;let o=U_(i[0]),s=U_(i[1]),c=U_(i[2]);return[o,s,c,a].some(e=>Number.isNaN(e))?null:{r:o,g:s,b:c,a}}function U_(e){return e.endsWith(`%`)?Math.round(G_(Number.parseFloat(e),0,100)*2.55):Math.round(G_(Number.parseFloat(e),0,255))}function W_(e){return e.endsWith(`%`)?G_(Number.parseFloat(e)/100,0,1):G_(Number.parseFloat(e),0,1)}function G_(e,t,n){return Math.min(n,Math.max(t,e))}function K_(e){let t=G_(Math.round(e.r),0,255),n=G_(Math.round(e.g),0,255),r=G_(Math.round(e.b),0,255);return e.a<.996?`rgba(${t}, ${n}, ${r}, ${Math.round(G_(e.a,0,1)*1e3)/1e3})`:`rgb(${t}, ${n}, ${r})`}function q_(e,t){let n=G_(e.a,0,1);return n<=0?{r:t.r,g:t.g,b:t.b,a:t.a}:n>=1?{r:e.r,g:e.g,b:e.b,a:1}:{r:e.r*n+t.r*(1-n),g:e.g*n+t.g*(1-n),b:e.b*n+t.b*(1-n),a:1}}function J_(e,t){let n=H_(t)??{r:255,g:255,b:255,a:1},r=H_(e);return!r||r.a<=.004?K_({...n,a:1}):K_(q_(r,{...n,a:1}))}function Y_(e){let t=e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b)}function X_(e){return Y_(e)>.45}function Z_(e){let t=document.createElement(`div`);t.style.cssText=`position:fixed;left:-99999px;top:0;width:8px;height:8px;pointer-events:none;background:${e}`,document.body.appendChild(t);let n=getComputedStyle(t).backgroundColor;return t.remove(),n}function Q_(){return getComputedStyle(document.documentElement).colorScheme.split(/\s+/).includes(`light`)?L_:R_}function $_(e){let t=Q_(),n=t;try{n=J_(Z_(`var(--bg)`),t)}catch{n=t}try{let e=J_(Z_(`var(--card-bg, var(--msgs-bg, var(--bg)))`),n),t=H_(e);if(t&&Y_(t)+t.a>0)return e}catch{}let r=e??null;for(;r;){let e=getComputedStyle(r).backgroundColor;if(e&&e!==`transparent`&&e!==`rgba(0, 0, 0, 0)`){let t=J_(e,n),r=H_(e);if(r&&r.a>.04)return t}r=r.parentElement}return n}function ev(e){return e instanceof HTMLElement||e instanceof SVGElement?e.style:null}function tv(e,t){let n=H_(e);return n?n.a<=.004?`transparent`:n.a>=.996?K_({...n,a:1}):K_(q_(n,{...H_(t)??{r:255,g:255,b:255,a:1},a:1})):null}function nv(e,t,n){let r=getComputedStyle(e),i=ev(t),a=n;if(i){let e=tv(r.backgroundColor,n);e===`transparent`?i.backgroundColor=`transparent`:e&&(i.backgroundColor=e,a=e);let t=tv(r.color,a);t&&t!==`transparent`&&(i.color=t);for(let[e]of[[`borderTopColor`,`border-top-color`],[`borderRightColor`,`border-right-color`],[`borderBottomColor`,`border-bottom-color`],[`borderLeftColor`,`border-left-color`],[`outlineColor`,`outline-color`],[`textDecorationColor`,`text-decoration-color`]]){let t=tv(r[e],a);t&&t!==`transparent`&&(i[e]=t)}let o=tv(r.fill,a);o&&o!==`transparent`&&r.fill!==`none`&&(i.fill=o);let s=tv(r.stroke,a);s&&s!==`transparent`&&r.stroke!==`none`&&(i.stroke=s),i.backdropFilter=`none`,i.setProperty(`-webkit-backdrop-filter`,`none`),r.mixBlendMode&&r.mixBlendMode!==`normal`&&(i.mixBlendMode=`normal`),i.caretColor=`transparent`}let o=Array.from(e.children),s=Array.from(t.children),c=Math.min(o.length,s.length);for(let e=0;e<c;e++)nv(o[e],s[e],a)}function rv(e){e.querySelectorAll(z_).forEach(e=>e.remove())}function iv(e,t={}){t.includeThinking||e.querySelectorAll(`.thinking`).forEach(e=>e.remove()),t.includeTools||e.querySelectorAll(`.toolcall`).forEach(e=>e.remove())}function av(e,t,n={}){let r=e.cloneNode(!0);return nv(e,r,t),iv(r,n),rv(r),r.classList.remove(`msg-export-selected`),r.style.margin=`0`,r.style.paddingLeft=``,r.removeAttribute(`id`),r.querySelectorAll(`[id]`).forEach(e=>e.removeAttribute(`id`)),r}async function ov(e,t={}){let{toBlob:n}=await As(async()=>{let{toBlob:e}=await import(`./es-DWMIuDU2.js`);return{toBlob:e}},[],import.meta.url),r=t.backgroundColor??$_(e),i=H_(r),a=await n(e,{pixelRatio:t.pixelRatio??2,backgroundColor:r,cacheBust:!1,style:{colorScheme:i&&!X_(i)?`dark`:`light`}});if(!a)throw Error(`toBlob returned null`);return a}function sv(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function cv(e){return document.querySelector(`.msg[data-msg-id="${sv(e)}"]`)??document.querySelector(`[data-msg-id="${sv(e)}"]`)}function lv(){let e=V(),t=Uf(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`pi-web-ui`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),b=(0,Q.useRef)(`#ffffff`);if((0,Q.useEffect)(()=>{t.open&&(d(!1),h(!1),_(``))},[t.open]),mt(()=>{Wf()},t.open),(0,Q.useLayoutEffect)(()=>{if(!t.open)return;let e=!1,n=0;p(!0);let r=()=>{if(e||!y.current)return;let i=[],a=!1;for(let e of t.selectedIds){let t=cv(e);t?i.push(t):a=!0}let o=t.includeThinking&&i.some(e=>e.querySelector(`.thinking`)&&!e.querySelector(`.thinking-body`))||t.includeTools&&i.some(e=>e.querySelector(`.toolcall`)&&!e.querySelector(`.toolcall-body`));if((a||o)&&n<12){n+=1,requestAnimationFrame(r);return}let s=i[0],c=$_(s??void 0);b.current=c;let l=document.createDocumentFragment();for(let e of i)l.appendChild(av(e,c,{includeThinking:t.includeThinking,includeTools:t.includeTools}));y.current.replaceChildren(l);let u=v.current;if(u){u.style.backgroundColor=c;let e=H_(c);if(u.style.colorScheme=e&&!X_(e)?`dark`:`light`,s){let e=getComputedStyle(s).color;e&&(u.style.color=e)}}p(!1)},i=requestAnimationFrame(()=>requestAnimationFrame(r));return()=>{e=!0,cancelAnimationFrame(i),y.current?.replaceChildren()}},[t.open,t.selectedIds,t.includeThinking,t.includeTools]),!t.open)return null;let x=async()=>{let n=v.current;if(n&&!u&&t.selectedIds.length!==0){d(!0),_(``);try{let t=V_(n.scrollHeight,n.scrollWidth);if(t===0){_(e(`exportTooLong`));return}let r=await ov(n,{backgroundColor:b.current,pixelRatio:t});await navigator.clipboard.write([new ClipboardItem({"image/png":r})]),h(!0),window.setTimeout(()=>h(!1),1500)}catch(t){let n=t instanceof Error?t.message:String(t);_(`${e(`copyFailed`)}: ${n}`)}finally{d(!1)}}};return(0,$.jsxs)(`aside`,{className:`saveimg-dock`,role:`dialog`,"aria-label":e(`saveAsImage`),children:[(0,$.jsxs)(`div`,{className:`saveimg-head`,children:[(0,$.jsx)(`span`,{className:`saveimg-title`,children:e(`saveAsImage`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),"aria-label":e(`close`),onClick:()=>Wf(),children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`p`,{className:`saveimg-hint`,children:e(`exportSelectHint`)}),(0,$.jsxs)(`div`,{className:`saveimg-body`,children:[(0,$.jsx)(`div`,{className:`saveimg-preview`,children:(0,$.jsxs)(`div`,{ref:v,className:`saveimg-card${i?` saveimg-card--border`:``}`,children:[n.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-title`,children:n.trim()}):null,(0,$.jsx)(`div`,{ref:y,className:`saveimg-card-md`}),o&&c.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-wm`,children:c.trim()}):null]})}),(0,$.jsxs)(`div`,{className:`saveimg-options`,children:[(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeTools,onChange:e=>Kf({includeTools:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeTools`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeThinking,onChange:e=>Kf({includeThinking:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeThinking`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt`,children:[(0,$.jsx)(`span`,{children:e(`imageTitle`)}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:n,onChange:e=>r(e.target.value),placeholder:e(`imageTitlePlaceholder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageBorder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageWatermark`)})]}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:c,disabled:!o,onChange:e=>l(e.target.value),placeholder:e(`imageWatermarkPlaceholder`)}),(0,$.jsxs)(`div`,{className:`saveimg-copy-row`,children:[(0,$.jsx)(`span`,{className:`saveimg-count`,children:e(`exportSelectedCount`,{n:t.selectedIds.length})}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary saveimg-copy`,onClick:()=>void x(),disabled:u||f||t.selectedIds.length===0,title:e(`copyImageBtn`),children:[u||f?(0,$.jsx)($o,{className:`saveimg-spin`}):m?(0,$.jsx)(et,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{children:e(u||f?`savingImage`:m?`copied`:`copyImageBtn`)})]})]})]}),g?(0,$.jsx)(`div`,{className:`saveimg-error`,children:g}):null]})]})}var uv=`.msg-text, .attachcard-content, .toolcall-output pre, .bashblock-output, .quote-content`,dv=`button, input, textarea, [contenteditable], .msg-meta, .msg-actions, .chead, .toolcall-output-label`;function fv(e){return e.nodeType===1?e:e.parentElement}function pv(e,t,n){if(!t||t.isCollapsed||t.rangeCount!==1)return null;let r=t.getRangeAt(0),i=fv(r.startContainer),a=fv(r.endContainer);if(!i||!a||!e.contains(i)||!e.contains(a)||!i.closest(uv)||!a.closest(uv)||i.closest(dv)||a.closest(dv))return null;let o=i.closest(`.msg[data-msg-id]`);if(!o||o!==a.closest(`.msg[data-msg-id]`))return null;for(let e of o.querySelectorAll(dv))if(r.intersectsNode(e))return null;let s=t.toString(),c=o.dataset.msgId,l=o.dataset.role;return!s.trim()||!c||!l?null:{text:s,messageId:c,role:l,...n?{sessionId:n}:{}}}function mv({rootRef:e,sessionId:t,enabled:n=!0,onSelect:r}){let i=V(),[a,o]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{o(null);let i=e.current;if(!i||!n)return;let a=!1,s=0,c=()=>{cancelAnimationFrame(s),o(null)},l=()=>{cancelAnimationFrame(s),s=requestAnimationFrame(()=>{let e=window.getSelection(),n=pv(i,e,t);if(!n||!e){o(null);return}let a=e.getRangeAt(0).getBoundingClientRect();if(!a.width&&!a.height){o(null);return}r?.(),o({quote:n,left:Math.max(8,Math.min(a.right-88,window.innerWidth-96)),top:Math.max(8,Math.min(a.top>=44?a.top-40:a.bottom+8,window.innerHeight-42))})})},u=e=>{e.target?.closest?.(`.quote-selection-button`)||(a=e.button===0&&i.contains(e.target),c())},d=e=>{a=!1,e.button===0&&l()},f=()=>{a||l()},p=e=>{e.key===`Escape`&&c()};return document.addEventListener(`mousedown`,u),document.addEventListener(`mouseup`,d),document.addEventListener(`selectionchange`,f),document.addEventListener(`keydown`,p),window.addEventListener(`scroll`,c,!0),window.addEventListener(`resize`,c),window.addEventListener(`blur`,c),()=>{cancelAnimationFrame(s),document.removeEventListener(`mousedown`,u),document.removeEventListener(`mouseup`,d),document.removeEventListener(`selectionchange`,f),document.removeEventListener(`keydown`,p),window.removeEventListener(`scroll`,c,!0),window.removeEventListener(`resize`,c),window.removeEventListener(`blur`,c)}},[e,t,n,r]),!a||!n||a.quote.sessionId!==t?null:(0,bn.createPortal)((0,$.jsxs)(`button`,{type:`button`,className:`quote-selection-button`,style:{left:a.left,top:a.top},onMouseDown:e=>e.preventDefault(),onClick:()=>{Ft({attachments:[{path:``,name:i(`quoteText`),mode:`quote`,quote:a.quote,key:ht()}]})&&(o(null),window.getSelection()?.removeAllRanges(),Xt())},children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),` `,i(`quoteSelection`)]}),document.body)}var hv=new Map,gv=new Set,_v=new Map,vv=15,yv=5,bv=100,xv=30,Sv=1200,Cv=2400,wv=1600;function Tv({kind:e,text:t,index:n,id:r,onRemoveQueued:i,onRecallQueued:a}){let o=V(),s=_s(t);return(0,$.jsxs)(`div`,{className:`msg msg-user msg-queued`,"data-role":`user`,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:o(`role.user`)}),(0,$.jsx)(`span`,{className:`queued-tag ${e===`steer`?`steer`:`follow`}`,children:o(e===`steer`?`queueSteerTag`:`queueFollowTag`)}),(0,$.jsxs)(`div`,{className:`msg-queued-actions`,children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-recall`,title:o(`queueRecallTip`),"aria-label":o(`queueRecallTip`),onClick:()=>a(e,t,n,r),children:`↩`}),i&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-remove`,title:o(`queueRemoveTip`),"aria-label":o(`queueRemoveTip`),onClick:()=>i(e,t,n,r),children:`✕`})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:(0,$.jsxs)(`div`,{className:`msg-text`,children:[s.quotes.map((e,t)=>(0,$.jsx)(Ss,{quote:e},`quote-${t}`)),s.attachments&&s.attachments.length>0&&(0,$.jsx)(`div`,{className:`queued-attachments`,children:s.attachments.map((e,t)=>(0,$.jsxs)(`span`,{className:`queued-att-chip`,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:e.type===`image`||e.type===`vision-bridge`?`🖼️`:e.type===`folder`?`📁`:e.type===`page`?`🌐`:e.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:e.name})]},`att-${t}`))}),s.text?(0,$.jsx)(sl,{text:s.text,hardBreaks:!0}):null]})})]})}function Ev({compaction:e}){let t=V(),[,n]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let e=setInterval(()=>n(e=>e+1),1e3);return()=>clearInterval(e)},[]);let r=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),i=e.reason===`manual`?t(`compactingReasonManual`):e.reason===`overflow`?t(`compactingReasonOverflow`):t(`compactingReasonThreshold`);return(0,$.jsxs)(`div`,{className:`compact-notice`,role:`status`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsxs)(`span`,{className:`compact-text`,children:[t(`compactingContext`),` · `,r,`s`]}),(0,$.jsx)(`span`,{className:`compact-reason`,children:i})]})}function Dv(e){return e.content.some(e=>e.type===`toolCall`)}function Ov(e,t,n,r,i){if(e.convKey!==t&&(e.convKey=t,e.pending=null,e.finalizedMap.clear()),e.pending&&r?.id!==e.pending.streamKey){let{index:t,streamKey:r}=e.pending;for(let a=Math.max(0,t);a<n.length;a++){let t=n[a];if(t.role===`assistant`&&!e.finalizedMap.has(t.id)){e.finalizedMap.set(t.id,r),i?.(r,t.id);break}}e.pending=null}return r&&e.pending?.streamKey!==r.id&&(e.pending={index:n.length,streamKey:r.id}),e.finalizedMap}function kv(e){return Array.isArray(e.content)?e.content.some(e=>{let t=ap(e);return t&&t.text.trim().length>0}):!1}function Av(e){return e.role&&e.role!==`assistant`||e.customType||!Array.isArray(e.content)||e.content.length===0||kv(e)?!1:e.content.some(e=>e.type===`toolCall`||e.type===`thinking`)}function jv(e){return e.customType?!1:e.role===`assistant`||!e.role}function Mv(e,t){let n=!!t?.mergeTurns,r=[],i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a.role===`system`||a.role===`toolResult`)continue;let o=Hg(a),s=jv(a),c=Av(a),l=!c&&!!i&&s&&!o&&t===e.length-1&&!kv(a);!o&&(n?s:c||l)?i?i.messages.push(a):(i={type:`tool_cluster`,id:`cluster-${a.id}`,messages:[a]},r.push(i)):(i=null,r.push({type:`single`,message:a}))}return r}function Nv(e,t=!1){return t?Math.max(48,Math.ceil(e.length/4)*30):Math.max(48,e.length*52)}var Pv=(0,Q.memo)(function({id:e,show:t,placeholderHeight:n,attachEl:r,onMeasured:i,variant:a=`trail`,children:o}){let s=(0,Q.useRef)(null);return(0,Q.useLayoutEffect)(()=>{if(!t)return;let n=s.current;if(!n)return;let r=Array.from(n.children,e=>e.getBoundingClientRect()),o=a===`contents`&&r.length?Math.max(...r.map(e=>e.bottom))-Math.min(...r.map(e=>e.top)):n.offsetHeight;o>0&&i?.(e,o)},[t,e,i,a]),t?(0,$.jsx)(`div`,{ref:e=>{s.current=e,r(e)},className:a===`flow`?`flow-turn`:a===`trail`?`turn-tools-trail`:void 0,style:a===`contents`?{display:`contents`}:void 0,"data-cluster-id":e,"data-lazy-id":e,children:o}):(0,$.jsx)(`div`,{ref:r,className:`msg-lazy-ph msg-lazy-ph-cluster`,"data-cluster-id":e,"data-lazy-id":e,style:{height:n},"aria-hidden":`true`})});function Fv({state:e,liveOutputs:t,toolStatuses:n,onEdit:r,onKillBash:i,onRetry:a,onRemoveQueued:o,onRecallQueued:s,thinkingWrap:c,toolsWrap:l,toolImages:u,keepRecent:d,reversePagination:f=!1,minimalNewChat:p=!1,jumpTarget:m,onJumpDone:h,urlJumpMessageId:g,onUrlJumpDone:_,preview:v=!1,messageLabels:y,readOnly:b=!1,uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,uiChatEmpty:T,onUiAction:E}){let D=V(),O=Uf(),k=(0,Q.useRef)(null),A=(0,Q.useRef)(!0),j=(0,Q.useRef)(!1),[M,N]=(0,Q.useState)(()=>new Set),[P,ee]=(0,Q.useState)(!1),F=(0,Q.useMemo)(()=>e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,[e.messages,e.streamingMessage]),te=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e.messages)n.role===`toolResult`&&n.toolCallId&&t.set(n.toolCallId,n);return t},[e.messages]),ne=(0,Q.useMemo)(()=>Fg(e.messages),[e.messages]),re=(0,Q.useMemo)(()=>{let t=new Map,n;for(let r of e.messages)r.role===`user`&&(n=r.id),n&&t.set(r.id,n);return t},[e.messages]),[I,L]=(0,Q.useState)(null),ie=(0,Q.useMemo)(()=>{for(let e=F.length-1;e>=0;e--)if(F[e].role!==`system`)return F[e].id;return null},[F]),ae=Math.min(bv,Math.max(yv,Math.floor(Number(d)||vv))),oe=(0,Q.useMemo)(()=>{let t=new Set;for(let n of e.messages)n.role!==`toolResult`&&Hg(n)&&!M.has(n.id)&&t.add(n.id);return t},[e.messages,M]),se=Gg(),ce=(0,Q.useMemo)(()=>({mergeTurns:!0}),[]),[R,le]=(0,Q.useState)(()=>{if(f||e.messages.length<=xv)return new Set;let t=Yg(e.messages,new Map,Math.max(wv,ae*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Mv(e.messages,ce))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);return n}),[ue,z]=(0,Q.useState)(()=>new Set),de=(0,Q.useRef)(new Map),B=(0,Q.useRef)(new Map),fe=(0,Q.useRef)(new Map),pe=(0,Q.useRef)(0),me=(0,Q.useRef)(0),he=(0,Q.useRef)(0),H=(0,Q.useRef)(null),ge=Math.max(se?240:60,ae*2),U=se?120:30,W=Math.min(ge,10),[G,_e]=(0,Q.useState)(()=>W),K=`${e.conversationId??``}:${e.sessionFile??``}`,q=(0,Q.useRef)(K),J=(0,Q.useRef)(F.length),ve=(0,Q.useRef)(F[0]?.id),Y=(0,Q.useRef)(null),ye=(0,Q.useRef)(null),be=(0,Q.useRef)(!1),[xe,Se]=(0,Q.useState)(!1),Ce=(0,Q.useRef)(!1),we=(0,Q.useCallback)(e=>{Ce.current=e,Se(e)},[]),Te=(0,Q.useRef)(0),Ee=(0,Q.useRef)(null),De=(0,Q.useCallback)(()=>{let e=k.current;if(!e)return null;let t=e.getBoundingClientRect().top,n=e.querySelectorAll(`[data-lazy-id]`);for(let e=0;e<n.length;e++){let r=n[e],i=r.getBoundingClientRect();if(i.bottom>t+2)return{id:r.dataset.lazyId??null,top:i.top-t}}return null},[]),X=(0,Q.useCallback)(()=>{Te.current&&=(cancelAnimationFrame(Te.current),0),Ee.current=null},[]),Oe=(0,Q.useCallback)(()=>{let e=k.current,t=De();ye.current={sh:e?e.scrollHeight:0,st:e?e.scrollTop:0,id:t?.id??null,top:t?.top??0,msgLen:F.length,firstId:F[0]?.id}},[De,F]),ke=(0,Q.useCallback)(e=>{let t=k.current;if(t){if(e.id){let n=null;try{n=t.querySelector(`[data-lazy-id="`+CSS.escape(e.id)+`"]`)}catch{n=null}if(n){let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top-e.top;r!==0&&(t.scrollTop+=r);return}}t.scrollTop=e.st+(t.scrollHeight-e.sh)}},[]),Ae=(0,Q.useCallback)(()=>{let e=ye.current,t=k.current;if(!t||!e)return;X(),we(!0),ke(e);let n=De();Ee.current={id:n?.id??null,top:n?.top??0,sh:t.scrollHeight,st:t.scrollTop};let r=0,i=0,a=()=>{Te.current=0;let e=k.current,t=Ee.current;if(!e||!t){we(!1);return}if(Math.abs(e.scrollTop-t.st)>2){let t=De();Ee.current={id:t?.id??null,top:t?.top??0,sh:e.scrollHeight,st:e.scrollTop},i=0}else{let n=0,r=!1;if(t.id){let i=null;try{i=e.querySelector(`[data-lazy-id="`+CSS.escape(t.id)+`"]`)}catch{i=null}i&&(r=!0,n=i.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top)}if(r)n!==0&&(e.scrollTop+=n),Ee.current={...t,sh:e.scrollHeight,st:e.scrollTop};else{n=e.scrollHeight-t.sh;let r=De();n!==0&&(e.scrollTop+=n),Ee.current={id:r?.id??null,top:r?.top??0,sh:e.scrollHeight,st:e.scrollTop}}i=n===0?i+1:0}if(r++,i>=3&&r>=4||r>=30){Ee.current=null,we(!1);return}Te.current=requestAnimationFrame(a)};Te.current=requestAnimationFrame(a)},[X,De,ke,we]);q.current!==K&&(q.current=K,Y.current=null,_e(W),J.current=F.length,ve.current=F[0]?.id,ye.current=null,X(),Ce.current&&we(!1),be.current=!1),(0,Q.useLayoutEffect)(()=>{let e=F.length-J.current;J.current=F.length;let t=F[0]?.id,n=t!==ve.current;ve.current=t,!(e<=0)&&(_e(t=>t+e),n&&(be.current=!1))},[F.length]),(0,Q.useLayoutEffect)(()=>{let e=ye.current;if(!e)return;let t=F[0]?.id!==e.firstId,n=F.length===e.msgLen&&!t;if(t||n){if(be.current&&n){Ae(),Oe();return}ye.current=null,Ae()}},[G]);let je=!!f&&!O.open&&!P;(0,Q.useEffect)(()=>{if(!je||G>=ge)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{(0,Q.startTransition)(()=>_e(e=>e<ge?ge:e))})});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[je,G,ge,K]);let Me=je?Math.min(F.length,G):F.length;(0,Q.useEffect)(()=>{be.current=!1},[e.historyStart,e.historyTotal]);let Ne=Math.max(0,e.historyStart??0),Pe=(0,Q.useRef)(Ne);Pe.current=Ne;let Fe=Xm({isPagingActive:je,totalMessages:F.length,visibleCount:G,historyStart:Ne}),Ie=!v&&!O.open&&!P&&Fe>0,Le=je&&Me<F.length?F.slice(-Me):F,Re=(0,Q.useCallback)(t=>{if(v||b||be.current)return;be.current=!0,X(),Oe();let n=F[0]?.id,r=Pe.current;Z(t.all?{type:`load_earlier_messages`,all:!0,conversationId:e.conversationId??void 0,beforeId:n,before:r}:{type:`load_earlier_messages`,count:t.count??U,conversationId:e.conversationId??void 0,beforeId:n,before:r}),setTimeout(()=>{be.current=!1},3e3)},[v,b,F,U,X,Oe,e.conversationId]),ze=(0,Q.useCallback)(e=>{if(v)return;let t=e??U;if(X(),je&&F.length-G>=t){Oe(),_e(e=>Math.min(F.length,e+t));return}je&&F.length>G&&(Oe(),_e(F.length)),Pe.current>0&&Re({count:t})},[je,F,G,Re,U,X,Oe]),Be=(0,Q.useRef)(Ie);Be.current=Ie;let Ve=(0,Q.useRef)(ze);Ve.current=ze,(0,Q.useEffect)(()=>{let t=e.conversationId;if(!t||Y.current===t||!Ie||v)return;let n=setTimeout(()=>{Y.current!==t&&(Y.current=t,Be.current&&ze())},150);return()=>clearTimeout(n)},[e.conversationId,Ie,v,ze]);let He=!v&&(P||O.open);(0,Q.useEffect)(()=>{He&&Pe.current>0&&Re({all:!0})},[He,Re]);let Ue=(0,Q.useMemo)(()=>Mv(Le,ce),[Le,ce]),We=!f&&e.messages.length>xv&&!P,Ke=(0,Q.useRef)(We);Ke.current=We;let qe=(0,Q.useMemo)(()=>We?Yg(F,de.current,Math.max(wv,ae*120)):gv,[We,F,ae]),Je=(0,Q.useMemo)(()=>{let e=new Set(qe);for(let t of Ue)t.type===`tool_cluster`&&t.messages.some(e=>qe.has(e.id))&&e.add(t.id);return e},[qe,Ue]),Ye=(0,Q.useRef)(Je);Ye.current=Je;let Xe=(0,Q.useMemo)(()=>{if(!We)return _v;let t=new Map;for(let n of e.messages)t.set(n.id,Qg(n));for(let e of Ue)if(e.type===`tool_cluster`){let n=0;for(let r of e.messages)n+=t.get(r.id)??0;t.set(e.id,n)}return t},[We,e.messages,Ue]),Ze=(0,Q.useRef)(R),Qe=R,$e=(0,Q.useRef)(K);if($e.current!==K){if($e.current=K,fe.current.clear(),!f&&e.messages.length>xv){let t=Yg(e.messages,de.current,Math.max(wv,ae*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Mv(e.messages,ce))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);Qe=n,le(n),Ze.current=n}else if(R.size>0){let e=new Set;Qe=e,le(e),Ze.current=e}}Ze.current=Qe;let et=(0,Q.useRef)(Xe);et.current=Xe;let tt=Ov((0,Q.useRef)({convKey:K,pending:null,finalizedMap:new Map}).current,K,e.messages,e.streamingMessage,(e,t)=>{let n=de.current.get(e);n!==void 0&&!de.current.has(t)&&de.current.set(t,n)}),nt=(0,Q.useCallback)((e,t,n)=>{n!==void 0&&(B.current.set(e,{h:t,len:n}),de.current.set(e,t))},[]),rt=(0,Q.useCallback)((e,t)=>{nt(e,t,et.current.get(e))},[nt]),it=(0,Q.useCallback)((t=!1)=>{let n=k.current;if(!n)return;if(!Ke.current){le(e=>e.size?new Set:e);return}if(!t&&Math.abs(n.scrollTop-me.current)<200&&e.messages.length===he.current)return;me.current=n.scrollTop,he.current=e.messages.length;let r=n.getBoundingClientRect(),i={top:r.top-Sv,bottom:r.bottom+Sv},a={top:r.top-Cv,bottom:r.bottom+Cv},o=[];for(let[e,t]of fe.current){let n=t.getBoundingClientRect();o.push({id:e,top:n.top,bottom:n.bottom}),Ze.current.has(e)||nt(e,n.bottom-n.top,et.current.get(e))}let s=qg(o,i,Ye.current,Ze.current,a);for(let e of s.hide){let t=fe.current.get(e);t&&nt(e,t.offsetHeight,et.current.get(e))}le(e=>Jg(e,s))},[nt,e.messages.length]),at=(0,Q.useCallback)(()=>{H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{H.current=null,it(!0)},120),!pe.current&&(pe.current=requestAnimationFrame(()=>{pe.current=0,it(!1)}))},[it]);(0,Q.useEffect)(()=>{at()},[at,e.conversationId,e.sessionFile,e.messages.length]);let ot=(0,Q.useRef)(P);(0,Q.useLayoutEffect)(()=>{ot.current&&!P&&it(!0),ot.current=P},[P,it]);let st=(0,Q.useCallback)(e=>{e&&fe.current.set(e.dataset.lazyId??``,e)},[]);(0,Q.useEffect)(()=>{let t=new Set(e.messages.map(e=>e.id));for(let e of Ue)e.type===`tool_cluster`&&t.add(e.id);for(let e of fe.current.keys())t.has(e)||(fe.current.delete(e),de.current.delete(e),B.current.delete(e));le(e=>{let n=!1,r=new Set;for(let i of e)t.has(i)?r.add(i):n=!0;return n?r:e})},[e.messages,Ue,M]),(0,Q.useEffect)(()=>()=>{cancelAnimationFrame(pe.current),X(),H.current&&clearTimeout(H.current)},[]);let ct=(0,Q.useMemo)(()=>{let t=[];for(let n of e.messages){if(n.role!==`user`)continue;let e=n.content.map(e=>ap(e)?.text??``).filter(Boolean).join(` `),r=Qd(e),i=r?r.userMessage??`skill:${r.name}`:e.trim();i&&t.push({id:n.id,text:i})}return t},[e.messages]),lt=(0,Q.useMemo)(()=>{let e=new Map;return ct.forEach((t,n)=>e.set(t.id,n)),e},[ct]),[ut,dt]=(0,Q.useState)(-1),ft=(0,Q.useRef)(-1),pt=(0,Q.useRef)(0),mt=(0,Q.useRef)(ct);(0,Q.useEffect)(()=>{mt.current=ct},[ct]);let ht=(0,Q.useCallback)(()=>{let e=k.current,t=mt.current;if(!e||t.length===0)return;if(A.current&&!j.current){let e=t.length-1;e!==ft.current&&(ft.current=e,dt(e));return}let n=e.getBoundingClientRect().top,r=-1;for(let i=0;i<t.length;i++){let a=fe.current.get(t[i].id)??e.querySelector(`[data-msg-id="${t[i].id}"]`);if(a){if(a.getBoundingClientRect().top<=n+140)r=i;else break}}r!==ft.current&&(ft.current=r,dt(r))},[]),gt=(0,Q.useCallback)(()=>{pt.current||=requestAnimationFrame(()=>{pt.current=0,ht()})},[ht]);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(pt.current),[]),(0,Q.useEffect)(()=>{ht()},[ct,ht]);let _t=(0,Q.useCallback)(e=>{N(t=>t.has(e)?t:new Set(t).add(e))},[]);(0,Q.useLayoutEffect)(()=>{Bf(e.messages.filter(Rf).map(e=>({id:e.id,role:e.role,content:e.content})))},[e.messages]),(0,Q.useEffect)(()=>{if(O.open){for(let e of O.selectedIds)_t(e);z(e=>{let t=!1,n=new Set(e);for(let e of O.selectedIds)n.has(e)||(n.add(e),t=!0);return t?n:e})}},[O.open,O.selectedIds,_t]),(0,Q.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.key.toLowerCase()!==`f`)return;let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.preventDefault(),ee(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let vt=(0,Q.useCallback)(e=>{N(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),yt=(0,Q.useCallback)(e=>{if(je){let t=F.findIndex(t=>t.id===e);t!==-1&&t<F.length-G&&(0,bn.flushSync)(()=>{_e(F.length-t+5)})}(0,bn.flushSync)(()=>{_t(e),z(t=>t.has(e)?t:new Set(t).add(e))});let t=mt.current.findIndex(t=>t.id===e);ft.current=t,dt(t),requestAnimationFrame(()=>{let t=k.current?.querySelector(`[data-msg-id="${e}"]`);t&&(k.current?.querySelectorAll(`.msg-flash`).forEach(e=>e.classList.remove(`msg-flash`)),t.scrollIntoView({block:`start`}),t.classList.remove(`msg-flash`),t.offsetWidth,t.classList.add(`msg-flash`),t!==k.current?.lastElementChild&&(j.current=!0))})},[_t]),bt=(0,Q.useCallback)(t=>{let n=re.get(t);n&&r&&(yt(n),L({id:n,session:e.sessionFile}))},[re,r,yt,e.sessionFile]),[xt,St]=(0,Q.useState)(null),Ct=(0,Q.useRef)(null),wt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let t=Ct.current;if(!t||t.convId!==e.conversationId){Ct.current={convId:e.conversationId,ids:new Set(e.messages.filter(e=>e.role===`compactionSummary`).map(e=>e.id))},wt.current=null,St(null);return}for(let n of e.messages)if(n.role===`compactionSummary`&&!t.ids.has(n.id)){t.ids.add(n.id),St(n.id);break}},[e.messages,e.conversationId]),(0,Q.useEffect)(()=>{xt&&wt.current!==xt&&(wt.current=xt,yt(xt))},[xt,yt]);let Tt=(0,Q.useMemo)(()=>m?e.messages.find(e=>e.role===m.role&&e.timestamp===m.timestamp)?.id??null:null,[e.messages,m]);(0,Q.useEffect)(()=>{if(m){if(Tt){yt(Tt),h?.();return}e.sessionFile===m.path&&e.messages.length>0&&h?.()}},[Tt,yt,h,m,e.sessionFile,e.messages.length]),(0,Q.useEffect)(()=>{if(!g)return;let t=is(e.messages,g);if(t){yt(t),_?.();return}e.messages.length>0&&_?.()},[g,e.messages,yt,_]);let{railRef:Et,stickBottom:Dt,scrollToBottom:Ot,pauseForSelection:kt,handleWheel:At,handleTouchStart:jt,handleTouchMove:Mt,handlePointerDown:Nt,onScroll:Pt}=g_({scrollRef:k,stickRef:A,escapedRef:j,messages:F,isStreaming:e.isStreaming,liveOutputs:t,toolStatuses:n,queue:e.queue,conversationId:e.conversationId,sessionFile:e.sessionFile,questions:ct,jumpTarget:m,urlJumpMessageId:g,hasEarlier:Ie,loadEarlier:ze,scheduleActiveFromScroll:gt,scheduleSweep:at}),[Ft,It]=(0,Q.useState)(0),Lt=ct.length>0;(0,Q.useLayoutEffect)(()=>{let e=Et.current;if(!e)return;let t=()=>It(e.clientHeight);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[Lt,Et]),(0,Q.useEffect)(()=>(window.addEventListener(`resize`,at),()=>window.removeEventListener(`resize`,at)),[at]);let{indices:Rt,gap:zt,many:Bt}=(0,Q.useMemo)(()=>Ig(ct.length,Ft,ut),[ct.length,Ft,ut]);return(0,$.jsxs)(`div`,{className:`messages-wrap${O.open?` messages-exporting`:``}`,children:[(0,$.jsx)(mv,{rootRef:k,sessionId:e.sessionId,enabled:!O.open,onSelect:kt}),(0,$.jsxs)(`div`,{className:`messages${P||xe||Dt&&!j.current?``:` anchor-live`}`,ref:k,onScroll:Pt,onWheel:At,onTouchStart:jt,onTouchMove:Mt,onPointerDown:Nt,children:[e.messages.length===0&&!e.streamingMessage&&!p&&(0,$.jsxs)(`div`,{className:`empty-state`,children:[(0,$.jsx)(k_,{}),!b&&T&&T.length>0&&(0,$.jsx)(`div`,{className:`chat-empty-slots`,children:P_(T,E)})]}),Ue.map(o=>{if(o.type===`tool_cluster`){let s=e.streamingMessage?.id,d=(s?o.messages.some(e=>e.id===s):!1)||e.isStreaming&&o.messages.some(e=>e.id===ie),f=o.messages.some(e=>ue.has(e.id)),p=o.messages.some(e=>Je.has(e.id)),m=Qe.has(o.id),h=!se&&!o.messages.every(Av),g=!We||d||f||p||!m,_=o.messages.filter(Av).length>=4;return(0,$.jsx)(Pv,{id:o.id,show:g,placeholderHeight:$g(o.id,Xe.get(o.id)??-1,B.current,Nv(o.messages,se)),attachEl:st,onMeasured:rt,variant:se?`flow`:h?`contents`:`trail`,children:o.messages.map(o=>{let s=(e.streamingMessage?o.id===e.streamingMessage.id:e.isStreaming&&o.id===ie)&&(o.role===`assistant`||!o.role),d=tt.get(o.id)??o.id,f=_?s?l:!1:l;return(0,$.jsx)(hp,{uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,onUiAction:b?void 0:E,message:o,toolResults:te,liveOutputs:Dv(o)?t:hv,toolStatuses:n,streaming:s,onKillBash:b?void 0:i,onRetry:!b&&o.id===ie?a:void 0,toolsWrap:f,toolImages:u,thinkingWrap:c,isLast:o.id===ie,onEdit:b?void 0:r,readOnly:b,messageLabel:y?.get(o.id),onRollbackEdit:bt,canRollbackEdit:!b&&!!r&&re.has(o.id),questionAttachments:ne.get(o.id),editRequest:I&&I.session===e.sessionFile&&I.id===o.id?I:void 0,searchActive:P},d)})},`cluster-${tt.get(o.messages[0].id)??o.messages[0].id}`)}let s=o.message,d=Hg(s);if(d&&!M.has(s.id))return(0,$.jsx)(Lg,{message:s,onExpand:_t,summary:d.kind===`prompt`?D(`goalBarReviewing`):d.verdict===`pass`?D(`goalBarPassed`):D(`goalBarFailed`)},s.id);let f=s.role===`user`?lt.get(s.id):void 0,p=!We||Je.has(s.id)||ue.has(s.id)||!Qe.has(s.id),m=(e.streamingMessage?s.id===e.streamingMessage.id:e.isStreaming&&s.id===ie)&&(s.role===`assistant`||!s.role),h=tt.get(s.id)??s.id;return(0,$.jsx)(Kg,{id:s.id,show:p,height:$g(s.id,Xe.get(s.id)??-1,B.current,Xg(s.role,s.customType)),containerRef:k,onMeasured:rt,lazyRef:st,children:(0,$.jsx)(hp,{uiMessageActions:x,uiContextMessage:S,uiContextToolCall:C,uiToolCardFooter:w,onUiAction:b?void 0:E,message:s,qnIndex:f,qnActive:f===void 0?void 0:f===ut,onJump:yt,toolResults:te,liveOutputs:Dv(s)?t:hv,toolStatuses:n,streaming:m,onKillBash:b?void 0:i,onRetry:!b&&s.id===ie?a:void 0,toolsWrap:l,toolImages:u,thinkingWrap:c,isLast:s.id===ie,onEdit:b?void 0:r,readOnly:b,messageLabel:y?.get(s.id),onRollbackEdit:bt,canRollbackEdit:!b&&!!r&&re.has(s.id),editRequest:I&&I.session===e.sessionFile&&I.id===s.id?I:void 0,questionAttachments:ne.get(s.id),onCollapse:d?vt:void 0,searchActive:P,autoExpand:s.id===xt},h)},h)}),e.retry&&e.isStreaming&&(0,$.jsxs)(`div`,{className:`retry-notice`,role:`status`,title:e.retry.errorMessage||void 0,children:[(0,$.jsx)(`span`,{className:`retry-pulse`}),(0,$.jsx)(`span`,{className:`retry-text`,children:e.retry.maxAttempts>0?D(`retryingApi`,{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):D(`retryingApiSoon`,{error:e.retry.errorMessage})})]}),e.compaction&&(0,$.jsx)(Ev,{compaction:e.compaction}),e.isStreaming&&F.length===0&&(0,$.jsx)(`div`,{className:`streaming-wait`,children:D(`waitingResponse`)}),(e.queue.entries?.steering??e.queue.steering).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(Tv,{kind:`steer`,text:r,index:t,id:i,onRemoveQueued:b?void 0:o,onRecallQueued:b?void 0:s},i||`q-steer-${t}`)}),(e.queue.entries?.followUp??e.queue.followUp).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(Tv,{kind:`followUp`,text:r,index:t,id:i,onRemoveQueued:b?void 0:o,onRecallQueued:b?void 0:s},i||`q-fu-${t}`)}),!b&&e.actionSuggestions&&e.actionSuggestions.length>0&&(0,$.jsx)(`div`,{className:`action-suggestions`,"aria-label":D(`actionSuggestions`),children:(0,$.jsx)(`div`,{className:`action-suggestions-list`,children:e.actionSuggestions.map(t=>(0,$.jsxs)(`button`,{type:`button`,className:`action-suggestion-chip`,title:t.prompt===t.label?t.label:D(`actionSuggestionsTip`,{prompt:t.prompt}),disabled:e.isStreaming,onClick:()=>{Ot(),Z({type:`prompt`,text:t.prompt})},children:[(0,$.jsx)(`span`,{className:`action-suggestion-label`,children:t.label}),(0,$.jsx)(`span`,{className:`action-suggestion-icon`,"aria-hidden":`true`,children:`↵`})]},t.id))})})]}),!Dt&&(0,$.jsxs)(`button`,{type:`button`,className:`scroll-bottom`,title:D(`backToBottom`),"aria-label":D(`backToBottom`),onClick:Ot,children:[(0,$.jsx)(Ge,{}),(0,$.jsx)(`span`,{className:`scroll-bottom-label`,children:D(`backToBottom`)})]}),(0,$.jsx)(u_,{containerRef:k,messages:F,collapsedIds:oe,toolResults:te,onExpand:_t,onProgrammaticScroll:()=>{kt()},open:P,onClose:()=>ee(!1)}),ct.length>0&&(0,$.jsxs)(`div`,{className:`qn-rail ${Bt?`many`:``}`,ref:Et,"aria-label":D(`questionNavTitle`),style:{"--rail-gap":`${zt}px`},children:[Rt.map(e=>{let t=ct[e];return(0,$.jsx)(`button`,{type:`button`,className:`qn-bar ${e===ut?`active`:``}`,"aria-label":`${e+1}. ${t.text}`,onClick:()=>yt(t.id),children:(0,$.jsxs)(`span`,{className:`qn-bar-text`,children:[e+1,`. `,t.text]})},t.id)}),Bt&&(0,$.jsx)(`div`,{className:`qn-list`,children:ct.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`qn-list-item ${t===ut?`active`:``}`,"aria-label":`${t+1}. ${e.text}`,onClick:()=>yt(e.id),children:[(0,$.jsx)(`span`,{className:`qn-list-idx`,children:t+1}),(0,$.jsx)(`span`,{className:`qn-list-text`,children:e.text})]},e.id))})]}),(0,$.jsx)(lv,{})]})}function Iv(e,t){return t?e.trim()?`${e.replace(/\s+$/,``)}\n${t}`:t:e}function Lv(e,t,n){let r=null;return e&&e.text&&e.ts>0&&(r={text:e.text,ts:e.ts}),t&&t.text&&t.ts>(r?.ts??0)&&(r=t),!r||r.ts<=n?null:r}function Rv(e){return e.mode===`quote`&&e.quote?`quote:${JSON.stringify([e.quote.sessionId??``,e.quote.messageId,e.quote.role,e.quote.text])}`:e.key?`key:${e.key}`:e.mode===`conversation`?e.conversationId?`conv:id:${e.conversationId}`:e.sessionPath?`conv:path:${e.sessionPath}`:null:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`:null}function zv(e,t){return t?e?{key:t,clear:e!==t}:{key:t,clear:!1}:{key:e,clear:!1}}function Bv(e,t){if(t.length===0)return e;if(e.length===0)return[...t];let n=new Set(e.map(Rv).filter(e=>e!==null)),r=[...e];for(let e of t){let t=Rv(e);if(t!==null){if(n.has(t))continue;n.add(t)}r.push(e)}return r}function Vv(e,t,n,r,i=!1){return!e||!e.trim()?!1:!!(t||i)}function Hv(e,t){if(!t||!t.trim())return!1;let n=e.trim();return!(!n||n===t.trim())}function Uv(e,t,n){switch(n){case`cancel`:return null;case`append`:return Iv(e,t);case`overwrite`:return t}}function Wv(e){let t=Number.parseFloat(getComputedStyle(e).lineHeight)||0;return t>0?Math.max(2,t/2):2}var Gv=``;function Kv(e,t,n=1){return{first:e<=n,last:Math.abs(t-e)<=n}}function qv(e,t){return{first:!e.slice(0,t).includes(`
|
|
66
66
|
`),last:!e.slice(t).includes(`
|
|
67
|
-
`)}}var Kv=null;function qv(){if(Kv?.isConnected)return Kv;let e=document.createElement(`div`);e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-caret-mirror`,``);let t=e.style;return t.position=`fixed`,t.top=`0`,t.left=`-99999px`,t.visibility=`hidden`,t.pointerEvents=`none`,t.margin=`0`,t.padding=`0`,t.border=`0`,t.boxSizing=`border-box`,t.overflow=`visible`,document.body.appendChild(e),Kv=e,e}function Jv(e,t){let n=getComputedStyle(e),r=t.style;r.fontFamily=n.fontFamily,r.fontSize=n.fontSize,r.fontStyle=n.fontStyle,r.fontWeight=n.fontWeight,r.fontVariant=n.fontVariant,r.fontStretch=n.fontStretch,r.lineHeight=n.lineHeight,r.letterSpacing=n.letterSpacing,r.wordSpacing=n.wordSpacing,r.textTransform=n.textTransform,r.textIndent=n.textIndent,r.tabSize=n.tabSize,r.whiteSpace=n.whiteSpace||`pre-wrap`,r.overflowWrap=n.overflowWrap||`break-word`,r.wordBreak=n.wordBreak||`normal`,r.direction=n.direction,r.writingMode=n.writingMode,r.paddingLeft=n.paddingLeft,r.paddingRight=n.paddingRight;let i=e.clientWidth;return i>0?(r.width=`${i}px`,i):0}function Yv(e,t){e.textContent=t;let n=document.createElement(`span`);return n.textContent=Uv,e.appendChild(n),n.offsetTop}function Xv(e){let t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};let r=Gv(t,n);if(!r.first&&!r.last||typeof document>`u`||typeof getComputedStyle!=`function`)return r;let i=qv();if(Jv(e,i)<=0)return r;let a=Yv(i,t.slice(0,n)),o=Yv(i,t),s=i.offsetHeight>0;return i.textContent=``,!s&&t!==``?r:Wv(a,o,Hv(e))}function Zv(e,t){let n=[],r=e?.length??0;for(let t=0;t<r;t++){let r=e?.[t];if(!r||r.kind!==`file`)continue;let i=r.getAsFile();i&&n.push(i)}if(n.length===0&&t)for(let e=0;e<t.length;e++){let r=t[e];r&&n.push(r)}return n}var Qv=`pi-web-ui:prompt-history`,$v=`pi-web-ui:prompt-history-settings`,ey={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function ty(e){let t=ey;if(!e||typeof e!=`object`)return{...t};let n=e,r=typeof n.maxEntries==`number`?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let i=typeof n.charLimit==`number`?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(i)||i<100)&&(i=100),i>2e4&&(i=2e4);let a=typeof n.charLimitEnabled==`boolean`?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:r,charLimitEnabled:a,charLimit:i}}function ny(){try{let e=localStorage.getItem($v);return e?ty(JSON.parse(e)):{...ey}}catch{return{...ey}}}function ry(e){let t=ty(e);try{localStorage.setItem($v,JSON.stringify(t))}catch{}try{let e=oy();t.charLimitEnabled&&(e=e.map(e=>e.length>t.charLimit?e.slice(0,t.charLimit):e)),e.length>t.maxEntries&&(e=e.slice(e.length-t.maxEntries)),sy(e)}catch{}}function iy(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e&&t.push(e)}return t}function ay(e,t,n=100){let r=t.trim();if(!r||e.length>0&&e[e.length-1]===r)return e;let i=[...e,r];return i.length>n?i.slice(i.length-n):i}function oy(){try{let e=localStorage.getItem(Qv);return e?iy(JSON.parse(e)):[]}catch{return[]}}function sy(e){let t=e;for(;t;)try{localStorage.setItem(Qv,JSON.stringify(t));return}catch(e){if(!(e instanceof DOMException&&(e.name===`QuotaExceededError`||e.code===22))||t.length<=1)return;t=t.slice(Math.ceil(t.length/2))}}function cy(e){let t=e.trim();if(!t)return;let n=ny();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));let r=oy(),i=ay(r,t,n.maxEntries);i!==r&&sy(i)}function ly(){try{localStorage.removeItem(Qv)}catch{}}var uy=`skill:`,dy=/[\s\-_./:]/;function fy(e,t){let n=e.toLowerCase();return t===`skill`&&n.startsWith(`skill:`)?[n,n.slice(6)]:[n]}function py(e,t){let n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r===-1)return-1;if(r>0&&dy.test(t[r-1]))return r;n=r+1}return-1}function my(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(!n)return{tier:0,score:0};if(n.length>r.length)return null;let i=3,a=-1;if(r===n)i=0,a=0;else if(r.startsWith(n))i=1,a=0;else{let e=py(n,r);e!==-1&&(i=2,a=e)}if(a!==-1){let e=0,t=0;for(let i=0;i<n.length;i++){let n=a+i,o=n===0||dy.test(r[n-1]);i>0&&(t++,e-=t*5),o&&(e-=10),e+=n*.1}return i===0&&(e-=100),{tier:i,score:e}}let o=0,s=0,c=-1,l=0;for(;o<n.length;){let e=r.indexOf(n[o],c+1);if(e===-1)return null;let t=e===0||dy.test(r[e-1]);c===e-1?(l++,s-=l*5):(l=0,c>=0&&(s+=(e-c-1)*2)),t&&(s-=10),s+=e*.1,c=e,o++}return{tier:3,score:s}}function hy(e,t){let n=t.toLowerCase();if(!n)return[...e];let r=[];for(let t=0;t<e.length;t++){let i=e[t],a=fy(i.name,i.source),o=null;for(let e of a){let t=my(n,e);t&&(!o||t.tier<o.tier||t.tier===o.tier&&t.score<o.score)&&(o=t)}o&&r.push({cmd:i,tier:o.tier,score:o.score,index:t})}return r.sort((e,t)=>e.tier===t.tier?e.tier<3?e.index-t.index:Math.abs(e.score-t.score)>1e-6?e.score-t.score:e.index-t.index:e.tier-t.tier),r.map(e=>e.cmd)}var gy=new Set([`p`,`page`,`pages`,`web`,`网页`,`页面`]);function _y(e,t,n,r=10){if(!Array.isArray(t))return[];let i=String(n??``).toLowerCase(),a=i===``||gy.has(i),o=[];for(let n of t){if(!n||typeof n.origin!=`string`||!n.origin||n.open!==!0)continue;let t=typeof n.title==`string`&&n.title.trim()?n.title.trim():n.origin;if(!a&&!t.toLowerCase().includes(i)&&!n.origin.toLowerCase().includes(i))continue;let s=t.indexOf(` · `),c=s===-1?`page · ${t}`:`page · ${t.slice(s+3)}`;if(o.push({providerId:`host:pages`,providerLabel:e,title:c,hint:n.origin,text:t,attachments:[{path:n.origin,name:t,mode:`page`}]}),o.length>=Math.max(0,r))break}return o}function vy(e,t,n=10){if(!Array.isArray(t))return[];let r=[];for(let i of t.slice(0,Math.max(0,n))){if(!i||typeof i!=`object`)continue;let t=i;typeof t.path==`string`&&t.path&&typeof t.name==`string`&&t.name&&r.push({providerId:`host:files`,providerLabel:e,title:t.name,hint:t.path,text:`@${t.path}`,attachments:[{path:t.path,name:t.name,mode:`reference`,...t.type===`dir`?{isDir:!0}:{}}]})}return r}function yy(e,t,n,r=10){if(!Array.isArray(n))return[];let i=[];for(let a of n.slice(0,Math.max(0,r))){if(!a||typeof a!=`object`)continue;let n=a;if(typeof n.title!=`string`||!n.title.trim())continue;let r=Array.isArray(n.attachments)?n.attachments.filter(e=>!!e&&typeof e==`object`&&typeof e.path==`string`).slice(0,4).map(e=>{let t=e.mode;return{path:e.path,...typeof e.name==`string`?{name:e.name}:{},...t===`inline`||t===`reference`||t===`lines`||t===`page`?{mode:t}:{},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{}}}):void 0;i.push({providerId:e,providerLabel:t,title:n.title.trim(),...typeof n.hint==`string`&&n.hint?{hint:n.hint}:{},...typeof n.text==`string`&&n.text?{text:n.text}:{},...r?.length?{attachments:r}:{}})}return i}function by(e,t,n,r=15,i){if(!Array.isArray(t)||r<=0)return[];let a=String(n??``).toLowerCase(),o=a.startsWith(uy),s=o?a.slice(uy.length):a,c=[],l=[],u=o||s.length>=3;for(let n of t){if(n.source!==`skill`)continue;let t=n.name.startsWith(`skill:`)?n.name.slice(uy.length):n.name,r=t.toLowerCase(),a=i?i(n):n.description??``,o=a.toLowerCase(),d=(n.descriptionEn??``).toLowerCase(),f={providerId:`host:skills`,providerLabel:e,title:t,hint:a||`Skill ${t}`,text:`@skill:${t}`};s?r.includes(s)?c.push(f):u&&(o.includes(s)||d.includes(s))&&l.push(f):c.push(f)}return[...c,...l].slice(0,Math.max(0,r))}function xy(e,t,n=30){let r=String(t??``).toLowerCase(),i=e.pages??[],a=e.canvases??[],o=e.skills??[],s=e.files??[],c=e.plugins??[],l;return l=r.startsWith(`skill:`)?[...o,...a,...i,...s,...c]:[...a,...i,...o,...s,...c],l.slice(0,Math.max(0,n))}function Sy(e){return e===void 0||!(e===`@`||/[A-Za-z0-9_]/.test(e))}function Cy(e,t){let n=typeof e==`string`?e:``,r=Math.max(0,Math.min(typeof t==`number`&&Number.isFinite(t)?Math.floor(t):0,n.length)),i=n.slice(0,r),a=i.lastIndexOf(`@`);if(a===-1||!Sy(a>0?i[a-1]:void 0))return null;let o=i.slice(a+1);return/[\s@]/.test(o)?null:{start:a,query:o}}function wy(e){let t=e.query;if(!t||!t(`(pointer: coarse)`)||!t(`(hover: none)`))return!1;let n=e.userAgent??``;return!(/Windows|CrOS/i.test(n)||/Linux/i.test(n)&&!/Android/i.test(n)||/Macintosh/i.test(n)&&(e.maxTouchPoints??0)<=1)}function Ty(){return typeof window>`u`||typeof navigator>`u`||typeof window.matchMedia!=`function`?!1:wy({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}var Ey=`pi-web-send-key`;function Dy(e,t){return e===`enter`||e===`mod-enter`?e:t?`mod-enter`:`enter`}function Oy(e){return e.key===`Enter`?Dy(e.pref,!!e.isTouch)===`enter`?e.shiftKey?`newline`:`send`:(e.ctrlKey||e.metaKey)&&!e.shiftKey?`send`:`newline`:`ignore`}function ky(){try{let e=localStorage.getItem(Ey);return e===`enter`||e===`mod-enter`?e:null}catch{return null}}function Ay(e){try{localStorage.setItem(Ey,e)}catch{}jy=e;for(let e of My)e()}var jy=null,My=new Set;function Ny(e){return My.add(e),()=>{My.delete(e)}}function Py(){return jy===null&&(jy=ky()),jy}function Fy(){return(0,Q.useSyncExternalStore)(Ny,Py)}function Iy(e=Ty()){return Dy(Fy(),e)}function Ly(e,t,n){if(t<=0||!e)return null;let r=null;for(let t of n){let n=[t.mode===`page`||t.mode===`conversation`?t.name:t.path,t.name].filter(e=>typeof e==`string`&&e.trim().length>0);for(let i of n){let n=`@`+i,a=e.endsWith(n+` `);if(a||e.endsWith(n)){let e=n.length;(!r||e>r.tokenLen)&&(r={attachment:t,tokenLen:e,withSpace:a})}}}let i=-1,a=r?.attachment;if(r){let n=t-(r.withSpace?r.tokenLen+1:r.tokenLen);n>0&&/[\w.\-/]/.test(e[n-1])?(i=-1,a=void 0):i=n}if(i<0){let r=/(^|[\s(("'"“‘[【])(@[^\s@,.;:!?,。!?)\]】」]+)(\s?)$/.exec(e);if(r){i=t-r[2].length-r[3].length;let o=e.slice(i,t).trim().replace(/^@/,``),s=o.split(`/`).pop()??o;a=n.find(e=>e.path&&e.path===o)??n.find(e=>e.name&&e.name===o)??n.find(e=>e.mode!==`page`&&e.mode!==`conversation`&&e.name===s)}}return i>=0&&i<t?{tokenStart:i,...a?{attachment:a}:{}}:null}function Ry(e,t=0,n=Date.now()){return!!(e.isComposing||e.keyCode===229||t>0&&n-t<50)}function zy(){let e=(0,Q.useRef)(0);return{onCompositionEnd:()=>{e.current=Date.now()},isImeKey:t=>Ry(t,e.current)}}var By=1;function Vy(){return++By}var Hy=(0,Q.memo)(function({state:e,models:t,modelsLoading:n,onManageModels:r,providerKeys:i={},defaultModel:a,compact:o=!1,only:s,onSelectModel:c,onSelectThinking:l,direction:u=`up`}){let d=V(),f=e?.model,p=f?f.id.includes(`/`)?f.id:`${f.provider}/${f.id}`:null,[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),[b,x]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!m){x(null);return}if(t.length===0)return;let e=requestAnimationFrame(()=>{let e=y.current;e&&x(e.offsetWidth)});return()=>cancelAnimationFrame(e)},[m,t.length]);let[S,C]=(0,Q.useState)(!1),w=e?.availableThinkingLevels&&e.availableThinkingLevels.length>0?new Set(e.availableThinkingLevels):null,T=wa.map(e=>({value:e,label:d(`thinking.${e}`),supported:!w||w.has(e)})),D=e=>T.find(t=>t.value===e)?.label??e,O=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{m||(O.current=!1)},[m]),(0,Q.useEffect)(()=>{C(!1)},[t]),(0,Q.useEffect)(()=>{m&&(v.current?.querySelector(`.dd-item.active`))?.scrollIntoView({block:`nearest`})},[m,p,t.length]);let k=(0,$.jsx)(Mo,{models:t,modelsLoading:n,providerKeys:i,defaultModel:a,currentModelId:p,active:m,onEnsureModels:()=>{O.current||t.length>0||n||(O.current=!0,C(!0),Z({type:`list_models`})||C(!1))},loading:S,onRefresh:()=>{C(!0),Z({type:`list_models`})},onManageModels:r?()=>{h(!1),r()}:void 0,onPickModel:(e,t)=>{if(c){c(e),h(!1);return}t&&!t.active&&Z({type:`activate_provider_key`,provider:e.provider,keyName:t.name}),p!==e.id&&f?.id!==e.id&&Z({type:`set_model`,modelId:e.id}),h(!1)},onToggleDefault:(e,t)=>{Z(t?{type:`clear_default_model`}:{type:`set_default_model`,modelId:e.id})},isRowActive:(e,t)=>(p===e.id||f?.id===e.id||`${e.provider}/${e.id}`===p)&&(!t||t.active),listRef:v}),A=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:d(`thinkingLevel`)}),T.map(t=>(0,$.jsx)(gt,{active:e?.thinkingLevel===t.value,disabled:!t.supported,title:t.supported?void 0:d(`thinkingUnsupported`),onClick:()=>{if(l){l(t.value),_(!1);return}e?.thinkingLevel!==t.value&&Z({type:`set_thinking`,level:t.value}),_(!1)},children:t.label},t.value))]}),j=(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{}),(0,$.jsx)(`span`,{className:`chip-model`,children:f?f.name:d(`selectModel`)}),!o&&f?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:d(`vision`),children:`🖼`}),!o&&f&&(0,$.jsx)(`span`,{className:`chip-sub`,children:f.provider})]}),open:m,onOpenChange:h,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:y,menuStyle:b==null?void 0:{width:b},direction:u,children:k}),M=(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(se,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:d(`thinkingChip`,{level:e?D(e.thinkingLevel):`—`})})]}),tip:d(`thinkingLevel`),open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:A});if(s===`model`)return j;if(s===`thinking`)return M;let N=e?.thinkingLevel&&e.thinkingLevel!==`off`;return(0,$.jsxs)(`div`,{className:`model-thinking-capsule`,children:[(0,$.jsx)(_t,{className:`capsule-dropdown capsule-model-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{}),(0,$.jsx)(`span`,{className:`capsule-model-name`,children:f?f.name:d(`selectModel`)}),!o&&f?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:d(`vision`),children:`🖼`})]}),triggerClassName:`capsule-segment capsule-model`,open:m,onOpenChange:h,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:y,menuStyle:b==null?void 0:{width:b},direction:u,children:k}),(0,$.jsx)(`div`,{className:`capsule-divider`}),(0,$.jsx)(_t,{className:`capsule-dropdown capsule-thinking-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-pulse-dot ${N?`on`:``}`}),(0,$.jsx)(`span`,{className:`capsule-thinking-text`,children:e?D(e.thinkingLevel):`—`})]}),triggerClassName:`capsule-segment capsule-thinking`,open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:A})]})}),Uy=[`standard`,`ptc`,`minimal`,`cordis`],Wy={standard:`preset.standard`,minimal:`preset.minimal`,code:`preset.code`,reader:`preset.reader`,ask:`preset.ask`},Gy={standard:`preset.standardDesc`,minimal:`preset.minimalDesc`,code:`preset.codeDesc`,reader:`preset.readerDesc`,ask:`preset.askDesc`};function Ky(e){return Wy[e]??null}function qy(e){return Gy[e]??null}function Jy(e,t,n){let r=H(t),i=Ky(e.id),a=qy(e.id);return i&&a?{name:n(i),description:n(a)}:{name:r?e.name??e.id:e.nameEn??e.name??e.id,description:r?e.description:e.descriptionEn??e.description}}function Yy(e){return[...e].sort((e,t)=>{let n=Number.isSafeInteger(e.order)?e.order:Uy.indexOf(e.id),r=Number.isSafeInteger(t.order)?t.order:Uy.indexOf(t.id),i=n>=0?n:1e3,a=r>=0?r:1e3;return i===a?e.id.localeCompare(t.id):i-a})}var Xy=(0,Q.memo)(function({preset:e,presets:t,defaultPreset:n,blank:r,conversationId:i,compact:a=!1}){let o=V(),{locale:s}=Ue(),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(e?.id??n);if((0,Q.useEffect)(()=>{d(e?.id??n)},[i,e?.id,n]),t.length===0)return null;let f=e?.locked||!r,p=Yy(t),m=p.find(t=>t.id===e?.id),h=p.find(e=>e.id===u)??m,g=e=>Jy(e,s,o),_=m?g(m):void 0,y=t=>{d(t),l(!1),r&&t!==e?.id&&Z({type:`dsh_preset_select`,preset:t})};if(a){let t=_?.description??m?.id??o(`dshPreset`);return(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(v,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:f?`${t}(${o(`dshPresetLocked`)})`:t,children:[_?.name??m?.id??e?.name??o(`dshPreset`),f&&(0,$.jsx)(Oe,{style:{marginLeft:3}})]})]}),open:c&&!f,onOpenChange:l,direction:`up`,align:`left`,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(gt,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>y(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-presetbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(v,{}),o(`dshPreset`)]}),(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{title:_?.description??m?.id??``,children:[_?.name??m?.id??e?.name??`…`,f&&(0,$.jsxs)(`span`,{className:`dsh-preset-lock`,title:o(`dshPresetBlankOnly`),children:[(0,$.jsx)(Oe,{}),` `,o(`dshPresetLocked`)]})]}),open:c&&!f,onOpenChange:l,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(gt,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>y(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})}),!f&&(0,$.jsx)(`span`,{className:`dsh-preset-hint`,title:o(`dshPresetBlankOnly`),children:o(`dshPresetBlankOnly`)}),h?.id===`minimal`&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:o(`dshPresetMinimalNote`)}),(0,$.jsxs)(`button`,{type:`button`,className:`chip`,title:o(`dshPresetNewChat`),onClick:()=>{Z({type:`new_chat`,preset:h?.id??u}),Xt()},children:[(0,$.jsx)(rt,{}),` `,o(`dshPresetNewChat`)]})]})}),Zy=[`read-only`,`workspace-write-never`,`danger-full-access`],Qy=[`read-only`,`workspace-write-never`,`danger-full-access`];function $y(e){return e===`read-only`?`dshPermReadOnly`:e===`danger-full-access`?`dshPermFullAccess`:`dshPermWorkspaceWrite`}function eb(e){return e===`read-only`?`dshPermReadOnlyDesc`:e===`danger-full-access`?`dshPermFullAccessDesc`:`dshPermWorkspaceWriteDesc`}var tb=(0,Q.memo)(function({current:e,options:t,defaultPreset:n,conversationId:r,compact:i=!1}){let a=V(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{l(!1),s(!1)},[r]);let u=Zy.filter(e=>t.some(t=>t.value===e));if(u.length===0)return null;let d=e??n,f=!!e&&!u.includes(e),p=e=>{if(e===`danger-full-access`&&e!==d&&!c){l(!0);return}l(!1),s(!1),e!==d&&Z({type:`dsh_permission_set`,preset:e})};if(i){let t=a(f?`dshPermCustom`:$y(d)),r=f?e??t:a(eb(d));return(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(A,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r,children:[t,d===`danger-full-access`&&(0,$.jsx)(He,{style:{marginLeft:3}})]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},direction:`up`,align:`left`,children:[u.map(e=>(0,$.jsxs)(gt,{active:e===d,title:a(eb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a($y(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(eb(e))})]},e)),c&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:a(`dshPermConfirmFull`)})]})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-permissionbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(A,{}),a(`dshPerm`)]}),(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{title:f?e:a(eb(d)),children:[a(f?`dshPermCustom`:$y(d)),d===`danger-full-access`&&(0,$.jsxs)(`span`,{className:`dd-preset-tag warn`,children:[(0,$.jsx)(He,{}),` `,a(`dshPermFullAccessTag`)]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},children:u.map(e=>(0,$.jsxs)(gt,{active:e===d,title:a(eb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a($y(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(eb(e))})]},e))}),c&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:a(`dshPermConfirmFull`)})]})}),nb=Ty(),rb=40,ib=320,ab=`pi-web-ui:composer-height`;function ob(){return typeof window>`u`?ib:Math.max(160,Math.min(ib,Math.floor(window.innerHeight*.42)))}var sb=(0,Q.memo)(function({groupDevices:e,groupReady:t,onGroupSend:n,streaming:r,planMode:i,messages:a,slashCommands:o,modelState:s,models:c,modelsLoading:l,attachments:u,onRemoveAttachment:d,onAddImageFiles:f,onAddLocalFiles:p,onAddPathAttachment:m,fileSearch:h,onSearchFiles:g,onNotice:_,onSent:v,onManageModels:y,providerKeys:b,defaultModel:x,quickPhrases:S,quickPhrasesEnabled:w,recallDrafts:T,composerLeading:E,composerActions:D,onUiAction:O,dshPermCurrent:k,dshPermOptions:A,dshPermDefault:j,dshPreset:M,dshPresets:N,dshPresetDefault:P,dshBlank:F,conversationId:te,sessionDraft:ne,sessionId:re,preserveDraftAcrossConversations:I=!1}){let L=V(),ie=en(`ready`),ae=e?!!t:ie,oe=$t(),se=rn(),ce=!!(i&&se.planMode),{locale:R}=Ue(),le=Iy(nb),ue=le===`mod-enter`,{openPicker:z,templates:de}=T_(),B=__(de,o),fe=[...o,...B.map(e=>({name:h_(e.command??``),description:e.desc||e.title,source:`prompt`}))],pe=e=>!H(R)&&e.descriptionEn?e.descriptionEn:e.description??``,me=e=>!H(R)&&e.argumentHintEn?e.argumentHintEn:e.argumentHint??``,[he,U]=(0,Q.useState)(``),[W,G]=(0,Q.useState)(()=>{try{let e=Number(localStorage.getItem(ab));if(Number.isFinite(e)&&e>44)return Math.min(e,ib)}catch{}return null}),_e=(0,Q.useRef)(null),[K,q]=(0,Q.useState)(null),[J,Y]=(0,Q.useState)(0),ye=(0,Q.useRef)(0),xe=(0,Q.useRef)(new Map),Se=(0,Q.useRef)(``),[Ce,we]=(0,Q.useState)(!1),[Te,Ee]=(0,Q.useState)(void 0),X=(0,Q.useRef)(null),Oe=(0,Q.useRef)(null),ke=(0,Q.useRef)(null),Ae=(0,Q.useRef)(-1),je=(0,Q.useRef)(``),Me=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!T||T.length===0)return;let e=T.filter(e=>e.text&&e.seq>Me.current);e.length!==0&&(Me.current=e[e.length-1].seq,q(null),U(t=>{let n=e.reduce((e,t)=>Pv(e,t.text),t);return Se.current=n,n}),Ae.current=-1,je.current=``,requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}))},[T]),(0,Q.useEffect)(()=>{if(!e)return kt(e=>{q(null),U(t=>{let n=Pv(t,e);return Se.current=n,n}),Ae.current=-1,je.current=``,requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})}),()=>kt(null)},[]),(0,Q.useEffect)(()=>(Ot(()=>{nb||requestAnimationFrame(()=>{X.current?.focus()})}),()=>Ot(null)),[]);let Ne=(0,Q.useRef)(``);Ne.current=he,(0,Q.useEffect)(()=>{if(!e)return At(e=>{{let t=e.trim(),n=new Set([`.`,`*`,`+`,`?`,`^`,`$`,`{`,`}`,`(`,`)`,`|`,`[`,`]`,`\\`]),r=t.split(``).map(e=>n.has(e)?`\\`+e:e).join(``),i=RegExp(`(^|[\\s(("'“‘[【])`+r+`(?=[\\s,.;:!?,。!?)\\]】」]|$)`);if(t&&i.test(Ne.current))return}let t=X.current;if(!t){U(t=>{let n=t+(t&&!t.endsWith(` `)?` `:``)+e;return Se.current=n,n});return}let n=t.selectionStart??Ne.current.length,r=t.selectionEnd??Ne.current.length,i=Ne.current,a=(n>0&&!/[\s([{]$/.test(i.slice(0,n))?` `:``)+e,o=i.slice(0,n)+a+i.slice(r);Se.current=o,U(o);let s=n+a.length;requestAnimationFrame(()=>{t.focus(),t.selectionStart=t.selectionEnd=s})}),()=>At(null)},[]),(0,Q.useEffect)(()=>{if(!e)return Bt(e=>{U(t=>{let n=new Set([`.`,`*`,`+`,`?`,`^`,`$`,`{`,`}`,`(`,`)`,`|`,`[`,`]`,`\\`]),r=e.split(``).map(e=>n.has(e)?`\\`+e:e).join(``),i=RegExp(`(^|\\s)`+r+`(?:\\s|$)`,`g`),a=t.replace(i,(e,t)=>t===` `?` `:``);return a=a.replace(/ {2,}/g,` `).trim(),Se.current=a,a})}),()=>Bt(null)},[]);let Pe=2e4,Fe=re?`${te??``}${re}`:null,Ie=Fe&&re?`pi-web-ui:composer-draft:${re}`:null,Re=(0,Q.useRef)(``),ze=(0,Q.useRef)(0),Be=(0,Q.useRef)(!1),Ve=(0,Q.useRef)(0),He=(0,Q.useRef)(null),We=(0,Q.useRef)(null),Ge=(0,Q.useRef)(null),Ke=(0,Q.useRef)(I);Ke.current=I;let qe=zy(),Je=e=>{try{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return typeof n.text!=`string`||!n.text||typeof n.ts!=`number`?null:{text:n.text.slice(0,Pe),ts:n.ts}}catch{return null}},Ye=(t,n,r,i)=>{let a=r.slice(0,Pe);try{a.trim()?localStorage.setItem(n,JSON.stringify({text:a,ts:i})):localStorage.removeItem(n)}catch{}e||Z({type:`draft_update`,sessionId:t,text:a,ts:i})},Xe=()=>{He.current&&=(clearTimeout(He.current),null),Be.current&&Fe&&Ie&&re&>&&Ye(re,Ie,Re.current,ze.current)},Ze=(0,Q.useRef)(new Set),Qe=(0,Q.useRef)([]),$e=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(Qe.current=[],$e.current=Ne.current,e&&re?.startsWith(`device-group:`))return yo(re.slice(13),e=>{if(Qe.current.find(t=>t.member.id===e.id)){X.current?.focus();return}let t=X.current,n=bo(Ne.current,t?.selectionStart??Ne.current.length,e);Qe.current=po(Ne.current,n.text,Qe.current),Qe.current.push({start:n.cursor-e.name.length-2,end:n.cursor-1,member:e}),$e.current=n.text,Re.current=n.text,Ne.current=n.text,Se.current=n.text,U(n.text),requestAnimationFrame(()=>{X.current?.focus(),X.current?.setSelectionRange(n.cursor,n.cursor)})})},[re,!!e]);let et=t=>{if(e){Qe.current=po($e.current,t,Qe.current),$e.current=t;let n=new Set(lo(t,e));for(let e of Ze.current)n.has(e)||Ze.current.delete(e)}if(Re.current=t,Be.current=!0,ze.current=Date.now(),Ie){let e=t.slice(0,Pe);try{e.trim()?localStorage.setItem(Ie,JSON.stringify({text:e,ts:ze.current})):localStorage.removeItem(Ie)}catch{}}if(Fe&&re&>){He.current&&clearTimeout(He.current);let e=re,t=Ie,n=ze.current,r=Fe;He.current=setTimeout(()=>{He.current=null,r===We.current&&t&&Ye(e,t,Re.current,n)},2e3)}},tt=(e,t)=>{Ae.current=-1,U(e),it(e,t),et(e)};(0,Q.useEffect)(()=>{let e=Fe,t=re,n=Ie;return()=>{He.current&&=(clearTimeout(He.current),null);let r=Re.current;if(Be.current&&r.trim()){e&&t&&n&&Ye(t,n,r,ze.current);let i=jt(),a=i>0&&ze.current>i;Ge.current={text:r,userEditedAfterSwitch:a}}else Ge.current=null}},[Fe]),(0,Q.useEffect)(()=>{We.current=Fe;let e=Ge.current;Ge.current=null;let t=e?.text??null,n=e?.userEditedAfterSwitch??!1,r=Ie?Je(Ie):null,i=!!(ne&&ne.text?.trim()&&ne.ts>0||r&&r.text?.trim());zv(t,n,a.length,i,Ke.current)&&t!==null&&Ie&&re?(Be.current=!0,Ve.current=Date.now(),Re.current=t,ze.current=Ve.current,U(t),i||Ye(re,Ie,t,ze.current)):(Be.current=!1,Ve.current=0,Re.current=``,ze.current=0,U(``)),q(null),Ae.current=-1},[Fe]);let nt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=a.length===0,t=nt.current!==null&&nt.current!==Fe,n=nt.current===null&&e;nt.current=Fe,ae&&!nb&&(t||n)&&requestAnimationFrame(()=>{X.current?.focus()})},[Fe,a.length,ae]),(0,Q.useEffect)(()=>{if(!Fe||!Ie||Be.current||Re.current!==``)return;let e=Fv(ne&&ne.text?{text:ne.text.slice(0,Pe),ts:ne.ts}:null,Je(Ie),Ve.current);e&&(Ve.current=e.ts,Re.current=e.text,ze.current=e.ts,U(e.text),it(e.text,null))});let rt={builtin:L(`slashBuiltin`),extension:L(`slashExtension`),prompt:L(`slashPrompt`),skill:L(`slashSkill`),plugin:L(`slashPlugin`)},it=(t,n)=>{Se.current=t;let r=t.match(/^\/([^\s]*)$/);if(r&&ae&&!e){let e=r[1].toLowerCase(),t=hy(fe,e);q(t.length>0?{kind:`slash`,items:t}:null),Y(0);return}if(n===null||!ae){q(null);return}let i=Cy(t,n);if(!i){q(null);return}if(e){let t=co(e,i.query);q(t.length?{kind:`at`,start:i.start,end:n,items:t}:null),Y(0);return}let a=[];try{a=qt()}catch{a=[]}let s=++ye.current,c=t,l=i.start,u=i.query,d=l+1+u.length,f=a.map(e=>({id:e.id,label:e.label,run:()=>{let t;try{t=Wt(e.id)?.search}catch{t=void 0}return typeof t==`function`?t(u):Promise.resolve([])}}));f.push({id:`host:canvases`,label:L(`canvasTab`),run:async()=>ss(await cs(()=>Z({type:`canvas_list`})),u,L(`canvasTab`))}),u&&typeof g==`function`&&f.push({id:`host:files`,label:L(`openFiles`),run:()=>at(u)});let p=[];if(se.pageRef&&(Ln(),p=_y(L(`browserControl`),In(),u),f.push({id:`host:pages`,label:L(`browserControl`),run:()=>Promise.resolve(p)})),f.length===0){q(null);return}let m=by(L(`slashSkill`),o,u,15,pe),h=xy({pages:p,skills:m},u,30),_=!1;h.length>0&&(_=!0,q({kind:`at`,start:l,end:d,items:h}),Y(0)),Promise.allSettled(f.map(e=>Promise.race([e.run(),new Promise((e,t)=>setTimeout(()=>t(Error(`at-mention timeout`)),2e3))]))).then(e=>{if(ye.current!==s||Se.current!==c)return;let t=[],n=[],r=[],i=[];e.forEach((e,a)=>{e.status===`fulfilled`&&(f[a].id===`host:pages`&&Array.isArray(e.value)?n.push(...e.value):f[a].id===`host:canvases`&&Array.isArray(e.value)?t.push(...e.value):f[a].id===`host:files`?r.push(...vy(f[a].label,e.value)):i.push(...yy(f[a].id,f[a].label,e.value)))});let a=xy({canvases:t,pages:n,skills:m,files:r,plugins:i},u,30);q(a.length>0?{kind:`at`,start:l,end:d,items:a}:null),!_&&a.length>0&&Y(0)})},at=e=>{if(typeof g!=`function`)return Promise.resolve([]);let t=Vy();return new Promise(n=>{xe.current.set(t,n);try{g(t,e)}catch{xe.current.delete(t),n([]);return}setTimeout(()=>{xe.current.get(t)===n&&(xe.current.delete(t),n([]))},3e3)})};(0,Q.useEffect)(()=>{if(!h||!h.ok)return;let e=xe.current.get(h.reqId);e&&(xe.current.delete(h.reqId),e(h.results??[]))},[h]);let ot=e=>it(e,null);(0,Q.useEffect)(()=>{(ke.current?.querySelector(`.slash-item.active`))?.scrollIntoView({block:`nearest`})},[J,K]);let st=e=>{let t=K?.kind===`slash`?K.items:[],n=e??t[J%Math.max(t.length,1)];if(!n){q(null);return}let r=he.match(/^\/([^\s]*)([\s\S]*)$/),i=r?r[2]:``,a=`/${n.name} ${i}`;Se.current=a,U(a),et(a),q(null),X.current?.focus()},ct=(t,n)=>{let r=K?.kind===`at`?K:null,i=r?.items??[],a=t??i[J%Math.max(i.length,1)],o=n??r?.start;if(!a||o===void 0){q(null);return}let s=X.current,c=s?s.selectionStart??he.length:he.length,l=r?.end!==void 0&&r.end>=o?r.end:c,u=a.attachments??[],d=e&&a.providerId===`host:group-devices`?e.find(e=>e.id===a.hint):void 0,f=d?`@${d.name}`:a.text??a.title;e&&a.providerId===`host:group-devices`&&a.hint&&Ze.current.add(a.hint);let p=u.length>0&&!f.startsWith(`@`)?`@${f} `:`${f} `,h=`${he.slice(0,o)}${p}${he.slice(l)}`;Se.current=h,U(h),et(h),d&&Qe.current.push({start:o,end:o+f.length,member:d}),q(null);for(let e of u)try{m?.({path:e.path,name:e.name??e.path.split(`/`).pop()??e.path,...e.mode?{mode:e.mode}:{mode:`reference`},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{},...e.lines?{lines:e.lines}:{},silent:!0})}catch{}requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=o+p.length)})},lt=()=>K?.kind===`slash`?K.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===J?` active`:``}`,onMouseEnter:()=>Y(t),onClick:()=>dt(e),children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:rt[e.source]}),(0,$.jsxs)(`span`,{className:`slash-desc`,children:[pe(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:me(e)})]})]},e.name)):null,ut=()=>K?.kind===`at`?K.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===J?` active`:``}`,onMouseEnter:()=>Y(t),onClick:()=>dt(e),title:e.hint??e.title,children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`@`,e.title]}),(0,$.jsx)(`span`,{className:`slash-source ${e.providerId===`host:skills`?`skill`:`plugin`}`,children:e.providerLabel}),e.hint&&(0,$.jsx)(`span`,{className:`slash-desc`,children:e.hint})]},`${e.providerId}:${e.title}:${t}`)):null,dt=e=>{K&&(K.kind===`slash`?st(e):ct(e,K.start))},ft=async()=>{let e=[...a].reverse().find(e=>e.role===`assistant`&&e.content.some(e=>e.type===`text`&&e.text))?.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
68
|
-
`);if(!e){_(`warning`,L(`slashCopyEmpty`));return}await nc(e)?_(`info`,L(`slashCopied`)):_(`error`,L(`slashCopyFailed`))},pt=t=>{if(e)return;if(!t||t.length===0){_(`warning`,L(`foldersNotSupported`));return}let n=Array.from(t).filter(e=>$d(e.type)),r=Array.from(t).filter(e=>!$d(e.type)),i=ht();n.length>0&&i?_(`warning`,i):n.length>0&&f(n),r.length>0&&p(r)},mt=e=>{let t=Zv(e.clipboardData?.items,e.clipboardData?.files);t.length!==0&&(e.preventDefault(),pt(t))},ht=()=>{let e=s?.model;if(!e?.id)return null;let t=c.find(t=>t.id===e.id);return t&&t.vision===!1?L(`modelNoVision`,{name:t.name}):null},gt=ae,_t=ae&&!!re,vt=(0,Q.useRef)(he);(0,Q.useEffect)(()=>{vt.current=he},[he]),(0,Q.useEffect)(()=>{!e&&/^\/[^\s]*$/.test(vt.current)&&ot(vt.current)},[o]);let[yt,bt]=(0,Q.useState)(null),xt=e=>{let t=yt;if(bt(null),t===null)return;let n=Vv(vt.current,t,e);n!==null&&(q(null),Se.current=n,U(n)),requestAnimationFrame(()=>X.current?.focus())};(0,Q.useEffect)(()=>{if(e)return;let t=e=>{let t=e.detail;if(typeof t==`string`){if(Bv(vt.current,t)){bt(t);return}q(null),Se.current=t,U(t),X.current?.focus()}};return window.addEventListener(`pi-web:fill`,t),()=>window.removeEventListener(`pi-web:fill`,t)},[]),(0,Q.useEffect)(()=>{if(!Ce&&yt===null)return;let e=e=>{e.key===`Escape`&&(yt===null?we(!1):(bt(null),requestAnimationFrame(()=>X.current?.focus())))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ce,yt]);let St=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=X.current,t=St.current;if(!e||!t)return;let n=e.closest(`main`)?.querySelector(`.messages`),r=t.getBoundingClientRect().height,i=n?.scrollTop??0,a=ob();e.style.maxHeight=`${a}px`;let o=W!=null&&W>44,s;e.style.height=`auto`;let c=e.scrollHeight;s=Math.min(o?W:Math.max(c,rb),a),e.style.height=`${s}px`,e.style.overflowY=c>s?`auto`:`hidden`,n&&(n.scrollTop=i+(t.getBoundingClientRect().height-r))},[he,W]);let Ct=(0,Q.useRef)(null),wt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Ct.current,t=wt.current,n=document.documentElement;if(!e&&!t){n.style.removeProperty(`--quick-row-h`);return}let r=()=>{let r=e?e.offsetHeight:0,i=t?t.offsetHeight:0,a=e&&t?6:0;n.style.setProperty(`--quick-row-h`,`${r+a+i}px`)};r();let i=new ResizeObserver(r);return e&&i.observe(e),t&&i.observe(t),()=>{i.disconnect(),n.style.removeProperty(`--quick-row-h`)}},[u.length,w,S.length]);let Tt=()=>u.map(e=>e.mode===`quote`?{path:``,mode:`quote`,quote:e.quote}:e.imageData?{path:``,imageData:e.imageData,mimeType:e.mimeType,name:e.name}:e.fileData?{path:``,fileData:e.fileData,mimeType:e.mimeType,name:e.name,size:e.size}:{path:e.path,mode:e.mode,...e.lines?{lines:e.lines}:{},...e.mode===`page`||e.mode===`canvas`?{name:e.name}:{},...e.mode===`conversation`?{name:e.name,...e.conversationId?{conversationId:e.conversationId}:{},...e.sessionPath?{sessionPath:e.sessionPath}:{}}:{}}),Et=()=>{if(Ie)try{localStorage.removeItem(Ie)}catch{}He.current&&=(clearTimeout(He.current),null),Be.current=!1,Ve.current=Date.now(),Re.current=``,ze.current=0},Dt=(0,Q.useRef)(!1),Mt=(t=!1)=>{let r=he.trim(),i=u.length>0;if(r||i){if(!gt){_(`error`,L(`netDisconnected`));return}if(!_t){_(`warning`,L(`sessionInitializingNotice`));return}if(e){if(!n||Dt.current)return;Dt.current=!0;let t=mo(he,Qe.current);n(t.text.trim(),[...new Set([...t.targets,...lo(r,e).filter(e=>Ze.current.has(e))])]).then(e=>{e&&Re.current.trim()===r&&(U(``),Ze.current.clear(),Qe.current=[],$e.current=``,Et(),v())}).catch(e=>_(`error`,String(e))).finally(()=>{Dt.current=!1});return}if(!se.conversationRef&&u.some(e=>e.mode===`conversation`)){_(`warning`,H(R)?`当前底层智能体不支持跨对话引用(缺少 conversation_read 工具),请移除会话引用后再发送。`:`The current agent engine does not support conversation references (conversation_read tool unavailable). Remove conversation references before sending.`);return}if(r===`/help`){let e=X.current?.closest(`.inputbox`)?.getBoundingClientRect();Ee(e?.width),we(!0),U(``),Et(),X.current?.focus();return}if(r===`/copy`){U(``),Et(),X.current?.focus(),ft();return}if(Z({type:`prompt`,text:v_(r,B),queue:t,attachments:Tt()})){r&&cy(r),Ae.current=-1,je.current=``,U(``),Et(),v();let e=s?.model;e&&Ao(`${e.provider}/${e.id}`),X.current?.focus()}else _(`error`,L(`netDisconnected`))}},Nt=(t,n=!1)=>{if(e)return;let r=t.trim();if(r){if(!gt){_(`error`,L(`netDisconnected`));return}if(!_t){_(`warning`,L(`sessionInitializingNotice`));return}if(Z({type:`prompt`,text:r,queue:n,attachments:Tt()})){r&&cy(r),Ae.current=-1,je.current=``,Xe(),v();let e=s?.model;e&&Ao(`${e.provider}/${e.id}`),nb||X.current?.focus()}else _(`error`,L(`netDisconnected`))}},Pt=t=>{if(!qe.isImeKey(t.nativeEvent)){if(K&&K.items.length>0){let e=K.items.length;switch(t.key){case`ArrowDown`:t.preventDefault(),Y(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),Y(t=>(t-1+e)%e);return;case`Tab`:case`Enter`:t.preventDefault(),dt();return;case`Escape`:t.preventDefault(),q(null);return}}if(e&&(t.key===`Backspace`||t.key===`Delete`)&&!t.nativeEvent.isComposing){let e=X.current;if(e){let n=ho(he,e.selectionStart,e.selectionEnd,t.key,Qe.current);if(n){t.preventDefault();let r=he.slice(0,n.start)+he.slice(n.end);et(r),U(r),Ne.current=r,requestAnimationFrame(()=>e.setSelectionRange(n.start,n.start));return}}}if(t.key===`Backspace`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=X.current;if(e&&e.selectionStart===e.selectionEnd&&e.selectionStart>0){let n=e.selectionStart,r=Ly(he.slice(0,n),n,u);if(r&&r.tokenStart>=0&&r.tokenStart<n){t.preventDefault();let e=r.tokenStart,i=he.slice(0,e)+he.slice(n);Se.current=i,U(i),requestAnimationFrame(()=>{X.current&&(X.current.selectionStart=X.current.selectionEnd=e)});let a=r.attachment;a&&d(a.key??(a.mode===`conversation`?`conv|${a.conversationId??``}|${a.sessionPath??``}`:a.path));return}}}if(!e&&(t.key===`ArrowUp`||t.key===`ArrowDown`)){if(t.ctrlKey||t.metaKey||t.altKey)return;let e=X.current;if(!e)return;let n=t.key===`ArrowUp`,r=Xv(e);if(n&&!r.first||!n&&!r.last||!n&&Ae.current===-1)return;let i=oy();if(i.length===0)return;if(t.preventDefault(),n){if(Ae.current===-1){je.current=he;let e=i.length-1;Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else if(Ae.current>0){let e=Ae.current-1;Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}}else{let e=Ae.current+1;if(e<i.length){Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else{Ae.current=-1;let e=je.current;U(e),ot(e),requestAnimationFrame(()=>{let t=X.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}}return}if(t.key===`Escape`&&Ae.current!==-1){t.preventDefault();let e=je.current;Ae.current=-1,U(e),ot(e),requestAnimationFrame(()=>{let t=X.current;t&&(t.selectionStart=t.selectionEnd=e.length)});return}if(Oy({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,isTouch:nb,pref:le})===`send`){t.preventDefault(),Mt();return}}},Ft=_t&&(he.trim()!==``||u.length>0),It=(0,Q.useMemo)(()=>wi((D??[]).filter(e=>e.source!==`host`&&!e.hidden)),[D]),Lt=(0,Q.useMemo)(()=>(E??[]).filter(e=>e.source!==`host`&&!e.hidden),[E]),Rt=D!==void 0,zt=(0,Q.useMemo)(()=>wi((D??[]).filter(e=>!e.hidden)),[D]),Vt=e=>{if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`composer-plugin-select`,title:e.hint||e.label,"aria-label":e.label,value:t,onChange:t=>O?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id)}let t=e.icon===`mic`?(0,$.jsx)(be,{}):e.icon===`camera`?(0,$.jsx)(ve,{}):e.icon||e.label;return(0,$.jsx)(`button`,{type:`button`,className:`btn composer-plugin-action`,"data-action":e.action,"data-plugin-slot-id":e.id,title:e.hint||e.label,"aria-label":e.label,onClick:()=>O?.(e),children:t},e.id)},Ht=se.steer!==!1&&!oe,Ut=()=>(0,$.jsx)(`div`,{className:`inputbox-actions`,children:r?Ft?(0,$.jsxs)(`div`,{className:`split-send${Ht?``:` single`}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`split-queue`,title:L(`supplementTip`),"aria-label":L(`queueFollowTag`),onClick:()=>Mt(!0),children:(0,$.jsx)(ge,{})}),Ht&&(0,$.jsx)(`button`,{type:`button`,className:`split-steer`,title:L(ue?`steerTipMod`:`steerTip`),"aria-label":L(`queueSteerTag`),onClick:()=>Mt(),children:(0,$.jsx)(De,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`btn stop`,title:L(`stopAgent`),onClick:()=>Z({type:`abort`}),children:(0,$.jsx)(C,{})}):(0,$.jsx)(`button`,{type:`button`,className:`btn send`,title:L(gt?_t?ue?`sendTipMod`:`sendTip`:`sessionInitializingNotice`:`netDisconnected`),disabled:!Ft,onClick:()=>Mt(),children:(0,$.jsx)(De,{})})}),Gt={"host:composer-upload":(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:L(`uploadFile`),disabled:!gt,onClick:()=>Oe.current?.click(),children:(0,$.jsx)(ee,{})}),"host:composer-templates":(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:L(`tpl.openPicker`),onClick:z,children:(0,$.jsx)(Le,{})}),"host:composer-model":(0,$.jsx)(Hy,{only:`model`,state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,defaultModel:x,compact:!0}),"host:composer-thinking":(0,$.jsx)(Hy,{only:`thinking`,state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,compact:!0}),"host:composer-dsh-perm":A&&A.length>0&&j!==void 0?(0,$.jsx)(tb,{compact:!0,current:k??null,options:A,defaultPreset:j,conversationId:te??``}):null,"host:composer-dsh-preset":N&&N.length>0&&P!==void 0?(0,$.jsx)(Xy,{compact:!0,preset:M??null,presets:N,defaultPreset:P,blank:F??!1,conversationId:te??``}):null,"host:composer-send":Ut()},Kt=e=>e.source===`host`?(0,$.jsx)(Q.Fragment,{children:Gt[e.id]??null},e.id):Vt(e);return(0,$.jsxs)(`div`,{ref:St,className:`inputbar`,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault(),e.stopPropagation(),pt(e.dataTransfer?.files??null)},children:[u.length>0&&(0,$.jsxs)(`div`,{className:`attach-row`,ref:Ct,children:[u.map(e=>e.mode===`quote`&&e.quote?(0,$.jsx)(bs,{quote:e.quote,onRemove:()=>d(e.key??``)},e.key):(0,$.jsxs)(`span`,{className:`attach-chip ${e.imageData?`image`:e.fileData?`file`:e.mode}`,title:e.imageData?L(`attachImage`,{name:e.name}):e.fileData?L(`attachFile`,{name:e.name}):e.isDir?L(`folderRef`,{path:e.path}):e.mode===`page`?L(`attachPage`,{name:e.name}):e.mode===`canvas`?`${L(`canvasTab`)} · ${e.name}`:e.mode===`conversation`?L(`attachConversation`,{name:e.name}):e.mode===`reference`?L(`refOnly`,{path:e.path}):e.mode===`lines`&&e.lines?L(`attachLines`,{path:e.path,start:e.lines.start,end:e.lines.end}):L(`attachContent`,{path:e.path}),children:[e.imageData?`🖼`:e.fileData?`📄`:e.isDir?`📁`:e.mode===`page`?`🌐`:e.mode===`canvas`?`◇`:e.mode===`conversation`?`💬`:e.mode===`reference`?`🔗`:`📎`,e.name,e.mode===`lines`&&e.lines&&(0,$.jsxs)(`span`,{className:`attach-range`,children:[`L`,e.lines.start,`-`,e.lines.end]}),(0,$.jsx)(`button`,{type:`button`,className:`attach-remove`,title:L(`removeAttachment`),onClick:()=>d(e.key??(e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:e.path)),children:`×`})]},e.key??(e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`))),(0,$.jsx)(`span`,{className:`attach-hint`,children:L(`attachHint`)})]}),K&&K.items.length>0&&(0,$.jsxs)(`div`,{className:`slash-menu`,role:`listbox`,ref:ke,"aria-label":K.kind===`slash`?L(`slashCommands`):L(`atMentions`),"data-menu-kind":K.kind,children:[(0,$.jsxs)(`div`,{className:`slash-menu-hint`,children:[(0,$.jsx)(`span`,{children:K.kind===`slash`?L(`slashMenuHint`):L(`atMenuHint`)}),(0,$.jsx)(`span`,{className:`slash-menu-close`,onClick:()=>q(null),children:`Esc`})]}),K.kind===`slash`?lt():ut()]}),yt!==null&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>xt(`cancel`),children:(0,$.jsxs)(`div`,{className:`slash-help`,role:`dialog`,"aria-modal":`true`,"aria-label":L(`tpl.confirmFillTitle`),style:{maxWidth:420},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`div`,{className:`slash-help-head`,children:(0,$.jsx)(`span`,{children:L(`tpl.confirmFillTitle`)})}),(0,$.jsxs)(`div`,{className:`slash-help-body`,style:{padding:`12px 16px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 14px`,lineHeight:1.5},children:L(`tpl.confirmFillDesc`)}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:8,flexWrap:`wrap`},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,autoFocus:!0,onClick:()=>xt(`cancel`),children:L(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xt(`append`),children:L(`tpl.confirmFillAppend`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>xt(`overwrite`),children:L(`tpl.confirmFillOverwrite`)})]})]})]})}),Ce&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>we(!1),children:(0,$.jsxs)(`div`,{className:`slash-help`,style:Te?{width:Te}:void 0,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`slash-help-head`,children:[(0,$.jsxs)(`span`,{children:[`⚡ `,L(`slashHelpTitle`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>we(!1),children:L(`close`)})]}),(0,$.jsx)(`div`,{className:`slash-help-body`,children:fe.length===0?(0,$.jsx)(`div`,{className:`slash-help-empty`,children:L(`slashLoading`)}):fe.map(e=>(0,$.jsxs)(`div`,{className:`slash-help-row`,children:[(0,$.jsxs)(`span`,{className:`slash-help-cmd`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:rt[e.source]}),(0,$.jsxs)(`span`,{className:`slash-help-desc`,children:[pe(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:me(e)})]})]},e.name))})]})}),w&&S.length>0&&(0,$.jsx)(`div`,{className:`quick-row`,"aria-label":L(`quickPhrases`),ref:wt,children:S.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`quick-chip`,title:`${L(`quickPhrasesTip`,{text:e})}(${L(`quickPhrasesSendTip`)})`,disabled:!gt,onClick:()=>Nt(e),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),Nt(e,!0)},children:e},e))}),(0,$.jsxs)(`div`,{className:`inputbox`,"data-pi-anchor":`composer`,children:[(0,$.jsx)(`div`,{className:`composer-resize${W!=null&&W>44?` is-manual`:``}`,"aria-label":L(W!=null&&W>44?`composerResizeFixed`:`composerResize`),role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":Math.round(W??rb),"aria-valuemin":rb,"aria-valuemax":ib,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId);let t=X.current?.getBoundingClientRect().height;_e.current={startY:e.clientY,startH:typeof t==`number`&&Number.isFinite(t)?t:W??rb,next:null}},onPointerMove:e=>{let t=_e.current;if(!t)return;let n=ob(),r=Math.min(n,Math.max(rb,t.startH+(t.startY-e.clientY)));t.next=r,G(r<=44?null:r)},onPointerUp:()=>{let e=_e.current?.next;if(_e.current=null,e!=null)try{if(e<=44)G(null),localStorage.removeItem(ab);else{let t=Math.round(e);G(t),localStorage.setItem(ab,String(t))}}catch{}},onPointerCancel:()=>{_e.current=null},onDoubleClick:()=>{G(null);try{localStorage.removeItem(ab)}catch{}},children:(0,$.jsx)(`span`,{className:`composer-resize-tip`,children:L(W!=null&&W>44?`composerResizeFixed`:`composerResize`)})}),(0,$.jsx)(`input`,{ref:Oe,type:`file`,multiple:!0,hidden:!0,onChange:e=>{pt(e.target.files),e.target.value=``}}),(0,$.jsx)(`textarea`,{ref:X,value:he,rows:1,placeholder:L(gt?r?oe?`placeholderStreamingQueued`:`placeholderStreaming`:ce?`placeholderPlanMode`:ue?`placeholderIdleMod`:`placeholderIdle`:`placeholderConnecting`),disabled:!gt,onChange:e=>{tt(e.target.value,e.target.selectionStart??e.target.value.length)},onSelect:e=>{if(K?.kind===`at`){let t=e.target.selectionStart;(t<K.start||t>K.end)&&q(null)}},onCompositionEnd:qe.onCompositionEnd,onBlur:Xe,onKeyDown:Pt,onPaste:mt}),ce&&(0,$.jsxs)(`button`,{type:`button`,style:{display:`inline-flex`,alignItems:`center`,gap:4,fontSize:11,color:`var(--accent, #38bdf8)`,background:`var(--accent-soft, rgba(56, 189, 248, 0.1))`,padding:`2px 8px`,borderRadius:12,position:`absolute`,right:12,top:8,cursor:`pointer`,border:`1px solid var(--border, rgba(255, 255, 255, 0.1))`,zIndex:2},onClick:()=>Z({type:`set_plan_mode`,enabled:!1}),title:L(`planModeTip`),children:[`📋 `,L(`planModeBadge`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),(0,$.jsx)(`div`,{className:`composer-tools`,children:e?(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Ut()}):Rt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Lt.map(Vt),zt.start.map(Kt)]}),zt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:zt.center.map(Kt)}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:zt.end.map(Kt)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Lt.map(Vt),(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:L(`uploadFile`),disabled:!gt,onClick:()=>Oe.current?.click(),children:(0,$.jsx)(ee,{})}),It.start.map(Vt),(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:L(`tpl.openPicker`),onClick:z,children:(0,$.jsx)(Le,{})}),(0,$.jsx)(Hy,{state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,defaultModel:x,compact:!0}),A&&A.length>0&&j!==void 0&&(0,$.jsx)(tb,{compact:!0,current:k??null,options:A,defaultPreset:j,conversationId:te??``}),N&&N.length>0&&P!==void 0&&(0,$.jsx)(Xy,{compact:!0,preset:M??null,presets:N,defaultPreset:P,blank:F??!1,conversationId:te??``})]}),It.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:It.center.map(Vt)}),(0,$.jsxs)(`div`,{className:`composer-tools-right`,children:[It.end.map(Vt),Ut()]})]})})]})]})}),cb=(0,Q.memo)(function({goal:e,models:t,modelsLoading:n,activeConversationId:r,uiGoalbarActions:i,onUiAction:a}){let o=V(),{locale:c}=Ue(),l=!H(c)&&e.statusEn?e.statusEn:e.status||``,u=!H(c)&&e.wizard?.statusEn?e.wizard.statusEn:e.wizard?.status||``,d=$t(),f=rn(),p=!e.conversationId||e.conversationId===r,m=e.goal!==null&&p,h=p?e.roles?.executor:void 0,g=h?.convId,_=h?.activity?!H(c)&&h.activityEn?h.activityEn:h.activity:h?.streaming?`…`:void 0,v=e.locked&&e.maxRounds>0?e.maxRounds:0,y=v>0?H(c)?o(`goalBarRound`,{n:`${e.round}/${v}`}):`Round ${e.round}/${v}`:`${o(`goalBarRound`,{n:e.round})}${e.locked?` · ${o(`goalBarUnlimitedShort`)}`:``}`,b=(e.usage?.inputTokens??0)+(e.usage?.outputTokens??0),x=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,S=!d&&e.execModel===void 0,[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(e.reviewModel??``),[O,k]=(0,Q.useState)(e.maxRounds),[A,j]=(0,Q.useState)(e.locked),[M,N]=(0,Q.useState)(e.execModel??``),[P,ee]=(0,Q.useState)(!1),[F,te]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[ie,oe]=(0,Q.useState)(!0);(0,Q.useEffect)(()=>{D(e.reviewModel??``),k(e.maxRounds||0),j(e.locked),N(e.execModel??``)},[e.goal,e.reviewModel,e.maxRounds,e.locked,e.execModel]),(0,Q.useEffect)(()=>{P&&t.length===0&&!I&&!n&&(L(!0),Z({type:`list_models`}))},[P,t.length,I,n]),(0,Q.useEffect)(()=>{t.length>0&&L(!1)},[t.length]);let se=()=>E?t.find(e=>e.id===E)?.name??E:o(`goalBarUseMainModel`),ce=()=>M?t.find(e=>e.id===M)?.name??M:o(`goalBarUseMainModel`),le=()=>{let e=w.trim();e&&(Z({type:`set_goal`,goal:e,...E?{reviewModel:E}:{},maxRounds:O,locked:A,...M?{execModel:M}:{}}),T(``),oe(!1))},ue=()=>{let e=w.trim();Z({type:`set_plan_mode`,enabled:!0}),e&&(Z({type:`prompt`,text:e}),T(``))},z=()=>{let e=w.trim();e&&(Z({type:`start_goal_wizard`,text:e,...E?{wizardModel:E}:{},maxRounds:O,locked:A}),T(``),oe(!1))},de=i===void 0?[`host:goal-pill`,`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`,`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`,`host:goal-openrole`,`host:goal-clear`].map(e=>({id:e,source:`host`})):i.filter(e=>!e.hidden),B=e=>{let t=new Set(e);return de.filter(e=>t.has(e.id)||e.source!==`host`)},fe=(e,t)=>{let n=de.find(t=>t.id===e);return n?.labelExplicit?n.label:t},pe={"host:goal-pill":(0,$.jsxs)(`button`,{type:`button`,className:`goalbar-hint`,title:o(`goalBarPlaceholder`),onClick:()=>oe(!1),children:[(0,$.jsx)(lt,{}),` `,(0,$.jsx)(`span`,{children:fe(`host:goal-pill`,o(`goalBarTitle`))})]}),"host:goal-set":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn`,disabled:!w.trim(),onClick:le,children:fe(`host:goal-set`,o(`goalBarSet`))}),"host:goal-wizard":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action wizard`,disabled:!w.trim(),title:o(`goalWizardTip`),onClick:z,children:fe(`host:goal-wizard`,o(`goalWizardBtn`))}),"host:goal-plan":f.planMode?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action plan`,disabled:!w.trim(),title:o(`planActionTip`),onClick:ue,children:fe(`host:goal-plan`,o(`planActionBtn`))}):null,"host:goal-lock":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(A?`goalBarLocked`:`goalBarUnlocked`),onClick:()=>j(e=>(Z({type:`set_goal_prefs`,locked:!e}),!e)),children:A?(0,$.jsx)(Oe,{}):(0,$.jsx)(ae,{})}),"host:goal-collapse":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarClear`),onClick:()=>oe(!0),children:(0,$.jsx)(s,{})}),"host:goal-model":d?(0,$.jsx)(`p`,{className:`goalbar-dsh-note`,children:o(`dshNoReviewModel`)}):(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarReviewModel`)}: ${se()}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-model`,o(`goalBarReviewModel`))}:`}),(0,$.jsx)(`b`,{children:se()})]}),open:P,onOpenChange:ee,direction:`up`,children:(0,$.jsx)(Mo,{models:t,modelsLoading:n,currentModelId:E||null,active:P,onEnsureModels:()=>{t.length===0&&!n&&!I&&(L(!0),Z({type:`list_models`}))},loading:I,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{D(e.id),ee(!1),Z({type:`set_goal_prefs`,reviewModel:e.id})},isRowActive:e=>jo(e,E),extraTopRow:(0,$.jsx)(gt,{active:E===``,onClick:()=>{D(``),ee(!1),Z({type:`set_goal_prefs`,reviewModel:``})},children:o(`goalBarUseMainModel`)})})}),"host:goal-rounds":(0,$.jsxs)(`label`,{className:`goalbar-round`,title:o(`goalBarMaxRoundsTip`),children:[(0,$.jsx)(`span`,{children:fe(`host:goal-rounds`,o(`goalBarMaxRounds`))}),(0,$.jsx)(`input`,{type:`number`,min:0,step:1,value:O,placeholder:o(`goalBarUnlimitedShort`),onChange:e=>{let t=parseInt(e.target.value,10);if(Number.isNaN(t)||t<0){k(0);return}k(t)},onBlur:()=>Z({type:`set_goal_prefs`,maxRounds:O}),onKeyDown:e=>{e.key===`Enter`&&(Z({type:`set_goal_prefs`,maxRounds:O}),e.target.blur())}})]}),"host:goal-execmodel":d?null:(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarExecModel`)}: ${ce()} · ${o(`goalBarExecModelTip`)}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-execmodel`,o(`goalBarExecModel`))}:`}),(0,$.jsx)(`b`,{children:ce()})]}),open:F,onOpenChange:te,direction:`up`,children:(0,$.jsx)(Mo,{models:t,modelsLoading:n,currentModelId:M||null,active:F,onEnsureModels:()=>{t.length===0&&!n&&!I&&(L(!0),Z({type:`list_models`}))},loading:I,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{N(e.id),te(!1),Z({type:`set_goal_prefs`,execModel:e.id})},isRowActive:e=>jo(e,M),extraTopRow:(0,$.jsx)(gt,{active:M===``,onClick:()=>{N(``),te(!1),Z({type:`set_goal_prefs`,execModel:``})},children:o(`goalBarUseMainModel`)})})})},me=(e.wizard?.active??!1)&&p;if(me)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${me?`wizard`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`🔍`})}),(0,$.jsxs)(`span`,{className:`goalbar-text`,title:e.wizard?.draft??``,children:[o(`goalWizardRunning`),`: `,e.wizard?.draft]}),(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[o(`goalBarRound`,{n:(e.wizard?.step??0)+1}),` / `,e.wizard?.maxSteps??6]}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:u||o(`goalBarReviewing`)}),P_(B([`host:goal-clear`]),{...pe,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x`,title:o(`goalBarClear`),onClick:()=>{Z({type:`clear_goal`}),oe(!0)},children:(0,$.jsx)(R,{})})},a)]})});if(m)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${e.reviewing?`reviewing`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:e.reviewing?(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`◌`}):`🎯`}),(0,$.jsx)(`span`,{className:`goalbar-text`,title:e.goal??``,children:e.goal}),e.reviewing?(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[e.phase===`executing`?o(`goalBarExecuting`):o(`goalBarReviewing`),` `,y]}):(0,$.jsx)(`span`,{className:`goalbar-chip ${e.verdict===`pass`?`pass`:e.verdict===`fail`?`fail`:e.verdict===`blocked`?`blocked`:``}`,children:e.verdict===`pass`?o(`goalBarPassed`):e.verdict===`fail`?o(`goalBarFailed`):e.verdict===`blocked`?o(`goalBarBlocked`):`${o(`goalBarRound`,{n:e.round||1})} · ${e.locked?o(`goalBarLocked`):o(`goalBarUnlocked`)}`}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:l}),_&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:h?.convId,children:[`· `,_]}),b>0&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:`${e.usage?.inputTokens??0} in / ${e.usage?.outputTokens??0} out`,children:[`· `,x(b),` tokens`]}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)}),P_(B([`host:goal-openrole`,`host:goal-clear`]),{...pe,"host:goal-openrole":g?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarOpenExecTip`),onClick:()=>Z({type:`switch_conversation`,id:g}),children:(0,$.jsx)(Ze,{})}):null,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x${e.reviewing?` stopping`:``}`,title:fe(`host:goal-clear`,e.reviewing?o(`goalBarStop`):o(`goalBarClear`)),onClick:()=>{e.goal&&T(e.goal),Z({type:`clear_goal`}),oe(!1)},children:e.reviewing?(0,$.jsx)(C,{}):(0,$.jsx)(R,{})})},a)]})});if(ie){let e=P_(B([`host:goal-pill`]),pe,a);return e?(0,$.jsx)(`div`,{className:`goalbar-collapsed`,children:e}):null}return(0,$.jsxs)(`div`,{className:`goalbar`,children:[(0,$.jsxs)(`div`,{className:`goalbar-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(lt,{})}),(0,$.jsx)(`input`,{className:`goalbar-input`,autoFocus:!0,value:w,placeholder:o(`goalBarPlaceholder`),title:o(`goalBarPlaceholder`),onChange:e=>T(e.target.value),onKeyDown:e=>{e.key===`Enter`&&le()}}),P_(B([`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`]),pe,a)]}),(0,$.jsxs)(`div`,{className:`goalbar-opts`,children:[B([`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`]).filter(e=>e.source===`host`).map(e=>(0,$.jsx)(Q.Fragment,{children:pe[e.id]},e.id)),e.history&&e.history.length>0&&(0,$.jsxs)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:o(`goalHistory`),children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${o(`goalHistory`)}:`}),(0,$.jsx)(`b`,{children:e.history.length})]}),open:ne,onOpenChange:re,direction:`up`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:o(`goalHistory`)}),e.history.map((e,t)=>(0,$.jsx)(gt,{onClick:()=>{T(e.goal),re(!1)},children:(0,$.jsxs)(`span`,{className:`dd-model-cell`,title:e.goal,children:[(0,$.jsxs)(`span`,{className:`dd-model-name`,children:[e.verdict===`pass`?`✅ `:e.verdict===`fail`?`❌ `:`⚠️ `,e.goal.length>42?`${e.goal.slice(0,42)}…`:e.goal]}),(0,$.jsx)(`span`,{className:`dd-model-meta`,children:(0,$.jsxs)(`span`,{className:`dd-model-id`,children:[o(`goalBarRound`,{n:e.rounds}),` · `,new Date(e.finishedAt).toLocaleString()]})})]})},`${e.finishedAt}-${t}`))]}),(0,$.jsx)(`span`,{className:`goalbar-lock-hint`,children:o(A?`goalBarLocked`:`goalBarUnlocked`)}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)})]})]})});function lb(e){return e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e}function ub(e,t,n){return!!(n&&t&&e&&n.path===t.path&&e.path===t.path&&(e.sandboxId===t.id||e.error&&e.sandboxId===``)&&e.requestId===n.requestId)}function db(e){return!!(e&&!e.error&&e.expectedRevision&&e.added.length+e.modified.length+e.deleted.length>0)}function fb({mode:e,currentCwd:t,currentSandbox:n,sandboxDiff:r,projects:i,send:a,onClose:o}){let s=V(),c=n?.sourcePath||(!n&&t?t:i.find(e=>!e.sandbox)?.path||t||``),[l,d]=(0,Q.useState)(c?`import`:`blank`),[f,h]=(0,Q.useState)(c),[g,_]=(0,Q.useState)(!0),[v,y]=(0,Q.useState)(``),b=n?.sourcePath?`${n.sourcePath}-exp`:`~/projects/${(n?.name||`sandbox-app`).replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-|-$/g,``)||`sandbox-app`}`,[x,S]=(0,Q.useState)(b),[C,w]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(null),D=()=>{if(!n)return;let e={requestId:ht(),path:n.path};E(e),a({type:`diff_sandbox`,...e})};(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,Q.useEffect)(()=>{if(E(null),e===`apply`&&n?.path){let e={requestId:ht(),path:n.path};E(e),a({type:`diff_sandbox`,...e})}},[e,n?.path,a]);let O=i.filter(e=>!e.sandbox),k=e=>{e.preventDefault();let t=l===`import`?f.trim():void 0;(l!==`import`||t)&&(a({type:`create_sandbox`,name:v.trim()||void 0,sourcePath:t,ephemeral:g}),o())},A=e=>{e.preventDefault();let t=x.trim();t&&(a({type:`promote_sandbox`,path:n?.path,targetPath:t,switchToTarget:C}),o())},j=e=>{e.preventDefault(),n?.path&&M&&db(r)&&r.expectedRevision&&(E(null),a({type:`apply_sandbox_to_source`,path:n.path,expectedRevision:r.expectedRevision}),o())},M=e===`apply`&&ub(r,n,T),N=M?r.added.length+r.modified.length+r.deleted.length:0,P=s(e===`create`?`sandboxModalTitle`:e===`promote`?`sandboxPromoteTitle`:`sandboxApplyTitle`);return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal sandbox-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,onClick:o,title:s(`close`),"aria-label":s(`close`),children:(0,$.jsx)(R,{})}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:(0,$.jsx)(An,{})}),(0,$.jsx)(`h2`,{children:P})]}),e===`create`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:k,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxModalSubtitle`)}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxModeLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`import`?`active`:``}`,onClick:()=>d(`import`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(at,{"aria-hidden":!0}),` `,s(`sandboxModeImport`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeImportDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`blank`?`active`:``}`,onClick:()=>d(`blank`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(p,{"aria-hidden":!0}),` `,s(`sandboxModeBlank`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeBlankDesc`)})]})]})]}),l===`import`&&(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxSourceLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:f,onChange:e=>h(e.target.value),placeholder:s(`sandboxSourcePlaceholder`),required:!0}),O.length>0&&(0,$.jsx)(`div`,{className:`sandbox-source-chips`,children:O.slice(0,6).map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-source-chip ${f===e.path?`active`:``}`,onClick:()=>h(e.path),title:e.path,children:[(0,$.jsx)(Be,{"aria-hidden":!0,style:{marginRight:4,verticalAlign:`-1px`}}),lb(e.path)]},e.path))})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxLifecycleLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${g?`active`:``}`,onClick:()=>_(!0),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(u,{"aria-hidden":!0}),` `,s(`sandboxLifecycleEphemeral`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecycleEphemeralDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${g?``:`active`}`,onClick:()=>_(!1),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(ke,{"aria-hidden":!0}),` `,s(`sandboxLifecyclePermanent`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecyclePermanentDesc`)})]})]})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxNameLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:v,onChange:e=>y(e.target.value),placeholder:l===`import`&&f.trim()?`${lb(f.trim())} (Sandbox)`:s(`sandboxNamePlaceholder`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:l===`import`&&!f.trim(),children:[(0,$.jsx)(An,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxCreateSubmit`)]})]})]}):e===`promote`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:A,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxPromoteSubtitle`,{name:n?.name||``})}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxPromoteTargetLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:x,onChange:e=>S(e.target.value),placeholder:s(`sandboxPromoteTargetPlaceholder`),autoFocus:!0,required:!0})]}),(0,$.jsxs)(`label`,{className:`sandbox-checkbox-row`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,$.jsx)(`span`,{children:s(`sandboxPromoteSwitchLabel`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!x.trim(),children:[(0,$.jsx)(m,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxPromoteSubmit`)]})]})]}):(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:j,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxActionApplyConfirm`,{name:n?.name||``,source:n?.sourcePath||``})}),M?r.error?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:r.error}):(0,$.jsxs)(`div`,{className:`sandbox-diff-box`,children:[(0,$.jsx)(`div`,{className:`sandbox-diff-stats`,children:s(`sandboxDiffStats`,{added:r.added.length,modified:r.modified.length,deleted:r.deleted.length,unchanged:r.unchangedCount})}),r.added.length+r.modified.length+r.deleted.length===0?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:s(`sandboxDiffEmpty`)}):(0,$.jsxs)(`div`,{className:`sandbox-diff-list`,children:[r.added.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item added`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag added`,children:`+`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`a:${e}`)),r.modified.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item modified`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag modified`,children:`~`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`m:${e}`)),r.deleted.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item deleted`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag deleted`,children:`-`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`d:${e}`))]}),(0,$.jsx)(`div`,{className:`sandbox-diff-note`,children:s(`sandboxDiffDeletedNote`)})]}):(0,$.jsx)(`div`,{className:`sandbox-diff-loading`,children:s(`loading`)}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:D,children:s(`sandboxDiffRefresh`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!M||!db(r),children:[(0,$.jsx)(z,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxApplySubmit`,{count:N})]})]})]})]})})}var pb=({worktree:e,onRefresh:t,onSwitch:n,onRemove:r})=>{let i=V(),[a,o]=(0,Q.useState)(!1),s=e=>{let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return t[t.length-1]||e},c=e.linkedWorktrees||[],l=JSON.stringify(c.map(e=>e.path).sort()),u=`pi-worktree-dismiss:${e.mainPath}`,[d,f]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{try{f(localStorage.getItem(u))}catch{f(null)}},[u]);let p=(0,Q.useRef)(t);if(p.current=t,(0,Q.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&p.current()};e();let t=window.setInterval(e,3e4);return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.clearInterval(t),window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[e.mainPath]),e.isLinkedWorktree){let t=e.branch||s(e.currentPath);return(0,$.jsxs)(`div`,{className:`worktree-banner linked`,role:`region`,"aria-label":t,children:[(0,$.jsxs)(`div`,{className:`worktree-banner-info`,children:[(0,$.jsxs)(`span`,{className:`worktree-banner-title`,children:[`🌿 `,i(`worktreeBannerActiveTitle`,{branch:t}),(0,$.jsx)(`span`,{className:`lp-worktree-badge linked`,children:i(`worktreeBadgeLinked`)})]}),(0,$.jsx)(`span`,{className:`worktree-banner-desc`,children:i(`worktreeBannerActiveDesc`,{main:e.mainPath,mainBranch:e.mainBranch||`main`})})]}),(0,$.jsxs)(`div`,{className:`worktree-banner-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn primary`,title:i(`worktreeActionSwitchMainTip`),onClick:()=>n(e.mainPath),children:[`⬅️ `,i(`worktreeActionSwitchMain`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn danger`,title:i(`worktreeActionRemoveTip`),onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.currentPath)},children:[`🗑️ `,i(`worktreeActionRemove`)]})]})]})}if(c.length===0||d===l)return null;let m=()=>{f(l);try{localStorage.setItem(u,l)}catch{}},h=c.filter(e=>e.isDirty).length,g=c.map(e=>{let t=e.branch||s(e.path);return e.isDirty?`${t}*`:t}).join(` · `);return(0,$.jsxs)(`div`,{className:`worktree-banner notice`,role:`region`,"aria-label":`Git Worktrees`,children:[(0,$.jsxs)(`div`,{className:`worktree-banner-info`,children:[(0,$.jsxs)(`span`,{className:`worktree-banner-title`,children:[`⚠️ `,i(`worktreeBannerUncleanedTitle`,{count:c.length}),h>0&&(0,$.jsx)(`span`,{className:`lp-worktree-badge dirty`,children:i(`worktreeBadgeDirtyCount`,{count:h})})]}),(0,$.jsx)(`span`,{className:`worktree-banner-desc`,children:i(`worktreeBannerUncleanedDesc`,{names:g})})]}),(0,$.jsxs)(`div`,{className:`worktree-banner-actions`,children:[c.slice(0,2).map(e=>{let t=e.branch||s(e.path);return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn`,title:i(`worktreeActionSwitchToTip`,{name:t}),onClick:()=>n(e.path),children:[`➡️ `,i(`worktreeActionSwitchTo`,{name:t})]}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn danger`,title:i(`worktreeActionRemoveTip`),onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.path)},children:`🗑️`})]},e.path)}),c.length>2&&(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn`,onClick:()=>o(!a),children:a?i(`worktreeActionCollapse`):i(`worktreeActionMore`,{count:c.length-2})}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-close`,title:i(`worktreeActionDismissTip`),"aria-label":i(`worktreeActionDismiss`),onClick:m,children:(0,$.jsx)(R,{"aria-hidden":!0})})]}),a&&c.length>2&&(0,$.jsx)(`div`,{className:`worktree-banner-expand`,children:c.slice(2).map(e=>{let t=e.branch||s(e.path);return(0,$.jsxs)(`div`,{className:`worktree-expand-row`,children:[(0,$.jsxs)(`span`,{className:`worktree-expand-name`,children:[t,e.isDirty&&(0,$.jsx)(`span`,{className:`lp-worktree-badge dirty`,children:i(`worktreeBadgeDirtyCount`,{count:e.uncommittedCount||1})})]}),(0,$.jsxs)(`div`,{className:`worktree-expand-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn`,onClick:()=>n(e.path),children:[`➡️ `,i(`worktreeActionSwitchTo`,{name:t})]}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn danger`,onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.path)},children:`🗑️`})]})]},e.path)})})]})},mb=[{id:`host:conn`,align:`start`},{id:`host:engine`,align:`start`},{id:`host:ctx`,align:`start`},{id:`host:cost`,align:`start`},{id:`host:cache`,align:`start`},{id:`host:msg-count`,align:`start`},{id:`host:plugin-status`,align:`start`},{id:`host:status-delegate`,align:`start`},{id:`host:working`,align:`start`},{id:`host:host-metrics`,align:`end`},{id:`host:cwd`,align:`end`}];function hb({chat:e,bottombarItems:t,onUiAction:n,onOpenSettings:r,onViewChange:i,onOpenGlobalSearch:a,onOpenBgTasks:o}){let s=en(`workspaceRoots`),c=e.state,[l,u]=(0,Q.useState)(!1);if(!c)return null;let d=t?t.map(e=>({id:e.id,entry:e,fallbackAlign:`start`})):mb.map(({id:e,align:t})=>({id:e,entry:null,fallbackAlign:t})),f=[],p=[],m=[];for(let{id:t,entry:s,fallbackAlign:c}of d){if(s?.hidden)continue;let d=s??{id:t,slot:`bottombar`,source:`host`,label:t.slice(5),kind:`action`,order:100,align:c,hidden:!1,userOverrides:[],arrangedBy:[]},h=(0,$.jsx)(to,{entry:d,bar:`bottom`,chat:e,view:void 0,onViewChange:i,onOpenSettings:r,onOpenGlobalSearch:a,onOpenBgTasks:o,onOpenProjectPicker:()=>u(!0),isProjectPickerOpen:l,onUiAction:n});if(!h)continue;let g=d.align??c;g===`end`?m.push({key:t,node:h}):g===`center`?p.push({key:t,node:h}):f.push({key:t,node:h})}let h=e=>e.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.key));return(0,$.jsxs)(`footer`,{className:`statusbar`,children:[(0,$.jsx)(`div`,{className:`statusbar-left`,children:h(f)}),p.length>0&&(0,$.jsx)(`div`,{className:`statusbar-center`,children:h(p)}),(0,$.jsx)(`div`,{className:`statusbar-right`,children:h(m)}),l&&(0,$.jsx)(ba,{open:!0,currentCwd:c.cwd,pathCompletions:e.pathCompletions,workspaceRoots:s,onClose:()=>u(!1),onSelectDirectory:e=>{e&&e!==c.cwd&&Z({type:`set_cwd`,path:e}),u(!1)},mode:`folder`})]})}var gb=[{slot:`topbar.primary`,labelKey:`uiLayoutTopbar`,alignable:!0,vertical:!1},{slot:`bottombar`,labelKey:`uiLayoutBottombar`,alignable:!0,vertical:!1},{slot:`sidebar.left`,labelKey:`uiLayoutSidebarLeft`,alignable:!0,vertical:!0},{slot:`sidebar.right`,labelKey:`uiLayoutSidebarRight`,alignable:!0,vertical:!0}],_b=`__tray`,vb=[`start`,`center`,`end`];function yb(e,t){return e(t===`start`?`uiLayoutAlignTop`:t===`end`?`uiLayoutAlignBottom`:`uiLayoutAlignMiddle`)}function bb(e,t=new Set){let n={},r=[],i=new Set;for(let a of gb){let o=(e[a.slot]??[]).filter(e=>!t.has(e.id));n[a.slot]=o;for(let e of o)e.hidden&&(r.push(e),i.add(e.id))}for(let n of e[`topbar.overflow`]??[])t.has(n.id)||i.has(n.id)||(r.push(n),i.add(n.id));return{zones:n,tray:r}}function xb(e,t){for(let n of Object.values(e.zones)){let e=n.find(e=>e.id===t);if(e)return e}return e.tray.find(e=>e.id===t)}function Sb(e){return(e??[]).filter(e=>!e.hidden)}function Cb(e,t){let n=Sb(e);return t===void 0?n:n.filter(e=>(e.align??`start`)===t)}function wb(e){return[...new Set(e)]}function Tb(e,t,n){let r=e??{},i=xb(t,n.id);if(!i)return r;let a={...r};i.hidden&&(a.hidden=(r.hidden??[]).filter(e=>e!==n.id),a.shown=wb([...r.shown??[],n.id])),i.slot!==n.slot&&(a.slots={...r.slots,[n.id]:n.slot});let o=n.align;o!==void 0&&(i.align??`start`)!==o&&(a.align={...r.align,[n.id]:o});let s=t.zones[n.slot]??[],c=Sb(s),l=e=>o===void 0||(e.align??`start`)===o,u=c.filter(e=>e.id!==n.id&&l(e)).map(e=>e.id),d=Math.max(0,Math.min(Math.trunc(n.index)||0,u.length));u.splice(d,0,n.id);let f=o===void 0?[]:c.filter(e=>e.id!==n.id&&!l(e)).map(e=>e.id),p=new Set(s.map(e=>e.id));return a.order=wb([...(r.order??[]).filter(e=>!p.has(e)&&e!==n.id),...u,...f]),a}function Eb(e,t){let n=e??{};return{...n,hidden:wb([...n.hidden??[],t]),shown:(n.shown??[]).filter(e=>e!==t)}}function Db({side:e,items:t,chat:n,view:r,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenBgTasks:s,onOpenGlobalSearch:c,onUiAction:l,uiContextTopbar:u,onOpenProjectPicker:d,onThemeToggle:f,onSoundToggle:p,zenMode:m,onToggleZenMode:h,dropdownProps:g,plugins:_,onOpenPluginMenu:v,isPluginMenuOpen:y}){let{t:b}=Ue(),[x,S]=(0,Q.useState)(!1),C=(0,Q.useRef)(null),w=n.settings?.uiLayout?.sideDockFloat===!0,T=w?` side-dock-float`:``,E=t.filter(e=>!e.hidden);if(E.length===0)return null;if(w&&x)return(0,$.jsx)(`div`,{ref:C,className:`side-dock side-dock-${e} side-dock-collapsed${T}`,children:(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-toggle-btn`,"data-tip":`${b(`sideDockExpand`)} (${E.length})`,onClick:()=>S(!1),"aria-label":b(`sideDockExpand`),children:e===`left`?(0,$.jsx)(P,{}):(0,$.jsx)(it,{})})});let D=wi(E),O=t=>(0,$.jsx)(to,{entry:t,bar:e,chat:n,view:r,plugins:_,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenGlobalSearch:c,onOpenBgTasks:s,onOpenProjectPicker:d,onOpenPluginMenu:v,isPluginMenuOpen:y,onUiAction:l,uiContextEntries:u,zenMode:m,onToggleZenMode:h,dropdownProps:g},t.id);return(0,$.jsxs)(`div`,{ref:C,className:`side-dock side-dock-${e}${T}`,children:[w&&(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-collapse-btn`,"data-tip":b(`sideDockCollapse`),onClick:()=>S(!0),"aria-label":b(`sideDockCollapse`),children:e===`left`?(0,$.jsx)(it,{}):(0,$.jsx)(P,{})}),vb.map(e=>(0,$.jsx)(`div`,{className:`side-dock-slot side-dock-slot-${e}`,children:D[e].length>0&&(0,$.jsx)(`div`,{className:`side-dock-seg`,children:D[e].map(O)})},e))]})}function Ob(e){let t=e.trim().toLowerCase();return/^(yes|allow|approve|confirm|ok|是|允许|同意|确认|放行)/i.test(t)}function kb(e){let t=e.trim().toLowerCase();return/^(no|deny|reject|cancel|block|否|拒绝|取消|阻止)/i.test(t)}function Ab(e){if(!e)return{hasRisk:!1,intro:``,command:null,outro:``};let t=/⚠️|danger|warning|高危|危险/i.test(e)||/\b(rm\s+-[a-zA-Z]*r[a-zA-Z]*f|chmod\s+(-R\s+)?777|mkfs|dd\s+if=|chown\s+-R|> \/dev\/|sudo\s+rm|drop\s+database|truncate\s+table)\b/i.test(e),n=e.match(/([\s\S]*?)```(?:[a-zA-Z0-9_-]*)\n([\s\S]*?)```([\s\S]*)/);if(n)return{hasRisk:t,intro:n[1].trim(),command:n[2].trim(),outro:n[3].trim()};let r=e.split(`
|
|
67
|
+
`)}}var Jv=null;function Yv(){if(Jv?.isConnected)return Jv;let e=document.createElement(`div`);e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-caret-mirror`,``);let t=e.style;return t.position=`fixed`,t.top=`0`,t.left=`-99999px`,t.visibility=`hidden`,t.pointerEvents=`none`,t.margin=`0`,t.padding=`0`,t.border=`0`,t.boxSizing=`border-box`,t.overflow=`visible`,document.body.appendChild(e),Jv=e,e}function Xv(e,t){let n=getComputedStyle(e),r=t.style;r.fontFamily=n.fontFamily,r.fontSize=n.fontSize,r.fontStyle=n.fontStyle,r.fontWeight=n.fontWeight,r.fontVariant=n.fontVariant,r.fontStretch=n.fontStretch,r.lineHeight=n.lineHeight,r.letterSpacing=n.letterSpacing,r.wordSpacing=n.wordSpacing,r.textTransform=n.textTransform,r.textIndent=n.textIndent,r.tabSize=n.tabSize,r.whiteSpace=n.whiteSpace||`pre-wrap`,r.overflowWrap=n.overflowWrap||`break-word`,r.wordBreak=n.wordBreak||`normal`,r.direction=n.direction,r.writingMode=n.writingMode,r.paddingLeft=n.paddingLeft,r.paddingRight=n.paddingRight;let i=e.clientWidth;return i>0?(r.width=`${i}px`,i):0}function Zv(e,t){e.textContent=t;let n=document.createElement(`span`);return n.textContent=Gv,e.appendChild(n),n.offsetTop}function Qv(e){let t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};let r=qv(t,n);if(!r.first&&!r.last||typeof document>`u`||typeof getComputedStyle!=`function`)return r;let i=Yv();if(Xv(e,i)<=0)return r;let a=Zv(i,t.slice(0,n)),o=Zv(i,t),s=i.offsetHeight>0;return i.textContent=``,!s&&t!==``?r:Kv(a,o,Wv(e))}function $v(e,t){let n=[],r=e?.length??0;for(let t=0;t<r;t++){let r=e?.[t];if(!r||r.kind!==`file`)continue;let i=r.getAsFile();i&&n.push(i)}if(n.length===0&&t)for(let e=0;e<t.length;e++){let r=t[e];r&&n.push(r)}return n}var ey=`pi-web-ui:prompt-history`,ty=`pi-web-ui:prompt-history-settings`,ny={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function ry(e){let t=ny;if(!e||typeof e!=`object`)return{...t};let n=e,r=typeof n.maxEntries==`number`?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let i=typeof n.charLimit==`number`?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(i)||i<100)&&(i=100),i>2e4&&(i=2e4);let a=typeof n.charLimitEnabled==`boolean`?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:r,charLimitEnabled:a,charLimit:i}}function iy(){try{let e=localStorage.getItem(ty);return e?ry(JSON.parse(e)):{...ny}}catch{return{...ny}}}function ay(e){let t=ry(e);try{localStorage.setItem(ty,JSON.stringify(t))}catch{}try{let e=cy();t.charLimitEnabled&&(e=e.map(e=>e.length>t.charLimit?e.slice(0,t.charLimit):e)),e.length>t.maxEntries&&(e=e.slice(e.length-t.maxEntries)),ly(e)}catch{}}function oy(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e&&t.push(e)}return t}function sy(e,t,n=100){let r=t.trim();if(!r||e.length>0&&e[e.length-1]===r)return e;let i=[...e,r];return i.length>n?i.slice(i.length-n):i}function cy(){try{let e=localStorage.getItem(ey);return e?oy(JSON.parse(e)):[]}catch{return[]}}function ly(e){let t=e;for(;t;)try{localStorage.setItem(ey,JSON.stringify(t));return}catch(e){if(!(e instanceof DOMException&&(e.name===`QuotaExceededError`||e.code===22))||t.length<=1)return;t=t.slice(Math.ceil(t.length/2))}}function uy(e){let t=e.trim();if(!t)return;let n=iy();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));let r=cy(),i=sy(r,t,n.maxEntries);i!==r&&ly(i)}function dy(){try{localStorage.removeItem(ey)}catch{}}var fy=`skill:`,py=/[\s\-_./:]/;function my(e,t){let n=e.toLowerCase();return t===`skill`&&n.startsWith(`skill:`)?[n,n.slice(6)]:[n]}function hy(e,t){let n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r===-1)return-1;if(r>0&&py.test(t[r-1]))return r;n=r+1}return-1}function gy(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(!n)return{tier:0,score:0};if(n.length>r.length)return null;let i=3,a=-1;if(r===n)i=0,a=0;else if(r.startsWith(n))i=1,a=0;else{let e=hy(n,r);e!==-1&&(i=2,a=e)}if(a!==-1){let e=0,t=0;for(let i=0;i<n.length;i++){let n=a+i,o=n===0||py.test(r[n-1]);i>0&&(t++,e-=t*5),o&&(e-=10),e+=n*.1}return i===0&&(e-=100),{tier:i,score:e}}let o=0,s=0,c=-1,l=0;for(;o<n.length;){let e=r.indexOf(n[o],c+1);if(e===-1)return null;let t=e===0||py.test(r[e-1]);c===e-1?(l++,s-=l*5):(l=0,c>=0&&(s+=(e-c-1)*2)),t&&(s-=10),s+=e*.1,c=e,o++}return{tier:3,score:s}}function _y(e,t){let n=t.toLowerCase();if(!n)return[...e];let r=[];for(let t=0;t<e.length;t++){let i=e[t],a=my(i.name,i.source),o=null;for(let e of a){let t=gy(n,e);t&&(!o||t.tier<o.tier||t.tier===o.tier&&t.score<o.score)&&(o=t)}o&&r.push({cmd:i,tier:o.tier,score:o.score,index:t})}return r.sort((e,t)=>e.tier===t.tier?e.tier<3?e.index-t.index:Math.abs(e.score-t.score)>1e-6?e.score-t.score:e.index-t.index:e.tier-t.tier),r.map(e=>e.cmd)}var vy=new Set([`p`,`page`,`pages`,`web`,`网页`,`页面`]);function yy(e,t,n,r=10){if(!Array.isArray(t))return[];let i=String(n??``).toLowerCase(),a=i===``||vy.has(i),o=[];for(let n of t){if(!n||typeof n.origin!=`string`||!n.origin||n.open!==!0)continue;let t=typeof n.title==`string`&&n.title.trim()?n.title.trim():n.origin;if(!a&&!t.toLowerCase().includes(i)&&!n.origin.toLowerCase().includes(i))continue;let s=t.indexOf(` · `),c=s===-1?`page · ${t}`:`page · ${t.slice(s+3)}`;if(o.push({providerId:`host:pages`,providerLabel:e,title:c,hint:n.origin,text:t,attachments:[{path:n.origin,name:t,mode:`page`}]}),o.length>=Math.max(0,r))break}return o}function by(e,t,n=10){if(!Array.isArray(t))return[];let r=[];for(let i of t.slice(0,Math.max(0,n))){if(!i||typeof i!=`object`)continue;let t=i;typeof t.path==`string`&&t.path&&typeof t.name==`string`&&t.name&&r.push({providerId:`host:files`,providerLabel:e,title:t.name,hint:t.path,text:`@${t.path}`,attachments:[{path:t.path,name:t.name,mode:`reference`,...t.type===`dir`?{isDir:!0}:{}}]})}return r}function xy(e,t,n,r=10){if(!Array.isArray(n))return[];let i=[];for(let a of n.slice(0,Math.max(0,r))){if(!a||typeof a!=`object`)continue;let n=a;if(typeof n.title!=`string`||!n.title.trim())continue;let r=Array.isArray(n.attachments)?n.attachments.filter(e=>!!e&&typeof e==`object`&&typeof e.path==`string`).slice(0,4).map(e=>{let t=e.mode;return{path:e.path,...typeof e.name==`string`?{name:e.name}:{},...t===`inline`||t===`reference`||t===`lines`||t===`page`?{mode:t}:{},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{}}}):void 0;i.push({providerId:e,providerLabel:t,title:n.title.trim(),...typeof n.hint==`string`&&n.hint?{hint:n.hint}:{},...typeof n.text==`string`&&n.text?{text:n.text}:{},...r?.length?{attachments:r}:{}})}return i}function Sy(e,t,n,r=15,i){if(!Array.isArray(t)||r<=0)return[];let a=String(n??``).toLowerCase(),o=a.startsWith(fy),s=o?a.slice(fy.length):a,c=[],l=[],u=o||s.length>=3;for(let n of t){if(n.source!==`skill`)continue;let t=n.name.startsWith(`skill:`)?n.name.slice(fy.length):n.name,r=t.toLowerCase(),a=i?i(n):n.description??``,o=a.toLowerCase(),d=(n.descriptionEn??``).toLowerCase(),f={providerId:`host:skills`,providerLabel:e,title:t,hint:a||`Skill ${t}`,text:`@skill:${t}`};s?r.includes(s)?c.push(f):u&&(o.includes(s)||d.includes(s))&&l.push(f):c.push(f)}return[...c,...l].slice(0,Math.max(0,r))}function Cy(e,t,n=30){let r=String(t??``).toLowerCase(),i=e.pages??[],a=e.canvases??[],o=e.skills??[],s=e.files??[],c=e.plugins??[],l;return l=r.startsWith(`skill:`)?[...o,...a,...i,...s,...c]:[...a,...i,...o,...s,...c],l.slice(0,Math.max(0,n))}function wy(e){return e===void 0||!(e===`@`||/[A-Za-z0-9_]/.test(e))}function Ty(e,t){let n=typeof e==`string`?e:``,r=Math.max(0,Math.min(typeof t==`number`&&Number.isFinite(t)?Math.floor(t):0,n.length)),i=n.slice(0,r),a=i.lastIndexOf(`@`);if(a===-1||!wy(a>0?i[a-1]:void 0))return null;let o=i.slice(a+1);return/[\s@]/.test(o)?null:{start:a,query:o}}function Ey(e){let t=e.query;if(!t||!t(`(pointer: coarse)`)||!t(`(hover: none)`))return!1;let n=e.userAgent??``;return!(/Windows|CrOS/i.test(n)||/Linux/i.test(n)&&!/Android/i.test(n)||/Macintosh/i.test(n)&&(e.maxTouchPoints??0)<=1)}function Dy(){return typeof window>`u`||typeof navigator>`u`||typeof window.matchMedia!=`function`?!1:Ey({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}var Oy=`pi-web-send-key`;function ky(e,t){return e===`enter`||e===`mod-enter`?e:t?`mod-enter`:`enter`}function Ay(e){return e.key===`Enter`?ky(e.pref,!!e.isTouch)===`enter`?e.shiftKey?`newline`:`send`:(e.ctrlKey||e.metaKey)&&!e.shiftKey?`send`:`newline`:`ignore`}function jy(){try{let e=localStorage.getItem(Oy);return e===`enter`||e===`mod-enter`?e:null}catch{return null}}function My(e){try{localStorage.setItem(Oy,e)}catch{}Ny=e;for(let e of Py)e()}var Ny=null,Py=new Set;function Fy(e){return Py.add(e),()=>{Py.delete(e)}}function Iy(){return Ny===null&&(Ny=jy()),Ny}function Ly(){return(0,Q.useSyncExternalStore)(Fy,Iy)}function Ry(e=Dy()){return ky(Ly(),e)}function zy(e,t,n){if(t<=0||!e)return null;let r=null;for(let t of n){let n=[t.mode===`page`||t.mode===`conversation`?t.name:t.path,t.name].filter(e=>typeof e==`string`&&e.trim().length>0);for(let i of n){let n=`@`+i,a=e.endsWith(n+` `);if(a||e.endsWith(n)){let e=n.length;(!r||e>r.tokenLen)&&(r={attachment:t,tokenLen:e,withSpace:a})}}}let i=-1,a=r?.attachment;if(r){let n=t-(r.withSpace?r.tokenLen+1:r.tokenLen);n>0&&/[\w.\-/]/.test(e[n-1])?(i=-1,a=void 0):i=n}if(i<0){let r=/(^|[\s(("'"“‘[【])(@[^\s@,.;:!?,。!?)\]】」]+)(\s?)$/.exec(e);if(r){i=t-r[2].length-r[3].length;let o=e.slice(i,t).trim().replace(/^@/,``),s=o.split(`/`).pop()??o;a=n.find(e=>e.path&&e.path===o)??n.find(e=>e.name&&e.name===o)??n.find(e=>e.mode!==`page`&&e.mode!==`conversation`&&e.name===s)}}return i>=0&&i<t?{tokenStart:i,...a?{attachment:a}:{}}:null}function By(e,t=0,n=Date.now()){return!!(e.isComposing||e.keyCode===229||t>0&&n-t<50)}function Vy(){let e=(0,Q.useRef)(0);return{onCompositionEnd:()=>{e.current=Date.now()},isImeKey:t=>By(t,e.current)}}var Hy=1;function Uy(){return++Hy}var Wy=(0,Q.memo)(function({state:e,models:t,modelsLoading:n,onManageModels:r,providerKeys:i={},defaultModel:a,compact:o=!1,only:s,onSelectModel:c,onSelectThinking:l,direction:u=`up`}){let d=V(),f=e?.model,p=f?f.id.includes(`/`)?f.id:`${f.provider}/${f.id}`:null,[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),[b,x]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!m){x(null);return}if(t.length===0)return;let e=requestAnimationFrame(()=>{let e=y.current;e&&x(e.offsetWidth)});return()=>cancelAnimationFrame(e)},[m,t.length]);let[S,C]=(0,Q.useState)(!1),w=e?.availableThinkingLevels&&e.availableThinkingLevels.length>0?new Set(e.availableThinkingLevels):null,T=wa.map(e=>({value:e,label:d(`thinking.${e}`),supported:!w||w.has(e)})),D=e=>T.find(t=>t.value===e)?.label??e,O=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{m||(O.current=!1)},[m]),(0,Q.useEffect)(()=>{C(!1)},[t]),(0,Q.useEffect)(()=>{m&&(v.current?.querySelector(`.dd-item.active`))?.scrollIntoView({block:`nearest`})},[m,p,t.length]);let k=(0,$.jsx)(Po,{models:t,modelsLoading:n,providerKeys:i,defaultModel:a,currentModelId:p,active:m,onEnsureModels:()=>{O.current||t.length>0||n||(O.current=!0,C(!0),Z({type:`list_models`})||C(!1))},loading:S,onRefresh:()=>{C(!0),Z({type:`list_models`})},onManageModels:r?()=>{h(!1),r()}:void 0,onPickModel:(e,t)=>{if(c){c(e),h(!1);return}t&&!t.active&&Z({type:`activate_provider_key`,provider:e.provider,keyName:t.name}),p!==e.id&&f?.id!==e.id&&Z({type:`set_model`,modelId:e.id}),h(!1)},onToggleDefault:(e,t)=>{Z(t?{type:`clear_default_model`}:{type:`set_default_model`,modelId:e.id})},isRowActive:(e,t)=>(p===e.id||f?.id===e.id||`${e.provider}/${e.id}`===p)&&(!t||t.active),listRef:v}),A=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:d(`thinkingLevel`)}),T.map(t=>(0,$.jsx)(gt,{active:e?.thinkingLevel===t.value,disabled:!t.supported,title:t.supported?void 0:d(`thinkingUnsupported`),onClick:()=>{if(l){l(t.value),_(!1);return}e?.thinkingLevel!==t.value&&Z({type:`set_thinking`,level:t.value}),_(!1)},children:t.label},t.value))]}),j=(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{}),(0,$.jsx)(`span`,{className:`chip-model`,children:f?f.name:d(`selectModel`)}),!o&&f?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:d(`vision`),children:`🖼`}),!o&&f&&(0,$.jsx)(`span`,{className:`chip-sub`,children:f.provider})]}),open:m,onOpenChange:h,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:y,menuStyle:b==null?void 0:{width:b},direction:u,children:k}),M=(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(se,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:d(`thinkingChip`,{level:e?D(e.thinkingLevel):`—`})})]}),tip:d(`thinkingLevel`),open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:A});if(s===`model`)return j;if(s===`thinking`)return M;let N=e?.thinkingLevel&&e.thinkingLevel!==`off`;return(0,$.jsxs)(`div`,{className:`model-thinking-capsule`,children:[(0,$.jsx)(_t,{className:`capsule-dropdown capsule-model-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(E,{}),(0,$.jsx)(`span`,{className:`capsule-model-name`,children:f?f.name:d(`selectModel`)}),!o&&f?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:d(`vision`),children:`🖼`})]}),triggerClassName:`capsule-segment capsule-model`,open:m,onOpenChange:h,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:y,menuStyle:b==null?void 0:{width:b},direction:u,children:k}),(0,$.jsx)(`div`,{className:`capsule-divider`}),(0,$.jsx)(_t,{className:`capsule-dropdown capsule-thinking-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-pulse-dot ${N?`on`:``}`}),(0,$.jsx)(`span`,{className:`capsule-thinking-text`,children:e?D(e.thinkingLevel):`—`})]}),triggerClassName:`capsule-segment capsule-thinking`,open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:A})]})}),Gy=[`standard`,`ptc`,`minimal`,`cordis`],Ky={standard:`preset.standard`,minimal:`preset.minimal`,code:`preset.code`,reader:`preset.reader`,ask:`preset.ask`},qy={standard:`preset.standardDesc`,minimal:`preset.minimalDesc`,code:`preset.codeDesc`,reader:`preset.readerDesc`,ask:`preset.askDesc`};function Jy(e){return Ky[e]??null}function Yy(e){return qy[e]??null}function Xy(e,t,n){let r=H(t),i=Jy(e.id),a=Yy(e.id);return i&&a?{name:n(i),description:n(a)}:{name:r?e.name??e.id:e.nameEn??e.name??e.id,description:r?e.description:e.descriptionEn??e.description}}function Zy(e){return[...e].sort((e,t)=>{let n=Number.isSafeInteger(e.order)?e.order:Gy.indexOf(e.id),r=Number.isSafeInteger(t.order)?t.order:Gy.indexOf(t.id),i=n>=0?n:1e3,a=r>=0?r:1e3;return i===a?e.id.localeCompare(t.id):i-a})}var Qy=(0,Q.memo)(function({preset:e,presets:t,defaultPreset:n,blank:r,conversationId:i,compact:a=!1}){let o=V(),{locale:s}=Ue(),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(e?.id??n);if((0,Q.useEffect)(()=>{d(e?.id??n)},[i,e?.id,n]),t.length===0)return null;let f=e?.locked||!r,p=Zy(t),m=p.find(t=>t.id===e?.id),h=p.find(e=>e.id===u)??m,g=e=>Xy(e,s,o),_=m?g(m):void 0,y=t=>{d(t),l(!1),r&&t!==e?.id&&Z({type:`dsh_preset_select`,preset:t})};if(a){let t=_?.description??m?.id??o(`dshPreset`);return(0,$.jsx)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(v,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:f?`${t}(${o(`dshPresetLocked`)})`:t,children:[_?.name??m?.id??e?.name??o(`dshPreset`),f&&(0,$.jsx)(Oe,{style:{marginLeft:3}})]})]}),open:c&&!f,onOpenChange:l,direction:`up`,align:`left`,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(gt,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>y(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-presetbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(v,{}),o(`dshPreset`)]}),(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{title:_?.description??m?.id??``,children:[_?.name??m?.id??e?.name??`…`,f&&(0,$.jsxs)(`span`,{className:`dsh-preset-lock`,title:o(`dshPresetBlankOnly`),children:[(0,$.jsx)(Oe,{}),` `,o(`dshPresetLocked`)]})]}),open:c&&!f,onOpenChange:l,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(gt,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>y(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})}),!f&&(0,$.jsx)(`span`,{className:`dsh-preset-hint`,title:o(`dshPresetBlankOnly`),children:o(`dshPresetBlankOnly`)}),h?.id===`minimal`&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:o(`dshPresetMinimalNote`)}),(0,$.jsxs)(`button`,{type:`button`,className:`chip`,title:o(`dshPresetNewChat`),onClick:()=>{Z({type:`new_chat`,preset:h?.id??u}),Xt()},children:[(0,$.jsx)(rt,{}),` `,o(`dshPresetNewChat`)]})]})}),$y=[`read-only`,`workspace-write-never`,`danger-full-access`],eb=[`read-only`,`workspace-write-never`,`danger-full-access`];function tb(e){return e===`read-only`?`dshPermReadOnly`:e===`danger-full-access`?`dshPermFullAccess`:`dshPermWorkspaceWrite`}function nb(e){return e===`read-only`?`dshPermReadOnlyDesc`:e===`danger-full-access`?`dshPermFullAccessDesc`:`dshPermWorkspaceWriteDesc`}var rb=(0,Q.memo)(function({current:e,options:t,defaultPreset:n,conversationId:r,compact:i=!1}){let a=V(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{l(!1),s(!1)},[r]);let u=$y.filter(e=>t.some(t=>t.value===e));if(u.length===0)return null;let d=e??n,f=!!e&&!u.includes(e),p=e=>{if(e===`danger-full-access`&&e!==d&&!c){l(!0);return}l(!1),s(!1),e!==d&&Z({type:`dsh_permission_set`,preset:e})};if(i){let t=a(f?`dshPermCustom`:tb(d)),r=f?e??t:a(nb(d));return(0,$.jsxs)(_t,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(A,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r,children:[t,d===`danger-full-access`&&(0,$.jsx)(He,{style:{marginLeft:3}})]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},direction:`up`,align:`left`,children:[u.map(e=>(0,$.jsxs)(gt,{active:e===d,title:a(nb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(tb(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(nb(e))})]},e)),c&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:a(`dshPermConfirmFull`)})]})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-permissionbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(A,{}),a(`dshPerm`)]}),(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{title:f?e:a(nb(d)),children:[a(f?`dshPermCustom`:tb(d)),d===`danger-full-access`&&(0,$.jsxs)(`span`,{className:`dd-preset-tag warn`,children:[(0,$.jsx)(He,{}),` `,a(`dshPermFullAccessTag`)]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},children:u.map(e=>(0,$.jsxs)(gt,{active:e===d,title:a(nb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(tb(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(nb(e))})]},e))}),c&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:a(`dshPermConfirmFull`)})]})}),ib=Dy(),ab=40,ob=320,sb=`pi-web-ui:composer-height`;function cb(){return typeof window>`u`?ob:Math.max(160,Math.min(ob,Math.floor(window.innerHeight*.42)))}var lb=(0,Q.memo)(function({groupDevices:e,groupReady:t,onGroupSend:n,streaming:r,planMode:i,messages:a,slashCommands:o,modelState:s,models:c,modelsLoading:l,attachments:u,onRemoveAttachment:d,onAddImageFiles:f,onAddLocalFiles:p,onAddPathAttachment:m,fileSearch:h,onSearchFiles:g,onNotice:_,onSent:v,onManageModels:y,providerKeys:b,defaultModel:x,quickPhrases:S,quickPhrasesEnabled:w,recallDrafts:T,composerLeading:E,composerActions:D,onUiAction:O,dshPermCurrent:k,dshPermOptions:A,dshPermDefault:j,dshPreset:M,dshPresets:N,dshPresetDefault:P,dshBlank:F,conversationId:te,sessionDraft:ne,sessionId:re,preserveDraftAcrossConversations:I=!1}){let L=V(),ie=en(`ready`),ae=e?!!t:ie,oe=$t(),se=rn(),ce=!!(i&&se.planMode),{locale:R}=Ue(),le=Ry(ib),ue=le===`mod-enter`,{openPicker:z,templates:de}=D_(),B=y_(de,o),fe=[...o,...B.map(e=>({name:__(e.command??``),description:e.desc||e.title,source:`prompt`}))],pe=e=>!H(R)&&e.descriptionEn?e.descriptionEn:e.description??``,me=e=>!H(R)&&e.argumentHintEn?e.argumentHintEn:e.argumentHint??``,[he,U]=(0,Q.useState)(``),[W,G]=(0,Q.useState)(()=>{try{let e=Number(localStorage.getItem(sb));if(Number.isFinite(e)&&e>44)return Math.min(e,ob)}catch{}return null}),_e=(0,Q.useRef)(null),[K,q]=(0,Q.useState)(null),[J,Y]=(0,Q.useState)(0),ye=(0,Q.useRef)(0),xe=(0,Q.useRef)(new Map),Se=(0,Q.useRef)(``),[Ce,we]=(0,Q.useState)(!1),[Te,Ee]=(0,Q.useState)(void 0),X=(0,Q.useRef)(null),Oe=(0,Q.useRef)(null),ke=(0,Q.useRef)(null),Ae=(0,Q.useRef)(-1),je=(0,Q.useRef)(``),Me=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!T||T.length===0)return;let e=T.filter(e=>e.text&&e.seq>Me.current);e.length!==0&&(Me.current=e[e.length-1].seq,q(null),U(t=>{let n=e.reduce((e,t)=>Iv(e,t.text),t);return Se.current=n,n}),Ae.current=-1,je.current=``,requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}))},[T]),(0,Q.useEffect)(()=>{if(!e)return kt(e=>{q(null),U(t=>{let n=Iv(t,e);return Se.current=n,n}),Ae.current=-1,je.current=``,requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})}),()=>kt(null)},[]),(0,Q.useEffect)(()=>(Ot(()=>{ib||requestAnimationFrame(()=>{X.current?.focus()})}),()=>Ot(null)),[]);let Ne=(0,Q.useRef)(``);Ne.current=he,(0,Q.useEffect)(()=>{if(!e)return At(e=>{{let t=e.trim(),n=new Set([`.`,`*`,`+`,`?`,`^`,`$`,`{`,`}`,`(`,`)`,`|`,`[`,`]`,`\\`]),r=t.split(``).map(e=>n.has(e)?`\\`+e:e).join(``),i=RegExp(`(^|[\\s(("'“‘[【])`+r+`(?=[\\s,.;:!?,。!?)\\]】」]|$)`);if(t&&i.test(Ne.current))return}let t=X.current;if(!t){U(t=>{let n=t+(t&&!t.endsWith(` `)?` `:``)+e;return Se.current=n,n});return}let n=t.selectionStart??Ne.current.length,r=t.selectionEnd??Ne.current.length,i=Ne.current,a=(n>0&&!/[\s([{]$/.test(i.slice(0,n))?` `:``)+e,o=i.slice(0,n)+a+i.slice(r);Se.current=o,U(o);let s=n+a.length;requestAnimationFrame(()=>{t.focus(),t.selectionStart=t.selectionEnd=s})}),()=>At(null)},[]),(0,Q.useEffect)(()=>{if(!e)return Bt(e=>{U(t=>{let n=new Set([`.`,`*`,`+`,`?`,`^`,`$`,`{`,`}`,`(`,`)`,`|`,`[`,`]`,`\\`]),r=e.split(``).map(e=>n.has(e)?`\\`+e:e).join(``),i=RegExp(`(^|\\s)`+r+`(?:\\s|$)`,`g`),a=t.replace(i,(e,t)=>t===` `?` `:``);return a=a.replace(/ {2,}/g,` `).trim(),Se.current=a,a})}),()=>Bt(null)},[]);let Pe=2e4,Fe=re?`${te??``}${re}`:null,Ie=Fe&&re?`pi-web-ui:composer-draft:${re}`:null,Re=(0,Q.useRef)(``),ze=(0,Q.useRef)(0),Be=(0,Q.useRef)(!1),Ve=(0,Q.useRef)(0),He=(0,Q.useRef)(null),We=(0,Q.useRef)(null),Ge=(0,Q.useRef)(null),Ke=(0,Q.useRef)(I);Ke.current=I;let qe=Vy(),Je=e=>{try{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return typeof n.text!=`string`||!n.text||typeof n.ts!=`number`?null:{text:n.text.slice(0,Pe),ts:n.ts}}catch{return null}},Ye=(t,n,r,i)=>{let a=r.slice(0,Pe);try{a.trim()?localStorage.setItem(n,JSON.stringify({text:a,ts:i})):localStorage.removeItem(n)}catch{}e||Z({type:`draft_update`,sessionId:t,text:a,ts:i})},Xe=()=>{He.current&&=(clearTimeout(He.current),null),Be.current&&Fe&&Ie&&re&>&&Ye(re,Ie,Re.current,ze.current)},Ze=(0,Q.useRef)(new Set),Qe=(0,Q.useRef)([]),$e=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(Qe.current=[],$e.current=Ne.current,e&&re?.startsWith(`device-group:`))return xo(re.slice(13),e=>{if(Qe.current.find(t=>t.member.id===e.id)){X.current?.focus();return}let t=X.current,n=So(Ne.current,t?.selectionStart??Ne.current.length,e);Qe.current=ho(Ne.current,n.text,Qe.current),Qe.current.push({start:n.cursor-e.name.length-2,end:n.cursor-1,member:e}),$e.current=n.text,Re.current=n.text,Ne.current=n.text,Se.current=n.text,U(n.text),requestAnimationFrame(()=>{X.current?.focus(),X.current?.setSelectionRange(n.cursor,n.cursor)})})},[re,!!e]);let et=t=>{if(e){Qe.current=ho($e.current,t,Qe.current),$e.current=t;let n=new Set(fo(t,e));for(let e of Ze.current)n.has(e)||Ze.current.delete(e)}if(Re.current=t,Be.current=!0,ze.current=Date.now(),Ie){let e=t.slice(0,Pe);try{e.trim()?localStorage.setItem(Ie,JSON.stringify({text:e,ts:ze.current})):localStorage.removeItem(Ie)}catch{}}if(Fe&&re&>){He.current&&clearTimeout(He.current);let e=re,t=Ie,n=ze.current,r=Fe;He.current=setTimeout(()=>{He.current=null,r===We.current&&t&&Ye(e,t,Re.current,n)},2e3)}},tt=(e,t)=>{Ae.current=-1,U(e),it(e,t),et(e)};(0,Q.useEffect)(()=>{let e=Fe,t=re,n=Ie;return()=>{He.current&&=(clearTimeout(He.current),null);let r=Re.current;if(Be.current&&r.trim()){e&&t&&n&&Ye(t,n,r,ze.current);let i=jt(),a=i>0&&ze.current>i;Ge.current={text:r,userEditedAfterSwitch:a}}else Ge.current=null}},[Fe]),(0,Q.useEffect)(()=>{We.current=Fe;let e=Ge.current;Ge.current=null;let t=e?.text??null,n=e?.userEditedAfterSwitch??!1,r=Ie?Je(Ie):null,i=!!(ne&&ne.text?.trim()&&ne.ts>0||r&&r.text?.trim());Vv(t,n,a.length,i,Ke.current)&&t!==null&&Ie&&re?(Be.current=!0,Ve.current=Date.now(),Re.current=t,ze.current=Ve.current,U(t),i||Ye(re,Ie,t,ze.current)):(Be.current=!1,Ve.current=0,Re.current=``,ze.current=0,U(``)),q(null),Ae.current=-1},[Fe]);let nt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=a.length===0,t=nt.current!==null&&nt.current!==Fe,n=nt.current===null&&e;nt.current=Fe,ae&&!ib&&(t||n)&&requestAnimationFrame(()=>{X.current?.focus()})},[Fe,a.length,ae]),(0,Q.useEffect)(()=>{if(!Fe||!Ie||Be.current||Re.current!==``)return;let e=Lv(ne&&ne.text?{text:ne.text.slice(0,Pe),ts:ne.ts}:null,Je(Ie),Ve.current);e&&(Ve.current=e.ts,Re.current=e.text,ze.current=e.ts,U(e.text),it(e.text,null))});let rt={builtin:L(`slashBuiltin`),extension:L(`slashExtension`),prompt:L(`slashPrompt`),skill:L(`slashSkill`),plugin:L(`slashPlugin`)},it=(t,n)=>{Se.current=t;let r=t.match(/^\/([^\s]*)$/);if(r&&ae&&!e){let e=r[1].toLowerCase(),t=_y(fe,e);q(t.length>0?{kind:`slash`,items:t}:null),Y(0);return}if(n===null||!ae){q(null);return}let i=Ty(t,n);if(!i){q(null);return}if(e){let t=uo(e,i.query);q(t.length?{kind:`at`,start:i.start,end:n,items:t}:null),Y(0);return}let a=[];try{a=qt()}catch{a=[]}let s=++ye.current,c=t,l=i.start,u=i.query,d=l+1+u.length,f=a.map(e=>({id:e.id,label:e.label,run:()=>{let t;try{t=Wt(e.id)?.search}catch{t=void 0}return typeof t==`function`?t(u):Promise.resolve([])}}));f.push({id:`host:canvases`,label:L(`canvasTab`),run:async()=>ls(await us(()=>Z({type:`canvas_list`})),u,L(`canvasTab`))}),u&&typeof g==`function`&&f.push({id:`host:files`,label:L(`openFiles`),run:()=>at(u)});let p=[];if(se.pageRef&&(Ln(),p=yy(L(`browserControl`),In(),u),f.push({id:`host:pages`,label:L(`browserControl`),run:()=>Promise.resolve(p)})),f.length===0){q(null);return}let m=Sy(L(`slashSkill`),o,u,15,pe),h=Cy({pages:p,skills:m},u,30),_=!1;h.length>0&&(_=!0,q({kind:`at`,start:l,end:d,items:h}),Y(0)),Promise.allSettled(f.map(e=>Promise.race([e.run(),new Promise((e,t)=>setTimeout(()=>t(Error(`at-mention timeout`)),2e3))]))).then(e=>{if(ye.current!==s||Se.current!==c)return;let t=[],n=[],r=[],i=[];e.forEach((e,a)=>{e.status===`fulfilled`&&(f[a].id===`host:pages`&&Array.isArray(e.value)?n.push(...e.value):f[a].id===`host:canvases`&&Array.isArray(e.value)?t.push(...e.value):f[a].id===`host:files`?r.push(...by(f[a].label,e.value)):i.push(...xy(f[a].id,f[a].label,e.value)))});let a=Cy({canvases:t,pages:n,skills:m,files:r,plugins:i},u,30);q(a.length>0?{kind:`at`,start:l,end:d,items:a}:null),!_&&a.length>0&&Y(0)})},at=e=>{if(typeof g!=`function`)return Promise.resolve([]);let t=Uy();return new Promise(n=>{xe.current.set(t,n);try{g(t,e)}catch{xe.current.delete(t),n([]);return}setTimeout(()=>{xe.current.get(t)===n&&(xe.current.delete(t),n([]))},3e3)})};(0,Q.useEffect)(()=>{if(!h||!h.ok)return;let e=xe.current.get(h.reqId);e&&(xe.current.delete(h.reqId),e(h.results??[]))},[h]);let ot=e=>it(e,null);(0,Q.useEffect)(()=>{(ke.current?.querySelector(`.slash-item.active`))?.scrollIntoView({block:`nearest`})},[J,K]);let st=e=>{let t=K?.kind===`slash`?K.items:[],n=e??t[J%Math.max(t.length,1)];if(!n){q(null);return}let r=he.match(/^\/([^\s]*)([\s\S]*)$/),i=r?r[2]:``,a=`/${n.name} ${i}`;Se.current=a,U(a),et(a),q(null),X.current?.focus()},ct=(t,n)=>{let r=K?.kind===`at`?K:null,i=r?.items??[],a=t??i[J%Math.max(i.length,1)],o=n??r?.start;if(!a||o===void 0){q(null);return}let s=X.current,c=s?s.selectionStart??he.length:he.length,l=r?.end!==void 0&&r.end>=o?r.end:c,u=a.attachments??[],d=e&&a.providerId===`host:group-devices`?e.find(e=>e.id===a.hint):void 0,f=d?`@${d.name}`:a.text??a.title;e&&a.providerId===`host:group-devices`&&a.hint&&Ze.current.add(a.hint);let p=u.length>0&&!f.startsWith(`@`)?`@${f} `:`${f} `,h=`${he.slice(0,o)}${p}${he.slice(l)}`;Se.current=h,U(h),et(h),d&&Qe.current.push({start:o,end:o+f.length,member:d}),q(null);for(let e of u)try{m?.({path:e.path,name:e.name??e.path.split(`/`).pop()??e.path,...e.mode?{mode:e.mode}:{mode:`reference`},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{},...e.lines?{lines:e.lines}:{},silent:!0})}catch{}requestAnimationFrame(()=>{let e=X.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=o+p.length)})},lt=()=>K?.kind===`slash`?K.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===J?` active`:``}`,onMouseEnter:()=>Y(t),onClick:()=>dt(e),children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:rt[e.source]}),(0,$.jsxs)(`span`,{className:`slash-desc`,children:[pe(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:me(e)})]})]},e.name)):null,ut=()=>K?.kind===`at`?K.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===J?` active`:``}`,onMouseEnter:()=>Y(t),onClick:()=>dt(e),title:e.hint??e.title,children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`@`,e.title]}),(0,$.jsx)(`span`,{className:`slash-source ${e.providerId===`host:skills`?`skill`:`plugin`}`,children:e.providerLabel}),e.hint&&(0,$.jsx)(`span`,{className:`slash-desc`,children:e.hint})]},`${e.providerId}:${e.title}:${t}`)):null,dt=e=>{K&&(K.kind===`slash`?st(e):ct(e,K.start))},ft=async()=>{let e=[...a].reverse().find(e=>e.role===`assistant`&&e.content.some(e=>e.type===`text`&&e.text))?.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
68
|
+
`);if(!e){_(`warning`,L(`slashCopyEmpty`));return}await ic(e)?_(`info`,L(`slashCopied`)):_(`error`,L(`slashCopyFailed`))},pt=t=>{if(e)return;if(!t||t.length===0){_(`warning`,L(`foldersNotSupported`));return}let n=Array.from(t).filter(e=>tf(e.type)),r=Array.from(t).filter(e=>!tf(e.type)),i=ht();n.length>0&&i?_(`warning`,i):n.length>0&&f(n),r.length>0&&p(r)},mt=e=>{let t=$v(e.clipboardData?.items,e.clipboardData?.files);t.length!==0&&(e.preventDefault(),pt(t))},ht=()=>{let e=s?.model;if(!e?.id)return null;let t=c.find(t=>t.id===e.id);return t&&t.vision===!1?L(`modelNoVision`,{name:t.name}):null},gt=ae,_t=ae&&!!re,vt=(0,Q.useRef)(he);(0,Q.useEffect)(()=>{vt.current=he},[he]),(0,Q.useEffect)(()=>{!e&&/^\/[^\s]*$/.test(vt.current)&&ot(vt.current)},[o]);let[yt,bt]=(0,Q.useState)(null),xt=e=>{let t=yt;if(bt(null),t===null)return;let n=Uv(vt.current,t,e);n!==null&&(q(null),Se.current=n,U(n)),requestAnimationFrame(()=>X.current?.focus())};(0,Q.useEffect)(()=>{if(e)return;let t=e=>{let t=e.detail;if(typeof t==`string`){if(Hv(vt.current,t)){bt(t);return}q(null),Se.current=t,U(t),X.current?.focus()}};return window.addEventListener(`pi-web:fill`,t),()=>window.removeEventListener(`pi-web:fill`,t)},[]),(0,Q.useEffect)(()=>{if(!Ce&&yt===null)return;let e=e=>{e.key===`Escape`&&(yt===null?we(!1):(bt(null),requestAnimationFrame(()=>X.current?.focus())))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ce,yt]);let St=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=X.current,t=St.current;if(!e||!t)return;let n=e.closest(`main`)?.querySelector(`.messages`),r=t.getBoundingClientRect().height,i=n?.scrollTop??0,a=cb();e.style.maxHeight=`${a}px`;let o=W!=null&&W>44,s;e.style.height=`auto`;let c=e.scrollHeight;s=Math.min(o?W:Math.max(c,ab),a),e.style.height=`${s}px`,e.style.overflowY=c>s?`auto`:`hidden`,n&&(n.scrollTop=i+(t.getBoundingClientRect().height-r))},[he,W]);let Ct=(0,Q.useRef)(null),wt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Ct.current,t=wt.current,n=document.documentElement;if(!e&&!t){n.style.removeProperty(`--quick-row-h`);return}let r=()=>{let r=e?e.offsetHeight:0,i=t?t.offsetHeight:0,a=e&&t?6:0;n.style.setProperty(`--quick-row-h`,`${r+a+i}px`)};r();let i=new ResizeObserver(r);return e&&i.observe(e),t&&i.observe(t),()=>{i.disconnect(),n.style.removeProperty(`--quick-row-h`)}},[u.length,w,S.length]);let Tt=()=>u.map(e=>e.mode===`quote`?{path:``,mode:`quote`,quote:e.quote}:e.imageData?{path:``,imageData:e.imageData,mimeType:e.mimeType,name:e.name}:e.fileData?{path:``,fileData:e.fileData,mimeType:e.mimeType,name:e.name,size:e.size}:{path:e.path,mode:e.mode,...e.lines?{lines:e.lines}:{},...e.mode===`page`||e.mode===`canvas`?{name:e.name}:{},...e.mode===`conversation`?{name:e.name,...e.conversationId?{conversationId:e.conversationId}:{},...e.sessionPath?{sessionPath:e.sessionPath}:{}}:{}}),Et=()=>{if(Ie)try{localStorage.removeItem(Ie)}catch{}He.current&&=(clearTimeout(He.current),null),Be.current=!1,Ve.current=Date.now(),Re.current=``,ze.current=0},Dt=(0,Q.useRef)(!1),Mt=(t=!1)=>{let r=he.trim(),i=u.length>0;if(r||i){if(!gt){_(`error`,L(`netDisconnected`));return}if(!_t){_(`warning`,L(`sessionInitializingNotice`));return}if(e){if(!n||Dt.current)return;Dt.current=!0;let t=go(he,Qe.current);n(t.text.trim(),[...new Set([...t.targets,...fo(r,e).filter(e=>Ze.current.has(e))])]).then(e=>{e&&Re.current.trim()===r&&(U(``),Ze.current.clear(),Qe.current=[],$e.current=``,Et(),v())}).catch(e=>_(`error`,String(e))).finally(()=>{Dt.current=!1});return}if(!se.conversationRef&&u.some(e=>e.mode===`conversation`)){_(`warning`,H(R)?`当前底层智能体不支持跨对话引用(缺少 conversation_read 工具),请移除会话引用后再发送。`:`The current agent engine does not support conversation references (conversation_read tool unavailable). Remove conversation references before sending.`);return}if(r===`/help`){let e=X.current?.closest(`.inputbox`)?.getBoundingClientRect();Ee(e?.width),we(!0),U(``),Et(),X.current?.focus();return}if(r===`/copy`){U(``),Et(),X.current?.focus(),ft();return}if(Z({type:`prompt`,text:b_(r,B),queue:t,attachments:Tt()})){r&&uy(r),Ae.current=-1,je.current=``,U(``),Et(),v();let e=s?.model;e&&Mo(`${e.provider}/${e.id}`),X.current?.focus()}else _(`error`,L(`netDisconnected`))}},Nt=(t,n=!1)=>{if(e)return;let r=t.trim();if(r){if(!gt){_(`error`,L(`netDisconnected`));return}if(!_t){_(`warning`,L(`sessionInitializingNotice`));return}if(Z({type:`prompt`,text:r,queue:n,attachments:Tt()})){r&&uy(r),Ae.current=-1,je.current=``,Xe(),v();let e=s?.model;e&&Mo(`${e.provider}/${e.id}`),ib||X.current?.focus()}else _(`error`,L(`netDisconnected`))}},Pt=t=>{if(!qe.isImeKey(t.nativeEvent)){if(K&&K.items.length>0){let e=K.items.length;switch(t.key){case`ArrowDown`:t.preventDefault(),Y(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),Y(t=>(t-1+e)%e);return;case`Tab`:case`Enter`:t.preventDefault(),dt();return;case`Escape`:t.preventDefault(),q(null);return}}if(e&&(t.key===`Backspace`||t.key===`Delete`)&&!t.nativeEvent.isComposing){let e=X.current;if(e){let n=_o(he,e.selectionStart,e.selectionEnd,t.key,Qe.current);if(n){t.preventDefault();let r=he.slice(0,n.start)+he.slice(n.end);et(r),U(r),Ne.current=r,requestAnimationFrame(()=>e.setSelectionRange(n.start,n.start));return}}}if(t.key===`Backspace`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=X.current;if(e&&e.selectionStart===e.selectionEnd&&e.selectionStart>0){let n=e.selectionStart,r=zy(he.slice(0,n),n,u);if(r&&r.tokenStart>=0&&r.tokenStart<n){t.preventDefault();let e=r.tokenStart,i=he.slice(0,e)+he.slice(n);Se.current=i,U(i),requestAnimationFrame(()=>{X.current&&(X.current.selectionStart=X.current.selectionEnd=e)});let a=r.attachment;a&&d(a.key??(a.mode===`conversation`?`conv|${a.conversationId??``}|${a.sessionPath??``}`:a.path));return}}}if(!e&&(t.key===`ArrowUp`||t.key===`ArrowDown`)){if(t.ctrlKey||t.metaKey||t.altKey)return;let e=X.current;if(!e)return;let n=t.key===`ArrowUp`,r=Qv(e);if(n&&!r.first||!n&&!r.last||!n&&Ae.current===-1)return;let i=cy();if(i.length===0)return;if(t.preventDefault(),n){if(Ae.current===-1){je.current=he;let e=i.length-1;Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else if(Ae.current>0){let e=Ae.current-1;Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}}else{let e=Ae.current+1;if(e<i.length){Ae.current=e;let t=i[e];U(t),ot(t),requestAnimationFrame(()=>{let e=X.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else{Ae.current=-1;let e=je.current;U(e),ot(e),requestAnimationFrame(()=>{let t=X.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}}return}if(t.key===`Escape`&&Ae.current!==-1){t.preventDefault();let e=je.current;Ae.current=-1,U(e),ot(e),requestAnimationFrame(()=>{let t=X.current;t&&(t.selectionStart=t.selectionEnd=e.length)});return}if(Ay({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,isTouch:ib,pref:le})===`send`){t.preventDefault(),Mt();return}}},Ft=_t&&(he.trim()!==``||u.length>0),It=(0,Q.useMemo)(()=>wi((D??[]).filter(e=>e.source!==`host`&&!e.hidden)),[D]),Lt=(0,Q.useMemo)(()=>(E??[]).filter(e=>e.source!==`host`&&!e.hidden),[E]),Rt=D!==void 0,zt=(0,Q.useMemo)(()=>wi((D??[]).filter(e=>!e.hidden)),[D]),Vt=e=>{if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`composer-plugin-select`,title:e.hint||e.label,"aria-label":e.label,value:t,onChange:t=>O?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id)}let t=e.icon===`mic`?(0,$.jsx)(be,{}):e.icon===`camera`?(0,$.jsx)(ve,{}):e.icon||e.label;return(0,$.jsx)(`button`,{type:`button`,className:`btn composer-plugin-action`,"data-action":e.action,"data-plugin-slot-id":e.id,title:e.hint||e.label,"aria-label":e.label,onClick:()=>O?.(e),children:t},e.id)},Ht=se.steer!==!1&&!oe,Ut=()=>(0,$.jsx)(`div`,{className:`inputbox-actions`,children:r?Ft?(0,$.jsxs)(`div`,{className:`split-send${Ht?``:` single`}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`split-queue`,title:L(`supplementTip`),"aria-label":L(`queueFollowTag`),onClick:()=>Mt(!0),children:(0,$.jsx)(ge,{})}),Ht&&(0,$.jsx)(`button`,{type:`button`,className:`split-steer`,title:L(ue?`steerTipMod`:`steerTip`),"aria-label":L(`queueSteerTag`),onClick:()=>Mt(),children:(0,$.jsx)(De,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`btn stop`,title:L(`stopAgent`),onClick:()=>Z({type:`abort`}),children:(0,$.jsx)(C,{})}):(0,$.jsx)(`button`,{type:`button`,className:`btn send`,title:L(gt?_t?ue?`sendTipMod`:`sendTip`:`sessionInitializingNotice`:`netDisconnected`),disabled:!Ft,onClick:()=>Mt(),children:(0,$.jsx)(De,{})})}),Gt={"host:composer-upload":(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:L(`uploadFile`),disabled:!gt,onClick:()=>Oe.current?.click(),children:(0,$.jsx)(ee,{})}),"host:composer-templates":(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:L(`tpl.openPicker`),onClick:z,children:(0,$.jsx)(Le,{})}),"host:composer-model":(0,$.jsx)(Wy,{only:`model`,state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,defaultModel:x,compact:!0}),"host:composer-thinking":(0,$.jsx)(Wy,{only:`thinking`,state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,compact:!0}),"host:composer-dsh-perm":A&&A.length>0&&j!==void 0?(0,$.jsx)(rb,{compact:!0,current:k??null,options:A,defaultPreset:j,conversationId:te??``}):null,"host:composer-dsh-preset":N&&N.length>0&&P!==void 0?(0,$.jsx)(Qy,{compact:!0,preset:M??null,presets:N,defaultPreset:P,blank:F??!1,conversationId:te??``}):null,"host:composer-send":Ut()},Kt=e=>e.source===`host`?(0,$.jsx)(Q.Fragment,{children:Gt[e.id]??null},e.id):Vt(e);return(0,$.jsxs)(`div`,{ref:St,className:`inputbar`,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault(),e.stopPropagation(),pt(e.dataTransfer?.files??null)},children:[u.length>0&&(0,$.jsxs)(`div`,{className:`attach-row`,ref:Ct,children:[u.map(e=>e.mode===`quote`&&e.quote?(0,$.jsx)(Ss,{quote:e.quote,onRemove:()=>d(e.key??``)},e.key):(0,$.jsxs)(`span`,{className:`attach-chip ${e.imageData?`image`:e.fileData?`file`:e.mode}`,title:e.imageData?L(`attachImage`,{name:e.name}):e.fileData?L(`attachFile`,{name:e.name}):e.isDir?L(`folderRef`,{path:e.path}):e.mode===`page`?L(`attachPage`,{name:e.name}):e.mode===`canvas`?`${L(`canvasTab`)} · ${e.name}`:e.mode===`conversation`?L(`attachConversation`,{name:e.name}):e.mode===`reference`?L(`refOnly`,{path:e.path}):e.mode===`lines`&&e.lines?L(`attachLines`,{path:e.path,start:e.lines.start,end:e.lines.end}):L(`attachContent`,{path:e.path}),children:[e.imageData?`🖼`:e.fileData?`📄`:e.isDir?`📁`:e.mode===`page`?`🌐`:e.mode===`canvas`?`◇`:e.mode===`conversation`?`💬`:e.mode===`reference`?`🔗`:`📎`,e.name,e.mode===`lines`&&e.lines&&(0,$.jsxs)(`span`,{className:`attach-range`,children:[`L`,e.lines.start,`-`,e.lines.end]}),(0,$.jsx)(`button`,{type:`button`,className:`attach-remove`,title:L(`removeAttachment`),onClick:()=>d(e.key??(e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:e.path)),children:`×`})]},e.key??(e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`))),(0,$.jsx)(`span`,{className:`attach-hint`,children:L(`attachHint`)})]}),K&&K.items.length>0&&(0,$.jsxs)(`div`,{className:`slash-menu`,role:`listbox`,ref:ke,"aria-label":K.kind===`slash`?L(`slashCommands`):L(`atMentions`),"data-menu-kind":K.kind,children:[(0,$.jsxs)(`div`,{className:`slash-menu-hint`,children:[(0,$.jsx)(`span`,{children:K.kind===`slash`?L(`slashMenuHint`):L(`atMenuHint`)}),(0,$.jsx)(`span`,{className:`slash-menu-close`,onClick:()=>q(null),children:`Esc`})]}),K.kind===`slash`?lt():ut()]}),yt!==null&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>xt(`cancel`),children:(0,$.jsxs)(`div`,{className:`slash-help`,role:`dialog`,"aria-modal":`true`,"aria-label":L(`tpl.confirmFillTitle`),style:{maxWidth:420},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`div`,{className:`slash-help-head`,children:(0,$.jsx)(`span`,{children:L(`tpl.confirmFillTitle`)})}),(0,$.jsxs)(`div`,{className:`slash-help-body`,style:{padding:`12px 16px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 14px`,lineHeight:1.5},children:L(`tpl.confirmFillDesc`)}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:8,flexWrap:`wrap`},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,autoFocus:!0,onClick:()=>xt(`cancel`),children:L(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xt(`append`),children:L(`tpl.confirmFillAppend`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>xt(`overwrite`),children:L(`tpl.confirmFillOverwrite`)})]})]})]})}),Ce&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>we(!1),children:(0,$.jsxs)(`div`,{className:`slash-help`,style:Te?{width:Te}:void 0,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`slash-help-head`,children:[(0,$.jsxs)(`span`,{children:[`⚡ `,L(`slashHelpTitle`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>we(!1),children:L(`close`)})]}),(0,$.jsx)(`div`,{className:`slash-help-body`,children:fe.length===0?(0,$.jsx)(`div`,{className:`slash-help-empty`,children:L(`slashLoading`)}):fe.map(e=>(0,$.jsxs)(`div`,{className:`slash-help-row`,children:[(0,$.jsxs)(`span`,{className:`slash-help-cmd`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:rt[e.source]}),(0,$.jsxs)(`span`,{className:`slash-help-desc`,children:[pe(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:me(e)})]})]},e.name))})]})}),w&&S.length>0&&(0,$.jsx)(`div`,{className:`quick-row`,"aria-label":L(`quickPhrases`),ref:wt,children:S.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`quick-chip`,title:`${L(`quickPhrasesTip`,{text:e})}(${L(`quickPhrasesSendTip`)})`,disabled:!gt,onClick:()=>Nt(e),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),Nt(e,!0)},children:e},e))}),(0,$.jsxs)(`div`,{className:`inputbox`,"data-pi-anchor":`composer`,children:[(0,$.jsx)(`div`,{className:`composer-resize${W!=null&&W>44?` is-manual`:``}`,"aria-label":L(W!=null&&W>44?`composerResizeFixed`:`composerResize`),role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":Math.round(W??ab),"aria-valuemin":ab,"aria-valuemax":ob,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId);let t=X.current?.getBoundingClientRect().height;_e.current={startY:e.clientY,startH:typeof t==`number`&&Number.isFinite(t)?t:W??ab,next:null}},onPointerMove:e=>{let t=_e.current;if(!t)return;let n=cb(),r=Math.min(n,Math.max(ab,t.startH+(t.startY-e.clientY)));t.next=r,G(r<=44?null:r)},onPointerUp:()=>{let e=_e.current?.next;if(_e.current=null,e!=null)try{if(e<=44)G(null),localStorage.removeItem(sb);else{let t=Math.round(e);G(t),localStorage.setItem(sb,String(t))}}catch{}},onPointerCancel:()=>{_e.current=null},onDoubleClick:()=>{G(null);try{localStorage.removeItem(sb)}catch{}},children:(0,$.jsx)(`span`,{className:`composer-resize-tip`,children:L(W!=null&&W>44?`composerResizeFixed`:`composerResize`)})}),(0,$.jsx)(`input`,{ref:Oe,type:`file`,multiple:!0,hidden:!0,onChange:e=>{pt(e.target.files),e.target.value=``}}),(0,$.jsx)(`textarea`,{ref:X,value:he,rows:1,placeholder:L(gt?r?oe?`placeholderStreamingQueued`:`placeholderStreaming`:ce?`placeholderPlanMode`:ue?`placeholderIdleMod`:`placeholderIdle`:`placeholderConnecting`),disabled:!gt,onChange:e=>{tt(e.target.value,e.target.selectionStart??e.target.value.length)},onSelect:e=>{if(K?.kind===`at`){let t=e.target.selectionStart;(t<K.start||t>K.end)&&q(null)}},onCompositionEnd:qe.onCompositionEnd,onBlur:Xe,onKeyDown:Pt,onPaste:mt}),ce&&(0,$.jsxs)(`button`,{type:`button`,style:{display:`inline-flex`,alignItems:`center`,gap:4,fontSize:11,color:`var(--accent, #38bdf8)`,background:`var(--accent-soft, rgba(56, 189, 248, 0.1))`,padding:`2px 8px`,borderRadius:12,position:`absolute`,right:12,top:8,cursor:`pointer`,border:`1px solid var(--border, rgba(255, 255, 255, 0.1))`,zIndex:2},onClick:()=>Z({type:`set_plan_mode`,enabled:!1}),title:L(`planModeTip`),children:[`📋 `,L(`planModeBadge`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),(0,$.jsx)(`div`,{className:`composer-tools`,children:e?(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Ut()}):Rt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Lt.map(Vt),zt.start.map(Kt)]}),zt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:zt.center.map(Kt)}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:zt.end.map(Kt)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Lt.map(Vt),(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:L(`uploadFile`),disabled:!gt,onClick:()=>Oe.current?.click(),children:(0,$.jsx)(ee,{})}),It.start.map(Vt),(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:L(`tpl.openPicker`),onClick:z,children:(0,$.jsx)(Le,{})}),(0,$.jsx)(Wy,{state:s,models:c,modelsLoading:l,onManageModels:y,providerKeys:b,defaultModel:x,compact:!0}),A&&A.length>0&&j!==void 0&&(0,$.jsx)(rb,{compact:!0,current:k??null,options:A,defaultPreset:j,conversationId:te??``}),N&&N.length>0&&P!==void 0&&(0,$.jsx)(Qy,{compact:!0,preset:M??null,presets:N,defaultPreset:P,blank:F??!1,conversationId:te??``})]}),It.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:It.center.map(Vt)}),(0,$.jsxs)(`div`,{className:`composer-tools-right`,children:[It.end.map(Vt),Ut()]})]})})]})]})}),ub=(0,Q.memo)(function({goal:e,models:t,modelsLoading:n,activeConversationId:r,uiGoalbarActions:i,onUiAction:a}){let o=V(),{locale:c}=Ue(),l=!H(c)&&e.statusEn?e.statusEn:e.status||``,u=!H(c)&&e.wizard?.statusEn?e.wizard.statusEn:e.wizard?.status||``,d=$t(),f=rn(),p=!e.conversationId||e.conversationId===r,m=e.goal!==null&&p,h=p?e.roles?.executor:void 0,g=h?.convId,_=h?.activity?!H(c)&&h.activityEn?h.activityEn:h.activity:h?.streaming?`…`:void 0,v=e.locked&&e.maxRounds>0?e.maxRounds:0,y=v>0?H(c)?o(`goalBarRound`,{n:`${e.round}/${v}`}):`Round ${e.round}/${v}`:`${o(`goalBarRound`,{n:e.round})}${e.locked?` · ${o(`goalBarUnlimitedShort`)}`:``}`,b=(e.usage?.inputTokens??0)+(e.usage?.outputTokens??0),x=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,S=!d&&e.execModel===void 0,[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(e.reviewModel??``),[O,k]=(0,Q.useState)(e.maxRounds),[A,j]=(0,Q.useState)(e.locked),[M,N]=(0,Q.useState)(e.execModel??``),[P,ee]=(0,Q.useState)(!1),[F,te]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[ie,oe]=(0,Q.useState)(!0);(0,Q.useEffect)(()=>{D(e.reviewModel??``),k(e.maxRounds||0),j(e.locked),N(e.execModel??``)},[e.goal,e.reviewModel,e.maxRounds,e.locked,e.execModel]),(0,Q.useEffect)(()=>{P&&t.length===0&&!I&&!n&&(L(!0),Z({type:`list_models`}))},[P,t.length,I,n]),(0,Q.useEffect)(()=>{t.length>0&&L(!1)},[t.length]);let se=()=>E?t.find(e=>e.id===E)?.name??E:o(`goalBarUseMainModel`),ce=()=>M?t.find(e=>e.id===M)?.name??M:o(`goalBarUseMainModel`),le=()=>{let e=w.trim();e&&(Z({type:`set_goal`,goal:e,...E?{reviewModel:E}:{},maxRounds:O,locked:A,...M?{execModel:M}:{}}),T(``),oe(!1))},ue=()=>{let e=w.trim();Z({type:`set_plan_mode`,enabled:!0}),e&&(Z({type:`prompt`,text:e}),T(``))},z=()=>{let e=w.trim();e&&(Z({type:`start_goal_wizard`,text:e,...E?{wizardModel:E}:{},maxRounds:O,locked:A}),T(``),oe(!1))},de=i===void 0?[`host:goal-pill`,`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`,`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`,`host:goal-openrole`,`host:goal-clear`].map(e=>({id:e,source:`host`})):i.filter(e=>!e.hidden),B=e=>{let t=new Set(e);return de.filter(e=>t.has(e.id)||e.source!==`host`)},fe=(e,t)=>{let n=de.find(t=>t.id===e);return n?.labelExplicit?n.label:t},pe={"host:goal-pill":(0,$.jsxs)(`button`,{type:`button`,className:`goalbar-hint`,title:o(`goalBarPlaceholder`),onClick:()=>oe(!1),children:[(0,$.jsx)(lt,{}),` `,(0,$.jsx)(`span`,{children:fe(`host:goal-pill`,o(`goalBarTitle`))})]}),"host:goal-set":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn`,disabled:!w.trim(),onClick:le,children:fe(`host:goal-set`,o(`goalBarSet`))}),"host:goal-wizard":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action wizard`,disabled:!w.trim(),title:o(`goalWizardTip`),onClick:z,children:fe(`host:goal-wizard`,o(`goalWizardBtn`))}),"host:goal-plan":f.planMode?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action plan`,disabled:!w.trim(),title:o(`planActionTip`),onClick:ue,children:fe(`host:goal-plan`,o(`planActionBtn`))}):null,"host:goal-lock":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(A?`goalBarLocked`:`goalBarUnlocked`),onClick:()=>j(e=>(Z({type:`set_goal_prefs`,locked:!e}),!e)),children:A?(0,$.jsx)(Oe,{}):(0,$.jsx)(ae,{})}),"host:goal-collapse":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarClear`),onClick:()=>oe(!0),children:(0,$.jsx)(s,{})}),"host:goal-model":d?(0,$.jsx)(`p`,{className:`goalbar-dsh-note`,children:o(`dshNoReviewModel`)}):(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarReviewModel`)}: ${se()}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-model`,o(`goalBarReviewModel`))}:`}),(0,$.jsx)(`b`,{children:se()})]}),open:P,onOpenChange:ee,direction:`up`,children:(0,$.jsx)(Po,{models:t,modelsLoading:n,currentModelId:E||null,active:P,onEnsureModels:()=>{t.length===0&&!n&&!I&&(L(!0),Z({type:`list_models`}))},loading:I,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{D(e.id),ee(!1),Z({type:`set_goal_prefs`,reviewModel:e.id})},isRowActive:e=>No(e,E),extraTopRow:(0,$.jsx)(gt,{active:E===``,onClick:()=>{D(``),ee(!1),Z({type:`set_goal_prefs`,reviewModel:``})},children:o(`goalBarUseMainModel`)})})}),"host:goal-rounds":(0,$.jsxs)(`label`,{className:`goalbar-round`,title:o(`goalBarMaxRoundsTip`),children:[(0,$.jsx)(`span`,{children:fe(`host:goal-rounds`,o(`goalBarMaxRounds`))}),(0,$.jsx)(`input`,{type:`number`,min:0,step:1,value:O,placeholder:o(`goalBarUnlimitedShort`),onChange:e=>{let t=parseInt(e.target.value,10);if(Number.isNaN(t)||t<0){k(0);return}k(t)},onBlur:()=>Z({type:`set_goal_prefs`,maxRounds:O}),onKeyDown:e=>{e.key===`Enter`&&(Z({type:`set_goal_prefs`,maxRounds:O}),e.target.blur())}})]}),"host:goal-execmodel":d?null:(0,$.jsx)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarExecModel`)}: ${ce()} · ${o(`goalBarExecModelTip`)}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-execmodel`,o(`goalBarExecModel`))}:`}),(0,$.jsx)(`b`,{children:ce()})]}),open:F,onOpenChange:te,direction:`up`,children:(0,$.jsx)(Po,{models:t,modelsLoading:n,currentModelId:M||null,active:F,onEnsureModels:()=>{t.length===0&&!n&&!I&&(L(!0),Z({type:`list_models`}))},loading:I,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{N(e.id),te(!1),Z({type:`set_goal_prefs`,execModel:e.id})},isRowActive:e=>No(e,M),extraTopRow:(0,$.jsx)(gt,{active:M===``,onClick:()=>{N(``),te(!1),Z({type:`set_goal_prefs`,execModel:``})},children:o(`goalBarUseMainModel`)})})})},me=(e.wizard?.active??!1)&&p;if(me)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${me?`wizard`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`🔍`})}),(0,$.jsxs)(`span`,{className:`goalbar-text`,title:e.wizard?.draft??``,children:[o(`goalWizardRunning`),`: `,e.wizard?.draft]}),(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[o(`goalBarRound`,{n:(e.wizard?.step??0)+1}),` / `,e.wizard?.maxSteps??6]}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:u||o(`goalBarReviewing`)}),I_(B([`host:goal-clear`]),{...pe,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x`,title:o(`goalBarClear`),onClick:()=>{Z({type:`clear_goal`}),oe(!0)},children:(0,$.jsx)(R,{})})},a)]})});if(m)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${e.reviewing?`reviewing`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:e.reviewing?(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`◌`}):`🎯`}),(0,$.jsx)(`span`,{className:`goalbar-text`,title:e.goal??``,children:e.goal}),e.reviewing?(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[e.phase===`executing`?o(`goalBarExecuting`):o(`goalBarReviewing`),` `,y]}):(0,$.jsx)(`span`,{className:`goalbar-chip ${e.verdict===`pass`?`pass`:e.verdict===`fail`?`fail`:e.verdict===`blocked`?`blocked`:``}`,children:e.verdict===`pass`?o(`goalBarPassed`):e.verdict===`fail`?o(`goalBarFailed`):e.verdict===`blocked`?o(`goalBarBlocked`):`${o(`goalBarRound`,{n:e.round||1})} · ${e.locked?o(`goalBarLocked`):o(`goalBarUnlocked`)}`}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:l}),_&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:h?.convId,children:[`· `,_]}),b>0&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:`${e.usage?.inputTokens??0} in / ${e.usage?.outputTokens??0} out`,children:[`· `,x(b),` tokens`]}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)}),I_(B([`host:goal-openrole`,`host:goal-clear`]),{...pe,"host:goal-openrole":g?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarOpenExecTip`),onClick:()=>Z({type:`switch_conversation`,id:g}),children:(0,$.jsx)(Ze,{})}):null,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x${e.reviewing?` stopping`:``}`,title:fe(`host:goal-clear`,e.reviewing?o(`goalBarStop`):o(`goalBarClear`)),onClick:()=>{e.goal&&T(e.goal),Z({type:`clear_goal`}),oe(!1)},children:e.reviewing?(0,$.jsx)(C,{}):(0,$.jsx)(R,{})})},a)]})});if(ie){let e=I_(B([`host:goal-pill`]),pe,a);return e?(0,$.jsx)(`div`,{className:`goalbar-collapsed`,children:e}):null}return(0,$.jsxs)(`div`,{className:`goalbar`,children:[(0,$.jsxs)(`div`,{className:`goalbar-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(lt,{})}),(0,$.jsx)(`input`,{className:`goalbar-input`,autoFocus:!0,value:w,placeholder:o(`goalBarPlaceholder`),title:o(`goalBarPlaceholder`),onChange:e=>T(e.target.value),onKeyDown:e=>{e.key===`Enter`&&le()}}),I_(B([`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`]),pe,a)]}),(0,$.jsxs)(`div`,{className:`goalbar-opts`,children:[B([`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`]).filter(e=>e.source===`host`).map(e=>(0,$.jsx)(Q.Fragment,{children:pe[e.id]},e.id)),e.history&&e.history.length>0&&(0,$.jsxs)(_t,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:o(`goalHistory`),children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${o(`goalHistory`)}:`}),(0,$.jsx)(`b`,{children:e.history.length})]}),open:ne,onOpenChange:re,direction:`up`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:o(`goalHistory`)}),e.history.map((e,t)=>(0,$.jsx)(gt,{onClick:()=>{T(e.goal),re(!1)},children:(0,$.jsxs)(`span`,{className:`dd-model-cell`,title:e.goal,children:[(0,$.jsxs)(`span`,{className:`dd-model-name`,children:[e.verdict===`pass`?`✅ `:e.verdict===`fail`?`❌ `:`⚠️ `,e.goal.length>42?`${e.goal.slice(0,42)}…`:e.goal]}),(0,$.jsx)(`span`,{className:`dd-model-meta`,children:(0,$.jsxs)(`span`,{className:`dd-model-id`,children:[o(`goalBarRound`,{n:e.rounds}),` · `,new Date(e.finishedAt).toLocaleString()]})})]})},`${e.finishedAt}-${t}`))]}),(0,$.jsx)(`span`,{className:`goalbar-lock-hint`,children:o(A?`goalBarLocked`:`goalBarUnlocked`)}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)})]})]})});function db(e){return e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e}function fb(e,t,n){return!!(n&&t&&e&&n.path===t.path&&e.path===t.path&&(e.sandboxId===t.id||e.error&&e.sandboxId===``)&&e.requestId===n.requestId)}function pb(e){return!!(e&&!e.error&&e.expectedRevision&&e.added.length+e.modified.length+e.deleted.length>0)}function mb({mode:e,currentCwd:t,currentSandbox:n,sandboxDiff:r,projects:i,send:a,onClose:o}){let s=V(),c=n?.sourcePath||(!n&&t?t:i.find(e=>!e.sandbox)?.path||t||``),[l,d]=(0,Q.useState)(c?`import`:`blank`),[f,h]=(0,Q.useState)(c),[g,_]=(0,Q.useState)(!0),[v,y]=(0,Q.useState)(``),b=n?.sourcePath?`${n.sourcePath}-exp`:`~/projects/${(n?.name||`sandbox-app`).replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-|-$/g,``)||`sandbox-app`}`,[x,S]=(0,Q.useState)(b),[C,w]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(null),D=()=>{if(!n)return;let e={requestId:ht(),path:n.path};E(e),a({type:`diff_sandbox`,...e})};(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,Q.useEffect)(()=>{if(E(null),e===`apply`&&n?.path){let e={requestId:ht(),path:n.path};E(e),a({type:`diff_sandbox`,...e})}},[e,n?.path,a]);let O=i.filter(e=>!e.sandbox),k=e=>{e.preventDefault();let t=l===`import`?f.trim():void 0;(l!==`import`||t)&&(a({type:`create_sandbox`,name:v.trim()||void 0,sourcePath:t,ephemeral:g}),o())},A=e=>{e.preventDefault();let t=x.trim();t&&(a({type:`promote_sandbox`,path:n?.path,targetPath:t,switchToTarget:C}),o())},j=e=>{e.preventDefault(),n?.path&&M&&pb(r)&&r.expectedRevision&&(E(null),a({type:`apply_sandbox_to_source`,path:n.path,expectedRevision:r.expectedRevision}),o())},M=e===`apply`&&fb(r,n,T),N=M?r.added.length+r.modified.length+r.deleted.length:0,P=s(e===`create`?`sandboxModalTitle`:e===`promote`?`sandboxPromoteTitle`:`sandboxApplyTitle`);return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal sandbox-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,onClick:o,title:s(`close`),"aria-label":s(`close`),children:(0,$.jsx)(R,{})}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:(0,$.jsx)(An,{})}),(0,$.jsx)(`h2`,{children:P})]}),e===`create`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:k,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxModalSubtitle`)}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxModeLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`import`?`active`:``}`,onClick:()=>d(`import`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(at,{"aria-hidden":!0}),` `,s(`sandboxModeImport`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeImportDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`blank`?`active`:``}`,onClick:()=>d(`blank`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(p,{"aria-hidden":!0}),` `,s(`sandboxModeBlank`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeBlankDesc`)})]})]})]}),l===`import`&&(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxSourceLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:f,onChange:e=>h(e.target.value),placeholder:s(`sandboxSourcePlaceholder`),required:!0}),O.length>0&&(0,$.jsx)(`div`,{className:`sandbox-source-chips`,children:O.slice(0,6).map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-source-chip ${f===e.path?`active`:``}`,onClick:()=>h(e.path),title:e.path,children:[(0,$.jsx)(Be,{"aria-hidden":!0,style:{marginRight:4,verticalAlign:`-1px`}}),db(e.path)]},e.path))})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxLifecycleLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${g?`active`:``}`,onClick:()=>_(!0),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(u,{"aria-hidden":!0}),` `,s(`sandboxLifecycleEphemeral`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecycleEphemeralDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${g?``:`active`}`,onClick:()=>_(!1),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(ke,{"aria-hidden":!0}),` `,s(`sandboxLifecyclePermanent`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecyclePermanentDesc`)})]})]})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxNameLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:v,onChange:e=>y(e.target.value),placeholder:l===`import`&&f.trim()?`${db(f.trim())} (Sandbox)`:s(`sandboxNamePlaceholder`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:l===`import`&&!f.trim(),children:[(0,$.jsx)(An,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxCreateSubmit`)]})]})]}):e===`promote`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:A,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxPromoteSubtitle`,{name:n?.name||``})}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxPromoteTargetLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:x,onChange:e=>S(e.target.value),placeholder:s(`sandboxPromoteTargetPlaceholder`),autoFocus:!0,required:!0})]}),(0,$.jsxs)(`label`,{className:`sandbox-checkbox-row`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),(0,$.jsx)(`span`,{children:s(`sandboxPromoteSwitchLabel`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!x.trim(),children:[(0,$.jsx)(m,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxPromoteSubmit`)]})]})]}):(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:j,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxActionApplyConfirm`,{name:n?.name||``,source:n?.sourcePath||``})}),M?r.error?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:r.error}):(0,$.jsxs)(`div`,{className:`sandbox-diff-box`,children:[(0,$.jsx)(`div`,{className:`sandbox-diff-stats`,children:s(`sandboxDiffStats`,{added:r.added.length,modified:r.modified.length,deleted:r.deleted.length,unchanged:r.unchangedCount})}),r.added.length+r.modified.length+r.deleted.length===0?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:s(`sandboxDiffEmpty`)}):(0,$.jsxs)(`div`,{className:`sandbox-diff-list`,children:[r.added.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item added`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag added`,children:`+`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`a:${e}`)),r.modified.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item modified`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag modified`,children:`~`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`m:${e}`)),r.deleted.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item deleted`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag deleted`,children:`-`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`d:${e}`))]}),(0,$.jsx)(`div`,{className:`sandbox-diff-note`,children:s(`sandboxDiffDeletedNote`)})]}):(0,$.jsx)(`div`,{className:`sandbox-diff-loading`,children:s(`loading`)}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:D,children:s(`sandboxDiffRefresh`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!M||!pb(r),children:[(0,$.jsx)(z,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxApplySubmit`,{count:N})]})]})]})]})})}var hb=({worktree:e,onRefresh:t,onSwitch:n,onRemove:r})=>{let i=V(),[a,o]=(0,Q.useState)(!1),s=e=>{let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return t[t.length-1]||e},c=e.linkedWorktrees||[],l=JSON.stringify(c.map(e=>e.path).sort()),u=`pi-worktree-dismiss:${e.mainPath}`,[d,f]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{try{f(localStorage.getItem(u))}catch{f(null)}},[u]);let p=(0,Q.useRef)(t);if(p.current=t,(0,Q.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&p.current()};e();let t=window.setInterval(e,3e4);return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.clearInterval(t),window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[e.mainPath]),e.isLinkedWorktree){let t=e.branch||s(e.currentPath);return(0,$.jsxs)(`div`,{className:`worktree-banner linked`,role:`region`,"aria-label":t,children:[(0,$.jsxs)(`div`,{className:`worktree-banner-info`,children:[(0,$.jsxs)(`span`,{className:`worktree-banner-title`,children:[`🌿 `,i(`worktreeBannerActiveTitle`,{branch:t}),(0,$.jsx)(`span`,{className:`lp-worktree-badge linked`,children:i(`worktreeBadgeLinked`)})]}),(0,$.jsx)(`span`,{className:`worktree-banner-desc`,children:i(`worktreeBannerActiveDesc`,{main:e.mainPath,mainBranch:e.mainBranch||`main`})})]}),(0,$.jsxs)(`div`,{className:`worktree-banner-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn primary`,title:i(`worktreeActionSwitchMainTip`),onClick:()=>n(e.mainPath),children:[`⬅️ `,i(`worktreeActionSwitchMain`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn danger`,title:i(`worktreeActionRemoveTip`),onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.currentPath)},children:[`🗑️ `,i(`worktreeActionRemove`)]})]})]})}if(c.length===0||d===l)return null;let m=()=>{f(l);try{localStorage.setItem(u,l)}catch{}},h=c.filter(e=>e.isDirty).length,g=c.map(e=>{let t=e.branch||s(e.path);return e.isDirty?`${t}*`:t}).join(` · `);return(0,$.jsxs)(`div`,{className:`worktree-banner notice`,role:`region`,"aria-label":`Git Worktrees`,children:[(0,$.jsxs)(`div`,{className:`worktree-banner-info`,children:[(0,$.jsxs)(`span`,{className:`worktree-banner-title`,children:[`⚠️ `,i(`worktreeBannerUncleanedTitle`,{count:c.length}),h>0&&(0,$.jsx)(`span`,{className:`lp-worktree-badge dirty`,children:i(`worktreeBadgeDirtyCount`,{count:h})})]}),(0,$.jsx)(`span`,{className:`worktree-banner-desc`,children:i(`worktreeBannerUncleanedDesc`,{names:g})})]}),(0,$.jsxs)(`div`,{className:`worktree-banner-actions`,children:[c.slice(0,2).map(e=>{let t=e.branch||s(e.path);return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn`,title:i(`worktreeActionSwitchToTip`,{name:t}),onClick:()=>n(e.path),children:[`➡️ `,i(`worktreeActionSwitchTo`,{name:t})]}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn danger`,title:i(`worktreeActionRemoveTip`),onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.path)},children:`🗑️`})]},e.path)}),c.length>2&&(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn`,onClick:()=>o(!a),children:a?i(`worktreeActionCollapse`):i(`worktreeActionMore`,{count:c.length-2})}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-close`,title:i(`worktreeActionDismissTip`),"aria-label":i(`worktreeActionDismiss`),onClick:m,children:(0,$.jsx)(R,{"aria-hidden":!0})})]}),a&&c.length>2&&(0,$.jsx)(`div`,{className:`worktree-banner-expand`,children:c.slice(2).map(e=>{let t=e.branch||s(e.path);return(0,$.jsxs)(`div`,{className:`worktree-expand-row`,children:[(0,$.jsxs)(`span`,{className:`worktree-expand-name`,children:[t,e.isDirty&&(0,$.jsx)(`span`,{className:`lp-worktree-badge dirty`,children:i(`worktreeBadgeDirtyCount`,{count:e.uncommittedCount||1})})]}),(0,$.jsxs)(`div`,{className:`worktree-expand-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`worktree-banner-btn`,onClick:()=>n(e.path),children:[`➡️ `,i(`worktreeActionSwitchTo`,{name:t})]}),(0,$.jsx)(`button`,{type:`button`,className:`worktree-banner-btn danger`,onClick:()=>{window.confirm(i(`worktreeActionRemoveConfirm`,{path:t}))&&r(e.path)},children:`🗑️`})]})]},e.path)})})]})},gb=[{id:`host:conn`,align:`start`},{id:`host:engine`,align:`start`},{id:`host:ctx`,align:`start`},{id:`host:cost`,align:`start`},{id:`host:cache`,align:`start`},{id:`host:msg-count`,align:`start`},{id:`host:plugin-status`,align:`start`},{id:`host:status-delegate`,align:`start`},{id:`host:working`,align:`start`},{id:`host:host-metrics`,align:`end`},{id:`host:cwd`,align:`end`}];function _b({chat:e,bottombarItems:t,onUiAction:n,onOpenSettings:r,onViewChange:i,onOpenGlobalSearch:a,onOpenBgTasks:o}){let s=en(`workspaceRoots`),c=e.state,[l,u]=(0,Q.useState)(!1);if(!c)return null;let d=t?t.map(e=>({id:e.id,entry:e,fallbackAlign:`start`})):gb.map(({id:e,align:t})=>({id:e,entry:null,fallbackAlign:t})),f=[],p=[],m=[];for(let{id:t,entry:s,fallbackAlign:c}of d){if(s?.hidden)continue;let d=s??{id:t,slot:`bottombar`,source:`host`,label:t.slice(5),kind:`action`,order:100,align:c,hidden:!1,userOverrides:[],arrangedBy:[]},h=(0,$.jsx)(ro,{entry:d,bar:`bottom`,chat:e,view:void 0,onViewChange:i,onOpenSettings:r,onOpenGlobalSearch:a,onOpenBgTasks:o,onOpenProjectPicker:()=>u(!0),isProjectPickerOpen:l,onUiAction:n});if(!h)continue;let g=d.align??c;g===`end`?m.push({key:t,node:h}):g===`center`?p.push({key:t,node:h}):f.push({key:t,node:h})}let h=e=>e.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.key));return(0,$.jsxs)(`footer`,{className:`statusbar`,children:[(0,$.jsx)(`div`,{className:`statusbar-left`,children:h(f)}),p.length>0&&(0,$.jsx)(`div`,{className:`statusbar-center`,children:h(p)}),(0,$.jsx)(`div`,{className:`statusbar-right`,children:h(m)}),l&&(0,$.jsx)(ba,{open:!0,currentCwd:c.cwd,pathCompletions:e.pathCompletions,workspaceRoots:s,onClose:()=>u(!1),onSelectDirectory:e=>{e&&e!==c.cwd&&Z({type:`set_cwd`,path:e}),u(!1)},mode:`folder`})]})}var vb=[{slot:`topbar.primary`,labelKey:`uiLayoutTopbar`,alignable:!0,vertical:!1},{slot:`bottombar`,labelKey:`uiLayoutBottombar`,alignable:!0,vertical:!1},{slot:`sidebar.left`,labelKey:`uiLayoutSidebarLeft`,alignable:!0,vertical:!0},{slot:`sidebar.right`,labelKey:`uiLayoutSidebarRight`,alignable:!0,vertical:!0}],yb=`__tray`,bb=[`start`,`center`,`end`];function xb(e,t){return e(t===`start`?`uiLayoutAlignTop`:t===`end`?`uiLayoutAlignBottom`:`uiLayoutAlignMiddle`)}function Sb(e,t=new Set){let n={},r=[],i=new Set;for(let a of vb){let o=(e[a.slot]??[]).filter(e=>!t.has(e.id));n[a.slot]=o;for(let e of o)e.hidden&&(r.push(e),i.add(e.id))}for(let n of e[`topbar.overflow`]??[])t.has(n.id)||i.has(n.id)||(r.push(n),i.add(n.id));return{zones:n,tray:r}}function Cb(e,t){for(let n of Object.values(e.zones)){let e=n.find(e=>e.id===t);if(e)return e}return e.tray.find(e=>e.id===t)}function wb(e){return(e??[]).filter(e=>!e.hidden)}function Tb(e,t){let n=wb(e);return t===void 0?n:n.filter(e=>(e.align??`start`)===t)}function Eb(e){return[...new Set(e)]}function Db(e,t,n){let r=e??{},i=Cb(t,n.id);if(!i)return r;let a={...r};i.hidden&&(a.hidden=(r.hidden??[]).filter(e=>e!==n.id),a.shown=Eb([...r.shown??[],n.id])),i.slot!==n.slot&&(a.slots={...r.slots,[n.id]:n.slot});let o=n.align;o!==void 0&&(i.align??`start`)!==o&&(a.align={...r.align,[n.id]:o});let s=t.zones[n.slot]??[],c=wb(s),l=e=>o===void 0||(e.align??`start`)===o,u=c.filter(e=>e.id!==n.id&&l(e)).map(e=>e.id),d=Math.max(0,Math.min(Math.trunc(n.index)||0,u.length));u.splice(d,0,n.id);let f=o===void 0?[]:c.filter(e=>e.id!==n.id&&!l(e)).map(e=>e.id),p=new Set(s.map(e=>e.id));return a.order=Eb([...(r.order??[]).filter(e=>!p.has(e)&&e!==n.id),...u,...f]),a}function Ob(e,t){let n=e??{};return{...n,hidden:Eb([...n.hidden??[],t]),shown:(n.shown??[]).filter(e=>e!==t)}}function kb({side:e,items:t,chat:n,view:r,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenBgTasks:s,onOpenGlobalSearch:c,onUiAction:l,uiContextTopbar:u,onOpenProjectPicker:d,onThemeToggle:f,onSoundToggle:p,zenMode:m,onToggleZenMode:h,dropdownProps:g,plugins:_,onOpenPluginMenu:v,isPluginMenuOpen:y}){let{t:b}=Ue(),[x,S]=(0,Q.useState)(!1),C=(0,Q.useRef)(null),w=n.settings?.uiLayout?.sideDockFloat===!0,T=w?` side-dock-float`:``,E=t.filter(e=>!e.hidden);if(E.length===0)return null;if(w&&x)return(0,$.jsx)(`div`,{ref:C,className:`side-dock side-dock-${e} side-dock-collapsed${T}`,children:(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-toggle-btn`,"data-tip":`${b(`sideDockExpand`)} (${E.length})`,onClick:()=>S(!1),"aria-label":b(`sideDockExpand`),children:e===`left`?(0,$.jsx)(P,{}):(0,$.jsx)(it,{})})});let D=wi(E),O=t=>(0,$.jsx)(ro,{entry:t,bar:e,chat:n,view:r,plugins:_,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenGlobalSearch:c,onOpenBgTasks:s,onOpenProjectPicker:d,onOpenPluginMenu:v,isPluginMenuOpen:y,onUiAction:l,uiContextEntries:u,zenMode:m,onToggleZenMode:h,dropdownProps:g},t.id);return(0,$.jsxs)(`div`,{ref:C,className:`side-dock side-dock-${e}${T}`,children:[w&&(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-collapse-btn`,"data-tip":b(`sideDockCollapse`),onClick:()=>S(!0),"aria-label":b(`sideDockCollapse`),children:e===`left`?(0,$.jsx)(it,{}):(0,$.jsx)(P,{})}),bb.map(e=>(0,$.jsx)(`div`,{className:`side-dock-slot side-dock-slot-${e}`,children:D[e].length>0&&(0,$.jsx)(`div`,{className:`side-dock-seg`,children:D[e].map(O)})},e))]})}function Ab(e){let t=e.trim().toLowerCase();return/^(yes|allow|approve|confirm|ok|是|允许|同意|确认|放行)/i.test(t)}function jb(e){let t=e.trim().toLowerCase();return/^(no|deny|reject|cancel|block|否|拒绝|取消|阻止)/i.test(t)}function Mb(e){if(!e)return{hasRisk:!1,intro:``,command:null,outro:``};let t=/⚠️|danger|warning|高危|危险/i.test(e)||/\b(rm\s+-[a-zA-Z]*r[a-zA-Z]*f|chmod\s+(-R\s+)?777|mkfs|dd\s+if=|chown\s+-R|> \/dev\/|sudo\s+rm|drop\s+database|truncate\s+table)\b/i.test(e),n=e.match(/([\s\S]*?)```(?:[a-zA-Z0-9_-]*)\n([\s\S]*?)```([\s\S]*)/);if(n)return{hasRisk:t,intro:n[1].trim(),command:n[2].trim(),outro:n[3].trim()};let r=e.split(`
|
|
69
69
|
`),i=-1,a=-1;for(let e=0;e<r.length;e++){let t=r[e],n=t.trim();if(/^(printf|rm|npm|npx|git|pnpm|yarn|docker|curl|cat|sh|bash|sudo|cp|mv|find|kill|echo|node|python|cargo|make|set|export|source|env|touch|mkdir|chmod|chown)\b/i.test(n)||/^[A-Za-z_][A-Za-z0-9_]*=/.test(n)||t.startsWith(` `)&&n.length>0||t.startsWith(`$ `))i===-1&&(i=e),a=e;else if(i!==-1&&n.length>0)break}if(i!==-1&&(a>i||/command|命令/i.test(e))){let e=r.slice(0,i).join(`
|
|
70
70
|
`).trim(),n=r.slice(i,a+1).map(e=>e.startsWith(`$ `)?e.slice(2):e.startsWith(` `)?e.trimStart():e).join(`
|
|
71
71
|
`).trim(),o=r.slice(a+1).join(`
|
|
72
|
-
`).trim();if(n.length>0)return{hasRisk:t,intro:e,command:n,outro:o}}return{hasRisk:t,intro:e,command:null,outro:``}}function
|
|
73
|
-
`),[e]),u=l.length>8;return(0,$.jsxs)(`div`,{className:`dialog-cmd-box ${t?`has-risk`:``}`,children:[t&&(0,$.jsxs)(`div`,{className:`dialog-cmd-risk`,children:[(0,$.jsx)(He,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorRisk`)})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-head`,children:[(0,$.jsxs)(`div`,{className:`dialog-cmd-tag`,children:[(0,$.jsx)(o,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorTitle`)}),(0,$.jsx)(`span`,{className:`dialog-cmd-badge`,children:n(`cmdInspectorLines`,{n:l.length})})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-actions`,children:[u&&(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>c(e=>!e),title:n(a?`cmdInspectorCollapse`:`cmdInspectorExpand`),children:[a?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{}),(0,$.jsx)(`span`,{children:n(a?`cmdInspectorCollapse`:`cmdInspectorExpand`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>{i(e)},title:n(`copy`),children:[r?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{children:n(r?`cmdCopied`:`copy`)})]})]})]}),(0,$.jsx)(`div`,{className:`dialog-cmd-code ${a?`expanded`:``}`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`dialog-cmd-line`,children:[(0,$.jsx)(`span`,{className:`cmd-line-num`,children:t+1}),(0,$.jsx)(`span`,{className:`cmd-line-text`,children:e})]},t))})})})]})}function
|
|
74
|
-
`)[0].trim():``,h=d.some(
|
|
75
|
-
`)||p.length>50||!f||e.code)&&(0,$.jsx)(
|
|
76
|
-
`),F=P.length>0||ee.length>0,te=P||ee;return(0,Q.useEffect)(()=>{if(f)return;let e=e=>{let t=e.target;if(!(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)){if(e.key>=`1`&&e.key<=`9`){let t=parseInt(e.key,10)-1;if(t<E.length){e.preventDefault(),k(T.id,E[t].label,!!T.multiSelect);return}}if(e.key===`ArrowLeft`&&w>0){e.preventDefault(),g(w-1);return}if(e.key===`ArrowRight`&&w<C-1&&j(T.id)){e.preventDefault(),g(w+1);return}e.key===`Enter`&&j(T.id)&&(e.preventDefault(),A())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f,E,T.id,T.multiSelect,w,C,j,A,k]),(0,$.jsxs)(`div`,{className:`dialog-inline${f?` collapsed`:``}`,"data-dialog-kind":`select`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,onClick:f?()=>p(!1):void 0,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:a(`modelQuestion`)}),o&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:o,children:o}),C>1&&(0,$.jsx)(`span`,{className:`question-progress`,children:a(`questionStep`,{cur:w+1,total:C})}),_>=0&&(0,$.jsx)(`span`,{className:`question-timer`,children:_>0?a(`questionTimeout`,{s:_}):a(`questionTimeoutExpired`)}),f&&(0,$.jsx)(`span`,{className:`question-collapsed-preview`,title:N,children:N}),(0,$.jsxs)(`div`,{className:`dialog-head-actions`,children:[i&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:e=>{e.stopPropagation(),i()},children:a(`questionQueueNavigate`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-toggle-collapse`,title:a(f?`expandSection`:`collapseSection`),onClick:e=>{e.stopPropagation(),p(e=>!e)},children:f?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:F?`modelQuestionRejectWithNoteTip`:`cancel`),onClick:e=>{e.stopPropagation(),r?r():b(F?te:void 0)},children:`✕`})]})]}),!f&&(0,$.jsxs)($.Fragment,{children:[C>1&&(0,$.jsx)(`div`,{className:`question-step-pills`,role:`tablist`,children:S.map((e,t)=>{let n=t===w,r=j(e.id),i=e.header||`${a(`modelQuestion`)} ${t+1}`;return(0,$.jsxs)(`button`,{type:`button`,className:`question-step-pill${n?` active`:``}${r?` done`:``}`,onClick:()=>g(t),title:i,"aria-selected":n,children:[(0,$.jsx)(`span`,{className:`question-step-pill-idx`,children:r&&!n?`✓`:t+1}),(0,$.jsx)(`span`,{className:`question-step-pill-label`,children:i})]},e.id)})}),(0,$.jsxs)(`div`,{className:`set-section`,children:[(0,$.jsx)(`div`,{className:`set-section-title`,children:T.header??`${a(`modelQuestion`)} ${w+1}`}),(0,$.jsx)(`div`,{className:`question-head`,children:(0,$.jsx)(al,{text:T.question,rawHtml:!0})}),T.detail&&(0,$.jsx)(`div`,{className:`set-hint`,children:(0,$.jsx)(al,{text:T.detail,rawHtml:!0})}),E.length>0&&(0,$.jsx)(`div`,{className:`set-list`,children:E.map((e,t)=>{let n=(c[T.id]??[]).includes(e.label),r=e.recommended??(t===0&&E.length>1),i=t<9?t+1:void 0;return(0,$.jsx)(Yb,{label:e.label,description:e.description,mark:T.multiSelect?n?`☑ `:`☐ `:n?`● `:`○ `,active:n,keyNumber:i,recommended:r,onPick:()=>k(T.id,e.label,!!T.multiSelect)},e.label)})}),M.length>0&&(0,$.jsxs)(`div`,{className:`question-preview`,children:[(0,$.jsx)(`div`,{className:`question-preview-label`,children:a(`optionPreview`)}),M.map((e,t)=>(0,$.jsx)(`div`,{className:`question-preview-body`,children:(0,$.jsx)(al,{text:e,rawHtml:!0})},t))]}),(0,$.jsx)(`input`,{className:`set-prompt-input question-custom`,placeholder:a(`modelQuestionCustom`),value:u[T.id]??``,onChange:e=>d(t=>({...t,[T.id]:e.target.value})),onCompositionEnd:m.onCompositionEnd,onKeyDown:e=>{m.isImeKey(e.nativeEvent)||e.key===`Enter`&&(e.preventDefault(),j(T.id)&&A())}})]},T.id),(0,$.jsxs)(`div`,{className:`dialog-nav`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss-inline${F?` reject-note`:``}`,onClick:()=>b(F?te:void 0),title:a(F?`modelQuestionRejectWithNoteTip`:`cancel`),children:a(F?`modelQuestionRejectWithNote`:`cancel`)}),(0,$.jsxs)(`div`,{className:`dialog-nav-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-prev`,disabled:w===0,onClick:()=>g(w-1),children:a(`previous`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-submit`,disabled:!j(T.id),onClick:A,children:w===C-1?a(`modelQuestionSubmit`):a(`next`)})]})]})]})]})}function Yb({label:e,description:t,mark:n,active:r,keyNumber:i,recommended:a,onPick:o}){let s=(0,Q.useRef)(null),c=V();return(0,$.jsxs)(`button`,{type:`button`,ref:s,className:`set-row question-option${r?` active`:``}`,onClick:o,children:[(0,$.jsxs)(`div`,{className:`set-row-name`,children:[i!==void 0&&(0,$.jsx)(`span`,{className:`question-key-badge`,title:c(`keyShortcutTip`,{key:i}),children:i}),(0,$.jsx)(`span`,{className:`question-mark`,children:n}),(0,$.jsx)(al,{text:e,rawHtml:!0}),a&&(0,$.jsx)(`span`,{className:`question-recommended-badge`,children:c(`recommended`)})]}),t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`set-row-desc`,children:(0,$.jsx)(al,{text:t,rawHtml:!0})}),(0,$.jsx)(Bb,{anchorRef:s,enabled:Qi(),className:`question-desc-tip`,children:(0,$.jsx)(al,{text:t,rawHtml:!0})})]})]})}function Xb({items:e,itemKey:t,title:n,summary:r,canAutoOpen:i,createdAt:a,onNavigate:o,canNavigate:s,children:c}){let l=V(),[u,d]=(0,Q.useState)(()=>new Set),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(Date.now),g=rs(e,t,f,u,i),_=g?t(g):null;(0,Q.useEffect)(()=>{p(_)},[_]);let v=e.some(e=>a(e)>0);return(0,Q.useEffect)(()=>{if(!v)return;h(Date.now());let e=setInterval(()=>h(Date.now()),1e3);return()=>clearInterval(e)},[v]),e.length?(0,$.jsxs)(`section`,{className:`question-queue`,"aria-label":n,children:[(0,$.jsxs)(`div`,{className:`question-queue-list`,children:[(0,$.jsxs)(`div`,{children:[n,` · `,e.length]}),e.filter(e=>e!==g).map(e=>(0,$.jsxs)(`div`,{className:`question-queue-item`,children:[(0,$.jsx)(`div`,{className:`question-queue-summary`,children:r(e)}),Fb(a(e),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,Fb(a(e),m)]}),(0,$.jsxs)(`div`,{className:`question-queue-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>p(t(e)),children:l(`questionQueueOpen`)}),o&&s?.(e)&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>o(e),children:l(`questionQueueNavigate`)})]})]},t(e)))]}),g&&(0,$.jsxs)(`div`,{className:`question-queue-dialog`,children:[Fb(a(g),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,Fb(a(g),m)]}),c(g,()=>{d(e=>new Set(e).add(t(g))),p(null)})]},_)]}):null}function Zb({questions:e,activeConversationId:t,mode:n}){let r=V(),i=e=>{let t=Pb(e);t&&Z(t)};return(0,$.jsx)(Xb,{items:e.filter(e=>e.audience===`user`),itemKey:Lb,title:r(`questionQueueTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.questions[0]?.header||e.questions[0]?.question||r(`modelQuestion`)]}),createdAt:e=>e.createdAt,canAutoOpen:e=>n!==`manual`&&(n===`all`||e.conversationId===t||!e.conversationId),onNavigate:i,canNavigate:e=>!!(e.rootConversationId||e.conversationId)&&(!!e.owner||(e.conversationId?e.conversationId!==t:!Rb(e,t))),children:(e,t)=>(0,$.jsx)(Jb,{question:e,owner:e.owner,onDefer:t,onNavigate:e.rootConversationId||e.conversationId?()=>i(e):void 0},Lb(e))})}function Qb({entry:e}){let t=(0,Q.useRef)(null),n=V();return(0,Q.useEffect)(()=>{let r=t.current;if(!r)return;let{container:i,cleanup:a}=dm(r,{isolated:!!(e.info.isolated||e.module.isolated||e.module.shadow)}),o;try{o=e.module.mount(i,Fm(e.info.id,e=>Z(e)))}catch(t){console.error(`[plugin:${e.info.id}] mount failed:`,t),i.textContent=n(`pluginMountFailed`,{name:e.info.name})}return()=>{if(typeof o==`function`)try{o()}catch(t){console.error(`[plugin:${e.info.id}] cleanup failed:`,t)}a()}},[e]),(0,$.jsx)(`div`,{className:`plugin-view`,ref:t})}function $b({pluginId:e,info:t,epoch:n,failed:r}){let i=V(),[a,o]=(0,Q.useState)(!1),s=t?.name||e;return r?(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsxs)(`div`,{className:`plugin-view-fallback`,role:`alert`,children:[(0,$.jsxs)(`div`,{className:`plugin-view-fallback-title`,children:[i(`pluginViewLoadFailed`),`:`,s]}),(0,$.jsx)(`div`,{className:`plugin-view-fallback-hint`,children:i(`pluginViewLoadFailedHint`)}),t&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-view-fallback-retry`,onClick:()=>{t&&!a&&(o(!0),Tm(t,n).finally(()=>o(!1)))},disabled:a,children:i(a?`pluginViewLoading`:`pluginViewRetry`)})]})}):(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsx)(`div`,{className:`plugin-view-fallback`,role:`status`,children:i(`pluginViewLoading`)})})}function ex({onAction:e}){let t=Ri(),n=(0,Q.useMemo)(()=>t?Gi(t.entries):[],[t]),{items:r,selectParents:i}=(0,Q.useMemo)(()=>Wi(n),[n]),a=(0,Q.useMemo)(()=>Ki(r),[r]),o=(0,Q.useMemo)(()=>typeof window>`u`?!1:a.length>14&&window.innerWidth>=640,[a.length]),s=(0,Q.useMemo)(()=>t?Vi(t.slot,t.target):void 0,[t,t?.slot,t?.target.kind]),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(-1),[m,h]=(0,Q.useState)(-1),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(0),b=(0,Q.useRef)(-1),x=e=>{b.current=e,p(e)},S=(0,Q.useMemo)(()=>m>=0?Gi(r[m]?.children??[]):[],[r,m]),C=(0,Q.useMemo)(()=>Ki(S),[S]),w=e=>{let n=r[e];if(t&&n&&!Ui(n,s)){if(n.children?.length){h(e);return}T(n,t)||Fi()}},T=(t,n,r)=>t.source===`host`&&n.onHostAction?n.onHostAction(t,n.target)===!0:(e(t,n.target,r),!1),E=(0,Q.useRef)(w);if((0,Q.useLayoutEffect)(()=>{E.current=w}),(0,Q.useEffect)(()=>{if(!t){b.current=-1,p(-1),h(-1);return}let e=Ji(r,-1,1,s);b.current=e,p(e),h(-1),c.current?.focus()},[t,r,s]),(0,Q.useLayoutEffect)(()=>{if(!t){d(null);return}let e=c.current;if(!e)return;let n=e.getBoundingClientRect();d(Bi(t.x,t.y,n.width,n.height,window.innerWidth,window.innerHeight))},[t,r]),(0,Q.useLayoutEffect)(()=>{let e=l.current,t=c.current;if(m<0||!e||!t){_(!1),y(0);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=window.innerWidth-r.right,a=r.left;_(i<n.width+8&&a>i);let o=n.bottom-(window.innerHeight-8);y(o>0?-Math.min(o,Math.max(0,n.top-8)):0)},[m,r]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>c.current&&e instanceof Node&&c.current.contains(e),n=t=>{e(t.target)||Fi()},r=t=>{e(t.target)||Fi()},i=()=>Fi();return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`wheel`,r,!0),window.addEventListener(`resize`,i),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`wheel`,r,!0),window.removeEventListener(`resize`,i)}},[t]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{let t=Ji(r,b.current,e,s);b.current=t,p(t)},n=t=>{switch(t.key){case`Escape`:t.preventDefault(),Fi();return;case`Tab`:Fi();return;case`ArrowDown`:t.preventDefault(),e(1);return;case`ArrowUp`:t.preventDefault(),e(-1);return;case`ArrowRight`:r[b.current]?.children?.length&&(t.preventDefault(),h(b.current));return;case`ArrowLeft`:m>=0&&(t.preventDefault(),h(-1));return;case`Enter`:case` `:t.preventDefault(),E.current(b.current);return;default:return}};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[t,r,m,s]),(0,Q.useEffect)(()=>{f<0||c.current?.querySelector(`[data-ctx-active="true"]`)?.scrollIntoView?.({block:`nearest`})},[f]),!t)return null;let D=e=>{let n=i.get(e.id);if(n){if(Ui(n.parent,s))return;t&&!T(n.parent,t,n.value)&&Fi();return}Ui(e,s)||T(e,t)||Fi()},O=(e,t,n)=>{let r=Ui(e,s),i=!!e.children?.length,a=Xi(e.icon),o=n&&f===t;return(0,$.jsxs)(`div`,{className:`ctx-menu-itemwrap`,role:`none`,children:[(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item${r?` disabled`:``}${o?` active`:``}${i?` has-sub`:``}`,"aria-label":e.label,title:e.hint,"aria-disabled":r||void 0,"aria-haspopup":i?`menu`:void 0,"aria-expanded":i?m===t:void 0,"data-ctx-active":o?`true`:void 0,onMouseEnter:n?()=>{x(t),i&&!r&&h(t)}:void 0,onClick:()=>n?w(t):D(e),children:[a?(0,$.jsx)(`span`,{className:`ctx-menu-icon`,"aria-hidden":`true`,children:a}):null,(0,$.jsx)(`span`,{className:`ctx-menu-label`,children:e.label}),e.badge?(0,$.jsx)(`span`,{className:`ctx-menu-badge`,children:e.badge}):null,i?(0,$.jsx)(`span`,{className:`ctx-menu-caret`,"aria-hidden":`true`,children:`▸`}):null]}),n&&i&&m===t?(0,$.jsx)(`div`,{ref:l,className:`ctx-menu-sub${g?` left`:``}`,role:`menu`,"aria-label":e.label,style:v?{marginTop:v}:void 0,children:C.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):O(e.entry,e.index,!1))}):null]},`${e.id}#${t}`)};return(0,bn.createPortal)((0,$.jsx)(`div`,{ref:c,className:`ctx-menu${o?` is-multi-col`:``}`,role:`menu`,"aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:u?.x??t.x,top:u?.y??t.y,visibility:u?`visible`:`hidden`},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},children:a.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):O(e.entry,e.index,!0))}),document.body)}var tx=0,nx=[],rx=new Map,ix=new Set;function ax(){for(let e of ix)try{e()}catch{}}function ox(e){let t=rx.get(e);t!==void 0&&(clearTimeout(t),rx.delete(e))}function sx(e){let t=e.id||`banner-${Date.now()}-${++tx}`,n={...e,id:t,type:e.type||`info`,persistent:!!e.persistent,timeoutMs:e.timeoutMs??5e3,dismissible:e.dismissible!==!1};if(ox(t),!n.persistent&&n.timeoutMs&&n.timeoutMs>0){let e=setTimeout(()=>{cx(t)},n.timeoutMs);rx.set(t,e)}let r=nx.findIndex(e=>e.id===t);if(r>=0){let e=[...nx];e[r]=n,nx=e}else nx=[...nx,n];return ax(),t}function cx(e,t){ox(e);let n=nx.find(t=>t.id===e);if(n){if(nx=nx.filter(t=>t.id!==e),!t?.silent)try{n.onClose?.()}catch{}ax()}}function lx(e,t){let n=nx.filter(e);if(n.length!==0){for(let e of n)if(ox(e.id),!t?.silent)try{e.onClose?.()}catch{}nx=nx.filter(t=>!e(t)),ax()}}function ux(){return nx}function dx(e){return ix.add(e),()=>{ix.delete(e)}}function fx(){return(0,Q.useSyncExternalStore)(dx,ux,ux)}function px({type:e}){switch(e){case`question`:return(0,$.jsx)(K,{className:`banner-icon banner-icon-question`});case`warning`:return(0,$.jsx)(He,{className:`banner-icon banner-icon-warning`});case`error`:return(0,$.jsx)(je,{className:`banner-icon banner-icon-error`});case`success`:return(0,$.jsx)(et,{className:`banner-icon banner-icon-success`});default:return(0,$.jsx)(We,{className:`banner-icon banner-icon-info`})}}var mx=(0,Q.memo)(function({banner:e}){let t=V(),n=typeof e.onClick==`function`;return(0,$.jsxs)(`div`,{className:`banner-card banner-type-${e.type||`info`} ${n?`banner-clickable`:``}`,onClick:n?e.onClick:void 0,role:n?`button`:`status`,tabIndex:n?0:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e.onClick?.())}:void 0,children:[(0,$.jsx)(`div`,{className:`banner-icon-col`,children:(0,$.jsx)(px,{type:e.type})}),(0,$.jsxs)(`div`,{className:`banner-content-col`,children:[e.title&&(0,$.jsx)(`div`,{className:`banner-title`,title:e.title,children:e.title}),(0,$.jsx)(`div`,{className:`banner-message`,title:e.message,children:e.message})]}),e.dismissible&&(0,$.jsx)(`button`,{type:`button`,className:`banner-close`,onClick:t=>{t.stopPropagation(),cx(e.id)},"aria-label":`Close banner`,title:t(`close`),children:(0,$.jsx)(R,{})})]})}),hx=(0,Q.memo)(function(){let e=fx();return e.length===0?null:(0,$.jsx)(`aside`,{className:`banner-container`,"aria-label":`Notifications`,children:e.map(e=>(0,$.jsx)(mx,{banner:e},e.id))})});function gx({slots:e,layout:t,exclude:n,onClose:r}){let i=V(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useMemo)(()=>bb(e,n),[e,n]),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(l),p=(0,Q.useRef)(t),m=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{f.current=l,p.current=t}),(0,Q.useEffect)(()=>{m.current=null},[t]);let h=(e,t)=>{let n=document.elementFromPoint(e,t)?.closest(`[data-drop-slot]`);if(!n)return null;let r=n.dataset.dropSlot;if(!r)return null;let i=n.dataset.dropAlign,a=u.current,o=Array.from(n.querySelectorAll(`[data-chip]`)).filter(e=>e.dataset.chip!==a),s=o.length;for(let n=0;n<o.length;n++){let r=o[n].getBoundingClientRect();if(t<r.top){s=n;break}if(t<=r.bottom+4&&e<r.left+r.width/2){s=n;break}}return{slot:r,align:i,index:s}},g=()=>{let e=u.current,t=d.current;if(u.current=null,d.current=null,o(null),c(null),!e||!t)return;let n=m.current??p.current,r=t.slot===`__tray`?Eb(n,e):Tb(n,f.current,{id:e,slot:t.slot,...t.align===void 0?{}:{align:t.align},index:t.index});m.current=r,Z({type:`set_settings`,uiLayout:r})};(0,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.preventDefault();let t=h(e.clientX,e.clientY);d.current=t,c(t)},t=()=>g();return window.addEventListener(`pointermove`,e,{passive:!1}),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t)}},[a]),mt(()=>{u.current||r()});let _=(e,t)=>{(e.pointerType!==`mouse`||e.button===0)&&(e.preventDefault(),u.current=t,d.current=null,o(t),c(null))},v=e=>(0,$.jsxs)(`button`,{type:`button`,"data-chip":e.id,className:`icon-editor-chip${a===e.id?` dragging`:``}`,title:e.label,onPointerDown:t=>_(t,e.id),children:[(0,$.jsx)(`span`,{className:`icon-editor-chip-icon`,children:Da(e)}),(0,$.jsx)(`span`,{className:`icon-editor-chip-label`,children:e.label})]},e.id),y=(e,t,n,r)=>{let o=s?.slot===e&&(s.align??null)===(t??null),c=r.map(v);return o&&s&&c.splice(Math.max(0,Math.min(s.index,c.length)),0,(0,$.jsx)(`span`,{className:`icon-editor-caret`,"aria-hidden":`true`},`__caret`)),(0,$.jsxs)(`div`,{className:`icon-editor-strip${o?` drop-over`:``}${a?` dragging-active`:``}`,"data-drop-slot":e,...t===void 0?{}:{"data-drop-align":t},children:[n!==null&&(0,$.jsx)(`span`,{className:`icon-editor-strip-label`,children:n}),c,r.length===0&&(0,$.jsx)(`span`,{className:`icon-editor-empty`,children:i(`uiIconEditDropHere`)})]},t??`__all`)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`icon-editor-backdrop`,onClick:r}),(0,$.jsxs)(`div`,{className:`icon-editor`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`uiIconEditTitle`),children:[(0,$.jsxs)(`div`,{className:`icon-editor-head`,children:[(0,$.jsx)(`span`,{className:`icon-editor-title`,children:i(`uiIconEditTitle`)}),(0,$.jsx)(`span`,{className:`icon-editor-hint`,children:i(`uiIconEditHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`icon-editor-close`,onClick:r,"aria-label":i(`close`),title:i(`close`),children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`icon-editor-body`,children:[gb.map(e=>{let t=l.zones[e.slot]??[],n=Sb(t);return(0,$.jsxs)(`div`,{className:`icon-editor-zone`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-zone-title`,children:[i(e.labelKey),a&&(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:n.length})]}),e.alignable?vb.map(n=>y(e.slot,n,e.vertical?yb(i,n):n,Cb(t,n))):y(e.slot,void 0,null,n)]},e.slot)}),(0,$.jsxs)(`div`,{className:`icon-editor-zone icon-editor-zone-tray`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-zone-title`,children:[i(`uiIconEditTray`),(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:l.tray.length})]}),y(_b,void 0,null,l.tray)]})]})]})]})}function _x(e,t){let n=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let r=Lv(n.current,e);n.current=r.key,r.clear&&t()},[e,t])}var vx=new Map,yx=-1;function bx(e){let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}function xx(e){let t=e.replace(/\\/g,`/`).split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(n).toLowerCase():``}function Sx(e,t){yx!==t&&(yx=t);let n=new Map;for(let t of e){let e=t;if(!e.error&&e.hasClient&&Array.isArray(e.fileHandlers)){for(let t of e.fileHandlers)if(t&&t.id&&Array.isArray(t.extensions))for(let r of t.extensions){if(typeof r!=`string`)continue;let i=bx(r);if(!/^\.[a-z0-9][a-z0-9._-]*$/.test(i))continue;let a=n.get(i)??[];a.push({plugin:e,declaration:t}),n.set(i,a)}}}for(let e of n.values())e.sort((e,t)=>t.declaration.priority-e.declaration.priority||e.plugin.id.localeCompare(t.plugin.id));vx=n}function Cx(e){return vx.get(xx(e))?.[0]??null}async function wx(e){let t=await jm(e.plugin,yx);if(!t)return null;let n=t.fileHandlers,r;if(Array.isArray(n))r=n.find(t=>t&&t.id===e.declaration.id),!r&&n.length===1&&typeof n[0]?.mount==`function`&&(r=n[0]);else if(n&&typeof n==`object`){r=n[e.declaration.id];let t=Object.values(n);!r&&t.length===1&&typeof t[0]?.mount==`function`&&(r=t[0])}return!r||typeof r.mount!=`function`?null:{handler:r,pluginId:e.plugin.id}}var Tx=(0,Q.memo)(function({open:e=!0,currentModelId:t,models:n,modelsLoading:r=!1,providerKeys:i={},defaultModel:a,onManageModels:o,onSelect:s,onClose:c,title:l}){let u=V();return(0,Q.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),c())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,c]),e?(0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:1200,display:`flex`,alignItems:`center`,justifyContent:`center`},onClick:e=>{e.target===e.currentTarget&&c()},children:(0,$.jsxs)(`div`,{className:`modal dd-menu dd-menu-model`,style:{position:`relative`,top:`auto`,bottom:`auto`,left:`auto`,right:`auto`,transform:`none`,width:`min(92vw, 680px)`,maxWidth:`680px`,height:`min(84vh, 640px)`,maxHeight:`86vh`,padding:0,gap:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,boxShadow:`0 24px 64px rgba(0, 0, 0, 0.55)`,background:`var(--bg-elev2, #1b1b24)`,borderRadius:`12px`,border:`1px solid var(--border)`},children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,style:{padding:`10px 14px`,borderBottom:`1px solid var(--border, #333)`},children:[(0,$.jsx)(`span`,{className:`dd-header-title`,style:{fontWeight:600},children:l||u(`availableModels`)}),(0,$.jsx)(`div`,{className:`dd-header-actions`,style:{marginLeft:`auto`},children:(0,$.jsx)(`button`,{type:`button`,className:`ghost dd-header-btn`,style:{border:0,cursor:`pointer`,fontSize:16},onClick:c,title:`关闭`,children:(0,$.jsx)(R,{})})})]}),(0,$.jsx)(Mo,{models:n,modelsLoading:r,providerKeys:i,defaultModel:a,currentModelId:t,active:e,onEnsureModels:()=>{n.length===0&&!r&&Z({type:`list_models`})},onRefresh:()=>Z({type:`list_models`}),onManageModels:o,onPickModel:e=>{s(e.id,e),c()},isRowActive:e=>jo(e,t),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{flex:`1 1 auto`,minHeight:0,minWidth:0,maxHeight:`none`,overflowY:`auto`}})]})}):null}),Ex=null,Dx=new Set;function Ox(){for(let e of Dx)e()}function kx(e){Ex=e,Ox()}function Ax(){Ex=null,Ox()}function jx(e){Ex&&(Z({type:`rollback_session`,messageId:Ex.messageId,conversationId:Ex.conversationId,restoreWorkspace:e}),Ex=null,Ox())}function Mx(){return(0,Q.useSyncExternalStore)(e=>(Dx.add(e),()=>Dx.delete(e)),()=>Ex)}function Nx(){let e=V(),t=Mx(),[n,r]=(0,Q.useState)(!0),i=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{t&&r(!0)},[t]),mt(()=>{t&&Ax()},!!t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{if(e.key!==`Enter`||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=e.target;(!t||t===document.body||i.current?.contains(t))&&(e.preventDefault(),jx(n))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]),t?(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:Ax,children:(0,$.jsxs)(`div`,{ref:i,className:`tool-info-modal rollback-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`rollbackSession`),onClick:e=>e.stopPropagation(),style:{maxWidth:520},children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(He,{}),e(`rollbackSession`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`cancel`),onClick:Ax,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 16px 0`,fontSize:14,lineHeight:1.6},children:e(`rollbackConfirm`)}),(0,$.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:10,padding:`12px 14px`,borderRadius:8,backgroundColor:`var(--bg-elev, rgba(255, 255, 255, 0.04))`,border:`1px solid var(--border-subtle, rgba(255, 255, 255, 0.1))`,cursor:`pointer`,marginBottom:20},title:e(`rollbackRestoreWorkspaceTip`),children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>r(e.target.checked),style:{marginTop:3,cursor:`pointer`}}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{style:{fontWeight:600,fontSize:13,color:`var(--text, #e2e8f0)`},children:e(`rollbackRestoreWorkspace`)}),(0,$.jsx)(`div`,{style:{fontSize:12,color:`var(--text-dim, #9aa1b4)`,marginTop:2},children:e(`rollbackRestoreWorkspaceTip`)})]})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:10},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:Ax,children:e(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>jx(n),children:[(0,$.jsx)(z,{}),e(`confirm`)]})]})]})]})}),document.body):null}function Px({approvals:e,activeConversationId:t,mode:n=`all`}){let r=V();return(0,$.jsx)(Xb,{items:e,itemKey:e=>e.id,title:r(`toolApprovalTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.toolName]}),createdAt:e=>e.createdAt??0,canAutoOpen:e=>n!==`manual`&&(n===`all`||e.conversationId===t||!e.conversationId),onNavigate:e=>{e.conversationId&&Z({type:`switch_conversation`,id:e.conversationId})},canNavigate:e=>!!e.conversationId,children:(e,t)=>(0,$.jsx)(Fx,{approval:e,onDefer:t},e.id)})}function Fx({approval:e,onDefer:t}){let n=V(),{locale:r}=Ue(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{if(e){let t=e.params;a(typeof t==`object`&&t?JSON.stringify(t,null,2):t==null?`{}`:String(t)),s(null)}},[e?.id]),!e)return null;let c=t=>{Z({type:`tool_approval_response`,id:e.id,decision:`approve`,...t&&t!==`once`?{scope:t}:{}})},l=()=>{Z({type:`tool_approval_response`,id:e.id,decision:`deny`,reason:`Operation rejected by user`})};return(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,children:(0,$.jsxs)(`div`,{className:`tool-info-modal approval-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`toolApprovalTitle`),style:{maxWidth:640,borderTop:`4px solid var(--amber, #f59e0b)`},onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(He,{}),n(`toolApprovalTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,style:{fontWeight:700},children:e.toolName}),e.parentTool===`codemode`&&(0,$.jsxs)(`span`,{className:`tool-info-label`,style:{backgroundColor:`rgba(245, 158, 11, 0.15)`,color:`var(--amber, #f59e0b)`,border:`1px solid rgba(245, 158, 11, 0.35)`,fontWeight:600},children:[`⚡ `,n(`codemodeNestedApprovalBadge`)]}),e.conversationTitle&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:e.conversationTitle}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,children:n(`pendingQueueDefer`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalDeny`),onClick:l,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[e.parentTool===`codemode`&&(0,$.jsxs)(`div`,{style:{padding:`8px 12px`,borderRadius:6,backgroundColor:`rgba(99, 102, 241, 0.12)`,border:`1px solid rgba(99, 102, 241, 0.25)`,marginBottom:12,color:`var(--text, #e2e8f0)`,fontSize:12.5,display:`flex`,alignItems:`center`,gap:6},children:[(0,$.jsx)(`span`,{style:{fontSize:14},children:`⚡`}),(0,$.jsx)(`span`,{children:n(`codemodeNestedApprovalDesc`)})]}),(e.reason||e.reasonEn)&&(0,$.jsxs)(`div`,{style:{padding:`10px 14px`,borderRadius:6,backgroundColor:`rgba(245, 158, 11, 0.12)`,border:`1px solid rgba(245, 158, 11, 0.3)`,marginBottom:16,color:`var(--amber, #f59e0b)`,fontSize:13,lineHeight:1.5,fontWeight:500},children:[(0,$.jsxs)(`div`,{style:{fontWeight:600,marginBottom:2},children:[n(`toolApprovalRiskAlert`),`:`]}),(0,$.jsx)(`div`,{children:H(r)?e.reason||e.reasonEn:e.reasonEn||e.reason}),e.category&&(0,$.jsxs)(`div`,{style:{marginTop:6,fontSize:12,opacity:.85},children:[n(`toolApprovalCategory`),`:`,H(r)?e.category.label:e.category.labelEn]}),e.hits&&e.hits.length>0&&(0,$.jsxs)(`div`,{className:`approval-hits-panel`,children:[(0,$.jsxs)(`div`,{className:`approval-hits-title`,children:[n(`toolApprovalHitsTitle`),` (`,e.hits.length,`)`]}),(0,$.jsx)(`div`,{className:`approval-hits-list`,children:e.hits.map((e,t)=>(0,$.jsxs)(`div`,{className:`approval-hit-item`,children:[(0,$.jsxs)(`div`,{className:`approval-hit-header`,children:[(0,$.jsx)(`span`,{className:`approval-hit-badge`,children:H(r)?e.label:e.labelEn||e.label}),(0,$.jsx)(`span`,{className:`approval-hit-field`,children:e.field}),(0,$.jsx)(`span`,{className:`approval-hit-pos`,children:n(`approvalHitPos`,{index:e.index+1,length:e.length})})]}),(0,$.jsx)(`div`,{className:`approval-hit-text`,children:(0,$.jsx)(`mark`,{className:`approval-danger-hit`,children:e.text})})]},t))})]})]}),e.toolName===`bash`&&typeof e.params?.command==`string`&&(0,$.jsxs)(`div`,{className:`approval-cmd-preview`,children:[(0,$.jsxs)(`div`,{className:`approval-cmd-preview-label`,children:[n(`approvalCommandPreview`),`:`]}),(0,$.jsxs)(`div`,{className:`approval-cmd-preview-box`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:ys(e.params.command,e.hits)})]})]}),(0,$.jsxs)(`div`,{style:{marginBottom:16},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:6},children:[(0,$.jsx)(`span`,{style:{fontSize:13,fontWeight:600,color:`var(--text, #e2e8f0)`},children:n(`toolApprovalParams`)}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim, #9aa1b4)`},children:n(`toolApprovalEditPlaceholder`)})]}),(0,$.jsx)(`textarea`,{rows:8,value:i,onChange:e=>{a(e.target.value),o&&s(null)},style:{width:`100%`,fontFamily:`var(--mono, monospace)`,fontSize:12,lineHeight:1.5,padding:10,borderRadius:6,backgroundColor:`var(--bg-elev, #111827)`,color:`var(--text, #f8fafc)`,border:o?`1px solid var(--red, #ef4444)`:`1px solid var(--border-subtle, rgba(255,255,255,0.1))`,boxSizing:`border-box`,resize:`vertical`}}),o&&(0,$.jsx)(`div`,{style:{color:`var(--red, #ef4444)`,fontSize:12,marginTop:4},children:o})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,justifyContent:`flex-end`,gap:10},children:[e.category&&(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowCategoryHint`),onClick:()=>c(`category`),children:[(0,$.jsx)(fe,{}),n(`toolApprovalAllowCategory`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowConversationHint`),onClick:()=>c(`all`),children:[(0,$.jsx)(et,{}),n(`toolApprovalAllowConversation`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,style:{color:`var(--red, #ef4444)`},onClick:l,children:[(0,$.jsx)(R,{}),n(`toolApprovalDeny`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>c(),style:{fontWeight:500},children:[(0,$.jsx)(z,{}),n(`toolApprovalApprove`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>{try{let t=e.params,n;n=typeof t==`object`&&t||t==null?JSON.parse(i):i,s(null),Z({type:`tool_approval_response`,id:e.id,decision:`edit`,editedParams:n})}catch(e){s(H(r)?`JSON 格式错误:${e.message}`:`JSON parse error: ${e.message}`)}},children:[(0,$.jsx)(ct,{}),n(`toolApprovalEditAndRun`)]})]})]})]})}),document.body)}var Ix={pending:`in_progress`,in_progress:`done`,done:`failed`,failed:`pending`};function Lx({plan:e}){let t=V(),n=H(Se()),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=rc({duration:2e3}),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(``);if(!e||!e.steps||e.steps.length===0)return null;let h=e.steps,_=h.filter(e=>e.status===`done`).length,v=h.length,y=Math.round(_/v*100),b=h.find(t=>t.id===e.activeStepId)??h.find(e=>e.status===`in_progress`),x=()=>{window.confirm(n?`确定要清空当前任务计划看板吗?`:`Are you sure you want to clear the plan board?`)&&Z({type:`plan_update`,steps:[]})},S=()=>{Z({type:`set_plan_mode`,enabled:!1}),Z({type:`prompt`,text:t(`planImplementRequest`)})},C=()=>{let e=h.map((e,t)=>`${t+1}. ${e.title}${e.description?` (${e.description})`:``}`).join(`
|
|
72
|
+
`).trim();if(n.length>0)return{hasRisk:t,intro:e,command:n,outro:o}}return{hasRisk:t,intro:e,command:null,outro:``}}function Nb({command:e,hasRisk:t}){let n=V(),{copied:r,copy:i}=ac({duration:2e3}),[a,c]=(0,Q.useState)(!1),l=(0,Q.useMemo)(()=>e.split(`
|
|
73
|
+
`),[e]),u=l.length>8;return(0,$.jsxs)(`div`,{className:`dialog-cmd-box ${t?`has-risk`:``}`,children:[t&&(0,$.jsxs)(`div`,{className:`dialog-cmd-risk`,children:[(0,$.jsx)(He,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorRisk`)})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-head`,children:[(0,$.jsxs)(`div`,{className:`dialog-cmd-tag`,children:[(0,$.jsx)(o,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorTitle`)}),(0,$.jsx)(`span`,{className:`dialog-cmd-badge`,children:n(`cmdInspectorLines`,{n:l.length})})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-actions`,children:[u&&(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>c(e=>!e),title:n(a?`cmdInspectorCollapse`:`cmdInspectorExpand`),children:[a?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{}),(0,$.jsx)(`span`,{children:n(a?`cmdInspectorCollapse`:`cmdInspectorExpand`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>{i(e)},title:n(`copy`),children:[r?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{children:n(r?`cmdCopied`:`copy`)})]})]})]}),(0,$.jsx)(`div`,{className:`dialog-cmd-code ${a?`expanded`:``}`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`dialog-cmd-line`,children:[(0,$.jsx)(`span`,{className:`cmd-line-num`,children:t+1}),(0,$.jsx)(`span`,{className:`cmd-line-text`,children:e})]},t))})})})]})}function Pb({text:e,structuredCode:t}){let n=(0,Q.useMemo)(()=>t?{hasRisk:t.hasRisk??!1,intro:e,command:t.content,outro:``}:Mb(e),[e,t]);return n.command?(0,$.jsxs)(`div`,{className:`dialog-prompt dialog-body`,children:[n.intro&&(0,$.jsx)(sl,{text:n.intro,rawHtml:!0,disableMath:!0}),(0,$.jsx)(Nb,{command:n.command,hasRisk:n.hasRisk}),n.outro&&(0,$.jsx)(sl,{text:n.outro,rawHtml:!0,disableMath:!0})]}):(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(sl,{text:e,rawHtml:!0,disableMath:!0})})}function Fb({dialog:e}){let t=V(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(0),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(``),u=t=>{Z({type:`dialog_response`,id:e.id,value:t})};(0,Q.useEffect)(()=>{r(``),a(0),s(!1),l(``)},[e.id]),mt(()=>u(null));let d=Array.isArray(e.args[0])?e.args[0]:[],f=typeof e.args[0]==`string`?e.args[0]:``,p=e.title&&e.title!==t(`pluginRequest`)?e.title:``,m=p?p.split(`
|
|
74
|
+
`)[0].trim():``,h=d.some(jb),g=d.find(jb)??d[d.length-1]??`No`,_=()=>{let e=c.trim();e&&(Ft({text:`${t(`rejectFeedbackPrefix`)}${e}\n`}),Xt()),u(g)};return(0,Q.useEffect)(()=>{let t=t=>{let n=t.target?.tagName;if(n!==`INPUT`&&n!==`TEXTAREA`){if(e.kind===`select`){if(d.length===0)return;if(t.key===`ArrowDown`)t.preventDefault(),a(e=>(e+1)%d.length);else if(t.key===`ArrowUp`)t.preventDefault(),a(e=>(e-1+d.length)%d.length);else if(t.key===`Enter`&&!t.isComposing)t.preventDefault(),d[i]!==void 0&&u(d[i]);else if((t.key===`y`||t.key===`Y`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=d.findIndex(Ab);e>=0&&(t.preventDefault(),u(d[e]))}else if((t.key===`n`||t.key===`N`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=d.findIndex(jb);e>=0&&(t.preventDefault(),u(d[e]))}}else e.kind===`confirm`&&((t.key===`y`||t.key===`Y`||t.key===`Enter`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey?(t.preventDefault(),u(!0)):(t.key===`n`||t.key===`N`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey&&(t.preventDefault(),u(!1)))}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e.kind,e.id,d,i]),(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":e.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:t(`pluginRequest`)}),m&&(0,$.jsx)(`span`,{className:`dialog-title`,title:p,children:m}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:t(`cancel`),onClick:()=>u(null),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-scroll-body`,children:[e.kind===`select`&&(0,$.jsx)(Pb,{text:p,structuredCode:e.code}),e.kind===`confirm`&&(0,$.jsxs)($.Fragment,{children:[p&&(p.includes(`
|
|
75
|
+
`)||p.length>50||!f||e.code)&&(0,$.jsx)(Pb,{text:p,structuredCode:e.code}),f&&(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(sl,{text:f,rawHtml:!0,disableMath:!0})})]}),e.kind===`input`&&(0,$.jsxs)($.Fragment,{children:[p&&(0,$.jsx)(Pb,{text:p,structuredCode:e.code}),(0,$.jsx)(`input`,{className:`dialog-input`,value:n,placeholder:f||t(`inputPlaceholder`),autoFocus:!0,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&u(n)}})]})]}),(0,$.jsxs)(`div`,{className:`dialog-footer`,children:[e.kind===`select`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dialog-options`,children:[d.map((e,t)=>{let n=Ab(e),r=jb(e),o=n?`Y`:r?`N`:void 0;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${t===i?`sel`:``} ${n?`opt-affirmative`:``} ${r?`opt-negative`:``}`,onMouseEnter:()=>a(t),onClick:()=>u(e),children:[(0,$.jsx)(`span`,{className:`dialog-option-text`,children:(0,$.jsx)(sl,{text:e,rawHtml:!0,disableMath:!0})}),o&&(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:o})]},t)}),d.length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:t(`noOptions`)})]}),h&&(0,$.jsx)(`div`,{className:`dialog-reject-box`,children:o?(0,$.jsxs)(`div`,{className:`dialog-reject-input-row`,children:[(0,$.jsx)(`input`,{className:`dialog-input dialog-reject-input`,value:c,placeholder:t(`rejectNotePlaceholder`),autoFocus:!0,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?_():e.key===`Escape`&&s(!1)}}),(0,$.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:_,children:t(`rejectWithNoteSubmit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn btn-sm ghost-btn`,title:t(`cancel`),onClick:()=>s(!1),children:`✕`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`dialog-reject-toggle`,onClick:()=>s(!0),children:[(0,$.jsx)(Ce,{}),(0,$.jsx)(`span`,{children:t(`rejectWithNote`)})]})})]}),e.kind===`confirm`&&(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>u(!1),children:[t(`cancel`),` `,(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:`N`})]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary`,onClick:()=>u(!0),children:[t(`ok`),` `,(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:`Y`})]})]}),e.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>u(null),children:t(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>u(n),children:t(`ok`)})]})]})]})}function Ib(e){if(e.owner)return{type:`navigate_question`,id:e.id};let t=e.conversationId??e.rootConversationId;return t?{type:`switch_conversation`,id:t}:void 0}function Lb(e,t){if(!Number.isFinite(e)||e<=0)return;let n=Math.max(0,Math.floor((t-e)/1e3)),r=Math.floor(n/60),i=String(n%60).padStart(2,`0`);return r<60?`${r}:${i}`:`${Math.floor(r/60)}:${String(r%60).padStart(2,`0`)}:${i}`}function Rb(e,t,n){if(e!==null)return e.filter(e=>e.audience===`user`);let r=[];for(let e of[t&&{...t,createdAt:0,audience:`user`},n&&{...n,conversationId:n.convId,createdAt:0,audience:`user`}])e&&(r.some(t=>t.id===e.id&&(`owner`in e?t.owner===e.owner:!e.conversationId||t.conversationId===e.conversationId))||r.push(e));return r}function zb(e){return JSON.stringify([e.owner??``,e.conversationId??``,e.id])}function Bb(e,t){return!!t&&(e.conversationId===t||e.rootConversationId===t)}var Vb=150;function Hb({anchorRef:e,enabled:t=!0,className:n,children:r}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)({left:0,top:0}),u=(0,Q.useCallback)(()=>{a.current!==null&&(clearTimeout(a.current),a.current=null)},[]),d=(0,Q.useCallback)(()=>{u(),a.current=setTimeout(()=>s(!1),Vb)},[u]);return(0,Q.useEffect)(()=>{let n=e.current;if(!n)return;let r=()=>{u(),s(!0)};n.addEventListener(`mouseenter`,r);let a=e=>{let t=e.relatedTarget;t&&i.current?.contains(t)||d()};return n.addEventListener(`mouseleave`,a),t&&(n.addEventListener(`focus`,r),n.addEventListener(`blur`,d)),()=>{u(),n.removeEventListener(`mouseenter`,r),n.removeEventListener(`mouseleave`,a),n.removeEventListener(`focus`,r),n.removeEventListener(`blur`,d)}},[e,t,u,d]),(0,Q.useLayoutEffect)(()=>{if(!o)return;let t=e.current?.getBoundingClientRect();if(!t)return;let n={left:Math.max(8,t.left-8),top:t.bottom+8};l(e=>e.left===n.left&&e.top===n.top?e:n)},[o,e]),(0,Q.useLayoutEffect)(()=>{if(!o)return;let t=i.current,n=e.current;if(!t||!n)return;let r=Zi(n.getBoundingClientRect(),t.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});l(e=>e.left===r.left&&e.top===r.top?e:r)},[o,e,r]),(0,Q.useEffect)(()=>{if(!o)return;let e=()=>s(!1);return window.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[o]),o?(0,bn.createPortal)((0,$.jsx)(`div`,{ref:i,className:`set-tip-bubble open${n?` ${n}`:``}`,role:`tooltip`,style:{position:`fixed`,left:c.left,top:c.top},onMouseEnter:u,onMouseLeave:d,children:r}),document.body):null}var Ub=`pi_web_qdraft_`,Wb=864e5,Gb=new Map;function Kb(e){return`${Ub}${e}`}function qb(e){if(!e)return null;try{if(typeof window<`u`&&window.sessionStorage){let t=window.sessionStorage.getItem(Kb(e));if(t){let n=JSON.parse(t);if(n&&typeof n==`object`&&n.selections&&typeof n.selections==`object`&&n.customs&&typeof n.customs==`object`&&typeof n.step==`number`)return n.updatedAt&&Date.now()-n.updatedAt>Wb?(Yb(e),null):n}}}catch{}let t=Gb.get(e);return t?t.updatedAt&&Date.now()-t.updatedAt>Wb?(Gb.delete(e),null):t:null}function Jb(e,t){if(!e)return;let n=Object.values(t.selections).some(e=>e&&e.length>0),r=Object.values(t.customs).some(e=>e&&e.trim().length>0),i=t.step>0;if(!n&&!r&&!i){Yb(e);return}let a={selections:{...t.selections},customs:{...t.customs},step:t.step,updatedAt:Date.now()};Gb.set(e,a);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.setItem(Kb(e),JSON.stringify(a))}catch{}}function Yb(e){if(e){Gb.delete(e);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.removeItem(Kb(e))}catch{}}}function Xb({question:e,owner:t,conversationTitle:n,onDefer:r,onNavigate:i}){let a=V(),o=e.conversationTitle||n,[c,l]=(0,Q.useState)(()=>qb(e.id)?.selections??{}),[u,d]=(0,Q.useState)(()=>qb(e.id)?.customs??{}),[f,p]=(0,Q.useState)(!1),m=Vy(),[h,g]=(0,Q.useState)(()=>qb(e.id)?.step??0),[_,v]=(0,Q.useState)(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1),y=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{y.current=!1;let t=qb(e.id);t?(l(t.selections),d(t.customs),g(t.step)):(l({}),d({}),g(0)),p(!1);let n=e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1;v(n)},[e.id,e.deadline,t]),(0,Q.useEffect)(()=>{y.current||Jb(e.id,{selections:c,customs:u,step:h})},[e.id,c,u,h]),(0,Q.useEffect)(()=>{if(!e.deadline)return;let t=setInterval(()=>{v(Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)))},1e3);return()=>clearInterval(t)},[e.id,e.deadline]);let b=(0,Q.useCallback)(n=>{y.current=!0,Yb(e.id),Z({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...n?.trim()?{cancelReason:n.trim()}:{},...t?{owner:t}:{}})},[e.id,t]);mt(()=>{r?r():b()},!f);let x=(e,t)=>{if(!e.dependsOn)return!0;let n=t[e.dependsOn.questionId]??[];if(e.dependsOn.value===void 0)return n.length>0;let r=Array.isArray(e.dependsOn.value)?e.dependsOn.value:[e.dependsOn.value];return n.some(e=>r.includes(e))},S=e.questions.filter(e=>x(e,c)),C=S.length;(0,Q.useEffect)(()=>{if(e.questions.length===0||C>0)return;let n=setTimeout(()=>{Z({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...t?{owner:t}:{}})},1500);return()=>clearTimeout(n)},[e.id,e.questions.length,C,t]);let w=Math.min(h,Math.max(0,C-1)),T=S[w];if(!T)return(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":`select`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:a(`modelQuestion`)}),o&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:o,children:o}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:`cancel`),onClick:()=>r?r():b(),children:`✕`})]}),(0,$.jsx)(`div`,{className:`set-section`,children:(0,$.jsx)(`div`,{className:`set-hint`,children:a(`questionNoneAvailable`)})})]});let E=(()=>{if(!T)return[];if(T.optionsMap&&T.dependsOn){let e=c[T.dependsOn.questionId]??[];for(let t of e)if(T.optionsMap[t])return T.optionsMap[t]}return T.options??[]})(),D=n=>{y.current=!0,Yb(e.id);let r=e.questions.map(e=>{let t=n[e.id]??[],r=(u[e.id]??``).trim();return{id:e.id,selected:t,...r?{custom:r}:{}}});Z({type:`question_answer`,id:e.id,answers:r,...t?{owner:t}:{}})},O=(e,t)=>{l(n=>{let r=n[e]??[];return{...n,[e]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}})},k=(t,n,r)=>{if(r){O(t,n);return}let i={...c,[t]:[n]};l(i);let a=e.questions.filter(e=>x(e,i));w>=a.length-1?D(i):g(w+1)},A=()=>{w>=C-1?D(c):g(w+1)},j=t=>{let n=e.questions.find(e=>e.id===t);return E.length===0&&(n?.options?.length??0)===0||(c[t]?.length??0)>0||(u[t]??``).trim()!==``},M=E.filter(e=>(c[T.id]??[]).includes(e.label)&&e.preview).map(e=>e.preview),N=(T.header||T.question).replace(/\s+/g,` `).trim(),P=(u[T.id]??``).trim(),ee=Object.values(u).map(e=>e?.trim()).filter(Boolean).join(`;
|
|
76
|
+
`),F=P.length>0||ee.length>0,te=P||ee;return(0,Q.useEffect)(()=>{if(f)return;let e=e=>{let t=e.target;if(!(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)){if(e.key>=`1`&&e.key<=`9`){let t=parseInt(e.key,10)-1;if(t<E.length){e.preventDefault(),k(T.id,E[t].label,!!T.multiSelect);return}}if(e.key===`ArrowLeft`&&w>0){e.preventDefault(),g(w-1);return}if(e.key===`ArrowRight`&&w<C-1&&j(T.id)){e.preventDefault(),g(w+1);return}e.key===`Enter`&&j(T.id)&&(e.preventDefault(),A())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f,E,T.id,T.multiSelect,w,C,j,A,k]),(0,$.jsxs)(`div`,{className:`dialog-inline${f?` collapsed`:``}`,"data-dialog-kind":`select`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,onClick:f?()=>p(!1):void 0,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:a(`modelQuestion`)}),o&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:o,children:o}),C>1&&(0,$.jsx)(`span`,{className:`question-progress`,children:a(`questionStep`,{cur:w+1,total:C})}),_>=0&&(0,$.jsx)(`span`,{className:`question-timer`,children:_>0?a(`questionTimeout`,{s:_}):a(`questionTimeoutExpired`)}),f&&(0,$.jsx)(`span`,{className:`question-collapsed-preview`,title:N,children:N}),(0,$.jsxs)(`div`,{className:`dialog-head-actions`,children:[i&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:e=>{e.stopPropagation(),i()},children:a(`questionQueueNavigate`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-toggle-collapse`,title:a(f?`expandSection`:`collapseSection`),onClick:e=>{e.stopPropagation(),p(e=>!e)},children:f?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:F?`modelQuestionRejectWithNoteTip`:`cancel`),onClick:e=>{e.stopPropagation(),r?r():b(F?te:void 0)},children:`✕`})]})]}),!f&&(0,$.jsxs)($.Fragment,{children:[C>1&&(0,$.jsx)(`div`,{className:`question-step-pills`,role:`tablist`,children:S.map((e,t)=>{let n=t===w,r=j(e.id),i=e.header||`${a(`modelQuestion`)} ${t+1}`;return(0,$.jsxs)(`button`,{type:`button`,className:`question-step-pill${n?` active`:``}${r?` done`:``}`,onClick:()=>g(t),title:i,"aria-selected":n,children:[(0,$.jsx)(`span`,{className:`question-step-pill-idx`,children:r&&!n?`✓`:t+1}),(0,$.jsx)(`span`,{className:`question-step-pill-label`,children:i})]},e.id)})}),(0,$.jsxs)(`div`,{className:`set-section`,children:[(0,$.jsx)(`div`,{className:`set-section-title`,children:T.header??`${a(`modelQuestion`)} ${w+1}`}),(0,$.jsx)(`div`,{className:`question-head`,children:(0,$.jsx)(sl,{text:T.question,rawHtml:!0})}),T.detail&&(0,$.jsx)(`div`,{className:`set-hint`,children:(0,$.jsx)(sl,{text:T.detail,rawHtml:!0})}),E.length>0&&(0,$.jsx)(`div`,{className:`set-list`,children:E.map((e,t)=>{let n=(c[T.id]??[]).includes(e.label),r=e.recommended??(t===0&&E.length>1),i=t<9?t+1:void 0;return(0,$.jsx)(Zb,{label:e.label,description:e.description,mark:T.multiSelect?n?`☑ `:`☐ `:n?`● `:`○ `,active:n,keyNumber:i,recommended:r,onPick:()=>k(T.id,e.label,!!T.multiSelect)},e.label)})}),M.length>0&&(0,$.jsxs)(`div`,{className:`question-preview`,children:[(0,$.jsx)(`div`,{className:`question-preview-label`,children:a(`optionPreview`)}),M.map((e,t)=>(0,$.jsx)(`div`,{className:`question-preview-body`,children:(0,$.jsx)(sl,{text:e,rawHtml:!0})},t))]}),(0,$.jsx)(`input`,{className:`set-prompt-input question-custom`,placeholder:a(`modelQuestionCustom`),value:u[T.id]??``,onChange:e=>d(t=>({...t,[T.id]:e.target.value})),onCompositionEnd:m.onCompositionEnd,onKeyDown:e=>{m.isImeKey(e.nativeEvent)||e.key===`Enter`&&(e.preventDefault(),j(T.id)&&A())}})]},T.id),(0,$.jsxs)(`div`,{className:`dialog-nav`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss-inline${F?` reject-note`:``}`,onClick:()=>b(F?te:void 0),title:a(F?`modelQuestionRejectWithNoteTip`:`cancel`),children:a(F?`modelQuestionRejectWithNote`:`cancel`)}),(0,$.jsxs)(`div`,{className:`dialog-nav-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-prev`,disabled:w===0,onClick:()=>g(w-1),children:a(`previous`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-submit`,disabled:!j(T.id),onClick:A,children:w===C-1?a(`modelQuestionSubmit`):a(`next`)})]})]})]})]})}function Zb({label:e,description:t,mark:n,active:r,keyNumber:i,recommended:a,onPick:o}){let s=(0,Q.useRef)(null),c=V();return(0,$.jsxs)(`button`,{type:`button`,ref:s,className:`set-row question-option${r?` active`:``}`,onClick:o,children:[(0,$.jsxs)(`div`,{className:`set-row-name`,children:[i!==void 0&&(0,$.jsx)(`span`,{className:`question-key-badge`,title:c(`keyShortcutTip`,{key:i}),children:i}),(0,$.jsx)(`span`,{className:`question-mark`,children:n}),(0,$.jsx)(sl,{text:e,rawHtml:!0}),a&&(0,$.jsx)(`span`,{className:`question-recommended-badge`,children:c(`recommended`)})]}),t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`set-row-desc`,children:(0,$.jsx)(sl,{text:t,rawHtml:!0})}),(0,$.jsx)(Hb,{anchorRef:s,enabled:Qi(),className:`question-desc-tip`,children:(0,$.jsx)(sl,{text:t,rawHtml:!0})})]})]})}function Qb({items:e,itemKey:t,title:n,summary:r,canAutoOpen:i,createdAt:a,onNavigate:o,canNavigate:s,children:c}){let l=V(),[u,d]=(0,Q.useState)(()=>new Set),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(Date.now),g=as(e,t,f,u,i),_=g?t(g):null;(0,Q.useEffect)(()=>{p(_)},[_]);let v=e.some(e=>a(e)>0);return(0,Q.useEffect)(()=>{if(!v)return;h(Date.now());let e=setInterval(()=>h(Date.now()),1e3);return()=>clearInterval(e)},[v]),e.length?(0,$.jsxs)(`section`,{className:`question-queue`,"aria-label":n,children:[(0,$.jsxs)(`div`,{className:`question-queue-list`,children:[(0,$.jsxs)(`div`,{children:[n,` · `,e.length]}),e.filter(e=>e!==g).map(e=>(0,$.jsxs)(`div`,{className:`question-queue-item`,children:[(0,$.jsx)(`div`,{className:`question-queue-summary`,children:r(e)}),Lb(a(e),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,Lb(a(e),m)]}),(0,$.jsxs)(`div`,{className:`question-queue-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>p(t(e)),children:l(`questionQueueOpen`)}),o&&s?.(e)&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>o(e),children:l(`questionQueueNavigate`)})]})]},t(e)))]}),g&&(0,$.jsxs)(`div`,{className:`question-queue-dialog`,children:[Lb(a(g),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,Lb(a(g),m)]}),c(g,()=>{d(e=>new Set(e).add(t(g))),p(null)})]},_)]}):null}function $b({questions:e,activeConversationId:t,mode:n}){let r=V(),i=e=>{let t=Ib(e);t&&Z(t)};return(0,$.jsx)(Qb,{items:e.filter(e=>e.audience===`user`),itemKey:zb,title:r(`questionQueueTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.questions[0]?.header||e.questions[0]?.question||r(`modelQuestion`)]}),createdAt:e=>e.createdAt,canAutoOpen:e=>n!==`manual`&&(n===`all`||e.conversationId===t||!e.conversationId),onNavigate:i,canNavigate:e=>!!(e.rootConversationId||e.conversationId)&&(!!e.owner||(e.conversationId?e.conversationId!==t:!Bb(e,t))),children:(e,t)=>(0,$.jsx)(Xb,{question:e,owner:e.owner,onDefer:t,onNavigate:e.rootConversationId||e.conversationId?()=>i(e):void 0},zb(e))})}function ex({entry:e}){let t=(0,Q.useRef)(null),n=V();return(0,Q.useEffect)(()=>{let r=t.current;if(!r)return;let{container:i,cleanup:a}=pm(r,{isolated:!!(e.info.isolated||e.module.isolated||e.module.shadow)}),o;try{o=e.module.mount(i,Lm(e.info.id,e=>Z(e)))}catch(t){console.error(`[plugin:${e.info.id}] mount failed:`,t),i.textContent=n(`pluginMountFailed`,{name:e.info.name})}return()=>{if(typeof o==`function`)try{o()}catch(t){console.error(`[plugin:${e.info.id}] cleanup failed:`,t)}a()}},[e]),(0,$.jsx)(`div`,{className:`plugin-view`,ref:t})}function tx({pluginId:e,info:t,epoch:n,failed:r}){let i=V(),[a,o]=(0,Q.useState)(!1),s=t?.name||e;return r?(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsxs)(`div`,{className:`plugin-view-fallback`,role:`alert`,children:[(0,$.jsxs)(`div`,{className:`plugin-view-fallback-title`,children:[i(`pluginViewLoadFailed`),`:`,s]}),(0,$.jsx)(`div`,{className:`plugin-view-fallback-hint`,children:i(`pluginViewLoadFailedHint`)}),t&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-view-fallback-retry`,onClick:()=>{t&&!a&&(o(!0),Dm(t,n).finally(()=>o(!1)))},disabled:a,children:i(a?`pluginViewLoading`:`pluginViewRetry`)})]})}):(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsx)(`div`,{className:`plugin-view-fallback`,role:`status`,children:i(`pluginViewLoading`)})})}function nx({onAction:e}){let t=Ri(),n=(0,Q.useMemo)(()=>t?Gi(t.entries):[],[t]),{items:r,selectParents:i}=(0,Q.useMemo)(()=>Wi(n),[n]),a=(0,Q.useMemo)(()=>Ki(r),[r]),o=(0,Q.useMemo)(()=>typeof window>`u`?!1:a.length>14&&window.innerWidth>=640,[a.length]),s=(0,Q.useMemo)(()=>t?Vi(t.slot,t.target):void 0,[t,t?.slot,t?.target.kind]),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(-1),[m,h]=(0,Q.useState)(-1),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(0),b=(0,Q.useRef)(-1),x=e=>{b.current=e,p(e)},S=(0,Q.useMemo)(()=>m>=0?Gi(r[m]?.children??[]):[],[r,m]),C=(0,Q.useMemo)(()=>Ki(S),[S]),w=e=>{let n=r[e];if(t&&n&&!Ui(n,s)){if(n.children?.length){h(e);return}T(n,t)||Fi()}},T=(t,n,r)=>t.source===`host`&&n.onHostAction?n.onHostAction(t,n.target)===!0:(e(t,n.target,r),!1),E=(0,Q.useRef)(w);if((0,Q.useLayoutEffect)(()=>{E.current=w}),(0,Q.useEffect)(()=>{if(!t){b.current=-1,p(-1),h(-1);return}let e=Ji(r,-1,1,s);b.current=e,p(e),h(-1),c.current?.focus()},[t,r,s]),(0,Q.useLayoutEffect)(()=>{if(!t){d(null);return}let e=c.current;if(!e)return;let n=e.getBoundingClientRect();d(Bi(t.x,t.y,n.width,n.height,window.innerWidth,window.innerHeight))},[t,r]),(0,Q.useLayoutEffect)(()=>{let e=l.current,t=c.current;if(m<0||!e||!t){_(!1),y(0);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=window.innerWidth-r.right,a=r.left;_(i<n.width+8&&a>i);let o=n.bottom-(window.innerHeight-8);y(o>0?-Math.min(o,Math.max(0,n.top-8)):0)},[m,r]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>c.current&&e instanceof Node&&c.current.contains(e),n=t=>{e(t.target)||Fi()},r=t=>{e(t.target)||Fi()},i=()=>Fi();return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`wheel`,r,!0),window.addEventListener(`resize`,i),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`wheel`,r,!0),window.removeEventListener(`resize`,i)}},[t]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{let t=Ji(r,b.current,e,s);b.current=t,p(t)},n=t=>{switch(t.key){case`Escape`:t.preventDefault(),Fi();return;case`Tab`:Fi();return;case`ArrowDown`:t.preventDefault(),e(1);return;case`ArrowUp`:t.preventDefault(),e(-1);return;case`ArrowRight`:r[b.current]?.children?.length&&(t.preventDefault(),h(b.current));return;case`ArrowLeft`:m>=0&&(t.preventDefault(),h(-1));return;case`Enter`:case` `:t.preventDefault(),E.current(b.current);return;default:return}};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[t,r,m,s]),(0,Q.useEffect)(()=>{f<0||c.current?.querySelector(`[data-ctx-active="true"]`)?.scrollIntoView?.({block:`nearest`})},[f]),!t)return null;let D=e=>{let n=i.get(e.id);if(n){if(Ui(n.parent,s))return;t&&!T(n.parent,t,n.value)&&Fi();return}Ui(e,s)||T(e,t)||Fi()},O=(e,t,n)=>{let r=Ui(e,s),i=!!e.children?.length,a=Xi(e.icon),o=n&&f===t;return(0,$.jsxs)(`div`,{className:`ctx-menu-itemwrap`,role:`none`,children:[(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item${r?` disabled`:``}${o?` active`:``}${i?` has-sub`:``}`,"aria-label":e.label,title:e.hint,"aria-disabled":r||void 0,"aria-haspopup":i?`menu`:void 0,"aria-expanded":i?m===t:void 0,"data-ctx-active":o?`true`:void 0,onMouseEnter:n?()=>{x(t),i&&!r&&h(t)}:void 0,onClick:()=>n?w(t):D(e),children:[a?(0,$.jsx)(`span`,{className:`ctx-menu-icon`,"aria-hidden":`true`,children:a}):null,(0,$.jsx)(`span`,{className:`ctx-menu-label`,children:e.label}),e.badge?(0,$.jsx)(`span`,{className:`ctx-menu-badge`,children:e.badge}):null,i?(0,$.jsx)(`span`,{className:`ctx-menu-caret`,"aria-hidden":`true`,children:`▸`}):null]}),n&&i&&m===t?(0,$.jsx)(`div`,{ref:l,className:`ctx-menu-sub${g?` left`:``}`,role:`menu`,"aria-label":e.label,style:v?{marginTop:v}:void 0,children:C.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):O(e.entry,e.index,!1))}):null]},`${e.id}#${t}`)};return(0,bn.createPortal)((0,$.jsx)(`div`,{ref:c,className:`ctx-menu${o?` is-multi-col`:``}`,role:`menu`,"aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:u?.x??t.x,top:u?.y??t.y,visibility:u?`visible`:`hidden`},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},children:a.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):O(e.entry,e.index,!0))}),document.body)}var rx=0,ix=[],ax=new Map,ox=new Set;function sx(){for(let e of ox)try{e()}catch{}}function cx(e){let t=ax.get(e);t!==void 0&&(clearTimeout(t),ax.delete(e))}function lx(e){let t=e.id||`banner-${Date.now()}-${++rx}`,n={...e,id:t,type:e.type||`info`,persistent:!!e.persistent,timeoutMs:e.timeoutMs??5e3,dismissible:e.dismissible!==!1};if(cx(t),!n.persistent&&n.timeoutMs&&n.timeoutMs>0){let e=setTimeout(()=>{ux(t)},n.timeoutMs);ax.set(t,e)}let r=ix.findIndex(e=>e.id===t);if(r>=0){let e=[...ix];e[r]=n,ix=e}else ix=[...ix,n];return sx(),t}function ux(e,t){cx(e);let n=ix.find(t=>t.id===e);if(n){if(ix=ix.filter(t=>t.id!==e),!t?.silent)try{n.onClose?.()}catch{}sx()}}function dx(e,t){let n=ix.filter(e);if(n.length!==0){for(let e of n)if(cx(e.id),!t?.silent)try{e.onClose?.()}catch{}ix=ix.filter(t=>!e(t)),sx()}}function fx(){return ix}function px(e){return ox.add(e),()=>{ox.delete(e)}}function mx(){return(0,Q.useSyncExternalStore)(px,fx,fx)}function hx({type:e}){switch(e){case`question`:return(0,$.jsx)(K,{className:`banner-icon banner-icon-question`});case`warning`:return(0,$.jsx)(He,{className:`banner-icon banner-icon-warning`});case`error`:return(0,$.jsx)(je,{className:`banner-icon banner-icon-error`});case`success`:return(0,$.jsx)(et,{className:`banner-icon banner-icon-success`});default:return(0,$.jsx)(We,{className:`banner-icon banner-icon-info`})}}var gx=(0,Q.memo)(function({banner:e}){let t=V(),n=typeof e.onClick==`function`;return(0,$.jsxs)(`div`,{className:`banner-card banner-type-${e.type||`info`} ${n?`banner-clickable`:``}`,onClick:n?e.onClick:void 0,role:n?`button`:`status`,tabIndex:n?0:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e.onClick?.())}:void 0,children:[(0,$.jsx)(`div`,{className:`banner-icon-col`,children:(0,$.jsx)(hx,{type:e.type})}),(0,$.jsxs)(`div`,{className:`banner-content-col`,children:[e.title&&(0,$.jsx)(`div`,{className:`banner-title`,title:e.title,children:e.title}),(0,$.jsx)(`div`,{className:`banner-message`,title:e.message,children:e.message})]}),e.dismissible&&(0,$.jsx)(`button`,{type:`button`,className:`banner-close`,onClick:t=>{t.stopPropagation(),ux(e.id)},"aria-label":`Close banner`,title:t(`close`),children:(0,$.jsx)(R,{})})]})}),_x=(0,Q.memo)(function(){let e=mx();return e.length===0?null:(0,$.jsx)(`aside`,{className:`banner-container`,"aria-label":`Notifications`,children:e.map(e=>(0,$.jsx)(gx,{banner:e},e.id))})});function vx({slots:e,layout:t,exclude:n,onClose:r}){let i=V(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useMemo)(()=>Sb(e,n),[e,n]),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(l),p=(0,Q.useRef)(t),m=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{f.current=l,p.current=t}),(0,Q.useEffect)(()=>{m.current=null},[t]);let h=(e,t)=>{let n=document.elementFromPoint(e,t)?.closest(`[data-drop-slot]`);if(!n)return null;let r=n.dataset.dropSlot;if(!r)return null;let i=n.dataset.dropAlign,a=u.current,o=Array.from(n.querySelectorAll(`[data-chip]`)).filter(e=>e.dataset.chip!==a),s=o.length;for(let n=0;n<o.length;n++){let r=o[n].getBoundingClientRect();if(t<r.top){s=n;break}if(t<=r.bottom+4&&e<r.left+r.width/2){s=n;break}}return{slot:r,align:i,index:s}},g=()=>{let e=u.current,t=d.current;if(u.current=null,d.current=null,o(null),c(null),!e||!t)return;let n=m.current??p.current,r=t.slot===`__tray`?Ob(n,e):Db(n,f.current,{id:e,slot:t.slot,...t.align===void 0?{}:{align:t.align},index:t.index});m.current=r,Z({type:`set_settings`,uiLayout:r})};(0,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.preventDefault();let t=h(e.clientX,e.clientY);d.current=t,c(t)},t=()=>g();return window.addEventListener(`pointermove`,e,{passive:!1}),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t)}},[a]),mt(()=>{u.current||r()});let _=(e,t)=>{(e.pointerType!==`mouse`||e.button===0)&&(e.preventDefault(),u.current=t,d.current=null,o(t),c(null))},v=e=>(0,$.jsxs)(`button`,{type:`button`,"data-chip":e.id,className:`icon-editor-chip${a===e.id?` dragging`:``}`,title:e.label,onPointerDown:t=>_(t,e.id),children:[(0,$.jsx)(`span`,{className:`icon-editor-chip-icon`,children:Da(e)}),(0,$.jsx)(`span`,{className:`icon-editor-chip-label`,children:e.label})]},e.id),y=(e,t,n,r)=>{let o=s?.slot===e&&(s.align??null)===(t??null),c=r.map(v);return o&&s&&c.splice(Math.max(0,Math.min(s.index,c.length)),0,(0,$.jsx)(`span`,{className:`icon-editor-caret`,"aria-hidden":`true`},`__caret`)),(0,$.jsxs)(`div`,{className:`icon-editor-strip${o?` drop-over`:``}${a?` dragging-active`:``}`,"data-drop-slot":e,...t===void 0?{}:{"data-drop-align":t},children:[n!==null&&(0,$.jsx)(`span`,{className:`icon-editor-strip-label`,children:n}),c,r.length===0&&(0,$.jsx)(`span`,{className:`icon-editor-empty`,children:i(`uiIconEditDropHere`)})]},t??`__all`)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`icon-editor-backdrop`,onClick:r}),(0,$.jsxs)(`div`,{className:`icon-editor`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`uiIconEditTitle`),children:[(0,$.jsxs)(`div`,{className:`icon-editor-head`,children:[(0,$.jsx)(`span`,{className:`icon-editor-title`,children:i(`uiIconEditTitle`)}),(0,$.jsx)(`span`,{className:`icon-editor-hint`,children:i(`uiIconEditHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`icon-editor-close`,onClick:r,"aria-label":i(`close`),title:i(`close`),children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`icon-editor-body`,children:[vb.map(e=>{let t=l.zones[e.slot]??[],n=wb(t);return(0,$.jsxs)(`div`,{className:`icon-editor-zone`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-zone-title`,children:[i(e.labelKey),a&&(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:n.length})]}),e.alignable?bb.map(n=>y(e.slot,n,e.vertical?xb(i,n):n,Tb(t,n))):y(e.slot,void 0,null,n)]},e.slot)}),(0,$.jsxs)(`div`,{className:`icon-editor-zone icon-editor-zone-tray`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-zone-title`,children:[i(`uiIconEditTray`),(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:l.tray.length})]}),y(yb,void 0,null,l.tray)]})]})]})]})}function yx(e,t){let n=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let r=zv(n.current,e);n.current=r.key,r.clear&&t()},[e,t])}var bx=new Map,xx=-1;function Sx(e){let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}function Cx(e){let t=e.replace(/\\/g,`/`).split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(n).toLowerCase():``}function wx(e,t){xx!==t&&(xx=t);let n=new Map;for(let t of e){let e=t;if(!e.error&&e.hasClient&&Array.isArray(e.fileHandlers)){for(let t of e.fileHandlers)if(t&&t.id&&Array.isArray(t.extensions))for(let r of t.extensions){if(typeof r!=`string`)continue;let i=Sx(r);if(!/^\.[a-z0-9][a-z0-9._-]*$/.test(i))continue;let a=n.get(i)??[];a.push({plugin:e,declaration:t}),n.set(i,a)}}}for(let e of n.values())e.sort((e,t)=>t.declaration.priority-e.declaration.priority||e.plugin.id.localeCompare(t.plugin.id));bx=n}function Tx(e){return bx.get(Cx(e))?.[0]??null}async function Ex(e){let t=await Nm(e.plugin,xx);if(!t)return null;let n=t.fileHandlers,r;if(Array.isArray(n))r=n.find(t=>t&&t.id===e.declaration.id),!r&&n.length===1&&typeof n[0]?.mount==`function`&&(r=n[0]);else if(n&&typeof n==`object`){r=n[e.declaration.id];let t=Object.values(n);!r&&t.length===1&&typeof t[0]?.mount==`function`&&(r=t[0])}return!r||typeof r.mount!=`function`?null:{handler:r,pluginId:e.plugin.id}}var Dx=(0,Q.memo)(function({open:e=!0,currentModelId:t,models:n,modelsLoading:r=!1,providerKeys:i={},defaultModel:a,onManageModels:o,onSelect:s,onClose:c,title:l}){let u=V();return(0,Q.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),c())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,c]),e?(0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:1200,display:`flex`,alignItems:`center`,justifyContent:`center`},onClick:e=>{e.target===e.currentTarget&&c()},children:(0,$.jsxs)(`div`,{className:`modal dd-menu dd-menu-model`,style:{position:`relative`,top:`auto`,bottom:`auto`,left:`auto`,right:`auto`,transform:`none`,width:`min(92vw, 680px)`,maxWidth:`680px`,height:`min(84vh, 640px)`,maxHeight:`86vh`,padding:0,gap:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,boxShadow:`0 24px 64px rgba(0, 0, 0, 0.55)`,background:`var(--bg-elev2, #1b1b24)`,borderRadius:`12px`,border:`1px solid var(--border)`},children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,style:{padding:`10px 14px`,borderBottom:`1px solid var(--border, #333)`},children:[(0,$.jsx)(`span`,{className:`dd-header-title`,style:{fontWeight:600},children:l||u(`availableModels`)}),(0,$.jsx)(`div`,{className:`dd-header-actions`,style:{marginLeft:`auto`},children:(0,$.jsx)(`button`,{type:`button`,className:`ghost dd-header-btn`,style:{border:0,cursor:`pointer`,fontSize:16},onClick:c,title:`关闭`,children:(0,$.jsx)(R,{})})})]}),(0,$.jsx)(Po,{models:n,modelsLoading:r,providerKeys:i,defaultModel:a,currentModelId:t,active:e,onEnsureModels:()=>{n.length===0&&!r&&Z({type:`list_models`})},onRefresh:()=>Z({type:`list_models`}),onManageModels:o,onPickModel:e=>{s(e.id,e),c()},isRowActive:e=>No(e,t),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{flex:`1 1 auto`,minHeight:0,minWidth:0,maxHeight:`none`,overflowY:`auto`}})]})}):null}),Ox=null,kx=new Set;function Ax(){for(let e of kx)e()}function jx(e){Ox=e,Ax()}function Mx(){Ox=null,Ax()}function Nx(e){Ox&&(Z({type:`rollback_session`,messageId:Ox.messageId,conversationId:Ox.conversationId,restoreWorkspace:e}),Ox=null,Ax())}function Px(){return(0,Q.useSyncExternalStore)(e=>(kx.add(e),()=>kx.delete(e)),()=>Ox)}function Fx(){let e=V(),t=Px(),[n,r]=(0,Q.useState)(!0),i=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{t&&r(!0)},[t]),mt(()=>{t&&Mx()},!!t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{if(e.key!==`Enter`||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=e.target;(!t||t===document.body||i.current?.contains(t))&&(e.preventDefault(),Nx(n))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]),t?(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:Mx,children:(0,$.jsxs)(`div`,{ref:i,className:`tool-info-modal rollback-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`rollbackSession`),onClick:e=>e.stopPropagation(),style:{maxWidth:520},children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(He,{}),e(`rollbackSession`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`cancel`),onClick:Mx,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 16px 0`,fontSize:14,lineHeight:1.6},children:e(`rollbackConfirm`)}),(0,$.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:10,padding:`12px 14px`,borderRadius:8,backgroundColor:`var(--bg-elev, rgba(255, 255, 255, 0.04))`,border:`1px solid var(--border-subtle, rgba(255, 255, 255, 0.1))`,cursor:`pointer`,marginBottom:20},title:e(`rollbackRestoreWorkspaceTip`),children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>r(e.target.checked),style:{marginTop:3,cursor:`pointer`}}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{style:{fontWeight:600,fontSize:13,color:`var(--text, #e2e8f0)`},children:e(`rollbackRestoreWorkspace`)}),(0,$.jsx)(`div`,{style:{fontSize:12,color:`var(--text-dim, #9aa1b4)`,marginTop:2},children:e(`rollbackRestoreWorkspaceTip`)})]})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:10},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:Mx,children:e(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>Nx(n),children:[(0,$.jsx)(z,{}),e(`confirm`)]})]})]})]})}),document.body):null}function Ix({approvals:e,activeConversationId:t,mode:n=`all`}){let r=V();return(0,$.jsx)(Qb,{items:e,itemKey:e=>e.id,title:r(`toolApprovalTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.toolName]}),createdAt:e=>e.createdAt??0,canAutoOpen:e=>n!==`manual`&&(n===`all`||e.conversationId===t||!e.conversationId),onNavigate:e=>{e.conversationId&&Z({type:`switch_conversation`,id:e.conversationId})},canNavigate:e=>!!e.conversationId,children:(e,t)=>(0,$.jsx)(Lx,{approval:e,onDefer:t},e.id)})}function Lx({approval:e,onDefer:t}){let n=V(),{locale:r}=Ue(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{if(e){let t=e.params;a(typeof t==`object`&&t?JSON.stringify(t,null,2):t==null?`{}`:String(t)),s(null)}},[e?.id]),!e)return null;let c=t=>{Z({type:`tool_approval_response`,id:e.id,decision:`approve`,...t&&t!==`once`?{scope:t}:{}})},l=()=>{Z({type:`tool_approval_response`,id:e.id,decision:`deny`,reason:`Operation rejected by user`})};return(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,children:(0,$.jsxs)(`div`,{className:`tool-info-modal approval-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`toolApprovalTitle`),style:{maxWidth:640,borderTop:`4px solid var(--amber, #f59e0b)`},onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(He,{}),n(`toolApprovalTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,style:{fontWeight:700},children:e.toolName}),e.parentTool===`codemode`&&(0,$.jsxs)(`span`,{className:`tool-info-label`,style:{backgroundColor:`rgba(245, 158, 11, 0.15)`,color:`var(--amber, #f59e0b)`,border:`1px solid rgba(245, 158, 11, 0.35)`,fontWeight:600},children:[`⚡ `,n(`codemodeNestedApprovalBadge`)]}),e.conversationTitle&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:e.conversationTitle}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,children:n(`pendingQueueDefer`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalDeny`),onClick:l,children:(0,$.jsx)(R,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[e.parentTool===`codemode`&&(0,$.jsxs)(`div`,{style:{padding:`8px 12px`,borderRadius:6,backgroundColor:`rgba(99, 102, 241, 0.12)`,border:`1px solid rgba(99, 102, 241, 0.25)`,marginBottom:12,color:`var(--text, #e2e8f0)`,fontSize:12.5,display:`flex`,alignItems:`center`,gap:6},children:[(0,$.jsx)(`span`,{style:{fontSize:14},children:`⚡`}),(0,$.jsx)(`span`,{children:n(`codemodeNestedApprovalDesc`)})]}),(e.reason||e.reasonEn)&&(0,$.jsxs)(`div`,{style:{padding:`10px 14px`,borderRadius:6,backgroundColor:`rgba(245, 158, 11, 0.12)`,border:`1px solid rgba(245, 158, 11, 0.3)`,marginBottom:16,color:`var(--amber, #f59e0b)`,fontSize:13,lineHeight:1.5,fontWeight:500},children:[(0,$.jsxs)(`div`,{style:{fontWeight:600,marginBottom:2},children:[n(`toolApprovalRiskAlert`),`:`]}),(0,$.jsx)(`div`,{children:H(r)?e.reason||e.reasonEn:e.reasonEn||e.reason}),e.category&&(0,$.jsxs)(`div`,{style:{marginTop:6,fontSize:12,opacity:.85},children:[n(`toolApprovalCategory`),`:`,H(r)?e.category.label:e.category.labelEn]}),e.hits&&e.hits.length>0&&(0,$.jsxs)(`div`,{className:`approval-hits-panel`,children:[(0,$.jsxs)(`div`,{className:`approval-hits-title`,children:[n(`toolApprovalHitsTitle`),` (`,e.hits.length,`)`]}),(0,$.jsx)(`div`,{className:`approval-hits-list`,children:e.hits.map((e,t)=>(0,$.jsxs)(`div`,{className:`approval-hit-item`,children:[(0,$.jsxs)(`div`,{className:`approval-hit-header`,children:[(0,$.jsx)(`span`,{className:`approval-hit-badge`,children:H(r)?e.label:e.labelEn||e.label}),(0,$.jsx)(`span`,{className:`approval-hit-field`,children:e.field}),(0,$.jsx)(`span`,{className:`approval-hit-pos`,children:n(`approvalHitPos`,{index:e.index+1,length:e.length})})]}),(0,$.jsx)(`div`,{className:`approval-hit-text`,children:(0,$.jsx)(`mark`,{className:`approval-danger-hit`,children:e.text})})]},t))})]})]}),e.toolName===`bash`&&typeof e.params?.command==`string`&&(0,$.jsxs)(`div`,{className:`approval-cmd-preview`,children:[(0,$.jsxs)(`div`,{className:`approval-cmd-preview-label`,children:[n(`approvalCommandPreview`),`:`]}),(0,$.jsxs)(`div`,{className:`approval-cmd-preview-box`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:xs(e.params.command,e.hits)})]})]}),(0,$.jsxs)(`div`,{style:{marginBottom:16},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:6},children:[(0,$.jsx)(`span`,{style:{fontSize:13,fontWeight:600,color:`var(--text, #e2e8f0)`},children:n(`toolApprovalParams`)}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim, #9aa1b4)`},children:n(`toolApprovalEditPlaceholder`)})]}),(0,$.jsx)(`textarea`,{rows:8,value:i,onChange:e=>{a(e.target.value),o&&s(null)},style:{width:`100%`,fontFamily:`var(--mono, monospace)`,fontSize:12,lineHeight:1.5,padding:10,borderRadius:6,backgroundColor:`var(--bg-elev, #111827)`,color:`var(--text, #f8fafc)`,border:o?`1px solid var(--red, #ef4444)`:`1px solid var(--border-subtle, rgba(255,255,255,0.1))`,boxSizing:`border-box`,resize:`vertical`}}),o&&(0,$.jsx)(`div`,{style:{color:`var(--red, #ef4444)`,fontSize:12,marginTop:4},children:o})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,justifyContent:`flex-end`,gap:10},children:[e.category&&(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowCategoryHint`),onClick:()=>c(`category`),children:[(0,$.jsx)(fe,{}),n(`toolApprovalAllowCategory`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowConversationHint`),onClick:()=>c(`all`),children:[(0,$.jsx)(et,{}),n(`toolApprovalAllowConversation`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,style:{color:`var(--red, #ef4444)`},onClick:l,children:[(0,$.jsx)(R,{}),n(`toolApprovalDeny`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>c(),style:{fontWeight:500},children:[(0,$.jsx)(z,{}),n(`toolApprovalApprove`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>{try{let t=e.params,n;n=typeof t==`object`&&t||t==null?JSON.parse(i):i,s(null),Z({type:`tool_approval_response`,id:e.id,decision:`edit`,editedParams:n})}catch(e){s(H(r)?`JSON 格式错误:${e.message}`:`JSON parse error: ${e.message}`)}},children:[(0,$.jsx)(ct,{}),n(`toolApprovalEditAndRun`)]})]})]})]})}),document.body)}var Rx={pending:`in_progress`,in_progress:`done`,done:`failed`,failed:`pending`};function zx({plan:e}){let t=V(),n=H(Se()),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=ac({duration:2e3}),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(``);if(!e||!e.steps||e.steps.length===0)return null;let h=e.steps,_=h.filter(e=>e.status===`done`).length,v=h.length,y=Math.round(_/v*100),b=h.find(t=>t.id===e.activeStepId)??h.find(e=>e.status===`in_progress`),x=()=>{window.confirm(n?`确定要清空当前任务计划看板吗?`:`Are you sure you want to clear the plan board?`)&&Z({type:`plan_update`,steps:[]})},S=()=>{Z({type:`set_plan_mode`,enabled:!1}),Z({type:`prompt`,text:t(`planImplementRequest`)})},C=()=>{let e=h.map((e,t)=>`${t+1}. ${e.title}${e.description?` (${e.description})`:``}`).join(`
|
|
77
77
|
`);Z({type:`plan_clean_handoff`,steps:h,prompt:`${t(`planCleanHandoffPrompt`)}\n\n${e}`})},w=async()=>{let e=[`# ${t(`planBoardTitle`)} (${_}/${v})`,``,...h.map((e,t)=>{let n=`${e.status===`done`?`[x]`:e.status===`in_progress`?`[>]`:e.status===`failed`?`[!]`:`[ ]`} ${t+1}. ${e.title}`;return e.description&&(n+=`\n ${e.description}`),n})];await o(e.join(`
|
|
78
|
-
`))},T=e=>{l(e.id),f(e.title),m(e.description||``)},E=()=>{l(null),f(``),m(``)},D=e=>{let t=d.trim();if(!t)return;let n={title:t};n.description=p.trim()?p.trim():void 0,Z({type:`plan_step_update`,stepId:e,patch:n}),l(null)},O=e=>{Z({type:`plan_step_delete`,stepId:e})},k=e=>{let t=h.find(t=>t.id===e);t&&Z({type:`plan_step_update`,stepId:e,patch:{status:Ix[t.status]}})},A=()=>{let e={id:`step-${Date.now()}`,title:t(`planBoardAddStep`),status:`pending`};Z({type:`plan_step_add`,step:e}),T(e)},j=(e,r)=>{let i=(()=>{switch(e){case`done`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(et,{}),t(`planBoardCompleted`)]});case`in_progress`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(u,{}),t(`planBoardInProgress`)]});case`failed`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(je,{}),t(`planBoardFailed`)]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(nt,{}),t(`planBoardPending`)]})}})();return(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),k(r)},title:n?`点击切换状态 (pending / in_progress / done / failed)`:`Click to toggle status (pending / in_progress / done / failed)`,style:{display:`inline-flex`,alignItems:`center`,gap:4,color:e===`done`?`var(--green, #22c55e)`:e===`in_progress`?`var(--accent, #38bdf8)`:e===`failed`?`var(--red, #ef4444)`:`var(--text-dim, #9aa1b4)`,fontSize:12,fontWeight:e===`pending`?400:600,background:`none`,border:`none`,cursor:`pointer`,padding:`2px 4px`,borderRadius:4},children:i})};return(0,$.jsxs)(`div`,{className:`plan-board ${r?``:`plan-board-collapsed`}`.trim(),children:[(0,$.jsxs)(`div`,{className:`plan-board-head`,onClick:()=>i(!r),children:[(0,$.jsxs)(`div`,{className:`plan-board-head-main`,children:[(0,$.jsx)(ge,{className:`plan-board-icon`}),(0,$.jsx)(`span`,{className:`plan-board-title`,children:t(`planBoardTitle`)}),(0,$.jsxs)(`span`,{className:`plan-board-count ${y===100?`plan-board-count-done`:``}`.trim(),children:[_,`/`,v]}),!r&&b&&(0,$.jsx)(`span`,{className:`plan-board-active`,title:b.title,children:b.title})]}),(0,$.jsxs)(`div`,{className:`plan-board-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-implement`,title:t(`planImplementTip`),onClick:e=>{e.stopPropagation(),S()},children:t(`planImplementBtn`)}),r&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-clean-handoff`,title:t(`planCleanHandoffTip`),onClick:e=>{e.stopPropagation(),C()},children:t(`planCleanHandoffBtn`)}),r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(a?`planBoardExportSuccess`:`planBoardExportMarkdown`),onClick:e=>{e.stopPropagation(),w()},children:a?(0,$.jsx)(z,{style:{color:`var(--green, #22c55e)`}}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`clear`),onClick:e=>{e.stopPropagation(),x()},children:(0,$.jsx)(g,{})})]}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(r?`collapseSection`:`expandSection`),children:r?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})})]}),r&&(0,$.jsx)(`div`,{className:`plan-board-head-divider`,children:(0,$.jsx)(`div`,{className:`plan-board-head-divider-fill`,style:{width:`${y}%`,backgroundColor:y===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})})]}),!r&&(0,$.jsx)(`div`,{className:`plan-board-progress-line`,children:(0,$.jsx)(`div`,{className:`plan-board-progress-line-fill`,style:{width:`${y}%`,backgroundColor:y===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})}),r&&(0,$.jsxs)(`div`,{className:`plan-board-steps`,style:{marginTop:8,display:`flex`,flexDirection:`column`,gap:8},children:[h.map((n,r)=>{let i=n.id===e.activeStepId||n.status===`in_progress`;return c===n.id?(0,$.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,padding:`8px 10px`,borderRadius:6,backgroundColor:`var(--bg-elev2, rgba(0, 0, 0, 0.2))`,border:`1px solid var(--accent, #38bdf8)`},children:[(0,$.jsx)(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:t(`planBoardStepTitlePlaceholder`),style:{width:`100%`,padding:`4px 8px`,borderRadius:4,border:`1px solid var(--border-subtle)`,background:`var(--bg, #0b0f17)`,color:`var(--text, #f1f5f9)`,fontSize:13},autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),D(n.id)):e.key===`Escape`&&E()}}),(0,$.jsx)(`textarea`,{rows:2,value:p,onChange:e=>m(e.target.value),placeholder:t(`planBoardStepDescPlaceholder`),style:{width:`100%`,padding:`4px 8px`,borderRadius:4,border:`1px solid var(--border-subtle)`,background:`var(--bg, #0b0f17)`,color:`var(--text-dim, #9aa1b4)`,fontSize:12,resize:`vertical`},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),D(n.id)):e.key===`Escape`&&E()}}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:6,marginTop:2},children:[(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-iconbtn`,onClick:E,title:t(`cancel`),style:{padding:`3px 8px`,fontSize:12},children:[(0,$.jsx)(R,{}),` `,t(`cancel`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-implement`,onClick:()=>D(n.id),title:t(`confirm`),style:{padding:`3px 10px`,fontSize:12},children:[(0,$.jsx)(z,{}),` `,t(`confirm`)]})]})]},n.id||r):(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,flexWrap:`wrap`,rowGap:4,minWidth:0,padding:`6px 10px`,borderRadius:6,backgroundColor:i?`rgba(56, 189, 248, 0.08)`:`var(--bg-elev2, rgba(0, 0, 0, 0.2))`,border:i?`1px solid rgba(56, 189, 248, 0.25)`:`1px solid transparent`},children:[(0,$.jsxs)(`div`,{style:{flex:`1 1 180px`,minWidth:0,paddingRight:10},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:6,minWidth:0},children:[(0,$.jsxs)(`span`,{style:{fontSize:11,fontWeight:700,color:i?`var(--accent, #38bdf8)`:`var(--text-dim, #9aa1b4)`,minWidth:16},children:[r+1,`.`]}),(0,$.jsx)(`span`,{style:{fontWeight:i?600:500,color:n.status===`done`?`var(--text-dim, #9aa1b4)`:`var(--text, #f1f5f9)`,textDecoration:n.status===`done`?`line-through`:`none`,minWidth:0,overflowWrap:`anywhere`,wordBreak:`break-word`},children:n.title})]}),n.description&&(0,$.jsx)(`div`,{style:{fontSize:12,color:`var(--text-dim, #9aa1b4)`,marginTop:2,paddingLeft:22,lineHeight:1.4,overflowWrap:`anywhere`,wordBreak:`break-word`},children:n.description})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,flexShrink:0,marginTop:2},children:[j(n.status,n.id),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardEditStep`),onClick:()=>T(n),children:(0,$.jsx)(M,{size:12})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardDeleteStep`),onClick:()=>O(n.id),children:(0,$.jsx)(g,{size:12})})]})]},n.id||r)}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-add-btn`,onClick:A,children:[(0,$.jsx)(rt,{}),` `,t(`planBoardAddStep`)]})]})]})}var Rx=3,zx=200;function Bx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vx(e){return typeof e==`string`&&e.trim()||void 0}function Hx(e,t){let n=[];for(let r of e){let e=Wx(r,t);if(n.includes(e)||n.push(e),n.length>=4){n.push(`…`);break}}return n.join(` | `)||`any`}function Ux(e){let t=e.slice(0,6).map(e=>typeof e==`string`?e:JSON.stringify(e)??String(e));if(t.length!==0)return`enum: ${t.join(` | `)}${e.length>t.length?` | …`:``}`}function Wx(e,t=0){if(t>6||!Bx(e))return`any`;if(Vx(e.$ref))return`ref`;let n=Vx(e.type);if(n===`array`){let n=e.items;return`array<${n===void 0?`any`:Wx(n,t+1)}>`}if(n)return n;for(let n of[`anyOf`,`oneOf`,`allOf`]){let r=e[n];if(Array.isArray(r)&&r.length>0)return Hx(r,t+1)}return Bx(e.properties)?`object`:Bx(e.additionalProperties)?`record<${Wx(e.additionalProperties,t+1)}>`:`any`}function Gx(e){let t=[],n=e.enum;if(Array.isArray(n)&&n.length>0){let e=Ux(n);e&&t.push(e)}return e.const!==void 0&&t.push(`const: ${JSON.stringify(e.const)}`),e.default!==void 0&&t.push(`default: ${JSON.stringify(e.default)}`),t.length>0?t.join(` · `):void 0}function Kx(e,t={}){let n=t.maxDepth??Rx,r=t.maxRows??zx,i=e;if(!Bx(i))return[];let a=i.properties;if(!Bx(a))return[];let o=[],s=new Set((Array.isArray(i.required)?i.required:[]).filter(e=>typeof e==`string`)),c=(e,t,i,a)=>{if(!(o.length>=r))for(let[s,l]of Object.entries(e)){if(o.length>=r)return;let e=Bx(l)?l:{},u=t?`${t}.${s}`:s,d={name:u,type:Wx(e,i),required:a.has(s),depth:i},f=Vx(e.description);f&&(d.description=f);let p=Gx(e);if(p&&(d.hint=p),o.push(d),i+1<n&&Bx(e.properties)){let t=new Set((Array.isArray(e.required)?e.required:[]).filter(e=>typeof e==`string`));c(e.properties,u,i+1,t)}}};return c(a,``,0,s),o}function qx(){let e=V(),t=Ul();return mt(()=>{zl()},!!t),t?(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:zl,children:(0,$.jsxs)(`div`,{className:`tool-info-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`toolInfoTitle`),onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,children:[(0,$.jsx)(We,{}),e(`toolInfoTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,children:t.name}),t.label&&t.label!==t.name&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:t.label}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),onClick:zl,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`div`,{className:`tool-info-body`,children:(0,$.jsx)(Jx,{info:t})})]})}),document.body):null}function Jx({info:e}){let t=V();if(e.status===`loading`)return(0,$.jsxs)(`div`,{className:`tool-info-state`,role:`status`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,t(`toolInfoLoading`)]});if(e.status===`unsupported`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoUnsupported`)});if(e.status===`missing`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoMissing`)});let n=e.parameters===void 0?[]:Kx(e.parameters),r=e.parameters===void 0?``:Xx(e.parameters);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`tool-info-badges`,children:[e.active!==void 0&&(0,$.jsx)(`span`,{className:`tool-info-badge ${e.active?`on`:`off`}`,children:e.active?t(`toolInfoActive`):t(`toolInfoInactive`)}),e.source&&(0,$.jsxs)(`span`,{className:`tool-info-badge`,children:[t(`toolInfoSource`),`: `,e.source,e.scope?` · ${e.scope}`:``]})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoDescription`)}),(0,$.jsx)(`div`,{className:`tool-info-text`,children:e.description||t(`toolInfoNoDescription`)})]}),e.promptSnippet&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoPromptSnippet`)}),(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:e.promptSnippet})]}),e.promptGuidelines&&e.promptGuidelines.length>0&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoGuidelines`)}),(0,$.jsx)(`ul`,{className:`tool-info-list`,children:e.promptGuidelines.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoParams`)}),n.length>0?(0,$.jsx)(Yx,{rows:n}):(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:t(`toolInfoParamsNone`)}),e.parametersDropped&&(0,$.jsx)(`div`,{className:`tool-info-text warn`,children:t(`toolInfoSchemaDropped`)}),r&&(0,$.jsxs)(`details`,{className:`tool-info-raw`,children:[(0,$.jsxs)(`summary`,{children:[t(`toolInfoRawSchema`),(0,$.jsx)(ic,{text:r})]}),(0,$.jsx)(`pre`,{children:r})]})]}),(0,$.jsx)(`div`,{className:`tool-info-foot`,children:t(`toolInfoFootnote`)})]})}function Yx({rows:e}){let t=V();return(0,$.jsx)(`div`,{className:`tool-schema-table`,role:`table`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`tool-schema-row`,role:`row`,style:{paddingLeft:8+e.depth*14},children:[(0,$.jsxs)(`div`,{className:`tool-schema-name`,children:[(0,$.jsx)(`code`,{children:e.name}),e.required&&(0,$.jsx)(`span`,{className:`tool-schema-req`,children:t(`toolInfoRequired`)})]}),(0,$.jsxs)(`div`,{className:`tool-schema-type`,children:[e.type,e.hint&&(0,$.jsx)(`span`,{className:`tool-schema-hint`,children:e.hint})]}),e.description&&(0,$.jsx)(`div`,{className:`tool-schema-desc`,children:e.description})]},e.name))})}function Xx(e){try{return JSON.stringify(e,null,2)??``}catch{return``}}var Zx={bash:(0,$.jsx)(o,{}),skill:(0,$.jsx)(Le,{}),read:(0,$.jsx)(x,{}),write:(0,$.jsx)(ct,{}),edit:(0,$.jsx)(M,{}),edit_soft:(0,$.jsx)(M,{}),grep:(0,$.jsx)(Ee,{}),find:(0,$.jsx)(D,{}),codemode:(0,$.jsx)(se,{}),eval:(0,$.jsx)(c,{}),lsp:(0,$.jsx)(c,{}),tool_search:(0,$.jsx)(Ee,{}),conversation:(0,$.jsx)(Ve,{}),subagent:(0,$.jsx)(Ve,{}),delegate_task:(0,$.jsx)(fe,{}),present_files:(0,$.jsx)(at,{}),browser_search:(0,$.jsx)(Ee,{}),browser_use:(0,$.jsx)(le,{}),ask_user_question:(0,$.jsx)(K,{}),conversation_read:(0,$.jsx)(Ae,{})};function Qx(){let e=zc();return!e||typeof document>`u`?null:(0,bn.createPortal)((0,$.jsx)($x,{state:e}),document.body)}function $x({state:e}){let[t,n]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),Ic())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let r=()=>n(e=>!e);if(e.isThinking)return(0,$.jsx)(eS,{state:e,isMaximized:t,onToggleMaximize:r});let i=e.name||``;return i===`edit`||i===`write`||i===`edit_soft`||i===`patch`?(0,$.jsx)(rS,{state:e,isMaximized:t,onToggleMaximize:r}):i===`bash`?(0,$.jsx)(tS,{state:e,isMaximized:t,onToggleMaximize:r}):i===`read`||i===`ls`||i===`grep`||i===`find`||i===`tool_search`?(0,$.jsx)(nS,{state:e,isMaximized:t,onToggleMaximize:r}):(0,$.jsx)(iS,{state:e,isMaximized:t,onToggleMaximize:r})}function eS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),{copy:i,copied:a}=rc({duration:1200}),o=e.thinking||e.output||``,s=o.length,c=o?o.split(`
|
|
79
|
-
`).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&
|
|
80
|
-
`).length:0,C=p&&typeof p==`object`?Object.keys(p).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&
|
|
81
|
-
`).length:0,D=d&&typeof d==`object`?Object.keys(d).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Ic()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:Zx[c]??(0,$.jsx)(x,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:y,children:y}),v&&(0,$.jsx)(`span`,{className:`file-diff-pattern`,title:i?`搜索表达式: ${v}`:`Pattern: ${v}`,children:c===`grep`?`REGEX`:`QUERY`}),_&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:_.split(`.`).pop()?.toUpperCase()||`FILE`}),S>1&&(0,$.jsxs)(`span`,{className:`file-diff-lang`,title:`起始偏移量: 第 ${S} 行`,children:[`L`,S,`~L`,S+E-1]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${T}`,children:[`✓ `,w]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`preview`)},children:i?`内容查看`:`Content`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),_&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!_)return;let t=_.split(`/`).pop()||_;Gc({path:_,name:t})},children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s.copied?` copied`:``}`,title:s.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),s.copy(u)},children:s.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Ic()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:l||`(无入参参数 / No arguments)`})]}),C&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[D,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:C})]})]}):(0,$.jsxs)(`div`,{className:`read-inspector-viewport`,children:[c===`tool_search`&&(0,$.jsx)(Pd,{details:d}),b&&h&&h.length>0?(0,$.jsxs)(`div`,{className:`read-image-viewport`,children:[h.map((e,t)=>{let n=e.startsWith(`/`)?q(e):e;return(0,$.jsx)(`div`,{className:`read-image-container`,children:(0,$.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,title:`点击新窗口查看原图`,children:(0,$.jsx)(`img`,{src:n,alt:_||`Image ${t+1}`,className:`read-image-item`})})},t)}),u&&(0,$.jsx)(`div`,{className:`read-image-caption`,children:u})]}):u?(0,$.jsx)(yd,{content:u,startLine:S}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`)})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${f?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:f?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:r(`toolInspectorStats`,{chars:u.length,lines:E})})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[D>0&&(0,$.jsxs)(`span`,{children:[`details: `,D,` keys`]}),D>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`preview`:`raw`)},children:a===`raw`?i?`返回内容`:`Back to content`:i?`查看完整参数`:`View raw`})]})]})]})})}function rS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,o]=(0,Q.useState)(`unified`),{copied:s,copy:c}=rc({duration:1200}),{name:l=`edit`,args:u=``,details:d,output:f=``,isError:p=!1,status:m,duration:h}=e,g=(0,Q.useMemo)(()=>_d(l,u,d,f),[l,u,d,f]),_=d&&typeof d==`object`?Object.keys(d).length:0,v=(0,Q.useMemo)(()=>{if(!d||typeof d!=`object`)return``;try{return JSON.stringify(d,null,2)}catch{return``}},[d]),y=p?r(`error`):h?`${r(`done`)} (${h})`:m||r(`done`),b=p?`err`:`ok`;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Ic()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(x,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:g?.filePath||l,children:g?.filePath||l}),g?.language&&g.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:g.language}),g?.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:r(`diffNewFile`)}):g?.stats.additions!==void 0&&(g.stats.additions>0||g.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[g.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,g.stats.additions]}),g.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,g.stats.deletions]})]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${b}`,children:[`✓ `,y]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`unified`)},children:r(`diffViewUnified`)}),!g?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`split`)},children:r(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s?` copied`:``}`,title:g?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),"aria-label":g?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),onClick:e=>{e.stopPropagation(),g?.isWrite&&g.content?c(g.content):u&&c(u)},children:s?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),g?.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(`diffOpenFile`),"aria-label":r(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!g?.filePath)return;let t=g.filePath.split(`/`).pop()||g.filePath;Gc({path:g.filePath,name:t})},children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),"aria-label":r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,"aria-label":r(`close`),onClick:e=>{e.stopPropagation(),Ic()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:u||`(无入参参数 / No arguments)`})]}),v&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[_,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:v})]})]}):g?.isWrite?(0,$.jsx)(yd,{content:g.content||``}):a===`split`?(0,$.jsx)(Sd,{hunks:g?.hunks||[],isStreaming:g?.isStreamingPartial,fallbackText:u}):(0,$.jsx)(bd,{hunks:g?.hunks||[],isStreaming:g?.isStreamingPartial,fallbackText:u})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${p?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:p?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:f||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[_>0&&(0,$.jsxs)(`span`,{children:[`details: `,_,` keys`]}),_>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`unified`:`raw`)},children:a===`raw`?i?`返回差异对比`:`Back to diff`:i?`查看完整日志`:`View raw logs`})]})]})]})})}function iS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,o]=(0,Q.useState)(`preview`),s=rc({duration:1200}),{name:c=`tool`,args:l=``,details:u,output:d=``,isError:f=!1,status:p,duration:m,images:h}=e,g=$l({name:c,argumentsText:l,hints:e.hints||eu(l)}),_=g?`${c}(${g.text})`:c?`${c}()`:r(`toolInspectorTitle`),v=(0,Q.useMemo)(()=>{if(!u||typeof u!=`object`)return``;try{return JSON.stringify(u,null,2)}catch{return``}},[u]),y=f?r(`error`):m?`${r(`done`)} (${m})`:p||r(`done`),b=f?`err`:`ok`,x=u&&typeof u==`object`?Object.keys(u).length:0,S=c===`present_files`,C=(0,Q.useMemo)(()=>S&&l?xu(l):null,[S,l]),w=c===`delegate_task`,T=(0,Q.useMemo)(()=>w&&l?iu(l):{},[w,l]),E=c===`codemode`,D=(0,Q.useMemo)(()=>E&&l?du(l):null,[E,l]),O=c===`ask_user_question`,k=(0,Q.useMemo)(()=>O&&l?hu(l):null,[O,l]),A=!!(S&&C||w&&Object.keys(T).length>0||E&&D?.code||O&&k);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Ic()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:Zx[c]??(0,$.jsx)(at,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_,children:_}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${b}`,children:[`✓ `,y]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[A&&(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`preview`)},children:i?`视图`:`View`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s.copied?` copied`:``}`,title:s.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),s.copy(`[Arguments]\n${l}\n\n[Output]\n${d}`)},children:s.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Ic()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:l||`(无入参参数 / No arguments)`})]}),v&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[x,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:v})]})]}):(0,$.jsxs)(`div`,{className:`generic-inspector-viewport`,children:[S&&C&&(0,$.jsx)(rd,{args:C,details:u,toolCallId:e.toolCallId??``,resultTimestamp:e.resultTimestamp}),w&&(0,$.jsx)(Fd,{args:T}),E&&D?.code&&(0,$.jsx)(Id,{code:D.code,options:D.options,details:u,output:d}),O&&k&&(0,$.jsx)(cd,{questions:k.questions,details:u,output:d,isError:f,waiting:e.statusClass===`run`}),h&&h.length>0&&(0,$.jsxs)(`div`,{className:`tool-inspector-section pi-we-inspector-section`,style:{padding:`8px 14px`},children:[(0,$.jsx)(`div`,{className:`tool-inspector-label-row`,children:(0,$.jsxs)(`span`,{className:`tool-inspector-label pi-we-inspector-label`,children:[r(`toolInspectorImages`),` (`,h.length,`)`]})}),(0,$.jsx)(`div`,{className:`tool-inspector-images`,children:h.map((e,t)=>(0,$.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,title:`点击新窗口打开图片`,children:(0,$.jsx)(`img`,{src:e,alt:`output image ${t+1}`,loading:`lazy`})},t))})]}),!A&&(0,$.jsx)(`pre`,{className:`generic-output-pre`,children:d||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${f?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:f?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:d?`${d.split(`
|
|
82
|
-
`).length} 行输出 · ${d.length} 字符`:`执行完成`})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[x>0&&(0,$.jsxs)(`span`,{children:[`details: `,x,` keys`]}),x>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`preview`:`raw`)},children:a===`raw`?i?`返回视图`:`Back to view`:i?`查看完整参数与详情`:`View raw & details`})]})]})]})})}function aS({entry:e,pluginView:t,onUiAction:n,onClose:r}){let i=V(),a=e.label||e.id,o=e.kind===`view`;return(0,$.jsx)(Ma,{className:`plugin-modal`,title:a,icon:e.icon,onClose:r,children:(0,$.jsx)(`div`,{className:`modal-body plugin-modal-body`,children:o?t?(0,$.jsx)(Qb,{entry:t}):(0,$.jsx)(`div`,{className:`plugin-modal-loading`,children:i(`loading`)}):e.kind===`divider`?(0,$.jsx)(`hr`,{className:`plugin-modal-divider`}):(0,$.jsx)(`button`,{type:`button`,className:`btn primary plugin-modal-action`,onClick:()=>n?.(e),children:e.badge??a})})})}function oS({active:e,children:t}){let n=(0,Q.useRef)(!1);return e&&(n.current=!0),n.current?(0,$.jsx)(Q.Suspense,{fallback:null,children:t}):null}function sS({file:e,plugin:t,declaration:n,epoch:r,send:i,onClose:a,onFallback:o}){let s=V(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),p=(0,Q.useRef)(o);p.current=o;let m=n.label??t.name;(0,Q.useEffect)(()=>{let r=c.current;if(!r)return;let a=!1,o;return u(null),f(!1),(async()=>{try{let s=await wx({plugin:t,declaration:n});if(a)return;if(!s)throw Error(`插件没有提供可用的文件查看器`);let c=`/plugins-api/${encodeURIComponent(t.id)}`,l={...Fm(t.id,i),file:e,apiUrl:(e,t)=>{let n=String(e??``).startsWith(`/`)?String(e):`/${String(e??``)}`,r=new URLSearchParams;for(let[e,n]of Object.entries(t??{}))n!==void 0&&r.set(e,String(n));r.set(`clientId`,yh());let i=r.toString();return Qe(q(`${c}${n}${i?`?${i}`:``}`))}};o=s.handler.mount(r,e,l),a||f(!0)}catch(e){a||(console.error(`[plugin:${t.id}] file handler failed:`,e),p.current())}})(),()=>{if(a=!0,typeof o==`function`)try{o()}catch(e){console.error(`[plugin:${t.id}] file handler cleanup failed:`,e)}r.textContent=``}},[e,t,n,r,i]);let h=(0,$.jsxs)(`div`,{className:`plugin-file-preview-title-row`,children:[(0,$.jsx)(`span`,{className:`plugin-file-preview-name`,title:e.path,children:e.name||e.path}),m?(0,$.jsx)(`span`,{className:`plugin-file-preview-badge`,children:m}):null]});return(0,$.jsx)(Ma,{className:`plugin-file-preview`,title:h,icon:t.icon,allowFullscreen:!0,onClose:a,children:(0,$.jsxs)(`div`,{className:`modal-body plugin-file-preview-body`,children:[l?(0,$.jsx)(`div`,{className:`plugin-file-preview-error`,children:l}):null,!l&&!d?(0,$.jsx)(`div`,{className:`plugin-file-preview-loading`,children:s(`loading`)}):null,(0,$.jsx)(`div`,{ref:c,className:`plugin-file-preview-host`})]})})}var cS=.4,lS=1.05;function uS(e){return Math.min(300,e*.86)}function dS(e,t,n){return n||(t<=144?null:e<=72?`left`:t-e<=72?`right`:null)}function fS(e,t){let n=Math.abs(e),r=Math.abs(t);return n<12&&r<12?`none`:n>r*1.2?`horizontal`:`vertical`}function pS(e,t){return e===`left`?t:-t}function mS(e,t){return Math.max(-e,Math.min(0,-e+t))}function hS(e,t,n){let r=n?e+t:t;return Math.max(0,Math.min(1,r/e))}function gS(e){let{wasOpen:t,pull:n,width:r,durationMs:i}=e;return i<=320&&Math.abs(n)>=48?n>0:hS(r*lS,n,t)>=cS}var _S=new Set([`auto`,`scroll`,`overlay`]);function vS(e,t){let n=e instanceof Element?e:null;for(;n;){if(n instanceof HTMLElement&&n.scrollWidth>n.clientWidth+4&&_S.has(getComputedStyle(n).overflowX))return!0;if(n===t)break;n=n.parentElement}return!1}function yS(){let e=e=>{e.stopPropagation(),e.preventDefault()};window.addEventListener(`click`,e,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,e,{capture:!0}),400)}function bS(e){let{enabled:t,open:n,onOpenChange:r,container:i}=e,{panelSelector:a,backdropSelector:o}=e;(0,Q.useEffect)(()=>{let e=i.current;if(!t||!e)return;let s=null,c=`none`,l=0,u=0,d=0,f=0,p=!1,m=0,h=0,g=null,_=null,v=()=>{g&&(g.classList.remove(`drawer-dragging`),g.style.transform=``),_&&(_.style.opacity=``),s=null,c=`none`,g=null,_=null,f=0,p=!1},y=t=>{if(v(),t.touches.length!==1)return;let r=t.touches[0],i=dS(r.clientX,window.innerWidth,n);i&&!vS(t.target,e)&&(s=i,l=r.clientX,u=r.clientY,d=Date.now())},b=t=>{let r=s;if(!r||t.touches.length!==1)return;let i=t.touches[0],d=i.clientX-l,v=i.clientY-u;if(c===`none`){let t=fS(d,v);if(t===`none`)return;if(t===`vertical`){s=null;return}c=`horizontal`,p=n===r,m=uS(window.innerWidth),h=m*lS;let i=e.querySelector(a?a(r):`.panel-drawer.drawer-${r}`);if(!i){s=null;return}g=i,_=o===null?null:e.querySelector(o??`.drawer-backdrop`),i.classList.add(`drawer-dragging`)}let y=g;if(!y)return;f=pS(r,d);let b=mS(h,f);y.style.transform=`translateX(${r===`left`?b:-b}px)`,_&&(_.style.opacity=String(hS(h,f,p))),t.preventDefault()},x=()=>{let e=s,t=c===`horizontal`&&e!==null&&g!==null,i=f,a=Date.now()-d,o=t?gS({wasOpen:p,pull:i,width:m,durationMs:a}):!1;v(),t&&e&&o!==(n===e)&&(yS(),r(o?e:null))},S=()=>v();return e.addEventListener(`touchstart`,y,{passive:!0}),e.addEventListener(`touchmove`,b,{passive:!1}),e.addEventListener(`touchend`,x),e.addEventListener(`touchcancel`,S),()=>{v(),e.removeEventListener(`touchstart`,y),e.removeEventListener(`touchmove`,b),e.removeEventListener(`touchend`,x),e.removeEventListener(`touchcancel`,S)}},[t,n,r,i,a,o])}var xS={revision:0},SS=new Set;function CS(e){xS={...e,revision:xS.revision+1};for(let e of SS)e()}function wS(){return(0,Q.useSyncExternalStore)(e=>(SS.add(e),()=>{SS.delete(e)}),()=>xS)}var TS={zh:[`继续`,`总结一下`,`详细解释一下`,`检查并修复问题`,`补充测试覆盖`,`发布上传`],en:[`Continue`,`Summarize`,`Explain in detail`,`Check and fix issues`,`Add test coverage`,`Publish release`],it:[`Continua`,`Riassumi`,`Spiega in dettaglio`,`Verifica e correggi i problemi`,`Aggiungi copertura dei test`,`Pubblica la release`],ja:[`続ける`,`要約して`,`詳しく説明して`,`問題を確認して修正`,`テストカバレッジを追加`,`公開・リリース`],ko:[`계속`,`요약해줘`,`자세히 설명해줘`,`문제를 확인하고 수정`,`테스트 커버리지 추가`,`게시/릴리스`],fr:[`Continuer`,`Résumer`,`Expliquer en détail`,`Vérifier et corriger les problèmes`,`Ajouter des tests`,`Publier`],de:[`Weiter`,`Zusammenfassen`,`Ausführlich erklären`,`Probleme prüfen und beheben`,`Testabdeckung ergänzen`,`Veröffentlichen`],es:[`Continuar`,`Resumir`,`Explicar en detalle`,`Revisar y corregir problemas`,`Añadir cobertura de pruebas`,`Publicar`],ru:[`Продолжить`,`Подведи итог`,`Объясни подробно`,`Проверь и исправь проблемы`,`Добавь покрытие тестами`,`Опубликовать`],pt:[`Continuar`,`Resumir`,`Explique em detalhes`,`Verifique e corrija os problemas`,`Adicione cobertura de testes`,`Publique a release`]},ES=`pi-web-sounds`,DS={enabled:!0,question:!0,done:!0,subagentDone:!0,start:!1,error:!0,approval:!0,volume:100};function OS(){try{let e=localStorage.getItem(ES);if(!e)return{...DS};let t=JSON.parse(e),n={...DS,...t};t.subagentDone===void 0&&typeof t.done==`boolean`&&(n.subagentDone=t.done);for(let e of[`enabled`,`question`,`done`,`subagentDone`,`start`,`error`,`approval`])typeof n[e]!=`boolean`&&(n[e]=DS[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?DS.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...DS}}}function kS(e){try{localStorage.setItem(ES,JSON.stringify(e))}catch{}}var AS=null;function jS(){try{if(!AS){let e=window.AudioContext??window.webkitAudioContext;if(!e)return null;AS=new e}return AS.state===`suspended`&&AS.resume(),AS}catch{return null}}var MS=[{type:`sine`,freq:587.33,start:0,dur:.13,peak:.5},{type:`sine`,freq:880,start:.11,dur:.24,peak:.5}],NS=[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],PS={question:MS,done:NS,subagentDone:NS,start:[{type:`triangle`,freq:660,start:0,dur:.08,peak:.22}],error:[{type:`square`,freq:220,start:0,dur:.16,peak:.18},{type:`square`,freq:174.61,start:.18,dur:.26,peak:.18}],approval:[{type:`sine`,freq:659.25,start:0,dur:.11,peak:.45},{type:`sine`,freq:659.25,start:.14,dur:.11,peak:.45},{type:`sine`,freq:880,start:.28,dur:.26,peak:.5}]};function FS(e,t,n){let r=e.createOscillator(),i=e.createGain();r.type=t.type,r.frequency.value=t.freq;let a=e.currentTime+t.start,o=Math.max(1e-4,t.peak*n);i.gain.setValueAtTime(1e-4,a),i.gain.exponentialRampToValueAtTime(o,a+.012),i.gain.exponentialRampToValueAtTime(1e-4,a+t.dur),r.connect(i),i.connect(e.destination),r.start(a),r.stop(a+t.dur+.05)}function IS(e,t=OS()){if(!t.enabled||!t[e])return;let n=jS();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));for(let t of PS[e])FS(n,t,r)}var LS=[`question`,`done`,`subagentDone`,`start`,`error`,`approval`];function RS(e,t,n){if(!t.enabled)return!1;let r=t.events?.[e];return r===`on`||r!==`off`&&n[e]}var zS=`pi-web-notify`,BS={enabled:!1};function VS(){try{let e=localStorage.getItem(zS);if(!e)return{...BS};let t=JSON.parse(e),n={};for(let e of LS){let r=t.events?.[e];(r===`follow`||r===`on`||r===`off`)&&(n[e]=r)}return{enabled:typeof t.enabled==`boolean`?t.enabled:BS.enabled,events:n}}catch{return{...BS}}}function HS(e){try{localStorage.setItem(zS,JSON.stringify(e))}catch{}}function US(){return typeof window<`u`&&`Notification`in window}function WS(){return US()?null:typeof window<`u`&&window.isSecureContext===!1?`insecure`:`unsupported`}function GS(e){let{screenX:t,screenY:n,outerWidth:r,outerHeight:i}=e;return Number.isFinite(t)&&KS(t)||Number.isFinite(n)&&KS(n)?!0:r>0&&r<=400&&i>0&&i<=40}function KS(e){return e<=-1e4}function qS(e){return!(e.visibility!==`visible`||e.minimized||!e.hasFocus||e.windows&&e.idleMs>12e4)}var JS=Date.now(),YS=!1;function XS(){JS=Date.now()}function ZS(){return Math.max(0,Date.now()-JS)}function QS(){if(YS||typeof window>`u`)return;YS=!0;let e={passive:!0,capture:!0};for(let t of[`pointerdown`,`pointermove`,`keydown`,`wheel`,`touchstart`,`focus`,`scroll`])window.addEventListener(t,XS,e);typeof document<`u`&&document.addEventListener(`visibilitychange`,XS,e)}function $S(){return typeof navigator>`u`?!1:/windows/i.test(navigator.userAgent??``)}function eC(){return QS(),typeof window>`u`||typeof document>`u`?{hasFocus:!0,visibility:`visible`,minimized:!1,idleMs:0,windows:!1}:{hasFocus:typeof document.hasFocus!=`function`||document.hasFocus(),visibility:document.visibilityState??``,minimized:GS({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:ZS(),windows:$S()}}function tC(){return US()?Notification.permission:`denied`}async function nC(){if(!US())return`denied`;try{return await Notification.requestPermission()}catch{return`denied`}}function rC(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function iC(e,t=!1){return{body:e,requireInteraction:t,icon:q(`/icons/icon-192.png`),badge:q(`/icons/icon-192.png`),data:{url:typeof location<`u`?location.href:q(`/`)}}}async function aC(e,t,n=!1){if(!US())return{path:`none`,error:`unsupported`};if(Notification.permission!==`granted`)return{path:`none`,error:`permission: ${Notification.permission}`};let r=iC(t,n),i;try{let t=await navigator.serviceWorker?.getRegistration();if(t?.active&&typeof t.showNotification==`function`)return await t.showNotification(e,r),{path:`sw`};i=t?`service worker not active`:`no service worker registration`}catch(e){i=rC(e)}try{return new Notification(e,r),{path:`page`,error:i}}catch(e){return{path:`none`,error:`${i}; page: ${rC(e)}`}}}async function oC(e,t,n=`done`){US()&&(qS(eC())||RS(n,VS(),OS())&&await aC(e,t))}var sC=`pi-web-ui:wide-chat`,cC={wide:!1};function lC(e){if(!e||typeof e!=`object`)return{...cC};let t=e;return{wide:typeof t.wide==`boolean`?t.wide:cC.wide}}function uC(){try{let e=localStorage.getItem(sC);return e?lC(JSON.parse(e)):{...cC}}catch{return{...cC}}}function dC(e){let t=lC(e);try{localStorage.setItem(sC,JSON.stringify(t))}catch{}fC=t;for(let e of pC)e()}var fC=null,pC=new Set;function mC(e){return pC.add(e),()=>{pC.delete(e)}}function hC(){return fC||=uC(),fC.wide}function gC(){return(0,Q.useSyncExternalStore)(mC,hC)}var _C=`pi-web-ui:hide-model-row`,vC={hide:!1};function yC(e){if(!e||typeof e!=`object`)return{...vC};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:vC.hide}}function bC(){try{let e=localStorage.getItem(_C);return e?yC(JSON.parse(e)):{...vC}}catch{return{...vC}}}function xC(e){let t=yC(e);try{localStorage.setItem(_C,JSON.stringify(t))}catch{}SC=t;for(let e of CC)e()}var SC=null,CC=new Set;function wC(e){return CC.add(e),()=>{CC.delete(e)}}function TC(){return SC||=bC(),SC.hide}function EC(){return(0,Q.useSyncExternalStore)(wC,TC)}var DC=`pi-web-ui:project-title`,OC={projectName:!0};function kC(e){if(!e||typeof e!=`object`)return{...OC};let t=e;return{projectName:typeof t.projectName==`boolean`?t.projectName:OC.projectName}}function AC(e){return e?e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``:``}function jC(){try{let e=localStorage.getItem(DC);return e?kC(JSON.parse(e)):{...OC}}catch{return{...OC}}}function MC(e){let t=kC(e);try{localStorage.setItem(DC,JSON.stringify(t))}catch{}NC=t;for(let e of PC)e()}var NC=null,PC=new Set;function FC(e){return PC.add(e),()=>{PC.delete(e)}}function IC(){return NC||=jC(),NC.projectName}function LC(){return(0,Q.useSyncExternalStore)(FC,IC)}var RC=`pi-web-ui:favicon-settings`,zC=[{id:`violet`,hex:`#8b5cf6`,nameKey:`colorViolet`},{id:`blue`,hex:`#3b82f6`,nameKey:`colorBlue`},{id:`cyan`,hex:`#06b6d4`,nameKey:`colorCyan`},{id:`emerald`,hex:`#10b981`,nameKey:`colorEmerald`},{id:`amber`,hex:`#f59e0b`,nameKey:`colorAmber`},{id:`rose`,hex:`#ef4444`,nameKey:`colorRose`},{id:`pink`,hex:`#ec4899`,nameKey:`colorPink`},{id:`indigo`,hex:`#6366f1`,nameKey:`colorIndigo`},{id:`slate`,hex:`#64748b`,nameKey:`colorSlate`}],BC=`#8b5cf6`,VC={color:`default`,customHex:``,instanceName:``};function HC(e){if(!e)return null;let t=e.trim(),n=/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`.toLowerCase():`#${r.toLowerCase()}`}function UC(e){if(!e||typeof e!=`object`)return{...VC};let t=e;return{color:typeof t.color==`string`&&t.color.trim()?t.color.trim():VC.color,customHex:typeof t.customHex==`string`?t.customHex.trim():``,instanceName:typeof t.instanceName==`string`?t.instanceName.trim():``}}function WC(e,t=zC){if(!e||t.length===0)return BC;let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t[Math.abs(n)%t.length].hex}function GC(e){let t=e.replace(`#`,``).trim();if(t.length!==3&&t.length!==6)return!1;let n=0,r=0,i=0;return t.length===3?(n=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),i=parseInt(t[2]+t[2],16)):(n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16)),Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?!1:.2126*n+.7152*r+.0722*i>180}function KC(e){let t=GC(e)?`#1e1e2e`:`#ffffff`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${e}"/><rect x="14" y="17" width="36" height="6.5" rx="3.25" fill="${t}"/><rect x="17.5" y="23.5" width="6.5" height="25" rx="3.25" fill="${t}"/><rect x="40" y="23.5" width="6.5" height="25" rx="3.25" fill="${t}"/></svg>`}var qC={};function JC(e){qC={...qC,...e},ew();for(let e of rw)e()}async function YC(){if(typeof window<`u`&&typeof fetch<`u`)try{let e=await fetch(q(`/api/health`));if(!e.ok)return;let t=await e.json();t&&(t.instanceName||t.faviconColor)&&JC({instanceName:t.instanceName,faviconColor:t.faviconColor})}catch{}}function XC(e,t=typeof window<`u`?window.location.host:``,n=qC.faviconColor){if(e.color===`custom`&&e.customHex){let t=HC(e.customHex);if(t)return t}if(e.color===`auto`)return WC(t||`localhost`);let r=zC.find(t=>t.id===e.color);if(r)return r.hex;let i=HC(e.color);if(i)return i;if(e.color==="default"&&n){let e=zC.find(e=>e.id===n.toLowerCase());if(e)return e.hex;let t=HC(n);if(t)return t}return BC}function ZC(e,t=qC.instanceName){return e.instanceName&&e.instanceName.trim()?e.instanceName.trim():t&&t.trim()?t.trim():``}function QC(e){if(typeof document>`u`)return;let t=document.querySelector(`link[rel~='icon']`);t||(t=document.createElement(`link`),t.rel=`icon`,document.head.appendChild(t)),t.type=`image/svg+xml`;let n=KC(e);t.href=`data:image/svg+xml;utf8,${encodeURIComponent(n)}`}function $C(){try{let e=localStorage.getItem(RC);return e?UC(JSON.parse(e)):{...VC}}catch{return{...VC}}}function ew(){QC(XC(nw??$C(),typeof window<`u`?window.location.host:``))}function tw(e){let t=UC(e);try{localStorage.setItem(RC,JSON.stringify(t))}catch{}nw=t,ew();for(let e of rw)e()}var nw=null,rw=new Set;function iw(e){return rw.add(e),()=>{rw.delete(e)}}function aw(){return nw||=$C(),nw}function ow(){return(0,Q.useSyncExternalStore)(iw,aw)}function sw(e,t,n,r,i,a=!1){let o=new Map;for(let e of r)o.set(e.id,!!e.isStreaming||!!e.completionPending);if(t&&o.set(t,n||a),e===null)return{startCue:!1,finishedConvs:[],nextMap:o};let s=!1;t&&(i===void 0||i===t)&&e.get(t)===!1&&n===!0&&(s=!0);let c=[];for(let[n,i]of e.entries())if(i&&o.has(n)&&!o.get(n)){let e=r.find(e=>e.id===n);c.push({id:n,title:e?.title,isActive:n===t,isSubagent:!!e?.isSubagent})}return{startCue:s,finishedConvs:c,nextMap:o}}var cw=`pi-web-ui:wallpaper`,lw=`has-wallpaper`,uw={url:``,dim:78,blur:0},dw=2e3,fw=28e5;function pw(e){if(typeof e!=`string`)return``;let t=e.trim();if(!t)return``;let n=t.toLowerCase().startsWith(`data:image/`)?fw:dw;return t.length>n?``:/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)?t:``}var mw=(e,t,n,r)=>typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function hw(e){if(!e||typeof e!=`object`)return{...uw};let t=e;return{url:pw(t.url),dim:mw(t.dim,0,95,uw.dim),blur:mw(t.blur,0,24,uw.blur)}}function gw(){try{let e=localStorage.getItem(cw);return e?hw(JSON.parse(e)):{...uw}}catch{return{...uw}}}function _w(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\r\n]/g,``)}async function vw(e){let t=await ef(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function yw(){let e=xw??gw(),t=document.documentElement;e.url?(t.style.setProperty(`--bg-image`,`url("${_w(e.url)}")`),t.style.setProperty(`--bg-image-dim`,String(e.dim/100)),t.style.setProperty(`--bg-image-blur`,`${e.blur}px`)):(t.style.removeProperty(`--bg-image`),t.style.removeProperty(`--bg-image-dim`),t.style.removeProperty(`--bg-image-blur`));let n=getComputedStyle(t).getPropertyValue(`--bg-image`).trim();document.body.classList.toggle(lw,e.url!==``||n!==``&&n!==`none`)}function bw(e){let t=hw(e);xw=t;try{localStorage.setItem(cw,JSON.stringify(t))}catch{}for(let e of Sw)e();yw()}var xw=null,Sw=new Set;function Cw(e){return Sw.add(e),()=>{Sw.delete(e)}}function ww(){return xw||=gw(),xw}function Tw(){return(0,Q.useSyncExternalStore)(Cw,ww)}function Ew(){let e=Tw();(0,Q.useEffect)(()=>{yw()},[e]),(0,Q.useEffect)(()=>{let e=()=>yw();return window.addEventListener(xt,e),yw(),()=>window.removeEventListener(xt,e)},[])}var Dw=(0,Q.lazy)(()=>Os(()=>import(`./TerminalPanel-CLkJJvxg.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([6,1,7,3,8,9,10,11,12]),import.meta.url)),Ow=(0,Q.lazy)(()=>Os(()=>import(`./SCMPanel-sVZcV7dR.js`).then(e=>({default:e.ScmPanel})),__vite__mapDeps([13,1,7,3,8,10]),import.meta.url)),kw=(0,Q.lazy)(()=>Os(()=>import(`./DeviceCenter-BQdDcO8A.js`).then(e=>({default:e.DeviceCenter})),__vite__mapDeps([14,1,7,3,15,16]),import.meta.url)),Aw=(0,Q.lazy)(()=>Os(()=>import(`./DeviceGroups-D2rogxEN.js`).then(e=>({default:e.DeviceGroupCreateDialog})),__vite__mapDeps([15,1,7,3,16]),import.meta.url)),jw=(0,Q.lazy)(()=>Os(()=>import(`./CanvasStudio-Csv1Sj1-.js`).then(e=>({default:e.CanvasStudio})),__vite__mapDeps([17,1,7,3,8,18,19,9,10,20]),import.meta.url)),Mw=(0,Q.lazy)(()=>Os(()=>import(`./PiSetupModal-DHbqfx8T.js`).then(e=>({default:e.PiSetupModal})),__vite__mapDeps([21,1,7,3,19,9,10,22]),import.meta.url)),Nw=(0,Q.lazy)(()=>Os(()=>import(`./ModelConfigModal-DDZccDYt.js`).then(e=>({default:e.ModelConfigModal})),__vite__mapDeps([23,1,7,3,10,22]),import.meta.url)),Pw=(0,Q.lazy)(()=>Os(()=>import(`./SettingsModal-Xw1Yoi3_.js`).then(e=>({default:e.SettingsModal})),__vite__mapDeps([24,1,7,3,16,8,18,19,9,10]),import.meta.url)),Fw=(0,Q.lazy)(()=>Os(()=>import(`./BgTasksModal-BIlQ89vr.js`).then(e=>({default:e.BgTasksModal})),__vite__mapDeps([25,1,7,3,10]),import.meta.url)),Iw=(0,Q.lazy)(()=>Os(()=>import(`./TuiOverlayModal-4-fFAZe7.js`).then(e=>({default:e.TuiOverlayModal})),__vite__mapDeps([26,1,7,3,9,10,11,12]),import.meta.url)),Lw=(0,Q.lazy)(()=>Os(()=>import(`./GlobalSearchModal-BXEGvUZq.js`).then(e=>({default:e.GlobalSearchModal})),__vite__mapDeps([27,1,7,3,18,8,19,9,10]),import.meta.url)),Rw=(0,Q.lazy)(()=>Os(()=>import(`./FilePreview-B9xoU6ON.js`).then(e=>({default:e.FilePreview})),__vite__mapDeps([28,1,7,3,10]),import.meta.url)),zw=(0,Q.lazy)(()=>Os(()=>import(`./GroupConversation-CyIpQzDd.js`).then(e=>({default:e.GroupConversation})),__vite__mapDeps([29,1,7,3,8]),import.meta.url));function Bw({notice:e,onDismiss:t}){let n=V(),{locale:r}=Ue(),i=!H(r)&&e.textEn?e.textEn:e.text,[a,o]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(a)return;let n=setTimeout(()=>t(e.id),Ym(e.level));return()=>clearTimeout(n)},[a,e.id,e.level,t]);let s=e.level===`error`?je:e.level===`warning`?He:We;return(0,$.jsxs)(`div`,{className:`notice notice-${e.level}${a?` paused`:``}`,role:`status`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:()=>{window.getSelection?.()?.toString()||t(e.id)},children:[(0,$.jsx)(s,{className:`notice-icon`}),(0,$.jsx)(`span`,{className:`notice-text`,children:i}),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:n(`close`),onClick:n=>{n.stopPropagation(),t(e.id)},children:(0,$.jsx)(R,{})})]})}var Vw=[],Hw=180,Uw=520,Ww=240,Gw=e=>`pi-web-ui:${e}-panel-width`;function Kw(e){try{let t=Number(localStorage.getItem(Gw(e)));return Number.isFinite(t)&&t>=Hw&&t<=Uw?t:Ww}catch{return Ww}}var qw=e=>`pi-web-ui:${e}-panel-collapsed`;function Jw(e){try{return localStorage.getItem(qw(e))===`1`}catch{return!1}}function Yw({side:e,width:t,onResize:n}){let r=V(),i=(0,Q.useCallback)(r=>{r.preventDefault();let i=r.clientX,a=t,o=a,s=t=>{let r=e===`left`?t.clientX-i:i-t.clientX;o=Math.min(Uw,Math.max(Hw,Math.round(a+r))),n(o)},c=()=>{window.removeEventListener(`pointermove`,s),window.removeEventListener(`pointerup`,c),document.body.classList.remove(`panel-resizing`);try{localStorage.setItem(Gw(e),String(o))}catch{}};window.addEventListener(`pointermove`,s),window.addEventListener(`pointerup`,c),document.body.classList.add(`panel-resizing`)},[e,t,n]);return(0,$.jsx)(`div`,{className:`resize-handle resize-${e}`,title:r(`dragToResize`),onPointerDown:i,onDoubleClick:()=>n(Ww)})}function Xw({side:e,onClick:t}){let n=V();return(0,$.jsx)(`button`,{type:`button`,className:`panel-rail panel-rail-${e}`,title:n(`expandPanel`),onClick:t,children:e===`left`?(0,$.jsx)(P,{}):(0,$.jsx)(it,{})})}var Zw=`pi-web-ui:plugin-path-grants`,Qw=e=>e?`${Zw}:${e}`:Zw;function $w(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function eT(e){try{let t=Qw(e);if(localStorage.getItem(t)!==null)return $w(localStorage.getItem(t));if(!e)return[];let n=$w(localStorage.getItem(Zw));return localStorage.setItem(t,JSON.stringify(n)),n}catch{return[]}}function tT(e,t){try{let n=[...new Set([...eT(t),e])];localStorage.setItem(Qw(t),JSON.stringify(n))}catch{}}function nT(){let e=V(),{locale:t}=Ue(),{chat:n,send:r,dismissNotice:i,pushNotice:a,terminal:o}=Ph(),s=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{n.ready&&n.settings&&(s.current||n.settings.quickPhrasesSeeded||(s.current=!0,n.settings.quickPhrases.length===0&&r({type:`set_settings`,quickPhrases:TS[t]??TS.en,quickPhrasesSeeded:!0})))},[n.ready,n.settings,r,t]);let c=n.state?.cwd??``,l=LC(),u=ZC(ow());(0,Q.useEffect)(()=>{YC()},[]),(0,Q.useEffect)(()=>{let t=l?AC(c):``,n=t?`${t} — pi-web-ui`:e(`docTitle`);document.title=u?`[${u}] ${n}`:n},[c,l,u,e]);let[d,f]=(0,Q.useState)([]);(0,Q.useEffect)(()=>(Mt(e=>f(t=>Rv(t,e))),()=>Mt(null)),[]);let[p,h]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{y.current=p!==null,b.current=_},[p,_]);let x=(0,Q.useCallback)((e,t)=>{let n=Cx(t);if(n){h(null),v({file:{path:e,name:t},plugin:n.plugin,declaration:n.declaration});return}v(null),h({path:e,name:t})},[]);(0,Q.useEffect)(()=>(Uc({open:e=>x(e.path,e.name),isOpen:()=>y.current||b.current!==null}),()=>Uc(null)),[x]);let[S,C]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=()=>C(!1);return window.addEventListener(`drop`,e,!0),()=>window.removeEventListener(`drop`,e,!0)},[]);let[w,T]=(0,Q.useState)(()=>new URLSearchParams(window.location.search).get(`view`)===`devices`?`devices`:`chat`),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(t&&typeof t==`object`){if(t.create===!0){k(!0);return}CS({roomId:typeof t.roomId==`string`?t.roomId:void 0,create:t.create===!0,manage:t.manage===!0}),typeof t.roomId==`string`&&!t.manage&&!t.create?(D(t.roomId),T(`chat`)):(D(null),T(`devices`))}};return window.addEventListener(`pi-web-ui:device-group-open`,e),()=>window.removeEventListener(`pi-web-ui:device-group-open`,e)},[]);let A=(e=>!n.tabs||e===`chat`||e===`devices`||n.tabs.includes(e))(w.startsWith(`plugin:`)?`plugins`:w)?w:`chat`,j=(0,Q.useMemo)(()=>n.plugins.filter(e=>!n.settings?.disabledPlugins?.includes(e.id)),[n.plugins,n.settings?.disabledPlugins]),[M,N]=(0,Q.useMemo)(()=>{let r=[];return[xi(ui(n.plugins),{locale:t,t:t=>e(t),disabledPlugins:n.settings?.disabledPlugins??[],layout:n.settings?.uiLayout,diagnostics:r}),r]},[n.plugins,n.settings?.disabledPlugins,n.settings?.uiLayout,t,e]),P=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let e=N.map(e=>`${e.level}:${e.pluginId??``}:${e.entryId??``}:${e.message}`).join(`
|
|
83
|
-
`);if(e!==P.current){P.current=e;for(let e of N){let t=`[ui-slot] ${e.pluginId?`[${e.pluginId}] `:``}`;e.level===`error`?console.error(`${t}${e.message}`):e.level===`warn`?console.warn(`${t}${e.message}`):console.debug(`${t}${e.message}`)}}},[N]);let ee=(0,Q.useMemo)(()=>M[`topbar.primary`].filter(e=>!e.hidden),[M]),F=(0,Q.useMemo)(()=>[...M[`topbar.primary`].filter(e=>e.hidden),...M[`topbar.overflow`]],[M]),re=(0,Q.useMemo)(()=>M[`leftpanel.sessions`].filter(e=>!e.hidden),[M]),I=(0,Q.useMemo)(()=>M[`leftpanel.projects.actions`].filter(e=>!e.hidden),[M]),L=(0,Q.useMemo)(()=>M[`leftpanel.project`].filter(e=>!e.hidden),[M]),ie=(0,Q.useMemo)(()=>M[`leftpanel.running.actions`].filter(e=>!e.hidden),[M]),ae=(0,Q.useMemo)(()=>M[`leftpanel.history.actions`].filter(e=>!e.hidden),[M]),oe=M[`leftpanel.sections`],se=(0,Q.useMemo)(()=>M[`leftpanel.running`].filter(e=>!e.hidden),[M]),ce=(0,Q.useMemo)(()=>M[`leftpanel.history`].filter(e=>!e.hidden),[M]),le=(0,Q.useMemo)(()=>M[`terminal.toolbar`].filter(e=>!e.hidden),[M]),ue=(0,Q.useMemo)(()=>M[`scm.toolbar`].filter(e=>!e.hidden),[M]),de=(0,Q.useMemo)(()=>M[`goalbar.actions`].filter(e=>!e.hidden),[M]),B=(0,Q.useMemo)(()=>M[`chat.header`].filter(e=>!e.hidden),[M]),fe=(0,Q.useMemo)(()=>M[`chat.empty`].filter(e=>!e.hidden),[M]),pe=(0,Q.useMemo)(()=>M[`file.preview.toolbar`].filter(e=>!e.hidden),[M]),me=(0,Q.useMemo)(()=>Object.fromEntries((n.dshPresets?.presets??[]).map(n=>[n.id,Jy(n,t,e).name])),[n.dshPresets,t]),he=(0,Q.useMemo)(()=>M[`notice.actions`].filter(e=>!e.hidden),[M]),ge=(0,Q.useMemo)(()=>M[`sidebar.left`]??[],[M]),U=(0,Q.useMemo)(()=>M[`sidebar.right`]??[],[M]),W=(0,Q.useCallback)((t,n,i)=>{if(t.id===`host:msg-fork`){i?.id&&r({type:`fork_session`,messageId:i.id,position:`before`});return}if(t.id===`host:msg-rollback`){i?.id&&kx({messageId:i.id});return}let o=(t.action??``).trim();if(t.kind===`view`||(!o||o===`view`)&&t.source!==`host`){T(t.view??`plugin:${t.source.startsWith(`plugin:`)?t.source.slice(7):``}`);return}if(!o)return;let s=t.source.startsWith(`plugin:`)?t.source.slice(7):``;Rt(s,o,t.id,{...n===void 0?{}:{value:n},...i===void 0?{}:{target:i},loadBundle:async e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Nm(t,De.current.pluginsEpoch):!1}}).then(t=>{t||a(`info`,e(`pluginUiNoHandler`))})},[e,a]),G=(0,Q.useCallback)(e=>{let t=n.plugins.find(t=>t.id===e.source.slice(7));return t?(0,$.jsx)(cg,{plugin:t,epoch:n.pluginsEpoch,send:r,className:`lp-plugin-page`}):null},[n.plugins,n.pluginsEpoch,r]),_e=(0,Q.useCallback)((t,n)=>{n.action&&Rt(t.pluginId,n.action,n.id,{target:{id:n.id,kind:`plugin-running`,label:n.title},loadBundle:async e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Nm(t,De.current.pluginsEpoch):!1}}).then(t=>{t||a(`info`,e(`pluginUiNoHandler`))})},[e,a]),[K,J]=(0,Q.useState)([]);(0,Q.useEffect)(()=>Em(J),[]);let[ve,Y]=(0,Q.useState)([]);(0,Q.useEffect)(()=>wm(Y),[]);let[ye,be]=(0,Q.useState)(null),[xe,Se]=(0,Q.useState)(null),[Ce,we]=(0,Q.useState)(null),Te=ye?M[`modal.dialog`].find(e=>e.id===ye&&!e.hidden):void 0,Ee=(0,Q.useMemo)(()=>{if(!Te||Te.kind!==`view`)return``;let e=Te.view??``;return e.startsWith(`plugin:`)?e.slice(7):Te.source.startsWith(`plugin:`)?Te.source.slice(7):``},[Te]);(0,Q.useEffect)(()=>{if(!Te||!Ee||K.some(e=>e.info.id===Ee))return;let e=De.current.plugins.find(e=>e.id===Ee);e&&Nm(e,De.current.pluginsEpoch)},[Te,Ee,K,n.pluginsEpoch]),(0,Q.useEffect)(()=>{bc(r),xc(j,n.pluginsEpoch),Oc(j,n.pluginsEpoch),Sx(j,n.pluginsEpoch),Pm(j,n.pluginsEpoch)},[j,n.pluginsEpoch,r]);let De=(0,Q.useRef)(n);De.current=n;let X=(0,Q.useRef)(T);X.current=T;let Oe=(0,Q.useRef)(M);Oe.current=M,(0,Q.useEffect)(()=>(Vt(Kt({send:r,isReady:()=>!!De.current.state,setView:e=>X.current(e),getCwd:()=>De.current.state?.cwd??``,getWorkspaceRoots:()=>De.current.state?.workspaceRoots??[],listSessions:()=>{let e=De.current,t=e.state?.cwd??``;return[...e.conversations.map(e=>({id:e.id,title:e.title,cwd:e.cwd||t,kind:`running`,isStreaming:e.isStreaming})),...(e.elsewhere??[]).filter(e=>!!(e.convId&&e.owner)).map(e=>({id:e.convId,title:e.title,cwd:e.cwd||t,kind:`elsewhere`,owner:e.owner,isStreaming:e.isStreaming})),...e.sessions.map(e=>({id:e.path,title:e.displayName||e.name||e.firstMessage?.trim()||e.path,cwd:t,kind:`history`}))]},getConversationId:()=>De.current.state?.conversationId??null,isConversationBlank:()=>(De.current.state?.messages.length??0)===0,listModels:()=>De.current.models.map(e=>({id:e.id,provider:e.provider,name:e.name,vision:e.vision,reasoning:e.reasoning})),getCurrentModelId:()=>{let e=De.current.state?.model;return e?`${e.provider}/${e.id}`:null},listProjects:()=>De.current.projects.map(e=>e.path),grantedPaths:eT,grantPath:tT,confirm:e=>new Promise(t=>{if(st.current){t(!1);return}let n={path:e.path,resolve:t};st.current=n,ot(n)}),openModal:e=>{let t=String(e??``).trim();if(!t)return!1;let n=Oe.current[`modal.dialog`].find(e=>e.id===t);return!n||n.hidden?!1:(be(t),!0)},closeModal:()=>be(null),pickDirectory:e=>new Promise(t=>{Se({initialPath:e?.initialPath,resolve:t})}),pickModel:e=>new Promise(t=>{we({currentModelId:e?.currentModelId,resolve:t})}),dialogConfirm:e=>new Promise(t=>{if(ut.current){t(!1);return}let n={kind:`confirm`,title:e.title,resolve:t};ut.current=n,lt(n)}),select:e=>new Promise(t=>{if(ut.current){t({ok:!1,error:`busy`});return}let n={kind:`select`,title:e.title,options:e.options,...e.multi?{multi:!0}:{},resolve:t};ut.current=n,ft([]),lt(n)}),input:e=>new Promise(t=>{if(ut.current){t({ok:!1,error:`busy`});return}let n={kind:`input`,title:e.title,...typeof e.placeholder==`string`?{placeholder:e.placeholder}:{},...typeof e.initial==`string`?{initial:e.initial}:{},resolve:t};ut.current=n,gt(e.initial??``),lt(n)}),notifyAction:e=>new Promise(t=>{try{let n=bt.current;bt.current=null,yt(null);try{n?.resolve(null)}catch{}let r={text:e.text,actions:e.actions,resolve:t};bt.current=r,yt(r)}catch{t(null)}}),loadPluginBundle:e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Nm(t,De.current.pluginsEpoch):Promise.resolve(!1)},openFileContextMenu:t=>{let n=String(t.path??``).replace(/\\/g,`/`).replace(/^\/+|\/+$/g,``),i=!n,o=t.kind??(t.path.endsWith(`/`)||i?`dir`:`file`),s=t.label??(n?n.split(`/`).pop()??n:`workspace`),c={id:n,kind:o,label:s},l=o===`file`,u=o===`dir`||i,d=o===`list`,f=(Oe.current[`contextmenu.file`]??[]).map(t=>{if(t.source!==`host`)return u&&t.when?.includes(`file.isFile`)||l&&t.when?.includes(`file.isDir`)?{...t,hidden:!0}:t;switch(t.id){case`host:file-compress`:case`host:file-compress-download`:return d?{...t,hidden:!0}:t;case`host:file-extract`:return l&&Qh(s)?t:{...t,hidden:!0};case`host:file-upload`:return u||d?{...t,label:e(`uploadToFolder`)}:{...t,hidden:!0};case`host:file-upload-folder`:return u||d?t:{...t,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:return l?t:{...t,hidden:!0};case`host:file-attach-ref`:return l?t:{...t,hidden:!0};case`host:file-attach-folder`:return u?t:{...t,hidden:!0};case`host:file-reveal`:return d?{...t,hidden:!0}:t;case`host:file-enter`:case`host:file-open-project`:case`host:file-add-root`:return{...t,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:case`host:file-paste`:return u||d?t:{...t,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!d&&!i?t:{...t,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:case`host:file-copy-rel`:return d?{...t,hidden:!0}:t;case`host:file-refresh`:return d?t:{...t,hidden:!0};default:return t}});Pi({x:t.x,y:t.y,slot:`contextmenu.file`,target:c,entries:f,onHostAction:(n,i)=>{if(t.onHostAction){let e=t.onHostAction(n.id,i);if(e!==void 0)return e}switch(n.id){case`host:file-reveal`:r({type:`file_reveal`,path:i.id});break;case`host:file-open-default`:i.kind===`file`&&r({type:`file_open_default`,path:i.id});break;case`host:file-copy-name`:navigator.clipboard?.writeText(i.label??i.id),a(`info`,e(`copied`));break;case`host:file-copy-rel`:navigator.clipboard?.writeText(i.id),a(`info`,e(`copied`));break;case`host:file-copy-path`:{let t=De.current.state?.cwd??``,n=t?`${t.replace(/\\/g,`/`).replace(/\/+$/,``)}/${i.id}`:i.id;navigator.clipboard?.writeText(n),a(`info`,e(`copied`));break}}}})}})),()=>Vt(null)),[r]);let[Ae,je]=(0,Q.useState)(()=>Kw(`left`)),[Me,Ne]=(0,Q.useState)(()=>Kw(`right`)),Pe=(0,Q.useCallback)(e=>je(e),[]),Fe=(0,Q.useCallback)(e=>Ne(e),[]),[Ie,Le]=(0,Q.useState)(()=>Jw(`left`)),[Re,ze]=(0,Q.useState)(()=>Jw(`right`)),Be=(0,Q.useCallback)(()=>{Le(e=>{try{localStorage.setItem(qw(`left`),e?`0`:`1`)}catch{}return!e})},[]),Ve=(0,Q.useCallback)(()=>{ze(e=>{try{localStorage.setItem(qw(`right`),e?`0`:`1`)}catch{}return!e})},[]),[He,We]=(0,Q.useState)(null),Ge=(0,Q.useRef)(null),[Ke,qe]=(0,Q.useState)(()=>window.matchMedia(`(max-width: 768px)`).matches);(0,Q.useEffect)(()=>{let e=window.matchMedia(`(max-width: 768px)`),t=e=>qe(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),bS({enabled:Ke&&A===`chat`,open:He,onOpenChange:We,container:Ge,backdropSelector:`.drawer-backdrop.persistent`});let[Je,Ye]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_web_setup_dismissed`)===`1`}catch{return!1}}),Xe=()=>{Ye(!0);try{localStorage.setItem(`pi_web_setup_dismissed`,`1`)}catch{}},[Ze,Qe]=(0,Q.useState)(!1),[$e,et]=(0,Q.useState)(!1),[tt,nt]=(0,Q.useState)(),[rt,it]=(0,Q.useState)(null),[at,ot]=(0,Q.useState)(null),st=(0,Q.useRef)(null),[ct,lt]=(0,Q.useState)(null),ut=(0,Q.useRef)(null),[dt,ft]=(0,Q.useState)([]),[pt,gt]=(0,Q.useState)(``),[_t,yt]=(0,Q.useState)(null),bt=(0,Q.useRef)(null),[xt,St]=(0,Q.useState)(()=>new Set),Ct=(e,t)=>{r({type:`plugin_path_response`,id:e,ok:t}),St(t=>new Set(t).add(e))},Tt=n.pathRequests.find(e=>!xt.has(e.id))??null,[Ot,kt]=(0,Q.useState)(()=>new Set),At=(e,t,n=!1)=>{r({type:`plugin_permission_response`,id:e,ok:t,...n?{remember:!0}:{}}),kt(t=>new Set(t).add(e))},jt=n.permRequests.find(e=>!Ot.has(e.id))??null,Nt=gC(),Ft=EC(),It=!!n.settings?.minimalNewChat&&(n.state?.messages?.length??0)===0&&!n.state?.streamingMessage,[Lt,Bt]=(0,Q.useState)(!1),[Ht,Wt]=(0,Q.useState)(!1),[qt,Jt]=(0,Q.useState)(!1),[Yt,Zt]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!Yt)return;let e=setTimeout(()=>Zt(null),15e3);return()=>clearTimeout(e)},[Yt]);let[Qt,$t]=(0,Q.useState)(null),tn=(0,Q.useRef)(null),nn=(0,Q.useRef)(null),rn=n.state?.sessionId??``,an=(0,Q.useRef)(rn);an.current=rn;let on=(0,Q.useRef)(n.ready);on.current=n.ready,(0,Q.useEffect)(()=>{let e=()=>{let e=Qo(window.location.hash);if(e){if(e.messageId?$t({sessionId:e.sessionId,messageId:e.messageId}):$t(null),!on.current||!an.current){tn.current=e.sessionId;return}an.current!==e.sessionId&&(nn.current=e.sessionId,T(`chat`),r({type:`switch_session`,path:``,sessionId:e.sessionId}))}};return e(),window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[r]),(0,Q.useEffect)(()=>{let e=nn.current;if(e&&n.notices.some(t=>t.text.includes(e)&&(t.text.includes(`未找到会话`)||t.text.includes(`Session not found`)))&&(nn.current=null,$t(null),rn)){let e=$o({sessionId:rn});window.location.hash!==e&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${e}`)}},[n.notices,rn]),(0,Q.useEffect)(()=>{if(!n.ready||!rn)return;if(tn.current){let e=tn.current;if(tn.current=null,e!==rn){nn.current=e,T(`chat`),r({type:`switch_session`,path:``,sessionId:e});return}}if(nn.current){if(rn===nn.current)nn.current=null;else return}let e=Qo(window.location.hash),t=e?.sessionId===rn?e.messageId:void 0,i=$o({sessionId:rn,...t?{messageId:t}:{}});window.location.hash!==i&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${i}`)},[n.ready,rn,r]),(0,Q.useEffect)(()=>{let t=t=>{let i=t.detail,a=i?.title||e(`pluginCommandFallback`),s=i?.command;if(!s||!n.ready)return;let c={name:a,command:s,cwd:"${pwd}"},l=n.terminals.find(e=>e.title===a);if(l)o.restart(l.id),r({type:`run_command`,terminalId:l.id,conversationId:l.conversationId,command:c,cols:80,rows:24});else{let e=ht();o.create({id:e,conversationId:n.activeConversationId||n.state?.conversationId||``,title:a,cwd:n.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:c})}T(`terminal`)};window.addEventListener(`pi-web-ui:plugin-run-command`,t);let i=e=>{let t=e.detail;typeof t==`string`&&t&&(T(e=>e===`chat`?e:`chat`),r({type:`switch_conversation`,id:t}),Xt())};return window.addEventListener(`pi-web-ui:switch-conversation`,i),()=>{window.removeEventListener(`pi-web-ui:plugin-run-command`,t),window.removeEventListener(`pi-web-ui:switch-conversation`,i)}},[n,o,r]),(0,Q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),Wt(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let[Z,sn]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_zen_mode`)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{Z?localStorage.setItem(`pi_zen_mode`,`1`):localStorage.removeItem(`pi_zen_mode`)}catch{}},[Z]);let cn=(0,Q.useCallback)(()=>{sn(e=>{let t=!e;return t&&A!==`chat`&&T(`chat`),t})},[A]);mt(()=>Z?(sn(!1),!0):!1,Z),(0,Q.useEffect)(()=>{let e=e=>{let t=e.altKey&&!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()===`z`,n=(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`;(t||n)&&(e.preventDefault(),cn())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[cn]);let[ln,un]=(0,Q.useState)(OS),[dn,fn]=(0,Q.useState)(uf),{themes:pn,theme:mn,switchTheme:hn,reloadThemes:gn}=vt();Ew(),(0,Q.useEffect)(()=>{try{typeof zt==`function`&&zt(mn??``)}catch{}},[mn]),(0,Q.useEffect)(()=>{try{typeof Ut==`function`&&Ut(t)}catch{}},[t]),(0,Q.useEffect)(()=>{try{typeof Pt==`function`&&Pt(A)}catch{}},[A]),(0,Q.useEffect)(()=>{try{let e=n.state?.model,t=e?`${e.provider}/${e.id}`:null;typeof Gt==`function`&&Gt(t)}catch{}},[n.state?.model?.provider,n.state?.model?.id]),(0,Q.useEffect)(()=>{if(!ct)return;let e=e=>{if(e.key!==`Escape`)return;let t=ut.current;ut.current=null,lt(null);try{if(!t)return;t.kind===`confirm`?t.resolve(!1):t.resolve({ok:!1})}catch{}};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ct]),(0,Q.useEffect)(()=>{if(!_t)return;let e=setTimeout(()=>{let e=bt.current;bt.current=null,yt(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[_t]);let _n=(0,Q.useRef)(null),vn=(0,Q.useRef)(null),yn=(0,Q.useRef)(n.state?.messages);yn.current=n.state?.messages;let bn=(0,Q.useRef)(new Set),xn=(0,Q.useRef)(new Set),Sn=(0,Q.useRef)(new Set),Cn=(0,Q.useRef)(0),wn=(0,Q.useRef)(!1),Tn=(0,Q.useRef)(n.terminals);(0,Q.useEffect)(()=>{kS(ln)},[ln]),(0,Q.useEffect)(()=>{df(dn)},[dn]),(0,Q.useEffect)(()=>{let e=Tn.current;Tn.current=n.terminals;for(let t of n.terminals){let n=t.command?.command??``;e.find(e=>e.id===t.id)?.running&&!t.running&&(n.startsWith(`pi remove `)?r({type:`extensions_reload`}):n.startsWith(`pi-web-ui install `)||n.startsWith(`pi-web-ui uninstall `)?r({type:`plugins_reload`}):n.startsWith(`npm i -g `)&&(r({type:`extensions_reload`}),r({type:`plugins_reload`}),r({type:`check_updates_all`,force:!0}),r({type:`check_engines`,force:!0})))}},[n.terminals,r]),(0,Q.useEffect)(()=>{let t=n.state?.conversationId??null,r=sw(_n.current,t,n.state?.isStreaming??!1,n.conversations,vn.current,!!n.state?.completionPending||!!n.state?.queue?.steering.length||!!n.state?.queue?.followUp.length);if(_n.current=r.nextMap,vn.current=t,r.startCue&&(IS(`start`,ln),oC(e(`notifyStartTitle`),e(`notifyStartBody`),`start`)),r.finishedConvs.length>0){r.finishedConvs.some(e=>!e.isSubagent&&ln.done)?IS(`done`,ln):r.finishedConvs.some(e=>e.isSubagent)&&IS(`subagentDone`,ln);let t=r.finishedConvs.find(e=>e.isActive);if(t&&(oC(e(`notifyDoneTitle`),e(`notifyDoneBody`),t.isSubagent?`subagentDone`:`done`),dn.enabled)){if(dn.readReplies){if(!dn.streamReplies){let t=gf(yn.current);t?Df(t,dn):dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceDone`),dn)}}else dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceDone`),dn)}for(let t of r.finishedConvs.filter(e=>!e.isActive)){let n=t.title?`${t.title}:${e(`notifyDoneBody`)}`:e(`notifyDoneBody`);oC(e(`notifyDoneTitle`),n,t.isSubagent?`subagentDone`:`done`)}!t&&dn.enabled&&dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceDone`),dn)}},[n.state?.conversationId,n.state?.isStreaming,n.state?.completionPending,n.state?.queue,n.conversations,ln,dn,e]);let En=(0,Q.useRef)(null),Dn=(0,Q.useRef)(null),On=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let e=n.state?.isStreaming??!1,t=n.state?.conversationId;if(!(dn.enabled&&dn.readReplies&&dn.streamReplies)||!e){if(En.current){let e=yn.current,t=Array.isArray(e)&&e.length>0?e[e.length-1]:null;if(t&&t.role===`assistant`&&Dn.current){let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
84
|
-
`);Dn.current.flush(e)}En.current.finish(),En.current=null,Dn.current=null,On.current=0}return}let r=n.state?.messages,i=Array.isArray(r)&&r.length>0?r[r.length-1]:null;if(!i||i.role!==`assistant`)return;let a=Date.now();if(a-On.current<150)return;if(On.current=a,!En.current){let e=
|
|
85
|
-
`);Dn.current?.feed(o)},[n.state?.messages,n.state?.isStreaming,n.state?.conversationId,dn]),(0,Q.useEffect)(()=>{let t=n.dialog?.id??null;if(t!==null&&!bn.current.has(t)){if(bn.current.add(t),bn.current.size>64){let e=bn.current.values().next().value;e!==void 0&&bn.current.delete(e)}IS(`question`,ln),oC(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),dn.enabled&&dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceQuestion`),dn)}},[n.dialog,ln,dn,e]),(0,Q.useEffect)(()=>{let t=n.question?.id??null,r=n.remoteQuestion?`${n.remoteQuestion.owner}:${n.remoteQuestion.id}`:null,i=!1;t!==null&&!xn.current.has(t)&&(xn.current.add(t),i=!0),r!==null&&!xn.current.has(r)&&(xn.current.add(r),i=!0);for(let e of n.conversations){if(!e.hasQuestion)continue;let n=e.questionId?`q:${e.questionId}`:`conv-q:${e.id}`;xn.current.has(n)||(xn.current.add(n),e.questionId&&xn.current.add(e.questionId),t!==e.questionId&&(i=!0))}if(xn.current.size>64){let e=xn.current.values().next().value;e!==void 0&&xn.current.delete(e)}i&&(IS(`question`,ln),oC(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),dn.enabled&&dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceQuestion`),dn))},[n.question,n.remoteQuestion,n.conversations,ln,dn,e]),(0,Q.useEffect)(()=>{let t=n.approval,r=t?.id??null;if(r!==null&&!Sn.current.has(r)){if(Sn.current.add(r),Sn.current.size>64){let e=Sn.current.values().next().value;e!==void 0&&Sn.current.delete(e)}IS(`approval`,ln);let n=typeof t?.toolName==`string`?t.toolName:``;oC(e(`notifyApprovalTitle`),n?e(`notifyApprovalBodyTool`,{tool:n}):e(`notifyApprovalBody`),`approval`),dn.enabled&&dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceApproval`),dn)}},[n.approval,ln,dn,e]),(0,Q.useEffect)(()=>{let t=[...n.notices].reverse().find(e=>e.level===`error`);t&&t.id!==Cn.current&&(Cn.current=t.id,IS(`error`,ln),oC(e(`notifyErrorTitle`),e(`notifyErrorBody`),`error`),dn.enabled&&dn.announce&&!qS(eC())&&Df(e(`ttsAnnounceError`),dn))},[n.notices,ln,dn,e]);let kn=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{let e=n.state?.messages??[];for(let t of e){if(t.toolName!==`live_preview`||kn.current.has(t.id))continue;kn.current.add(t.id);let e=``;for(let n of t.content??[]){if(n.type!==`text`)continue;let t=/🔗 已自动在浏览器打开\]\((\/(?!\/)[^)\s]+)\)/.exec(n.text??``);if(t?.[1]){e=t[1];break}}if(!e)continue;let n=null;try{let t=new URL(q(e),window.location.href);t.origin===window.location.origin&&document.hasFocus()&&(n=window.open(t.href,`_blank`,`noopener`))}catch{n=null}n||a(`info`,e)}},[n.state?.messages,a]);let jn=(e,t,n,r=!1,i,a=!1)=>{let o=`${e}|${n}|${i?`${i.start}-${i.end}`:``}`;f(a=>a.some(e=>`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`===o)?a:[...a,{path:e,name:t,mode:n,isDir:r,...i?{lines:i}:{}}]);let s=n===`page`||n===`canvas`?t:e;!a&&s&&Dt(`@${s} `)},Mn=e=>{let t=``;f(n=>n.filter(n=>{let r=n.key?n.key===e:n.mode===`conversation`?`conv|${n.conversationId??``}|${n.sessionPath??``}`===e:n.path===e;return r&&!t&&(t=n.mode===`page`||n.mode===`conversation`||n.mode===`canvas`?n.name:n.path),!r})),t&&Et(`@${t}`)},Nn=(0,Q.useCallback)(e=>(!e.type.startsWith(`list_`)&&!e.type.startsWith(`get_`)&&We(null),(e.type===`new_chat`||e.type===`switch_conversation`||e.type===`switch_session`)&&(D(null),T(e=>e===`chat`?e:`chat`),Xt()),r(e)),[r]),Pn=(0,Q.useRef)(new Set),Fn=n.activeConversationId||n.state?.conversationId||``;(0,Q.useEffect)(()=>{let t=n.conversations.filter(e=>e.hasQuestion),r=new Set(t.map(e=>e.id)),i=new Set(t.map(e=>e.questionId).filter(Boolean));for(let e of Pn.current)i.has(e)||Pn.current.delete(e);for(let n of t){let t=`question-${n.id}`;if(n.id===Fn){cx(t,{silent:!0});continue}n.questionId&&Pn.current.has(n.questionId)||sx({id:t,type:`question`,title:n.title||e(`chat`),message:n.questionTitle||e(`waitingQuestionBadge`),persistent:!0,dismissible:!0,data:{conversationId:n.id,questionId:n.questionId},onClose:()=>{n.questionId&&Pn.current.add(n.questionId)},onClick:()=>{Nn({type:`switch_conversation`,id:n.id}),cx(t,{silent:!0})}})}lx(e=>{let t=e.data?.conversationId;return t?!r.has(t)||t===Fn:!1},{silent:!0})},[n.conversations,Fn,Nn,e]);let In=en(`chatUploadMaxMb`),[Ln,Rn]=(0,Q.useState)({}),zn=(0,Q.useRef)(0),Bn=(0,Q.useRef)(0),Vn=(0,Q.useRef)(0),Hn=(0,Q.useCallback)(t=>{let r=Date.now();n.state?.model&&!n.state.model.vision&&r-Vn.current>1e4&&(Vn.current=r,a(`warning`,e(`imageNotSupported`)));let i=`paste-${++Bn.current}`;f(e=>[...e,{path:``,key:i,name:t.name,imageData:t.data,mimeType:t.mimeType}])},[n.state?.model,a,e]),Un=(0,Q.useCallback)(async t=>{for(let n of t){if(n.size>In*1024*1024){a(`warning`,e(`fileTooLarge`,{name:n.name,size:In}));continue}let t=String(++zn.current);Rn(e=>({...e,[t]:{name:n.name}}));try{let t=await ef(n);t?Hn(t):a(`error`,e(`imageLoadFailed`,{name:n.name}))}catch{a(`error`,e(`imageLoadFailed`,{name:n.name}))}finally{Rn(e=>{let n={...e};return delete n[t],n})}}},[Hn,a,e,In]),Wn=In*1024*1024,Gn=(0,Q.useRef)(0),Kn=(0,Q.useCallback)(async t=>{if(t.size>Wn){a(`warning`,e(`fileTooLarge`,{name:t.name,size:Wn/1024/1024}));return}let n=String(++zn.current);Rn(e=>({...e,[n]:{name:t.name,percent:0}}));let r;try{r=(await new Promise((e,r)=>{let i=new FileReader;i.onprogress=e=>{e.lengthComputable&&Rn(r=>({...r,[n]:{name:t.name,percent:Math.round(e.loaded/e.total*100)}}))},i.onload=()=>e(i.result),i.onerror=()=>r(i.error??Error(`read failed`)),i.onabort=()=>r(Error(`read aborted`)),i.readAsDataURL(t)})).replace(/^data:[^;]*;base64,/,``)}catch{a(`error`,e(`fileLoadFailed`,{name:t.name}));return}finally{Rn(e=>{let t={...e};return delete t[n],t})}let i=`upload-${++Gn.current}`;f(e=>[...e,{path:``,key:i,name:t.name,fileData:r,size:t.size,mimeType:t.type||void 0}])},[Wn,a,e]),qn=(0,Q.useCallback)(async e=>{for(let t of e)$d(t.type)?await Un([t]):await Kn(t)},[Un,Kn]),Jn=(0,Q.useCallback)((e,t,n)=>{r({type:`edit_message`,messageId:e,text:t,attachments:n})},[r]),Yn=(0,Q.useCallback)((e,t,n,i)=>{r({type:`queue_remove`,kind:e,text:t,index:n,id:i})},[r]),[Xn,Zn]=(0,Q.useState)([]),Qn=(0,Q.useRef)(0),$n=(0,Q.useCallback)((e,t,n,i)=>{r({type:`queue_remove`,kind:e,text:t,index:n,id:i}),Qn.current+=1;let a=hs(t),o={text:a.text,seq:Qn.current};if(a.quotes.length&&f(e=>Rv(e,a.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:ht()})))),a.attachments?.length){let e=a.attachments.filter(e=>e.type!==`vision-bridge`).map(e=>({path:e.path||e.url||``,name:e.name,mode:e.type===`page`?`page`:e.type===`canvas`?`canvas`:e.type===`conversation`?`conversation`:e.lines?`lines`:`reference`,lines:e.lines,key:ht()}));e.length&&f(t=>Rv(t,e))}Zn(e=>[...e.slice(-9),o])},[r]),er=(0,Q.useCallback)(()=>Qe(!0),[]),tr=(0,Q.useCallback)(()=>f([]),[]);_x(n.state?.sessionId??``,tr);let nr=(0,Q.useCallback)(Mn,[]),rr=Un,ir=qn,ar=(0,Q.useCallback)((e,t)=>r({type:`search_files`,reqId:e,query:t}),[r]),or=(0,Q.useCallback)(e=>jn(e.path,e.name,e.mode??`reference`,e.isDir??!1,e.lines,e.silent??!1),[]),sr=n.state?.model,cr=n.state?.thinkingLevel,lr=n.state?.availableThinkingLevels,ur=(0,Q.useMemo)(()=>sr?{model:sr,thinkingLevel:cr??`off`,availableThinkingLevels:lr??[]}:null,[sr,cr,lr]),dr=(0,Q.useCallback)(()=>!n.ready||n.terminals.length!==0?!1:(o.create({id:ht(),conversationId:n.activeConversationId||n.state?.conversationId||``,title:e(`terminalTitle`,{n:1}),cwd:n.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null}),!0),[n.ready,n.state?.cwd,n.terminals.length,e,o]);return(0,Q.useEffect)(()=>{if(wn.current){if(A!==`terminal`||n.terminals.length!==0){wn.current=!1;return}dr()&&(wn.current=!1)}},[n.terminals.length,dr,A]),(0,$.jsxs)(`div`,{className:`app${Z?` zen-mode`:``}`,"data-pi-anchor":`app`,onDragOver:e=>{Array.from(e.dataTransfer?.types??[]).includes(`Files`)&&(e.preventDefault(),C(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||C(!1)},onDrop:t=>{if(C(!1),!Array.from(t.dataTransfer?.types??[]).includes(`Files`))return;t.preventDefault();let n=Array.from(t.dataTransfer?.files??[]);if(n.length===0){a(`warning`,e(`foldersNotSupported`));return}let r=n.filter(e=>$d(e.type)),i=n.filter(e=>!$d(e.type));r.length>0&&Un(r),i.length>0&&qn(i)},children:[Z&&(0,$.jsxs)(`button`,{type:`button`,className:`zen-exit-pill`,onClick:cn,title:e(`zenModeExitTip`),"aria-label":e(`zenModeExit`),children:[(0,$.jsx)(ne,{}),(0,$.jsx)(`span`,{children:e(`zenModeExit`)})]}),S&&(0,$.jsx)(`div`,{className:`app-drop-overlay`,"aria-hidden":!0,children:(0,$.jsxs)(`span`,{children:[`📎 `,e(`dropHereToAttach`)]})}),(0,$.jsx)(oo,{chat:n,terminal:o,view:A,plugins:j,uiPrimary:ee,uiOverflow:F,uiContextTopbar:M[`contextmenu.topbar`],onUiAction:W,zenMode:Z,onToggleZenMode:cn,onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:()=>{nt(void 0),et(!0)},onManagePlugins:()=>{nt(`plugins`),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onOpenIconEdit:()=>Jt(!0),onOpenSandboxModal:()=>it(`create`),themes:pn,theme:mn,onThemeChange:hn,reloadThemes:gn}),qt&&(0,$.jsx)(gx,{slots:M,layout:n.settings?.uiLayout,exclude:ni,onClose:()=>Jt(!1)}),n.protocolMismatch&&(0,$.jsxs)(`div`,{className:`protocol-banner`,children:[`⚠ `,e(`protocolMismatch`)]}),(0,$.jsxs)(`div`,{className:`notices`,children:[n.notices.map(e=>(0,$.jsx)(Bw,{notice:e,onDismiss:i},e.id)),_t&&(0,$.jsxs)(`div`,{className:`notice notice-info`,role:`status`,children:[(0,$.jsx)(`span`,{className:`notice-text`,children:_t.text}),_t.actions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let t=bt.current;bt.current=null,yt(null);try{t?.resolve(e.id)}catch{}},children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:e(`close`),onClick:()=>{let e=bt.current;bt.current=null,yt(null);try{e?.resolve(null)}catch{}},children:(0,$.jsx)(R,{})})]}),he.length>0&&(0,$.jsx)(`div`,{className:`notice-actions`,role:`toolbar`,children:he.map(e=>e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`btn btn-slot notice-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>W(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-slot`,title:e.hint??e.label,onClick:()=>W(e),children:[e.icon?`${e.icon} `:``,e.badge??e.label]},e.id))})]}),(0,$.jsx)(E_,{currentModelId:sr?`${sr.provider}/${sr.id}`:null,children:(0,$.jsxs)(`div`,{ref:Ge,className:`layout`,style:{"--left-w":`${Ae}px`,"--right-w":`${Me}px`},children:[Ke?(0,$.jsx)(`div`,{className:`drawer-backdrop persistent${He?` on`:``}`,onClick:()=>We(null)}):He&&(0,$.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>We(null)}),(0,$.jsx)(Db,{side:`left`,items:ge,chat:n,view:A,plugins:j,dropdownProps:{theme:mn,themes:pn,onThemeChange:hn,reloadThemes:gn},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:e=>{nt(e),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onUiAction:W,uiContextTopbar:M[`contextmenu.topbar`],onThemeToggle:()=>hn(mn===`light`?null:`light`),onSoundToggle:()=>un({...ln,enabled:!ln.enabled}),zenMode:Z,onToggleZenMode:cn}),(0,$.jsxs)(`div`,{className:`view-pane ${A===`chat`?``:`hidden`}`,children:[!Ke&&Ie&&(0,$.jsx)(Xw,{side:`left`,onClick:Be}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-left ${He===`left`?`open`:``}${Ke?``:Ie?` hidden`:``}`,children:(0,$.jsx)(Zh,{collapsible:!Ke,onToggleCollapse:Be,panelSend:Nn,active:!Ke||He===`left`,sessionFile:E?null:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,pathCompletions:n.pathCompletions,activeConversationId:E?``:n.activeConversationId,activeGroupId:E,uiContextSession:M[`contextmenu.session`],uiLeftSessions:re,uiContextProject:M[`contextmenu.project`],uiProjectsActions:I,uiLeftProject:L,uiRunningActions:ie,uiHistoryActions:ae,uiSections:oe,renderPluginSectionBody:G,uiLeftRunning:se,uiLeftHistory:ce,uiPluginRunning:n.pluginPanelGroups,onPluginRunningAction:_e,onUiAction:W,presetNames:me,transition:n.transition,onOpenSandboxModal:()=>it(`create`)})}),!Ke&&!Ie&&(0,$.jsx)(Yw,{side:`left`,width:Ae,onResize:Pe}),(0,$.jsx)(`main`,{className:`${Nt?`main wide-chat`:`main`}${Ft?` hide-model-row`:``}${n.transition&&!n.transition.previewMessages?.length?` main-transitioning`:``}${It?` main-minimal-empty`:``}`,children:E?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(zw,{roomId:E,active:A===`chat`,onBack:()=>D(null)},E)}):(0,$.jsxs)($.Fragment,{children:[n.transition&&(0,$.jsxs)(`div`,{className:`workspace-transition-bar phase-${n.transition.phase}`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`div`,{className:`workspace-transition-track`,children:(0,$.jsx)(`div`,{className:`workspace-transition-fill`,style:{width:`${Math.min(100,Math.max(8,n.transition.progress))}%`}})}),(0,$.jsxs)(`div`,{className:`workspace-transition-pill`,children:[(0,$.jsx)(`span`,{className:`workspace-transition-spinner`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`workspace-transition-text`,children:!H(t)&&n.transition.textEn?n.transition.textEn:n.transition.text}),(0,$.jsxs)(`span`,{className:`workspace-transition-pct`,children:[n.transition.progress,`%`]})]})]}),B.length>0&&(0,$.jsx)(`div`,{className:`chat-header`,role:`toolbar`,children:M_(B,W)}),n.state?(0,$.jsxs)($.Fragment,{children:[n.state.sandbox&&(0,$.jsxs)(`div`,{className:`sandbox-banner`,role:`region`,"aria-label":n.state.sandbox.name,children:[(0,$.jsxs)(`div`,{className:`sandbox-banner-info`,children:[(0,$.jsxs)(`span`,{className:`sandbox-banner-title`,children:[(0,$.jsx)(An,{className:`sandbox-banner-icon`,"aria-hidden":!0}),e(`sandboxBannerTitle`,{name:n.state.sandbox.name}),(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${n.state.sandbox.ephemeral?`ephemeral`:`permanent`}`,children:n.state.sandbox.ephemeral?e(`sandboxBadgeEphemeral`):e(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`sandbox-banner-desc`,children:n.state.sandbox.sourcePath?e(`sandboxBannerSourceDesc`,{source:n.state.sandbox.sourcePath}):e(`sandboxBannerBlankDesc`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-banner-actions`,children:[n.state.sandbox.ephemeral&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPersistTip`),onClick:()=>r({type:`persist_sandbox`,path:n.state?.sandbox?.path}),children:[(0,$.jsx)(ke,{"aria-hidden":!0}),` `,e(`sandboxActionPersist`)]}),n.state.sandbox.sourcePath&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn primary`,title:e(`sandboxActionApplySourceTip`),onClick:()=>it(`apply`),children:[(0,$.jsx)(z,{"aria-hidden":!0}),` `,e(`sandboxActionApplySource`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPromoteTip`),onClick:()=>it(`promote`),children:[(0,$.jsx)(m,{"aria-hidden":!0}),` `,e(`sandboxActionPromote`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionResetTip`),onClick:()=>{let t=n.state?.sandbox;t&&window.confirm(e(`sandboxActionResetConfirm`,{name:t.name}))&&r({type:`reset_sandbox`,path:t.path})},children:[(0,$.jsx)(te,{"aria-hidden":!0}),` `,e(`sandboxActionReset`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn danger`,title:e(`sandboxActionDestroyTip`),onClick:()=>{let t=n.state?.sandbox;t&&window.confirm(e(`sandboxActionDestroyConfirm`,{name:t.name}))&&r({type:`destroy_sandbox`,path:t.path})},children:[(0,$.jsx)(g,{"aria-hidden":!0}),` `,e(`sandboxActionDestroy`)]})]})]}),n.state.worktree&&(0,$.jsx)(pb,{worktree:n.state.worktree,onRefresh:()=>r({type:`refresh_worktrees`}),onSwitch:e=>r({type:`switch_worktree`,path:e}),onRemove:(e,t)=>r({type:`remove_worktree`,path:e,force:t})}),n.state.isEphemeral&&(0,$.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,$.jsxs)(`span`,{children:[`🎭 `,e(`ephemeralBannerText`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>r({type:`persist_conversation`,id:Fn}),children:[`💾 `,e(`saveEphemeral`)]})]}),(0,$.jsx)(Nv,{uiMessageActions:M[`message.actions`],uiContextMessage:M[`contextmenu.message`],uiContextToolCall:M[`contextmenu.toolcall`],uiToolCardFooter:M[`tool.card.footer`],uiChatEmpty:fe,onUiAction:W,preview:!!n.transition?.previewMessages?.length,state:n.transition?.previewMessages?.length?{...n.state,conversationId:n.transition.target,sessionFile:void 0,historyStart:0,historyTotal:n.transition.previewMessages.length,messages:n.transition.previewMessages,streamingMessage:null,isStreaming:!1,pendingQuestion:null,pendingApproval:null}:n.state,liveOutputs:n.liveOutputs,toolStatuses:n.toolStatuses,onEdit:Jn,onKillBash:()=>{let e=n.state?.conversationId;e&&!n.transition&&r({type:`abort_bash`,conversationId:e})},onRetry:()=>{if(r({type:`retry_last`})){let e=n.state?.model;e&&Ao(`${e.provider}/${e.id}`)}},onRemoveQueued:Yn,onRecallQueued:$n,thinkingWrap:n.settings?.thinkingWrap??!0,toolsWrap:n.settings?.toolsWrap??!0,toolImages:n.settings?.toolImagesEnabled??!0,keepRecent:n.settings?.keepRecentMessages,reversePagination:n.settings?.reversePagination??!1,minimalNewChat:n.settings?.minimalNewChat??!1,jumpTarget:Yt,onJumpDone:()=>Zt(null),urlJumpMessageId:Qt&&Qt.sessionId===n.state.sessionId?Qt.messageId:null,onUrlJumpDone:()=>$t(null)},n.transition?.previewMessages?.length?n.transition.target:n.state.conversationId??`boot`)]}):(0,$.jsx)(`div`,{className:`boot-wait`,children:n.ready?e(`loadingSession`):e(`connectingServer`)}),n.settings?.goalModeEnabled!==!1&&(0,$.jsx)(`div`,{className:`goalbar-slot`,children:(0,$.jsx)(cb,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId,uiGoalbarActions:de,onUiAction:W})}),(0,$.jsx)(ex,{onAction:(e,t,n)=>W(e,n,t)}),n.dialog&&(0,$.jsx)(Nb,{dialog:n.dialog}),ct&&(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":ct.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),ct.title&&(0,$.jsx)(`span`,{className:`dialog-title`,children:ct.title}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.kind===`confirm`?e.resolve(!1):e?.resolve({ok:!1})}catch{}},children:`✕`})]}),ct.kind===`select`&&(0,$.jsxs)(`div`,{className:`dialog-options`,children:[(ct.options??[]).map((e,t)=>{let n=ct.multi?dt.includes(t):!1;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${n?`sel`:``}`,title:e.description,onClick:()=>{if(ct.multi){ft(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);return}let n=ut.current;ut.current=null,lt(null);try{n?.resolve({ok:!0,selected:[e.label]})}catch{}},children:[e.label,e.description&&(0,$.jsx)(`span`,{className:`dialog-hint`,children:e.description})]},t)}),(ct.options??[]).length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:e(`noOptions`)}),ct.multi&&(0,$.jsx)(`div`,{className:`dialog-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current,t=(e?.options??[]).filter((e,t)=>dt.includes(t)).map(e=>e.label);ut.current=null,lt(null);try{e?.resolve({ok:!0,selected:t})}catch{}},children:e(`ok`)})})]}),ct.kind===`confirm`&&(0,$.jsx)(`div`,{className:`dialog-body`,children:(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve(!1)}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve(!0)}catch{}},children:e(`ok`)})]})}),ct.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-body`,children:[(0,$.jsx)(`input`,{className:`dialog-input`,value:pt,placeholder:ct.placeholder||e(`inputPlaceholder`),autoFocus:!0,onChange:e=>gt(e.target.value),onKeyDown:e=>{if(e.key===`Enter`&&!e.nativeEvent.isComposing){let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!0,value:pt})}catch{}}}}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!1})}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!0,value:pt})}catch{}},children:e(`ok`)})]})]})]}),(0,$.jsx)(Zb,{questions:Ib(n.questionQueue,n.question,n.remoteQuestion),activeConversationId:Fn,mode:n.settings?.questionPresentation??`queue`}),(0,$.jsx)(Px,{approvals:n.approvals,activeConversationId:Fn,mode:n.settings?.toolApprovalPresentation??`all`}),(0,$.jsx)(Lx,{plan:n.activeConversationId&&n.state?.conversationId!==n.activeConversationId?null:n.state?.plan}),Object.entries(Ln).map(([t,n])=>(0,$.jsxs)(`div`,{role:`status`,children:[n.percent===void 0?e(`uploadPreparing`,{name:n.name}):e(`uploadReading`,{name:n.name,percent:n.percent}),(0,$.jsx)(`progress`,{max:100,value:n.percent,"aria-label":n.name})]},t)),(0,$.jsx)(sb,{composerLeading:M[`composer.leading`],composerActions:M[`composer.actions`],onUiAction:W,streaming:n.state?.isStreaming??!1,planMode:n.state?.planMode??!1,messages:n.state?.messages??Vw,slashCommands:n.slashCommands,modelState:ur,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,defaultModel:n.defaultModel??void 0,attachments:d,onRemoveAttachment:nr,onAddImageFiles:rr,onAddLocalFiles:ir,onAddPathAttachment:or,fileSearch:n.fileSearch,onSearchFiles:ar,onNotice:a,onManageModels:er,onSent:tr,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:!Z&&(n.settings?.quickPhrasesEnabled??!0)&&(!n.settings?.minimalNewChat||(n.state?.messages?.length??0)>0||!!n.state?.streamingMessage),recallDrafts:Xn,dshPermCurrent:n.state?.permission??null,dshPermOptions:n.dshPermission?.options??void 0,dshPermDefault:n.dshPermission?.defaultPreset,dshPreset:n.state?.agentPreset??null,dshPresets:n.dshPresets?.presets??void 0,dshPresetDefault:n.dshPresets?.defaultPreset,dshBlank:(n.state?.messages?.length??0)===0,conversationId:n.activeConversationId||n.state?.conversationId||``,sessionDraft:n.state?.draft??null,sessionId:n.state?.sessionId??``,preserveDraftAcrossConversations:n.settings?.preserveDraftAcrossConversations??!1})]})}),!Ke&&!Re&&(0,$.jsx)(Yw,{side:`right`,width:Me,onResize:Fe}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-right ${He===`right`?`open`:``}${Ke?``:Re?` hidden`:``}`,children:(0,$.jsx)(Og,{collapsible:!Ke,onToggleCollapse:Ve,panelSend:Nn,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(e,t,n,r)=>{We(null),jn(e,t,n,r)},onPreview:(e,t)=>{We(null),x(e,t)},onNotice:(e,t)=>a(e,t),uiRightPanelTabs:M[`rightpanel.tabs`],uiContextFile:M[`contextmenu.file`],plugins:j,pluginsEpoch:n.pluginsEpoch,send:r})}),!Ke&&Re&&(0,$.jsx)(Xw,{side:`right`,onClick:Ve})]}),(0,$.jsx)(`div`,{className:`view-pane ${A===`terminal`?``:`hidden`}`,children:(0,$.jsx)(oS,{active:A===`terminal`,children:(0,$.jsx)(Dw,{chat:n,terminal:o,uiTerminalToolbar:le,onUiAction:W})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`git`?``:`hidden`}`,children:(0,$.jsx)(oS,{active:A===`git`,children:(0,$.jsx)(Ow,{chat:n,terminal:o,active:A===`git`,onSwitchToTerminal:()=>T(`terminal`),uiScmToolbar:ue,onUiAction:W})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`canvas`?``:`hidden`}`,children:(0,$.jsx)(oS,{active:A===`canvas`,children:(0,$.jsx)(jw,{send:r,active:A===`canvas`,models:n.models,defaultModel:n.defaultModel,installedSkills:n.settings?.skills,projects:n.projects,workspaceRoots:n.state?.workspaceRoots??[],pathCompletions:n.pathCompletions,currentCwd:n.state?.cwd||`.`})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`devices`?``:`hidden`}`,children:(0,$.jsx)(oS,{active:A===`devices`,children:(0,$.jsx)(kw,{pathCompletions:n.pathCompletions})})}),K.map(e=>{let t=`plugin:${e.info.id}`;return(0,$.jsx)(`div`,{className:`view-pane ${A===t?``:`hidden`}`,children:(0,$.jsx)(Qb,{entry:e})},e.info.id)}),A.startsWith(`plugin:`)&&!K.some(e=>`plugin:${e.info.id}`===A)&&(0,$.jsx)($b,{pluginId:A.slice(7),info:n.plugins.find(e=>`plugin:${e.id}`===A),epoch:n.pluginsEpoch,failed:ve.includes(A.slice(7))}),(0,$.jsx)(Db,{side:`right`,items:U,chat:n,view:A,plugins:j,dropdownProps:{theme:mn,themes:pn,onThemeChange:hn,reloadThemes:gn},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:e=>{nt(e),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onUiAction:W,uiContextTopbar:M[`contextmenu.topbar`],onThemeToggle:()=>hn(mn===`light`?null:`light`),onSoundToggle:()=>un({...ln,enabled:!ln.enabled}),zenMode:Z,onToggleZenMode:cn})]})}),(0,$.jsx)(hb,{chat:n,bottombarItems:M.bottombar,onUiAction:W,onOpenSettings:()=>{nt(void 0),et(!0)},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenGlobalSearch:()=>Wt(!0),onOpenBgTasks:()=>Bt(!0)}),p&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Rw,{file:p,content:n.fileContent,onAddLines:(e,t,n,r)=>jn(e,t,`lines`,!1,{start:n,end:r}),onAttach:(e,t,n)=>jn(e,t,n),onClose:()=>h(null),uiFilePreviewToolbar:pe,onUiAction:W})}),_&&(0,$.jsx)(sS,{file:_.file,plugin:_.plugin,declaration:_.declaration,epoch:n.pluginsEpoch,send:r,onClose:()=>v(null),onFallback:()=>{v(null),h(_.file)}}),n.ready&&n.state&&n.state.piConfigured===!1&&!Je&&!Ze&&!wt()&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Mw,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,installResult:n.installResult,onClose:Xe})}),Ze&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Nw,{providers:n.modelsConfig,providerStatus:n.providers,providerKeys:n.providerKeys,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,fetchModelsResult:n.fetchModelsResult,testModelConnectionResult:n.testModelConnectionResult,enrichModelsResult:n.enrichModelsResult,enrichModelsProgress:n.enrichModelsProgress,refreshBuiltinResult:n.refreshBuiltinResult,refreshProviderResult:n.refreshProviderResult,appendBuiltinResult:n.appendBuiltinResult,cloneProviderResult:n.cloneProviderResult,defaultModel:n.defaultModel,onClose:()=>Qe(!1)})}),$e&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Pw,{chat:n,terminal:o,initialSection:tt,onSwitchToTerminal:()=>T(`terminal`),onClose:()=>et(!1),onOpenIconEdit:()=>Jt(!0),onOpenManageModels:()=>{et(!1),Qe(!0)},sound:ln,onSoundChange:un,tts:dn,onTtsChange:fn})}),Lt&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Fw,{servers:n.bgServers,plugins:n.plugins,epoch:n.pluginsEpoch,send:r,onUiAction:W,autoCleanupMin:n.settings?.bgAutoCleanupMin??0,onClose:()=>Bt(!1)})}),(0,$.jsx)(qx,{}),(0,$.jsx)(Qx,{}),(0,$.jsx)(Nx,{}),n.tuiOverlay&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Iw,{overlay:n.tuiOverlay})}),Te&&(0,$.jsx)(aS,{entry:Te,pluginView:Ee?K.find(e=>e.info.id===Ee):void 0,onUiAction:(e,t)=>{W(e,t),be(null)},onClose:()=>be(null)}),(0,$.jsx)(oS,{active:Ht,children:(0,$.jsx)(Lw,{open:Ht,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>Wt(!1),onSwitchSession:(e,t)=>{r({type:`switch_session`,path:e});let n=t&&t[0];Zt(n?{path:e,role:n.role,timestamp:n.timestamp}:null)},onSwitchProject:e=>{r({type:`set_cwd`,path:e})},onPreviewFile:(e,t)=>{x(e,t)}})}),xe&&(0,$.jsx)(ya,{currentCwd:xe.initialPath||n.state?.cwd||``,pathCompletions:n.pathCompletions,workspaceRoots:n.state?.workspaceRoots??[],onClose:()=>{xe.resolve({ok:!1,canceled:!0}),Se(null)},onSelectDirectory:e=>{xe.resolve({ok:!0,path:e}),Se(null)},onCreateProject:e=>{r({type:`make_dir`,path:e}),xe.resolve({ok:!0,path:e}),Se(null)},mode:`project`,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:e(`projectPickerTitle`)}),Ce&&(0,$.jsx)(Tx,{currentModelId:Ce.currentModelId,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,onManageModels:()=>Qe(!0),defaultModel:n.defaultModel,onClose:()=>{Ce.resolve({ok:!1,canceled:!0}),we(null)},onSelect:(e,t)=>{Ce.resolve({ok:!0,modelId:e,name:t?.name,provider:t?.provider}),we(null)}}),O&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Aw,{onClose:()=>k(!1)})}),(jt||Tt||at)&&(0,$.jsxs)(`div`,{className:`modal-backdrop perm-modal-backdrop`,children:[jt&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginPermTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>At(jt.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[jt.family===`net`?e(`pluginPermBodyNet`).replace(`{plugin}`,jt.pluginId).replace(`{hosts}`,(jt.hosts??[]).join(`, `)):e(`pluginPermBodyLlm`).replace(`{plugin}`,jt.pluginId).replace(`{models}`,(jt.models??[]).length>0?` ${(jt.models??[]).join(`, `)}`:``),jt.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:jt.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>At(jt.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>At(jt.id,!0),children:e(`pluginPermOnce`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>At(jt.id,!0,!0),children:e(`pluginPermAlways`)})]})]})]}),Tt&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginGrantRequestTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>Ct(Tt.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginGrantRequestBody`).replace(`{plugin}`,Tt.pluginId).replace(`{path}`,Tt.path),Tt.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:Tt.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Ct(Tt.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>Ct(Tt.id,!0),children:e(`pluginGrantAllow`)})]})]})]}),at&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginSessionGrantTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{st.current=null,at.resolve(!1),ot(null)},children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginSessionGrantBody`).replace(`{path}`,at.path),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{st.current=null,at.resolve(!1),ot(null)},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{st.current=null,at.resolve(!0),ot(null)},children:e(`ok`)})]})]})]})]}),!$e&&Object.values(n.pluginJobs??{}).some(e=>e.phase!==`done`)&&(0,$.jsxs)(`div`,{className:`active-plugin-jobs-bar`,onClick:()=>{nt(`plugins`),et(!0)},title:e(`pluginJobRunning`),children:[(0,$.jsx)(te,{className:`spin`}),(0,$.jsxs)(`span`,{className:`active-plugin-jobs-title`,children:[e(`pluginJobRunning`),`:`,` `,Object.values(n.pluginJobs??{}).filter(e=>e.phase!==`done`).map(e=>e.pluginId).join(`, `)]}),(()=>{let e=Object.values(n.pluginJobs??{}).find(e=>e.phase!==`done`),t=e?.lines[e.lines.length-1];return t?(0,$.jsx)(`span`,{className:`active-plugin-jobs-line`,children:t}):null})()]}),rt&&(0,$.jsx)(fb,{mode:rt,currentCwd:n.state?.cwd,currentSandbox:n.state?.sandbox,sandboxDiff:n.sandboxDiff,projects:n.projects,send:r,onClose:()=>it(null)}),(0,$.jsx)(hx,{})]})}function rT(){typeof document<`u`&&(iT(aT()),sT())}function iT(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty(`--msgs-gutter`,`${Math.round(e*100)/100}px`)}function aT(){let e=document.createElement(`div`);e.style.cssText=`position:fixed;top:-9999px;left:0;width:100px;height:100px;overflow-y:auto;scrollbar-gutter:stable both-edges;visibility:hidden;pointer-events:none;`,document.body.appendChild(e);let t=(e.offsetWidth-e.clientWidth)/2;return e.remove(),t}function oT(e){let t=document.createElement(`div`);t.style.cssText=`width:0;height:0;pointer-events:none;`,e.appendChild(t);let n=getComputedStyle(e),r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=Number.parseFloat(n.borderLeftWidth)||0,o=Number.parseFloat(n.paddingLeft)||0,s=i.left-(r.left+a+o);return t.remove(),s}function sT(){let e=()=>{let e=document.querySelector(`.messages`);return e?(iT(oT(e)),!0):!1},t=0;if(window.addEventListener(`resize`,()=>{t||=window.requestAnimationFrame(()=>{t=0,e()})}),e())return;let n=new MutationObserver(()=>{e()&&n.disconnect()});n.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>n.disconnect(),6e4)}function cT(e){let t=typeof e==`object`&&e&&`message`in e?String(e.message):String(e);return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|Unable to preload CSS for|Loading (?:CSS )?chunk .+ failed/i.test(t)}function lT(e,t){let n=!1;return r=>{if(!cT(r))return!1;if(n)return!0;try{let n=`pi-web:chunk-recovery`,r=t.storage.getItem(n),i=r?JSON.parse(r):null,a=t.now();if(i&&(i.buildId===e||a-i.time<6e4))return!1;t.storage.setItem(n,JSON.stringify({buildId:e,time:a}))}catch{return!1}return n=!0,t.reload(),!0}}function uT(e){let t=lT(e,{storage:{getItem:e=>window.sessionStorage.getItem(e),setItem:(e,t)=>window.sessionStorage.setItem(e,t)},reload:()=>window.location.reload(),now:Date.now});return window.addEventListener(`vite:preloadError`,e=>{t(e.payload)&&e.preventDefault()}),t}var dT=uT(`20261031T04314`),fT=class extends Q.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){dT(e)||console.error(`RootErrorBoundary caught error:`,e,t)}render(){return this.state.error?(0,$.jsxs)(`div`,{style:{minHeight:`100vh`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,padding:`24px`,background:`var(--bg, rgb(13, 14, 18))`,color:`var(--text, #e2e8f0)`,fontFamily:`system-ui, -apple-system, sans-serif`,textAlign:`center`},children:[(0,$.jsx)(`h2`,{style:{fontSize:`18px`,marginBottom:`12px`,color:`var(--red, #f43f5e)`},children:`页面加载出现异常 / App Failed to Render`}),(0,$.jsx)(`pre`,{style:{maxWidth:`600px`,overflow:`auto`,padding:`12px 16px`,background:`rgba(0, 0, 0, 0.4)`,borderRadius:`8px`,fontSize:`12px`,lineHeight:`1.5`,marginBottom:`20px`,whiteSpace:`pre-wrap`,wordBreak:`break-word`,color:`#94a3b8`},children:this.state.error.message||String(this.state.error)}),(0,$.jsx)(`button`,{type:`button`,style:{padding:`8px 20px`,background:`var(--accent, #38bdf8)`,color:`#0f172a`,border:`none`,borderRadius:`6px`,fontWeight:600,cursor:`pointer`,fontSize:`13px`},onClick:()=>window.location.reload(),children:`刷新重试 / Reload`})]}):this.props.children}};X(),bt(yt()),ew(),St(),rT(),(0,xn.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(fT,{children:(0,$.jsx)(_e,{children:(0,$.jsx)(nT,{})})})})),!yn&&`serviceWorker`in navigator&&window.addEventListener(`load`,()=>{let e=W();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(e=>{console.warn(`Service worker registration failed:`,e)})});export{om as $,eb as A,Ti as At,ny as B,Cn as Bt,IS as C,Ma as Ct,yb as D,ti as Dt,vb as E,ni as Et,Vy as F,qn as Ft,cg as G,Nv as H,Ay as I,Er as It,Wm as J,yh as K,Iy as L,Dr as Lt,Jy as M,Ir as Mt,Yy as N,vr as Nt,sb as O,xi as Ot,Hy as P,yr as Pt,cm as Q,ly as R,Cr as Rt,HS as S,Na as St,wS as T,ea as Tt,P_ as U,ry as V,M_ as W,Lm as X,Rm as Y,Um as Z,$S as _,Lo as _t,BC as a,pf as at,WS as b,fo as bt,tw as c,sf as ct,LC as d,zu as dt,um as et,dC as f,Bu as ft,LS as g,cs as gt,gC as h,rc as ht,Tw as i,ff as it,$y as j,ui as jt,Qy as k,Ei as kt,ow as l,qu as lt,EC as m,ic as mt,pw as n,pp as nt,zC as o,Df as ot,xC as p,al as pt,Im as q,bw as r,lf as rt,HC as s,of as st,vw as t,em as tt,MC as u,$u as ut,VS as v,Co as vt,TS as w,wa as wt,nC as x,Za as xt,tC as y,uo as yt,oy as z,Tn as zt};
|
|
78
|
+
`))},T=e=>{l(e.id),f(e.title),m(e.description||``)},E=()=>{l(null),f(``),m(``)},D=e=>{let t=d.trim();if(!t)return;let n={title:t};n.description=p.trim()?p.trim():void 0,Z({type:`plan_step_update`,stepId:e,patch:n}),l(null)},O=e=>{Z({type:`plan_step_delete`,stepId:e})},k=e=>{let t=h.find(t=>t.id===e);t&&Z({type:`plan_step_update`,stepId:e,patch:{status:Rx[t.status]}})},A=()=>{let e={id:`step-${Date.now()}`,title:t(`planBoardAddStep`),status:`pending`};Z({type:`plan_step_add`,step:e}),T(e)},j=(e,r)=>{let i=(()=>{switch(e){case`done`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(et,{}),t(`planBoardCompleted`)]});case`in_progress`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(u,{}),t(`planBoardInProgress`)]});case`failed`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(je,{}),t(`planBoardFailed`)]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(nt,{}),t(`planBoardPending`)]})}})();return(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),k(r)},title:n?`点击切换状态 (pending / in_progress / done / failed)`:`Click to toggle status (pending / in_progress / done / failed)`,style:{display:`inline-flex`,alignItems:`center`,gap:4,color:e===`done`?`var(--green, #22c55e)`:e===`in_progress`?`var(--accent, #38bdf8)`:e===`failed`?`var(--red, #ef4444)`:`var(--text-dim, #9aa1b4)`,fontSize:12,fontWeight:e===`pending`?400:600,background:`none`,border:`none`,cursor:`pointer`,padding:`2px 4px`,borderRadius:4},children:i})};return(0,$.jsxs)(`div`,{className:`plan-board ${r?``:`plan-board-collapsed`}`.trim(),children:[(0,$.jsxs)(`div`,{className:`plan-board-head`,onClick:()=>i(!r),children:[(0,$.jsxs)(`div`,{className:`plan-board-head-main`,children:[(0,$.jsx)(ge,{className:`plan-board-icon`}),(0,$.jsx)(`span`,{className:`plan-board-title`,children:t(`planBoardTitle`)}),(0,$.jsxs)(`span`,{className:`plan-board-count ${y===100?`plan-board-count-done`:``}`.trim(),children:[_,`/`,v]}),!r&&b&&(0,$.jsx)(`span`,{className:`plan-board-active`,title:b.title,children:b.title})]}),(0,$.jsxs)(`div`,{className:`plan-board-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-implement`,title:t(`planImplementTip`),onClick:e=>{e.stopPropagation(),S()},children:t(`planImplementBtn`)}),r&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-clean-handoff`,title:t(`planCleanHandoffTip`),onClick:e=>{e.stopPropagation(),C()},children:t(`planCleanHandoffBtn`)}),r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(a?`planBoardExportSuccess`:`planBoardExportMarkdown`),onClick:e=>{e.stopPropagation(),w()},children:a?(0,$.jsx)(z,{style:{color:`var(--green, #22c55e)`}}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`clear`),onClick:e=>{e.stopPropagation(),x()},children:(0,$.jsx)(g,{})})]}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(r?`collapseSection`:`expandSection`),children:r?(0,$.jsx)(s,{}):(0,$.jsx)(pe,{})})]}),r&&(0,$.jsx)(`div`,{className:`plan-board-head-divider`,children:(0,$.jsx)(`div`,{className:`plan-board-head-divider-fill`,style:{width:`${y}%`,backgroundColor:y===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})})]}),!r&&(0,$.jsx)(`div`,{className:`plan-board-progress-line`,children:(0,$.jsx)(`div`,{className:`plan-board-progress-line-fill`,style:{width:`${y}%`,backgroundColor:y===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})}),r&&(0,$.jsxs)(`div`,{className:`plan-board-steps`,style:{marginTop:8,display:`flex`,flexDirection:`column`,gap:8},children:[h.map((n,r)=>{let i=n.id===e.activeStepId||n.status===`in_progress`;return c===n.id?(0,$.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,padding:`8px 10px`,borderRadius:6,backgroundColor:`var(--bg-elev2, rgba(0, 0, 0, 0.2))`,border:`1px solid var(--accent, #38bdf8)`},children:[(0,$.jsx)(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:t(`planBoardStepTitlePlaceholder`),style:{width:`100%`,padding:`4px 8px`,borderRadius:4,border:`1px solid var(--border-subtle)`,background:`var(--bg, #0b0f17)`,color:`var(--text, #f1f5f9)`,fontSize:13},autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),D(n.id)):e.key===`Escape`&&E()}}),(0,$.jsx)(`textarea`,{rows:2,value:p,onChange:e=>m(e.target.value),placeholder:t(`planBoardStepDescPlaceholder`),style:{width:`100%`,padding:`4px 8px`,borderRadius:4,border:`1px solid var(--border-subtle)`,background:`var(--bg, #0b0f17)`,color:`var(--text-dim, #9aa1b4)`,fontSize:12,resize:`vertical`},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),D(n.id)):e.key===`Escape`&&E()}}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:6,marginTop:2},children:[(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-iconbtn`,onClick:E,title:t(`cancel`),style:{padding:`3px 8px`,fontSize:12},children:[(0,$.jsx)(R,{}),` `,t(`cancel`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-implement`,onClick:()=>D(n.id),title:t(`confirm`),style:{padding:`3px 10px`,fontSize:12},children:[(0,$.jsx)(z,{}),` `,t(`confirm`)]})]})]},n.id||r):(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,flexWrap:`wrap`,rowGap:4,minWidth:0,padding:`6px 10px`,borderRadius:6,backgroundColor:i?`rgba(56, 189, 248, 0.08)`:`var(--bg-elev2, rgba(0, 0, 0, 0.2))`,border:i?`1px solid rgba(56, 189, 248, 0.25)`:`1px solid transparent`},children:[(0,$.jsxs)(`div`,{style:{flex:`1 1 180px`,minWidth:0,paddingRight:10},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,gap:6,minWidth:0},children:[(0,$.jsxs)(`span`,{style:{fontSize:11,fontWeight:700,color:i?`var(--accent, #38bdf8)`:`var(--text-dim, #9aa1b4)`,minWidth:16},children:[r+1,`.`]}),(0,$.jsx)(`span`,{style:{fontWeight:i?600:500,color:n.status===`done`?`var(--text-dim, #9aa1b4)`:`var(--text, #f1f5f9)`,textDecoration:n.status===`done`?`line-through`:`none`,minWidth:0,overflowWrap:`anywhere`,wordBreak:`break-word`},children:n.title})]}),n.description&&(0,$.jsx)(`div`,{style:{fontSize:12,color:`var(--text-dim, #9aa1b4)`,marginTop:2,paddingLeft:22,lineHeight:1.4,overflowWrap:`anywhere`,wordBreak:`break-word`},children:n.description})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,flexShrink:0,marginTop:2},children:[j(n.status,n.id),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardEditStep`),onClick:()=>T(n),children:(0,$.jsx)(M,{size:12})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardDeleteStep`),onClick:()=>O(n.id),children:(0,$.jsx)(g,{size:12})})]})]},n.id||r)}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-add-btn`,onClick:A,children:[(0,$.jsx)(rt,{}),` `,t(`planBoardAddStep`)]})]})]})}var Bx=3,Vx=200;function Hx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ux(e){return typeof e==`string`&&e.trim()||void 0}function Wx(e,t){let n=[];for(let r of e){let e=Kx(r,t);if(n.includes(e)||n.push(e),n.length>=4){n.push(`…`);break}}return n.join(` | `)||`any`}function Gx(e){let t=e.slice(0,6).map(e=>typeof e==`string`?e:JSON.stringify(e)??String(e));if(t.length!==0)return`enum: ${t.join(` | `)}${e.length>t.length?` | …`:``}`}function Kx(e,t=0){if(t>6||!Hx(e))return`any`;if(Ux(e.$ref))return`ref`;let n=Ux(e.type);if(n===`array`){let n=e.items;return`array<${n===void 0?`any`:Kx(n,t+1)}>`}if(n)return n;for(let n of[`anyOf`,`oneOf`,`allOf`]){let r=e[n];if(Array.isArray(r)&&r.length>0)return Wx(r,t+1)}return Hx(e.properties)?`object`:Hx(e.additionalProperties)?`record<${Kx(e.additionalProperties,t+1)}>`:`any`}function qx(e){let t=[],n=e.enum;if(Array.isArray(n)&&n.length>0){let e=Gx(n);e&&t.push(e)}return e.const!==void 0&&t.push(`const: ${JSON.stringify(e.const)}`),e.default!==void 0&&t.push(`default: ${JSON.stringify(e.default)}`),t.length>0?t.join(` · `):void 0}function Jx(e,t={}){let n=t.maxDepth??Bx,r=t.maxRows??Vx,i=e;if(!Hx(i))return[];let a=i.properties;if(!Hx(a))return[];let o=[],s=new Set((Array.isArray(i.required)?i.required:[]).filter(e=>typeof e==`string`)),c=(e,t,i,a)=>{if(!(o.length>=r))for(let[s,l]of Object.entries(e)){if(o.length>=r)return;let e=Hx(l)?l:{},u=t?`${t}.${s}`:s,d={name:u,type:Kx(e,i),required:a.has(s),depth:i},f=Ux(e.description);f&&(d.description=f);let p=qx(e);if(p&&(d.hint=p),o.push(d),i+1<n&&Hx(e.properties)){let t=new Set((Array.isArray(e.required)?e.required:[]).filter(e=>typeof e==`string`));c(e.properties,u,i+1,t)}}};return c(a,``,0,s),o}function Yx(){let e=V(),t=Gl();return mt(()=>{Vl()},!!t),t?(0,bn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:Vl,children:(0,$.jsxs)(`div`,{className:`tool-info-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`toolInfoTitle`),onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,children:[(0,$.jsx)(We,{}),e(`toolInfoTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,children:t.name}),t.label&&t.label!==t.name&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:t.label}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),onClick:Vl,children:(0,$.jsx)(R,{})})]}),(0,$.jsx)(`div`,{className:`tool-info-body`,children:(0,$.jsx)(Xx,{info:t})})]})}),document.body):null}function Xx({info:e}){let t=V();if(e.status===`loading`)return(0,$.jsxs)(`div`,{className:`tool-info-state`,role:`status`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,t(`toolInfoLoading`)]});if(e.status===`unsupported`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoUnsupported`)});if(e.status===`missing`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoMissing`)});let n=e.parameters===void 0?[]:Jx(e.parameters),r=e.parameters===void 0?``:Qx(e.parameters);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`tool-info-badges`,children:[e.active!==void 0&&(0,$.jsx)(`span`,{className:`tool-info-badge ${e.active?`on`:`off`}`,children:e.active?t(`toolInfoActive`):t(`toolInfoInactive`)}),e.source&&(0,$.jsxs)(`span`,{className:`tool-info-badge`,children:[t(`toolInfoSource`),`: `,e.source,e.scope?` · ${e.scope}`:``]})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoDescription`)}),(0,$.jsx)(`div`,{className:`tool-info-text`,children:e.description||t(`toolInfoNoDescription`)})]}),e.promptSnippet&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoPromptSnippet`)}),(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:e.promptSnippet})]}),e.promptGuidelines&&e.promptGuidelines.length>0&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoGuidelines`)}),(0,$.jsx)(`ul`,{className:`tool-info-list`,children:e.promptGuidelines.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoParams`)}),n.length>0?(0,$.jsx)(Zx,{rows:n}):(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:t(`toolInfoParamsNone`)}),e.parametersDropped&&(0,$.jsx)(`div`,{className:`tool-info-text warn`,children:t(`toolInfoSchemaDropped`)}),r&&(0,$.jsxs)(`details`,{className:`tool-info-raw`,children:[(0,$.jsxs)(`summary`,{children:[t(`toolInfoRawSchema`),(0,$.jsx)(oc,{text:r})]}),(0,$.jsx)(`pre`,{children:r})]})]}),(0,$.jsx)(`div`,{className:`tool-info-foot`,children:t(`toolInfoFootnote`)})]})}function Zx({rows:e}){let t=V();return(0,$.jsx)(`div`,{className:`tool-schema-table`,role:`table`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`tool-schema-row`,role:`row`,style:{paddingLeft:8+e.depth*14},children:[(0,$.jsxs)(`div`,{className:`tool-schema-name`,children:[(0,$.jsx)(`code`,{children:e.name}),e.required&&(0,$.jsx)(`span`,{className:`tool-schema-req`,children:t(`toolInfoRequired`)})]}),(0,$.jsxs)(`div`,{className:`tool-schema-type`,children:[e.type,e.hint&&(0,$.jsx)(`span`,{className:`tool-schema-hint`,children:e.hint})]}),e.description&&(0,$.jsx)(`div`,{className:`tool-schema-desc`,children:e.description})]},e.name))})}function Qx(e){try{return JSON.stringify(e,null,2)??``}catch{return``}}var $x={bash:(0,$.jsx)(o,{}),skill:(0,$.jsx)(Le,{}),read:(0,$.jsx)(x,{}),write:(0,$.jsx)(ct,{}),edit:(0,$.jsx)(M,{}),edit_soft:(0,$.jsx)(M,{}),grep:(0,$.jsx)(Ee,{}),find:(0,$.jsx)(D,{}),codemode:(0,$.jsx)(se,{}),eval:(0,$.jsx)(c,{}),lsp:(0,$.jsx)(c,{}),tool_search:(0,$.jsx)(Ee,{}),conversation:(0,$.jsx)(Ve,{}),subagent:(0,$.jsx)(Ve,{}),delegate_task:(0,$.jsx)(fe,{}),present_files:(0,$.jsx)(at,{}),browser_search:(0,$.jsx)(Ee,{}),browser_use:(0,$.jsx)(le,{}),ask_user_question:(0,$.jsx)(K,{}),conversation_read:(0,$.jsx)(Ae,{})};function eS(){let e=Vc();return!e||typeof document>`u`?null:(0,bn.createPortal)((0,$.jsx)(tS,{state:e}),document.body)}function tS({state:e}){let[t,n]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),Rc())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let r=()=>n(e=>!e);if(e.isThinking)return(0,$.jsx)(nS,{state:e,isMaximized:t,onToggleMaximize:r});let i=e.name||``;return i===`edit`||i===`write`||i===`edit_soft`||i===`patch`?(0,$.jsx)(aS,{state:e,isMaximized:t,onToggleMaximize:r}):i===`bash`?(0,$.jsx)(rS,{state:e,isMaximized:t,onToggleMaximize:r}):i===`read`||i===`ls`||i===`grep`||i===`find`||i===`tool_search`?(0,$.jsx)(iS,{state:e,isMaximized:t,onToggleMaximize:r}):(0,$.jsx)(oS,{state:e,isMaximized:t,onToggleMaximize:r})}function nS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),{copy:i,copied:a}=ac({duration:1200}),o=e.thinking||e.output||``,s=o.length,c=o?o.split(`
|
|
79
|
+
`).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Rc()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(E,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,children:r(`toolInspectorThinkingSection`).replace(/^💭\s*/,``)}),(0,$.jsx)(`span`,{className:`file-diff-lang`,children:r(`toolInspectorStats`,{chars:s,lines:c})}),(0,$.jsx)(`span`,{className:`file-diff-status-pill ${e.streaming?`run`:`ok`}`,children:e.streaming?`⚡ 思考中...`:`✓ 完成`})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${a?` copied`:``}`,title:r(a?`toolInspectorCopied`:`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),i(o)},children:a?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Rc()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:(0,$.jsx)(`div`,{className:`thinking-inspector-content`,children:o?(0,$.jsx)(`div`,{className:`markdown thinking-markdown`,children:(0,$.jsx)(sl,{text:o})}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`toolInspectorEmptyThinking`)})})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:`💭`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:e.streaming?`思考分析链路生成中...`:`分析记录共 ${c} 行`})]}),e.duration&&(0,$.jsx)(`div`,{className:`file-diff-footer-meta`,children:(0,$.jsxs)(`span`,{children:[`耗时: `,e.duration]})})]})]})})}function rS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,s]=(0,Q.useState)(`preview`),l=ac({duration:1200}),u=ac({duration:1200}),{args:d=``,output:f=``,details:p,isError:m=!1,status:h,duration:g,exitHint:_}=e,v=(e.hints||nu(d)).command||(d&&!d.startsWith(`{`)?d:``),y=(0,Q.useMemo)(()=>{if(!p||typeof p!=`object`)return``;try{return JSON.stringify(p,null,2)}catch{return``}},[p]),b=m?r(`error`):g?`${r(`done`)} (${g})`:h||r(`done`),x=m?`err`:`ok`,S=f?f.split(`
|
|
80
|
+
`).length:0,C=p&&typeof p==`object`?Object.keys(p).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Rc()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(o,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:v||`bash`,children:v?`$ ${v}`:`bash`}),_&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:_}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${x}`,children:[`✓ `,b]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`preview`)},children:i?`终端输出`:`Terminal`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:r(`diffViewRaw`)})]}),v&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${l.copied?` copied`:``}`,title:l.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyArgs`),onClick:e=>{e.stopPropagation(),l.copy(v)},children:l.copied?(0,$.jsx)(z,{}):(0,$.jsx)(c,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${u.copied?` copied`:``}`,title:u.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),u.copy(f)},children:u.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Rc()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:d||`(无入参参数 / No arguments)`})]}),y&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[C,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:y})]})]}):(0,$.jsxs)(`div`,{className:`bash-terminal-viewport`,children:[v&&(0,$.jsx)(Fd,{command:v}),(0,$.jsx)(`pre`,{className:`bash-output-pre`,children:f||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${m?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:m?`✕`:`✓`}),(0,$.jsxs)(`span`,{className:`file-diff-status-text`,children:[_||(m?`命令执行失败`:`执行完成`),` · `,S,` 行输出 · `,f.length,` 字符`]})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[C>0&&(0,$.jsxs)(`span`,{children:[`details: `,C,` keys`]}),C>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(a===`raw`?`preview`:`raw`)},children:a===`raw`?i?`返回终端输出`:`Back to terminal`:i?`查看完整日志与详情`:`View raw & details`})]})]})]})})}function iS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,o]=(0,Q.useState)(`preview`),s=ac({duration:1200}),{name:c=`read`,args:l=``,output:u=``,details:d,isError:f=!1,status:p,duration:m,images:h}=e,g=e.hints||nu(l),_=g.path||``,v=g.query||``,y=v?_?`${v} (${_})`:v:_||c,b=(0,Q.useMemo)(()=>{if(h&&h.length>0)return!0;if(_){let e=_.split(`.`).pop()?.toLowerCase();return e&&[`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`,`bmp`].includes(e)}return!1},[h,_]),S=(0,Q.useMemo)(()=>{if(!l)return 1;try{let e=JSON.parse(l);if(typeof e?.offset==`number`&&e.offset>0)return e.offset;if(typeof e?.startLine==`number`&&e.startLine>0)return e.startLine}catch{let e=/"(?:offset|startLine|start)"\s*:\s*(\d+)/.exec(l);if(e){let t=parseInt(e[1],10);if(t>0)return t}}return 1},[l]),C=(0,Q.useMemo)(()=>{if(!d||typeof d!=`object`)return``;try{return JSON.stringify(d,null,2)}catch{return``}},[d]),w=f?r(`error`):m?`${r(`done`)} (${m})`:p||r(`done`),T=f?`err`:`ok`,E=u?u.split(`
|
|
81
|
+
`).length:0,D=d&&typeof d==`object`?Object.keys(d).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Rc()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:$x[c]??(0,$.jsx)(x,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:y,children:y}),v&&(0,$.jsx)(`span`,{className:`file-diff-pattern`,title:i?`搜索表达式: ${v}`:`Pattern: ${v}`,children:c===`grep`?`REGEX`:`QUERY`}),_&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:_.split(`.`).pop()?.toUpperCase()||`FILE`}),S>1&&(0,$.jsxs)(`span`,{className:`file-diff-lang`,title:`起始偏移量: 第 ${S} 行`,children:[`L`,S,`~L`,S+E-1]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${T}`,children:[`✓ `,w]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`preview`)},children:i?`内容查看`:`Content`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),_&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!_)return;let t=_.split(`/`).pop()||_;qc({path:_,name:t})},children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s.copied?` copied`:``}`,title:s.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),s.copy(u)},children:s.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Rc()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:l||`(无入参参数 / No arguments)`})]}),C&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[D,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:C})]})]}):(0,$.jsxs)(`div`,{className:`read-inspector-viewport`,children:[c===`tool_search`&&(0,$.jsx)(Id,{details:d}),b&&h&&h.length>0?(0,$.jsxs)(`div`,{className:`read-image-viewport`,children:[h.map((e,t)=>{let n=e.startsWith(`/`)?q(e):e;return(0,$.jsx)(`div`,{className:`read-image-container`,children:(0,$.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,title:`点击新窗口查看原图`,children:(0,$.jsx)(`img`,{src:n,alt:_||`Image ${t+1}`,className:`read-image-item`})})},t)}),u&&(0,$.jsx)(`div`,{className:`read-image-caption`,children:u})]}):u?(0,$.jsx)(xd,{content:u,startLine:S}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`)})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${f?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:f?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:r(`toolInspectorStats`,{chars:u.length,lines:E})})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[D>0&&(0,$.jsxs)(`span`,{children:[`details: `,D,` keys`]}),D>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`preview`:`raw`)},children:a===`raw`?i?`返回内容`:`Back to content`:i?`查看完整参数`:`View raw`})]})]})]})})}function aS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,o]=(0,Q.useState)(`unified`),{copied:s,copy:c}=ac({duration:1200}),{name:l=`edit`,args:u=``,details:d,output:f=``,isError:p=!1,status:m,duration:h}=e,g=(0,Q.useMemo)(()=>yd(l,u,d,f),[l,u,d,f]),_=d&&typeof d==`object`?Object.keys(d).length:0,v=(0,Q.useMemo)(()=>{if(!d||typeof d!=`object`)return``;try{return JSON.stringify(d,null,2)}catch{return``}},[d]),y=p?r(`error`):h?`${r(`done`)} (${h})`:m||r(`done`),b=p?`err`:`ok`;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Rc()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(x,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:g?.filePath||l,children:g?.filePath||l}),g?.language&&g.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:g.language}),g?.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:r(`diffNewFile`)}):g?.stats.additions!==void 0&&(g.stats.additions>0||g.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[g.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,g.stats.additions]}),g.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,g.stats.deletions]})]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${b}`,children:[`✓ `,y]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`unified`)},children:r(`diffViewUnified`)}),!g?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`split`)},children:r(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s?` copied`:``}`,title:g?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),"aria-label":g?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),onClick:e=>{e.stopPropagation(),g?.isWrite&&g.content?c(g.content):u&&c(u)},children:s?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),g?.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(`diffOpenFile`),"aria-label":r(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!g?.filePath)return;let t=g.filePath.split(`/`).pop()||g.filePath;qc({path:g.filePath,name:t})},children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),"aria-label":r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,"aria-label":r(`close`),onClick:e=>{e.stopPropagation(),Rc()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:u||`(无入参参数 / No arguments)`})]}),v&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[_,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:v})]})]}):g?.isWrite?(0,$.jsx)(xd,{content:g.content||``}):a===`split`?(0,$.jsx)(wd,{hunks:g?.hunks||[],isStreaming:g?.isStreamingPartial,fallbackText:u}):(0,$.jsx)(Sd,{hunks:g?.hunks||[],isStreaming:g?.isStreamingPartial,fallbackText:u})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${p?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:p?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:f||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[_>0&&(0,$.jsxs)(`span`,{children:[`details: `,_,` keys`]}),_>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`unified`:`raw`)},children:a===`raw`?i?`返回差异对比`:`Back to diff`:i?`查看完整日志`:`View raw logs`})]})]})]})})}function oS({state:e,isMaximized:t,onToggleMaximize:n}){let r=V(),i=H(Se()),[a,o]=(0,Q.useState)(`preview`),s=ac({duration:1200}),{name:c=`tool`,args:l=``,details:u,output:d=``,isError:f=!1,status:p,duration:m,images:h}=e,g=tu({name:c,argumentsText:l,hints:e.hints||nu(l)}),_=g?`${c}(${g.text})`:c?`${c}()`:r(`toolInspectorTitle`),v=(0,Q.useMemo)(()=>{if(!u||typeof u!=`object`)return``;try{return JSON.stringify(u,null,2)}catch{return``}},[u]),y=f?r(`error`):m?`${r(`done`)} (${m})`:p||r(`done`),b=f?`err`:`ok`,x=u&&typeof u==`object`?Object.keys(u).length:0,S=c===`present_files`,C=(0,Q.useMemo)(()=>S&&l?Cu(l):null,[S,l]),w=c===`delegate_task`,T=(0,Q.useMemo)(()=>w&&l?ou(l):{},[w,l]),E=c===`codemode`,D=(0,Q.useMemo)(()=>E&&l?pu(l):null,[E,l]),O=c===`ask_user_question`,k=(0,Q.useMemo)(()=>O&&l?_u(l):null,[O,l]),A=!!(S&&C||w&&Object.keys(T).length>0||E&&D?.code||O&&k);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Rc()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:$x[c]??(0,$.jsx)(at,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_,children:_}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${b}`,children:[`✓ `,y]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[A&&(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`preview`)},children:i?`视图`:`View`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${a===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),o(`raw`)},children:r(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s.copied?` copied`:``}`,title:s.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),s.copy(`[Arguments]\n${l}\n\n[Output]\n${d}`)},children:s.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(de,{}):(0,$.jsx)(J,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Rc()},children:(0,$.jsx)(R,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:a===`raw`?(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:l||`(无入参参数 / No arguments)`})]}),v&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[x,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:v})]})]}):(0,$.jsxs)(`div`,{className:`generic-inspector-viewport`,children:[S&&C&&(0,$.jsx)(ad,{args:C,details:u,toolCallId:e.toolCallId??``,resultTimestamp:e.resultTimestamp}),w&&(0,$.jsx)(Ld,{args:T}),E&&D?.code&&(0,$.jsx)(Rd,{code:D.code,options:D.options,details:u,output:d}),O&&k&&(0,$.jsx)(ud,{questions:k.questions,details:u,output:d,isError:f,waiting:e.statusClass===`run`}),h&&h.length>0&&(0,$.jsxs)(`div`,{className:`tool-inspector-section pi-we-inspector-section`,style:{padding:`8px 14px`},children:[(0,$.jsx)(`div`,{className:`tool-inspector-label-row`,children:(0,$.jsxs)(`span`,{className:`tool-inspector-label pi-we-inspector-label`,children:[r(`toolInspectorImages`),` (`,h.length,`)`]})}),(0,$.jsx)(`div`,{className:`tool-inspector-images`,children:h.map((e,t)=>(0,$.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,title:`点击新窗口打开图片`,children:(0,$.jsx)(`img`,{src:e,alt:`output image ${t+1}`,loading:`lazy`})},t))})]}),!A&&(0,$.jsx)(`pre`,{className:`generic-output-pre`,children:d||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status${f?` err`:``}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:f?`✕`:`✓`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:d?`${d.split(`
|
|
82
|
+
`).length} 行输出 · ${d.length} 字符`:`执行完成`})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[x>0&&(0,$.jsxs)(`span`,{children:[`details: `,x,` keys`]}),x>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),o(a===`raw`?`preview`:`raw`)},children:a===`raw`?i?`返回视图`:`Back to view`:i?`查看完整参数与详情`:`View raw & details`})]})]})]})})}function sS({entry:e,pluginView:t,onUiAction:n,onClose:r}){let i=V(),a=e.label||e.id,o=e.kind===`view`;return(0,$.jsx)(Ma,{className:`plugin-modal`,title:a,icon:e.icon,onClose:r,children:(0,$.jsx)(`div`,{className:`modal-body plugin-modal-body`,children:o?t?(0,$.jsx)(ex,{entry:t}):(0,$.jsx)(`div`,{className:`plugin-modal-loading`,children:i(`loading`)}):e.kind===`divider`?(0,$.jsx)(`hr`,{className:`plugin-modal-divider`}):(0,$.jsx)(`button`,{type:`button`,className:`btn primary plugin-modal-action`,onClick:()=>n?.(e),children:e.badge??a})})})}function cS({active:e,children:t}){let n=(0,Q.useRef)(!1);return e&&(n.current=!0),n.current?(0,$.jsx)(Q.Suspense,{fallback:null,children:t}):null}function lS({file:e,plugin:t,declaration:n,epoch:r,send:i,onClose:a,onFallback:o}){let s=V(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),p=(0,Q.useRef)(o);p.current=o;let m=n.label??t.name;(0,Q.useEffect)(()=>{let r=c.current;if(!r)return;let a=!1,o;return u(null),f(!1),(async()=>{try{let s=await Ex({plugin:t,declaration:n});if(a)return;if(!s)throw Error(`插件没有提供可用的文件查看器`);let c=`/plugins-api/${encodeURIComponent(t.id)}`,l={...Lm(t.id,i),file:e,apiUrl:(e,t)=>{let n=String(e??``).startsWith(`/`)?String(e):`/${String(e??``)}`,r=new URLSearchParams;for(let[e,n]of Object.entries(t??{}))n!==void 0&&r.set(e,String(n));r.set(`clientId`,xh());let i=r.toString();return Qe(q(`${c}${n}${i?`?${i}`:``}`))}};o=s.handler.mount(r,e,l),a||f(!0)}catch(e){a||(console.error(`[plugin:${t.id}] file handler failed:`,e),p.current())}})(),()=>{if(a=!0,typeof o==`function`)try{o()}catch(e){console.error(`[plugin:${t.id}] file handler cleanup failed:`,e)}r.textContent=``}},[e,t,n,r,i]);let h=(0,$.jsxs)(`div`,{className:`plugin-file-preview-title-row`,children:[(0,$.jsx)(`span`,{className:`plugin-file-preview-name`,title:e.path,children:e.name||e.path}),m?(0,$.jsx)(`span`,{className:`plugin-file-preview-badge`,children:m}):null]});return(0,$.jsx)(Ma,{className:`plugin-file-preview`,title:h,icon:t.icon,allowFullscreen:!0,onClose:a,children:(0,$.jsxs)(`div`,{className:`modal-body plugin-file-preview-body`,children:[l?(0,$.jsx)(`div`,{className:`plugin-file-preview-error`,children:l}):null,!l&&!d?(0,$.jsx)(`div`,{className:`plugin-file-preview-loading`,children:s(`loading`)}):null,(0,$.jsx)(`div`,{ref:c,className:`plugin-file-preview-host`})]})})}var uS=.4,dS=1.05;function fS(e){return Math.min(300,e*.86)}function pS(e,t,n){return n||(t<=144?null:e<=72?`left`:t-e<=72?`right`:null)}function mS(e,t){let n=Math.abs(e),r=Math.abs(t);return n<12&&r<12?`none`:n>r*1.2?`horizontal`:`vertical`}function hS(e,t){return e===`left`?t:-t}function gS(e,t){return Math.max(-e,Math.min(0,-e+t))}function _S(e,t,n){let r=n?e+t:t;return Math.max(0,Math.min(1,r/e))}function vS(e){let{wasOpen:t,pull:n,width:r,durationMs:i}=e;return i<=320&&Math.abs(n)>=48?n>0:_S(r*dS,n,t)>=uS}var yS=new Set([`auto`,`scroll`,`overlay`]);function bS(e,t){let n=e instanceof Element?e:null;for(;n;){if(n instanceof HTMLElement&&n.scrollWidth>n.clientWidth+4&&yS.has(getComputedStyle(n).overflowX))return!0;if(n===t)break;n=n.parentElement}return!1}function xS(){let e=e=>{e.stopPropagation(),e.preventDefault()};window.addEventListener(`click`,e,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,e,{capture:!0}),400)}function SS(e){let{enabled:t,open:n,onOpenChange:r,container:i}=e,{panelSelector:a,backdropSelector:o}=e;(0,Q.useEffect)(()=>{let e=i.current;if(!t||!e)return;let s=null,c=`none`,l=0,u=0,d=0,f=0,p=!1,m=0,h=0,g=null,_=null,v=()=>{g&&(g.classList.remove(`drawer-dragging`),g.style.transform=``),_&&(_.style.opacity=``),s=null,c=`none`,g=null,_=null,f=0,p=!1},y=t=>{if(v(),t.touches.length!==1)return;let r=t.touches[0],i=pS(r.clientX,window.innerWidth,n);i&&!bS(t.target,e)&&(s=i,l=r.clientX,u=r.clientY,d=Date.now())},b=t=>{let r=s;if(!r||t.touches.length!==1)return;let i=t.touches[0],d=i.clientX-l,v=i.clientY-u;if(c===`none`){let t=mS(d,v);if(t===`none`)return;if(t===`vertical`){s=null;return}c=`horizontal`,p=n===r,m=fS(window.innerWidth),h=m*dS;let i=e.querySelector(a?a(r):`.panel-drawer.drawer-${r}`);if(!i){s=null;return}g=i,_=o===null?null:e.querySelector(o??`.drawer-backdrop`),i.classList.add(`drawer-dragging`)}let y=g;if(!y)return;f=hS(r,d);let b=gS(h,f);y.style.transform=`translateX(${r===`left`?b:-b}px)`,_&&(_.style.opacity=String(_S(h,f,p))),t.preventDefault()},x=()=>{let e=s,t=c===`horizontal`&&e!==null&&g!==null,i=f,a=Date.now()-d,o=t?vS({wasOpen:p,pull:i,width:m,durationMs:a}):!1;v(),t&&e&&o!==(n===e)&&(xS(),r(o?e:null))},S=()=>v();return e.addEventListener(`touchstart`,y,{passive:!0}),e.addEventListener(`touchmove`,b,{passive:!1}),e.addEventListener(`touchend`,x),e.addEventListener(`touchcancel`,S),()=>{v(),e.removeEventListener(`touchstart`,y),e.removeEventListener(`touchmove`,b),e.removeEventListener(`touchend`,x),e.removeEventListener(`touchcancel`,S)}},[t,n,r,i,a,o])}var CS={revision:0},wS=new Set;function TS(e){CS={...e,revision:CS.revision+1};for(let e of wS)e()}function ES(){return(0,Q.useSyncExternalStore)(e=>(wS.add(e),()=>{wS.delete(e)}),()=>CS)}var DS={zh:[`继续`,`总结一下`,`详细解释一下`,`检查并修复问题`,`补充测试覆盖`,`发布上传`],en:[`Continue`,`Summarize`,`Explain in detail`,`Check and fix issues`,`Add test coverage`,`Publish release`],it:[`Continua`,`Riassumi`,`Spiega in dettaglio`,`Verifica e correggi i problemi`,`Aggiungi copertura dei test`,`Pubblica la release`],ja:[`続ける`,`要約して`,`詳しく説明して`,`問題を確認して修正`,`テストカバレッジを追加`,`公開・リリース`],ko:[`계속`,`요약해줘`,`자세히 설명해줘`,`문제를 확인하고 수정`,`테스트 커버리지 추가`,`게시/릴리스`],fr:[`Continuer`,`Résumer`,`Expliquer en détail`,`Vérifier et corriger les problèmes`,`Ajouter des tests`,`Publier`],de:[`Weiter`,`Zusammenfassen`,`Ausführlich erklären`,`Probleme prüfen und beheben`,`Testabdeckung ergänzen`,`Veröffentlichen`],es:[`Continuar`,`Resumir`,`Explicar en detalle`,`Revisar y corregir problemas`,`Añadir cobertura de pruebas`,`Publicar`],ru:[`Продолжить`,`Подведи итог`,`Объясни подробно`,`Проверь и исправь проблемы`,`Добавь покрытие тестами`,`Опубликовать`],pt:[`Continuar`,`Resumir`,`Explique em detalhes`,`Verifique e corrija os problemas`,`Adicione cobertura de testes`,`Publique a release`]},OS=`pi-web-sounds`,kS={enabled:!0,question:!0,done:!0,subagentDone:!0,start:!1,error:!0,approval:!0,volume:100};function AS(){try{let e=localStorage.getItem(OS);if(!e)return{...kS};let t=JSON.parse(e),n={...kS,...t};t.subagentDone===void 0&&typeof t.done==`boolean`&&(n.subagentDone=t.done);for(let e of[`enabled`,`question`,`done`,`subagentDone`,`start`,`error`,`approval`])typeof n[e]!=`boolean`&&(n[e]=kS[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?kS.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...kS}}}function jS(e){try{localStorage.setItem(OS,JSON.stringify(e))}catch{}}var MS=null;function NS(){try{if(!MS){let e=window.AudioContext??window.webkitAudioContext;if(!e)return null;MS=new e}return MS.state===`suspended`&&MS.resume(),MS}catch{return null}}var PS=[{type:`sine`,freq:587.33,start:0,dur:.13,peak:.5},{type:`sine`,freq:880,start:.11,dur:.24,peak:.5}],FS=[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],IS={question:PS,done:FS,subagentDone:FS,start:[{type:`triangle`,freq:660,start:0,dur:.08,peak:.22}],error:[{type:`square`,freq:220,start:0,dur:.16,peak:.18},{type:`square`,freq:174.61,start:.18,dur:.26,peak:.18}],approval:[{type:`sine`,freq:659.25,start:0,dur:.11,peak:.45},{type:`sine`,freq:659.25,start:.14,dur:.11,peak:.45},{type:`sine`,freq:880,start:.28,dur:.26,peak:.5}]};function LS(e,t,n){let r=e.createOscillator(),i=e.createGain();r.type=t.type,r.frequency.value=t.freq;let a=e.currentTime+t.start,o=Math.max(1e-4,t.peak*n);i.gain.setValueAtTime(1e-4,a),i.gain.exponentialRampToValueAtTime(o,a+.012),i.gain.exponentialRampToValueAtTime(1e-4,a+t.dur),r.connect(i),i.connect(e.destination),r.start(a),r.stop(a+t.dur+.05)}function RS(e,t=AS()){if(!t.enabled||!t[e])return;let n=NS();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));for(let t of IS[e])LS(n,t,r)}var zS=[`question`,`done`,`subagentDone`,`start`,`error`,`approval`];function BS(e,t,n){if(!t.enabled)return!1;let r=t.events?.[e];return r===`on`||r!==`off`&&n[e]}var VS=`pi-web-notify`,HS={enabled:!1};function US(){try{let e=localStorage.getItem(VS);if(!e)return{...HS};let t=JSON.parse(e),n={};for(let e of zS){let r=t.events?.[e];(r===`follow`||r===`on`||r===`off`)&&(n[e]=r)}return{enabled:typeof t.enabled==`boolean`?t.enabled:HS.enabled,events:n}}catch{return{...HS}}}function WS(e){try{localStorage.setItem(VS,JSON.stringify(e))}catch{}}function GS(){return typeof window<`u`&&`Notification`in window}function KS(){return GS()?null:typeof window<`u`&&window.isSecureContext===!1?`insecure`:`unsupported`}function qS(e){let{screenX:t,screenY:n,outerWidth:r,outerHeight:i}=e;return Number.isFinite(t)&&JS(t)||Number.isFinite(n)&&JS(n)?!0:r>0&&r<=400&&i>0&&i<=40}function JS(e){return e<=-1e4}function YS(e){return!(e.visibility!==`visible`||e.minimized||!e.hasFocus||e.windows&&e.idleMs>12e4)}var XS=Date.now(),ZS=!1;function QS(){XS=Date.now()}function $S(){return Math.max(0,Date.now()-XS)}function eC(){if(ZS||typeof window>`u`)return;ZS=!0;let e={passive:!0,capture:!0};for(let t of[`pointerdown`,`pointermove`,`keydown`,`wheel`,`touchstart`,`focus`,`scroll`])window.addEventListener(t,QS,e);typeof document<`u`&&document.addEventListener(`visibilitychange`,QS,e)}function tC(){return typeof navigator>`u`?!1:/windows/i.test(navigator.userAgent??``)}function nC(){return eC(),typeof window>`u`||typeof document>`u`?{hasFocus:!0,visibility:`visible`,minimized:!1,idleMs:0,windows:!1}:{hasFocus:typeof document.hasFocus!=`function`||document.hasFocus(),visibility:document.visibilityState??``,minimized:qS({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:$S(),windows:tC()}}function rC(){return GS()?Notification.permission:`denied`}async function iC(){if(!GS())return`denied`;try{return await Notification.requestPermission()}catch{return`denied`}}function aC(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function oC(e,t=!1){return{body:e,requireInteraction:t,icon:q(`/icons/icon-192.png`),badge:q(`/icons/icon-192.png`),data:{url:typeof location<`u`?location.href:q(`/`)}}}async function sC(e,t,n=!1){if(!GS())return{path:`none`,error:`unsupported`};if(Notification.permission!==`granted`)return{path:`none`,error:`permission: ${Notification.permission}`};let r=oC(t,n),i;try{let t=await navigator.serviceWorker?.getRegistration();if(t?.active&&typeof t.showNotification==`function`)return await t.showNotification(e,r),{path:`sw`};i=t?`service worker not active`:`no service worker registration`}catch(e){i=aC(e)}try{return new Notification(e,r),{path:`page`,error:i}}catch(e){return{path:`none`,error:`${i}; page: ${aC(e)}`}}}async function cC(e,t,n=`done`){GS()&&(YS(nC())||BS(n,US(),AS())&&await sC(e,t))}var lC=`pi-web-ui:wide-chat`,uC={wide:!1};function dC(e){if(!e||typeof e!=`object`)return{...uC};let t=e;return{wide:typeof t.wide==`boolean`?t.wide:uC.wide}}function fC(){try{let e=localStorage.getItem(lC);return e?dC(JSON.parse(e)):{...uC}}catch{return{...uC}}}function pC(e){let t=dC(e);try{localStorage.setItem(lC,JSON.stringify(t))}catch{}mC=t;for(let e of hC)e()}var mC=null,hC=new Set;function gC(e){return hC.add(e),()=>{hC.delete(e)}}function _C(){return mC||=fC(),mC.wide}function vC(){return(0,Q.useSyncExternalStore)(gC,_C)}var yC=`pi-web-ui:hide-model-row`,bC={hide:!1};function xC(e){if(!e||typeof e!=`object`)return{...bC};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:bC.hide}}function SC(){try{let e=localStorage.getItem(yC);return e?xC(JSON.parse(e)):{...bC}}catch{return{...bC}}}function CC(e){let t=xC(e);try{localStorage.setItem(yC,JSON.stringify(t))}catch{}wC=t;for(let e of TC)e()}var wC=null,TC=new Set;function EC(e){return TC.add(e),()=>{TC.delete(e)}}function DC(){return wC||=SC(),wC.hide}function OC(){return(0,Q.useSyncExternalStore)(EC,DC)}var kC=`pi-web-ui:project-title`,AC={projectName:!0};function jC(e){if(!e||typeof e!=`object`)return{...AC};let t=e;return{projectName:typeof t.projectName==`boolean`?t.projectName:AC.projectName}}function MC(e){return e?e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``:``}function NC(){try{let e=localStorage.getItem(kC);return e?jC(JSON.parse(e)):{...AC}}catch{return{...AC}}}function PC(e){let t=jC(e);try{localStorage.setItem(kC,JSON.stringify(t))}catch{}FC=t;for(let e of IC)e()}var FC=null,IC=new Set;function LC(e){return IC.add(e),()=>{IC.delete(e)}}function RC(){return FC||=NC(),FC.projectName}function zC(){return(0,Q.useSyncExternalStore)(LC,RC)}var BC=`pi-web-ui:favicon-settings`,VC=[{id:`violet`,hex:`#8b5cf6`,nameKey:`colorViolet`},{id:`blue`,hex:`#3b82f6`,nameKey:`colorBlue`},{id:`cyan`,hex:`#06b6d4`,nameKey:`colorCyan`},{id:`emerald`,hex:`#10b981`,nameKey:`colorEmerald`},{id:`amber`,hex:`#f59e0b`,nameKey:`colorAmber`},{id:`rose`,hex:`#ef4444`,nameKey:`colorRose`},{id:`pink`,hex:`#ec4899`,nameKey:`colorPink`},{id:`indigo`,hex:`#6366f1`,nameKey:`colorIndigo`},{id:`slate`,hex:`#64748b`,nameKey:`colorSlate`}],HC=`#8b5cf6`,UC={color:`default`,customHex:``,instanceName:``};function WC(e){if(!e)return null;let t=e.trim(),n=/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`.toLowerCase():`#${r.toLowerCase()}`}function GC(e){if(!e||typeof e!=`object`)return{...UC};let t=e;return{color:typeof t.color==`string`&&t.color.trim()?t.color.trim():UC.color,customHex:typeof t.customHex==`string`?t.customHex.trim():``,instanceName:typeof t.instanceName==`string`?t.instanceName.trim():``}}function KC(e,t=VC){if(!e||t.length===0)return HC;let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t[Math.abs(n)%t.length].hex}function qC(e){let t=e.replace(`#`,``).trim();if(t.length!==3&&t.length!==6)return!1;let n=0,r=0,i=0;return t.length===3?(n=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),i=parseInt(t[2]+t[2],16)):(n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16)),Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?!1:.2126*n+.7152*r+.0722*i>180}function JC(e){let t=qC(e)?`#1e1e2e`:`#ffffff`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${e}"/><rect x="14" y="17" width="36" height="6.5" rx="3.25" fill="${t}"/><rect x="17.5" y="23.5" width="6.5" height="25" rx="3.25" fill="${t}"/><rect x="40" y="23.5" width="6.5" height="25" rx="3.25" fill="${t}"/></svg>`}var YC={};function XC(e){YC={...YC,...e},nw();for(let e of aw)e()}async function ZC(){if(typeof window<`u`&&typeof fetch<`u`)try{let e=await fetch(q(`/api/health`));if(!e.ok)return;let t=await e.json();t&&(t.instanceName||t.faviconColor)&&XC({instanceName:t.instanceName,faviconColor:t.faviconColor})}catch{}}function QC(e,t=typeof window<`u`?window.location.host:``,n=YC.faviconColor){if(e.color===`custom`&&e.customHex){let t=WC(e.customHex);if(t)return t}if(e.color===`auto`)return KC(t||`localhost`);let r=VC.find(t=>t.id===e.color);if(r)return r.hex;let i=WC(e.color);if(i)return i;if(e.color==="default"&&n){let e=VC.find(e=>e.id===n.toLowerCase());if(e)return e.hex;let t=WC(n);if(t)return t}return HC}function $C(e,t=YC.instanceName){return e.instanceName&&e.instanceName.trim()?e.instanceName.trim():t&&t.trim()?t.trim():``}function ew(e){if(typeof document>`u`)return;let t=document.querySelector(`link[rel~='icon']`);t||(t=document.createElement(`link`),t.rel=`icon`,document.head.appendChild(t)),t.type=`image/svg+xml`;let n=JC(e);t.href=`data:image/svg+xml;utf8,${encodeURIComponent(n)}`}function tw(){try{let e=localStorage.getItem(BC);return e?GC(JSON.parse(e)):{...UC}}catch{return{...UC}}}function nw(){ew(QC(iw??tw(),typeof window<`u`?window.location.host:``))}function rw(e){let t=GC(e);try{localStorage.setItem(BC,JSON.stringify(t))}catch{}iw=t,nw();for(let e of aw)e()}var iw=null,aw=new Set;function ow(e){return aw.add(e),()=>{aw.delete(e)}}function sw(){return iw||=tw(),iw}function cw(){return(0,Q.useSyncExternalStore)(ow,sw)}function lw(e,t,n,r,i,a=!1){let o=new Map;for(let e of r)o.set(e.id,!!e.isStreaming||!!e.completionPending);if(t&&o.set(t,n||a),e===null)return{startCue:!1,finishedConvs:[],nextMap:o};let s=!1;t&&(i===void 0||i===t)&&e.get(t)===!1&&n===!0&&(s=!0);let c=[];for(let[n,i]of e.entries())if(i&&o.has(n)&&!o.get(n)){let e=r.find(e=>e.id===n);c.push({id:n,title:e?.title,isActive:n===t,isSubagent:!!e?.isSubagent})}return{startCue:s,finishedConvs:c,nextMap:o}}var uw=`pi-web-ui:wallpaper`,dw=`has-wallpaper`,fw={url:``,dim:78,blur:0},pw=2e3,mw=28e5;function hw(e){if(typeof e!=`string`)return``;let t=e.trim();if(!t)return``;let n=t.toLowerCase().startsWith(`data:image/`)?mw:pw;return t.length>n?``:/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)?t:``}var gw=(e,t,n,r)=>typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function _w(e){if(!e||typeof e!=`object`)return{...fw};let t=e;return{url:hw(t.url),dim:gw(t.dim,0,95,fw.dim),blur:gw(t.blur,0,24,fw.blur)}}function vw(){try{let e=localStorage.getItem(uw);return e?_w(JSON.parse(e)):{...fw}}catch{return{...fw}}}function yw(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\r\n]/g,``)}async function bw(e){let t=await nf(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function xw(){let e=Cw??vw(),t=document.documentElement;e.url?(t.style.setProperty(`--bg-image`,`url("${yw(e.url)}")`),t.style.setProperty(`--bg-image-dim`,String(e.dim/100)),t.style.setProperty(`--bg-image-blur`,`${e.blur}px`)):(t.style.removeProperty(`--bg-image`),t.style.removeProperty(`--bg-image-dim`),t.style.removeProperty(`--bg-image-blur`));let n=getComputedStyle(t).getPropertyValue(`--bg-image`).trim();document.body.classList.toggle(dw,e.url!==``||n!==``&&n!==`none`)}function Sw(e){let t=_w(e);Cw=t;try{localStorage.setItem(uw,JSON.stringify(t))}catch{}for(let e of ww)e();xw()}var Cw=null,ww=new Set;function Tw(e){return ww.add(e),()=>{ww.delete(e)}}function Ew(){return Cw||=vw(),Cw}function Dw(){return(0,Q.useSyncExternalStore)(Tw,Ew)}function Ow(){let e=Dw();(0,Q.useEffect)(()=>{xw()},[e]),(0,Q.useEffect)(()=>{let e=()=>xw();return window.addEventListener(xt,e),xw(),()=>window.removeEventListener(xt,e)},[])}var kw=(0,Q.lazy)(()=>As(()=>import(`./TerminalPanel-Da-Xs4Wk.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([6,1,7,3,8,9,10,11,12]),import.meta.url)),Aw=(0,Q.lazy)(()=>As(()=>import(`./SCMPanel-CghgsyBN.js`).then(e=>({default:e.ScmPanel})),__vite__mapDeps([13,1,7,3,8,10]),import.meta.url)),jw=(0,Q.lazy)(()=>As(()=>import(`./DeviceCenter-Bmgr-Bwm.js`).then(e=>({default:e.DeviceCenter})),__vite__mapDeps([14,1,7,3,15,16]),import.meta.url)),Mw=(0,Q.lazy)(()=>As(()=>import(`./DeviceGroups-aeLD2msl.js`).then(e=>({default:e.DeviceGroupCreateDialog})),__vite__mapDeps([15,1,7,3,16]),import.meta.url)),Nw=(0,Q.lazy)(()=>As(()=>import(`./CanvasStudio-DxW7C3Sz.js`).then(e=>({default:e.CanvasStudio})),__vite__mapDeps([17,1,7,3,8,18,19,9,10,20]),import.meta.url)),Pw=(0,Q.lazy)(()=>As(()=>import(`./PiSetupModal-DD8srwBJ.js`).then(e=>({default:e.PiSetupModal})),__vite__mapDeps([21,1,7,3,19,9,10,22]),import.meta.url)),Fw=(0,Q.lazy)(()=>As(()=>import(`./ModelConfigModal-Bp7tfKYh.js`).then(e=>({default:e.ModelConfigModal})),__vite__mapDeps([23,1,7,3,10,22]),import.meta.url)),Iw=(0,Q.lazy)(()=>As(()=>import(`./SettingsModal-BbBe2rYo.js`).then(e=>({default:e.SettingsModal})),__vite__mapDeps([24,1,7,3,16,8,18,19,9,10]),import.meta.url)),Lw=(0,Q.lazy)(()=>As(()=>import(`./BgTasksModal-DSC8ncW3.js`).then(e=>({default:e.BgTasksModal})),__vite__mapDeps([25,1,7,3,10]),import.meta.url)),Rw=(0,Q.lazy)(()=>As(()=>import(`./TuiOverlayModal-CpBKjG6x.js`).then(e=>({default:e.TuiOverlayModal})),__vite__mapDeps([26,1,7,3,9,10,11,12]),import.meta.url)),zw=(0,Q.lazy)(()=>As(()=>import(`./GlobalSearchModal-CMW0xz0P.js`).then(e=>({default:e.GlobalSearchModal})),__vite__mapDeps([27,1,7,3,18,8,19,9,10]),import.meta.url)),Bw=(0,Q.lazy)(()=>As(()=>import(`./FilePreview-CJa27G_Q.js`).then(e=>({default:e.FilePreview})),__vite__mapDeps([28,1,7,3,10]),import.meta.url)),Vw=(0,Q.lazy)(()=>As(()=>import(`./GroupConversation-DoELa83U.js`).then(e=>({default:e.GroupConversation})),__vite__mapDeps([29,1,7,3,8]),import.meta.url));function Hw({notice:e,onDismiss:t}){let n=V(),{locale:r}=Ue(),i=!H(r)&&e.textEn?e.textEn:e.text,[a,o]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(a)return;let n=setTimeout(()=>t(e.id),Zm(e.level));return()=>clearTimeout(n)},[a,e.id,e.level,t]);let s=e.level===`error`?je:e.level===`warning`?He:We;return(0,$.jsxs)(`div`,{className:`notice notice-${e.level}${a?` paused`:``}`,role:`status`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:()=>{window.getSelection?.()?.toString()||t(e.id)},children:[(0,$.jsx)(s,{className:`notice-icon`}),(0,$.jsx)(`span`,{className:`notice-text`,children:i}),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:n(`close`),onClick:n=>{n.stopPropagation(),t(e.id)},children:(0,$.jsx)(R,{})})]})}var Uw=[],Ww=180,Gw=520,Kw=240,qw=e=>`pi-web-ui:${e}-panel-width`;function Jw(e){try{let t=Number(localStorage.getItem(qw(e)));return Number.isFinite(t)&&t>=Ww&&t<=Gw?t:Kw}catch{return Kw}}var Yw=e=>`pi-web-ui:${e}-panel-collapsed`;function Xw(e){try{return localStorage.getItem(Yw(e))===`1`}catch{return!1}}function Zw({side:e,width:t,onResize:n}){let r=V(),i=(0,Q.useCallback)(r=>{r.preventDefault();let i=r.clientX,a=t,o=a,s=t=>{let r=e===`left`?t.clientX-i:i-t.clientX;o=Math.min(Gw,Math.max(Ww,Math.round(a+r))),n(o)},c=()=>{window.removeEventListener(`pointermove`,s),window.removeEventListener(`pointerup`,c),document.body.classList.remove(`panel-resizing`);try{localStorage.setItem(qw(e),String(o))}catch{}};window.addEventListener(`pointermove`,s),window.addEventListener(`pointerup`,c),document.body.classList.add(`panel-resizing`)},[e,t,n]);return(0,$.jsx)(`div`,{className:`resize-handle resize-${e}`,title:r(`dragToResize`),onPointerDown:i,onDoubleClick:()=>n(Kw)})}function Qw({side:e,onClick:t}){let n=V();return(0,$.jsx)(`button`,{type:`button`,className:`panel-rail panel-rail-${e}`,title:n(`expandPanel`),onClick:t,children:e===`left`?(0,$.jsx)(P,{}):(0,$.jsx)(it,{})})}var $w=`pi-web-ui:plugin-path-grants`,eT=e=>e?`${$w}:${e}`:$w;function tT(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function nT(e){try{let t=eT(e);if(localStorage.getItem(t)!==null)return tT(localStorage.getItem(t));if(!e)return[];let n=tT(localStorage.getItem($w));return localStorage.setItem(t,JSON.stringify(n)),n}catch{return[]}}function rT(e,t){try{let n=[...new Set([...nT(t),e])];localStorage.setItem(eT(t),JSON.stringify(n))}catch{}}function iT(){let e=V(),{locale:t}=Ue(),{chat:n,send:r,dismissNotice:i,pushNotice:a,terminal:o}=Ih(),s=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{n.ready&&n.settings&&(s.current||n.settings.quickPhrasesSeeded||(s.current=!0,n.settings.quickPhrases.length===0&&r({type:`set_settings`,quickPhrases:DS[t]??DS.en,quickPhrasesSeeded:!0})))},[n.ready,n.settings,r,t]);let c=n.state?.cwd??``,l=zC(),u=$C(cw());(0,Q.useEffect)(()=>{ZC()},[]),(0,Q.useEffect)(()=>{let t=l?MC(c):``,n=t?`${t} — pi-web-ui`:e(`docTitle`);document.title=u?`[${u}] ${n}`:n},[c,l,u,e]);let[d,f]=(0,Q.useState)([]);(0,Q.useEffect)(()=>(Mt(e=>f(t=>Bv(t,e))),()=>Mt(null)),[]);let[p,h]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{y.current=p!==null,b.current=_},[p,_]);let x=(0,Q.useCallback)((e,t)=>{let n=Tx(t);if(n){h(null),v({file:{path:e,name:t},plugin:n.plugin,declaration:n.declaration});return}v(null),h({path:e,name:t})},[]);(0,Q.useEffect)(()=>(Gc({open:e=>x(e.path,e.name),isOpen:()=>y.current||b.current!==null}),()=>Gc(null)),[x]);let[S,C]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=()=>C(!1);return window.addEventListener(`drop`,e,!0),()=>window.removeEventListener(`drop`,e,!0)},[]);let[w,T]=(0,Q.useState)(()=>new URLSearchParams(window.location.search).get(`view`)===`devices`?`devices`:`chat`),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(t&&typeof t==`object`){if(t.create===!0){k(!0);return}TS({roomId:typeof t.roomId==`string`?t.roomId:void 0,create:t.create===!0,manage:t.manage===!0}),typeof t.roomId==`string`&&!t.manage&&!t.create?(D(t.roomId),T(`chat`)):(D(null),T(`devices`))}};return window.addEventListener(`pi-web-ui:device-group-open`,e),()=>window.removeEventListener(`pi-web-ui:device-group-open`,e)},[]);let A=(e=>!n.tabs||e===`chat`||e===`devices`||n.tabs.includes(e))(w.startsWith(`plugin:`)?`plugins`:w)?w:`chat`,j=(0,Q.useMemo)(()=>n.plugins.filter(e=>!n.settings?.disabledPlugins?.includes(e.id)),[n.plugins,n.settings?.disabledPlugins]),[M,N]=(0,Q.useMemo)(()=>{let r=[];return[xi(ui(n.plugins),{locale:t,t:t=>e(t),disabledPlugins:n.settings?.disabledPlugins??[],layout:n.settings?.uiLayout,diagnostics:r}),r]},[n.plugins,n.settings?.disabledPlugins,n.settings?.uiLayout,t,e]),P=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let e=N.map(e=>`${e.level}:${e.pluginId??``}:${e.entryId??``}:${e.message}`).join(`
|
|
83
|
+
`);if(e!==P.current){P.current=e;for(let e of N){let t=`[ui-slot] ${e.pluginId?`[${e.pluginId}] `:``}`;e.level===`error`?console.error(`${t}${e.message}`):e.level===`warn`?console.warn(`${t}${e.message}`):console.debug(`${t}${e.message}`)}}},[N]);let ee=(0,Q.useMemo)(()=>M[`topbar.primary`].filter(e=>!e.hidden),[M]),F=(0,Q.useMemo)(()=>[...M[`topbar.primary`].filter(e=>e.hidden),...M[`topbar.overflow`]],[M]),re=(0,Q.useMemo)(()=>M[`leftpanel.sessions`].filter(e=>!e.hidden),[M]),I=(0,Q.useMemo)(()=>M[`leftpanel.projects.actions`].filter(e=>!e.hidden),[M]),L=(0,Q.useMemo)(()=>M[`leftpanel.project`].filter(e=>!e.hidden),[M]),ie=(0,Q.useMemo)(()=>M[`leftpanel.running.actions`].filter(e=>!e.hidden),[M]),ae=(0,Q.useMemo)(()=>M[`leftpanel.history.actions`].filter(e=>!e.hidden),[M]),oe=M[`leftpanel.sections`],se=(0,Q.useMemo)(()=>M[`leftpanel.running`].filter(e=>!e.hidden),[M]),ce=(0,Q.useMemo)(()=>M[`leftpanel.history`].filter(e=>!e.hidden),[M]),le=(0,Q.useMemo)(()=>M[`terminal.toolbar`].filter(e=>!e.hidden),[M]),ue=(0,Q.useMemo)(()=>M[`scm.toolbar`].filter(e=>!e.hidden),[M]),de=(0,Q.useMemo)(()=>M[`goalbar.actions`].filter(e=>!e.hidden),[M]),B=(0,Q.useMemo)(()=>M[`chat.header`].filter(e=>!e.hidden),[M]),fe=(0,Q.useMemo)(()=>M[`chat.empty`].filter(e=>!e.hidden),[M]),pe=(0,Q.useMemo)(()=>M[`file.preview.toolbar`].filter(e=>!e.hidden),[M]),me=(0,Q.useMemo)(()=>Object.fromEntries((n.dshPresets?.presets??[]).map(n=>[n.id,Xy(n,t,e).name])),[n.dshPresets,t]),he=(0,Q.useMemo)(()=>M[`notice.actions`].filter(e=>!e.hidden),[M]),ge=(0,Q.useMemo)(()=>M[`sidebar.left`]??[],[M]),U=(0,Q.useMemo)(()=>M[`sidebar.right`]??[],[M]),W=(0,Q.useCallback)((t,n,i)=>{if(t.id===`host:msg-fork`){i?.id&&r({type:`fork_session`,messageId:i.id,position:`before`});return}if(t.id===`host:msg-rollback`){i?.id&&jx({messageId:i.id});return}let o=(t.action??``).trim();if(t.kind===`view`||(!o||o===`view`)&&t.source!==`host`){T(t.view??`plugin:${t.source.startsWith(`plugin:`)?t.source.slice(7):``}`);return}if(!o)return;let s=t.source.startsWith(`plugin:`)?t.source.slice(7):``;Rt(s,o,t.id,{...n===void 0?{}:{value:n},...i===void 0?{}:{target:i},loadBundle:async e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Fm(t,De.current.pluginsEpoch):!1}}).then(t=>{t||a(`info`,e(`pluginUiNoHandler`))})},[e,a]),G=(0,Q.useCallback)(e=>{let t=n.plugins.find(t=>t.id===e.source.slice(7));return t?(0,$.jsx)(ug,{plugin:t,epoch:n.pluginsEpoch,send:r,className:`lp-plugin-page`}):null},[n.plugins,n.pluginsEpoch,r]),_e=(0,Q.useCallback)((t,n)=>{n.action&&Rt(t.pluginId,n.action,n.id,{target:{id:n.id,kind:`plugin-running`,label:n.title},loadBundle:async e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Fm(t,De.current.pluginsEpoch):!1}}).then(t=>{t||a(`info`,e(`pluginUiNoHandler`))})},[e,a]),[K,J]=(0,Q.useState)([]);(0,Q.useEffect)(()=>Om(J),[]);let[ve,Y]=(0,Q.useState)([]);(0,Q.useEffect)(()=>Em(Y),[]);let[ye,be]=(0,Q.useState)(null),[xe,Se]=(0,Q.useState)(null),[Ce,we]=(0,Q.useState)(null),Te=ye?M[`modal.dialog`].find(e=>e.id===ye&&!e.hidden):void 0,Ee=(0,Q.useMemo)(()=>{if(!Te||Te.kind!==`view`)return``;let e=Te.view??``;return e.startsWith(`plugin:`)?e.slice(7):Te.source.startsWith(`plugin:`)?Te.source.slice(7):``},[Te]);(0,Q.useEffect)(()=>{if(!Te||!Ee||K.some(e=>e.info.id===Ee))return;let e=De.current.plugins.find(e=>e.id===Ee);e&&Fm(e,De.current.pluginsEpoch)},[Te,Ee,K,n.pluginsEpoch]),(0,Q.useEffect)(()=>{Sc(r),Cc(j,n.pluginsEpoch),Ac(j,n.pluginsEpoch),wx(j,n.pluginsEpoch),Im(j,n.pluginsEpoch)},[j,n.pluginsEpoch,r]);let De=(0,Q.useRef)(n);De.current=n;let X=(0,Q.useRef)(T);X.current=T;let Oe=(0,Q.useRef)(M);Oe.current=M,(0,Q.useEffect)(()=>(Vt(Kt({send:r,isReady:()=>!!De.current.state,setView:e=>X.current(e),getCwd:()=>De.current.state?.cwd??``,getWorkspaceRoots:()=>De.current.state?.workspaceRoots??[],listSessions:()=>{let e=De.current,t=e.state?.cwd??``;return[...e.conversations.map(e=>({id:e.id,title:e.title,cwd:e.cwd||t,kind:`running`,isStreaming:e.isStreaming})),...(e.elsewhere??[]).filter(e=>!!(e.convId&&e.owner)).map(e=>({id:e.convId,title:e.title,cwd:e.cwd||t,kind:`elsewhere`,owner:e.owner,isStreaming:e.isStreaming})),...e.sessions.map(e=>({id:e.path,title:e.displayName||e.name||e.firstMessage?.trim()||e.path,cwd:t,kind:`history`}))]},getConversationId:()=>De.current.state?.conversationId??null,isConversationBlank:()=>(De.current.state?.messages.length??0)===0,listModels:()=>De.current.models.map(e=>({id:e.id,provider:e.provider,name:e.name,vision:e.vision,reasoning:e.reasoning})),getCurrentModelId:()=>{let e=De.current.state?.model;return e?`${e.provider}/${e.id}`:null},listProjects:()=>De.current.projects.map(e=>e.path),grantedPaths:nT,grantPath:rT,confirm:e=>new Promise(t=>{if(st.current){t(!1);return}let n={path:e.path,resolve:t};st.current=n,ot(n)}),openModal:e=>{let t=String(e??``).trim();if(!t)return!1;let n=Oe.current[`modal.dialog`].find(e=>e.id===t);return!n||n.hidden?!1:(be(t),!0)},closeModal:()=>be(null),pickDirectory:e=>new Promise(t=>{Se({initialPath:e?.initialPath,resolve:t})}),pickModel:e=>new Promise(t=>{we({currentModelId:e?.currentModelId,resolve:t})}),dialogConfirm:e=>new Promise(t=>{if(ut.current){t(!1);return}let n={kind:`confirm`,title:e.title,resolve:t};ut.current=n,lt(n)}),select:e=>new Promise(t=>{if(ut.current){t({ok:!1,error:`busy`});return}let n={kind:`select`,title:e.title,options:e.options,...e.multi?{multi:!0}:{},resolve:t};ut.current=n,ft([]),lt(n)}),input:e=>new Promise(t=>{if(ut.current){t({ok:!1,error:`busy`});return}let n={kind:`input`,title:e.title,...typeof e.placeholder==`string`?{placeholder:e.placeholder}:{},...typeof e.initial==`string`?{initial:e.initial}:{},resolve:t};ut.current=n,gt(e.initial??``),lt(n)}),notifyAction:e=>new Promise(t=>{try{let n=bt.current;bt.current=null,yt(null);try{n?.resolve(null)}catch{}let r={text:e.text,actions:e.actions,resolve:t};bt.current=r,yt(r)}catch{t(null)}}),loadPluginBundle:e=>{let t=De.current.plugins.find(t=>t.id===e);return t?Fm(t,De.current.pluginsEpoch):Promise.resolve(!1)},openFileContextMenu:t=>{let n=String(t.path??``).replace(/\\/g,`/`).replace(/^\/+|\/+$/g,``),i=!n,o=t.kind??(t.path.endsWith(`/`)||i?`dir`:`file`),s=t.label??(n?n.split(`/`).pop()??n:`workspace`),c={id:n,kind:o,label:s},l=o===`file`,u=o===`dir`||i,d=o===`list`,f=(Oe.current[`contextmenu.file`]??[]).map(t=>{if(t.source!==`host`)return u&&t.when?.includes(`file.isFile`)||l&&t.when?.includes(`file.isDir`)?{...t,hidden:!0}:t;switch(t.id){case`host:file-compress`:case`host:file-compress-download`:return d?{...t,hidden:!0}:t;case`host:file-extract`:return l&&eg(s)?t:{...t,hidden:!0};case`host:file-upload`:return u||d?{...t,label:e(`uploadToFolder`)}:{...t,hidden:!0};case`host:file-upload-folder`:return u||d?t:{...t,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:return l?t:{...t,hidden:!0};case`host:file-attach-ref`:return l?t:{...t,hidden:!0};case`host:file-attach-folder`:return u?t:{...t,hidden:!0};case`host:file-reveal`:return d?{...t,hidden:!0}:t;case`host:file-enter`:case`host:file-open-project`:case`host:file-add-root`:return{...t,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:case`host:file-paste`:return u||d?t:{...t,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!d&&!i?t:{...t,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:case`host:file-copy-rel`:return d?{...t,hidden:!0}:t;case`host:file-refresh`:return d?t:{...t,hidden:!0};default:return t}});Pi({x:t.x,y:t.y,slot:`contextmenu.file`,target:c,entries:f,onHostAction:(n,i)=>{if(t.onHostAction){let e=t.onHostAction(n.id,i);if(e!==void 0)return e}switch(n.id){case`host:file-reveal`:r({type:`file_reveal`,path:i.id});break;case`host:file-open-default`:i.kind===`file`&&r({type:`file_open_default`,path:i.id});break;case`host:file-copy-name`:navigator.clipboard?.writeText(i.label??i.id),a(`info`,e(`copied`));break;case`host:file-copy-rel`:navigator.clipboard?.writeText(i.id),a(`info`,e(`copied`));break;case`host:file-copy-path`:{let t=De.current.state?.cwd??``,n=t?`${t.replace(/\\/g,`/`).replace(/\/+$/,``)}/${i.id}`:i.id;navigator.clipboard?.writeText(n),a(`info`,e(`copied`));break}}}})}})),()=>Vt(null)),[r]);let[Ae,je]=(0,Q.useState)(()=>Jw(`left`)),[Me,Ne]=(0,Q.useState)(()=>Jw(`right`)),Pe=(0,Q.useCallback)(e=>je(e),[]),Fe=(0,Q.useCallback)(e=>Ne(e),[]),[Ie,Le]=(0,Q.useState)(()=>Xw(`left`)),[Re,ze]=(0,Q.useState)(()=>Xw(`right`)),Be=(0,Q.useCallback)(()=>{Le(e=>{try{localStorage.setItem(Yw(`left`),e?`0`:`1`)}catch{}return!e})},[]),Ve=(0,Q.useCallback)(()=>{ze(e=>{try{localStorage.setItem(Yw(`right`),e?`0`:`1`)}catch{}return!e})},[]),[He,We]=(0,Q.useState)(null),Ge=(0,Q.useRef)(null),[Ke,qe]=(0,Q.useState)(()=>window.matchMedia(`(max-width: 768px)`).matches);(0,Q.useEffect)(()=>{let e=window.matchMedia(`(max-width: 768px)`),t=e=>qe(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),SS({enabled:Ke&&A===`chat`,open:He,onOpenChange:We,container:Ge,backdropSelector:`.drawer-backdrop.persistent`});let[Je,Ye]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_web_setup_dismissed`)===`1`}catch{return!1}}),Xe=()=>{Ye(!0);try{localStorage.setItem(`pi_web_setup_dismissed`,`1`)}catch{}},[Ze,Qe]=(0,Q.useState)(!1),[$e,et]=(0,Q.useState)(!1),[tt,nt]=(0,Q.useState)(),[rt,it]=(0,Q.useState)(null),[at,ot]=(0,Q.useState)(null),st=(0,Q.useRef)(null),[ct,lt]=(0,Q.useState)(null),ut=(0,Q.useRef)(null),[dt,ft]=(0,Q.useState)([]),[pt,gt]=(0,Q.useState)(``),[_t,yt]=(0,Q.useState)(null),bt=(0,Q.useRef)(null),[xt,St]=(0,Q.useState)(()=>new Set),Ct=(e,t)=>{r({type:`plugin_path_response`,id:e,ok:t}),St(t=>new Set(t).add(e))},Tt=n.pathRequests.find(e=>!xt.has(e.id))??null,[Ot,kt]=(0,Q.useState)(()=>new Set),At=(e,t,n=!1)=>{r({type:`plugin_permission_response`,id:e,ok:t,...n?{remember:!0}:{}}),kt(t=>new Set(t).add(e))},jt=n.permRequests.find(e=>!Ot.has(e.id))??null,Nt=vC(),Ft=OC(),It=!!n.settings?.minimalNewChat&&(n.state?.messages?.length??0)===0&&!n.state?.streamingMessage,[Lt,Bt]=(0,Q.useState)(!1),[Ht,Wt]=(0,Q.useState)(!1),[qt,Jt]=(0,Q.useState)(!1),[Yt,Zt]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!Yt)return;let e=setTimeout(()=>Zt(null),15e3);return()=>clearTimeout(e)},[Yt]);let[Qt,$t]=(0,Q.useState)(null),tn=(0,Q.useRef)(null),nn=(0,Q.useRef)(null),rn=n.state?.sessionId??``,an=(0,Q.useRef)(rn);an.current=rn;let on=(0,Q.useRef)(n.ready);on.current=n.ready,(0,Q.useEffect)(()=>{let e=()=>{let e=es(window.location.hash);if(e){if(e.messageId?$t({sessionId:e.sessionId,messageId:e.messageId}):$t(null),!on.current||!an.current){tn.current=e.sessionId;return}an.current!==e.sessionId&&(nn.current=e.sessionId,T(`chat`),r({type:`switch_session`,path:``,sessionId:e.sessionId}))}};return e(),window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[r]),(0,Q.useEffect)(()=>{let e=nn.current;if(e&&n.notices.some(t=>t.text.includes(e)&&(t.text.includes(`未找到会话`)||t.text.includes(`Session not found`)))&&(nn.current=null,$t(null),rn)){let e=ts({sessionId:rn});window.location.hash!==e&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${e}`)}},[n.notices,rn]),(0,Q.useEffect)(()=>{if(!n.ready||!rn)return;if(tn.current){let e=tn.current;if(tn.current=null,e!==rn){nn.current=e,T(`chat`),r({type:`switch_session`,path:``,sessionId:e});return}}if(nn.current){if(rn===nn.current)nn.current=null;else return}let e=es(window.location.hash),t=e?.sessionId===rn?e.messageId:void 0,i=ts({sessionId:rn,...t?{messageId:t}:{}});window.location.hash!==i&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${i}`)},[n.ready,rn,r]),(0,Q.useEffect)(()=>{let t=t=>{let i=t.detail,a=i?.title||e(`pluginCommandFallback`),s=i?.command;if(!s||!n.ready)return;let c={name:a,command:s,cwd:"${pwd}"},l=n.terminals.find(e=>e.title===a);if(l)o.restart(l.id),r({type:`run_command`,terminalId:l.id,conversationId:l.conversationId,command:c,cols:80,rows:24});else{let e=ht();o.create({id:e,conversationId:n.activeConversationId||n.state?.conversationId||``,title:a,cwd:n.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:c})}T(`terminal`)};window.addEventListener(`pi-web-ui:plugin-run-command`,t);let i=e=>{let t=e.detail;typeof t==`string`&&t&&(T(e=>e===`chat`?e:`chat`),r({type:`switch_conversation`,id:t}),Xt())};return window.addEventListener(`pi-web-ui:switch-conversation`,i),()=>{window.removeEventListener(`pi-web-ui:plugin-run-command`,t),window.removeEventListener(`pi-web-ui:switch-conversation`,i)}},[n,o,r]),(0,Q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),Wt(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let[Z,sn]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_zen_mode`)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{Z?localStorage.setItem(`pi_zen_mode`,`1`):localStorage.removeItem(`pi_zen_mode`)}catch{}},[Z]);let cn=(0,Q.useCallback)(()=>{sn(e=>{let t=!e;return t&&A!==`chat`&&T(`chat`),t})},[A]);mt(()=>Z?(sn(!1),!0):!1,Z),(0,Q.useEffect)(()=>{let e=e=>{let t=e.altKey&&!e.ctrlKey&&!e.metaKey&&e.key.toLowerCase()===`z`,n=(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`;(t||n)&&(e.preventDefault(),cn())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[cn]);let[ln,un]=(0,Q.useState)(AS),[dn,fn]=(0,Q.useState)(ff),{themes:pn,theme:mn,switchTheme:hn,reloadThemes:gn}=vt();Ow(),(0,Q.useEffect)(()=>{try{typeof zt==`function`&&zt(mn??``)}catch{}},[mn]),(0,Q.useEffect)(()=>{try{typeof Ut==`function`&&Ut(t)}catch{}},[t]),(0,Q.useEffect)(()=>{try{typeof Pt==`function`&&Pt(A)}catch{}},[A]),(0,Q.useEffect)(()=>{try{let e=n.state?.model,t=e?`${e.provider}/${e.id}`:null;typeof Gt==`function`&&Gt(t)}catch{}},[n.state?.model?.provider,n.state?.model?.id]),(0,Q.useEffect)(()=>{if(!ct)return;let e=e=>{if(e.key!==`Escape`)return;let t=ut.current;ut.current=null,lt(null);try{if(!t)return;t.kind===`confirm`?t.resolve(!1):t.resolve({ok:!1})}catch{}};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[ct]),(0,Q.useEffect)(()=>{if(!_t)return;let e=setTimeout(()=>{let e=bt.current;bt.current=null,yt(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[_t]);let _n=(0,Q.useRef)(null),vn=(0,Q.useRef)(null),yn=(0,Q.useRef)(n.state?.messages);yn.current=n.state?.messages;let bn=(0,Q.useRef)(new Set),xn=(0,Q.useRef)(new Set),Sn=(0,Q.useRef)(new Set),Cn=(0,Q.useRef)(0),wn=(0,Q.useRef)(!1),Tn=(0,Q.useRef)(n.terminals);(0,Q.useEffect)(()=>{jS(ln)},[ln]),(0,Q.useEffect)(()=>{pf(dn)},[dn]),(0,Q.useEffect)(()=>{let e=Tn.current;Tn.current=n.terminals;for(let t of n.terminals){let n=t.command?.command??``;e.find(e=>e.id===t.id)?.running&&!t.running&&(n.startsWith(`pi remove `)?r({type:`extensions_reload`}):n.startsWith(`pi-web-ui install `)||n.startsWith(`pi-web-ui uninstall `)?r({type:`plugins_reload`}):n.startsWith(`npm i -g `)&&(r({type:`extensions_reload`}),r({type:`plugins_reload`}),r({type:`check_updates_all`,force:!0}),r({type:`check_engines`,force:!0})))}},[n.terminals,r]),(0,Q.useEffect)(()=>{let t=n.state?.conversationId??null,r=lw(_n.current,t,n.state?.isStreaming??!1,n.conversations,vn.current,!!n.state?.completionPending||!!n.state?.queue?.steering.length||!!n.state?.queue?.followUp.length);if(_n.current=r.nextMap,vn.current=t,r.startCue&&(RS(`start`,ln),cC(e(`notifyStartTitle`),e(`notifyStartBody`),`start`)),r.finishedConvs.length>0){r.finishedConvs.some(e=>!e.isSubagent&&ln.done)?RS(`done`,ln):r.finishedConvs.some(e=>e.isSubagent)&&RS(`subagentDone`,ln);let t=r.finishedConvs.find(e=>e.isActive);if(t&&(cC(e(`notifyDoneTitle`),e(`notifyDoneBody`),t.isSubagent?`subagentDone`:`done`),dn.enabled)){if(dn.readReplies){if(!dn.streamReplies){let t=vf(yn.current);t?kf(t,dn):dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceDone`),dn)}}else dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceDone`),dn)}for(let t of r.finishedConvs.filter(e=>!e.isActive)){let n=t.title?`${t.title}:${e(`notifyDoneBody`)}`:e(`notifyDoneBody`);cC(e(`notifyDoneTitle`),n,t.isSubagent?`subagentDone`:`done`)}!t&&dn.enabled&&dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceDone`),dn)}},[n.state?.conversationId,n.state?.isStreaming,n.state?.completionPending,n.state?.queue,n.conversations,ln,dn,e]);let En=(0,Q.useRef)(null),Dn=(0,Q.useRef)(null),On=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let e=n.state?.isStreaming??!1,t=n.state?.conversationId;if(!(dn.enabled&&dn.readReplies&&dn.streamReplies)||!e){if(En.current){let e=yn.current,t=Array.isArray(e)&&e.length>0?e[e.length-1]:null;if(t&&t.role===`assistant`&&Dn.current){let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
84
|
+
`);Dn.current.flush(e)}En.current.finish(),En.current=null,Dn.current=null,On.current=0}return}let r=n.state?.messages,i=Array.isArray(r)&&r.length>0?r[r.length-1]:null;if(!i||i.role!==`assistant`)return;let a=Date.now();if(a-On.current<150)return;if(On.current=a,!En.current){let e=Mf(dn,t);En.current=e,Dn.current=new _f(t=>{e.push(t)})}let o=(i.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
85
|
+
`);Dn.current?.feed(o)},[n.state?.messages,n.state?.isStreaming,n.state?.conversationId,dn]),(0,Q.useEffect)(()=>{let t=n.dialog?.id??null;if(t!==null&&!bn.current.has(t)){if(bn.current.add(t),bn.current.size>64){let e=bn.current.values().next().value;e!==void 0&&bn.current.delete(e)}RS(`question`,ln),cC(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),dn.enabled&&dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceQuestion`),dn)}},[n.dialog,ln,dn,e]),(0,Q.useEffect)(()=>{let t=n.question?.id??null,r=n.remoteQuestion?`${n.remoteQuestion.owner}:${n.remoteQuestion.id}`:null,i=!1;t!==null&&!xn.current.has(t)&&(xn.current.add(t),i=!0),r!==null&&!xn.current.has(r)&&(xn.current.add(r),i=!0);for(let e of n.conversations){if(!e.hasQuestion)continue;let n=e.questionId?`q:${e.questionId}`:`conv-q:${e.id}`;xn.current.has(n)||(xn.current.add(n),e.questionId&&xn.current.add(e.questionId),t!==e.questionId&&(i=!0))}if(xn.current.size>64){let e=xn.current.values().next().value;e!==void 0&&xn.current.delete(e)}i&&(RS(`question`,ln),cC(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),dn.enabled&&dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceQuestion`),dn))},[n.question,n.remoteQuestion,n.conversations,ln,dn,e]),(0,Q.useEffect)(()=>{let t=n.approval,r=t?.id??null;if(r!==null&&!Sn.current.has(r)){if(Sn.current.add(r),Sn.current.size>64){let e=Sn.current.values().next().value;e!==void 0&&Sn.current.delete(e)}RS(`approval`,ln);let n=typeof t?.toolName==`string`?t.toolName:``;cC(e(`notifyApprovalTitle`),n?e(`notifyApprovalBodyTool`,{tool:n}):e(`notifyApprovalBody`),`approval`),dn.enabled&&dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceApproval`),dn)}},[n.approval,ln,dn,e]),(0,Q.useEffect)(()=>{let t=[...n.notices].reverse().find(e=>e.level===`error`);t&&t.id!==Cn.current&&(Cn.current=t.id,RS(`error`,ln),cC(e(`notifyErrorTitle`),e(`notifyErrorBody`),`error`),dn.enabled&&dn.announce&&!YS(nC())&&kf(e(`ttsAnnounceError`),dn))},[n.notices,ln,dn,e]);let kn=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{let e=n.state?.messages??[];for(let t of e){if(t.toolName!==`live_preview`||kn.current.has(t.id))continue;kn.current.add(t.id);let e=``;for(let n of t.content??[]){if(n.type!==`text`)continue;let t=/🔗 已自动在浏览器打开\]\((\/(?!\/)[^)\s]+)\)/.exec(n.text??``);if(t?.[1]){e=t[1];break}}if(!e)continue;let n=null;try{let t=new URL(q(e),window.location.href);t.origin===window.location.origin&&document.hasFocus()&&(n=window.open(t.href,`_blank`,`noopener`))}catch{n=null}n||a(`info`,e)}},[n.state?.messages,a]);let jn=(e,t,n,r=!1,i,a=!1)=>{let o=`${e}|${n}|${i?`${i.start}-${i.end}`:``}`;f(a=>a.some(e=>`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`===o)?a:[...a,{path:e,name:t,mode:n,isDir:r,...i?{lines:i}:{}}]);let s=n===`page`||n===`canvas`?t:e;!a&&s&&Dt(`@${s} `)},Mn=e=>{let t=``;f(n=>n.filter(n=>{let r=n.key?n.key===e:n.mode===`conversation`?`conv|${n.conversationId??``}|${n.sessionPath??``}`===e:n.path===e;return r&&!t&&(t=n.mode===`page`||n.mode===`conversation`||n.mode===`canvas`?n.name:n.path),!r})),t&&Et(`@${t}`)},Nn=(0,Q.useCallback)(e=>(!e.type.startsWith(`list_`)&&!e.type.startsWith(`get_`)&&We(null),(e.type===`new_chat`||e.type===`switch_conversation`||e.type===`switch_session`)&&(D(null),T(e=>e===`chat`?e:`chat`),Xt()),r(e)),[r]),Pn=(0,Q.useRef)(new Set),Fn=n.activeConversationId||n.state?.conversationId||``;(0,Q.useEffect)(()=>{let t=n.conversations.filter(e=>e.hasQuestion),r=new Set(t.map(e=>e.id)),i=new Set(t.map(e=>e.questionId).filter(Boolean));for(let e of Pn.current)i.has(e)||Pn.current.delete(e);for(let n of t){let t=`question-${n.id}`;if(n.id===Fn){ux(t,{silent:!0});continue}n.questionId&&Pn.current.has(n.questionId)||lx({id:t,type:`question`,title:n.title||e(`chat`),message:n.questionTitle||e(`waitingQuestionBadge`),persistent:!0,dismissible:!0,data:{conversationId:n.id,questionId:n.questionId},onClose:()=>{n.questionId&&Pn.current.add(n.questionId)},onClick:()=>{Nn({type:`switch_conversation`,id:n.id}),ux(t,{silent:!0})}})}dx(e=>{let t=e.data?.conversationId;return t?!r.has(t)||t===Fn:!1},{silent:!0})},[n.conversations,Fn,Nn,e]);let In=en(`chatUploadMaxMb`),[Ln,Rn]=(0,Q.useState)({}),zn=(0,Q.useRef)(0),Bn=(0,Q.useRef)(0),Vn=(0,Q.useRef)(0),Hn=(0,Q.useCallback)(t=>{let r=Date.now();n.state?.model&&!n.state.model.vision&&r-Vn.current>1e4&&(Vn.current=r,a(`warning`,e(`imageNotSupported`)));let i=`paste-${++Bn.current}`;f(e=>[...e,{path:``,key:i,name:t.name,imageData:t.data,mimeType:t.mimeType}])},[n.state?.model,a,e]),Un=(0,Q.useCallback)(async t=>{for(let n of t){if(n.size>In*1024*1024){a(`warning`,e(`fileTooLarge`,{name:n.name,size:In}));continue}let t=String(++zn.current);Rn(e=>({...e,[t]:{name:n.name}}));try{let t=await nf(n);t?Hn(t):a(`error`,e(`imageLoadFailed`,{name:n.name}))}catch{a(`error`,e(`imageLoadFailed`,{name:n.name}))}finally{Rn(e=>{let n={...e};return delete n[t],n})}}},[Hn,a,e,In]),Wn=In*1024*1024,Gn=(0,Q.useRef)(0),Kn=(0,Q.useCallback)(async t=>{if(t.size>Wn){a(`warning`,e(`fileTooLarge`,{name:t.name,size:Wn/1024/1024}));return}let n=String(++zn.current);Rn(e=>({...e,[n]:{name:t.name,percent:0}}));let r;try{r=(await new Promise((e,r)=>{let i=new FileReader;i.onprogress=e=>{e.lengthComputable&&Rn(r=>({...r,[n]:{name:t.name,percent:Math.round(e.loaded/e.total*100)}}))},i.onload=()=>e(i.result),i.onerror=()=>r(i.error??Error(`read failed`)),i.onabort=()=>r(Error(`read aborted`)),i.readAsDataURL(t)})).replace(/^data:[^;]*;base64,/,``)}catch{a(`error`,e(`fileLoadFailed`,{name:t.name}));return}finally{Rn(e=>{let t={...e};return delete t[n],t})}let i=`upload-${++Gn.current}`;f(e=>[...e,{path:``,key:i,name:t.name,fileData:r,size:t.size,mimeType:t.type||void 0}])},[Wn,a,e]),qn=(0,Q.useCallback)(async e=>{for(let t of e)tf(t.type)?await Un([t]):await Kn(t)},[Un,Kn]),Jn=(0,Q.useCallback)((e,t,n)=>{r({type:`edit_message`,messageId:e,text:t,attachments:n})},[r]),Yn=(0,Q.useCallback)((e,t,n,i)=>{r({type:`queue_remove`,kind:e,text:t,index:n,id:i})},[r]),[Xn,Zn]=(0,Q.useState)([]),Qn=(0,Q.useRef)(0),$n=(0,Q.useCallback)((e,t,n,i)=>{r({type:`queue_remove`,kind:e,text:t,index:n,id:i}),Qn.current+=1;let a=_s(t),o={text:a.text,seq:Qn.current};if(a.quotes.length&&f(e=>Bv(e,a.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:ht()})))),a.attachments?.length){let e=a.attachments.filter(e=>e.type!==`vision-bridge`).map(e=>({path:e.path||e.url||``,name:e.name,mode:e.type===`page`?`page`:e.type===`canvas`?`canvas`:e.type===`conversation`?`conversation`:e.lines?`lines`:`reference`,lines:e.lines,key:ht()}));e.length&&f(t=>Bv(t,e))}Zn(e=>[...e.slice(-9),o])},[r]),er=(0,Q.useCallback)(()=>Qe(!0),[]),tr=(0,Q.useCallback)(()=>f([]),[]);yx(n.state?.sessionId??``,tr);let nr=(0,Q.useCallback)(Mn,[]),rr=Un,ir=qn,ar=(0,Q.useCallback)((e,t)=>r({type:`search_files`,reqId:e,query:t}),[r]),or=(0,Q.useCallback)(e=>jn(e.path,e.name,e.mode??`reference`,e.isDir??!1,e.lines,e.silent??!1),[]),sr=n.state?.model,cr=n.state?.thinkingLevel,lr=n.state?.availableThinkingLevels,ur=(0,Q.useMemo)(()=>sr?{model:sr,thinkingLevel:cr??`off`,availableThinkingLevels:lr??[]}:null,[sr,cr,lr]),dr=(0,Q.useCallback)(()=>!n.ready||n.terminals.length!==0?!1:(o.create({id:ht(),conversationId:n.activeConversationId||n.state?.conversationId||``,title:e(`terminalTitle`,{n:1}),cwd:n.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null}),!0),[n.ready,n.state?.cwd,n.terminals.length,e,o]);return(0,Q.useEffect)(()=>{if(wn.current){if(A!==`terminal`||n.terminals.length!==0){wn.current=!1;return}dr()&&(wn.current=!1)}},[n.terminals.length,dr,A]),(0,$.jsxs)(`div`,{className:`app${Z?` zen-mode`:``}`,"data-pi-anchor":`app`,onDragOver:e=>{Array.from(e.dataTransfer?.types??[]).includes(`Files`)&&(e.preventDefault(),C(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||C(!1)},onDrop:t=>{if(C(!1),!Array.from(t.dataTransfer?.types??[]).includes(`Files`))return;t.preventDefault();let n=Array.from(t.dataTransfer?.files??[]);if(n.length===0){a(`warning`,e(`foldersNotSupported`));return}let r=n.filter(e=>tf(e.type)),i=n.filter(e=>!tf(e.type));r.length>0&&Un(r),i.length>0&&qn(i)},children:[Z&&(0,$.jsxs)(`button`,{type:`button`,className:`zen-exit-pill`,onClick:cn,title:e(`zenModeExitTip`),"aria-label":e(`zenModeExit`),children:[(0,$.jsx)(ne,{}),(0,$.jsx)(`span`,{children:e(`zenModeExit`)})]}),S&&(0,$.jsx)(`div`,{className:`app-drop-overlay`,"aria-hidden":!0,children:(0,$.jsxs)(`span`,{children:[`📎 `,e(`dropHereToAttach`)]})}),(0,$.jsx)(co,{chat:n,terminal:o,view:A,plugins:j,uiPrimary:ee,uiOverflow:F,uiContextTopbar:M[`contextmenu.topbar`],onUiAction:W,zenMode:Z,onToggleZenMode:cn,onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:()=>{nt(void 0),et(!0)},onManagePlugins:()=>{nt(`plugins`),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onOpenIconEdit:()=>Jt(!0),onOpenSandboxModal:()=>it(`create`),themes:pn,theme:mn,onThemeChange:hn,reloadThemes:gn}),qt&&(0,$.jsx)(vx,{slots:M,layout:n.settings?.uiLayout,exclude:ni,onClose:()=>Jt(!1)}),n.protocolMismatch&&(0,$.jsxs)(`div`,{className:`protocol-banner`,children:[`⚠ `,e(`protocolMismatch`)]}),(0,$.jsxs)(`div`,{className:`notices`,children:[n.notices.map(e=>(0,$.jsx)(Hw,{notice:e,onDismiss:i},e.id)),_t&&(0,$.jsxs)(`div`,{className:`notice notice-info`,role:`status`,children:[(0,$.jsx)(`span`,{className:`notice-text`,children:_t.text}),_t.actions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let t=bt.current;bt.current=null,yt(null);try{t?.resolve(e.id)}catch{}},children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:e(`close`),onClick:()=>{let e=bt.current;bt.current=null,yt(null);try{e?.resolve(null)}catch{}},children:(0,$.jsx)(R,{})})]}),he.length>0&&(0,$.jsx)(`div`,{className:`notice-actions`,role:`toolbar`,children:he.map(e=>e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`btn btn-slot notice-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>W(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-slot`,title:e.hint??e.label,onClick:()=>W(e),children:[e.icon?`${e.icon} `:``,e.badge??e.label]},e.id))})]}),(0,$.jsx)(O_,{currentModelId:sr?`${sr.provider}/${sr.id}`:null,children:(0,$.jsxs)(`div`,{ref:Ge,className:`layout`,style:{"--left-w":`${Ae}px`,"--right-w":`${Me}px`},children:[Ke?(0,$.jsx)(`div`,{className:`drawer-backdrop persistent${He?` on`:``}`,onClick:()=>We(null)}):He&&(0,$.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>We(null)}),(0,$.jsx)(kb,{side:`left`,items:ge,chat:n,view:A,plugins:j,dropdownProps:{theme:mn,themes:pn,onThemeChange:hn,reloadThemes:gn},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:e=>{nt(e),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onUiAction:W,uiContextTopbar:M[`contextmenu.topbar`],onThemeToggle:()=>hn(mn===`light`?null:`light`),onSoundToggle:()=>un({...ln,enabled:!ln.enabled}),zenMode:Z,onToggleZenMode:cn}),(0,$.jsxs)(`div`,{className:`view-pane ${A===`chat`?``:`hidden`}`,children:[!Ke&&Ie&&(0,$.jsx)(Qw,{side:`left`,onClick:Be}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-left ${He===`left`?`open`:``}${Ke?``:Ie?` hidden`:``}`,children:(0,$.jsx)($h,{collapsible:!Ke,onToggleCollapse:Be,panelSend:Nn,active:!Ke||He===`left`,sessionFile:E?null:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,pathCompletions:n.pathCompletions,activeConversationId:E?``:n.activeConversationId,activeGroupId:E,uiContextSession:M[`contextmenu.session`],uiLeftSessions:re,uiContextProject:M[`contextmenu.project`],uiProjectsActions:I,uiLeftProject:L,uiRunningActions:ie,uiHistoryActions:ae,uiSections:oe,renderPluginSectionBody:G,uiLeftRunning:se,uiLeftHistory:ce,uiPluginRunning:n.pluginPanelGroups,onPluginRunningAction:_e,onUiAction:W,presetNames:me,transition:n.transition,onOpenSandboxModal:()=>it(`create`)})}),!Ke&&!Ie&&(0,$.jsx)(Zw,{side:`left`,width:Ae,onResize:Pe}),(0,$.jsx)(`main`,{className:`${Nt?`main wide-chat`:`main`}${Ft?` hide-model-row`:``}${n.transition&&!n.transition.previewMessages?.length?` main-transitioning`:``}${It?` main-minimal-empty`:``}`,children:E?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Vw,{roomId:E,active:A===`chat`,onBack:()=>D(null)},E)}):(0,$.jsxs)($.Fragment,{children:[n.transition&&(0,$.jsxs)(`div`,{className:`workspace-transition-bar phase-${n.transition.phase}`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`div`,{className:`workspace-transition-track`,children:(0,$.jsx)(`div`,{className:`workspace-transition-fill`,style:{width:`${Math.min(100,Math.max(8,n.transition.progress))}%`}})}),(0,$.jsxs)(`div`,{className:`workspace-transition-pill`,children:[(0,$.jsx)(`span`,{className:`workspace-transition-spinner`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`workspace-transition-text`,children:!H(t)&&n.transition.textEn?n.transition.textEn:n.transition.text}),(0,$.jsxs)(`span`,{className:`workspace-transition-pct`,children:[n.transition.progress,`%`]})]})]}),B.length>0&&(0,$.jsx)(`div`,{className:`chat-header`,role:`toolbar`,children:P_(B,W)}),n.state?(0,$.jsxs)($.Fragment,{children:[n.state.sandbox&&(0,$.jsxs)(`div`,{className:`sandbox-banner`,role:`region`,"aria-label":n.state.sandbox.name,children:[(0,$.jsxs)(`div`,{className:`sandbox-banner-info`,children:[(0,$.jsxs)(`span`,{className:`sandbox-banner-title`,children:[(0,$.jsx)(An,{className:`sandbox-banner-icon`,"aria-hidden":!0}),e(`sandboxBannerTitle`,{name:n.state.sandbox.name}),(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${n.state.sandbox.ephemeral?`ephemeral`:`permanent`}`,children:n.state.sandbox.ephemeral?e(`sandboxBadgeEphemeral`):e(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`sandbox-banner-desc`,children:n.state.sandbox.sourcePath?e(`sandboxBannerSourceDesc`,{source:n.state.sandbox.sourcePath}):e(`sandboxBannerBlankDesc`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-banner-actions`,children:[n.state.sandbox.ephemeral&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPersistTip`),onClick:()=>r({type:`persist_sandbox`,path:n.state?.sandbox?.path}),children:[(0,$.jsx)(ke,{"aria-hidden":!0}),` `,e(`sandboxActionPersist`)]}),n.state.sandbox.sourcePath&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn primary`,title:e(`sandboxActionApplySourceTip`),onClick:()=>it(`apply`),children:[(0,$.jsx)(z,{"aria-hidden":!0}),` `,e(`sandboxActionApplySource`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPromoteTip`),onClick:()=>it(`promote`),children:[(0,$.jsx)(m,{"aria-hidden":!0}),` `,e(`sandboxActionPromote`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionResetTip`),onClick:()=>{let t=n.state?.sandbox;t&&window.confirm(e(`sandboxActionResetConfirm`,{name:t.name}))&&r({type:`reset_sandbox`,path:t.path})},children:[(0,$.jsx)(te,{"aria-hidden":!0}),` `,e(`sandboxActionReset`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn danger`,title:e(`sandboxActionDestroyTip`),onClick:()=>{let t=n.state?.sandbox;t&&window.confirm(e(`sandboxActionDestroyConfirm`,{name:t.name}))&&r({type:`destroy_sandbox`,path:t.path})},children:[(0,$.jsx)(g,{"aria-hidden":!0}),` `,e(`sandboxActionDestroy`)]})]})]}),n.state.worktree&&(0,$.jsx)(hb,{worktree:n.state.worktree,onRefresh:()=>r({type:`refresh_worktrees`}),onSwitch:e=>r({type:`switch_worktree`,path:e}),onRemove:(e,t)=>r({type:`remove_worktree`,path:e,force:t})}),n.state.isEphemeral&&(0,$.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,$.jsxs)(`span`,{children:[`🎭 `,e(`ephemeralBannerText`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>r({type:`persist_conversation`,id:Fn}),children:[`💾 `,e(`saveEphemeral`)]})]}),(0,$.jsx)(Fv,{uiMessageActions:M[`message.actions`],uiContextMessage:M[`contextmenu.message`],uiContextToolCall:M[`contextmenu.toolcall`],uiToolCardFooter:M[`tool.card.footer`],uiChatEmpty:fe,onUiAction:W,preview:!!n.transition?.previewMessages?.length,state:n.transition?.previewMessages?.length?{...n.state,conversationId:n.transition.target,sessionFile:void 0,historyStart:0,historyTotal:n.transition.previewMessages.length,messages:n.transition.previewMessages,streamingMessage:null,isStreaming:!1,pendingQuestion:null,pendingApproval:null}:n.state,liveOutputs:n.liveOutputs,toolStatuses:n.toolStatuses,onEdit:Jn,onKillBash:()=>{let e=n.state?.conversationId;e&&!n.transition&&r({type:`abort_bash`,conversationId:e})},onRetry:()=>{if(r({type:`retry_last`})){let e=n.state?.model;e&&Mo(`${e.provider}/${e.id}`)}},onRemoveQueued:Yn,onRecallQueued:$n,thinkingWrap:n.settings?.thinkingWrap??!0,toolsWrap:n.settings?.toolsWrap??!0,toolImages:n.settings?.toolImagesEnabled??!0,keepRecent:n.settings?.keepRecentMessages,reversePagination:n.settings?.reversePagination??!1,minimalNewChat:n.settings?.minimalNewChat??!1,jumpTarget:Yt,onJumpDone:()=>Zt(null),urlJumpMessageId:Qt&&Qt.sessionId===n.state.sessionId?Qt.messageId:null,onUrlJumpDone:()=>$t(null)},n.transition?.previewMessages?.length?n.transition.target:n.state.conversationId??`boot`)]}):(0,$.jsx)(`div`,{className:`boot-wait`,children:n.ready?e(`loadingSession`):e(`connectingServer`)}),n.settings?.goalModeEnabled!==!1&&(0,$.jsx)(`div`,{className:`goalbar-slot`,children:(0,$.jsx)(ub,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId,uiGoalbarActions:de,onUiAction:W})}),(0,$.jsx)(nx,{onAction:(e,t,n)=>W(e,n,t)}),n.dialog&&(0,$.jsx)(Fb,{dialog:n.dialog}),ct&&(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":ct.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),ct.title&&(0,$.jsx)(`span`,{className:`dialog-title`,children:ct.title}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.kind===`confirm`?e.resolve(!1):e?.resolve({ok:!1})}catch{}},children:`✕`})]}),ct.kind===`select`&&(0,$.jsxs)(`div`,{className:`dialog-options`,children:[(ct.options??[]).map((e,t)=>{let n=ct.multi?dt.includes(t):!1;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${n?`sel`:``}`,title:e.description,onClick:()=>{if(ct.multi){ft(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);return}let n=ut.current;ut.current=null,lt(null);try{n?.resolve({ok:!0,selected:[e.label]})}catch{}},children:[e.label,e.description&&(0,$.jsx)(`span`,{className:`dialog-hint`,children:e.description})]},t)}),(ct.options??[]).length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:e(`noOptions`)}),ct.multi&&(0,$.jsx)(`div`,{className:`dialog-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current,t=(e?.options??[]).filter((e,t)=>dt.includes(t)).map(e=>e.label);ut.current=null,lt(null);try{e?.resolve({ok:!0,selected:t})}catch{}},children:e(`ok`)})})]}),ct.kind===`confirm`&&(0,$.jsx)(`div`,{className:`dialog-body`,children:(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve(!1)}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve(!0)}catch{}},children:e(`ok`)})]})}),ct.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-body`,children:[(0,$.jsx)(`input`,{className:`dialog-input`,value:pt,placeholder:ct.placeholder||e(`inputPlaceholder`),autoFocus:!0,onChange:e=>gt(e.target.value),onKeyDown:e=>{if(e.key===`Enter`&&!e.nativeEvent.isComposing){let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!0,value:pt})}catch{}}}}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!1})}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ut.current;ut.current=null,lt(null);try{e?.resolve({ok:!0,value:pt})}catch{}},children:e(`ok`)})]})]})]}),(0,$.jsx)($b,{questions:Rb(n.questionQueue,n.question,n.remoteQuestion),activeConversationId:Fn,mode:n.settings?.questionPresentation??`queue`}),(0,$.jsx)(Ix,{approvals:n.approvals,activeConversationId:Fn,mode:n.settings?.toolApprovalPresentation??`all`}),(0,$.jsx)(zx,{plan:n.activeConversationId&&n.state?.conversationId!==n.activeConversationId?null:n.state?.plan}),Object.entries(Ln).map(([t,n])=>(0,$.jsxs)(`div`,{role:`status`,children:[n.percent===void 0?e(`uploadPreparing`,{name:n.name}):e(`uploadReading`,{name:n.name,percent:n.percent}),(0,$.jsx)(`progress`,{max:100,value:n.percent,"aria-label":n.name})]},t)),(0,$.jsx)(lb,{composerLeading:M[`composer.leading`],composerActions:M[`composer.actions`],onUiAction:W,streaming:n.state?.isStreaming??!1,planMode:n.state?.planMode??!1,messages:n.state?.messages??Uw,slashCommands:n.slashCommands,modelState:ur,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,defaultModel:n.defaultModel??void 0,attachments:d,onRemoveAttachment:nr,onAddImageFiles:rr,onAddLocalFiles:ir,onAddPathAttachment:or,fileSearch:n.fileSearch,onSearchFiles:ar,onNotice:a,onManageModels:er,onSent:tr,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:!Z&&(n.settings?.quickPhrasesEnabled??!0)&&(!n.settings?.minimalNewChat||(n.state?.messages?.length??0)>0||!!n.state?.streamingMessage),recallDrafts:Xn,dshPermCurrent:n.state?.permission??null,dshPermOptions:n.dshPermission?.options??void 0,dshPermDefault:n.dshPermission?.defaultPreset,dshPreset:n.state?.agentPreset??null,dshPresets:n.dshPresets?.presets??void 0,dshPresetDefault:n.dshPresets?.defaultPreset,dshBlank:(n.state?.messages?.length??0)===0,conversationId:n.activeConversationId||n.state?.conversationId||``,sessionDraft:n.state?.draft??null,sessionId:n.state?.sessionId??``,preserveDraftAcrossConversations:n.settings?.preserveDraftAcrossConversations??!1})]})}),!Ke&&!Re&&(0,$.jsx)(Zw,{side:`right`,width:Me,onResize:Fe}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-right ${He===`right`?`open`:``}${Ke?``:Re?` hidden`:``}`,children:(0,$.jsx)(Ag,{collapsible:!Ke,onToggleCollapse:Ve,panelSend:Nn,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(e,t,n,r)=>{We(null),jn(e,t,n,r)},onPreview:(e,t)=>{We(null),x(e,t)},onNotice:(e,t)=>a(e,t),uiRightPanelTabs:M[`rightpanel.tabs`],uiContextFile:M[`contextmenu.file`],plugins:j,pluginsEpoch:n.pluginsEpoch,send:r})}),!Ke&&Re&&(0,$.jsx)(Qw,{side:`right`,onClick:Ve})]}),(0,$.jsx)(`div`,{className:`view-pane ${A===`terminal`?``:`hidden`}`,children:(0,$.jsx)(cS,{active:A===`terminal`,children:(0,$.jsx)(kw,{chat:n,terminal:o,uiTerminalToolbar:le,onUiAction:W})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`git`?``:`hidden`}`,children:(0,$.jsx)(cS,{active:A===`git`,children:(0,$.jsx)(Aw,{chat:n,terminal:o,active:A===`git`,onSwitchToTerminal:()=>T(`terminal`),uiScmToolbar:ue,onUiAction:W})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`canvas`?``:`hidden`}`,children:(0,$.jsx)(cS,{active:A===`canvas`,children:(0,$.jsx)(Nw,{send:r,active:A===`canvas`,models:n.models,defaultModel:n.defaultModel,installedSkills:n.settings?.skills,projects:n.projects,workspaceRoots:n.state?.workspaceRoots??[],pathCompletions:n.pathCompletions,currentCwd:n.state?.cwd||`.`})})}),(0,$.jsx)(`div`,{className:`view-pane ${A===`devices`?``:`hidden`}`,children:(0,$.jsx)(cS,{active:A===`devices`,children:(0,$.jsx)(jw,{pathCompletions:n.pathCompletions})})}),K.map(e=>{let t=`plugin:${e.info.id}`;return(0,$.jsx)(`div`,{className:`view-pane ${A===t?``:`hidden`}`,children:(0,$.jsx)(ex,{entry:e})},e.info.id)}),A.startsWith(`plugin:`)&&!K.some(e=>`plugin:${e.info.id}`===A)&&(0,$.jsx)(tx,{pluginId:A.slice(7),info:n.plugins.find(e=>`plugin:${e.id}`===A),epoch:n.pluginsEpoch,failed:ve.includes(A.slice(7))}),(0,$.jsx)(kb,{side:`right`,items:U,chat:n,view:A,plugins:j,dropdownProps:{theme:mn,themes:pn,onThemeChange:hn,reloadThemes:gn},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenPanel:We,onOpenSettings:e=>{nt(e),et(!0)},onOpenBgTasks:()=>Bt(!0),onOpenGlobalSearch:()=>Wt(!0),onUiAction:W,uiContextTopbar:M[`contextmenu.topbar`],onThemeToggle:()=>hn(mn===`light`?null:`light`),onSoundToggle:()=>un({...ln,enabled:!ln.enabled}),zenMode:Z,onToggleZenMode:cn})]})}),(0,$.jsx)(_b,{chat:n,bottombarItems:M.bottombar,onUiAction:W,onOpenSettings:()=>{nt(void 0),et(!0)},onViewChange:e=>{wn.current=e===`terminal`&&n.terminals.length===0,wn.current&&dr()&&(wn.current=!1),T(e),We(null)},onOpenGlobalSearch:()=>Wt(!0),onOpenBgTasks:()=>Bt(!0)}),p&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Bw,{file:p,content:n.fileContent,onAddLines:(e,t,n,r)=>jn(e,t,`lines`,!1,{start:n,end:r}),onAttach:(e,t,n)=>jn(e,t,n),onClose:()=>h(null),uiFilePreviewToolbar:pe,onUiAction:W})}),_&&(0,$.jsx)(lS,{file:_.file,plugin:_.plugin,declaration:_.declaration,epoch:n.pluginsEpoch,send:r,onClose:()=>v(null),onFallback:()=>{v(null),h(_.file)}}),n.ready&&n.state&&n.state.piConfigured===!1&&!Je&&!Ze&&!wt()&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Pw,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,installResult:n.installResult,onClose:Xe})}),Ze&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Fw,{providers:n.modelsConfig,providerStatus:n.providers,providerKeys:n.providerKeys,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,fetchModelsResult:n.fetchModelsResult,testModelConnectionResult:n.testModelConnectionResult,enrichModelsResult:n.enrichModelsResult,enrichModelsProgress:n.enrichModelsProgress,refreshBuiltinResult:n.refreshBuiltinResult,refreshProviderResult:n.refreshProviderResult,appendBuiltinResult:n.appendBuiltinResult,cloneProviderResult:n.cloneProviderResult,defaultModel:n.defaultModel,onClose:()=>Qe(!1)})}),$e&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Iw,{chat:n,terminal:o,initialSection:tt,onSwitchToTerminal:()=>T(`terminal`),onClose:()=>et(!1),onOpenIconEdit:()=>Jt(!0),onOpenManageModels:()=>{et(!1),Qe(!0)},sound:ln,onSoundChange:un,tts:dn,onTtsChange:fn})}),Lt&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Lw,{servers:n.bgServers,plugins:n.plugins,epoch:n.pluginsEpoch,send:r,onUiAction:W,autoCleanupMin:n.settings?.bgAutoCleanupMin??0,onClose:()=>Bt(!1)})}),(0,$.jsx)(Yx,{}),(0,$.jsx)(eS,{}),(0,$.jsx)(Fx,{}),n.tuiOverlay&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Rw,{overlay:n.tuiOverlay})}),Te&&(0,$.jsx)(sS,{entry:Te,pluginView:Ee?K.find(e=>e.info.id===Ee):void 0,onUiAction:(e,t)=>{W(e,t),be(null)},onClose:()=>be(null)}),(0,$.jsx)(cS,{active:Ht,children:(0,$.jsx)(zw,{open:Ht,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>Wt(!1),onSwitchSession:(e,t)=>{r({type:`switch_session`,path:e});let n=t&&t[0];Zt(n?{path:e,role:n.role,timestamp:n.timestamp}:null)},onSwitchProject:e=>{r({type:`set_cwd`,path:e})},onPreviewFile:(e,t)=>{x(e,t)}})}),xe&&(0,$.jsx)(ya,{currentCwd:xe.initialPath||n.state?.cwd||``,pathCompletions:n.pathCompletions,workspaceRoots:n.state?.workspaceRoots??[],onClose:()=>{xe.resolve({ok:!1,canceled:!0}),Se(null)},onSelectDirectory:e=>{xe.resolve({ok:!0,path:e}),Se(null)},onCreateProject:e=>{r({type:`make_dir`,path:e}),xe.resolve({ok:!0,path:e}),Se(null)},mode:`project`,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:e(`projectPickerTitle`)}),Ce&&(0,$.jsx)(Dx,{currentModelId:Ce.currentModelId,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,onManageModels:()=>Qe(!0),defaultModel:n.defaultModel,onClose:()=>{Ce.resolve({ok:!1,canceled:!0}),we(null)},onSelect:(e,t)=>{Ce.resolve({ok:!0,modelId:e,name:t?.name,provider:t?.provider}),we(null)}}),O&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Mw,{onClose:()=>k(!1)})}),(jt||Tt||at)&&(0,$.jsxs)(`div`,{className:`modal-backdrop perm-modal-backdrop`,children:[jt&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginPermTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>At(jt.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[jt.family===`net`?e(`pluginPermBodyNet`).replace(`{plugin}`,jt.pluginId).replace(`{hosts}`,(jt.hosts??[]).join(`, `)):e(`pluginPermBodyLlm`).replace(`{plugin}`,jt.pluginId).replace(`{models}`,(jt.models??[]).length>0?` ${(jt.models??[]).join(`, `)}`:``),jt.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:jt.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>At(jt.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>At(jt.id,!0),children:e(`pluginPermOnce`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>At(jt.id,!0,!0),children:e(`pluginPermAlways`)})]})]})]}),Tt&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginGrantRequestTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>Ct(Tt.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginGrantRequestBody`).replace(`{plugin}`,Tt.pluginId).replace(`{path}`,Tt.path),Tt.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:Tt.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Ct(Tt.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>Ct(Tt.id,!0),children:e(`pluginGrantAllow`)})]})]})]}),at&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:e(`pluginSessionGrantTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{st.current=null,at.resolve(!1),ot(null)},children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginSessionGrantBody`).replace(`{path}`,at.path),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{st.current=null,at.resolve(!1),ot(null)},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{st.current=null,at.resolve(!0),ot(null)},children:e(`ok`)})]})]})]})]}),!$e&&Object.values(n.pluginJobs??{}).some(e=>e.phase!==`done`)&&(0,$.jsxs)(`div`,{className:`active-plugin-jobs-bar`,onClick:()=>{nt(`plugins`),et(!0)},title:e(`pluginJobRunning`),children:[(0,$.jsx)(te,{className:`spin`}),(0,$.jsxs)(`span`,{className:`active-plugin-jobs-title`,children:[e(`pluginJobRunning`),`:`,` `,Object.values(n.pluginJobs??{}).filter(e=>e.phase!==`done`).map(e=>e.pluginId).join(`, `)]}),(()=>{let e=Object.values(n.pluginJobs??{}).find(e=>e.phase!==`done`),t=e?.lines[e.lines.length-1];return t?(0,$.jsx)(`span`,{className:`active-plugin-jobs-line`,children:t}):null})()]}),rt&&(0,$.jsx)(mb,{mode:rt,currentCwd:n.state?.cwd,currentSandbox:n.state?.sandbox,sandboxDiff:n.sandboxDiff,projects:n.projects,send:r,onClose:()=>it(null)}),(0,$.jsx)(_x,{})]})}function aT(){typeof document<`u`&&(oT(sT()),lT())}function oT(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty(`--msgs-gutter`,`${Math.round(e*100)/100}px`)}function sT(){let e=document.createElement(`div`);e.style.cssText=`position:fixed;top:-9999px;left:0;width:100px;height:100px;overflow-y:auto;scrollbar-gutter:stable both-edges;visibility:hidden;pointer-events:none;`,document.body.appendChild(e);let t=(e.offsetWidth-e.clientWidth)/2;return e.remove(),t}function cT(e){let t=document.createElement(`div`);t.style.cssText=`width:0;height:0;pointer-events:none;`,e.appendChild(t);let n=getComputedStyle(e),r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=Number.parseFloat(n.borderLeftWidth)||0,o=Number.parseFloat(n.paddingLeft)||0,s=i.left-(r.left+a+o);return t.remove(),s}function lT(){let e=()=>{let e=document.querySelector(`.messages`);return e?(oT(cT(e)),!0):!1},t=0;if(window.addEventListener(`resize`,()=>{t||=window.requestAnimationFrame(()=>{t=0,e()})}),e())return;let n=new MutationObserver(()=>{e()&&n.disconnect()});n.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>n.disconnect(),6e4)}function uT(e){let t=typeof e==`object`&&e&&`message`in e?String(e.message):String(e);return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|Unable to preload CSS for|Loading (?:CSS )?chunk .+ failed/i.test(t)}function dT(e,t){let n=!1;return r=>{if(!uT(r))return!1;if(n)return!0;try{let n=`pi-web:chunk-recovery`,r=t.storage.getItem(n),i=r?JSON.parse(r):null,a=t.now();if(i&&(i.buildId===e||a-i.time<6e4))return!1;t.storage.setItem(n,JSON.stringify({buildId:e,time:a}))}catch{return!1}return n=!0,t.reload(),!0}}function fT(e){let t=dT(e,{storage:{getItem:e=>window.sessionStorage.getItem(e),setItem:(e,t)=>window.sessionStorage.setItem(e,t)},reload:()=>window.location.reload(),now:Date.now});return window.addEventListener(`vite:preloadError`,e=>{t(e.payload)&&e.preventDefault()}),t}var pT=fT(`20261031T05280`),mT=class extends Q.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){pT(e)||console.error(`RootErrorBoundary caught error:`,e,t)}render(){return this.state.error?(0,$.jsxs)(`div`,{style:{minHeight:`100vh`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,padding:`24px`,background:`var(--bg, rgb(13, 14, 18))`,color:`var(--text, #e2e8f0)`,fontFamily:`system-ui, -apple-system, sans-serif`,textAlign:`center`},children:[(0,$.jsx)(`h2`,{style:{fontSize:`18px`,marginBottom:`12px`,color:`var(--red, #f43f5e)`},children:`页面加载出现异常 / App Failed to Render`}),(0,$.jsx)(`pre`,{style:{maxWidth:`600px`,overflow:`auto`,padding:`12px 16px`,background:`rgba(0, 0, 0, 0.4)`,borderRadius:`8px`,fontSize:`12px`,lineHeight:`1.5`,marginBottom:`20px`,whiteSpace:`pre-wrap`,wordBreak:`break-word`,color:`#94a3b8`},children:this.state.error.message||String(this.state.error)}),(0,$.jsx)(`button`,{type:`button`,style:{padding:`8px 20px`,background:`var(--accent, #38bdf8)`,color:`#0f172a`,border:`none`,borderRadius:`6px`,fontWeight:600,cursor:`pointer`,fontSize:`13px`},onClick:()=>window.location.reload(),children:`刷新重试 / Reload`})]}):this.props.children}};X(),bt(yt()),nw(),St(),aT(),(0,xn.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(mT,{children:(0,$.jsx)(_e,{children:(0,$.jsx)(iT,{})})})})),!yn&&`serviceWorker`in navigator&&window.addEventListener(`load`,()=>{let e=W();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(e=>{console.warn(`Service worker registration failed:`,e)})});export{cm as $,nb as A,Ti as At,iy as B,Cn as Bt,RS as C,Ma as Ct,xb as D,ti as Dt,bb as E,ni as Et,Uy as F,qn as Ft,ug as G,Fv as H,My as I,Er as It,Km as J,xh as K,Ry as L,Dr as Lt,Xy as M,Ir as Mt,Zy as N,vr as Nt,lb as O,xi as Ot,Wy as P,yr as Pt,um as Q,dy as R,Cr as Rt,WS as S,Na as St,ES as T,ea as Tt,I_ as U,ay as V,P_ as W,zm as X,Bm as Y,Gm as Z,tC as _,zo as _t,HC as a,hf as at,KS as b,mo as bt,rw as c,lf as ct,zC as d,Vu as dt,fm as et,pC as f,Hu as ft,zS as g,us as gt,vC as h,ac as ht,Dw as i,mf as it,tb as j,ui as jt,eb as k,Ei as kt,cw as l,Yu as lt,OC as m,oc as mt,hw as n,hp as nt,VC as o,kf as ot,CC as p,sl as pt,Rm as q,Sw as r,df as rt,WC as s,cf as st,bw as t,nm as tt,PC as u,td as ut,US as v,To as vt,DS as w,wa as wt,iC as x,Za as xt,rC as y,po as yt,cy as z,Tn as zt};
|