pi-web-ui 0.116.0 → 0.117.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +38 -4
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +138 -70
  4. package/dist/server/agent-service-daemon.js +52 -6
  5. package/dist/server/agent-service.js +495 -141
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +35 -6
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +48 -1
  11. package/dist/server/device-center/collab-service.js +26 -8
  12. package/dist/server/device-center/collab-tool.js +394 -18
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +15 -5
  18. package/dist/server/device-center/executor.js +47 -5
  19. package/dist/server/device-center/hub-conversations.js +14 -4
  20. package/dist/server/device-center/hub-deliveries.js +120 -15
  21. package/dist/server/device-center/hub-integration.js +655 -334
  22. package/dist/server/device-center/hub-page.js +5 -4
  23. package/dist/server/device-center/hub-setup.js +23 -1
  24. package/dist/server/device-center/hub-transaction-log.js +197 -0
  25. package/dist/server/device-center/hub.js +772 -354
  26. package/dist/server/device-center/integration-verification.js +113 -0
  27. package/dist/server/device-center/local-hub.js +6 -2
  28. package/dist/server/device-center/local-publication.js +423 -0
  29. package/dist/server/device-center/local-verification-job.js +97 -0
  30. package/dist/server/device-center/local-verification.js +274 -0
  31. package/dist/server/device-center/local.js +107 -12
  32. package/dist/server/device-center/main.js +4 -1
  33. package/dist/server/device-center/partition-log.js +62 -25
  34. package/dist/server/device-center/publication-journal.js +312 -0
  35. package/dist/server/device-center/publish-intent.js +379 -0
  36. package/dist/server/device-center/relay.js +134 -24
  37. package/dist/server/device-center/runtime.js +426 -42
  38. package/dist/server/device-center/store.js +225 -47
  39. package/dist/server/device-center/task-outcome.js +81 -0
  40. package/dist/server/device-center/task-recovery.js +603 -178
  41. package/dist/server/device-center/task-settlement.js +353 -0
  42. package/dist/server/device-center/task-workspace.js +443 -0
  43. package/dist/server/device-center/verification-limits.js +10 -0
  44. package/dist/server/device-center/work-contract.js +995 -0
  45. package/dist/server/dispatch-domain-handlers.js +15 -0
  46. package/dist/server/dsh/dsh-agent-service.js +9 -2
  47. package/dist/server/index.js +26 -1
  48. package/dist/server/patch-node-pty.js +3 -2
  49. package/dist/server/patch-remote-catalog.js +3 -2
  50. package/dist/server/preset-fields.js +17 -1
  51. package/dist/server/preset-share.js +1 -0
  52. package/dist/server/protocol-version.js +1 -1
  53. package/dist/server/quick-ask-settings.js +28 -0
  54. package/dist/server/quick-ask.js +164 -0
  55. package/dist/server/resolve-global-sdk.js +61 -11
  56. package/dist/server/scheduler-tasks.js +35 -8
  57. package/dist/server/session-list-scan.js +223 -0
  58. package/dist/server/session-open.js +93 -0
  59. package/dist/server/session-parser.js +4 -0
  60. package/dist/server/session-scan.js +90 -38
  61. package/dist/server/settings-service.js +9 -1
  62. package/dist/server/soft-cap.js +5 -0
  63. package/dist/server/transcript-prepare.js +73 -0
  64. package/dist/server/universal/drivers/claude-code.js +98 -34
  65. package/dist/server/universal/universal-session.js +4 -0
  66. package/dist/server/workspace-handle.js +428 -0
  67. package/docs/architecture-plugins.md +18 -5
  68. package/docs/device-center.md +30 -22
  69. package/package.json +3 -4
  70. package/plugin-sdk/README.md +16 -8
  71. package/plugin-sdk/client.d.ts +27 -0
  72. package/plugin-sdk/client.mjs +82 -0
  73. package/plugin-sdk/index.d.ts +10 -0
  74. package/plugin-sdk/index.mjs +4 -683
  75. package/plugin-sdk/package.json +15 -4
  76. package/plugin-sdk/testing.d.ts +10 -0
  77. package/plugin-sdk/testing.mjs +566 -0
  78. package/themes/flow-cristallo.css +168 -0
  79. package/themes/flow-ink.css +169 -0
  80. package/themes/flow-obsidian.css +169 -0
  81. package/themes/flow-zurich.css +169 -0
  82. package/web/dist/.build-assets.json +1 -1
  83. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
  84. package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
  85. package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  86. package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
  87. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  88. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  89. package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
  90. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  91. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  92. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
  93. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  94. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  95. package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  96. package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  97. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  98. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  99. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
  100. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  101. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  102. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
  103. package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  104. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  105. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  106. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  107. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  108. package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
  109. package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
  110. package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  112. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  113. package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
  114. package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
  115. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  116. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  117. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  118. package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
  119. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  120. package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
  121. package/web/dist/index.html +11 -11
  122. package/web/dist/sw.js +1 -1
  123. package/dist/gh-comment-781.md +0 -5
  124. package/dist/server/device-center/local-page.js +0 -17
  125. package/dist/server/device-center/smoke-preview.js +0 -3
  126. package/dist/server/durable/durable-capabilities.js +0 -11
  127. package/dist/server/markers/builtins/services.js +0 -123
  128. package/dist/server/markers/builtins/todo.js +0 -189
  129. package/dist/server/markers-list-tool.js +0 -34
  130. package/dist/server/orchestrator.js +0 -109
  131. package/dist/server/patch-turn-end-boundary.js +0 -77
  132. package/dist/server/system-prompt-soul.js +0 -41
  133. package/dist/server/univer-service.js +0 -448
  134. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  135. package/dist/test-artifact.md +0 -9
  136. package/dist/test-preview-modal.md +0 -11
  137. package/dist/test-report.html +0 -20
  138. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  139. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  140. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  141. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  142. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  143. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  144. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  145. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  146. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  147. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  148. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  149. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  150. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  151. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  152. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  153. package/web/dist/assets/index-C6DwztqE.css +0 -1
  154. package/web/dist/assets/index-CuN802Sj.js +0 -93
  155. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
@@ -1,93 +0,0 @@
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-0CYvD72B.js","./app-globals-CZxzGvIo.js","./uuid-BzDIGCwP.js","./theme-D2l_mLNo.js","./xterm-Cf5xxe4g.js","./xterm-B1njb2Cr.css","./SCMPanel-B8_EDxNr.js","./DeviceCenter-DfAHKcid.js","./DeviceExecutionSettings-q5Ik8oXg.js","./DeviceGroups-CI14_SRb.js","./shortcut-stack-hhrDyRBn.js","./group-view-state-CGCzYF8k.js","./CanvasStudio-zSxyIx1R.js","./plugin-host-BRWib9DF.js","./desktop-aAKpvKJV.js","./es-DWMIuDU2.js","./canvas-client-CUnXlQYX.js","./PiSetupModal-BmMrrgB9.js","./ProviderOAuthControls-BGSBIKD7.js","./ModelConfigModal-YVEgyy34.js","./SettingsModal-OBmGTh-5.js","./HintTip-c6d0TJoh.js","./BgTasksModal-C0i3O1FT.js","./TuiOverlayModal-BsA-QTvN.js","./GlobalSearchModal-F7fNimKk.js","./FilePreview-D4NrhF-U.js","./GroupConversation-Dh71Pdb-.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,Cn as c,Ct as l,D as u,Dn as d,Dt as f,E as p,En as m,Et as h,F as g,Ft as _,G as v,Gt as y,H as b,Ht as x,I as S,J as C,Jt as w,K as T,Kt as E,L as D,M as O,Mt as k,N as A,Nt as j,O as M,On as N,Ot as P,P as F,Pt as I,Q as L,Qt as ee,R,Rt as te,Sn as ne,St as re,Tn as z,Tt as B,U as ie,Ut as ae,V,Vt as oe,W as se,Wt as ce,X as le,Xt as ue,Y as de,Z as fe,Zt as pe,_ as me,_n as H,a as he,an as ge,at as U,b as _e,bn as W,bt as ve,c as G,cn as K,ct as q,d as ye,dn as be,dt as xe,en as Se,et as J,f as Ce,fn as we,ft as Te,g as Ee,gn as De,gt as Oe,h as ke,hn as Ae,ht as je,i as Me,in as Y,it as Ne,j as Pe,jt as Fe,k as Ie,kt as Le,l as Re,ln as ze,lt as Be,m as Ve,mn as He,mt as Ue,n as We,nn as Ge,nt as Ke,o as qe,ot as Je,p as Ye,pt as Xe,q as Ze,r as Qe,rn as $e,rt as et,s as tt,st as nt,t as X,tn as rt,tt as it,u as at,un as Z,ut as ot,vn as st,vt as ct,w as lt,wn as ut,wt as dt,x as ft,xn as pt,xt as mt,y as ht,yn as gt,yt as _t,z as vt,zt as yt}from"./app-globals-CZxzGvIo.js";import{i as bt,n as xt,r as St,t as Ct}from"./react-CR5VJ85Q.js";import{t as wt}from"./shortcut-stack-hhrDyRBn.js";import{t as Tt}from"./uuid-BzDIGCwP.js";import{n as Et,t as Dt}from"./Dropdown-C4LIhshN.js";import{a as Ot,i as kt,n as At,t as jt}from"./theme-D2l_mLNo.js";import{i as Mt,n as Nt,r as Pt,t as Ft}from"./desktop-aAKpvKJV.js";import{A as It,C as Lt,D as Rt,E as zt,O as Bt,S as Vt,T as Ht,_ as Ut,a as Wt,b as Gt,c as Kt,g as qt,h as Jt,i as Yt,j as Xt,k as Zt,l as Qt,m as $t,n as en,o as tn,r as nn,t as rn,u as an,v as on,w as sn,x as cn,y as ln}from"./plugin-host-BRWib9DF.js";import{i as un,n as dn,r as fn,t as pn}from"./HintTip-c6d0TJoh.js";import{a as mn,c as hn,i as gn,l as _n,n as vn,o as yn,r as bn,s as xn,t as Sn}from"./remote-ssh-client-CfYSMEZg.js";import{a as Cn,c as wn,d as Tn,h as En,l as Dn,m as On,s as kn,t as An,u as jn}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 Mn(){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 Nn(e){let t=N(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:Mn()})}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 Pn=typeof window<`u`&&Nn(window),Fn=St(),In=xt(),Q=e(bt(),1);function Ln(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 Rn(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=Ln(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]),wt(()=>{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}}var zn=null,Bn=new Set,Vn=e=>(Bn.add(e),()=>{Bn.delete(e)}),Hn=()=>zn;function Un(e){zn===e&&(zn=null,Bn.forEach(e=>e()))}async function Wn(e,t,n,r,i=!1){let a=n&&!i,o=window.piDesktop,s=a||o?.openHub?null:window.open(`about:blank`,`_blank`);if(!a&&!o?.openHub&&!s)throw Error(r?`请允许弹出窗口后重试。`:`Allow popups and try again.`);s&&(s.opener=null);try{let i=await fetch(z(d(`/api/device-center/devices/${encodeURIComponent(e)}/open`)),{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,signal:AbortSignal.timeout(15e3)});if(!i.ok)throw Error(r?`无法打开设备,请确认设备在线且本机绑定有效。`:`Could not open the device. Check connectivity and local pairing.`);let c=await i.json(),l=new URL(c.url),u=new URL(t);if(![`http:`,`https:`].includes(l.protocol)||l.hostname!==u.hostname||l.username||l.password||!(l.pathname===`/__device/open`||l.origin===u.origin&&l.pathname===`/device/${encodeURIComponent(e)}/__open`))throw Error(`Invalid device access URL`);if(l.searchParams.delete(`next`),n&&l.searchParams.set(`next`,`/desktop`),a)zn={id:e,hubUrl:t,url:l.href,zh:r},Bn.forEach(e=>e());else if(o?.openHub){if(!await o.openHub(l.href))throw Error(r?`无法打开设备窗口。`:`Could not open device window.`)}else s&&s.location.replace(l.href)}catch(e){throw s?.close(),e}}var $=Ct();function Gn({hubUrl:e,currentDeviceId:n,onRemarkUpdated:i}){let{locale:a}=st(),o=c(a),[s,l]=(0,Q.useState)([]),[u,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(0),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(z(d(`/api/device-center/devices`)),{signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]),credentials:`same-origin`});if(!n.ok)throw Error(n.status===409?o?`请重新绑定本机以读取设备列表。`:`Pair this computer again to read the device list.`:o?`无法读取设备列表,请重试。`:`Could not load devices. Try again.`);let r=await n.json();if(!Array.isArray(r.devices))throw Error(o?`设备列表格式异常。`:`Invalid device list.`);e||(l(r.devices),f(``))}catch(t){e||(l([]),f(t instanceof Error?t.message:String(t)))}finally{e||(n=setTimeout(r,5e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[e,n,p,o]);function x(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 S(t,n,r=!1){t.preventDefault();try{await Wn(n,e,r,o),f(``)}catch(e){f(e instanceof Error?e.message:String(e))}}async function C(e,t){b(e);let n=t.trim();try{let t=await fetch(z(d(`/api/device-center/devices/${encodeURIComponent(e)}/remark`)),{method:`POST`,credentials:`same-origin`,headers:{"Content-Type":`application/json`},body:JSON.stringify({remark:n})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error||(o?`保存备注失败`:`Failed to save remark`))}l(t=>t.map(t=>t.id===e?{...t,remark:n||void 0}:t)),g(null),f(``),i?.(e,n),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-remark-updated`,{detail:{deviceId:e,remark:n||void 0}}))}catch(e){f(e instanceof Error?e.message:String(e))}finally{b(null)}}return(0,$.jsxs)(`section`,{className:`dc-card`,"aria-label":o?`所有设备`:`All devices`,children:[(0,$.jsxs)(`div`,{className:`dc-card-header`,children:[(0,$.jsx)(`span`,{className:`dc-icon`,children:(0,$.jsx)(k,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{children:[o?`所有设备`:`All devices`,` · `,s.length]}),(0,$.jsx)(`p`,{children:o?`同一账号下的设备,使用本机绑定授权直接访问。`:`Devices in your account. Access is authorized through this computer's pairing.`})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-icon-button`,"aria-label":o?`刷新设备`:`Refresh devices`,onClick:()=>m(e=>e+1),children:(0,$.jsx)(yt,{})})]}),u&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:u}),(0,$.jsx)(`div`,{className:`dd-list`,children:s.map(e=>{let i=!!e.remark?.trim(),a=i?e.remark.trim():e.name,s=h===e.id;return(0,$.jsxs)(`div`,{className:`dd-device`,style:s?{flexWrap:`wrap`}:void 0,children:[(0,$.jsx)(`span`,{className:`dc-device-icon`,children:(0,$.jsx)(k,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`dd-identity`,children:[(0,$.jsx)(`strong`,{children:a}),(0,$.jsxs)(`span`,{children:[i?`${e.name} · `:``,e.id===n?o?`本机`:`This device`:e.id]})]}),(0,$.jsx)(`span`,{className:`dc-status ${e.online?`is-online`:`is-offline`}`,children:e.online?o?`在线`:`Online`:o?`离线`:`Offline`}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,title:o?i?`修改备注`:`设置备注`:i?`Edit remark`:`Set remark`,onClick:()=>{s?g(null):(g(e.id),v(e.remark??``))},children:[(0,$.jsx)(fe,{"aria-hidden":!0}),o?i?`修改备注`:`设置备注`:i?`Edit remark`:`Set remark`]}),x(e.id)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`a`,{className:`dc-button`,href:x(e.id),target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void S(t,e.id),children:[(0,$.jsx)(t,{"aria-hidden":!0}),o?`打开设备`:`Open device`]}),(0,$.jsxs)(`a`,{className:`dc-button`,href:`${x(e.id)}/desktop`,target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void S(t,e.id,!0),children:[(0,$.jsx)(k,{"aria-hidden":!0}),o?`远程桌面`:`Remote desktop`]})]})]}),s&&(0,$.jsxs)(`form`,{className:`dd-remark-form`,style:{display:`flex`,alignItems:`center`,gap:`8px`,width:`100%`,paddingTop:`8px`,paddingBottom:`4px`},onSubmit:t=>{t.preventDefault(),C(e.id,_)},children:[(0,$.jsx)(`input`,{type:`text`,maxLength:80,autoFocus:!0,disabled:y===e.id,placeholder:o?`输入设备备注(留空清除)`:`Device remark (leave blank to clear)`,value:_,onChange:e=>v(e.target.value),style:{flex:1,minWidth:`180px`,background:`var(--bg)`,border:`1px solid var(--border)`,borderRadius:`6px`,padding:`6px 10px`,color:`var(--text)`,fontSize:`12px`}}),(0,$.jsxs)(`button`,{type:`submit`,className:`dc-button is-primary`,disabled:y===e.id,children:[(0,$.jsx)(r,{"aria-hidden":!0}),y===e.id?o?`保存中…`:`Saving…`:o?`保存`:`Save`]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:y===e.id,onClick:()=>g(null),children:[(0,$.jsx)(Z,{"aria-hidden":!0}),o?`取消`:`Cancel`]})]})]},e.id)})})]})}function Kn({label:e=`pi-web-ui`,barItem:t=!1,onContextMenu:n}){let{locale:r}=st(),i=c(r),[a,o]=(0,Q.useState)(null),[s,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),{panelRef:f,style:p}=Rn({open:s&&!!a,anchor:u,align:`left`,onClose:()=>l(!1)});(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(z(d(`/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||l(!1)}}catch{}finally{e||(n=setTimeout(r,15e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[]);let m=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{className:t?`brand-logo bar-item-brand-logo bar-item-icon`:`brand-logo`,src:d(`/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})]}),h=t?`bar-item brand bar-item-brand`:`brand`;return a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:u,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,type:`button`,className:`${h} brand-device-trigger`,title:i?`设备列表`:`Devices`,"aria-label":i?`设备列表`:`Devices`,"aria-haspopup":`dialog`,"aria-expanded":s,onClick:()=>l(e=>!e),children:m}),s&&(0,Fn.createPortal)((0,$.jsx)(`div`,{ref:f,style:p,className:`brand-device-panel`,role:`dialog`,"aria-label":i?`设备列表`:`Devices`,children:(0,$.jsx)(Gn,{hubUrl:a.hubUrl,currentDeviceId:a.deviceId})}),document.body)]}):(0,$.jsx)(`span`,{className:h,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,children:m})}function qn(e){return He({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 Jn(e){return He({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 Yn(e){return He({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 Xn(e){return He({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M20 17a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.9a2 2 0 0 1-1.69-.9l-.81-1.2a2 2 0 0 0-1.67-.9H8a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2Z`},child:[]},{tag:`path`,attr:{d:`M2 8v11a2 2 0 0 0 2 2h14`},child:[]}]})(e)}function Zn(e){return He({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 Qn(e){return e.map(e=>e.kind===`package`?`pi update npm:${e.name}`:e.kind===`git-extension`?`pi update ${$n(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 $n(e){return e.startsWith(`git:`)?e:`git:${e}`}var er=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost),tr=null,nr=0;function rr(){return tr?.available===!0?tr.pages??[]:[]}function ir(){Date.now()-nr<5e3||ar().catch(()=>{})}async function ar(){if(Pt())return{available:!1,pages:[],desktop:!0,error:`桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)`};let e=er();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&&(tr=r,nr=Date.now()),r}catch(e){return{available:!1,pages:[],error:e instanceof Error?e.message:String(e)}}}function or(e){return e.length===1?e[0]:null}function sr(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:`page`,key:`page:${e.origin}`}}async function cr(){let e=er();if(!e)return!1;try{return(await e({op:`openOptions`,timeoutMs:5e3})).ok===!0}catch{return!1}}function lr(e=45e3){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(!0),i=(0,Q.useCallback)(async e=>{let t=await ar();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 ur(){let e=W(),{status:t,refresh:n}=lr(),[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=or(c),d=e=>{o(e),s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>o(null),2600)},f=t=>{let n=Gt({attachments:[sr(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)(k,{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)(k,{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)(dr,{status:t,onRefresh:n,onCite:f,onClose:()=>i(!1)})]})}function dr({status:e,onRefresh:t,onCite:n,onClose:r}){let i=W(),[a,o]=(0,Q.useState)(!1),s=e?.pages??[],c=async()=>{o(!0);try{await cr()||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)(k,{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 fr=`canvas`,pr=`terminal`,mr=[pr],hr=[`terminal_create`,`terminal_list`,`terminal_close`,`terminal_input`,`terminal_key`,`terminal_read`,`terminal_wait`],gr=`conversation`,_r=`communicate`,vr=[gr,`subagent`],yr=[`subagent_spawn`,`subagent_get_result`,`subagent_steer`,`subagent_list`,`subagent_stop`,`subagent_wait_all`,`subagent_templates`,`subagent_handoff`],br=`edit_soft`,xr=`delegate_task`,Sr=`ask_user_question`,Cr=`browser_page`,wr=`skill`,Tr=`schedule`,Er=[`schedule_task`,`schedule_list`,`schedule_cancel`],Dr=`eval`,Or=`present_files`,kr=`claim_files`,Ar=`plan_update`,jr=`compact_context`,Mr=`patch`,Nr=`mcp_manage`,Pr=`sandbox`,Fr=`worktree`,Ir=`device_collab`,Lr=`codemode`,Rr=`tool_search`,zr=[...mr.map(e=>({name:e,group:`terminal`,defaultOn:!1,dshVisible:!0})),...vr.map(e=>({name:e,group:`subagent`,defaultOn:!0,dshVisible:!1})),{name:_r,group:`subagent`,defaultOn:!0,dshVisible:!1,descKey:`communicateEnabledDesc`,offHintKey:`communicateOffHint`},{name:br,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`editSoftEnabledDesc`,offHintKey:`editSoftOffHint`},{name:xr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`delegateTaskEnabledDesc`,offHintKey:`delegateTaskOffHint`},{name:Sr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`questionnaireEnabledDesc`,offHintKey:`questionnaireOffHint`},{name:Cr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`browserPageEnabledDesc`,offHintKey:`browserPageOffHint`},{name:kr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`claimFilesEnabledDesc`,offHintKey:`claimFilesOffHint`},{name:Ar,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`planUpdateEnabledDesc`,offHintKey:`planUpdateOffHint`},{name:Mr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`patchToolEnabledDesc`,offHintKey:`patchToolOffHint`},{name:`lsp`,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`lspToolEnabledDesc`,offHintKey:`lspToolOffHint`},{name:Or,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`presentFilesEnabledDesc`,offHintKey:`presentFilesOffHint`},{name:wr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`skillEnabledDesc`,offHintKey:`skillOffHint`},{name:Dr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`evalEnabledDesc`,offHintKey:`evalOffHint`},{name:Lr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`codemodeEnabledDesc`,offHintKey:`codemodeOffHint`},{name:Rr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolSearchEnabledDesc`,offHintKey:`toolSearchOffHint`},{name:Tr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`scheduleTaskEnabledDesc`,offHintKey:`scheduleTaskOffHint`},{name:jr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`compactContextEnabledDesc`,offHintKey:`compactContextOffHint`},{name:Nr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`mcpManageEnabledDesc`,offHintKey:`mcpManageOffHint`},{name:Pr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`sandboxEnabledDesc`,offHintKey:`sandboxOffHint`},{name:Fr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`toolsWorktreeDesc`,offHintKey:`toolsWorktreeOffHint`},{name:fr,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`canvasToolEnabledDesc`,offHintKey:`canvasToolOffHint`}],Br=[{name:Ir,group:`other`,defaultOn:!1,allowAgentToggle:!1,dshVisible:!1,descKey:`toolsDeviceCollabDesc`,offHintKey:`toolsDeviceCollabOffHint`}],Vr=[{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`}],Hr=[...Vr.map(e=>({name:e.name,group:`core`,defaultOn:e.defaultOn,platform:e.platform,allowAgentToggle:e.allowAgentToggle,dshVisible:!1,descKey:e.descKey})),...zr,...Br];new Map(Hr.map(e=>[e.name,e]));var Ur=new Set(Hr.map(e=>e.name)),Wr=Hr.map(e=>e.name);function Gr(e){let t=new Set(Kr(e));return Wr.filter(e=>!t.has(e))}function Kr(e){if(!Array.isArray(e))return qr();let t=[];for(let n of e){let e=n;if(typeof e==`string`&&hr.includes(e)&&(e=pr),typeof e==`string`&&yr.includes(e)&&(e=gr),e===`conversation_read`&&(e=gr),typeof e==`string`&&vr.includes(e)){for(let e of vr)t.includes(e)||t.push(e);continue}typeof e==`string`&&Er.includes(e)&&(e=Tr),typeof e==`string`&&Ur.has(e)&&!t.includes(e)&&t.push(e)}return t}function qr(){return Hr.filter(e=>!e.defaultOn).map(e=>e.name)}function Jr(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 Yr(e){return Jr([wr],e).includes(wr)}var Xr=new Set([`svg`,`g`,`path`,`circle`,`rect`,`line`,`polyline`,`polygon`,`ellipse`,`use`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`]),Zr=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(`.`)),Qr=new Set([`script`,`style`,`title`,`desc`,`foreignobject`]),$r=new Set([...Xr].map(e=>e.toLowerCase())),ei=new Set([...Zr].map(e=>e.toLowerCase()));function ti(e){return $r.has(e.toLowerCase())}function ni(e){return ei.has(e.toLowerCase())}function ri(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(!ti(e)){Qr.has(e)?t.remove():(i(t),t.replaceWith(...t.childNodes));continue}for(let e of Array.from(t.attributes)){let n=e.name.toLowerCase();(!ni(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();(!ni(t)||/^on/i.test(t))&&r.removeAttribute(e.name)}return i(r),new XMLSerializer().serializeToString(r)}function ii({icon:e,iconSvg:t,className:n}){let r=ri(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 ai={projects:`host:lp-projects`,groups:`host:lp-groups`,convs:`host:lp-running`,sessions:`host:lp-history`},oi=[`projects`,`convs`,`sessions`],si=new Map(Object.keys(ai).map(e=>[ai[e],e])),ci=`plugin:`;function li(e){return e.startsWith(ci)&&e.length>7}function ui(e){let t=[],n=new Set;for(let r of e??[]){let e=null,i,a=si.get(r.id);a?e=a:r.source?.startsWith(`plugin:`)&&r.kind===`view`&&(e=`${ci}${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 oi)n.has(e)||t.push({key:e,shown:!0});return t}function di(e){if(e.some(e=>e.key===`groups`))return[...e];let t=[...e],n=t.findIndex(e=>e.key===`projects`&&e.shown);return t.splice(n+1,0,{key:`groups`,shown:!0}),t}function fi(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 pi(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||li(e))&&typeof i==`number`&&Number.isFinite(i)&&i>0&&(n[e]=i)}catch{}return n}var mi=new Set([`view`,`action`,`badge`,`menu`,`page`,`organizer`,`divider`,`toggle`,`input`,`progress`,`select`]),hi=new Set([`disabled`,`always`,`never`,`file.isDir`,`file.isFile`,`session.isRunning`,`message.hasSelection`]),gi=`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,device.group.header,device.group.actions,device.group.workspace`.split(`,`),_i=gi.map(e=>({slot:e,cardinality:`list`}));function vi(e){return _i.find(t=>t.slot===e)?.cardinality??`list`}function yi(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 bi=[{id:`host:lp-projects`,slot:`leftpanel.sections`,labelKey:`recentProjects`,icon:`folder`,kind:`action`,order:10},{id:`host:lp-groups`,slot:`leftpanel.sections`,labelKey:`leftPanelGroups`,icon:`users`,kind:`action`,order:15},{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:worktrees`,slot:`topbar.primary`,labelKey:`worktreeViewTitle`,icon:`folders`,kind:`action`,order:4,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:msg-delete`,slot:`message.actions`,labelKey:`delete`,icon:`trash`,kind:`action`,order:30,hidden:!0},{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:msg-ctx-delete`,slot:`contextmenu.message`,labelKey:`delete`,icon:`trash`,kind:`action`,context:`message`,order:30,group:`danger`},{id:`host:tool-info`,slot:`contextmenu.toolcall`,labelKey:`toolInfoMenuLabel`,icon:`info`,kind:`action`,context:`toolcall`,order:10}],xi=`__view`,Si=new Set([`host:settings`,`host:history`,`host:files`]),Ci=new Set([`host:history`,`host:files`]);function wi(e){return`${e}:${xi}`}function Ti(e){return e.source.startsWith(`plugin:`)?e.id===wi(e.source.slice(7)):!1}function Ei(e,t,n){let r=wi(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 Di(e,t){let n=t.map(wi),r=new Set(n),i=(e?.order??[]).filter(e=>!r.has(e));return{...e,order:[...i,...n]}}var Oi=`host:brand`,ki=[`host:brand-logo`,`host:brand-name`];function Ai(e){if(!((e.hidden??[]).some(e=>ki.includes(e))||(e.shown??[]).some(e=>ki.includes(e))||(e.order??[]).some(e=>ki.includes(e))||ki.some(t=>e.align?.[t]!==void 0)||ki.some(t=>e.groups?.[t]!==void 0)||ki.some(t=>e.labels?.[t]!==void 0)||ki.some(t=>e.slots?.[t]!==void 0)))return e;let t=e=>{if(!e)return;let t=[];for(let n of e){let e=ki.includes(n)?Oi: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))ki.includes(t)||(n[t]=r);if(n[Oi]===void 0){let r=t?e[ki[0]]??e[ki[1]]:e[ki[1]]??e[ki[0]];r!==void 0&&(n[Oi]=r)}return n},r=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ki.includes(n)||(t[n]=r);if(t[Oi]===void 0){let n=e[ki[0]]??e[ki[1]];n!==void 0&&(t[Oi]=n)}return t},i=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))ki.includes(n)||(t[n]=r);if(t[Oi]===void 0){let n=e[ki[0]]??e[ki[1]];n!==void 0&&(t[Oi]=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 ji(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:xi,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 Mi(e){return{id:e.id,slot:e.slot,source:`host`,label:e.label,icon:e.icon,kind:e.kind??`action`,order:e.order??100,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[],when:e.when}}function Ni(e){return typeof e==`string`&&gi.includes(e)}function Pi(e,t){return t?e.label:e.labelEn??e.label}function Fi(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function Ii(e,t,n,r,i){let a=`${e}#${r.id}`,o=Li(a,t,n,r.children,i),s=Fi(r,i),c=Ri(r.options,i),l=zi(r.progress);return{id:a,slot:t,source:n,label:Pi(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 Li(e,t,n,r,i){return r?.length?r.map((r,a)=>({entry:Ii(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 Ri(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 zi(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function Bi(e,t,n,r,i,a){let o=Li(e,t,n,r.children,i),s=Fi(r,i),c=zi(r.progress),l=Ri(r.options,i);return{id:e,slot:t,source:n,label:Pi(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 Vi(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 Hi(e,t){let n=e.filter(e=>Ti(e)&&!t.has(e.id));if(n.length===0)return e;let r=e.filter(e=>!Ti(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 Ui(e,t){let n=c(t.locale),r=new Set(t.disabledPlugins??[]),i=Ai(t.layout??{}),a=e=>{t.diagnostics?.push({level:e.level??`warn`,...e})},o=new Map,s=0;for(let e of bi)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(!Ni(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&&!mi.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)hi.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,Bi(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);Gi(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 l=new Map,u=(e,t)=>{let n=l.get(e)??[];n.includes(t)||n.push(t),l.set(e,n)};for(let e of i.hidden??[]){let t=o.get(e);t&&(t.hidden=!0,u(e,`hidden`))}for(let e of i.shown??[]){let t=o.get(e);t&&(t.hidden=!1,u(e,`hidden`))}for(let[e,t]of Object.entries(i.groups??{})){let n=o.get(e);n&&(n.group=t,u(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,u(e,`align`))}for(let[e,t]of Object.entries(i.labels??{})){let n=o.get(e);n&&(n.label=t,n.labelExplicit=!0,u(e,`label`))}for(let[e,t]of Object.entries(i.slots??{})){let n=o.get(e);n&&Ni(t)&&n.slot!==t&&(n.movedFrom=n.movedFrom??n.slot,n.slot=t,u(e,`slot`))}for(let e of Si){let t=o.get(e);t&&(i.slots?.[e]||(t.slot=`topbar.primary`),t.hidden=!1)}let d=new Map;(i.order??[]).forEach((e,t)=>{o.has(e)&&(d.has(e)||d.set(e,t),u(e,`order`))});for(let e of Object.values(ai)){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 f=new Map;for(let e of gi)f.set(e,[]);for(let e of o.values())f.get(e.slot)?.push(e);let p={};for(let e of gi){let t=Vi(f.get(e)??[],d),n=yi(e===`topbar.primary`?Hi(t,d):t,vi(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`});p[e]=n.entries.map(e=>Wi(e,l.get(e.id)??[]))}return p}function Wi(e,t){let n={...e,userOverrides:t};return delete n.seq,n}function Gi(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&&Ni(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 Ki(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 qi(e,t){let n=e??{},r={},i=t===Oi?[t,...ki]:[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=Yi(n.groups,t),l=Yi(n.labels,t),u=Yi(n.align,t),d=Yi(n.slots,t);if(t===Oi)for(let e of ki)c=Yi(c,e),l=Yi(l,e),u=Yi(u,e),d=Yi(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 Ji(){return{}}function Yi(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 Xi=new Set([`host:files`]);function Zi(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 Qi(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 $i=null,ea=new Set;function ta(){for(let e of ea)e()}function na(e){$i={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}:{}},ta()}function ra(){$i!==null&&($i=null,ta())}function ia(e){return ea.add(e),()=>{ea.delete(e)}}function aa(){return $i}function oa(){return(0,Q.useSyncExternalStore)(ia,aa,aa)}function sa(e){return Number.isFinite(e)?e:0}function ca(e,t,n,r,i,a){let o=Math.max(0,sa(n)),s=Math.max(0,sa(r)),c=Math.max(8,sa(i)-o-8),l=Math.max(8,sa(a)-s-8);return{x:Math.min(Math.max(8,sa(e)),c),y:Math.min(Math.max(8,sa(t)),l)}}function la(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 ua(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 da(e,t){return!e||ua(e.when,t)}function fa(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 pa(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 ma(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 ha(e,t){return!e||e.kind===`divider`||e.hidden===!0?!1:!da(e,t)}function ga(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,ha(e[o],r))return o;return-1}var _a={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 va(e){let t=(e??``).trim();return t?_a[t.toLowerCase()]||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:``):``}var ya=`@root`,ba=e=>e.endsWith(`/`)?e:e+`/`;function xa(e,t){let n=t.trim(),r=e.replace(/\\/g,`/`);return r.endsWith(`/`)?r+n:(/^[A-Za-z]:$/.test(r),r+`/`+n)}function Sa(e){let t=e.trim();return!(!t||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`))}var Ca=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)?ya:null;if(n===0)return`/`;let r=t.slice(0,n);return/^[A-Za-z]:$/.test(r)?r+`/`:r};function wa({currentCwd:e,pathCompletions:t,workspaceRoots:n,onClose:i,onSelectDirectory:a,mode:o=`folder`,onCreateProject:s,className:l,backdropClassName:d,role:f,ariaLabel:p,localOnly:m=!1,portalContainer:h}){let g=W(),_=c(gt()),v=qe().remoteSsh&&!m,b=Me(`homeDir`),x=Me(`desktopDir`),[S,C]=(0,Q.useState)(()=>v&&gn(e)?`remote`:`local`);(0,Q.useEffect)(()=>{!v&&S===`remote`&&C(`local`)},[v,S]);let[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(``),[O,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(-1),L=(0,Q.useRef)(null),ee=(0,Q.useRef)(null),[R,te]=(0,Q.useState)([]),[ne,re]=(0,Q.useState)(``),[z,B]=(0,Q.useState)(`22`),[ie,ae]=(0,Q.useState)(``),[V,oe]=(0,Q.useState)(`password`),[se,ce]=(0,Q.useState)(``),[le,ue]=(0,Q.useState)(`~/.ssh/id_rsa`),[de,fe]=(0,Q.useState)(!0),[pe,me]=(0,Q.useState)(``),[H,he]=(0,Q.useState)(!1),[ge,U]=(0,Q.useState)(null),[ve,G]=(0,Q.useState)(null),[K,q]=(0,Q.useState)(null),[ye,be]=(0,Q.useState)(null),[xe,Se]=(0,Q.useState)([]),[J,Ce]=(0,Q.useState)(!1),[we,Ee]=(0,Q.useState)(`/`),[De,Oe]=(0,Q.useState)(`/`),[ke,Ae]=(0,Q.useState)([]),[je,Y]=(0,Q.useState)(!1),[Ne,Pe]=(0,Q.useState)(!1),[Fe,Ie]=(0,Q.useState)(``),[Le,Re]=(0,Q.useState)(null),ze=t.filter(e=>e.type===`dir`);(0,Q.useEffect)(()=>{if(gn(e)){let t=mn(e);t&&(re(t.host),B(String(t.port)),ae(t.username),Ee(t.remotePath),Oe(t.remotePath))}else{let t=(e||``).replace(/\\/g,`/`);T(t),D(t)}A(!1),M(``),P(null),I(-1)},[e]),(0,Q.useEffect)(()=>{let e=requestAnimationFrame(()=>{L.current?.focus()});return()=>cancelAnimationFrame(e)},[S]),wt(()=>{O||Ne?(A(!1),M(``),P(null),Pe(!1),Ie(``),Re(null)):i()}),(0,Q.useEffect)(()=>{if(S!==`local`)return;let e=setTimeout(()=>{X({type:`complete_path`,path:ba(w)})},60);return()=>clearTimeout(e)},[w,S]),(0,Q.useEffect)(()=>{if(S!==`local`||E===w)return;let e=setTimeout(()=>{X({type:`complete_path`,path:E})},150);return()=>clearTimeout(e)},[E,w,S]);let Be=e=>{let t=e.trim();t&&t!==`@root`&&a(t)},Ve=e=>{T(e),D(e),I(-1),P(null)},He=()=>{let e=j.trim();if(e&&w!==`@root`){if(o===`project`){if(!Sa(e)){P(g(`invalidProjectName`));return}let t=xa(w,e);s?s(t):(X({type:`make_dir`,path:t}),a(t)),A(!1),M(``),P(null),i()}else X({type:`make_dir`,path:`${ba(w)}${e}`}),setTimeout(()=>{X({type:`complete_path`,path:ba(w)})},80),M(``),A(!1)}},We=e=>{if(e.key===`Escape`)e.stopPropagation(),O?(A(!1),M(``),P(null)):i();else if(e.key===`Enter`&&!e.nativeEvent.isComposing)Be(E);else if(e.key===`Tab`){if(ze.length===0)return;e.preventDefault();let t=F>=0?(F+1)%ze.length:0;I(t),D(ze[t].path),T(ze[t].path)}},Ke=async t=>{let n=(t?.host??ne).trim(),r=t?.port??(parseInt(z,10)||22),i=(t?.username??ie).trim();if(!n||!i){U(_?`请填写主机地址和用户名`:`Please provide host address and username`);return}he(!0),U(null);let a=t?.auth??(V===`password`?{type:`password`,password:se}:V===`key`?{type:`key`,privateKeyPath:le}:{type:`agent`}),o=await hn({host:n,port:r,username:i,auth:a,saveProfile:de,profileName:t?.profileName||pe.trim()||void 0});if(he(!1),!o.ok||!o.connectionId){U(o.error||(_?`连接远程服务器失败`:`Failed to connect to remote server`));return}G(o.connectionId),q(o.system??null),be(o.tools??null),Se(o.suggestedInstall??[]);let s=gn(e)?mn(e)?.remotePath:null,c=s&&s!==`/`?s:o.system?.homeDir||`/`;Ee(c),Oe(c),Xe(o.connectionId,c),_n().then(e=>te(e))},Ye=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{S===`remote`&&_n().then(t=>{if(te(t),!Ye.current&&!ve&&!H&&gn(e)){let n=mn(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&&(Ye.current=!0,re(e.host),B(String(e.port)),ae(e.username),oe(e.authType),e.privateKeyPath&&ue(e.privateKeyPath),Ke({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`}}))}}})},[S,e,ve,H]);let Xe=async(e,t)=>{Y(!0),U(null);let n=await xn(e,t);Y(!1),n.ok?(Ee(n.path),Oe(n.path),Ae(n.items)):U(n.error||(_?`读取远程目录失败`:`Failed to read remote directory`))},Ze=async e=>{if(!ve)return;Ce(!0),U(null);let t=await yn(ve,[e]);Ce(!1),t.ok?(Se(t=>t.filter(t=>t!==e)),ye&&e===`git`&&be({...ye,git:{installed:!0,version:_?`已安装`:`Installed`}})):U(t.error||(_?`安装 ${e} 失败,可能需要远端 sudo 权限`:`Failed to install ${e}, remote sudo permissions may be required`))},Qe=e=>{let t=parseInt(z,10)||22,n=K?.homeDir||`/`,r=(e||``).trim()||we||`/`;r===`~`?r=n:(r.startsWith(`~/`)||r.startsWith(`~\\`))&&(r=`${n.replace(/\/+$/,``)}/${r.slice(2).replace(/\\/g,`/`)}`),a(bn(ie,ne,t,r)),i()},$e=()=>{let e=Fe.trim();if(!e||!ve)return;if(!Sa(e)){Re(g(`invalidProjectName`));return}let t=parseInt(z,10)||22,n=we.replace(/\/+$/,``)||`/`,r=n===`/`?`/${e}`:`${n}/${e}`,c=bn(ie,ne,t,r);if(o===`project`)s?s(c):(X({type:`make_dir`,path:c}),a(c)),Pe(!1),Ie(``),Re(null),i();else{X({type:`make_dir`,path:c}),Ie(``),Pe(!1),Re(null);let e=ve,t=we;setTimeout(()=>{Xe(e,t)},300)}},et=Ca(w),tt=Ca(we),rt=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);return/^[A-Za-z]:/.test(t)?t.toLowerCase():t},it=rt(w),at=!!w&&w!==`@root`&&it!==rt(e)&&!n.some(e=>rt(e)===it);return(0,Fn.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`status-cwd-backdrop ${d??``}`.trim(),onClick:i,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation()}),(0,$.jsxs)(`div`,{className:`cwd-picker ${l??``}`.trim(),role:f,"aria-label":p,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[v?(0,$.jsxs)(`div`,{className:`cwd-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${S===`local`?`active`:``}`,onClick:()=>C(`local`),children:[`💻 `,g(`workspaceModeLocal`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${S===`remote`?`active`:``}`,onClick:()=>C(`remote`),children:[`🌐 `,g(`workspaceModeRemote`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:g(`close`),"aria-label":g(`close`),onClick:i,children:(0,$.jsx)(Z,{})})]}):(0,$.jsxs)(`div`,{className:`cwd-mode-tabs cwd-mode-tabs-single`,children:[(0,$.jsxs)(`div`,{className:`cwd-mode-tab active`,style:{cursor:`default`},children:[`💻 `,g(`workspaceModeLocal`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:g(`close`),"aria-label":g(`close`),onClick:i,children:(0,$.jsx)(Z,{})})]}),S===`local`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:w===`@root`?g(`computer`):w,children:[w===`@root`?(0,$.jsx)(Te,{}):(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{children:w===`@root`?g(`computer`):w})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":g(`projectPickerTitle`),children:[(0,$.jsx)(dn,{className:`cwd-jump ${w===`@root`?`active`:``}`,tip:g(`computer`),onClick:()=>Ve(`@root`),children:(0,$.jsx)(Te,{})}),b!==``&&(0,$.jsx)(dn,{className:`cwd-jump ${rt(w)===rt(b)?`active`:``}`,tip:`${g(`homeDir`)} ${b}`,onClick:()=>Ve(b),children:(0,$.jsx)(Ue,{})}),x!==``&&(0,$.jsx)(dn,{className:`cwd-jump ${rt(w)===rt(x)?`active`:``}`,tip:`${g(`desktopDir`)} ${x}`,onClick:()=>Ve(x),children:(0,$.jsx)(k,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-sep`,"aria-hidden":`true`}),(0,$.jsx)(dn,{className:`cwd-jump tool-up`,tip:et?`${g(`cwdGoUp`)} · ${et}`:`${g(`cwdGoUp`)} · ${_?`已在顶层`:`already at top`}`,"aria-disabled":!et,onClick:()=>{et&&Ve(et)},children:(0,$.jsx)(ft,{})}),(0,$.jsx)(dn,{className:`cwd-jump tool-root`,tip:at?g(`addWorkspaceRootHint`):w===`@root`?`${g(`addWorkspaceRoot`)} · ${_?`此电脑本身不是目录`:`This PC is not a directory`}`:it===rt(e)?`${g(`addWorkspaceRoot`)} · ${_?`已是当前项目目录`:`Already the current project`}`:`${g(`addWorkspaceRoot`)} · ${_?`已在工作区根中`:`Already a workspace root`}`,"aria-disabled":!at,onClick:()=>{at&&X({type:`set_workspace_roots`,roots:[...n,w]})},children:(0,$.jsx)(u,{})}),(0,$.jsx)(dn,{className:`cwd-jump tool-new ${O?`active`:``}`,tip:w===`@root`?`${g(`cwdNewFolder`)} · ${_?`此电脑下不能新建`:`Cannot create here`}`:g(O?`cwdCancel`:`cwdNewFolder`),"aria-disabled":w===`@root`,onClick:()=>{w!==`@root`&&(O?(A(!1),M(``),P(null)):(M(``),P(null),A(!0)))},children:(0,$.jsx)(nt,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`}),(0,$.jsx)(dn,{className:`cwd-jump primary tool-pick`,tip:w===`@root`?`${g(`cwdPickCurrent`)} · ${_?`此电脑不能作为工作目录`:`This PC cannot be a workspace`}`:`${g(`cwdPickCurrent`)} · ${w}`,"aria-disabled":w===`@root`,onClick:()=>Be(w),children:(0,$.jsx)(r,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{ref:L,className:`status-cwd-input cwd-picker-input`,value:E,placeholder:g(`enterPath`),spellCheck:!1,onChange:e=>{D(e.target.value),I(-1)},onKeyDown:We}),E.trim()!==``&&E!==w&&(0,$.jsx)(dn,{className:`cwd-jump tool-enter`,tip:`${g(`cwdEnter`)} · ${E.trim()}`,onClick:()=>{T(E.trim()),I(-1)},children:(0,$.jsx)(_e,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[et&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${g(`cwdGoUp`)} · ${et}`,onClick:()=>Ve(et),children:[(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),ze.length===0&&!et&&(0,$.jsx)(`div`,{className:`cwd-empty`,children:g(`cwdEmpty`)}),ze.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${g(`cwdEnter`)} ${e.path}`,onClick:()=>{T(e.path),D(e.path),I(-1)},children:[(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),(0,$.jsx)(dn,{className:`cwd-jump tool-choose`,tip:`${g(`cwdChoose`)} · ${e.path}`,onClick:()=>Be(e.path),children:(0,$.jsx)(r,{})})]},e.path))]}),O&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{ref:ee,value:j,autoFocus:!0,spellCheck:!1,placeholder:g(`cwdNewName`),onChange:e=>{M(e.target.value),N&&P(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),He()):e.key===`Escape`&&(e.stopPropagation(),A(!1),M(``),P(null))}}),(0,$.jsx)(dn,{className:`cwd-jump primary`,tip:g(`cwdCreate`),onClick:He,children:(0,$.jsx)(r,{})}),(0,$.jsx)(dn,{className:`cwd-jump`,tip:g(`cwdCancel`),onClick:()=>{A(!1),M(``),P(null)},children:(0,$.jsx)(Z,{})})]}),N&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:N})]})]}),S===`remote`&&(0,$.jsx)(`div`,{className:`cwd-ssh-container`,children:ve?(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,` (`,K?.os,` `,K?.arch,`)`]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,onClick:()=>{G(null),q(null),be(null)},children:g(`sshDisconnect`)})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,flexWrap:`wrap`,fontSize:`10px`},children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${ye?.git.installed?`ok`:`missing`}`,children:[`Git: `,ye?.git.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${ye?.node.installed?`ok`:`missing`}`,children:[`Node: `,ye?.node.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${ye?.bash.installed?`ok`:`missing`}`,children:[`Bash: `,ye?.bash.installed?`✓`:`✗`]})]}),xe.length>0&&(0,$.jsxs)(`div`,{className:`cwd-ssh-install-box`,children:[(0,$.jsxs)(`div`,{children:[`⚠️`,` `,_?`远端环境未检测到 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:J,onClick:()=>void Ze(xe[0]),children:J?g(`sshInstalling`):`⚡ ${g(`sshInstallTool`)} ${xe[0]}`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>Se([]),children:g(`sshSkipAndBrowse`)})]})]})]}),(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:we,children:[(0,$.jsx)(ot,{}),(0,$.jsx)(`span`,{children:we})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":g(`workspaceModeRemote`),children:[(0,$.jsx)(dn,{className:`cwd-jump tool-up`,tip:we===`/`?`${g(`cwdGoUp`)} · ${_?`已在顶层`:`already at top`}`:`${g(`cwdGoUp`)} · ${Ca(we)||`/`}`,"aria-disabled":we===`/`||je,onClick:()=>{if(je)return;let e=Ca(we);e&&ve&&Xe(ve,e)},children:(0,$.jsx)(ft,{})}),(0,$.jsx)(dn,{className:`cwd-jump tool-new ${Ne?`active`:``}`,tip:g(Ne?`cwdCancel`:`cwdNewFolder`),onClick:()=>Pe(e=>!e),children:(0,$.jsx)(nt,{})}),(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:De,placeholder:g(`enterPath`),spellCheck:!1,onChange:e=>Oe(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ve&&Xe(ve,De)}}),De.trim()&&De.trim()!==we&&ve&&(0,$.jsx)(dn,{className:`cwd-jump tool-enter`,tip:`${g(`cwdEnter`)} · ${De.trim()}`,onClick:()=>void Xe(ve,De),children:(0,$.jsx)(_e,{})}),(0,$.jsx)(dn,{className:`cwd-jump primary tool-pick`,tip:`${g(`sshOpenRemoteWorkspace`)} · ${De.trim()||we}`,onClick:()=>Qe(De.trim()||we),children:(0,$.jsx)(r,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[!je&&tt&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${g(`cwdGoUp`)} · ${tt}`,onClick:()=>{ve&&Xe(ve,tt)},children:[(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),je?(0,$.jsx)(`div`,{className:`cwd-empty`,children:_?`正在加载远程目录…`:`Loading remote directory…`}):ke.length===0?(0,$.jsx)(`div`,{className:`cwd-empty`,children:g(`cwdEmpty`)}):ke.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${e.type===`dir`?g(`cwdEnter`):``} ${e.path}`,onClick:()=>{e.type===`dir`&&ve&&Xe(ve,e.path)},children:[e.type===`dir`?(0,$.jsx)(Je,{}):(0,$.jsx)(`span`,{children:`📄`}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),e.type===`dir`&&(0,$.jsx)(dn,{className:`cwd-jump tool-choose`,tip:`${g(`cwdChoose`)} · ${e.path}`,onClick:()=>Qe(e.path),children:(0,$.jsx)(r,{})})]},e.path))]}),ve&&Ne&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{value:Fe,autoFocus:!0,spellCheck:!1,placeholder:g(`cwdNewName`),onChange:e=>{Ie(e.target.value),Le&&Re(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),$e()):e.key===`Escape`&&(e.stopPropagation(),Pe(!1),Ie(``),Re(null))}}),(0,$.jsx)(dn,{className:`cwd-jump primary`,tip:g(`cwdCreate`),onClick:$e,children:(0,$.jsx)(r,{})}),(0,$.jsx)(dn,{className:`cwd-jump`,tip:g(`cwdCancel`),onClick:()=>{Pe(!1),Ie(``),Re(null)},children:(0,$.jsx)(Z,{})})]}),Le&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:Le})]})]}):(0,$.jsxs)(`div`,{className:`cwd-ssh-form`,children:[R.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profiles-title`,children:[`📋 `,g(`sshSavedProfiles`)]}),R.map(e=>(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-card`,onClick:()=>{re(e.host),B(String(e.port)),ae(e.username),oe(e.authType),e.privateKeyPath&&ue(e.privateKeyPath),Ke({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)(y,{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:g(`delete`),onClick:t=>{t.stopPropagation(),confirm(g(`sshDeleteProfileConfirm`))&&(Sn(e.name),te(t=>t.filter(t=>t.name!==e.name)))},children:(0,$.jsx)(Ge,{})})]},e.name))]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,style:{marginTop:`4px`},children:[(0,$.jsxs)(`label`,{children:[g(`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:[g(`sshPort`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,style:{width:`45px`,flex:`none`},value:z,onChange:e=>B(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`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:[g(`sshAuthType`),`:`]}),(0,$.jsxs)(`select`,{className:`cwd-ssh-select`,value:V,onChange:e=>oe(e.target.value),children:[(0,$.jsx)(`option`,{value:`password`,children:g(`sshPassword`)}),(0,$.jsx)(`option`,{value:`key`,children:g(`sshKeyPath`)}),(0,$.jsx)(`option`,{value:`agent`,children:g(`sshAgent`)})]})]}),V===`password`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`sshPassword`),`:`]}),(0,$.jsx)(`input`,{type:`password`,className:`cwd-ssh-input`,value:se,placeholder:`••••••••`,onChange:e=>ce(e.target.value)})]}),V===`key`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`sshKeyPath`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:le,placeholder:`~/.ssh/id_rsa`,onChange:e=>ue(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:de,onChange:e=>fe(e.target.checked),style:{marginRight:`4px`}}),g(`sshSaveProfile`)]})}),de&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`sshProfileName`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:pe,placeholder:`my-server`,onChange:e=>me(e.target.value)})]}),ge&&(0,$.jsxs)(`div`,{style:{color:`var(--red)`,fontSize:`11px`,padding:`2px 0`},children:[`⚠️ `,ge]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,style:{marginTop:`4px`},disabled:H,onClick:()=>void Ke(),children:g(H?`sshConnecting`:`sshConnectAndProbe`)})]})})]})]}),h??document.body)}function Ta({open:e,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,onCreateProject:o,mode:s=`project`,localOnly:c,portalContainer:l}){let u=W();return e?(0,$.jsx)(wa,{portalContainer:l,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:u(`projectPickerTitle`)}):null}function Ea(e){return He({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 Da(e){return He({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 Oa({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}=st(),{panelRef:f,style:p,measure:m}=Rn({anchor:e,anchorEl:t,onClose:u}),[,g]=(0,Q.useState)(null),_=(0,Q.useRef)(null),[v,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${v===e.id?` drop-target`:``}${t?` pm-row-ext`:``}`,role:`none`,onDragOver:t=>{!n&&_.current&&(t.preventDefault(),y(e.id))},onDrop:t=>{t.preventDefault(),w(t.dataTransfer.getData(`text/plain`)||_.current,e.id),_.current=null,g(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=>{g(e.id),_.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:()=>{_.current=null,g(null),y(null)},onKeyDown:t=>{(t.key===`ArrowUp`||t.key===`ArrowDown`)&&(t.preventDefault(),C(e.id,t.key===`ArrowUp`?-1:1))},children:(0,$.jsx)(h,{"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)(ii,{icon:o,iconSvg:e.iconSvg,className:`pm-icon`}):(0,$.jsx)(M,{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)(ue,{"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)(Da,{"aria-hidden":!0}):(0,$.jsx)(Ea,{"aria-hidden":!0})})]})]},e.id)};return(0,Fn.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)(M,{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)(ue,{"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)(ue,{"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)(I,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginMenuManage`)})]})]})]}),document.body)}var ka=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Aa={off:0,minimal:1024,low:2048,medium:8192,high:16384,xhigh:32e3,max:64e3},ja=[{value:``,label:`自动检测 (Auto / Default)`},{value:`openai`,label:`OpenAI 档位 (reasoning_effort: low/med/high)`},{value:`qwen`,label:`通义千问 Qwen (enable_thinking: true)`},{value:`deepseek`,label:`DeepSeek 协议 (thinking: {type: enabled})`},{value:`openrouter`,label:`OpenRouter 协议 (reasoning: {effort})`},{value:`zai`,label:`智谱 GLM (zai thinking 对象)`}],Ma=[{id:`claude-budget`,name:`⚡ Claude 3.7+ 预算型 (1K~64K)`,desc:`支持关/开,按 Token 精准预算(1024~64000 tokens)`,type:`budget`,map:{off:`off`,minimal:`1024`,low:`2048`,medium:`8192`,high:`16384`,xhigh:`32000`,max:`64000`}},{id:`openai-effort`,name:`⚡ OpenAI o 系列档位 (低/中/高)`,desc:`标准 effort 档位,不可关闭思考`,type:`effort`,thinkingFormat:`openai`,map:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`qwen-thinking`,name:`⚡ Qwen 通义千问协议`,desc:`发送 enable_thinking: true 专属参数`,type:`effort`,thinkingFormat:`qwen`,map:{off:`off`,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`deepseek-compat`,name:`⚡ DeepSeek 兼容协议`,desc:`发送 thinking: { type: 'enabled' } 协议对象`,type:`effort`,thinkingFormat:`deepseek`,map:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`openrouter-effort`,name:`⚡ OpenRouter 规范`,desc:`发送 reasoning: { effort } 跨端归一格式`,type:`effort`,thinkingFormat:`openrouter`,map:{off:`none`,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`gemini-budget`,name:`⚡ Gemini 2.0+ 预算型 (0~32K)`,desc:`Gemini Flash Thinking 预算控制`,type:`budget`,map:{off:`0`,minimal:`1024`,low:`2048`,medium:`8192`,high:`16384`,xhigh:`24576`,max:`32768`}},{id:`full-open`,name:`⚡ 全开模式 (全部 7 档)`,desc:`包含极高与最大,全量开放供自由选择`,type:`full`,map:{off:`off`,minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`}},{id:`fixed-deepseek`,name:`⚡ 固定深度推理 (不可调)`,desc:`适用于 DeepSeek R1 / QwQ 等不可控模型`,type:`fixed`,map:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:null,max:null}}];function Na(e,t,n,r){if(e===`off`)return t;if(n&&/^\d+$/.test(String(n).trim())){let e=Number(n);return`${t} (${e>=1024?`${Math.round(e/1024)}K`:`${e}`} tokens)`}if(r&&e in Aa){let n=Aa[e];if(n&&n>0)return`${t} (${n>=1024?`${Math.round(n/1024)}K`:`${n}`} tokens)`}return t}function Pa(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 ka)i(e);let a=typeof n==`string`?n:n==null?``:String(n);return a&&i(a),r}var Fa={activity:(0,$.jsx)(ye,{}),aperture:(0,$.jsx)(ke,{}),branch:(0,$.jsx)(q,{}),browser:(0,$.jsx)(ot,{}),chat:(0,$.jsx)(f,{}),check:(0,$.jsx)(r,{}),"chevron-up":(0,$.jsx)(S,{}),clock:(0,$.jsx)(vt,{}),code:(0,$.jsx)(a,{}),coins:(0,$.jsx)(de,{}),copy:(0,$.jsx)(b,{}),cpu:(0,$.jsx)(T,{}),cut:(0,$.jsx)(x,{}),database:(0,$.jsx)(C,{}),dot:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`●`}),download:(0,$.jsx)(le,{}),edit:(0,$.jsx)(fe,{}),engine:(0,$.jsx)(ke,{}),eye:(0,$.jsx)(J,{}),feather:(0,$.jsx)(Ke,{}),file:(0,$.jsx)(et,{}),folder:(0,$.jsx)(Je,{}),folders:(0,$.jsx)(Xn,{}),gauge:(0,$.jsx)(ye,{}),git:(0,$.jsx)(q,{}),github:(0,$.jsx)(Be,{}),globe:(0,$.jsx)(ot,{}),grid:(0,$.jsx)(xe,{}),hash:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`#`}),image:(0,$.jsx)(je,{}),info:(0,$.jsx)(Oe,{}),layers:(0,$.jsx)(ct,{}),link:(0,$.jsx)(ve,{}),list:(0,$.jsx)(mt,{}),lock:(0,$.jsx)(re,{}),markdown:(0,$.jsx)(U,{}),maximize:(0,$.jsx)(B,{}),menu:(0,$.jsx)(h,{}),minimize:(0,$.jsx)(i,{}),message:(0,$.jsx)(f,{}),open:(0,$.jsx)(t,{}),paste:(0,$.jsx)(R,{}),pin:(0,$.jsx)(Ve,{}),plus:(0,$.jsx)(te,{}),refresh:(0,$.jsx)(yt,{}),sandbox:(0,$.jsx)(Zn,{}),save:(0,$.jsx)(oe,{}),share:(0,$.jsx)(Jn,{}),search:(0,$.jsx)(ae,{}),send:(0,$.jsx)(ce,{}),settings:(0,$.jsx)(E,{}),sound:(0,$.jsx)(ze,{}),sun:(0,$.jsx)(ee,{}),target:(0,$.jsx)(Ze,{}),terminal:(0,$.jsx)(Se,{}),text:(0,$.jsx)($e,{}),trash:(0,$.jsx)(Ge,{}),undo:(0,$.jsx)(v,{}),upload:(0,$.jsx)(ge,{}),users:(0,$.jsx)(K,{}),volume:(0,$.jsx)(ze,{}),wrap:(0,$.jsx)(ie,{}),x:(0,$.jsx)(Z,{}),zap:(0,$.jsx)(be,{}),zoom:(0,$.jsx)(we,{})};Object.keys(Fa);function Ia(e){if(e.iconSvg)return(0,$.jsx)(ii,{icon:e.icon,iconSvg:e.iconSvg});if(!e.icon)return null;let t=Fa[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 La=0,Ra=``;function za(){typeof document<`u`&&(La===0&&(Ra=document.body.style.overflow,document.body.style.overflow=`hidden`),La++)}function Ba(){typeof document<`u`&&(La=Math.max(0,La-1),La===0&&(document.body.style.overflow=Ra))}function Va({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 _=W(),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(wt(()=>a&&S?(y||x(!1),s?.(!1),!0):p?(v.current(),!0):!1,e),(0,Q.useEffect)(()=>{if(e&&g)return za(),()=>{Ba()}},[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,Fn.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)(Le,{}):(0,$.jsx)(dt,{})}),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 Ha({plugin:e,models:t=[]}){let n=W(),r=gt(),i=c(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}),[l,u]=(0,Q.useState)(!1);if(a.length===0)return null;let d=(e,t)=>s(n=>({...n,[e]:t})),f=e=>Pa(e,t,o[e.key]).map(r=>{if(r===``)return{value:``,label:n(`pluginSettingsInherit`)};if(e.optionsFrom===`thinkingLevels`&&ka.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}}),p=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=>d(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=>d(t.key,e.target.value)}):t.type===`select`?(0,$.jsx)(`select`,{value:String(o[t.key]??``),onChange:e=>d(t.key,e.target.value),children:f(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=>d(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:!p||l,onClick:()=>{u(!0),X({type:`plugin_settings`,pluginId:e.id,values:o}),setTimeout(()=>u(!1),800)},children:n(l?`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 Ua({plugin:e}){if(e.iconSvg)return(0,$.jsx)(ii,{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=Ia({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)(ue,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(M,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(_t,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0})}function Wa({open:e=!0,onClose:n,focusPluginId:i,plugins:a,disabledPlugins:o,models:s=[],onTogglePlugin:c,onOpenView:l,onOpenMarketplace:u}){let d=W(),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(`all`),[_,v]=(0,Q.useState)({}),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(!1),C=(0,Q.useRef)(new Map),w=(0,Q.useMemo)(()=>new Set(o),[o]),T=(0,Q.useMemo)(()=>{let e=0,t=0,n=0;for(let r of a){let i=!!(r.settingsSchema&&r.settingsSchema.length>0),a=w.has(r.id),o=!!r.error;i&&e++,!a&&!o&&t++,a&&n++}return{total:a.length,configurable:e,enabled:t,disabled:n}},[a,w]);(0,Q.useEffect)(()=>{if(!e||!i)return;v(e=>({...e,[i]:!0})),b(i),a.find(e=>e.id===i)&&h(`all`);let t=setTimeout(()=>{let e=C.current.get(i);e&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},120),n=setTimeout(()=>{b(null)},2600);return()=>{clearTimeout(t),clearTimeout(n)}},[e,i,a]);let E=(0,Q.useCallback)(e=>{v(t=>({...t,[e]:!t[e]}))},[]),D=(0,Q.useCallback)(()=>{let e=a.some(e=>e.settingsSchema?.length&&!_[e.id]),t={};for(let n of a)n.settingsSchema?.length&&(t[n.id]=e);v(t)},[a,_]),O=(0,Q.useMemo)(()=>{let e=f.trim().toLowerCase();return a.filter(t=>{let n=!!(t.settingsSchema&&t.settingsSchema.length>0),r=w.has(t.id),i=!!t.error;if(m===`configurable`&&!n||m===`enabled`&&(r||i)||m===`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})},[a,m,f,w]),k=(0,Q.useCallback)(()=>{S(!0),X({type:`plugins_reload`}),setTimeout(()=>S(!1),800)},[]);return(0,$.jsxs)(Va,{open:e,onClose:n,className:`plugin-mgr-modal`,ariaLabel:d(`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:d(`pluginCountSummary`,{total:T.total,enabled:T.enabled,configurable:T.configurable}),children:[(0,$.jsx)(M,{className:`plugin-mgr-title-icon`,"aria-hidden":!0}),(0,$.jsx)(`h2`,{className:`plugin-mgr-title`,children:d(`pluginManagerTitle`)})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-title-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,title:d(`pluginRescanHint`),onClick:k,disabled:x,children:[(0,$.jsx)(yt,{className:x?`spin`:``,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginRescan`)})]}),u&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{n(),u()},children:[(0,$.jsx)(I,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginGoMarket`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-close-btn`,"aria-label":d(`close`),title:d(`close`),onClick:n,children:(0,$.jsx)(Z,{"aria-hidden":!0})})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-toolbar`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-search-wrap`,children:[(0,$.jsx)(ae,{className:`plugin-mgr-search-icon`,"aria-hidden":!0}),(0,$.jsx)(`input`,{type:`text`,className:`plugin-mgr-search-input`,placeholder:d(`pluginSearchPlaceholder`),value:f,onChange:e=>p(e.target.value)}),f&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-search-clear`,onClick:()=>p(``),"aria-label":`Clear`,children:(0,$.jsx)(Z,{"aria-hidden":!0})})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-filters`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${m===`all`?` active`:``}`,onClick:()=>h(`all`),children:[d(`pluginFilterAll`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:T.total})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${m===`configurable`?` active`:``}`,onClick:()=>h(`configurable`),children:[(0,$.jsx)(ue,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),d(`pluginFilterConfigurable`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:T.configurable})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${m===`enabled`?` active`:``}`,onClick:()=>h(`enabled`),children:[(0,$.jsx)(r,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),d(`pluginFilterEnabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:T.enabled})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${m===`disabled`?` active`:``}`,onClick:()=>h(`disabled`),children:[d(`pluginFilterDisabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:T.disabled})]})]}),T.configurable>0&&(0,$.jsx)(`div`,{className:`plugin-mgr-expand-action`,children:(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-text-btn`,onClick:D,children:a.some(e=>e.settingsSchema?.length&&!_[e.id])?d(`pluginExpandAll`):d(`pluginCollapseAll`)})})]})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-body`,children:O.length===0?(0,$.jsxs)(`div`,{className:`plugin-mgr-empty`,children:[(0,$.jsx)(M,{className:`plugin-mgr-empty-icon`,"aria-hidden":!0}),(0,$.jsx)(`p`,{children:d(f||m!==`all`?`pluginEmptyFilter`:`pluginMenuEmpty`)}),(f||m!==`all`)&&(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{p(``),h(`all`)},children:d(`pluginFilterAll`)})]}):(0,$.jsx)(`div`,{className:`plugin-mgr-list`,children:O.map(e=>{let r=!!(e.settingsSchema&&e.settingsSchema.length>0),i=w.has(e.id),a=!!e.error,o=!!_[e.id],u=e.view!==!1&&!a,f=y===e.id,p=e.homepage||(e.source?.startsWith(`http`)?e.source:void 0);return(0,$.jsxs)(`div`,{ref:t=>{t?C.current.set(e.id,t):C.current.delete(e.id)},className:`plugin-mgr-card${i?` disabled`:``}${a?` 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)(Ua,{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:[r&&(0,$.jsxs)(`span`,{className:`plugin-badge config`,title:d(`pluginBadgeConfig`),children:[(0,$.jsx)(ue,{"aria-hidden":!0}),d(`pluginBadgeConfig`)]}),u?(0,$.jsx)(`span`,{className:`plugin-badge view`,children:d(`pluginBadgeView`)}):(0,$.jsx)(`span`,{className:`plugin-badge bg`,children:d(`pluginBadgeBg`)}),e.agentTools&&e.agentTools.length>0&&(0,$.jsx)(`span`,{className:`plugin-badge tools`,children:d(`pluginBadgeTools`,{count:e.agentTools.length})}),a&&(0,$.jsxs)(`span`,{className:`plugin-badge error`,children:[(0,$.jsx)(Ye,{"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:d(`pluginOfficialLink`),children:(0,$.jsx)(t,{"aria-hidden":!0})}),u&&!i&&l&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-open-view`,onClick:()=>{n(),l(e.id)},title:d(`pluginOpenView`),children:[(0,$.jsx)(J,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginOpenView`)})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-toggle-wrap`,children:(0,$.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!i&&!a,disabled:a,title:d(i?`pluginToggleEnable`:`pluginToggleDisable`),className:`plugin-mgr-switch${!i&&!a?` on`:``}`,onClick:()=>c(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)(Ye,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:e.error})]}),r&&(0,$.jsxs)(`div`,{className:`plugin-mgr-settings-section`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-settings-toggle`,onClick:()=>E(e.id),"aria-expanded":o,children:[o?(0,$.jsx)(A,{"aria-hidden":!0}):(0,$.jsx)(g,{"aria-hidden":!0}),(0,$.jsx)(ue,{className:`plugin-mgr-settings-icon`,"aria-hidden":!0}),(0,$.jsxs)(`span`,{className:`plugin-mgr-settings-toggle-title`,children:[d(`pluginSettingsTitle`),` (`,e.settingsSchema.length,`)`]}),(0,$.jsx)(`span`,{className:`plugin-mgr-settings-toggle-hint`,children:d(o?`pluginSettingsHide`:`pluginSettingsShow`)})]}),o&&(0,$.jsx)(`div`,{className:`plugin-mgr-settings-content`,children:(0,$.jsx)(Ha,{plugin:e,models:s})})]})]},e.id)})})})]})}function Ga({onClose:e}){let t=W(),{locale:n,setLocale:r,reloadPacks:i}=st(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``);async function f(){try{let e=await fetch(z(d(`/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)(()=>{f()},[]);async function p(e){u(e),c(``);try{let t=await fetch(z(d(`/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 f()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}async function m(e){u(e),c(``);try{let t=await fetch(z(d(`/api/locales/${e}`)),{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);H(e),n===e&&r(`zh`),await i(),await f()}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)(ot,{}),` `,t(`localePacks`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:t(`close`),onClick:e,children:(0,$.jsx)(Z,{})})]}),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 m(e.code),children:[(0,$.jsx)(Ge,{}),(0,$.jsx)(`span`,{children:t(n?`localeRemoving`:`localeRemove`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:n,title:t(`localeInstall`),onClick:()=>void p(e.code),children:[(0,$.jsx)(le,{}),(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 f(),children:[(0,$.jsx)(yt,{}),(0,$.jsx)(`span`,{children:t(`bgTaskRefresh`)})]})})]})})}var Ka=`xing-shuyin/pi-web-ui`,qa={state:`idle`,version:null,percent:0,message:null};function Ja(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Ya(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:Ja(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 Xa(e){if(!Pt(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 Za(e){return e instanceof Error?e.message:String(e)}function Qa(e){let t=(e??``).trim().replace(/^v/,``);return t?`https://github.com/${Ka}/releases/tag/v${t}`:`https://github.com/${Ka}/releases/latest`}function $a(){let[e]=(0,Q.useState)(()=>Xa()),[t,n]=(0,Q.useState)(qa);(0,Q.useEffect)(()=>{if(e)return e.onEvent(e=>n(t=>Ya(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:Za(e)}))))},[e]),i=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`downloading`,message:null})),e.download().catch(e=>n(t=>({...t,state:`error`,message:Za(e)}))))},[e]),a=(0,Q.useCallback)(()=>{e&&e.quitAndInstall().catch(e=>n(t=>({...t,state:`error`,message:Za(e)})))},[e]);return{...t,bridge:e,check:r,download:i,quitAndInstall:a}}function eo(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 to=2e3;function no(e,t,n=to){return e.filter(e=>t-e.t<=n)}function ro(e,t=to){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 io(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 ao(e){let t=0;for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text?t+=io(n.text):n.type===`thinking`&&typeof n.thinking==`string`&&n.thinking&&(t+=io(n.thinking));return t}var oo=[{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 so({direction:e,align:t,className:n,label:i,caret:a=!1,bar:o,portal:s}){let{engine:c}=he(),l=tt(),{t:u}=st(),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),h=(0,Q.useRef)(null),g=e??(o===`left`?`right`:o===`right`?`left`:o===`bottom`?`up`:`down`),_=s??(o===`left`||o===`right`||o===`bottom`),v=e=>{e?X({type:`check_engines`}):m(null),f(e)},y=oo.find(e=>e.id===c)??{id:c,titleKey:`settingsEnginePiTitle`,badge:c.toUpperCase(),tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-${c}`},b=u(y.titleKey),x=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ke,{className:`bar-item-icon engine-picker-icon`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`chip-sub bar-item-text engine-picker-name`,children:i}),(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${y.colorClass}`,children:y.badge})]}):(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${y.colorClass}`,children:y.badge})]});return(0,$.jsx)(`div`,{ref:h,className:`engine-picker-wrap ${y.colorClass} ${n??``}`,"data-bar-item":`host:engine`,children:(0,$.jsxs)(Dt,{trigger:x,open:d,onOpenChange:v,direction:g,align:t??(o===`right`?`right`:`left`),fit:!0,caret:a,portal:_,triggerClassName:`bar-item chip engine-picker-btn ${y.colorClass}`,menuClassName:`engine-picker-menu`,tip:`${u(`engineBadge`)}: ${i??b} — ${u(`engineSwitchTip`)}`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-header`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-title`,children:[(0,$.jsx)(ke,{}),(0,$.jsx)(`span`,{children:u(`settingsEngineSection`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-subtitle`,children:u(`enginePickerDesc`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-list`,role:`menu`,children:oo.map(e=>{let t=e.id===c,n=l.find(t=>t.id===e.id),i=e.id===`pi`||(n?n.installed:!1),a=!!n?.updating,o=!!n?.uninstalling,s=!!(i&&n?.hasUpdate&&n?.latestVersion),d=s||a,h=e.id!==`pi`&&i,g=t=>{t.stopPropagation(),f(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:u(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}))},_=t=>{t.stopPropagation(),!(a||o)&&(f(!1),X({type:`update_engine`,engineId:e.id}))},v=n=>{n.stopPropagation(),!(o||a)&&(t||(p===e.id?(m(null),X({type:`uninstall_engine`,engineId:e.id})):m(e.id)))},y=()=>{if(!i){f(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:u(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}));return}f(!1),t||X({type:`switch_engine`,engine:e.id})};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,title:i?void 0:u(`engineInstallTip`),className:`engine-picker-item ${e.colorClass}${t?` active`:``}${i?``:` uninstalled`}`,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),y())},onClick:y,children:[(0,$.jsxs)(`div`,{className:`engine-picker-item-head`,children:[(0,$.jsx)(ke,{className:`engine-picker-item-icon`}),(0,$.jsx)(`span`,{className:`engine-badge ${e.colorClass}`,children:e.badge}),u(e.titleKey)!==e.badge&&(0,$.jsx)(`span`,{className:`engine-picker-item-name`,children:u(e.titleKey)}),(0,$.jsx)(`span`,{className:`engine-picker-item-tag${i?o?` uninstalling`:a||s?` update-available`:``:` uninstalled`}`,title:s?u(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}):void 0,children:u(i?o?`engineUninstalling`:a?`engineUpdating`:s?`engineUpdateAvailable`:e.tagKey:`engineNotInstalled`)}),!i&&e.installCommand&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-install-btn`,title:u(`engineInstallTip`),onClick:g,children:[(0,$.jsx)(le,{className:`engine-install-icon`}),(0,$.jsx)(`span`,{children:u(`engineInstall`)})]}),d&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-update-btn`,disabled:a||o,title:a?u(`engineUpdating`):u(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}),onClick:_,children:[(0,$.jsx)(yt,{className:`engine-update-icon${a?` spinning`:``}`}),(0,$.jsx)(`span`,{children:u(a?`engineUpdating`:`engineUpdate`)})]}),h&&(0,$.jsxs)(`button`,{type:`button`,"data-testid":`engine-uninstall-${e.id}`,className:`engine-picker-uninstall-btn${p===e.id?` confirm`:``}`,disabled:o||a||t,title:t?u(`engineActiveNoUninstall`):o?u(`engineUninstalling`):p===e.id?u(`engineUninstallConfirm`):u(`engineUninstallTip`),onClick:v,children:[(0,$.jsx)(Ge,{className:`engine-uninstall-icon`}),(0,$.jsx)(`span`,{children:o?u(`engineUninstalling`):p===e.id?u(`engineUninstallConfirm`):u(`engineUninstall`)})]}),t&&(0,$.jsx)(r,{className:`engine-picker-check`})]}),(0,$.jsx)(`div`,{className:`engine-picker-item-desc`,children:u(e.descKey)})]},e.id)})})]})})}function co(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}var lo={systemPrompt:`settingsSystemPrompt`,memoryFiles:`contextMemoryFiles`,tools:`contextTools`,skills:`contextSkills`,toolResults:`contextToolResults`,messages:`messages`,other:`contextOther`};function uo({context:e,bar:t,title:n,onContextMenu:r,children:i}){let a=W(),o=(0,Q.useId)(),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(!1),{panelRef:u,style:d,measure:f}=Rn({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 lo)??[],x=b.length>0,S=b.map(e=>({...e,label:a(lo[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,Fn.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":`${co(_)} / ${co(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:co(_),total:co(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:co(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:co(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:co(m),max:co(p)})})]}):(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextUsageUnavailable`)})]}),document.body)]})}function fo(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 po({entry:e,bar:t,chat:n,view:r,plugins:i,onViewChange:a,onOpenPanel:o,onOpenSettings:s,onOpenGlobalSearch:l,onOpenBgTasks:u,onOpenProjectPicker:d,onOpenPluginMenu:p,isPluginMenuOpen:m,isProjectPickerOpen:g,onUiAction:_,uiContextEntries:v,dropdownProps:y,zenMode:b,onToggleZenMode:x,onOpenSandboxModal:S}){let w=W(),{locale:D,packs:O,setLocale:k}=st(),{engine:A}=he(),j=A===`dsh`,[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),ne=n.settings?.uiLayout,re=n.state,z=re?.stats,B=re?.isStreaming??!1,ie=re?.turnTiming,V=!!ie&&ie.finishedAt===void 0,[oe,se]=(0,Q.useState)(Date.now);(0,Q.useEffect)(()=>{if(e.id!==`host:working`||!V)return;se(Date.now());let t=window.setInterval(()=>se(Date.now()),1e3);return()=>window.clearInterval(t)},[e.id,V,ie?.startedAt]);let ce=ln(z?.cost??0),ue=(0,Q.useRef)([]),de=re?.streamingMessage?ao(re.streamingMessage.content):0;(0,Q.useEffect)(()=>{if(!B){ue.current=[];return}let e=Date.now(),t=ue.current,n=t[t.length-1];n&&e-n.t<250||(ue.current=no([...t,{t:e,out:de}],e))},[B,de]);let fe=B?ro(ue.current):0,pe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current)},[]);let me=n=>{n.preventDefault(),n.stopPropagation();let r=t=>{let n={...ne?.slots,[e.id]:t},r={...ne?.align};(t===`sidebar.left`||t===`sidebar.right`)&&!r[e.id]&&(r[e.id]=`center`),X({type:`set_settings`,uiLayout:{...ne,slots:n,...r[e.id]?{align:r}:{}}})},i=()=>{let t=new Set(ne?.hidden??[]);t.add(e.id);let n=(ne?.shown??[]).filter(t=>t!==e.id);X({type:`set_settings`,uiLayout:{...ne,hidden:[...t],shown:n}})},a=()=>{X({type:`set_settings`,uiLayout:qi(ne,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:[]}),Si.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||ne?.slots?.[e.id]||ne?.labels?.[e.id]||ne?.align?.[e.id]||ne?.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:[]}),v&&v.length>0&&o.push(...v),na({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()}})},H=e.id,ge=e.labelExplicit?e.label:``,U=e=>ge||e,_e=e=>ge?`${ge} ${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=>_?.(e,t.target.value),onContextMenu:me,"data-bar-item":H,children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})}if(H===`host:brand`)return(0,$.jsx)(Kn,{label:U(`pi-web-ui`),barItem:!0,onContextMenu:me});if(H===`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:me,"data-bar-item":H,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(H===`host:engine`)return(0,$.jsx)(`span`,{onContextMenu:me,"data-bar-item":H,className:`bar-item-engine-wrap`,style:{display:`inline-flex`,alignItems:`center`},children:(0,$.jsx)(so,{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(H===`host:ctx`){let e=z?.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?co(e.tokens):null,c=a>0?co(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`)}: ${co(e?.tokens??0)} / ${co(r)} (${w(`softCapMarker`)}, max ${co(e?.contextWindow??0)})`:r!==null&&r>0?`${w(`contextUsage`)}: ${l} · ${w(`softCapMarker`)}: ${co(r)}`:`${w(`contextUsage`)}: ${l}`,f=o!==null&&o>0?+(31.42*(1-Math.min(o,100)/100)).toFixed(2):31.42;return(0,$.jsxs)(uo,{context:e,bar:t,title:d,onContextMenu:me,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:[ge?`${ge} `:``,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}:${re?.conversationId??re?.sessionId??``}`)}if(H===`host:cache`){let e=eo(z?.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:co(e.read),write:co(e.write),miss:co(e.miss),input:co(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:me,"data-bar-item":H,children:[(0,$.jsx)(C,{className:`bar-item-icon`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[ge?`${ge} `:``,(0,$.jsx)(`b`,{className:`cache-pct ${n}`,children:r})]})]})}if(H===`host:cost`){let e=z?.cost??0,t=ce.tooltip||w(`cumulativeCost`);return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cost bar-item-cost${e<=0?` is-zero`:``}${ge?` has-name`:``}`,title:t,"data-tip":t,onContextMenu:me,"data-bar-item":H,children:[ge?(0,$.jsx)(`span`,{className:`bar-item-text`,children:ge}):null,ce.symbol?(0,$.jsx)(`span`,{className:`bar-item-char`,children:ce.symbol}):null,(0,$.jsx)(`span`,{className:`bar-item-text`,children:ce.value})]})}if(H===`host:msg-count`){let e=z?.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:me,"data-bar-item":H,children:[(0,$.jsx)(f,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(String(e))})]})}if(H===`host:working`){if(!B&&!ie)return null;let e=B||V,t=w(e?`working`:`done`),n=ie?Math.max(0,Math.floor(((ie.finishedAt??oe)-ie.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=(re?.queue?.steering?.length??0)+(re?.queue?.followUp?.length??0);return(0,$.jsxs)(`span`,{className:`bar-item status-item bar-item-working${e?` working`:``}`,title:`${t}${ie?` · ${r}`:``}`,"data-tip":`${t}${ie?` · ${r}`:``}`,onContextMenu:me,"data-bar-item":H,children:[e&&(0,$.jsx)(`span`,{className:`working-spin`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[U(t),i>0&&` ⏳ ${i}`]}),ie&&(0,$.jsx)(`span`,{className:`bar-item-duration`,children:r}),e&&fe>0&&(0,$.jsx)(`span`,{className:`status-rate bar-item-rate`,title:w(`rateTip`),children:`${Math.round(fe)}${w(`tps`)}`})]})}if(H===`host:status-delegate`)return re?.delegateMode?(0,$.jsxs)(`span`,{className:`bar-item status-item delegate-badge bar-item-delegate`,title:re.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),"data-tip":re.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),onContextMenu:me,"data-bar-item":H,children:[(0,$.jsx)(`span`,{className:`bar-item-icon`,children:`🔎`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:U(w(`delegateModeBadge`))}),re.delegateConvId?(0,$.jsx)(`button`,{type:`button`,className:`delegate-badge-open`,title:w(`delegateModeOpenTip`),onClick:()=>X({type:`switch_conversation`,id:re.delegateConvId}),children:`↗`}):null]}):null;if(H===`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:me,"data-bar-item":H,children:[(0,$.jsx)(T,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:_e(`${t} · ${r}`)})]})}if(H===`host:browser`)return n.settings?.disabledAgentTools?.includes(`browser_page`)?null:(0,$.jsx)(`span`,{className:`bar-item-wrap`,onContextMenu:me,"data-bar-item":H,children:(0,$.jsx)(ur,{})});let ve=t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`;if(H===`host:language`)return(0,$.jsxs)(Dt,{direction:ve,align:t===`right`?`right`:`left`,portal:!0,open:N,onOpenChange:P,tip:U(w(`language`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:me,dataBarItem:H,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ot,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(fo(D))})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`language`)}),O.map(e=>(0,$.jsx)(Et,{active:D===e.code,onClick:()=>{k(e.code),P(!1)},children:e.nativeName},e.code)),y?.onLocaleModalOpen?(0,$.jsxs)(Et,{onClick:()=>{P(!1),y.onLocaleModalOpen?.()},children:[(0,$.jsx)(le,{}),` `,w(`localeGetMore`)]}):null]});if(H===`host:theme`){let e=y?.themes??[],n=y?.theme??null;return(0,$.jsx)(Dt,{direction:ve,align:t===`right`?`right`:`left`,portal:!0,open:F,onOpenChange:t=>{I(t),t&&e.length===0&&y?.reloadThemes?.()},tip:U(w(`theme`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:me,dataBarItem:H,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ee,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:U(w(`theme`))})]}),children:(()=>{let t=e.filter(e=>e.group===`classic`),r=e.filter(e=>e.group!==`classic`),i=e=>{let t=c(D)?e.name:e.nameEn??e.name,n=e.scheme===`light`?w(`themeLight`):e.scheme===`dark`?w(`themeDark`):``;return n?c(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)(Et,{active:n===e.id,onClick:()=>{y?.onThemeChange?.(e.id),I(!1)},children:i(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:t.length>0?w(`themeGroupBuiltin`):w(`theme`)}),(0,$.jsx)(Et,{active:n===null,onClick:()=>{y?.onThemeChange?.(null),I(!1)},children:w(`themeDefault`)}),r.map(e=>(0,$.jsx)(Et,{active:n===e.id,onClick:()=>{y?.onThemeChange?.(e.id),I(!1)},children:i(e)},e.id))]})})()})}if(H===`host:update`){let e=y?.updatesCount??0;return y?.managed?(0,$.jsxs)(`span`,{className:`bar-item chip`,title:w(`updatesManaged`),"data-tip":w(`updatesManaged`),onContextMenu:me,"data-bar-item":H,children:[(0,$.jsx)(le,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:_e(`v${y?.appVersion??n.update?.current??`…`}`)})]}):(0,$.jsxs)(Dt,{direction:ve,align:t===`right`?`right`:`left`,portal:!0,open:L,onOpenChange:e=>{R(e),e&&(X({type:`check_update`}),X({type:`check_updates_all`}))},tip:U(w(`update`)),fit:!0,caret:!1,triggerClassName:`bar-item chip`,onContextMenu:me,dataBarItem:H,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{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`)}),y?.renderUpdateBody?.(),y?.renderAllUpdatesBody?.()]})}let G=null,K=e.label,be=null,xe=!1,J=!1,Ce=``,we,Te,Ee;switch(H){case`host:chat`:G=(0,$.jsx)(f,{className:`bar-item-icon`}),K=U(w(`chat`)),xe=r===`chat`,J=!0,Te=()=>a?.(`chat`);break;case`host:terminal`:G=(0,$.jsx)(Se,{className:`bar-item-icon`}),K=U(w(`terminal`)),xe=r===`terminal`,J=!0,Te=()=>a?.(`terminal`);break;case`host:worktrees`:{let e=n.state?.worktree;if(!e)return null;let t=new Set(e.linkedWorktrees.map(e=>e.path));e.isLinkedWorktree&&t.add(e.currentPath),G=(0,$.jsx)(Xn,{className:`bar-item-icon`}),K=U(w(`worktreeViewTitle`)),Ce=`chip worktree-entry`,xe=r===`worktrees`,J=!0,we=w(`worktreeEntryTip`,{count:t.size}),be=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`worktree-count bar-item-badge`,children:t.size}),e.linkedWorktrees.some(e=>e.isDirty)&&(0,$.jsx)(`span`,{className:`worktree-dirty-dot`,"aria-label":w(`worktreeHasChanges`)})]}),Te=()=>a?.(r===`worktrees`?`chat`:`worktrees`);break}case`host:git`:G=(0,$.jsx)(q,{className:`bar-item-icon`}),K=U(w(`scmTab`)),xe=r===`git`,J=!0,Te=()=>a?.(`git`);break;case`host:canvas`:G=(0,$.jsx)(Jn,{className:`bar-item-icon`}),K=U(w(`canvasTab`)),xe=r===`canvas`,J=!0,Te=()=>a?.(`canvas`);break;case`host:new-chat`:G=(0,$.jsx)(te,{className:`bar-item-icon`}),K=U(w(`newChat`)),Ce=`chip newchat`,Te=()=>{a?.(`chat`),X({type:`new_chat`}),cn()};break;case`host:new-ephemeral-chat`:if(j)return null;G=(0,$.jsx)(Yn,{className:`bar-item-icon`}),K=U(w(`newChatEphemeral`)),Ce=`chip newchat ephemeral-chat-btn`,Te=()=>{a?.(`chat`),X({type:`new_chat`,ephemeral:!0}),cn()};break;case`host:new-sandbox`:G=(0,$.jsx)(Zn,{className:`bar-item-icon`}),K=U(w(`newSandbox`)),Ce=`chip newchat sandbox-chip`,Te=()=>S?.();break;case`host:history`:if(r&&r!==`chat`)return null;G=(0,$.jsx)(h,{className:`bar-item-icon`}),K=U(w(`openHistory`)),Ce=`panel-toggle`,Te=()=>o?.(`left`);break;case`host:files`:if(r&&r!==`chat`)return null;G=(0,$.jsx)(Je,{className:`bar-item-icon`}),K=U(w(`openFiles`)),Ce=`panel-toggle has-label`,Te=()=>o?.(`right`);break;case`host:open-project`:G=(0,$.jsx)(nt,{className:`bar-item-icon`}),K=U(w(`openProject`)),Ce=`chip open-project`,xe=!!g,Te=()=>d?.();break;case`host:search`:G=(0,$.jsx)(ae,{className:`bar-item-icon`}),K=U(w(`searchGlobal`)),Ce=`chip`,Te=()=>l?.();break;case`host:tasks`:G=(0,$.jsx)(ct,{className:`bar-item-icon`}),K=U(w(`bgTasks`)),Ce=`chip bg-task-chip`,n.bgServers.length>0&&(be=(0,$.jsx)(`span`,{className:`bg-task-badge bar-item-badge`,children:n.bgServers.length})),Te=()=>u?.();break;case`host:zen-mode`:G=(0,$.jsx)(Ke,{className:`bar-item-icon`}),K=U(w(`zenMode`)),Ce=`chip chip-zen`,xe=!!b,we=w(`zenModeTip`),Te=()=>x?.();break;case`host:device-center`:G=(0,$.jsx)(ot,{className:`bar-item-icon`}),K=U(w(`deviceCenter`)),Ce=`chip`,we=w(`deviceCenterTip`),J=!0,xe=r===`devices`,Te=()=>a?.(`devices`);break;case`host:settings`:G=(0,$.jsx)(E,{className:`bar-item-icon`}),K=U(w(`settings`)),Ce=`chip`,Te=()=>s?.();break;case`host:plugins`:G=(0,$.jsx)(M,{className:`bar-item-icon`}),K=U(w(`pluginMenuTitle`)),Ce=`chip`,Te=e=>{p?p(e.currentTarget):s?.(`plugins`)};break;case`host:github`:G=(0,$.jsx)(Be,{className:`bar-item-icon`}),K=U(`GitHub`),Ce=`chip github`,Te=()=>window.open(`https://github.com/xing-shuyin/pi-web-ui`,`_blank`,`noreferrer,noopener`);break;case`host:cwd`:G=(0,$.jsx)(Je,{className:`bar-item-icon`}),K=_e(re?.cwd?re.cwd.split(/[/\\]/).pop()||re.cwd:w(`openProject`)),Ce=`status-item status-cwd`,xe=!!g,Te=()=>{pe.current!==null&&(window.clearTimeout(pe.current),pe.current=null),pe.current=window.setTimeout(()=>{d?.(),pe.current=null},220)},Ee=e=>{e.preventDefault(),e.stopPropagation(),pe.current!==null&&(window.clearTimeout(pe.current),pe.current=null),X({type:`new_chat`}),cn()};break;case`host:plugin-status`:if(n.statuses.length===0)return null;G=(0,$.jsx)(ye,{className:`bar-item-icon`}),K=_e(n.statuses.map(e=>e.text).join(` · `)),Ce=`status-item ext-status`;break;default:if(e.kind===`view`){let t=e.view??``;xe=r===t,J=!0;let o=(i??n.plugins??[]).find(t=>`plugin:${t.id}`===e.source);Ce=`plugin-tab${o?.error?` broken`:``}`,o?.error&&(we=`${e.label}: ${o.error}`);let s=e.iconSvg||o?.iconSvg,c=e.icon||o?.icon;G=s?(0,$.jsx)(ii,{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,Te=()=>a?.(t)}else{let n=e.iconSvg,r=e.icon;Ce=t===`bottom`?`status-item status-action chip`:`chip`,G=n?(0,$.jsx)(ii,{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&&(be=(0,$.jsx)(`span`,{className:`bar-item-badge`,children:e.badge})),Te=()=>_?.(e)}}let De=we??e.hint??K,Oe=[`bar-item`,J?`tb-tab${xe?` active`:``}`:``,Ce,xe&&!J?`active`:``].filter(Boolean).join(` `);return(0,$.jsxs)(`button`,{type:`button`,role:J?`tab`:void 0,"aria-selected":J?xe:void 0,"aria-haspopup":H===`host:plugins`?`menu`:void 0,"aria-expanded":H===`host:plugins`?!!m:void 0,className:Oe,title:De,"data-tip":De,"aria-label":K,onClick:Te,onDoubleClick:Ee,onContextMenu:me,"data-bar-item":H,children:[G,!(H===`host:worktrees`&&t===`top`&&!e.labelExplicit)&&(0,$.jsx)(`span`,{className:`bar-item-text`,children:K}),be]})}function mo(){let{locale:e}=st(),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(()=>typeof window<`u`);if((0,Q.useEffect)(()=>{i(!0);let e=Nt();if(!e)return;e.isMaximized().then(n);let t=e.onMaximizedChange(e=>{n(e)});return()=>t()},[]),!r||!Pt()||Ft()===`darwin`)return null;let a=Nt();if(!a)return null;let o=c(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 ho={name:`@earendil-works/pi-coding-agent`,kind:`pi-core`,current:``,latest:null,upToDate:!1};function go({anchorRef:e,open:t,onClose:n,children:r}){let{panelRef:i,style:a,measure:o}=Rn({open:t,anchor:e,onClose:n});return(0,Q.useLayoutEffect)(()=>{t&&o()},[t,r,o]),t?(0,Fn.createPortal)((0,$.jsx)(`div`,{ref:i,className:`plugin-topbar-menu portal`,role:`menu`,style:a,children:r}),document.body):null}function _o(){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 vo({chat:e,terminal:t,view:n,plugins:r,uiPrimary:i,uiOverflow:a,uiContextTopbar:o,onUiAction:s,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onManagePlugins:p,onOpenBgTasks:m,onOpenGlobalSearch:g,themes:_,theme:v,onThemeChange:y,reloadThemes:b,onOpenIconEdit:x,zenMode:S,onToggleZenMode:C,onOpenSandboxModal:w}){let{locale:T,setLocale:D,t:O,packs:k}=st(),[A,j]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(null),[L,R]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(null),z=Me(`cwd`),B=Me(`workspaceRoots`),ie=G(),V=qe().ephemeralChat!==!1&&!ie,oe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{oe.current!==null&&window.clearTimeout(oe.current)},[]);let se=(0,Q.useRef)(null),ce=t=>!e.tabs||t===`chat`||e.tabs.includes(t),ue=[...a??[]].filter(e=>(e.source!==`host`||e.id!==`host:brand`)&&!Ti(e)),de=new Set([...i??[],...a??[]].filter(e=>Ti(e)&&!e.hidden).map(e=>e.source.slice(7))),pe=new Map((e.settings?.uiLayout?.order??[]).map((e,t)=>[e,t])),me=r.map((e,t)=>({id:e.id,index:t})).sort((e,t)=>(pe.get(`${e.id}:__view`)??1e6+e.index)-(pe.get(`${t.id}:__view`)??1e6+t.index)).map(e=>e.id),H=i===void 0?[`host:history`,`host:brand`,`host:worktrees`,`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})),ge=(ce(`plugins`)?r:[]).filter(e=>e.view!==!1&&e.error&&!H.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:[]})),U=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`),X({type:`new_chat`}),cn(),!0;case`host:new-ephemeral-chat`:return l(`chat`),X({type:`new_chat`,ephemeral:!0}),cn(),!0;case`host:new-sandbox`:return w?.(),!0;case`host:open-project`:return P(!0),!0;case`host:search`:return g(),!0;case`host:tasks`:return m(),!0;case`host:zen-mode`:return C?.(),!0;case`host:worktrees`:return l(`worktrees`),!0;case`host:device-center`:return l(`devices`),!0;case`host:settings`:return d(),!0;case`host:plugins`:return I(se.current?{rect:se.current.getBoundingClientRect(),el:se.current}:null),!0;default:return!1}},_e=(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`),X({type:`set_settings`,uiLayout:{...i,slots:t,...r[n]?{align:r}:{}}})},s=()=>{let e=new Set(i?.hidden??[]);e.add(n);let t=(i?.shown??[]).filter(e=>e!==n);X({type:`set_settings`,uiLayout:{...i,hidden:[...e],shown:t}})},c=()=>{X({type:`set_settings`,uiLayout:qi(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:[]}];Si.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:[]}),o&&o.length>0&&l.push(...o),na({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`?s():e.id===`host:restore-item`&&c()}})},{appVersion:W}=he(),ve=Re(),K=at(),[ye,be]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{ye&&e.status===`open`&&be(!1)},[ye,e.status]);let[xe,J]=(0,Q.useState)(!1),[Ce,we]=(0,Q.useState)(!1),[Te,Ee]=(0,Q.useState)(!1),Oe=Pt(),ke=$a(),[Ae,je]=(0,Q.useState)(!1),Y=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{if(Y.current.size===0)return;let t=!1;for(let n of Array.from(Y.current)){let r=e.terminals.find(e=>e.id===n);r&&!r.running&&(Y.current.delete(n),t=!0)}t&&e.ready&&(X({type:`check_update`}),X({type:`check_updates_all`,force:!0}))},[e.terminals,e.ready]);let Ne=()=>{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),a=i?i.id:Tt();i?(Y.current.add(i.id),t.restart(i.id),X({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:r,cols:80,rows:24})):(Y.current.add(a),t.create({id:a,conversationId:e.activeConversationId||e.state?.conversationId||``,title:n,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:r})),Ee(!1),t.select?.(a),l(`terminal`,{skipAutoCreate:!0})},Pe=(n,r)=>{if(!e.ready||n.length===0)return;let i={name:r,command:Qn(n),cwd:"${pwd}"},a=e.terminals.find(e=>e.title===r),o=a?a.id:Tt();a?(Y.current.add(a.id),t.restart(a.id),X({type:`run_command`,terminalId:a.id,conversationId:a.conversationId,command:i,cols:80,rows:24})):(Y.current.add(o),t.create({id:o,conversationId:e.activeConversationId||e.state?.conversationId||``,title:r,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:i})),Ee(!1),t.select?.(o),l(`terminal`,{skipAutoCreate:!0})},Fe=e.updatesAll??[],Ie=e.updatesSdk,Le=Ie&&Ie.newerInstalled?{running:Ie.running,installed:Ie.newerInstalled}:null,ze=Ie?.bundledInUse===!0,Ve=Fe.find(e=>e.kind===`pi-core`&&!e.error),He=ze&&(!Ve||!Ve.upToDate),Ue=He&&!Ve,We=Fe.filter(e=>!e.upToDate&&!e.error).length,Ge=Fe.filter(e=>!e.upToDate&&!e.error&&e.kind!==`webui`),Ye=e=>e.kind===`git-extension`&&e.source?e.source:e.name,Xe=e=>e.kind===`git-extension`&&e.source&&e.source!==e.name?`${e.source} (${e.name})`:e.name,Ze=e=>{let t=e.replace(/ \([0-9a-f]{7}\)$/,``);return/^[0-9a-f]{7}$/.test(t)?``:t},Qe=e=>(e.match(/\(([0-9a-f]{7})\)$/)??e.match(/^([0-9a-f]{7})$/))?.[1]??null,$e=(e,t)=>{if(!t)return Ze(e);let n=Ze(e),r=Ze(t);if(n!==r)return`${n} → ${r}`;let i=Qe(e),a=Qe(t);return i&&a&&i!==a?n?`${n} (${i} → ${a})`:`${i} → ${a}`:n},et=()=>(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`)}):Fe.length===0?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updatesAllUpToDate`)}):(0,$.jsx)(`ul`,{className:`dd-all-list`,children:Fe.map(e=>{let t=Le!=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:()=>Pe([e],O(`updatePkgTabTitle`,{name:e.name})),children:O(`updateBtn`)}),(0,$.jsx)(`span`,{className:`dd-all-name`,title:Xe(e),children:Ye(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?Ze(e.current):$e(e.current,e.latest):e.kind===`plugin`?e.upToDate?e.current.startsWith(`v`)?e.current:Ze(e.current):$e(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:Le.running})})]})]},`${e.kind}:${e.name}`)})}),Le&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`piSdkSplitNote`,{running:Le.running,installed:Le.installed})}),He&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`piSdkBundledNote`,{running:Ie.running})}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[Ue&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Pe([ho],O(`installGlobalEngineTabTitle`)),children:O(`installGlobalEngineBtn`)}),Ge.length>0&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Pe(Ge,O(`updateAllTabTitle`)),children:O(`updateAllBtn`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,style:Ge.length>0?{flex:1}:void 0,onClick:()=>X({type:`check_updates_all`,force:!0}),children:O(`updatesAllRefresh`)})]})]}),tt=()=>{let t=Qa(e.update?.latest??ke.version),n=(0,$.jsx)(`a`,{className:`dd-refresh dd-more-link`,href:t,target:`_blank`,rel:`noreferrer noopener`,children:O(`updateDesktopManual`)});if(!ke.bridge)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopNoBridge`)}),n]});switch(ke.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:ke.version??e.update?.latest??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>ke.download(),children:O(`updateDesktopDownload`)}),n]});case`downloading`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopDownloading`,{n:ke.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:()=>ke.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:ke.message??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>ke.check(),children:O(`updateDesktopCheck`)}),n]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>ke.check(),children:O(`updateDesktopCheck`)}),n]})}},rt=()=>(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&&!Oe&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateTerminalHint`)}),e.update&&!e.update.upToDate&&e.update.latest&&Oe&&(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:()=>X({type:`check_update`}),children:e.update===null?O(`checkingUpdate`):O(`checkUpdate`)}),e.update&&!e.update.upToDate&&e.update.latest&&!Oe&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:Ne,children:O(`updateNow`)}),e.update&&!e.update.upToDate&&e.update.latest&&Oe&&tt(),K&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,disabled:ye,title:O(`restartServiceTip`,{name:K.name}),onClick:()=>{ye||(be(!0),X({type:`restart_service`}))},children:O(ye?`restartingService`:`restartService`)})]})]}),it=_o(),Z={"host:brand":(0,$.jsx)(Kn,{}),"host:worktrees":e.state?.worktree?(0,$.jsxs)(`button`,{type:`button`,className:`tb-tab${n===`worktrees`?` active`:``}`,title:O(`worktreeViewTitle`),onClick:()=>l(`worktrees`),children:[(0,$.jsx)(Xn,{}),(0,$.jsx)(`span`,{children:O(`worktreeViewTitle`)})]}):null,"host:open-project":(0,$.jsxs)(`button`,{type:`button`,className:`chip open-project`,"data-tip":O(`openProject`),onClick:()=>P(!0),children:[(0,$.jsx)(nt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`openProject`)})]}),"host:history":n===`chat`&&ce(`history`)?(0,$.jsx)(`button`,{type:`button`,className:`panel-toggle`,"data-tip":O(`openHistory`),"aria-label":O(`openHistory`),onClick:()=>u(`left`),children:(0,$.jsx)(h,{})}):null,"host:files":n===`chat`&&ce(`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)(Je,{}),(0,$.jsx)(`span`,{children:O(`openFiles`)})]}):null,"host:new-chat":ce(`new-chat`)?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat`,"data-tip":O(`newChatTip`),onClick:()=>{l(`chat`),X({type:`new_chat`}),cn()},children:[(0,$.jsx)(te,{}),(0,$.jsx)(`span`,{children:O(`newChat`)})]}):null,"host:new-ephemeral-chat":V?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat ephemeral-chat-btn`,"data-tip":O(`newChatEphemeralTip`),onClick:()=>{l(`chat`),X({type:`new_chat`,ephemeral:!0}),cn()},children:[(0,$.jsx)(Yn,{}),(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)(Zn,{}),(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)(f,{}),(0,$.jsx)(`span`,{children:O(`chat`)})]}),"host:terminal":ce(`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)(Se,{}),(0,$.jsx)(`span`,{children:O(`terminal`)})]}):null,"host:git":ce(`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)(q,{}),(0,$.jsx)(`span`,{children:O(`scmTab`)})]}):null,"host:canvas":ce(`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)(Jn,{}),(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;I(e=>e?.el===t?null:{rect:t.getBoundingClientRect(),el:t})},children:[(0,$.jsx)(M,{"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:g,children:[(0,$.jsx)(ae,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`searchGlobal`)})]}),"host:browser":e.settings?.disabledAgentTools?.includes(`browser_page`)??!1?null:(0,$.jsx)(ur,{}),"host:tasks":(0,$.jsxs)(`button`,{type:`button`,className:`chip bg-task-chip`,"data-tip":O(`bgTasksTip`),onClick:m,children:[(0,$.jsx)(ct,{}),(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${S?` active`:``}`,"data-tip":O(`zenModeTip`),onClick:C,"aria-label":O(`zenMode`),"aria-pressed":S,children:[(0,$.jsx)(Ke,{}),(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)(ot,{}),(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)(E,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`settings`)})]}),"host:language":(0,$.jsxs)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ot,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:De(T)})]}),tip:O(`language`),open:xe,onOpenChange:J,caret:!1,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`language`)}),k.map(e=>(0,$.jsx)(Et,{active:T===e.code,onClick:()=>{D(e.code),J(!1)},children:e.nativeName},e.code)),(0,$.jsxs)(Et,{onClick:()=>{J(!1),je(!0)},children:[(0,$.jsx)(le,{}),` `,O(`localeGetMore`)]})]}),"host:theme":(0,$.jsx)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ee,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`theme`)})]}),tip:O(`theme`),open:Ce,caret:!1,onOpenChange:e=>{we(e),e&&_.length===0&&b()},children:(()=>{let e=_.filter(e=>e.group===`classic`),t=_.filter(e=>e.group!==`classic`),n=e=>{let t=c(T)?e.name:e.nameEn??e.name,n=e.scheme===`light`?O(`themeLight`):e.scheme===`dark`?O(`themeDark`):``;return n?c(T)?`${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)(Et,{active:v===e.id,onClick:()=>{y(e.id),we(!1)},children:n(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:e.length>0?O(`themeGroupBuiltin`):O(`theme`)}),(0,$.jsx)(Et,{active:v===null,onClick:()=>{y(null),we(!1)},children:O(`themeDefault`)}),t.map(e=>(0,$.jsx)(Et,{active:v===e.id,onClick:()=>{y(e.id),we(!1)},children:n(e)},e.id))]})})()}),"host:update":ve?(0,$.jsxs)(`span`,{className:`chip`,"data-tip":O(`updatesManaged`),children:[(0,$.jsx)(le,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,W??e.update?.current??`…`]})]}):(0,$.jsxs)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(le,{}),(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??``})}),We>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:O(`updatesAllBadge`,{n:We})})]}),tip:O(`update`),open:Te,caret:!1,onOpenChange:e=>{Ee(e),e&&(X({type:`check_update`}),X({type:`check_updates_all`}))},fit:!0,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`update`)}),rt(),et()]}),"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)(Be,{})}),"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)(so,{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=on(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:()=>{oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null),oe.current=window.setTimeout(()=>{P(!0),oe.current=null},220)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null),X({type:`new_chat`}),cn()},children:[(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.state?.cwd?.split(/[/\\]/).pop()||e.state?.cwd})]})},lt=new Set([`host:search`,`host:tasks`,`host:settings`,`host:plugins`]),ut=new Set([`host:language`,`host:theme`,`host:update`,`host:browser`,`host:engine`]),dt=e=>lt.has(e)&&!ce(e.slice(5)),ft=e=>{if(e.kind===`view`){if(!ce(`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=>_e(t,e.id,e.label),children:[(0,$.jsx)(ii,{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=>s?.(e,t.target.value),onContextMenu:t=>_e(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:()=>s?.(e),onContextMenu:t=>_e(t,e.id,e.label),children:[(0,$.jsx)(ii,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)},pt=[];for(let t of H){if(t.entry?.hidden||dt(t.id)||t.id===`host:worktrees`&&!e.state?.worktree)continue;let i=null;t.entry?i=(0,$.jsx)(po,{entry:t.entry,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onOpenGlobalSearch:g,onOpenBgTasks:m,onOpenProjectPicker:()=>P(!0),isProjectPickerOpen:N,onOpenPluginMenu:e=>I(t=>t?.el===e?null:{rect:e.getBoundingClientRect(),el:e}),isPluginMenuOpen:F!==null,onUiAction:s,uiContextEntries:o,zenMode:S,onToggleZenMode:C,onOpenSandboxModal:w,dropdownProps:{theme:v,themes:_,onThemeChange:y,reloadThemes:b,onLocaleModalOpen:()=>je(!0),renderUpdateBody:rt,renderAllUpdatesBody:et,updatesCount:We,managed:ve,appVersion:W}},t.id):t.id.startsWith(`host:`)&&Z[t.id]&&(i=Z[t.id]),i&&pt.push({id:t.id,entry:t.entry,node:i})}for(let t of ge){let i=(0,$.jsx)(po,{entry:t,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onUiAction:s,uiContextEntries:o},t.id);i&&pt.push({id:t.id,entry:t,node:i})}let mt=e=>e.entry?.align??`start`,[ht,gt]=(0,Q.useState)(()=>new Set),_t=(0,Q.useRef)(null),vt=(0,Q.useRef)(new Map),yt=pt.filter(e=>!ht.has(e.id)),bt=it?yt.filter(e=>Xi.has(e.id)):[],xt=it?yt.filter(e=>!Xi.has(e.id)):yt,St=it?pt.filter(e=>!Xi.has(e.id)):pt,Ct=[...St.filter(e=>mt(e)===`start`),...St.filter(e=>mt(e)===`center`),...St.filter(e=>mt(e)===`end`)],wt=Ct.filter(e=>!ht.has(e.id)),Ot=(0,Q.useRef)(Ct),kt=(0,Q.useRef)(wt);(0,Q.useLayoutEffect)(()=>{Ot.current=Ct,kt.current=wt});let At=()=>{let e=_t.current;if(!e||typeof ResizeObserver>`u`)return;let t=Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`)),n=kt.current;t.length===n.length&&n.forEach((e,n)=>vt.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=Ot.current,a=Qi(i.map(e=>({id:e.id,width:e.entry?vt.current.get(e.id)??0:0})),e.clientWidth,r,0,new Set([...Si,`host:worktrees`]));gt(e=>e.size===a.size&&[...a].every(t=>e.has(t))?e:a)},jt=`${yt.map(e=>`${e.id}:${e.entry?.label??``}`).join(`|`)}|${n}|${(e.tabs??[]).join(`,`)}|${it?`m`:`d`}`;(0,Q.useLayoutEffect)(At,[jt]),(0,Q.useEffect)(()=>{let e=_t.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>At());return t.observe(e),()=>t.disconnect()},[jt]);let Mt=xt.filter(e=>mt(e)===`start`),Nt=xt.filter(e=>mt(e)===`center`),Ft=xt.filter(e=>mt(e)===`end`),It=pt.filter(e=>ht.has(e.id)&&e.entry).map(e=>e.entry),Lt=new Map;[...i??[],...a??[]].forEach((e,t)=>{Lt.has(e.id)||Lt.set(e.id,t)});let Rt=Zi([...ue,...It],e=>Lt.get(e)??999999),zt=e=>e.icon&&!/[a-z]/i.test(e.icon)?e.icon:null,Bt=e.settings?.uiLayout?.topbarText===!1;return(0,$.jsxs)(`header`,{className:`topbar${Bt?` no-labels`:``}`,"data-pi-anchor":`topbar`,children:[(0,$.jsxs)(`div`,{className:`topbar-flow`,ref:_t,role:`toolbar`,"aria-label":O(`viewSwitch`),children:[Mt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(Nt.length>0||Ft.length>0)&&(0,$.jsx)(`span`,{className:`tb-spacer${Nt.length===0&&Ft.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Nt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),Nt.length>0&&(0,$.jsx)(`span`,{className:`tb-spacer${Ft.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Ft.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id))]}),(Rt.length>0||pt.length>0)&&(0,$.jsxs)(`div`,{className:`plugin-topbar-more`,children:[(0,$.jsx)(`button`,{ref:se,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)(qn,{})}),(0,$.jsxs)(go,{anchorRef:se,open:A,onClose:()=>j(!1),children:[Rt.map(e=>{let t=e.source===`host`&&ut.has(e.id)?Z[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)(Be,{}),(0,$.jsx)(`span`,{children:`GitHub`})]},e.id);if(e.source===`host`){let t=Z[e.id];if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}else{let t=ft(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:[zt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:zt(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),U(e)||s?.(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),U(e)||s?.(e)},children:[zt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:zt(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),x()},children:[(0,$.jsx)(fe,{}),(0,$.jsx)(`span`,{className:`tb-row-text`,children:O(`uiIconEdit`)})]})]})]}),bt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(0,$.jsx)(mo,{}),Ae&&(0,$.jsx)(Ga,{onClose:()=>je(!1)}),F&&(0,$.jsx)(Oa,{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:de,orderedPluginIds:me,onTogglePin:(t,n)=>X({type:`set_settings`,uiLayout:Ei(e.settings?.uiLayout,t,n)}),onReorder:t=>X({type:`set_settings`,uiLayout:Di(e.settings?.uiLayout,t)}),onOpenView:e=>{I(null),l(`plugin:${e}`)},onOpenPluginSettings:e=>{re(e??null),R(!0)},onManagePlugins:p,onClose:()=>I(null)}),L&&(0,$.jsx)(Wa,{open:L,onClose:()=>{R(!1),re(null)},focusPluginId:ne,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),X({type:`set_settings`,disabledPlugins:[...n]})},onOpenView:e=>{R(!1),l(`plugin:${e}`)},onOpenMarketplace:()=>{R(!1),p()}}),N&&(0,$.jsx)(Ta,{open:!0,currentCwd:z,pathCompletions:e.pathCompletions??[],workspaceRoots:B,onClose:()=>P(!1),onSelectDirectory:e=>X({type:`set_cwd`,path:e}),onCreateProject:e=>X({type:`make_dir`,path:e,setAsCwd:!0})})]})}function yo(){let e=(0,Q.useSyncExternalStore)(Vn,Hn);return e?(0,$.jsx)(bo,{access:e},e.url):null}function bo({access:e}){let{zh:t}=e,[n,r]=(0,Q.useState)({x:24,y:64,width:Math.min(960,window.innerWidth-32),height:Math.min(640,window.innerHeight-88)}),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{let e=()=>r(e=>({...e,x:Math.max(0,Math.min(e.x,window.innerWidth-240)),y:Math.max(0,Math.min(e.y,window.innerHeight-40)),width:Math.min(e.width,window.innerWidth),height:Math.min(e.height,window.innerHeight)}));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);function f(e,t){if(o||e.button!==0||e.target.closest(`button`))return;e.preventDefault();let i=e.currentTarget;i.setPointerCapture(e.pointerId);let a={...n,px:e.clientX,py:e.clientY},s=e=>{let i=e.clientX-a.px,o=e.clientY-a.py;r(t?{...n,width:Math.max(Math.min(320,window.innerWidth),Math.min(window.innerWidth-n.x,a.width+i)),height:Math.max(Math.min(200,window.innerHeight),Math.min(window.innerHeight-n.y,a.height+o))}:{...n,x:Math.max(0,Math.min(window.innerWidth-Math.min(n.width,240),a.x+i)),y:Math.max(0,Math.min(window.innerHeight-40,a.y+o))})},c=()=>{i.removeEventListener(`pointermove`,s),i.removeEventListener(`lostpointercapture`,c)};i.addEventListener(`pointermove`,s),i.addEventListener(`lostpointercapture`,c)}async function p(){l(!0),d(``);try{await Wn(e.id,e.hubUrl,!0,t,!0),Un(e)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}}let m=t?`远程桌面`:`Remote desktop`,h=!!window.piDesktop?.openHub;return(0,Fn.createPortal)((0,$.jsxs)(`div`,{className:`remote-desktop-window${o?` is-fullscreen`:``}${i?` is-minimized`:``}`,role:`dialog`,"aria-label":m,style:o?void 0:{left:n.x,top:n.y,width:i?Math.min(420,n.width):n.width,height:i?`auto`:n.height},children:[(0,$.jsxs)(`div`,{className:`remote-desktop-titlebar`,onPointerDown:e=>f(e,!1),children:[(0,$.jsxs)(`strong`,{children:[m,` · `,e.id]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:c,onClick:()=>void p(),children:h?t?`独立窗口`:`Separate window`:t?`独立标签页`:`Separate tab`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":i?t?`还原`:`Restore`:t?`最小化`:`Minimize`,onClick:()=>{a(!i),s(!1)},children:i?`▢`:`−`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":o?t?`退出全屏`:`Exit fullscreen`:t?`全屏`:`Fullscreen`,onClick:()=>{s(!o),a(!1)},children:o?`⤡`:`⤢`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":t?`关闭`:`Close`,onClick:()=>Un(e),children:`×`})]}),u&&(0,$.jsx)(`div`,{role:`alert`,className:`remote-desktop-error`,children:u}),(0,$.jsx)(`iframe`,{title:m,src:e.url,sandbox:`allow-scripts allow-forms allow-pointer-lock`,allow:`fullscreen`,allowFullScreen:!0,hidden:i}),!o&&!i&&(0,$.jsx)(`div`,{className:`remote-desktop-resize`,onPointerDown:e=>f(e,!0),"aria-hidden":`true`})]}),document.body)}function xo(e,t,n,r){return e.flatMap(e=>[{providerId:`host:group-devices`,providerLabel:r?`新对话`:`New conversation`,title:e.name,hint:e.id,text:`@${e.name} · ${r?`新对话`:`New conversation`}`},...t.filter(t=>t.botId===e.id&&t.status!==`closed`&&!t.stale).map(t=>({providerId:`host:group-conversations`,providerLabel:r?`继续对话`:`Continue conversation`,title:`${e.name} · ${t.name||(r?`未命名对话`:`Untitled conversation`)}`,hint:t.id,text:`@${e.name} · ${r?`继续:`:`Continue: `}${t.name||(r?`未命名对话`:`Untitled conversation`)}`}))].filter(t=>`${t.title} ${t.providerLabel} ${e.id}`.toLocaleLowerCase().includes(n.toLocaleLowerCase())))}function So(e){return`@${e.name}(${e.id})`}function Co(e){return e.replace(/@([^\s()]+)\([a-f0-9-]{8,}\)/g,`@$1`)}function wo(e,t){let n=Co(e),r=n.match(/^@([^\s()]+)\s*(.*)$/);return r?{botPrefix:`@${r[1]}`,summary:r[2].trim()||n}:{botPrefix:t?`@${t}`:``,summary:n}}function To(e,t=!0){if(!e.includes(`Device task failed`))return Co(e);let n=e.match(/Device task failed\s*\[phase=([^;]+);\s*category=([^\]]+)\]\.\s*(.*)/s);if(!n)return Co(e);let[,r,i,a]=n,o=(t?{model:`模型推理阶段`,tool:`工具调用阶段`,approval:`权限审批阶段`,connection:`网络连接`,handshake:`设备握手`,init:`环境初始化`,switch_session:`会话切换`,new_chat:`新建会话`}:{model:`Model Execution`,tool:`Tool Execution`,approval:`Approval Phase`,connection:`Network Connection`,handshake:`Device Handshake`,init:`Initialization`,switch_session:`Session Switch`,new_chat:`New Chat`})[r]||r,s=a.trim();return t?[`> ⚠️ **任务执行中断 · ${o}**`,`>`,`> **执行阶段**:\`${r}\` · **错误类型**:\`${i}\``,`>`,`> ${s||`远端设备执行异常,现场任务会话已完整保留在目标设备上,可前往排查或重新提交。`}`].join(`
3
- `):[`> ⚠️ **Task Interrupted · ${o}**`,`>`,`> **Phase**: \`${r}\` · **Category**: \`${i}\``,`>`,`> ${s||`Remote agent execution failed; task session is safely retained on target device.`}`].join(`
4
- `)}function Eo(e,t){return[...new Set(t.filter(t=>e.includes(So(t))).map(e=>e.id))]}function Do(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 n=`group-message:${e.id}`,o=e.sender.type===`bot`,d=e.text,f=o?To(d,r):Co(d),p=e.replyToMessageId?t?.messages.find(t=>t.id===e.replyToMessageId):void 0;if(p){let e=Co(p.text).replace(/\s+/g,` `).slice(0,120);f=`> ↩ ${p.sender.name}: ${e}\n\n${f}`}if(a.push({id:n,role:o?`assistant`:`user`,timestamp:e.createdAt,content:[{type:`text`,text:f}]}),!o){let t=e.sender.type===`webhook`?` [Webhook]`:``;i.set(n,`${e.sender.name}${t}`);continue}let m=(e.taskIds??[]).map(e=>c.get(e)).filter(t=>!!t&&t.botId===e.sender.id);for(let e of m)e.report&&l.add(e.id);let h=[...new Set(m.map(e=>s[e.status]))].join(` · `),g=t?.room.primaryBotId&&e.sender.id===t.room.primaryBotId?` [${r?`群组主管`:`Coordinator`}]`:``,_=`${u(e.sender.id,e.sender.name,e.sender.sourceDeviceId)}${g}`;i.set(n,h?`${_} · ${h}`:_)}for(let e of t?.tasks??[]){if(l.has(e.id)||e.kind===`result`)continue;let t=`group-task:${e.id}`,n=o.get(e.botId),c=!!(e.parentTaskId||e.sourceBotId&&e.sourceBotId!==e.botId),d=r?`协同子代理`:`Worker Subagent`,f=u(e.botId,n?.name??e.botId,e.deviceId);i.set(t,c?`${f} [${d}] · ${s[e.status]}`:`${f} · ${s[e.status]}`);let p=e.report,m=Co(e.text),h;if(p){if(c){let t=r?`📋 展开查看工作内容与交付详情`:`📋 View Detailed Delivery & Evidence`;h=[`> 🤖 **${r?`协同子代理交付完成`:`Worker Subagent Completed`}** · \`@${n?.name??e.botId}\``,`>`,`> 🎯 **${r?`分配指令`:`Instruction`}**:${m}`,``,`<details>`,`<summary>${t}</summary>`,``,To(p,r),``,`</details>`].join(`
5
- `)}else h=To(p,r)}else if(e.status===`running`){let t=c?r?`协同子代理执行中`:`Worker Subagent Running`:r?`任务执行中`:`Task Running`,i=e.progress?.phase,a=e.progress?.toolName,o=e.progress?.text?.trim();h=[`> ⏳ **${t}**${c?` · \`@${n?.name??e.botId}\``:``}`,`>`,`> **${r?c?`分配指令`:`目标指令`:`Instruction`}**:${m}`,...i?[`> **${r?`执行阶段`:`Phase`}**:\`${i}\`${a?` · ${r?`工具`:`Tool`}: \`${a}\``:``}`]:[],...o?[`>`,`> ${o}`]:[]].join(`
6
- `)}else h=e.status===`queued`?[`> ⏱️ **${c?r?`协同子代理排队等待调度`:`Worker Subagent Queued`:r?`任务排队等待调度`:`Task Queued`}**${c?` · \`@${n?.name??e.botId}\``:``}`,`>`,`> **${r?c?`分配指令`:`目标指令`:`Instruction`}**:${m}`].join(`
7
- `):e.status===`failed`&&c?[`> ❌ **${r?`协同子代理执行失败`:`Worker Subagent Failed`}** · \`@${n?.name??e.botId}\``,`>`,`> 🎯 **${r?`分配指令`:`Instruction`}**:${m}`,...p?[``,To(p,r)]:[]].join(`
8
- `):`${s[e.status]}\n\n${m}`;a.push({id:t,role:`assistant`,timestamp:e.createdAt,content:[{type:`text`,text:h}]})}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 Oo(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 ko(e){let t=e.filter(e=>e.conversationId);if(!t.length)return;let n=t[0].conversationId;if(e.some(e=>e.conversationId!==n))throw Error(`同一条消息只能继续一个对话,请移除其他 @ 目标。 / Continue one conversation per message. Remove other @ targets.`);return n}function Ao(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 jo(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 Mo(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 No=new Map,Po=new Map;function Fo(e,t){let n=Po.get(e);if(n)n(t);else{let n=No.get(e)??[];n.some(e=>e.id===t.id)||n.push(t),No.set(e,n)}window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{roomId:e}}))}function Io(e,t){Po.set(e,t);let n=No.get(e)??[];No.delete(e);for(let e of n)t(e);return()=>{Po.get(e)===t&&Po.delete(e)}}function Lo(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 Ro({botIds:e,roomId:n}){let{locale:r}=st(),i=c(r),[a,o]=(0,Q.useState)(null),[s,l]=(0,Q.useState)(``),[u,f]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=async e=>{let n=await fetch(z(d(`/api/device-center/${e}`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)throw Error(i?`无法加载群成员,请重试。`:`Could not load members. Try again.`);return n.json()},[r,a]=await Promise.all([n(`chat-status`),n(`bots`)]);if(!r.hubUrl||!Array.isArray(a.bots))throw Error(i?`设备绑定无效。`:`Invalid device binding.`);e||(o({hubUrl:r.hubUrl,deviceId:r.deviceId,bots:a.bots}),l(``))}catch(t){e||l(t instanceof Error?t.message:String(t))}finally{t.abort(),e||(n=setTimeout(r,15e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[i]);async function p(e,t){if(a&&!u){f(!0);try{await Wn(e.deviceId,a.hubUrl,t,i),l(``)}catch(e){l(e instanceof Error?e.message:String(e))}finally{f(!1)}}}return(0,$.jsxs)(`div`,{className:`dg-side-members`,children:[s&&(0,$.jsx)(`div`,{className:`dg-side-error`,role:`alert`,children:s}),!a&&!s&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:i?`加载中…`:`Loading…`}),e.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:i?`暂无成员`:`No members`}),a&&e.map(e=>{let r=a.bots.find(t=>t.id===e);return(0,$.jsx)(`div`,{className:`dg-side-member`,children:(0,$.jsxs)(`div`,{className:`dg-side-member-name`,title:r?.name||e,children:[(0,$.jsx)(`span`,{children:r?.name||e}),(0,$.jsx)(`small`,{children:r?.online?i?`在线`:`Online`:i?`离线`:`Offline`}),n&&r&&(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:i?`引用成员`:`Reference member`,"aria-label":`${i?`引用成员`:`Reference member`} · ${r.name}`,onClick:()=>Fo(n,r),children:(0,$.jsx)(lt,{"aria-hidden":!0})}),r?.deviceId&&a.deviceId&&r.deviceId!==a.deviceId&&(0,$.jsxs)(`div`,{className:`dg-side-member-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:i?`远程桌面`:`Remote desktop`,"aria-label":i?`远程桌面`:`Remote desktop`,disabled:u||!r?.deviceId,onClick:()=>r&&void p(r,!0),children:(0,$.jsx)(k,{"aria-hidden":!0})}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:i?`访问设备`:`Open device`,"aria-label":i?`访问设备`:`Open device`,disabled:u||!r?.deviceId,onClick:()=>r&&void p(r,!1),children:(0,$.jsx)(t,{"aria-hidden":!0})})]})]})},e)})]})}function zo(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 Bo({cwd:e,onSelectCwd:t,onOpenProjectPicker:n,projects:r=[],workspaceRoots:i=[],pathCompletions:a=[],mode:o=`project`,baseCwd:s,onCreateProject:c,className:l=``,placeholder:u=`如 . 或 web 或绝对路径`,inputId:d,disabled:f=!1,commitOnBlur:p=!1,localOnly:m=!1,onPickerOpenChange:h}){let[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(e);(0,Q.useEffect)(()=>y(e),[e]);let[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(null),C=W();(0,Q.useEffect)(()=>{let e=e=>{S.current&&!S.current.contains(e.target)&&_(!1)};if(g)return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[g]);let w=[{label:`. (当前项目根目录)`,value:`.`},{label:`web (前端目录)`,value:`web`},{label:`server (后端服务)`,value:`server`},{label:`tests (测试套件)`,value:`tests`},{label:`src (源码目录)`,value:`src`},{label:`docs (文档目录)`,value:`docs`}],T=()=>{x(!1),h?.(!1)},E=()=>{f||(n?n():(_(!1),x(!0),h?.(!0)))},D=e&&e!==`.`?e:s||e||`.`;return(0,$.jsxs)(`div`,{className:`universal-path-picker-root ${l}`,ref:S,children:[(0,$.jsxs)(`div`,{className:`universal-path-input-group`,children:[(0,$.jsx)(Je,{className:`universal-path-icon`}),(0,$.jsx)(`input`,{type:`text`,className:`universal-path-input`,value:p?v:e,id:d,disabled:f,onChange:e=>p?y(e.target.value):t(e.target.value),onBlur:()=>{p&&v!==e&&t(v)},onKeyDown:n=>{p&&n.key===`Enter`&&(n.preventDefault(),v!==e&&t(v))},placeholder:u,title:`工作目录: ${e||`.`}`}),(0,$.jsx)(`button`,{type:`button`,className:`universal-path-dropdown-toggle`,disabled:f,onClick:()=>_(!g),title:`选择推荐子目录或最近项目`,children:(0,$.jsx)(A,{})})]}),(0,$.jsx)(dn,{className:`universal-path-browse-btn`,tip:C(`projectPickerTitle`),disabled:f,onClick:E,children:(0,$.jsx)(nt,{})}),g&&(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),_(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e})},e))]}),(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`推荐子目录`}),w.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.value),_(!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)(vt,{}),` 最近项目`]}),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),_(!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&&b&&(0,$.jsx)(Ta,{portalContainer:S.current?.closest(`dialog`)??void 0,localOnly:m,open:!0,currentCwd:D,pathCompletions:a,workspaceRoots:i,onClose:T,onSelectDirectory:e=>{t(e),T()},onCreateProject:c?e=>{c(e),T()}:void 0,mode:o})]})}var Vo=`pi-web-model-usage`;function Ho(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 Uo(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function Wo(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 Go(){try{let e=localStorage.getItem(Vo);return e?Ho(JSON.parse(e)):{}}catch{return{}}}function Ko(e){try{localStorage.setItem(Vo,JSON.stringify(e))}catch{}}function qo(e){let t=Uo(Go(),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 Yo({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=W(),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null),[w,T]=(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}T(Go()),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)),Wo(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]),F=(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(),X({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)(yt,{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)(E,{})})]})]}),(0,$.jsxs)(`div`,{className:`dd-search-row`,children:[(0,$.jsx)(ae,{}),(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})})]}),F.map(e=>{let t=e.model,n=r!==void 0&&r===t.id;return(0,$.jsxs)(Et,{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 Xo({title:e,entries:t,selected:n,onChange:r,disabled:i,pending:a}){let o=W(),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${n.includes(e.id)?` is-selected`:``}`,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}),e.warning===`high_privilege`&&(0,$.jsx)(`small`,{children:o(`localBotToolHighPrivilege`)}),e.warning===`unsupported_platform`&&(0,$.jsx)(`small`,{children:o(`localBotToolUnsupportedPlatform`)}),!u.has(e.id)&&(0,$.jsx)(`small`,{children:o(a?`localBotUnverified`:`localBotUnavailable`)}),e.description&&(0,$.jsx)(`small`,{className:`dc-bot-option-description`,title:e.description,children:e.description}),e.status===`not_loaded`&&(0,$.jsx)(`small`,{children:o(`localBotMcpNotLoaded`)}),e.status===`disabled`&&(0,$.jsx)(`small`,{children:o(`localBotMcpDisabled`)}),e.source&&e.source!==`builtin`&&(0,$.jsx)(`small`,{className:`dc-bot-option-source`,children:e.source}),e.path&&(0,$.jsx)(`small`,{className:`dc-bot-option-path`,title:e.path,children:e.path})]})]},e.id)),!m.length&&(0,$.jsx)(`p`,{children:o(a?`localBotOptionsLoading`:`localBotNoOptions`)})]})]})}var Zo=e=>e.id.startsWith(`${e.provider}/`)?e.id.slice(e.provider.length+1):e.id,Qo=()=>({name:``,description:``,systemPrompt:``,cwd:``,tools:[],skills:[],mcpServers:[],enabled:!0});async function $o(e,t,n){let r=await fetch(z(d(`/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 es({pathCompletions:e=[],createOnly:t=!1,onCreated:n,onCancel:r}){let i=W(),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(()=>t?Qo():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)(`tools`),[O,k]=(0,Q.useState)(`identity`),A=(0,Q.useRef)(null),j=(0,Q.useRef)(``),M=(0,Q.useRef)(null),N=s!==null,P=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{if(P.current=!1,!N)return;let e=M.current,t=document.activeElement,n=document.body.style.overflow;return document.body.style.overflow=`hidden`,k(`identity`),e?.showModal?.(),()=>{e?.close?.(),document.body.style.overflow=n,t?.focus()}},[N]),(0,Q.useEffect)(()=>{let e=new AbortController;return $o(`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(),A.current?.abort()}},[]);let F=s?.cwd;(0,Q.useEffect)(()=>{if(F===void 0)return;let e=new AbortController;return x(!0),y(``),_(null),$o(F?`local-bot-options?cwd=${encodeURIComponent(F)}`:`local-bot-options`,e.signal).then(t=>{if(e.signal.aborted)return;if(![t.models,t.tools,t.skills,t.mcpServers,t.projects].every(Array.isArray)||!t.defaultCwd||!t.cwd)throw Error(i(`localBotOptionsInvalid`));j.current=t.defaultCwd,_(t);let n=!P.current;P.current=!0,c(e=>e&&{...e,...e.cwd?{}:{cwd:t.cwd},...n&&!e.id?{tools:[...t.defaultTools??[]]}:{}})}).catch(t=>{e.signal.aborted||y(String(t))}).finally(()=>{e.signal.aborted||x(!1)}),()=>e.abort()},[F,S]),wt(()=>T(!1),w);async function I(e=!1){if(!s||u)return;let t=new AbortController;A.current=t,d(!0),p(``),h(``);try{let r=await $o(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 L=g?.models.find(e=>e.provider===s?.model?.provider&&Zo(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(Qo()),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:M,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(),I()},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":O===e,tabIndex:O===e?0:-1,onClick:()=>k(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(),k(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:O!==`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:O!==`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)(Bo,{inputId:`local-bot-cwd`,localOnly:!0,commitOnBlur:!0,pathCompletions:e,cwd:s.cwd,baseCwd:j.current||s.cwd,projects:g?.projects.map(e=>({...e,lastUsed:0}))??[],disabled:u,onSelectCwd:e=>c({...s,cwd:zo(e,j.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?L?.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&&!L&&(0,$.jsx)(`small`,{children:i(b?`localBotUnverified`:`localBotUnavailable`)})]})]})]}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`bot-panel-permissions`,"aria-labelledby":`bot-tab-permissions`,hidden:O!==`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-catalog-tabs`,role:`tablist`,"aria-label":i(`localBotPermissions`),children:[[`tools`,i(`localBotTools`)],[`skills`,i(`localBotSkills`)],[`mcpServers`,i(`localBotMcpServers`)]].map(([e,t])=>(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`bot-catalog-tab-${e}`,"aria-controls":`bot-catalog-${e}`,"aria-selected":E===e,onClick:()=>D(e),children:[t,(0,$.jsx)(`span`,{children:s[e].length})]},e))}),(0,$.jsx)(`div`,{className:`dc-bot-permissions`,children:[[`tools`,i(`localBotTools`)],[`skills`,i(`localBotSkills`)],[`mcpServers`,i(`localBotMcpServers`)]].map(([e,t])=>(0,$.jsx)(`div`,{role:`tabpanel`,id:`bot-catalog-${e}`,"aria-labelledby":`bot-catalog-tab-${e}`,hidden:E!==e,children:(0,$.jsx)(Xo,{title:t,entries:g?.[e]??[],selected:s[e],disabled:u,pending:b||!!v,onChange:t=>{e===`tools`&&(P.current=!0),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`))&&I(!0)},children:i(`localBotDelete`)})]})]})})]}),s&&w&&(0,Fn.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)(Yo,{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:Zo(e)}}),T(!1)},isRowActive:e=>e.provider===s.model?.provider&&Zo(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})]})}),M.current??document.body)]})}function ts({room:e,onClose:t}){let{locale:n}=st(),r=c(n),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(e.botIds),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!0),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(0),x=(0,Q.useRef)(null),S=()=>{!h&&!d&&t()};wt(S),(0,Q.useEffect)(()=>()=>x.current?.abort(),[]),(0,Q.useEffect)(()=>{let t=new AbortController;return m(!0),Promise.all([as(`bots`,t.signal),as(`rooms/${encodeURIComponent(e.id)}`,t.signal)]).then(([e,n])=>{t.signal.aborted||(a(e.bots),s(n.room.botIds))}).catch(e=>{t.signal.aborted||v(e instanceof Error?e.message:String(e))}).finally(()=>{t.signal.aborted||m(!1)}),()=>t.abort()},[e.id,y]);async function C(n){if(x.current)return;let r=new AbortController;x.current=r,g(!0),v(``);try{let i=`rooms/${encodeURIComponent(e.id)}`,a=await as(i,r.signal);if(r.signal.aborted||(await as(`${i}/members`,r.signal,{botIds:[...new Set([...a.room.botIds,...n])]}),r.signal.aborted))return;window.dispatchEvent(new CustomEvent(ns)),t()}catch(e){r.signal.aborted||v(e instanceof Error?e.message:String(e))}finally{x.current=null,r.signal.aborted||g(!1)}}return(0,Fn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:S,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:h||d,onClick:S,children:r?`关闭`:`Close`})]}),_&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:_}),(0,$.jsx)(`p`,{children:r?`选择已有 Bot 加入群组,或在本机新建 Bot。`:`Add existing Bots to this group or create a Bot on this computer.`}),p?(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:h||d,checked:l.includes(e.id),onChange:t=>u(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:h||d,onClick:()=>{f(!0),v(``)},children:r?`新建 Bot`:`Create Bot`}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:p||h||d||!l.length,onClick:()=>void C(l),children:h?r?`正在添加…`:`Adding…`:r?`添加到群组`:`Add to group`})]}),d&&(0,$.jsx)(es,{createOnly:!0,onCancel:()=>f(!1),onCreated:(e,t)=>{if(f(!1),b(e=>e+1),!t||!e.enabled){v(r?`Bot 已保存;请启用并同步到中心后,再添加到群组。`:`Bot saved. Enable and sync it to the hub before adding it to the group.`);return}C([e.id])}})]})}),document.body)}var ns=`pi-web-ui:device-groups-changed`,rs={zh:{groups:`群组`,create:`建群`,rename:`重命名`,members:`管理成员`,clear:`清空消息`,delete:`删除群组`,confirmClear:`确定清空群组“{name}”的全部消息和历史任务记录?此操作无法撤销,群组和成员将保留。`,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`,clear:`Clear messages`,delete:`Delete group`,confirmClear:`Clear all messages and task history in “{name}”? This cannot be undone. The group and members will be kept.`,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`}},is=class extends Error{status;code;constructor(e,t){super(`Device group request failed (${e})`),this.status=e,this.code=t}};async function as(e,t,n){let r=await fetch(z(d(`/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 is(r.status,typeof i?.code==`string`?i.code:``);return i}function os(e){return e instanceof is?[`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 ss(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 cs(e){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:e}))}function ls({active:e=!0,entry:t,selectedRoomId:n,flex:r,onCollapsedChange:i,hideHeader:a=!1,onRoomCountChange:o}){let{locale:s}=st(),l=rs[c(s)?`zh`:`en`],u=t?.labelExplicit?t.label:l.groups,[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>i?.(d),[d,i]);let[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(null),[x,C]=(0,Q.useState)(!0),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(``),[j,M]=(0,Q.useState)(!1),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),F=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(F.current=!0,()=>{F.current=!1,P.current?.abort()}),[]),(0,Q.useEffect)(()=>{if(!e)return;let t=!1,n=ss(async e=>{let n=await as(`chat-status`,e);if(t=!!(n.hubUrl&&n.deviceId),!t)return[];let r=await as(`rooms`,e);if(!Array.isArray(r.rooms))throw Error(`Invalid rooms response`);return r.rooms},e=>{b(t),v(e),o?.(e.length),T(null),C(!1)},e=>{T(os(e)),C(!1)});N.current=n;let r=()=>{document.hidden||n.refresh()},i=()=>{document.hidden?n.pause():r()};r();let a=window.setInterval(r,15e3);return window.addEventListener(ns,r),document.addEventListener(`visibilitychange`,i),()=>{n.stop(),N.current=null,window.clearInterval(a),window.removeEventListener(ns,r),document.removeEventListener(`visibilitychange`,i)}},[e]);let I=async(e,t)=>{if(P.current||t===`delete`&&!window.confirm(l.confirm.replace(`{name}`,e.name))||t===`clear`&&!window.confirm(l.confirmClear.replace(`{name}`,e.name)))return;let n=new AbortController;P.current=n,M(!0),T(null);try{if(await as(`rooms/${encodeURIComponent(e.id)}/${t}`,n.signal,t===`rename`?{name:O.trim()}:{}),!F.current||n.signal.aborted)return;D(null),window.dispatchEvent(new CustomEvent(ns))}catch(e){F.current&&!n.signal.aborted&&T(os(e))}finally{P.current=null,F.current&&M(!1)}},L=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=[`rename`,`members`,`clear`,`delete`].map((e,t)=>({id:`host:device-group-${e}`,slot:`contextmenu.project`,source:`host`,label:l[e],kind:`action`,action:e,order:t,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));na({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.id,kind:`device-group`,label:t.name},entries:n,onHostAction:e=>{P.current||(e.action===`rename`?(D(t.id),k(t.name)):e.action===`members`?cs({roomId:t.id,manage:!0}):(e.action===`clear`||e.action===`delete`)&&I(t,e.action))}})};if(y===!1||y===null&&x)return null;let ee=(0,$.jsxs)(`div`,{className:`lp-section-body dg-side-body`,children:[w&&(0,$.jsxs)(`div`,{className:`dg-side-error`,role:`status`,children:[l[w],w===`bind`?(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>cs({}),children:l.settings}):(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>N.current?.refresh(),children:l.retry})]}),!w&&_.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:x?l.loading:l.empty}),_.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":h.has(e.id),"aria-label":`${e.name} · ${c(s)?`成员`:`Members`}`,onClick:()=>g(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:h.has(e.id)?(0,$.jsx)(S,{}):(0,$.jsx)(A,{})}),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`dg-side-row${n===e.id?` is-selected`:``}`,"aria-current":n===e.id?`page`:void 0,title:e.name,onClick:()=>cs({roomId:e.id}),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),cs({roomId:e.id}))},onContextMenu:t=>L(t,e),children:[(0,$.jsx)(K,{}),(0,$.jsx)(`span`,{className:`dg-side-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-label":`${e.name} · ${c(s)?`添加 Bot`:`Add Bot`}`,title:c(s)?`添加或新建 Bot`:`Add or create Bot`,onClick:()=>m(e),children:(0,$.jsx)(te,{})})]}),h.has(e.id)&&(0,$.jsx)(Ro,{botIds:e.botIds,roomId:e.id}),E===e.id&&(0,$.jsxs)(`form`,{className:`dg-side-rename`,onSubmit:t=>{t.preventDefault(),O.trim()&&I(e,`rename`)},children:[(0,$.jsx)(`input`,{className:`dc-input`,"aria-label":l.name,value:O,maxLength:120,autoFocus:!0,disabled:j,onChange:e=>k(e.target.value),onKeyDown:e=>{e.key===`Escape`&&D(null)}}),(0,$.jsx)(`button`,{type:`submit`,className:`dc-button`,disabled:j||!O.trim(),children:l.save}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:j,onClick:()=>D(null),children:l.cancel})]})]},e.id))]});return a?(0,$.jsxs)(`section`,{className:`lp-section dg-side-section`,"aria-label":u,style:r===void 0?void 0:{flex:`${r} 1 0px`},children:[ee,p&&(0,$.jsx)(ts,{room:p,onClose:()=>m(null)})]}):(0,$.jsxs)(`section`,{className:`lp-section dg-side-section ${d?`collapsed`:``}`,"aria-label":u,style:!d&&r!==void 0?{flex:`${r} 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":!d,title:d?l.expand:l.collapse,onClick:()=>f(!d),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[t&&Ia(t),` `,u,` (`,_.length,`)`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:d?(0,$.jsx)(A,{}):(0,$.jsx)(S,{})})]}),(0,$.jsx)(`div`,{className:`lp-section-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action`,title:l.create,"aria-label":l.create,onClick:()=>cs({create:!0}),children:(0,$.jsx)(te,{})})})]}),!d&&ee,p&&(0,$.jsx)(ts,{room:p,onClose:()=>m(null)})]})}var us=`pi.unread_conversations`,ds=6048e5;function fs(){if(typeof window>`u`||!window.sessionStorage)return[];try{let e=window.sessionStorage.getItem(us);if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=Date.now();return t.filter(e=>e&&typeof e.id==`string`&&n-(e.finishedAt||0)<ds)}catch{return[]}}function ps(e){if(typeof window<`u`&&window.sessionStorage)try{let t=Array.from(e);t.length===0?window.sessionStorage.removeItem(us):window.sessionStorage.setItem(us,JSON.stringify(t))}catch{}}var ms=new class{entries=new Map;keyToPrimaryId=new Map;cachedKeySet=new Set;listeners=new Set;constructor(){let e=fs();if(e.length>0){for(let t of e)this.addEntryInternal(t);this.updateCachedKeySet()}}normalizeKey(e){if(!e)return null;let t=e.trim();return t?t.toLowerCase():null}addEntryInternal(e){this.entries.set(e.id,e);let t=this.normalizeKey(e.id);t&&this.keyToPrimaryId.set(t,e.id);let n=this.normalizeKey(e.sessionId);n&&this.keyToPrimaryId.set(n,e.id);let r=this.normalizeKey(e.sessionFile);r&&this.keyToPrimaryId.set(r,e.id);let i=this.normalizeKey(e.path);i&&this.keyToPrimaryId.set(i,e.id)}updateCachedKeySet(){let e=new Set;for(let[t]of this.keyToPrimaryId.entries())e.add(t);for(let t of this.entries.values())t.id&&e.add(t.id),t.sessionId&&e.add(t.sessionId),t.sessionFile&&e.add(t.sessionFile),t.path&&e.add(t.path);this.cachedKeySet=e}notify(){this.updateCachedKeySet(),ps(this.entries.values());for(let e of this.listeners)try{e()}catch{}}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.cachedKeySet;markUnread(e){let t=!1,n=Date.now();for(let r of e){if(!r.id)continue;let e=this.entries.get(r.id),i={id:r.id,sessionId:r.sessionId||e?.sessionId,sessionFile:r.sessionFile||e?.sessionFile,path:r.path||e?.path,finishedAt:n};this.addEntryInternal(i),t=!0}t&&this.notify()}clearUnread(e){if(!e)return;let t=this.normalizeKey(e);if(!t)return;let n=this.keyToPrimaryId.get(t)??(this.entries.has(e)?e:null);if(!n){this.entries.delete(e)&&(this.rebuildKeyMap(),this.notify());return}let r=this.entries.get(n);if(this.entries.delete(n),r){let e=this.normalizeKey(r.id);e&&this.keyToPrimaryId.delete(e);let t=this.normalizeKey(r.sessionId);t&&this.keyToPrimaryId.delete(t);let n=this.normalizeKey(r.sessionFile);n&&this.keyToPrimaryId.delete(n);let i=this.normalizeKey(r.path);i&&this.keyToPrimaryId.delete(i)}this.keyToPrimaryId.delete(t),this.notify()}rebuildKeyMap(){this.keyToPrimaryId.clear();for(let e of this.entries.values())this.addEntryInternal(e)}clearAll(){(this.entries.size!==0||this.keyToPrimaryId.size!==0)&&(this.entries.clear(),this.keyToPrimaryId.clear(),this.notify())}isUnread(e){return!!(e.id&&(this.cachedKeySet.has(e.id)||this.cachedKeySet.has(e.id.trim().toLowerCase()))||e.sessionId&&(this.cachedKeySet.has(e.sessionId)||this.cachedKeySet.has(e.sessionId.trim().toLowerCase()))||e.sessionFile&&(this.cachedKeySet.has(e.sessionFile)||this.cachedKeySet.has(e.sessionFile.trim().toLowerCase()))||e.path&&(this.cachedKeySet.has(e.path)||this.cachedKeySet.has(e.path.trim().toLowerCase())))}};function hs(e){ms.markUnread(e)}function gs(e){ms.clearUnread(e)}function _s(){return(0,Q.useSyncExternalStore)(ms.subscribe,ms.getSnapshot,ms.getSnapshot)}function vs(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 ys(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 bs(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 xs({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 Ss(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 Cs(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 ws(e,t){let n=Cs(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 Es(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 Ds(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 ks=`pi:canvas-list-result`,As=new Set([`canvas`,`canvases`,`画布`,`工作流`,`workflow`,`workflows`]);function js(e,t,n,r=10){let i=t.toLowerCase();return e.filter(e=>!i||As.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 Ms(e,t=1800){return new Promise(n=>{let r=e=>{clearTimeout(a),window.removeEventListener(ks,i),n(e)},i=e=>{let t=e.detail;r(t.graphs)},a=setTimeout(()=>r([]),t);window.addEventListener(ks,i);try{e()||r([])}catch{r([])}})}function Ns(){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 Ps(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 Fs(e){return`<quoted-text>\n${JSON.stringify(e)}\n</quoted-text>`}function Is(e){let t=/^<quoted-text>\n([^\n]*)\n<\/quoted-text>$/.exec(e);if(!t)return null;try{return Ps(JSON.parse(t[1]))}catch{return null}}function Ls(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Rs(e,t=[],n=[],r=[]){let i=[],a=(e??``).trim();a&&i.push(a);for(let e of r)e&&i.push(`<attached-image name="${Ls(e)}" />`);for(let e of t){let t=(e??``).trim();t&&i.push(t)}for(let e of n)i.push(Fs(e));return i.join(`
9
-
10
- `)}function zs(e){let t=e,n=[];for(;;){let e=/(?:^|\n\n)(<quoted-text>\n[^\n]*\n<\/quoted-text>)$/.exec(t),r=e?Is(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(/&quot;/g,`"`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/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 Bs=[{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 Vs(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 Hs(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 Vs(n)}let n=[];for(let t of Bs){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 Vs(n)}function Us(e,t){let n=Hs(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 Ws({quote:e,onRemove:t,forceOpen:n=!1}){let r=W(),[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 Gs=function(){let e=this.data();(e.micromarkExtensions??=[]).push({flow:{92:Ks(!0)},text:{92:Ks(!1)}});let t={enter:{backslashMathInline:qs,backslashMathDisplay:qs,backslashMathBlock:qs},exit:{backslashMathInline:Js,backslashMathDisplay:Js,backslashMathBlock:Js}};(e.fromMarkdownExtensions??=[]).push(t)};function Ks(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 qs=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)},Js=function(e){this.exit(e)},Ys=`modulepreload`,Xs=function(e,t){return new URL(e,t).href},Zs={},Qs=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=Xs(t,n),t=s(t),t in Zs)return;Zs[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`:Ys,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)})},$s,ec,tc=new Set,nc={load:()=>Qs(()=>import(`./math-1uRJCsA9.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)};function rc(){return $s}function ic(e){return tc.add(e),()=>{tc.delete(e)}}function ac(){return $s?Promise.resolve():(ec||=nc.load().then(e=>{$s=e.default,ec=void 0;for(let e of tc)e()},()=>{ec=void 0}),ec)}var oc=[`ariaDescribedBy`,`ariaLabel`,`ariaLabelledBy`],sc={ancestors:{tbody:[`table`],td:[`table`],th:[`table`],thead:[`table`],tfoot:[`table`],tr:[`table`]},attributes:{a:[...oc,`dataFootnoteBackref`,`dataFootnoteRef`,[`className`,`data-footnote-backref`],`href`],blockquote:[`cite`],code:[[`className`,/^language-./]],del:[`cite`],div:[`itemScope`,`itemType`],dl:[...oc],h2:[[`className`,`sr-only`]],img:[...oc,`longDesc`,`src`],input:[[`disabled`,!0],[`type`,`checkbox`]],ins:[`cite`],li:[[`className`,`task-list-item`]],ol:[...oc,[`className`,`contains-task-list`]],q:[`cite`],section:[`dataFootnotes`,[`className`,`footnotes`]],source:[`srcSet`],summary:[...oc],table:[...oc],ul:[...oc,[`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(`.`)},cc={}.hasOwnProperty;function lc(e,t){let n={type:`root`,children:[]},r=uc({schema:t?{...sc,...t}:sc,stack:[]},e);return r&&(Array.isArray(r)?r.length===1?n=r[0]:n.children=r:n=r),n}function uc(e,t){if(t&&typeof t==`object`){let n=t;switch(typeof n.type==`string`?n.type:``){case`comment`:return dc(e,n);case`doctype`:return fc(e,n);case`element`:return pc(e,n);case`root`:return mc(e,n);case`text`:return hc(e,n)}}}function dc(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 Sc(r,t),r}}function fc(e,t){if(e.schema.allowDoctypes){let e={type:`doctype`};return Sc(e,t),e}}function pc(e,t){let n=typeof t.tagName==`string`?t.tagName:``;e.stack.push(n);let r=gc(e,t.children),i=_c(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&&cc.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 Sc(o,t),o}function mc(e,t){let n={type:`root`,children:gc(e,t.children)};return Sc(n,t),n}function hc(e,t){let n={type:`text`,value:typeof t.value==`string`?t.value:``};return Sc(n,t),n}function gc(e,t){let n=[];if(Array.isArray(t)){let r=t,i=-1;for(;++i<r.length;){let t=uc(e,r[i]);t&&(Array.isArray(t)?n.push(...t):n.push(t))}}return n}function _c(e,t){let n=e.stack[e.stack.length-1],r=e.schema.attributes,i=e.schema.required,a=r&&cc.call(r,n)?r[n]:void 0,o=r&&cc.call(r,`*`)?r[`*`]:void 0,s=t&&typeof t==`object`?t:{},c={},l;for(l in s)if(cc.call(s,l)){let t=s[l],n=vc(e,Cc(a,l),l,t);n??=vc(e,Cc(o,l),l,t),n!=null&&(c[l]=n)}if(i&&cc.call(i,n)){let e=i[n];for(l in e)cc.call(e,l)&&!cc.call(c,l)&&(c[l]=e[l])}return c}function vc(e,t,n,r){return t?Array.isArray(r)?yc(e,t,n,r):bc(e,t,n,r):void 0}function yc(e,t,n,r){let i=-1,a=[];for(;++i<r.length;){let o=bc(e,t,n,r[i]);(typeof o==`number`||typeof o==`string`)&&a.push(o)}return a}function bc(e,t,n,r){if((typeof r==`boolean`||typeof r==`number`||typeof r==`string`)&&xc(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 xc(e,t,n){let r=e.schema.protocols&&cc.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 Sc(e,t){let n=En(t);t.data&&(e.data=On(t.data)),n&&(e.position=n)}function Cc(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 wc(e){return function(t){return lc(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 Ec(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 Dc(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 Ec(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=W(),{copied:n,copy:i}=Dc({duration:1200});return e?(0,$.jsx)(`button`,{type:`button`,className:`copy-btn`,title:t(`copy`),onClick:()=>void i(e),children:n?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}):null});function kc(e){let t=e.trim();return t?t.split(/\r?\n/).map(e=>e.replace(/^\s*[$%>]\s+/,``)).join(`
11
- `).trim():``}function Ac(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(t.length===0)return``;let n=t.find(e=>!e.startsWith(`#`)&&!e.startsWith(`//`))??t[0];return n.length>28?n.slice(0,25).trimEnd()+`…`:n}function jc(e,t){if(typeof window>`u`)return!1;let n=kc(e);if(!n)return!1;let r=t||Ac(n);return window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:r,command:n}})),!0}var Mc=(0,Q.memo)(function({code:e,title:t}){let n=W(),[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]);let s=(0,Q.useCallback)(()=>{jc(e,t)&&(a(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a(!1),o.current=null},1200))},[e,t]);return!e||!e.trim()?null:(0,$.jsx)(`button`,{type:`button`,className:`term-run-btn`,title:n(i?`executedInTerminal`:`runInTerminal`),"aria-label":n(`runInTerminal`),onClick:s,children:i?(0,$.jsx)(r,{}):(0,$.jsx)(Se,{})})});function Nc(e){let t=e=>{if(typeof e==`string`||typeof e==`number`){let t=String(e);return t===``?[[]]:t.split(`
12
- `).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 Pc(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(Pc).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return Pc(t?.children)}return``}function Fc(e){let t=Array.isArray(e)?e[0]:e;return!t||typeof t!=`object`||!(`props`in t)?null:t}function Ic(e){let t=Fc(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`,Rc=new Map,zc=new Map,Bc=new Set,Vc=-1,Hc=0,Uc=new Set;function Wc(){Hc++;for(let e of Uc)e()}function Gc(e){return Uc.add(e),()=>{Uc.delete(e)}}function Kc(){return Hc}var qc=null;function Jc(e){qc=e}function Yc(e,t){t!==Vc&&(Vc=t,zc.clear(),Bc.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!==Rc.size;if(!r){for(let[e,t]of n)if(Rc.get(e)!==t){r=!0;break}}if(r){for(let e of zc.keys())n.has(e)||zc.delete(e);for(let e of Bc)n.has(e)||Bc.delete(e);Rc=n,Wc()}}async function Xc(e,t){let n=Rc.get(e);if(!n)return null;let r=zc.get(e);if(!r&&!Bc.has(e))try{let t=(await Qs(()=>import(d(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${Vc}`)),[],import.meta.url)).default?.renderers?.[e];typeof t==`function`?(r={pluginId:n,renderer:t},zc.set(e,r)):(Bc.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(t){Bc.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,t)}if(!r)return null;let i={pluginId:r.pluginId,send:e=>{qc?.({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 Zc(e){return Rc.has(e)}var Qc=new Map,$c=new Map,el=new Set,tl=-1;function nl(e,t){t!==tl&&(tl=t,$c.clear(),el.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(Qc.keys()))n.has(e)||Qc.delete(e);for(let[e,t]of n)Qc.set(e,t);for(let e of $c.keys())n.has(e)||$c.delete(e);for(let e of el)n.has(e)||el.delete(e)}function rl(e){return Qc.has(e)}async function il(e){let t=Qc.get(e);if(!t)return null;let n=$c.get(e);if(!n&&!el.has(e))try{let r=(await Qs(()=>import(d(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${tl}`)),[],import.meta.url)).default?.messageWidgets?.[e];typeof r==`function`?(n={pluginId:t,renderer:r},$c.set(e,n)):(el.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(n){el.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,n)}return n?.renderer??null}function al({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(jt)),a.current.set(t,e))};return window.addEventListener(jt,e),()=>window.removeEventListener(jt,e)},[]),(0,Q.useEffect)(()=>{let n=!1,r=i.current;return s(null),Xc(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(jt)),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,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(Mc,{code:t}),(0,$.jsx)(Oc,{text:t})]}),(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:t})})]})}var ol=null,sl=new Set;function cl(){for(let e of sl)e()}function ll(e){ol=e,cl()}function ul(){ol!==null&&(ol=null,cl())}function dl(e,t){if(!ol||ol.isThinking||ol.toolCallId!==e)return;let n=!1,r=ol;for(let[e,i]of Object.entries(t))if(r[e]!==i){n=!0;break}n&&(ol={...ol,...t},cl())}function fl(){return ol}function pl(e){return sl.add(e),()=>{sl.delete(e)}}function ml(){return(0,Q.useSyncExternalStore)(pl,fl,fl)}function hl(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 gl=null,_l=null;function vl(e){gl=e?.open??null,_l=e?.isOpen??null}function yl(){return _l?_l():!1}function bl(e){return!gl||!e?.path?!1:(ul(),gl(e),!0)}function xl(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 Sl(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 Cl(e,t){return(t===`href`||t===`src`)&&/^(?:[a-z]:[\\/]|file:\/\/|pi-file:\/\/)/i.test(e)?e:Tn(e)}function wl(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 Tl(e){let t=e.split(`?`)[0]?.split(`#`)[0]?.toLowerCase()??``;return t.endsWith(`.html`)||t.endsWith(`.htm`)||t.endsWith(`.xhtml`)}function El(e,t){let n=wl(e,t),r=sg();if(Tl(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 z(d(`${i}?clientId=${encodeURIComponent(r)}&allowJs=1`))}let i=new URLSearchParams({clientId:r,path:n});return z(d(`/api/file?${i}`))}var Dl=[Dn,kn,Gs],Ol=[Dn],kl=[Dn,wn,kn,Gs],Al=[Dn,wn],jl=[[Cn,{detect:!1,ignoreMissing:!0}]];function Ml(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 Nl({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){let i=(0,Q.useSyncExternalStore)(ic,rc,rc),a=!r&&(t||/[$\\\\]|math/i.test(e));(0,Q.useEffect)(()=>{a&&!i&&ac()},[a,i]);let o=!r&&i?[[i,{strict:!1,throwOnError:!1}],...jl]:jl,s=t?[An,wc,...o]:o,c=(0,Q.useMemo)(()=>Ml(e),[e]);return(0,$.jsx)(jn,{remarkPlugins:r?n?Al:Ol:n?kl:Dl,rehypePlugins:s,urlTransform:Cl,components:{pre:Ll,a:Fl,img:Il},children:c})}var Pl=(0,Q.memo)(function({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){return(0,$.jsx)(`div`,{className:`md`,children:(0,$.jsx)(Nl,{text:e,rawHtml:t,hardBreaks:n,disableMath:r})})});function Fl({node:e,href:t,children:n,...r}){let i=String(t??``),a=c(gt()),o=Me(`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(),bl({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(!Sl(i)){let e=wl(i,o),t=e.split(`/`).pop()||e,s=El(i,o);return(0,$.jsx)(`a`,{...r,href:s,onClick:n=>{n.button===0&&!n.ctrlKey&&!n.metaKey&&!n.shiftKey&&!n.altKey&&bl({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 Il({node:e,src:t,alt:n,...r}){let i=String(t??``),a=Me(`cwd`),o=i;return i&&!Sl(i)&&!i.startsWith(`data:`)&&!i.startsWith(`blob:`)&&(o=El(i,a)),(0,$.jsx)(`img`,{...r,src:o,alt:n,loading:`lazy`})}function Ll({children:e,...t}){(0,Q.useSyncExternalStore)(Gc,Kc,Kc);let n=Ic(e);return n&&Zc(n)?(0,$.jsx)(al,{lang:n,code:Pc(e)}):(0,$.jsx)(Rl,{children:e,...t})}function Rl({children:e,...t}){let n=Nc(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,a=zl(e);return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(Mc,{code:a}),(0,$.jsx)(Oc,{text:a})]}),(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 zl(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(zl).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return zl(t?.children)}return``}function Bl({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),rl(e))return il(e).then(async r=>{if(!n&&r)try{let i=await r(t,{pluginId:Qc.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 Vl=/^\s{0,3}(`{3,}|~{3,})/,Hl=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Ul(e){return e.trim()===``}function Wl(e){let t=Vl.exec(e);return t?t[1]:null}function Gl(e){let t=e.split(`
13
- `),n=[],r=[],i=null;for(let e=0;e<t.length;e++){let a=t[e];if(i!==null){let e=Wl(a);e&&e[0]===i[0]&&e.length>=i.length&&(i=null),r.push(a);continue}let o=Wl(a);if(o&&!Ul(a)){i=o,r.push(a);continue}if(Ul(a)){let i=e;for(;i<t.length&&Ul(t[i]);)i++;if(!(i<t.length&&Hl.test(t[i]))&&r.length>0){n.push(r.join(`
14
- `)),r=[];continue}r.push(a);continue}r.push(a)}return{frozen:n,active:r.join(`
15
- `),inFence:i!==null}}function Kl(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 ql=22,Jl=14,Yl=()=>typeof document<`u`&&document.hidden;function Xl(e,t=!0,n=!1,r){let[i,a]=(0,Q.useState)(()=>!t||Yl()||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(Yl()){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?Jl:ql;if(f.current>0&&e-f.current<t){d.current=requestAnimationFrame(r);return}f.current=e;let n=o.current,i=Kl(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 Zl=600,Ql=32,$l=(0,Q.memo)(function({text:e,active:t,inFence:n}){let r=t&&!n&&e.length>=Zl,[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>=Ql){n();return}return s.current=setTimeout(n,Ql-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)(Nl,{text:r?i:e})}),eu=(0,Q.memo)(function({text:e,finishing:t=!1,onSettled:n}){let r=Xl(e,!0,t,n),{frozen:i,active:a,inFence:o}=(0,Q.useMemo)(()=>Gl(r),[r]);return(0,$.jsx)(`div`,{className:`md`,children:[...i,...a.length>0?[a]:[]].map((e,t)=>(0,$.jsx)($l,{text:e,active:t===i.length,inFence:t===i.length&&o},t))})});function tu({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)(A,{}):(0,$.jsx)(g,{})}):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 nu=300;function ru(e){let t=e.split(`
16
- `),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(`
17
- `)}function iu(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 au(e){let t=iu(e).replace(/\r\n/g,`
18
- `).replace(/[ \t]+\n/g,`
19
- `),n=ru(t).trim()||t.trim();return n?n.replace(/\n{3,}/g,`
20
-
21
- `):``}function ou(e){let t=iu(e),n=ru(t).trim()||t.trim();return n?n.split(/\n+/).map(e=>e.trim()).filter(Boolean).join(` `):``}function su(e,t){let n=ou(e);return n?t?n.slice(-300):n.slice(0,nu):``}function cu({thinking:e,streaming:t,wrap:n=!0,forceOpen:i=!1}){let a=W(),[o,s]=(0,Q.useState)(null),c=o??n,l=c||i,u=!!t,d=(0,Q.useRef)(u);d.current=u;let f=()=>typeof document<`u`&&document.hidden,[p,m]=(0,Q.useState)(()=>u&&!f());(0,Q.useEffect)(()=>{u&&!f()?m(!0):!u&&f()&&m(!1)},[u]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{d.current||m(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let h=(0,Q.useCallback)(()=>{d.current||m(!1)},[]),g=u||p,_=Xl(e,g,!u&&p,h),v=au(_),y=su(_,g),{copied:x,copy:S}=Dc({duration:1200}),C=()=>{S(e)},w=l?a(`collapseMsg`):y?`${a(`expandMsg`)} · ${y}`:a(`expandMsg`),E=(0,Q.useRef)(null),D=hl(E.current),O=()=>{ll({isThinking:!0,title:a(`toolInspectorThinkingTitle`),status:a(g?`thinkingNow`:`done`),statusClass:g?`run`:`ok`,output:v||e,thinking:e,streaming:g})};return D?(0,$.jsx)(`div`,{ref:E,className:`thinking ${g?`live run`:`ok`}`,"data-thinking":e,onClick:e=>{e.preventDefault(),e.stopPropagation(),O()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O())},role:`button`,tabIndex:0,title:a(`toolInspectorThinkingTitle`),children:(0,$.jsxs)(`div`,{className:`thinking-head chead`,children:[(0,$.jsx)(`span`,{className:`thinking-icon chead-icon`,children:(0,$.jsx)(T,{})}),(0,$.jsx)(`span`,{className:`thinking-name chead-title`,children:`think`}),(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:a(g?`thinkingNow`:`done`),"aria-label":a(g?`thinkingNow`:`done`),children:g?(0,$.jsx)(xs,{className:`spin`}):(0,$.jsx)(r,{})})]})}):(0,$.jsxs)(`div`,{ref:E,className:`thinking ${l?`open`:``} ${g?`live`:``} ${g?`run`:`ok`}`,"data-thinking":e,onClick:e=>{hl(E.current)&&(e.target?.closest(`.chead-copy, .toolcall-copy, .thinking-copy, a`)||(e.preventDefault(),e.stopPropagation(),O()))},children:[(0,$.jsxs)(tu,{open:!D&&l,headClassName:`thinking-head${g?` thinking-live`:``}`,toggleClassName:`thinking-toggle`,titleText:w,onToggle:()=>{if(hl(E.current)){O();return}s(!c)},icon:(0,$.jsx)(T,{}),iconClassName:`thinking-icon`,titleClassName:`thinking-label`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:a(g?`thinkingNow`:`done`),"aria-label":a(g?`thinkingNow`:`done`),children:g?(0,$.jsx)(xs,{className:`spin`}):(0,$.jsx)(r,{})}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy thinking-copy${x?` copied`:``}`,title:a(x?`copied`:`copyMessage`),"aria-label":a(`copyMessage`),onClick:e=>{e.stopPropagation(),C()},children:x?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{})})]}),children:[(0,$.jsx)(`span`,{className:`thinking-name`,children:`think`}),g&&l?(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[a(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):g?y?(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:[y,(0,$.jsx)(`span`,{className:`stream-cursor`})]})})]}):(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[a(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):y?(0,$.jsxs)(`span`,{className:`thinking-summary-text`,children:[` · `,y]}):null]}),!D&&l&&(0,$.jsxs)(`div`,{className:`thinking-body`,children:[v,g&&(0,$.jsx)(`span`,{className:`stream-cursor`})]})]})}function lu(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 uu=null,du=new Set;function fu(){for(let e of du)e()}function pu(e){let t=(e??``).trim();t&&(uu={name:t,status:`loading`},fu(),X({type:`get_tool_info`,name:t}))}function mu(){uu!==null&&(uu=null,fu())}function hu(e){uu!==null&&uu.name===e.name&&(uu=lu(e),fu())}function gu(e){return du.add(e),()=>{du.delete(e)}}function _u(){return uu}function vu(){return(0,Q.useSyncExternalStore)(gu,_u,_u)}var yu=262144,bu=300,xu=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,Su=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,Cu=/"(?:name|skill)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,wu=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,Tu=/"(query|q|search|pattern)"\s*:\s*"((?:[^"\\\n]|\\.){0,400})"/,Eu=1e9;function Du(e){let t=e.split(`
22
- `),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 Ou(e){let{name:t,argumentsText:n,isCollapsed:r=!1}=e,i=e.hints??ku(n);switch(t){case`bash`:{if(!r||!i.command)return null;let e=Du(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:Pu(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:Pu(i.path),title:i.path,className:`toolcall-path`}:i.query?{text:i.query,title:i.query,className:`toolcall-query`}:null}}function ku(e){if(!e)return{};let t=e.length>yu?e.slice(0,yu):e;return{path:Fu(t),timeout:Iu(t),command:Ru(e),agent:Au(t),skillName:ju(t),codeLines:Vu(e),query:Lu(t),questionTitle:Uu(t)}}function Au(e){let t=Su.exec(e);if(!t)return;let n=t[1].replace(/[\u0000-\u001f\u007f]/g,``).trim();if(n)return n.length>bu?`${n.slice(0,bu)}…`:n}function ju(e){let t=Cu.exec(e);if(!t)return;let n=zu(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>bu?`${n.slice(0,299)}…`:n}var Mu=[`task`,`expected_outcome`,`required_tools`,`must_do`,`must_not_do`,`context`];function Nu(e){if(!e||e.length>yu)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r={};for(let e of[...Mu,`agent`,`model`])typeof n[e]==`string`&&n[e].trim()&&(r[e]=n[e]);return r}catch{return{}}}function Pu(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 Fu(e){let t=xu.exec(e);if(!t)return;let n=zu(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>bu?`${n.slice(0,299)}…`:n}function Iu(e){let t=wu.exec(e);if(!t)return;let n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>Eu)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 Lu(e){let t=Tu.exec(e);if(!t)return;let n=zu(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>60?`${n.slice(0,57)}…`:n}function Ru(e){if(!(e.length>yu))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 zu(e){try{let t=JSON.parse(`"${e}"`);return typeof t==`string`?t:e}catch{return e}}function Bu(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=zu(e[1]))}else n&&(t=e);if(!t)return{};let r=t.indexOf(`
23
- `),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 Vu(e){let t=Bu(e);if(!t.code)return;let n=t.code.split(`
24
- `).length;return n>0?n:void 0}var Hu=/"(?:header|question)"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/;function Uu(e){let t=Hu.exec(e);if(!t)return;let n=zu(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>40?`${n.slice(0,38)}…`:n}function Wu(e){if(!e||e.length>yu)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 Gu=new Set([`image`,`video`,`audio`,`markdown`,`html`,`pdf`,`text`,`binary`,`dir`,`missing`]);function Ku(e){let t=String(e??``).trim().replace(/\\/g,`/`);return t.length>1?t.replace(/\/+$/,``):t}function qu(e){let t=Ku(e).split(`/`);return(t[t.length-1]??``)||String(e??``)}function Ju(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Yu(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function Xu(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=Ju(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=Ju(e),n=t?Yu(t.path):void 0;if(!n)continue;let r={path:n},a=Yu(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=Yu(n.title);o&&(a.title=o);let s=Yu(n.note);return s&&(a.note=s),a}function Zu(e,t){let n=Ju(t),r=Array.isArray(n?.items)?n.items.map(Ju):[],i=new Map;for(let e of r){if(!e)continue;let t=Ku(String(e.path??e.abs??``));t&&!i.has(t)&&i.set(t,e)}return e.items.map((e,t)=>{let n=i.get(Ku(e.path))??r[t]??null,a=Yu(n?.kind),o={path:e.path,target:Yu(n?.abs)??e.path,name:qu(Yu(n?.name)??e.path),kind:a&&Gu.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=Yu(n?.excerpt);return s&&(o.excerpt=s),n?.excerptTruncated===!0&&(o.excerptTruncated=!0),o})}function Qu(e,t){return Yu(Ju(t)?.title)??e.title}function $u(e,t){return Yu(Ju(t)?.note)??e.note}function ed(e){return e===`image`||e===`video`||e===`audio`?e:null}function td(e){return e!==`dir`&&e!==`missing`}function nd(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 rd(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 id(e){return e.find(e=>e.focus&&td(e.kind))}function ad(e){return id(e)??e.find(e=>td(e.kind))}function od(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 sd=209715200,cd=/windows/i.test(navigator.userAgent),ld=/[<>:"/\\|?*\u0000-\u001f]/g,ud=/[. ]+$/,dd=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function fd(e){let t=e.replace(ld,`_`).replace(ud,``);return t?dd.test(t)?`_${t}`:t:`_`}function pd(e,t=!0){let n=new URLSearchParams({clientId:sg(),path:e,...t?{download:`1`}:{}});return z(d(`/api/file?${n}`))}async function md(e,t){let n=cd?fd(t):t;try{let t=await fetch(pd(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`)>sd)return window.location.assign(pd(e)),{ok:!0};let r=await t.blob();return window.showSaveFilePicker&&window.isSecureContext?gd(r,n):_d(r,n)}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}async function hd(e,t){let n=cd?fd(t):t;return window.showSaveFilePicker&&window.isSecureContext?gd(e,n):_d(e,n)}async function gd(e,t){let n,r=window.showSaveFilePicker;if(!r)return _d(e,t);try{n=await r({suggestedName:t})}catch(n){return n instanceof DOMException&&n.name===`AbortError`?{ok:!1,cancelled:!0}:_d(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 _d(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 vd=`pi-web-ui:present-auto-open`,yd=3e4,bd=`pi-web-ui:present-auto-opened`;function xd(){try{return localStorage.getItem(vd)===`1`}catch{return!1}}function Sd(e){try{localStorage.setItem(vd,e?`1`:`0`)}catch{}Ed=e,wd()}var Cd=new Set;function wd(){for(let e of Cd)e()}function Td(e){return Cd.add(e),()=>{Cd.delete(e)}}var Ed=null;function Dd(){return Ed===null&&(Ed=xd()),Ed}function Od(){return(0,Q.useSyncExternalStore)(Td,Dd)}function kd(){try{let e=sessionStorage.getItem(bd);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function Ad(e){if(!e)return!1;let t=kd();if(t.includes(e))return!1;let n=[...t,e].slice(-200);try{sessionStorage.setItem(bd,JSON.stringify(n))}catch{}return!0}function jd(e,t,n=Date.now()){return od({enabled:xd(),seen:!1,timestamp:t,now:n,maxAgeMs:yd})?Ad(e):!1}var Md=(0,Q.memo)(function({args:e,details:t,toolCallId:n,resultTimestamp:r}){let i=W(),a=Od(),o=(0,Q.useMemo)(()=>Zu(e,t),[e,t]),s=Qu(e,t),c=$u(e,t),l=(0,Q.useMemo)(()=>id(o),[o]);return(0,Q.useEffect)(()=>{a&&l&&n&&(yl()||jd(n,r)&&bl({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)(Pl,{text:c,rawHtml:!0})}),(0,$.jsx)(`div`,{className:`present-items`,children:o.map(e=>(0,$.jsx)(Pd,{item:e},`${e.target}\u0000${e.path}`))})]})});function Nd(e){return typeof e.mtime==`number`?`${e.path}\n${new Date(e.mtime).toLocaleString()}`:e.path}function Pd({item:e}){let n=W(),{copied:r,copy:i}=Dc({duration:1200}),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=a?null:ed(e.kind),u=rd(e.size),d=e.kind===`missing`,f={path:e.target,name:e.name},p=!xl(),m=El(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:nd(e.kind)}),(0,$.jsx)(`span`,{className:`present-item-name`,title:Nd(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:[td(e.kind)&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:n(`previewFile`),"aria-label":n(`previewFile`),onClick:()=>bl(f),children:(0,$.jsx)(J,{})}),p?(0,$.jsxs)(`a`,{className:`present-btn labeled`,href:m,target:`_blank`,rel:`noreferrer noopener`,title:n(`openInNewTab`),children:[(0,$.jsx)(t,{}),(0,$.jsx)(`span`,{children:n(`openInNewTab`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`present-btn labeled`,title:n(`fileOpenDefault`),onClick:()=>X({type:`file_open_default`,path:e.target}),children:[(0,$.jsx)(t,{}),(0,$.jsx)(`span`,{children:n(`presentOpenLocal`)})]}),!p&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:n(`fileReveal`),"aria-label":n(`fileReveal`),onClick:()=>X({type:`file_reveal`,path:e.target}),children:(0,$.jsx)(Je,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:n(`downloadFile`),"aria-label":n(`downloadFile`),onClick:()=>{c(``),md(e.target,e.name).then(e=>{e.ok||e.cancelled||c(e.error===`FILE_NOT_FOUND`?n(`fileNotFoundShort`):e.error)})},children:(0,$.jsx)(le,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn${r?` on`:``}`,title:n(`copyPath`),"aria-label":n(`copyPath`),onClick:()=>{i(e.path)},children:(0,$.jsx)(b,{})})]})]}),d&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:n(`presentMissing`)}),s&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:n(`downloadFailed`,{error:s})}),l===`image`&&(0,$.jsx)(`button`,{type:`button`,className:`present-media`,title:n(`previewFile`),onClick:()=>bl(f),children:(0,$.jsx)(`img`,{src:pd(e.target,!1),alt:e.name,loading:`lazy`,onError:()=>o(!0)})}),l===`video`&&(0,$.jsx)(`video`,{className:`present-media-video`,src:pd(e.target,!1),controls:!0,preload:`metadata`,onError:()=>o(!0)}),l===`audio`&&(0,$.jsx)(`audio`,{className:`present-media-audio`,src:pd(e.target,!1),controls:!0,preload:`metadata`,onError:()=>o(!0)}),e.excerpt&&(0,$.jsxs)(`pre`,{className:`present-excerpt`,children:[e.excerpt,e.excerptTruncated?`…`:``]})]})}function Fd(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(`
25
- `).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 Id(e){if(!e)return;let t=/(?:User note \/ 附言|附言)[::]\s*([^\n\r]+)/.exec(e);return t?t[1].trim():void 0}var Ld=(0,Q.memo)(function({questions:e,details:t,output:n,isError:i=!1,waiting:a=!1}){let o=W(),s=(0,Q.useMemo)(()=>Fd(t,n),[t,n]),c=(0,Q.useMemo)(()=>i?Id(n):void 0,[i,n]);return(0,$.jsxs)(`div`,{className:`qcard-wrap`,children:[i&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-cancelled`,children:[(0,$.jsx)(`span`,{className:`qcard-status-icon`,children:(0,$.jsx)(Z,{})}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:o(`questionCardCancelled`)}),c&&(0,$.jsxs)(`div`,{className:`qcard-reject-reason`,children:[(0,$.jsx)(se,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{children:[(0,$.jsxs)(`strong`,{children:[o(`questionCardRejectReason`),`:`]}),` `,c]})]})]}),a&&!i&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:o(`questionCardWaiting`)})]}),(0,$.jsx)(`div`,{className:`qcard-items`,children:e.map((e,t)=>{let n=s.get(e.id)??s.get(e.header??``),i=new Set(n?.selected??[]),a=n!==void 0,c=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??`${o(`modelQuestion`)} ${t+1}`})]}),(0,$.jsx)(`div`,{className:`qcard-question`,children:(0,$.jsx)(Pl,{text:e.question,rawHtml:!0})}),e.detail&&(0,$.jsx)(`div`,{className:`qcard-detail`,children:(0,$.jsx)(Pl,{text:e.detail,rawHtml:!0})}),c.length>0&&(0,$.jsx)(`div`,{className:`qcard-options`,children:c.map((t,n)=>{let s=i.has(t.label),l=t.recommended??(n===0&&c.length>1);return(0,$.jsxs)(`div`,{className:`qcard-option${s?` selected`:``}${a&&!s?` dimmed`:``}`,children:[(0,$.jsx)(`span`,{className:`qcard-opt-mark`,children:e.multiSelect?s?(0,$.jsx)(r,{className:`qcard-check-icon`}):`☐`:s?`●`:`○`}),(0,$.jsxs)(`div`,{className:`qcard-opt-content`,children:[(0,$.jsxs)(`div`,{className:`qcard-opt-label`,children:[(0,$.jsx)(Pl,{text:t.label,rawHtml:!0}),l&&(0,$.jsx)(`span`,{className:`question-recommended-badge`,children:o(`recommended`)})]}),t.description&&(0,$.jsx)(`div`,{className:`qcard-opt-desc`,children:(0,$.jsx)(Pl,{text:t.description,rawHtml:!0})})]})]},t.label)})}),a&&i.size===0&&!n.custom&&(0,$.jsx)(`div`,{className:`qcard-empty-sel`,children:o(`questionCardNoSelection`)}),n?.custom&&(0,$.jsxs)(`div`,{className:`qcard-custom-note`,children:[(0,$.jsx)(f,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{className:`qcard-custom-label`,children:[o(`questionCardUserCustom`),`:`]}),(0,$.jsx)(`span`,{className:`qcard-custom-text`,children:n.custom})]})]},e.id)})})]})}),Rd={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 zd(e){if(!e)return`plaintext`;let t=e.split(`.`).pop()?.toLowerCase();return t&&Rd[t]||`plaintext`}var Bd=/\s+|[a-zA-Z0-9_$]+|[^\s\w]/g;function Vd(e){return e?e.replace(/\\([nrtbfv\\/"]|u[0-9a-fA-F]{4})/g,(e,t)=>{switch(t){case`n`:return`
26
- `;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(Bd)||[e],r=t.match(Bd)||[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 Ud=/^([+\- ])(\s*\d+)?\s(.*)$/;function Wd(e){let t=[],n=null,r=0,i=0,a=1,o=1,s=e.split(`
27
- `),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=Ud.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 Gd(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(`
28
- `):[],c=o?o.split(`
29
- `):[];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 Kd(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=zd(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=Vd(i)}else n=Vd(t)}let r=n?n.split(`
30
- `).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=Wd(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=Wd(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}=Gd(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 qd=(0,Q.memo)(function({toolName:e,argumentsText:n,details:a,output:o,isError:s,onOpenInspector:c}){let l=W(),[u,d]=(0,Q.useState)(`unified`),[f,p]=(0,Q.useState)(!1),{copied:m,copy:h}=Dc({duration:1200}),g=(0,Q.useMemo)(()=>Kd(e,n,a,o),[e,n,a,o]),_=(0,Q.useMemo)(()=>{if(!a||typeof a!=`object`)return``;try{return JSON.stringify(a,null,2)}catch{return``}},[a]);(0,Q.useEffect)(()=>{if(!f)return;let e=e=>{e.key===`Escape`&&(e.stopPropagation(),p(!1))};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},[f]);let v=e=>{e.stopPropagation(),g?.isWrite&&g.content?h(g.content):n&&h(n)},y=e=>{if(e.stopPropagation(),!g?.filePath)return;let t=g.filePath.split(`/`).pop()||g.filePath;bl({path:g.filePath,name:t})},x=e=>{e.stopPropagation(),p(e=>!e),c?.()};if(!g||u===`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:g?.filePath||e}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`unified`)},children:l(`diffViewUnified`)}),!g?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`split`)},children:l(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`raw`)},children:l(`diffViewRaw`)}),c&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:l(`diffFullscreen`),"aria-label":l(`diffFullscreen`),onClick:x,children:(0,$.jsx)(B,{})})]})]}),(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:[`⚡ `,l(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n||`(无入参参数 / No arguments)`})]}),_&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,l(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[Object.keys(a).length,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:_})]})]})]});let S=()=>g.isWrite?(0,$.jsx)(Jd,{content:g.content||``}):u===`split`?(0,$.jsx)(Zd,{hunks:g.hunks,isStreaming:g.isStreamingPartial,fallbackText:n}):(0,$.jsx)(Yd,{hunks:g.hunks,isStreaming:g.isStreamingPartial,fallbackText:n});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`file-diff-card${s?` is-err`:``}`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(U,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:g.filePath,children:g.filePath||e}),g.language&&g.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:g.language}),g.isStreamingPartial&&(0,$.jsx)(`span`,{className:`file-diff-streaming-badge`,children:l(`diffStreaming`)}),g.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:l(`diffNewFile`)}):(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)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`unified`)},children:l(`diffViewUnified`)}),!g.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`split`)},children:l(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`raw`)},children:l(`diffViewRaw`)})]}),g.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:l(`diffOpenFile`),"aria-label":l(`diffOpenFile`),onClick:y,children:(0,$.jsx)(t,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:l(`diffFullscreen`),"aria-label":l(`diffFullscreen`),onClick:x,children:(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${m?` copied`:``}`,title:g.isWrite?l(`diffCopyContent`):l(`diffCopyPatch`),"aria-label":g.isWrite?l(`diffCopyContent`):l(`diffCopyPatch`),onClick:v,children:m?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-body`,children:S()})]}),f&&(0,Fn.createPortal)((0,$.jsx)(`div`,{className:`file-diff-fullscreen-backdrop`,role:`dialog`,"aria-modal":`true`,onClick:e=>{e.target===e.currentTarget&&p(!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)(U,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:g.filePath,children:g.filePath||e}),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:l(`diffNewFile`)}):(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)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`unified`)},children:l(`diffViewUnified`)}),!g.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`split`)},children:l(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${u===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),d(`raw`)},children:l(`diffViewRaw`)})]}),g.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:l(`diffOpenFile`),"aria-label":l(`diffOpenFile`),onClick:y,children:(0,$.jsx)(t,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${m?` copied`:``}`,title:g.isWrite?l(`diffCopyContent`):l(`diffCopyPatch`),"aria-label":g.isWrite?l(`diffCopyContent`):l(`diffCopyPatch`),onClick:v,children:m?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${l(`diffRestoreScreen`)} (ESC)`,"aria-label":l(`diffRestoreScreen`),onClick:e=>{e.stopPropagation(),p(!1)},children:(0,$.jsx)(i,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${l(`close`)} (ESC)`,"aria-label":l(`close`),onClick:e=>{e.stopPropagation(),p(!1)},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-fullscreen-body`,children:S()})]})}),document.body)]})});function Jd({content:e,startLine:t=1}){let n=(0,Q.useMemo)(()=>e?e.split(`
31
- `):[],[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 Yd({hunks:e,isStreaming:t,fallbackText:n}){let r=W();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 Zd({hunks:e,isStreaming:t,fallbackText:n}){let r=W(),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 Qd={bash:(0,$.jsx)(Se,{}),delegate_task:(0,$.jsx)(ct,{}),conversation:(0,$.jsx)(K,{}),subagent:(0,$.jsx)(K,{}),read:(0,$.jsx)(U,{}),write:(0,$.jsx)(L,{}),edit:(0,$.jsx)(fe,{}),edit_soft:(0,$.jsx)(fe,{}),patch:(0,$.jsx)(Ne,{}),grep:(0,$.jsx)(ae,{}),find:(0,$.jsx)(V,{}),ls:(0,$.jsx)(Je,{}),codemode:(0,$.jsx)(be,{}),eval:(0,$.jsx)(a,{}),lsp:(0,$.jsx)(a,{}),tool_search:(0,$.jsx)(ae,{}),load_tools:(0,$.jsx)(I,{}),ask_user_question:(0,$.jsx)(Xe,{}),[Or]:(0,$.jsx)(je,{}),browser_page:(0,$.jsx)(ot,{}),conversation_read:(0,$.jsx)(f,{}),claim_files:(0,$.jsx)(re,{}),plan_update:(0,$.jsx)(O,{}),skill:(0,$.jsx)(p,{}),schedule:(0,$.jsx)(vt,{}),compact_context:(0,$.jsx)(Ee,{}),mcp_manage:(0,$.jsx)(M,{}),sandbox:(0,$.jsx)(M,{}),worktree:(0,$.jsx)(q,{}),sftp:(0,$.jsx)(y,{}),mail:(0,$.jsx)(l,{}),obs_recall:(0,$.jsx)(C,{})},$d=(0,$.jsx)(rt,{}),ef={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`,[Or]:`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`},tf=`toolcall-icon tc-tone-default`;function nf(e){return Qd[e]??$d}function rf(e){return ef[e]??tf}function af(e,t){let n=Xu(e);if(!n)return!1;let r=ad(Zu(n,t));return r?bl({path:r.target,name:r.name}):!1}function of({blockId:e,view:t,statusClass:n,statusLabel:r,duration:i,durationMs:a,exitHint:o,isError:s,isBash:c,onKillBash:l,t:u}){(0,Q.useEffect)(()=>{let d=fl(),f=t.result?.toolCallId??e;if(!d||d.isThinking||d.toolCallId!==e&&d.toolCallId!==f)return;let p=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,m=p.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>u(`liveOutputOmitted`,{n:t})),h=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl);dl(d.toolCallId,{status:r,statusClass:n,duration:i,durationMs:a,exitHint:o,rawOutput:p,output:m,details:t.result?.details,images:h,isError:s,resultTimestamp:t.result?.timestamp,onKillBash:c?l:void 0})},[e,t.liveOutput,t.result,t.status,n,r,i,a,o,s,c,l,u])}var sf=(0,Q.memo)(function({block:e,view:t,onKillBash:n,uiContextToolCall:i,onUiAction:a,rootRef:o}){let s=W(),l=c(gt()),u=e.name===Or,d=e.name===`bash`,f=!t.result&&t.streaming&&!t.status,p=d&&(f||!t.result),m=t.result!==void 0,h=!t.result&&!!t.status,g=t.result?.isError??t.status?.isError??!1,_=t.status?.durationMs,v=t.result?.durationMs,y=typeof v==`number`?v:_,b=g?`err`:m?`ok`:f||h?`run`:`idle`,x=s(g?`error`:m?`done`:f?`running`:h?`toolDoneWaitingModel`:`toolQueued`),S=(h||m)&&y!==void 0?mf(y):``;(h||m)&&S&&(x=`${x} · ${S}`);let C=h&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,w=ku(e.argumentsText),T=Ou({name:e.name,argumentsText:e.argumentsText,hints:w}),E=T?`${e.name}(${T.text})`:`${e.name}()`;of({blockId:e.id,view:t,statusClass:b,statusLabel:x,duration:S,durationMs:y,exitHint:C,isError:g,isBash:d,onKillBash:n,t:s});let D=(0,Q.useMemo)(()=>{let e=t.result?.content;return Array.isArray(e)?e.some(e=>e.type===`image`):!1},[t.result?.content]),O=(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]),k=t=>{let r=i??[],o=[];d&&n&&o.push(Mi({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:l?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:p?void 0:[`disabled`]})),o.push(...r),o.length!==0&&(t.preventDefault(),t.stopPropagation(),na({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:kill-bash`){n?.();return}if(t.id===`host:tool-info`){pu(e.name);return}a?.(t)}}))},A=()=>{let r=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,i=r.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>s(`liveOutputOmitted`,{n:t})),a=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),o=u?Xu(e.argumentsText):null;ll({isThinking:!1,name:e.name,title:E,status:x,statusClass:b,duration:S,durationMs:y,exitHint:C,hints:w,args:e.argumentsText||``,rawOutput:r,output:i,details:t.result?.details,images:a,isError:g,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,onKillBash:d?n:void 0,presentData:u&&o?{title:o.title,note:o.note,items:o.items}:null})},j=n=>{u&&!n?.altKey&&af(e.argumentsText,t.result?.details)||A()};return(0,$.jsx)(`div`,{ref:o,className:`toolcall ${b}`,onClick:e=>{e.preventDefault(),e.stopPropagation(),j(e)},onContextMenu:k,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),j(e))},role:`button`,tabIndex:0,title:`${e.name}(${T?T.text:``}) · ${x}`,children:(0,$.jsxs)(`div`,{className:`toolcall-head chead`,children:[(0,$.jsx)(`span`,{className:`toolcall-icon chead-icon ${rf(e.name)}`,children:nf(e.name)}),(0,$.jsx)(`span`,{className:`toolcall-name chead-title`,children:e.name}),(0,$.jsx)(`span`,{className:`toolcall-status`,title:C?`${x} · ${C}`:x,"aria-label":C?`${x} · ${C}`:x,children:g?(0,$.jsx)(Z,{}):m?(0,$.jsx)(r,{}):f||h?(0,$.jsx)(xs,{}):(0,$.jsx)(Fe,{})}),D&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:s(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(je,{})}),O&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:l?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(U,{})})]})})}),cf=(0,Q.memo)(function({block:e,view:t,onKillBash:n,wrap:i=!0,showImages:a=!0,forceOpen:o=!1,uiContextToolCall:s,uiToolCardFooter:l,onUiAction:u,rootRef:f}){let p=W(),m=c(gt()),[h,g]=(0,Q.useState)(null),_=e.name===Or,v=h??(_?!0:i),y=v||o,{copied:x,copy:S}=Dc({duration:1200}),C=!t.result&&t.streaming&&!t.status,w=e.name===`bash`,T=w&&(C||!t.result),E=t.result!==void 0,D=!t.result&&!!t.status,O=t.result?.isError??t.status?.isError??!1,k=(0,Q.useRef)(null),A=(0,Q.useRef)(!0),j=(0,Q.useMemo)(()=>y?t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``:``,[y,t.result,t.liveOutput]),M=(0,Q.useMemo)(()=>!y||!j?``:j.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>p(`liveOutputOmitted`,{n:t})),[y,j,p]);(0,Q.useEffect)(()=>{y&&(C||D)&&A.current&&k.current&&(k.current.scrollTop=k.current.scrollHeight)},[y,M,C,D]);let N=(0,Q.useMemo)(()=>a?(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))):[],[a,t.result]),[P,F]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!P)return;let e=e=>{e.key===`Escape`&&F(null)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[P]);let I=e.name===`delegate_task`,L=(0,Q.useMemo)(()=>!I||!y?{}:Nu(e.argumentsText),[I,y,e.argumentsText]),ee=e.name===`codemode`,R=(0,Q.useMemo)(()=>ee&&y?Bu(e.argumentsText):null,[ee,y,e.argumentsText]),te=e.name===`ask_user_question`,ne=(0,Q.useMemo)(()=>te&&y?Wu(e.argumentsText):null,[te,y,e.argumentsText]),re=e.name===`edit`||e.name===`write`||e.name===`edit_soft`||e.name===`patch`,z=(0,Q.useMemo)(()=>re?Kd(e.name,e.argumentsText,t.result?.details,M):null,[re,e.name,e.argumentsText,t.result?.details,M]),B=N.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)(()=>_&&y?Xu(e.argumentsText):null,[_,y,e.argumentsText]),V=I&&t.result&&typeof t.result.details==`object`&&t.result.details!==null?t.result.details.convId:void 0,oe=(0,Q.useMemo)(()=>{if(!I)return;if(V)return V;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]},[I,V,t.result?.content]),se=(0,Q.useRef)(void 0),ce=t.status?.durationMs,le=t.result?.durationMs;(0,Q.useEffect)(()=>{ce!==void 0&&(se.current=ce),typeof le==`number`&&(se.current=le)},[ce,le]);let ue=typeof le==`number`?le:ce??se.current,de=O?`err`:E?`ok`:C||D?`run`:`idle`,fe=p(O?`error`:E?`done`:C?`running`:D?`toolDoneWaitingModel`:`toolQueued`),me=(D||E)&&ue!==void 0?mf(ue):``;(D||E)&&me&&(fe=`${fe} · ${me}`);let H=D&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,he=ku(e.argumentsText),ge=e.name===`bash`?he.command:void 0,ve=Ou({name:e.name,argumentsText:e.argumentsText,hints:he,isCollapsed:!y}),G=ve?`${e.name}(${ve.text})`:`${e.name}()`;of({blockId:e.id,view:t,statusClass:de,statusLabel:fe,duration:me,durationMs:ue,exitHint:H,isError:O,isBash:w,onKillBash:n,t:p});let K=()=>{e.argumentsText&&S(e.argumentsText)};(s??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`);let q=t=>{let r=t.target;if(r instanceof Element&&r.closest(`pre, code, a, input, textarea, [contenteditable='true']`))return;let i=window.getSelection?.();if(i&&!i.isCollapsed&&i.toString().trim().length>0)return;let a=s??[],o=[];w&&n&&o.push(Mi({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:m?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:T?void 0:[`disabled`]})),o.push(...a),o.length!==0&&(t.preventDefault(),t.stopPropagation(),na({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:kill-bash`){n?.();return}if(t.id===`host:tool-info`){pu(e.name);return}u?.(t)}}))},ye=()=>{let r=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,i=r.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>p(`liveOutputOmitted`,{n:t})),a=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl),o=_?Xu(e.argumentsText):null;ll({isThinking:!1,name:e.name,title:G,status:fe,statusClass:de,duration:me,durationMs:ue,exitHint:H,hints:he,args:e.argumentsText||``,rawOutput:r,output:i,details:t.result?.details,images:a,isError:O,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,onKillBash:w?n:void 0,presentData:_&&o?{title:o.title,note:o.note,items:o.items}:null})},be=n=>{_&&!n?.altKey&&af(e.argumentsText,t.result?.details)||ye()};return(0,$.jsxs)(`div`,{ref:f,className:`toolcall ${de}${N.length>0?` has-images`:``}`,onClick:e=>{hl(f.current)&&(e.target?.closest(`button, a, .toolcall-kill, .toolcall-open, .toolcall-image, .file-diff-action-btn, .btn-tag`)||(e.preventDefault(),e.stopPropagation(),be(e)))},children:[(0,$.jsx)(tu,{open:y,headClassName:`toolcall-head`,toggleClassName:`toolcall-toggle`,titleText:p(y?`collapseMsg`:`expandMsg`),onToggle:()=>{if(hl(f.current)){be();return}g(!v)},onHeadContextMenu:q,icon:nf(e.name),iconClassName:rf(e.name),titleClassName:`toolcall-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`toolcall-status`,title:H?`${fe} · ${H}`:fe,"aria-label":H?`${fe} · ${H}`:fe,children:O?(0,$.jsx)(Z,{}):E?(0,$.jsx)(r,{}):C||D?(0,$.jsx)(xs,{}):(0,$.jsx)(Fe,{})}),B&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:p(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(je,{})}),ie&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:m?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(U,{})}),me&&(0,$.jsx)(`span`,{className:`toolcall-duration toolcall-timeout`,style:{marginLeft:-2,fontFamily:`var(--mono)`},title:H?`${fe} · ${H}`:fe,children:me}),ve&&(0,$.jsxs)(`span`,{className:ve.className,title:ve.title??ve.text,children:[ve.prefix,ve.text]}),z&&(z.stats.additions>0||z.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`toolcall-diff-badge`,title:`+${z.stats.additions} -${z.stats.deletions}`,children:[z.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,z.stats.additions]}),z.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,z.stats.deletions]})]}),he.timeout&&(0,$.jsxs)(`span`,{className:`toolcall-timeout`,children:[`⏱ `,he.timeout]}),(0,$.jsx)(`span`,{className:`toolcall-spacer`}),T&&n&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-kill`,title:p(`stopBashTip`),onClick:e=>{e.stopPropagation(),n?.()},children:[(0,$.jsx)(pe,{}),(0,$.jsx)(`span`,{children:p(`stopBash`)})]}),I&&E&&oe&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-open`,title:p(`delegateOpenSubagent`),onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:oe}))},children:[(0,$.jsx)(_e,{}),(0,$.jsx)(`span`,{children:p(`delegateOpenSubagent`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy${x?` copied`:``}`,title:p(`copyArgs`),"aria-label":p(`copyArgs`),onClick:e=>{e.stopPropagation(),K()},children:x?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{})})]}),children:e.name}),N.length>0&&(0,$.jsx)(`div`,{className:`toolcall-images`,children:N.map((e,t)=>{let n=e.dataUrl.startsWith(`/`)?d(e.dataUrl):e.dataUrl;return(0,$.jsx)(`button`,{type:`button`,className:`toolcall-image`,title:p(`toolImageZoom`),"aria-label":p(`toolImageZoom`),onClick:e=>{e.stopPropagation(),F(n)},children:(0,$.jsx)(`img`,{src:n,loading:`lazy`,decoding:`async`,alt:`tool result image ${t+1}`})},t)})}),P&&(0,Fn.createPortal)((0,$.jsxs)(`div`,{className:`img-lightbox`,role:`dialog`,"aria-label":p(`toolImageZoom`),onClick:()=>F(null),children:[(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-close`,title:p(`close`),"aria-label":p(`close`),onClick:e=>{e.stopPropagation(),F(null)},children:(0,$.jsx)(Z,{})}),(0,$.jsx)(`img`,{src:P,alt:`tool result preview`})]}),document.body),y&&(0,$.jsxs)(`div`,{className:`toolcall-body`,children:[_&&ae?(0,$.jsx)(Md,{args:ae,details:t.result?.details,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp}):I?(0,$.jsx)(ff,{args:L}):ee&&R?.code?(0,$.jsx)(pf,{code:R.code,options:R.options,details:t.result?.details,output:M}):te&&ne?(0,$.jsx)(Ld,{questions:ne.questions,details:t.result?.details,output:M,isError:O,waiting:C||D}):re?(0,$.jsx)(qd,{toolName:e.name,argumentsText:e.argumentsText,details:t.result?.details,output:M,isError:O,onOpenInspector:ye}):e.argumentsText&&(0,$.jsx)(`div`,{className:`toolcall-args`,children:ge?(0,$.jsx)(uf,{command:ge}):(0,$.jsx)(`pre`,{children:e.argumentsText})}),e.name===`tool_search`&&(0,$.jsx)(df,{details:t.result?.details}),M.length>0&&!(te&&ne)&&(0,$.jsxs)(`div`,{className:`toolcall-output`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[p(O?`errorOutput`:`output`),(C||D)&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{ref:k,onWheel:e=>{if(e.deltaY<0)A.current=!1;else if(e.deltaY>0&&k.current){let e=k.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(A.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(A.current=!0)},children:M})]}),C&&M.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,p(`waitingOutput`)]}),D&&M.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,p(`waitingModel`)]}),l&&l.length>0&&(0,$.jsx)(`div`,{className:`toolcall-footer`,children:l.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:()=>u?.(e),children:[e.icon&&Gp(e.icon),(0,$.jsx)(`span`,{children:n})]},`${e.id}#${t}`)})})]})]})}),lf=(0,Q.memo)(function(e){let t=(0,Q.useRef)(null);return hl(t.current)?(0,$.jsx)(sf,{block:e.block,view:e.view,onKillBash:e.onKillBash,uiContextToolCall:e.uiContextToolCall,onUiAction:e.onUiAction,rootRef:t}):(0,$.jsx)(cf,{...e,rootRef:t})});function uf({command:e}){return(0,$.jsxs)(`div`,{className:`termline`,children:[(0,$.jsx)(Se,{className:`termline-icon`}),(0,$.jsx)(`code`,{children:Us(e)})]})}function df({details:e}){let t=W(),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 ff({args:e}){let t=W(),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 pf({code:e,options:t,details:n,output:r}){let i=W(),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:mf(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)(je,{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)(b,{})})]},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 mf(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 hf=Object.freeze({status:`idle`,messages:[]}),gf=new Map,_f=new Set,vf=16;function yf(){for(;gf.size>vf;){let e=gf.keys().next().value;if(e===void 0)break;gf.delete(e)}}function bf(){for(let e of _f)e()}function xf(e,t){let n=(e??``).trim();if(!n)return;let r=gf.get(n);(!r||r.status!==`loading`&&r.status!==`ready`)&&(gf.set(n,{status:`loading`,messages:r?.messages??[]}),yf(),bf(),X({type:`get_compacted_messages`,compactionMessageId:n,conversationId:t}))}function Sf(e){let t=e.compactionMessageId;t&&(e.error?gf.set(t,{status:`error`,messages:[],error:e.error}):gf.set(t,{status:`ready`,messages:e.messages??[]}),yf(),bf())}function Cf(e){let t=gf.get(e);return t?(gf.delete(e),gf.set(e,t),t):hf}function wf(e){return _f.add(e),()=>{_f.delete(e)}}function Tf(e){return(0,Q.useSyncExternalStore)(wf,()=>Cf(e),()=>hf)}var Ef=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Df(e){let t=e.match(Ef);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}var Of=1568,kf=2097152;function Af(e){return e.startsWith(`image/`)&&e!==`image/svg+xml`&&e!==`image/svg`}async function jf(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,Of/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<=kf)return o}return o}finally{t.close()}}var Mf=null;function Nf(e){Mf=e?.open??null,e?.close,e?.isOpen}function Pf(e){return!Mf||!e?.src?!1:(Mf(e),!0)}function Ff(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 If(e){return Ff(e).join(`
32
-
33
- `)}function Lf(e){return Rf(If(e))}function Rf(e){let t=e.split(`
34
- `),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(`
35
- `).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(`
36
- `).map(e=>e.replace(/[ \t]+/g,` `).replace(/^\s+|\s+$/g,``)).join(`
37
- `).replace(/\n{3,}/g,`
38
-
39
- `).trim()}function zf(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 Bf(e){return e==null||!Number.isFinite(e)?``:e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}var Vf=`pi-web-tts`,Hf={enabled:!1,announce:!0,readReplies:!1,streamReplies:!0,rate:1,voiceURI:``,engine:`builtin`};function Uf(){try{let e=localStorage.getItem(Vf);if(!e)return{...Hf};let t={...Hf,...JSON.parse(e)};for(let e of[`enabled`,`announce`,`readReplies`,`streamReplies`])typeof t[e]!=`boolean`&&(t[e]=Hf[e]);return t.rate=typeof t.rate!=`number`||!Number.isFinite(t.rate)?Hf.rate:Math.round(Math.max(.5,Math.min(2,t.rate))*10)/10,typeof t.voiceURI!=`string`&&(t.voiceURI=Hf.voiceURI),typeof t.engine!=`string`&&(t.engine=Hf.engine),t}catch{return{...Hf}}}function Wf(e){try{localStorage.setItem(Vf,JSON.stringify(e))}catch{}}function Gf(){return typeof window<`u`&&`speechSynthesis`in window}function Kf(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 qf(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 Jf=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=qf(r,0);i&&this.onSentence(i)}}flush(e){if(e.length>this.cursor){let t=qf(e.slice(this.cursor),0);t&&this.onSentence(t),this.cursor=e.length}}reset(){this.cursor=0}};function Yf(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 qf((n.content??[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
40
- `))}return``}var Xf=!1,Zf=null,Qf=null,$f=null,ep=null,tp=new Set;function np(e,t=null){let n=!!e,r=n?t:null;if(Xf!==n||Zf!==r){Xf=n,Zf=r;for(let e of tp)try{e(n)}catch{}}}function rp(){return Xf}function ip(){return Xf?Zf:null}function ap(e){return tp.add(e),()=>tp.delete(e)}function op(e,t=Uf(),n){if(!e)return;sp();let r=(t.engine||`builtin`).trim(),i=r===`builtin`?void 0:Kt(r);if(i&&typeof i.play==`function`){let r=!1;np(!0,n??null);try{let a=i.play({text:e,rate:t.rate,voiceURI:t.voiceURI,onStart:()=>{r||np(!0,n??null)},onEnd:()=>{r||(r=!0,Qf=null,np(!1))},onError:()=>{r||(r=!0,Qf=null,np(!1))}});Qf=()=>{r=!0;try{a?.()}catch{}}}catch{np(!1)}return}if(Gf())try{let r=window.speechSynthesis,i=new SpeechSynthesisUtterance(e);i.rate=t.rate;let a=Kf(t.voiceURI,r.getVoices(),navigator.language);a&&(i.voice=a),i.onend=()=>{ep===i&&np(!1)},i.onerror=()=>{ep===i&&np(!1)},ep=i,np(!0,n??null),r.speak(i)}catch{ep=null,np(!1)}}function sp(){if($f&&=($f.stop(),null),Qf){try{Qf()}catch{}Qf=null}if(Gf())try{window.speechSynthesis.cancel()}catch{}ep=null,np(!1)}var cp=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();np(!0,this.sourceId??null),await new Promise(t=>{let n=(this.settings.engine||`builtin`).trim(),r=n===`builtin`?void 0:Kt(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(Gf()){let n=window.speechSynthesis,r=new SpeechSynthesisUtterance(e);r.rate=this.settings.rate;let i=Kf(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,$f===this&&($f=null),np(!1)}};function lp(e=Uf(),t){sp();let n=new cp(e,t);return $f=n,n}var up={open:!1,triggerId:``,selectedIds:[],includeTools:!1,includeThinking:!1},dp=up,fp=[],pp=new Set;function mp(){for(let e of pp)e()}function hp(e){return(e.role===`user`||e.role===`assistant`)&&If(e.content).length>0}function gp(e,t=fp){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 _p(e){if(fp=e,dp.open){let e=gp(dp.selectedIds,fp);e.join(`\0`)!==dp.selectedIds.join(`\0`)&&(dp={...dp,selectedIds:e},mp())}}function vp(){return dp}function yp(e){return pp.add(e),()=>{pp.delete(e)}}function bp(){return(0,Q.useSyncExternalStore)(yp,vp,vp)}function xp(){dp.open&&(dp=up,mp())}function Sp(e){let t=fp.find(t=>t.id===e);if(t&&hp(t)){if(dp.open){dp={...dp,selectedIds:gp([...dp.selectedIds,e])},mp();return}dp={open:!0,triggerId:e,selectedIds:[e],includeTools:!1,includeThinking:!1},mp()}}function Cp(e){dp.open&&(dp={...dp,includeTools:e.includeTools??dp.includeTools,includeThinking:e.includeThinking??dp.includeThinking},mp())}function wp(e){if(!dp.open||!fp.filter(hp).map(e=>e.id).includes(e))return;let t=dp.selectedIds.includes(e)?dp.selectedIds.filter(t=>t!==e):gp([...dp.selectedIds,e]);dp={...dp,selectedIds:t},mp()}function Tp({title:e,children:t,...n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(!1),o=(0,Q.useId)(),s=Rn({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,Fn.createPortal)((0,$.jsx)(`div`,{ref:s.panelRef,id:o,role:`tooltip`,className:`msg-action-tooltip`,style:s.style,children:e}),document.body)]})}var Ep=/^(This operation was aborted|Request aborted)$/;function Dp(e){return e.stopReason===`aborted`||e.stopReason===`error`&&Ep.test((e.errorMessage??``).trim())}var Op=/\[\[\s*([A-Za-z][A-Za-z0-9_-]*)\s*:\s*([A-Za-z][A-Za-z0-9_-]*)\s*:(.*?)\s*\]\]/g,kp=new Set([`todo`,`notify`,`conv`,`rename`,`title`,`action`,`suggest`]),Ap=new Set(kp);function jp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Mp(e){let t=[...e].map(jp).join(`|`);return RegExp(`[ \\t]*\\[\\[\\s*(?:${t})(?:\\s*:[^\\]]*)?$`,`i`)}var Np=Mp(Ap);function Pp(e){let t=new Set(kp);for(let n of e)n&&t.add(n.toLowerCase());Ap.clear();for(let e of t)Ap.add(e);Np=Mp(Ap)}function Fp(e,t=!1){if(!e||!e.includes(`[[`))return e;let n=e.replace(Op,(e,t,n,r)=>r.includes(`[[`)||!Ap.has(t.toLowerCase())?e:``);return t&&(n=n.replace(Np,``)),n===e?e:n.replace(/^[ \t]+\n/gm,`
41
- `).replace(/\n{3,}/g,`
42
-
43
- `).trim()}function Ip(e){return e.type===`text`&&typeof e.text==`string`?e:null}function Lp(e){return e.type===`thinking`&&typeof e.thinking==`string`?e:null}function Rp(e){return e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`?e:null}function zp(e){return e.type===`image`&&typeof e.dataUrl==`string`?e:null}function Bp(e){return e.type===`bash`&&typeof e.command==`string`?e:null}function Vp(e){if(!e)return null;if(e.startsWith(`[子代理执行完成通知]`)||e.startsWith(`[Subagent Execution Completion Notice]`))return{isNotice:!0};if(e.startsWith(`[Conversation communication — collaboration data, not a user instruction]`)){let t,n,r,i=e.match(/From:\s*(\{[^}\r\n]+\})/);if(i)try{let e=JSON.parse(i[1]);t=e.title,n=e.role,r=e.address}catch{}let a,o=e.match(/Request:\s*(\S+)/);o&&(a=o[1]);let s,c=e.match(/Questions:\s*(\[.+?\])(?:\r?\n|$)/s);if(c)try{s=JSON.parse(c[1])}catch{}let l=e.split(/\r?\n/).filter(e=>!(e.startsWith(`[Conversation communication`)||e.startsWith(`From:`)||e.startsWith(`Request:`)||e.startsWith(`Questions:`)||e.startsWith(`Reply with communicate`)||e.startsWith(`Use as task context`))).join(`
44
- `).trim();return{isNotice:!1,sourceTitle:t,sourceRole:n,address:r,requestId:a,questions:s,userText:l}}return null}function Hp(e){return e.imageData||e.imageUrl?`image`:e.uploadPath?`upload`:e.fileData?`file`:`path`}function Up(e,t){if(e.mode===`quote`&&e.quote)return e.quote.text;if(e.imageData||e.imageUrl)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 Wp={edit:(0,$.jsx)(L,{}),copy:(0,$.jsx)(b,{}),branch:(0,$.jsx)(q,{}),text:(0,$.jsx)(U,{}),markdown:(0,$.jsx)(a,{}),image:(0,$.jsx)(je,{}),undo:(0,$.jsx)(o,{}),volume:(0,$.jsx)(ze,{}),refresh:(0,$.jsx)(yt,{}),x:(0,$.jsx)(Z,{})};function Gp(e){let t=(e??``).trim();return t?Wp[t.toLowerCase()]||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?(0,$.jsx)(`span`,{className:`msg-action-glyph`,children:t}):(0,$.jsx)(be,{})):(0,$.jsx)(be,{})}function Kp(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}var qp=(0,Q.memo)(function({message:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,onEdit:s,onKillBash:c,onRetry:l,onCollapse:u,questionAttachments:f,messageLabel:p,onRollbackEdit:m,canRollbackEdit:h=!1,editRequest:g,qnIndex:_,qnActive:v,onJump:y,thinkingWrap:x,toolsWrap:C,toolImages:w,searchActive:T,autoExpand:E,uiMessageActions:D,uiContextMessage:O,uiContextToolCall:k,uiToolCardFooter:j,onUiAction:M,readOnly:N=!1}){let P=W(),[F,I]=(0,Q.useState)(!1),[ee,R]=(0,Q.useState)(``),[te,ne]=(0,Q.useState)([]),[re,z]=(0,Q.useState)(!1),B=Me(`chatUploadMaxMb`),ie=Me(`engine`),ae=(0,Q.useRef)(0),[V,oe]=(0,Q.useState)([]),se=e=>oe(t=>t.filter(t=>t.id!==e)),[ce,le]=(0,Q.useState)(null),ue=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ue.current&&clearTimeout(ue.current)},[]);let de=e=>{le(e),ue.current&&clearTimeout(ue.current),ue.current=setTimeout(()=>le(t=>t===e?null:t),4e3)};if(e.role===`toolResult`||e.role===`system`)return null;if(e.role===`compactionSummary`)return(0,$.jsx)(Xp,{message:e,forceOpen:T,autoExpand:E});let fe=e.role===`custom`&&e.customType===`file`,me=fe&&e.details?.mode===`quote`?Ps(e.details.quote):null,H=e.details?.quotes,he=e.role===`user`&&Array.isArray(H)?H.map(Ps).filter(e=>e!==null):[],ge=e.details?.attachments,_e=e.role===`user`&&Array.isArray(ge)?ge.filter(t=>t.type!==`image`||!e.content.some(e=>e.type===`image`)):[],ve=e.content.map(e=>Ip(e)?.text??``).filter(Boolean).join(`
45
- `),G=e.role===`user`?Df(ve):null,K=G?G.userMessage??`skill:${G.name}`:ve.split(`
46
- `).join(` `).trim(),q=i&&o&&e.role===`assistant`&&e.content.length===0,ye=!N&&e.role===`user`&&!i&&!q&&!!s,be=!N&&ie===`pi`&&!i&&!F&&(e.role===`user`||e.role===`assistant`),xe=()=>{be&&X({type:`delete_message`,messageId:e.id})},Se=async e=>{let t=[];for(let n of e){if(!Af(n.type))continue;if(n.size>B*1024*1024){de(P(`fileTooLarge`,{name:n.name,size:B}));continue}let e=++ae.current;oe(t=>[...t,{id:e,name:n.name,percent:null}]);try{let e=await jf(n);if(!e){de(P(`fileLoadFailed`,{name:n.name}));continue}t.push({path:``,imageData:e.data,mimeType:e.mimeType,name:e.name})}catch{de(P(`fileLoadFailed`,{name:n.name}))}finally{se(e)}}t.length>0&&ne(e=>[...e,...t])},J=async e=>{if(e.size>B*1024*1024){de(P(`fileTooLarge`,{name:e.name,size:B}));return}let t=++ae.current;oe(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;oe(e=>e.map(e=>e.id===t?{...e,percent:n}:e))},i.readAsDataURL(e)})).replace(/^data:[^;]*;base64,/,``)}catch{de(P(`fileLoadFailed`,{name:e.name}));return}finally{se(t)}ne(t=>[...t,{path:``,fileData:n,name:e.name,size:e.size,mimeType:e.type||void 0}])},Ce=async e=>{let t=[];for(let n of e)Af(n.type)?t.push(n):J(n);t.length>0&&await Se(t)},[we,Te]=(0,Q.useState)(!1),Ee=(0,Q.useRef)(!1),De=async(t,n)=>{if(!Ee.current){if(!n.some(e=>e.imageUrl)){s?.(e.id,t,n.length?n:void 0),I(!1);return}Ee.current=!0,Te(!0);try{let r=await Promise.all(n.map(async({imageUrl:e,...t})=>{if(!e)return t;let n=await fetch(d(e));if(!n.ok)throw Error(`Image load failed: ${n.status}`);let r=await n.blob(),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result)),n.onerror=()=>t(n.error),n.readAsDataURL(r)});return{...t,imageData:i.slice(i.indexOf(`,`)+1),mimeType:r.type||t.mimeType}}));s?.(e.id,t,r.length?r:void 0),I(!1)}catch{I(!0),de(P(`fileLoadFailed`,{name:n.find(e=>e.imageUrl)?.name??`image`}))}finally{Ee.current=!1,Te(!1)}}},Oe=()=>{let t=(G?`/skill:`+G.name+(G.userMessage?` `+G.userMessage:``):e.content.map(e=>Ip(e)?.text??``).filter(Boolean).join(`
47
- `)).trim(),n=!!(f&&f.length>0);(t||n)&&(R(t),ne(f??[]),De(t,f??[]))},ke=()=>{R(G?`/skill:${G.name}${G.userMessage?` ${G.userMessage}`:``}`:e.content.map(e=>Ip(e)?.text??``).filter(Boolean).join(`
48
- `)),ne(f??[]),I(!0)};(0,Q.useEffect)(()=>{g&&ye&&ke()},[g]);let Ae=()=>{ye?ke():m?.(e.id)},Y=!N&&!i&&!F&&(ye||h),Ne=()=>{let e=ee.trim();(e||te.some(e=>e.mode===`quote`&&Ps(e.quote)))&&De(e,te)},Fe=!D||D.some(e=>e?.id===`host:msg-copy`&&e.hidden!==!0),Ie=(0,Q.useRef)(null),[Le,Re]=(0,Q.useState)(null),Be=bp(),Ve=(0,Q.useRef)(0),He=If(e.content),Ue=(e.role===`assistant`||e.role===`user`)&&He.length>0,We=async t=>{try{let n=!1;if(t===`host:msg-copy-text`)n=await Ec(Lf(e.content));else if(t===`host:msg-copy-markdown`)n=await Ec(He);else{Sp(e.id);return}window.clearTimeout(Ve.current),Re({id:t,ok:n}),Ve.current=window.setTimeout(()=>Re(null),1600)}catch{window.clearTimeout(Ve.current),Re({id:t,ok:!1}),Ve.current=window.setTimeout(()=>Re(null),1600)}},Ge=Kp(Lf(e.content),40)||em(e.role,P),[Ke,qe]=(0,Q.useState)(rp());(0,Q.useEffect)(()=>ap(qe),[]);let Je=e.role===`assistant`&&Lf(e.content).trim().length>0&&!i&&Gf(),Ye=Je&&ip()===e.id,Xe=()=>{if(Ye){sp();return}op(qf(Lf(e.content),5e3),{...Uf(),enabled:!0},e.id)},[Ze,Qe]=(0,Q.useState)(!1),$e=(0,Q.useRef)(null),et=Rn({open:Ze,anchor:$e,onClose:()=>Qe(!1)}),tt=e=>Je?(0,$.jsxs)(Tp,{type:`button`,className:`msg-action${Ye?` msg-action-speaking`:``}`,title:P(Ye?`stopSpeakingMsg`:`speakMsg`),"aria-label":P(Ye?`stopSpeakingMsg`:`speakMsg`),onClick:Xe,children:[Ye?(0,$.jsx)(pe,{}):(0,$.jsx)(ze,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(Ye?`stopSpeakingMsg`:`speakMsg`)})]},e):null,nt=()=>bi.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:[]})),rt=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=(O&&O.length>0?O:nt()).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 Ue?t:{...t,hidden:!0};case`host:msg-ctx-copy-image`:return Ue?t:{...t,hidden:!0};case`host:msg-ctx-copy-link`:{let n=Ss(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 ye?t:{...t,hidden:!0};case`host:msg-ctx-rollback`:return Y?t:{...t,hidden:!0};case`host:msg-ctx-fork`:return!N&&!i&&!F?t:{...t,hidden:!0};case`host:msg-ctx-delete`:return be?t:{...t,hidden:!0};case`host:msg-ctx-speak`:return Je?Ye?{...t,label:P(`stopSpeakingMsg`),icon:`square`}:t:{...t,hidden:!0};default:return t}});pa(a).length!==0&&(t.preventDefault(),na({x:t.clientX,y:t.clientY,slot:`contextmenu.message`,target:{id:e.id,kind:`message`,label:Ge},entries:a,onHostAction:t=>{switch(t.id){case`host:msg-ctx-copy-markdown`:We(`host:msg-copy-markdown`);return;case`host:msg-ctx-copy-text`:We(`host:msg-copy-text`);return;case`host:msg-ctx-copy-image`:We(`host:msg-copy-image`);return;case`host:msg-ctx-copy-link`:{let t=Ss(window.location.hash)?.sessionId;t&&e.id&&Ec(ws(window.location.href,{sessionId:t,messageId:e.id}));return}case`host:msg-ctx-reask`:Oe();return;case`host:msg-ctx-edit-reask`:ke();return;case`host:msg-ctx-fork`:X({type:`fork_session`,messageId:e.id,position:`at`});return;case`host:msg-ctx-rollback`:Ae();return;case`host:msg-ctx-delete`:xe();return;case`host:msg-ctx-speak`:Xe();return;default:M?.(t);return}}}))},it=(e,t)=>{if(!Ue)return null;let n=[{id:`host:msg-copy-markdown`,label:P(`copyMarkdown`),icon:(0,$.jsx)(a,{})},{id:`host:msg-copy-text`,label:P(`copyText`),icon:(0,$.jsx)(U,{})},{id:`host:msg-copy-image`,label:P(`copyImage`),icon:(0,$.jsx)(je,{})}].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=Le!==null,i=Le?.ok;return(0,$.jsxs)(`div`,{ref:$e,className:`msg-copy-group${Ze?` has-open-dropdown`:``}`,children:[(0,$.jsxs)(Tp,{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 We(`host:msg-copy-markdown`),children:[i?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{}),(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(i?`copied`:`copy`)})]}),(0,$.jsx)(Tp,{type:`button`,className:`msg-action msg-copy-caret-btn${Ze?` active`:``}`,title:P(`moreCopyOptions`),"aria-label":P(`moreCopyOptions`),"aria-expanded":Ze,onClick:e=>{e.stopPropagation(),Qe(e=>!e)},children:(0,$.jsx)(A,{className:`msg-copy-caret-icon${Ze?` open`:``}`})}),Ze&&(0,Fn.createPortal)((0,$.jsx)(`div`,{ref:et.panelRef,style:et.style,className:`msg-copy-dropdown`,role:`menu`,children:n.map(e=>(0,$.jsxs)(Tp,{type:`button`,className:`msg-copy-menu-item`,title:e.label,role:`menuitem`,onClick:()=>{Qe(!1),We(e.id)},children:[e.icon,(0,$.jsx)(`span`,{children:e.label})]},e.id))}),document.body)]},e)},at=()=>{if(!D){let e=it(`fb-copy`),t=tt(`fb-speak`);if(!ye&&!e&&!t)return null;let n=[];return ye&&n.push((0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":P(`reaskDirectly`),onClick:Oe,children:[(0,$.jsx)(yt,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:P(`reaskDirectly`)})]}),(0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),"aria-label":P(`editReask`),onClick:ke,children:[(0,$.jsx)(L,{}),` `,(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 D.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=it(`copy-dropdown`,D);e&&t.push(e)}return}if(r.id===`host:msg-speak`){let e=tt(o);e&&t.push(e);return}if(r.id===`host:msg-delete`){if(!be)return;t.push((0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:xe,children:[Gp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-reask`){if(!ye)return;t.push((0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`reaskDirectlyTip`),"aria-label":s,onClick:Oe,children:[Gp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-edit-reask`){if(!ye)return;t.push((0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`editReaskTip`),onClick:ke,children:[Gp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-fork`){if(N||i||F)return;t.push((0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`forkSessionTip`),"aria-label":s,onClick:()=>X({type:`fork_session`,messageId:e.id,position:`at`}),children:[Gp(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-rollback`){if(!Y)return;t.push((0,$.jsxs)(Tp,{type:`button`,className:`msg-action`,title:P(`rollbackSessionTip`),"aria-label":s,onClick:()=>{Ae()},children:[Gp(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)(Tp,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:()=>M?.(r),children:[Gp(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},ot=()=>{let e=at();return e?(0,$.jsx)(`div`,{className:`msg-actions${Ze?` has-open-dropdown`:``}`,children:e}):null},st=e.role===`custom`&&(e.customType===`goal-review`||e.customType===`goal-wizard`),ct=e.role===`custom`&&e.customType===`goal-wizard`,lt=e.role===`custom`&&!!e.customType&&e.customType!==`file`&&!st&&rl(e.customType),ut=lt?JSON.stringify({customType:e.customType,details:e.details??{}}):``,dt=Be.open&&Be.selectedIds.includes(e.id),ft=Be.open&&Ue,pt=dt&&Be.includeThinking,mt=dt&&Be.includeTools,ht=!F&&(e.role===`user`||Ue),gt=(0,Q.useMemo)(()=>{if(e.role!==`assistant`)return-1;for(let t=e.content.length-1;t>=0;t--)if(Ip(e.content[t]))return t;return-1},[e.role,e.content]),_t=(0,Q.useMemo)(()=>{if(e.role!==`user`)return null;for(let t of e.content){let e=Ip(t);if(e){let t=Vp(e.text);if(t)return t}}return null},[e.role,e.content]);return(0,$.jsxs)(`div`,{ref:Ie,className:`msg msg-${e.role}${_t?_t.isNotice?` msg-collab-notice`:` msg-collaboration`:``}${st?` msg-goal-review`:``}${dt?` msg-export-selected`:``}${N?` msg-readonly`:``}${p&&e.id.startsWith(`group-`)?` msg-group`:``}`,"data-role":e.role,"data-msg-id":e.id,onContextMenu:rt,children:[ft&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:dt,title:P(`copyImage`),"aria-label":P(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>wp(e.id)}),(0,$.jsxs)(`div`,{className:`msg-meta`,children:[u&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-collapse-btn`,title:P(`collapseMsg`),onClick:()=>u(e.id),children:[(0,$.jsx)(S,{}),` `,P(`collapseMsg`)]}),(0,$.jsx)(`span`,{className:`msg-role`,children:e.role===`custom`?ct?P(`goalWizardCard`):st?P(`goalBarTitle`):e.customType===`file`?P(`attachment`):`${P(`plugin`)} · ${e.customType??P(`unknown`)}`:_t?_t.isNotice?`${P(`subagentBadge`)} · 完成通知`:`${P(`subagentBadge`)} · ${_t.sourceTitle||_t.sourceRole||P(`subagentBadge`)}`:em(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:tm(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:F?(0,$.jsxs)(`div`,{className:`msg-editor${re?` drag-over`:``}`,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),z(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||z(!1)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),z(!1),Ce(Array.from(e.dataTransfer?.files??[]))},children:[te.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-images`,children:te.map((e,t)=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(Ws,{quote:e.quote,onRemove:()=>ne(e=>e.filter((e,n)=>n!==t))},`quote-${t}`);let n=Hp(e);return(0,$.jsxs)(`span`,{className:`msg-editor-img ${n===`image`?``:`file-chip`}`,title:Up(e,P),children:[n===`image`?(0,$.jsx)(`img`,{src:e.imageUrl?d(e.imageUrl):`data:${e.mimeType??`image/png`};base64,${e.imageData}`,alt:e.name,className:`msg-editor-img-clickable`,title:P(`toolImageZoom`),onClick:()=>{Pf({src:e.imageUrl?d(e.imageUrl):`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:()=>ne(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(Z,{})})]},`${e.name??e.path??`att`}-${t}`)})}),V.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:V.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))}),ce&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,children:ce}),(0,$.jsx)(`textarea`,{className:`msg-editor-input`,value:ee,autoFocus:!0,placeholder:P(`editPlaceholder`),rows:Math.max(2,Math.min(10,ee.split(`
49
- `).length+1)),onChange:e=>R(e.target.value),onPaste:e=>{let t=[];for(let n of e.clipboardData?.items??[])if(n.kind===`file`&&Af(n.type)){let e=n.getAsFile();e&&t.push(e)}t.length!==0&&(e.preventDefault(),Se(t))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),Ne()):e.key===`Escape`&&I(!1)}}),(0,$.jsxs)(`div`,{className:`msg-editor-actions`,children:[(0,$.jsxs)(`span`,{className:`msg-editor-hint`,children:[(0,$.jsx)(je,{}),` `,P(`editAttachmentHint`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn sm`,onClick:()=>I(!1),children:P(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary sm`,disabled:we||!ee.trim()&&!te.some(e=>e.mode===`quote`&&Ps(e.quote)),title:P(`reaskFromHere`),onClick:Ne,children:[(0,$.jsx)(L,{}),` `,P(`reaskFromHere`)]})]})]}):(0,$.jsxs)($.Fragment,{children:[Dp(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}),o&&!i&&l&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-retry-btn`,title:P(`retryLastTip`),onClick:l,children:[(0,$.jsx)(yt,{}),` `,P(`retryNow`)]})]}),he.map((e,t)=>(0,$.jsx)(Ws,{quote:e,forceOpen:T},`quote-${t}`)),_e.length>0&&(0,$.jsx)(`div`,{className:`msg-queued-atts-bar`,children:_e.map((t,n)=>{let r;if(t.url)r=t.url.startsWith(`/`)?d(t.url):t.url;else if(t.type===`image`||t.type===`vision-bridge`){let n=f?.find(e=>e.name===t.name||e.imageData||e.imageUrl);if(n?.imageUrl)r=d(n.imageUrl);else if(n?.imageData)r=`data:${n.mimeType??`image/png`};base64,${n.imageData}`;else{let t=e.content.find(e=>e.type===`image`);t?.dataUrl&&(r=t.dataUrl.startsWith(`/`)?d(t.dataUrl):t.dataUrl)}}let i=!!(t.path&&t.type!==`page`&&t.type!==`conversation`&&t.type!==`canvas`),a=!!(r||i),o=()=>{r?Pf({src:r,alt:t.name}):i&&t.path&&bl({path:t.path,name:t.name})};return(0,$.jsxs)(`span`,{className:`queued-att-chip${a?` previewable`:``}`,title:a?`${t.name} (${P(r?`toolImageZoom`:`fileOpenPreview`)})`:t.name,onClick:a?o:void 0,role:a?`button`:void 0,tabIndex:a?0:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}:void 0,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:t.type===`image`||t.type===`vision-bridge`?`🖼️`:t.type===`folder`?`📁`:t.type===`page`?`🌐`:t.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:t.name})]},`qatt-${n}`)})}),me?(0,$.jsx)(Ws,{quote:me,forceOpen:T}):fe?(0,$.jsx)(Jp,{message:e,forceOpen:T}):G?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Qp,{block:G,forceOpen:T}),G.userMessage&&(0,$.jsx)(`div`,{className:`msg-text`,children:(0,$.jsx)(Pl,{text:G.userMessage,hardBreaks:!0})}),e.content.map((a,s)=>a.type===`text`?null:(0,$.jsx)($p,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:C,toolImages:w,thinkingWrap:x,searchActive:T,forceThinking:pt,forceTools:mt,role:e.role,showCopy:Fe,uiContextToolCall:k,uiToolCardFooter:j,onUiAction:M},s))]}):lt?(0,$.jsx)(Bl,{type:e.customType??``,code:ut,children:e.content.map((a,s)=>(0,$.jsx)($p,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:C,toolImages:w,thinkingWrap:x,searchActive:T,forceThinking:pt,forceTools:mt,role:e.role,showCopy:Fe,uiContextToolCall:k,uiToolCardFooter:j,onUiAction:M},s))}):e.content.map((a,s)=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)($p,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:C,toolImages:w,thinkingWrap:x,searchActive:T,forceThinking:pt,forceTools:mt,role:e.role,showCopy:Fe,uiContextToolCall:k,uiToolCardFooter:j,onUiAction:M}),s===gt&&ht&&ot()]},s)),q&&(0,$.jsx)(`div`,{className:`thinking-wait minimal`,title:P(`thinkingWait`),"aria-label":P(`thinkingWait`),role:`status`,children:(0,$.jsx)(`span`,{className:`dot`})})]})}),ht&&gt<0&&ot()]})});function Jp({message:e,forceOpen:t=!1}){let n=W(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=Dc({duration:1200}),s=r||t,c=e.details??{},l=c.name??c.path??n(`attachment`),u=c.type===`folder`,f=c.mode===`canvas`,p=c.mode===`reference`||f,m=c.mode===`bridged`,h=c.mode===`page`,_=c.mode===`conversation`,v=c.path&&/^https?:\/\//i.test(c.path.trim())?c.path.trim():null,y=Yp(e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
50
- `)),x=e.content.find(e=>e.type===`image`),S=y.split(`
51
- `).length,C=!p&&!h&&!_&&y.length>0;return(0,$.jsxs)(`div`,{className:`attachcard ${p?`reference`:``}${h?` page`:``}${_?` conversation`:``}`,children:[(0,$.jsx)(tu,{open:s,headClassName:`attachcard-head`,titleText:n(s?`collapseMsg`:`expandMsg`),onToggle:()=>i(e=>t?!0:!e),toggle:!p&&!h&&!_?(0,$.jsx)(`span`,{className:`chead-toggle`,children:s?(0,$.jsx)(A,{}):(0,$.jsx)(g,{})}):null,icon:f?`◈`:u?`📁`:h?`🌐`:_?`💬`:`📎`,iconClassName:`attachcard-icon`,titleClassName:`attachcard-name`,after:(0,$.jsxs)($.Fragment,{children:[c.path&&(h&&v?(0,$.jsx)(`a`,{className:`attachcard-path attachcard-link`,href:v,target:`_blank`,rel:`noreferrer`,children:c.path}):!h&&!_&&!u?(0,$.jsx)(`span`,{className:`attachcard-path attachcard-path-clickable`,title:n(`fileOpenPreview`),onClick:e=>{e.stopPropagation(),bl({path:c.path,name:l})},children:c.path}):(0,$.jsx)(`span`,{className:`attachcard-path`,children:c.path})),(0,$.jsx)(`span`,{className:`attachcard-mode ${c.mode===`lines`?`lines`:p?`ref`:h?`page`:_?`conversation`:m?`bridged`:`inline`}`,children:f?n(`canvasTab`):h?n(`attachPageShort`):_?n(`attachConversationShort`):p?u?n(`folderRefShort`):`${n(`refOnlyShort`)} · ${Bf(c.size)}`:m?n(`bridgedVision`):x?n(`image`):c.mode===`lines`?n(`inlineLinesRange`,{start:c.startLine??1,end:c.endLine??c.lines??1}):n(`inlineLines`,{n:c.lines??S})}),C&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(a?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:e=>{e.stopPropagation(),o(y)},children:a?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{})})]}),children:l}),!p&&s&&(()=>{let e=x?.dataUrl?x.dataUrl.startsWith(`/`)?d(x.dataUrl):x.dataUrl:void 0;return m?(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,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>Pf({src:e,alt:l})})}),y&&(0,$.jsx)(`pre`,{className:`attachcard-content`,children:y})]}):e?(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:l,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>Pf({src:e,alt:l})})}):(0,$.jsx)(`pre`,{className:`attachcard-content`,children:y})})(),p&&(0,$.jsxs)(`div`,{className:`attachcard-refnote`,children:[(0,$.jsx)(`span`,{children:u?n(`folderNotExpanded`):n(`fileNotExpanded`,{size:Bf(c.size)})}),!u&&c.path&&(0,$.jsxs)(`button`,{type:`button`,className:`attachcard-ref-open`,onClick:()=>bl({path:c.path,name:l}),children:[(0,$.jsx)(J,{}),` `,n(`fileOpenPreview`)]})]})]})}function Yp(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 Xp({message:e,forceOpen:t=!1,autoExpand:n=!1}){let r=W(),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Dc({duration:1200}),[c,l]=(0,Q.useState)(n);n!==c&&(l(n),n&&a(!0));let u=i||t,d=Tf(e.id),[f,p]=(0,Q.useState)(!1),m=()=>{f?p(!1):(p(!0),d.status===`idle`&&xf(e.id))},h=e.content.map(e=>Ip(e)?.text??``).filter(Boolean).join(`
52
- `),_=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:tm(e.timestamp)})]}),(0,$.jsxs)(`div`,{className:`compaction-card${i?` expanded`:``}`,children:[(0,$.jsx)(tu,{open:u,headClassName:`compaction-head`,titleText:r(u?`collapseMsg`:`expandMsg`),onToggle:()=>a(e=>t?!0:!e),toggle:(0,$.jsx)(`span`,{className:`chead-toggle`,children:u?(0,$.jsx)(A,{}):(0,$.jsx)(g,{})}),icon:(0,$.jsx)(Ee,{}),iconClassName:`compaction-icon`,titleClassName:`compaction-title`,after:h&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:r(o?`copied`:`copyMessage`),"aria-label":r(`copyMessage`),onClick:e=>{e.stopPropagation(),s(h)},children:o?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{})}),children:_?r(`compactionFrom`,{tokens:_}):r(`role.compaction`)}),u&&(0,$.jsxs)(`div`,{className:`compaction-body`,children:[(0,$.jsx)(Pl,{text:h}),(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:m,"aria-expanded":f,children:[(0,$.jsx)(`span`,{className:`compacted-history-chevron`,children:f?(0,$.jsx)(A,{}):(0,$.jsx)(g,{})}),(0,$.jsx)(vt,{className:`compacted-history-clock-icon`}),(0,$.jsx)(`span`,{className:`compacted-history-btn-text`,children:r(f?`hideCompactedHistory`:`viewCompactedHistory`)}),d.status===`ready`&&d.messages.length>0&&(0,$.jsx)(`span`,{className:`compacted-history-count-pill`,children:r(`compactedHistoryTurns`,{count:d.messages.length})})]})}),f&&(0,$.jsxs)(`div`,{className:`compacted-history-panel`,children:[d.status===`loading`&&(0,$.jsxs)(`div`,{className:`compacted-history-loading`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsx)(`span`,{children:r(`compactedHistoryLoading`)})]}),d.status===`error`&&(0,$.jsx)(`div`,{className:`compacted-history-error`,children:(0,$.jsx)(`span`,{children:d.error===`compactedHistoryNotFound`||d.error===`Compaction entry not found`?r(`compactedHistoryNotFound`):d.error||r(`compactedHistoryEmpty`)})}),d.status===`ready`&&d.messages.length===0&&(0,$.jsx)(`div`,{className:`compacted-history-empty`,children:r(`compactedHistoryEmpty`)}),d.status===`ready`&&d.messages.length>0&&(0,$.jsx)(Zp,{messages:d.messages})]})]})]})]})}function Zp({messages:e}){let t=W(),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)(Ee,{}),` `,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)(qp,{message:e,toolResults:n,liveOutputs:r,toolStatuses:r,streaming:!1,isLast:!1,readOnly:!0},e.id))})]})}function Qp({block:e,forceOpen:t=!1}){let n=W(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=Dc({duration:1200}),s=r||t;return(0,$.jsxs)(`div`,{className:`skillcard${r?` expanded`:``}`,children:[(0,$.jsx)(tu,{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)(A,{}):(0,$.jsx)(g,{})}),icon:(0,$.jsx)(p,{}),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)(Pe,{}):(0,$.jsx)(b,{})})]}),children:e.name}),s&&(0,$.jsx)(`div`,{className:`skillcard-body`,children:(0,$.jsx)(Pl,{text:e.content})})]})}function $p({block:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:o,onKillBash:s,thinkingWrap:c,toolsWrap:l,toolImages:u,searchActive:f,forceThinking:p,forceTools:m,role:h,showCopy:g,uiContextToolCall:_,uiToolCardFooter:v,onUiAction:y}){let x=W(),{copied:S,copy:C}=Dc({duration:1200}),w=o??!0,T=Ip(e),E=!!(T&&i&&a&&w),D=(0,Q.useRef)(E);D.current=E;let O=(0,Q.useRef)(E);E&&(O.current=!0);let k=()=>typeof document<`u`&&document.hidden,[A,j]=(0,Q.useState)(()=>E&&!k());(0,Q.useEffect)(()=>{E&&!k()?j(!0):!E&&k()&&j(!1)},[E]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{D.current||j(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let M=(0,Q.useCallback)(()=>{D.current||j(!1)},[]);if(T){let e=h===`user`?T.text:Fp(T.text,E);if(!e.trim())return null;let t=e===T.text?T:{...T,text:e},n=h===`user`?Vp(T.text):null,r=(h===`assistant`||h===`user`)&&g!==!1,i=r&&!t.text.includes(`
53
- `)&&!t.truncated,a=n&&!n.isNotice?(0,$.jsxs)(`div`,{className:`collab-request-box`,children:[n.userText?(0,$.jsx)(Pl,{text:n.userText,hardBreaks:!0}):null,n.questions&&n.questions.length>0&&(0,$.jsx)(`div`,{className:`collab-questions`,children:n.questions.map((e,t)=>(0,$.jsxs)(`div`,{className:`collab-q-item`,children:[(0,$.jsx)(`div`,{className:`collab-q-title`,children:(0,$.jsx)(`strong`,{children:e.question})}),e.options&&e.options.length>0&&(0,$.jsx)(`div`,{className:`collab-q-options`,children:e.options.map((e,t)=>(0,$.jsx)(`span`,{className:`collab-q-opt-tag`,children:e.label},t))})]},e.id||t))}),n.requestId&&(0,$.jsxs)(`div`,{className:`collab-req-id`,children:[`Request: `,(0,$.jsx)(`code`,{children:n.requestId})]})]}):h===`user`?(0,$.jsx)(Pl,{text:t.text,hardBreaks:!0}):E||A||O.current?(0,$.jsx)(eu,{text:t.text,finishing:!E&&A,onSettled:M}):(0,$.jsx)(Pl,{text:t.text}),o=r?(0,$.jsx)(`button`,{type:`button`,className:`msg-text-copy${S?` copied`:``}`,title:x(S?`copied`:`copyMessage`),"aria-label":x(`copyMessage`),onClick:()=>{C(t.text)},children:S?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{})},`msg-text-copy`):null;return(0,$.jsx)(`div`,{className:`msg-text${i?` single`:``}`,children:i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`msg-text-main`,children:a}),o]}):(0,$.jsxs)($.Fragment,{children:[o,a,t.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:x(`truncated`)})]})})}let N=Lp(e);if(N)return(0,$.jsx)(cu,{thinking:N.thinking,streaming:i&&a&&w,wrap:c,forceOpen:f||p});let P=Rp(e);if(P){let e={result:t.get(P.id),liveOutput:n.get(P.id)?.text,streaming:i,status:r.get(P.id)};return(0,$.jsx)(lf,{block:P,view:e,onKillBash:s,wrap:l,showImages:u??!0,forceOpen:f||m,uiContextToolCall:_,uiToolCardFooter:v,onUiAction:y})}let F=zp(e);if(F&&F.dataUrl){let e=F.dataUrl.startsWith(`/`)?d(F.dataUrl):F.dataUrl;return(0,$.jsx)(`div`,{className:`msg-image`,children:(0,$.jsx)(`img`,{src:e,loading:`lazy`,decoding:`async`,alt:`attachment`,className:`msg-image-clickable`,title:x(`toolImageZoom`),onClick:()=>Pf({src:e,alt:`attachment`})})})}let I=Bp(e);return I?(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:Us(I.command)}),I.exitCode!==void 0&&(0,$.jsx)(`span`,{className:`bashblock-exit ${I.exitCode===0?`ok`:`err`}`,children:x(`exitCode`,{code:I.exitCode})}),I.cancelled&&(0,$.jsx)(`span`,{className:`bashblock-exit err`,children:x(`cancelled`)})]}),I.output&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:I.output}),I.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:x(`outputTruncated`)})]}):null}function em(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 tm(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function nm(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 rm(e,t){let n=e.indexOf(t);return n<0?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function im(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)]:rm(e,t)}var am=`echo-`;function om(e){return`${am}${e}`}function sm(e){return typeof e==`string`&&e.startsWith(`echo-`)}function cm(){return{adds:[],removes:[],echoes:[]}}function lm(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function um(e,t){let n=(t??[]).filter(e=>e.mode===`quote`).map(e=>Ps(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="${lm(t)}" />`);continue}if(e.mode===`page`){let t=e.path||``,n=e.name||t;i.push(`<browser-page url="${lm(t)}" title="${lm(n)}"></browser-page>`);continue}if(e.mode===`canvas`){i.push(`<canvas-ref id="${lm(e.path)}" title="${lm(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="${lm(t)}"></conversation-ref>`);continue}if(e.path){let t=e.lines?` lines="${e.lines.start}-${e.lines.end}"`:``;i.push(`<file path="${lm(e.path)}"${t} />`)}}return Rs(e,i,n,r)}function dm(e){let t=zs(e);return`${t.text.trim()}\u0000${t.quotes.map(e=>`${e.role}:${e.messageId}:${e.text.trim()}`).join(`|`)}`}function fm(e,t){return e===t||dm(e)===dm(t)}function pm(e,t){let n=0;for(let r of e)fm(r,t)&&(n+=1);return n}function mm(e,t){let n=t.trim(),r=0;for(let t of e)t.role===`user`&&(sm(t.id)||(t.content.find(e=>e.type===`text`)?.text??``).trim()===n&&(r+=1));return r}function hm(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 gm(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 _m(e,t,n){let r=n.now??Date.now();if(!t||!gm({state:t,text:n.text,attachments:n.attachments}))return{tracker:e,state:t};let i=(n.text??``).trim(),a=ym(e),o={conversationId:t.conversationId,rawText:i,messageId:bm(a),baselineUserMsgMatches:mm(t.messages,i),createdAt:r},s=xm(o,r);return{tracker:{...e,echoes:[...vm(e),o]},state:{...t,messages:[...t.messages,s]}}}function vm(e){return e.echoes??[]}function ym(e){let t=0;for(let n of vm(e)){let e=Number.parseInt(n.messageId.slice(5),10);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function bm(e){return om(e)}function xm(e,t){let n=[];return e.rawText&&n.push({type:`text`,text:e.rawText}),{id:e.messageId,role:`user`,content:n,timestamp:t}}function Sm(e,t,n){let r=n.now??Date.now();if(!hm({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=um(n.text,n.attachments),s=zs(o).text.trim(),c=a===`steer`?t.queue.steering:t.queue.followUp,l=e.adds.filter(e=>e.conversationId===t.conversationId&&e.kind===a&&fm(e.formattedText,o)).length,u=pm(c,o),d=Math.max(0,u-l),f=mm(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:vm(e)},state:{...t,queue:m}}}function Cm(e,t,n){if(!t)return{tracker:e,state:t};let r=n.now??Date.now(),{kind:i,text:a,index:o}=n,s=im(i===`steer`?t.queue.steering:t.queue.followUp,a,o),c=e.adds,l=c.findIndex(e=>e.conversationId===t.conversationId&&e.kind===i&&fm(e.formattedText,a));l>=0&&(c=[...c.slice(0,l),...c.slice(l+1)]);let u=pm(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:vm(e)},state:{...t,queue:f}}}function wm(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(pm(e,t.text)>t.expectedRemainingMatches){let n=im(e,t.text,t.index);if(n.length===e.length){let r=e.findIndex(e=>fm(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}:${dm(s.formattedText)}`,d=l.get(u)??0,f=pm(e,s.formattedText),p=mm(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 Tm(e,t){if(!t)return{tracker:e,state:t};let n=t.conversationId,r=e.adds.filter(e=>e.conversationId===n),i=vm(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=im(a,e.formattedText):o=im(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:vm(e).filter(e=>e.conversationId!==n)},state:{...t,queue:{steering:a,followUp:o},messages:c}}}function Em(e,t,n=Date.now()){if(vm(e).length===0)return{tracker:e,state:t};if(t.isStreaming){let r=new Set,i=[];for(let a of vm(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===vm(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 vm(e)){if(n-s.createdAt>=15e3){s.conversationId===r&&a.add(s.messageId);continue}if(s.conversationId!==r){i.push(s);continue}if(mm(t.messages,s.rawText)>s.baselineUserMsgMatches){a.add(s.messageId);continue}i.push(s),t.messages.some(e=>e.id===s.messageId)||o.push(xm(s,s.createdAt))}let s=i.length===vm(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 Dm(e){let{current:t,source:n,snapshot:r,answered:i,activeConversationId:a,pendingDelivery:o}=e,s=!!(r?.conversationId&&a&&r.conversationId!==a);return r&&r.id&&!i.has(r.id)&&!o?.(r.id)&&!s?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`&&!s?{changed:!0,question:null,source:`live`}:{changed:!1,question:t,source:n}}function Om(e,t){return t?`${t}\u0000${e}`:e}var km=new Map;function Am(e){let t=Om(e.id,e.owner);if(km.delete(t),km.set(t,e),km.size>64){let e=km.keys().next().value;e!==void 0&&km.delete(e)}return X(e)}function jm(e,t){km.delete(Om(e,t))}function Mm(e,t){return km.has(Om(e,t))}function Nm(){let e=Array.from(km.values());for(let t of e)if(!X(t))return}function Pm(){km.clear()}var Fm=new Set,Im=1048576,Lm=null,Rm=[],zm=0;function Bm(e=null){Lm=e,Rm=[],zm=0}function Vm(e){if(Fm.add(e),Lm!==null&&Rm.length){let t=Lm,n=Rm;Rm=[],zm=0;for(let r of n)e(t,r)}return()=>{Fm.delete(e)}}function Hm(e,t){if(e===Lm){if(!Fm.size){zm+t.length>Im&&(Rm=[],zm=0),t.length<=Im&&(Rm.push(t),zm+=t.length);return}for(let n of Fm)try{n(e,t)}catch(e){console.error(`[tui-overlay-bridge] listener error:`,e)}}}function Um(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 Wm={},Gm=new Set;function Km(){for(let e of Gm)e()}function qm(e){let t=(e??``).trim();t&&(Wm[t]&&Wm[t].status!==`loading`||(Wm={...Wm,[t]:{name:t,status:`loading`}},Km(),X({type:`get_tool_prompt`,name:t})))}function Jm(e){let t=typeof e.name==`string`?e.name:``;t&&Wm[t]&&(Wm={...Wm,[t]:Um(e)},Km())}function Ym(e){if(!Wm[e])return;let t={...Wm};delete t[e],Wm=t,Km()}function Xm(e){return Gm.add(e),()=>Gm.delete(e)}function Zm(e){return(0,Q.useSyncExternalStore)(Xm,()=>e?Wm[e]??null:null)}function Qm(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=`
54
- :host {
55
- display: block;
56
- width: 100%;
57
- height: 100%;
58
- box-sizing: border-box;
59
- color: var(--text, inherit);
60
- font-family: inherit;
61
- font-size: var(--text-base, 13.5px);
62
- line-height: 1.5;
63
- }
64
- *, *::before, *::after {
65
- box-sizing: inherit;
66
- }
67
- `,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 $m=`pi-web-ui:plugin-data`;function eh(e,t){window.dispatchEvent(new CustomEvent($m,{detail:{pluginId:e,payload:t}}))}function th(e){let t=t=>{let n=t.detail;e(n.pluginId,n.payload)};return window.addEventListener($m,t),()=>window.removeEventListener($m,t)}var nh=new Map,rh=new Set,ih=new Set,ah=new Set,oh=new Set,sh=-1;function ch(){return[...nh.values()]}function lh(){let e=ch();for(let t of ih)t(e)}function uh(){let e=[...ah];for(let t of oh)t(e)}function dh(e){return oh.add(e),e([...ah]),()=>oh.delete(e)}async function fh(e,t){ah.delete(e.id),mh.set(e.id,(mh.get(e.id)??0)+1),uh();let n=await yh(e,t);return lh(),n}function ph(e){return ih.add(e),e(ch()),()=>ih.delete(e)}var mh=new Map;function hh(e,t){let n=mh.get(e)??0;return d(`/plugins/${encodeURIComponent(e)}/client/entry.mjs?e=${t}${n>0?`&r=${n}`:``}`)}function gh(e){let t=Promise.resolve();return(n,r)=>{let i=t.then(()=>qt(n,()=>e(r)));return t=i.then(()=>void 0,()=>void 0),i}}var _h=gh(e=>Qs(()=>import(e),[],import.meta.url));async function vh(e,t){if(!e.hasClient||e.error)return null;try{let n=await _h(e.id,hh(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 yh(e,t){try{let n=(await _h(e.id,hh(e.id,t))).default;return n&&typeof n.mount==`function`?(nh.set(e.id,{info:e,module:n}),!0):e.preload?(rh.add(e.id),!0):(ah.add(e.id),uh(),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(t){return ah.add(e.id),uh(),console.error(`[plugin:${e.id}] 客户端加载失败:`,t),!1}}async function bh(e,t){if(nh.has(e.id)||rh.has(e.id))return!0;if(ah.has(e.id)||!e.hasClient)return!1;let n=await yh(e,t);return lh(),n}async function xh(e,t){t!==sh&&(sh=t,nh.clear(),rh.clear(),ah.clear(),mh.clear(),uh());let n=new Set(e.map(e=>e.id));for(let e of[...nh.keys()])n.has(e)||nh.delete(e);for(let e of[...rh])n.has(e)||rh.delete(e);for(let e of[...ah])n.has(e)||ah.delete(e);uh(),await Promise.all(e.filter(e=>e.hasClient&&(e.view!==!1||e.preload)&&!e.error&&!nh.has(e.id)&&!rh.has(e.id)&&!ah.has(e.id)).map(e=>yh(e,t))),lh()}function Sh(e,t){return{pluginId:e,send:n=>t({type:`plugin_message`,pluginId:e,payload:n}),onData:t=>th((n,r)=>{n===e&&t(r)})}}var Ch=[`debug`,`info`,`warn`,`error`];function wh(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`get`}}}function Th(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`clear`}}}function Eh(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`&&Ch.includes(String(e.level)))}var Dh=new Map,Oh=new Set;function kh(){for(let e of[...Oh])try{e()}catch{}}function Ah(e){return Oh.add(e),()=>Oh.delete(e)}function jh(e){return(Dh.get(e)??[]).map(e=>({...e}))}function Mh(e,t){return Eh(t)?(Dh.set(e,t.logs.map(e=>({ts:e.ts,level:e.level,text:e.text}))),kh(),!0):!1}function Nh(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 Ph(e,t){if(Nh(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 Fh(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 Ih(e){switch(e){case`error`:return 6500;case`warning`:return 4200;default:return 2400}}var Lh=[/^(已在工作目录|正在切换到工作目录|已切换到工作目录)[::]/,/^(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 Rh(e){if(e.level!==`info`)return!1;let t=(e.text??``).trim(),n=(e.textEn??``).trim();return Lh.some(e=>t&&e.test(t)||n&&e.test(n))}function zh(e,t,n=2){if(Rh(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 Bh(){return{flows:[],results:{}}}function Vh(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 Hh(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:Vh(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:Vh(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 Uh(){return ne()}var Wh=typeof WebSocket<`u`&&WebSocket.OPEN!==void 0?WebSocket.OPEN:1,Gh=typeof WebSocket<`u`&&WebSocket.CLOSING!==void 0?WebSocket.CLOSING:2,Kh=typeof WebSocket<`u`&&WebSocket.CLOSED!==void 0?WebSocket.CLOSED:3,qh=e=>!!(e&&e.readyState===Wh),Jh=2e5,Yh=`LIVE_OMIT`,Xh={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 Zh(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 Qh(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 $h(e,t,n,r){let i=e.filter(e=>e.id!==t||e.owner!==n);return r&&i.push(r),i}function eg(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:yg(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!==43}}case`snapshot`:{let n=e.state?.cwd,r=e.state?.conversationId,i=t.state.cwd,a=e.sessions;i&&i!==n&&(a=yg(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||a&&(a.includes(e)||e.includes(a))||n&&(n.includes(e)||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=Em(e.optimisticQueue,t.state),l=wm(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:Zh(e.liveOutputs,l.state),toolStatuses:Qh(e.toolStatuses,l.state)}}case`earlier_messages`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId)return e;let i=Ph(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=Em(e.optimisticQueue,i),o=wm(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:Zh(e.liveOutputs,s),toolStatuses:Qh(e.toolStatuses,s)}}case`optimistic_queue_add`:{let n=e.goal.reviewing&&!!(e.state?.conversationId&&e.goal.conversationId===e.state.conversationId),r=Sm(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=Cm(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=_m(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>Jh?`…[${Yh}:${r.length-Jh}]…\n`+r.slice(r.length-Jh):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:nm(n,t.msg)}}case`tool_status`:return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case`notice`:{let n=zh(e.notices,t.notice),r=(t.notice.level===`error`||t.notice.level===`warning`)&&e.optimisticQueue.adds.length>0?Tm(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`:{let n=t.cwd;if(!n||gg(n)===gg(e.state?.cwd))return xg(e.state?.cwd,t.sessions,e.engine),{...e,sessions:t.sessions};xg(n,t.sessions,e.engine);let r=gg(n);return{...e,projectSessions:{...e.projectSessions??{},[r]:t.sessions}}}case`conversations`:return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case`projects`:return mg(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=Hh({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`global_interactions`:return{...e,globalQuestions:t.questions,globalApprovals:t.approvals};case`global_question`:return{...e,globalQuestions:$h(e.globalQuestions,t.id,t.owner,t.question)};case`global_approval`:return{...e,globalApprovals:$h(e.globalApprovals,t.id,t.owner,t.approval)};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`?yg(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 tg=`pi-web-client-id`,ng=`pi-web-client-id:`,rg=`__PI_CID__:`,ig=null;function ag(){try{if(typeof window<`u`&&typeof window.name==`string`&&window.name){let e=window.name;if(e.startsWith(ng)){let t=e.slice(17).trim();if(t)return t}let t=e.indexOf(rg);if(t!==-1){let n=e.slice(t+11).trim();if(n)return n}}}catch{}try{if(typeof sessionStorage<`u`){let e=sessionStorage.getItem(tg);if(e)return e}}catch{}return null}function og(e){try{if(typeof window<`u`){let t=typeof window.name==`string`?window.name:``;if(!t||t.startsWith(ng))window.name=`${ng}${e}`;else{let n=t.indexOf(rg),r=n===-1?t:t.slice(0,n);window.name=`${r}${rg}${e}`}}}catch{}try{typeof sessionStorage<`u`&&sessionStorage.setItem(tg,e)}catch{}}function sg(){if(ig)return ig;let e=ag();return e||=Tt(),og(e),ig=e,e}var cg=`pi-web-last-cwd`;function lg(){try{return localStorage.getItem(cg)}catch{return null}}function ug(e){try{localStorage.setItem(cg,e)}catch{}}function dg(e){try{let t=localStorage.getItem(cg);if(!t)return;let n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase();(t===e||n(t)===n(e))&&localStorage.removeItem(cg)}catch{}}var fg=`pi-web-recent-projects`;function pg(){try{let e=localStorage.getItem(fg);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function mg(e){try{localStorage.setItem(fg,JSON.stringify(e.slice(0,20)))}catch{}}function hg(e){try{let t=pg(),n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),r=n(e);mg(t.filter(e=>n(e.path)!==r))}catch{}}var gg=e=>e?e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase():``,_g=`pi-web-recent-sessions:`;function vg(e,t){let n=t??`pi`;return e?`${_g}${n}:${gg(e)}`:`pi-web-recent-sessions:${n}:default`}function yg(e,t){try{let n=e??lg(),r=vg(n,t),i=localStorage.getItem(r);if(i){let e=JSON.parse(i);if(Array.isArray(e)&&e.length>0)return e}if(n){for(let e of[`pi`,`default`]){if(e===(t??`pi`))continue;let r=vg(n,e),i=localStorage.getItem(r);if(i){let e=JSON.parse(i);if(Array.isArray(e)&&e.length>0)return e}}let e=`:${gg(n)}`;for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(_g)&&n.endsWith(e)){let e=localStorage.getItem(n);if(e){let t=JSON.parse(e);if(Array.isArray(t)&&t.length>0)return t}}}}return[]}catch{return[]}}function bg(e,t){if(!e||!t||e.startsWith(`conv:`)||e.startsWith(`virtual:`))return!0;let n=e.toLowerCase().replace(/\\/g,`/`),r=t.toLowerCase().replace(/\\/g,`/`).replace(/\/+$/,``);if(!n.includes(`/`)||n.startsWith(r+`/`))return!0;let i=r.replace(/[^a-zA-Z0-9]/g,`-`).toLowerCase();if(n.includes(`--${i}--`))return!0;let a=r.split(`/`).filter(Boolean).pop();return!!(a&&RegExp(`[-_/]${a.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}[-_/]`,`i`).test(n))}function xg(e,t,n){try{let r=e??lg(),i=r?t.filter(e=>bg(e.path,r)):t,a=vg(r,n);localStorage.setItem(a,JSON.stringify(i.slice(0,50)))}catch{}}function Sg(e,t,n){try{let r=yg(t,n),i=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),a=i(e);xg(t,r.filter(e=>i(e.path)!==a),n)}catch{}}function Cg(){let e=location.protocol===`https:`?`wss:`:`ws:`;return z(`${e}//${location.host}${d(`/ws`)}`)}function wg(){let[e,t]=(0,Q.useReducer)(eg,{status:`connecting`,ready:!1,state:null,hostMetrics:null,latencyMs:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:yg(),conversations:[],elsewhere:[],activeConversationId:``,projects:pg(),files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},defaultModel:null,providerOAuthFlows:[],providerOAuthResults:Bh().results,installResult:null,pathCompletions:[],update:null,updatesAll:null,updatesSdk:null,widgets:[],statuses:[],dialog:null,tuiOverlay:null,approval:null,approvals:[],globalQuestions:[],globalApprovals:[],question:null,questionQueue:null,remoteQuestion:null,commands:[],commandsPath:``,slashCommands:[],terminals:[],terminalActiveId:null,goal:Xh,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:cm()}),n=(0,Q.useRef)(null),r=(0,Q.useRef)(Ns()),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=(0,Q.useRef)(null),g=()=>{u.current||=setTimeout(()=>{u.current=null;let e=n.current;qh(e)&&e.send(JSON.stringify({type:`get_state`}))},300)},_=(e,t)=>{let n=l.current,r=n.get(e);if(r!==void 0&&t!==r+1){let t=O.current.chat;e===(t.activeConversationId||t.state?.conversationId)&&g()}n.set(e,t)},v=(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=e.state;if(n&&e.ready){let r=(e.transition.target??``).trim().replace(/\\/g,`/`).toLowerCase(),i=(n.sessionId??``).trim().replace(/\\/g,`/`).toLowerCase(),a=(n.sessionFile??``).trim().replace(/\\/g,`/`).toLowerCase(),o=(n.conversationId??``).trim().replace(/\\/g,`/`).toLowerCase();if(r&&(i===r||a===r||o===r||i&&(i.includes(r)||r.includes(i))||a&&(a.includes(r)||r.includes(a)))){t({type:`transition_clear`});return}}let r=setInterval(()=>{if(Date.now()-(e.transition?.startedAt??0)>2e4){t({type:`transition_clear`});return}t({type:`transition_tick`})},160);return()=>clearInterval(r)},[e.transition,e.state,e.ready]);let y=(0,Q.useCallback)(e=>{let r=n.current;if(!qh(r))return!1;let i=O.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===`new_chat`||e.type===`switch_session`&&(e.path||e.sessionId)||(e.type===`switch_conversation`||e.type===`open_shared_conversation`||e.type===`take_over_conversation`)&&e.id)&&sn(),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)){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),c=s===r||s===i||s===o||i&&(i.includes(s)||s.includes(i))||r&&(r.includes(s)||s.includes(r));s&&!c&&t({type:`transition_start`,kind:`session`,target:e.path||e.sessionId||``,progress:14,text:`正在流式载入历史会话…`,textEn:`Streaming session history…`})}else e.type===`new_chat`?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&&a&&e.id!==a.conversationId&&t({type:`transition_start`,kind:`conversation`,target:e.id,progress:35,text:`正在切换对话…`,textEn:`Switching conversation…`});if(qh(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`&&e.global)t({type:`global_question`,id:e.id,owner:e.owner});else if(e.type===`question_answer`){if(t({type:`question_queue_answered`,id:e.id,owner:e.owner}),e.owner){O.current.chat.question?.id===e.id&&O.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=O.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},[]),b=(0,Q.useCallback)((e,n)=>{let r=Dm({current:O.current.chat.question,source:m.current,snapshot:e,answered:p.current,activeConversationId:n,pendingDelivery:Mm});r.changed&&(m.current=r.source,t({type:`question`,question:r.question}))},[]);Qe(y);let x=(0,Q.useCallback)(()=>{if(!o.current)return;t({type:`status`,status:`connecting`});let e=new WebSocket(Cg());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:sg(),locale:Uh()})))};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=O.current.chat.activeConversationId||O.current.chat.state?.conversationId;if(e&&a.conversationId!==e)return}switch(a.type){case`ready`:{if((O.current.chat.settings?.autoReload??!0)&&a.buildId&&a.buildId!==`20261104T17521`){let e=`pi-web-ui-reloaded-${a.buildId}`;if(!sessionStorage.getItem(e)){sessionStorage.setItem(e,`1`),location.reload();return}}let n=O.current.chat.engine;n&&a.engine&&n!==a.engine&&r.current.clear(),We({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}),a.runId!==void 0&&a.runId!==h.current||a.runId===void 0?(h.current=a.runId??null,p.current.clear(),Pm(),t({type:`question`,question:null})):(t({type:`question`,question:null}),Nm()),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}),b(a.state.pendingQuestion,a.state.conversationId);break;case`snapshot_delta`:{let e=O.current.chat.state;if(e)(e.conversationId!==a.conversationId||e.rev!==a.baseRev)&&g();else{let e=n.current;qh(e)&&e.send(JSON.stringify({type:`get_state`}))}let r=O.current.chat.activeConversationId||e?.conversationId;if(r&&a.conversationId!==r)break;t({type:`snapshot_delta`,msg:a}),b(a.state.pendingQuestion,r||a.conversationId);break}case`earlier_messages`:{let e=O.current.chat.state;if(e?.conversationId!==a.conversationId)break;if(Nh(e,a)){g();break}t({type:`earlier_messages`,msg:a});break}case`tool_delta`:_(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`:_(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`:We({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(ks,{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`:hu(a);break;case`tool_prompt`:Jm(a);break;case`compacted_messages_result`:Sf(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`:Bm(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`:Hm(a.id,a.ansi);break;case`tui_overlay_close`:Bm(),t({type:`tui_overlay`,overlay:null});break;case`global_interactions`:t(a);break;case`question_pending`:if(a.global){t({type:`global_question`,id:a.id,owner:a.owner,question:a});break}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`:if(a.global){t({type:`global_approval`,id:a.id,owner:a.owner,approval:a});break}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`:if(a.global){t({type:`global_approval`,id:a.id,owner:a.owner});break}t({type:`tool_approval`,approval:null,resolvedId:a.id});break;case`question_retracted`:{if(jm(a.id,a.owner),a.global){t({type:`global_question`,id:a.id,owner:a.owner});break}O.current.chat.remoteQuestion?.id===a.id&&t({type:`remote_question`,question:null});let e=O.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)}}y({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??O.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&&Pp(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===sg()&&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`:Ut(a);break;case`plugin_catalog_sync_result`:$t(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`:Mh(a.pluginId,a.payload)||eh(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`:vn(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,x()},s)},e.onerror=()=>{}},[]);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail??Uh();t&&y({type:`set_locale`,locale:t})};return window.addEventListener(pt,e),()=>window.removeEventListener(pt,e)},[y]),(0,Q.useEffect)(()=>{let n=n=>{let r=e.state?.cwd;r&&n.key&&n.key===vg(r,e.engine)&&t({type:`sync_cached_sessions`,sessions:yg(r,e.engine)})};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)},[e.state?.cwd,e.engine]),(0,Q.useEffect)(()=>{o.current=!0,x();let e=setInterval(()=>{if(!o.current)return;let e=n.current;qh(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===Kh||e.readyState===Gh){a.current&&=(clearTimeout(a.current),null),x();return}qh(e)&&(Date.now()-s.current>15e3||!O.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()}},[x]),(0,Q.useEffect)(()=>{let t=e.state?.cwd;if(t){if(!d.current){d.current=!0;let e=lg();if(e&&e!==t){y({type:`set_cwd`,path:e});return}}f.current!==t&&(f.current=t,ug(t))}},[e.state?.cwd,y]),(0,Q.useEffect)(()=>{We({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 S=(0,Q.useCallback)(e=>t({type:`dismiss_notice`,id:e}),[]),C=(0,Q.useCallback)(e=>{let n=O.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?y({type:`run_command`,...i,command:e.command}):y({type:`terminal_create`,...i,title:e.title,cwd:e.cwd,agentBash:e.agentBash,locale:Uh()}))&&t({type:`terminal_add`,meta:{...e,ownerKind:r}})},[y]),w=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_remove`,id:e,ownerKind:n,conversationId:r}),[]),T=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_restart`,terminalId:e,ownerKind:n,conversationId:r}),[]),E=(0,Q.useCallback)(e=>t({type:`terminal_active`,id:e}),[]),D=(0,Q.useCallback)((e,t,n,i=`client`)=>r.current.register(e,t,n,i),[]),O=(0,Q.useRef)({chat:e,send:y,pushNotice:v,dismissNotice:S,terminal:{create:C,close:w,register:D,restart:T,select:E}});return O.current={chat:e,send:y,pushNotice:v,dismissNotice:S,terminal:{create:C,close:w,register:D,restart:T,select:E}},O.current}function Tg(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 Eg(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 Dg=`pi-web-ui:lp-collapse-projects`,Og=`pi-web-ui:lp-collapse-convs`,kg=`pi-web-ui:lp-collapse-sessions`,Ag=`pi-web-ui:lp-collapse-subagents`;function jg(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Ag);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(Ag,JSON.stringify([...n]))}catch{}return n})},[])]}function Mg(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 Ng=`pi-web-ui:lp-collapse-plugin-sections`;function Pg(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Ng),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(Ng,JSON.stringify([...n]))}catch{}return n})},[])]}var Fg=`pi-web-ui:lp-sizes`,Ig={projects:1,groups:1,convs:1,sessions:1},Lg=32,Rg={running:`pluginRunStatusRunning`,done:`pluginRunStatusDone`,error:`pluginRunStatusError`},zg=72;function Bg(){try{return pi(localStorage.getItem(Fg),Ig)}catch{return{...Ig}}}var Vg=typeof process<`u`&&(!!{}.VITEST||!1),Hg=`pi.leftpanel.conv_tab`;function Ug(){try{let e=localStorage.getItem(Hg);if(e===`running`||e===`stream`||e===`split`)return e}catch{}return Vg?`split`:`stream`}var Wg=`pi.leftpanel.workspace_tab`;function Gg(){try{let e=localStorage.getItem(Wg);if(e===`projects`||e===`groups`||e===`split`)return e}catch{}return Vg?`split`:`projects`}var Kg=(0,Q.memo)(function({sessionFile:e,conversations:t,elsewhere:n,sessions:i,projects:a,activeConversationId:o,sharedConversationOwner:s,activeGroupId:c,projectSessions:l,engine:u,unreadConvKeys:d,panelSend:p,active:m,collapsible:h,onToggleCollapse:g,pathCompletions:_,uiContextSession:v,uiLeftSessions:y,uiContextProject:b,uiProjectsActions:x,uiLeftProject:C,uiRunningActions:w,uiHistoryActions:T,uiSections:E,renderPluginSectionBody:D,uiPluginRunning:O,onPluginRunningAction:k,uiLeftRunning:M,uiLeftHistory:N,onUiAction:P,presetNames:I,transition:L,onOpenSandboxModal:ee}){let R=W(),ne=qe(),re=_s(),z=d??re,B=(0,Q.useCallback)(e=>!z||z.size===0?!1:!!(e.id&&(z.has(e.id)||z.has(e.id.trim().toLowerCase()))||e.sessionId&&(z.has(e.sessionId)||z.has(e.sessionId.trim().toLowerCase()))||e.sessionFile&&(z.has(e.sessionFile)||z.has(e.sessionFile.trim().toLowerCase()))||e.path&&(z.has(e.path)||z.has(e.path.trim().toLowerCase()))),[z]),ie=e,ae=Me(`ready`),V=Me(`status`),oe=Me(`cwd`),se=Me(`workspaceRoots`),ce=oe,[le,ue]=(0,Q.useState)(!1),[de,pe]=(0,Q.useState)(null),[me,H]=(0,Q.useState)(null),[he,ge]=(0,Q.useState)(null),[U,_e]=(0,Q.useState)(``),[ve,G]=Mg(Dg,!1),[q,ye]=Mg(Og,!1),[xe,Se]=Mg(kg,!1),[J,Ce]=Pg(),[we,Te]=(0,Q.useState)(!1),[Ee,De]=jg(),[Oe,ke]=(0,Q.useState)(()=>Ug());(0,Q.useEffect)(()=>{try{localStorage.setItem(Hg,Oe)}catch{}},[Oe]);let[Ae,je]=(0,Q.useState)(()=>Gg());(0,Q.useEffect)(()=>{try{localStorage.setItem(Wg,Ae)}catch{}},[Ae]);let[Y,Ne]=(0,Q.useState)(!1),Pe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!Y)return;let e=e=>{Pe.current&&!Pe.current.contains(e.target)&&Ne(!1)};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[Y]);let[Fe,Ie]=(0,Q.useState)(0),[Le,Re]=(0,Q.useState)(60);(0,Q.useEffect)(()=>{Re(60)},[ce]);let ze=(0,Q.useMemo)(()=>{let e=new Set,r=[];for(let t of a){let n=gg(t.path);e.has(n)||(e.add(n),r.push(t))}for(let n of t){if(!n.cwd)continue;let t=gg(n.cwd);e.has(t)||(e.add(t),r.push({path:n.cwd,lastUsed:Date.now()}))}for(let t of n){if(!t.cwd)continue;let n=gg(t.cwd);e.has(n)||(e.add(n),r.push({path:t.cwd,lastUsed:Date.now()}))}return r},[a,t,n]),Be=(0,Q.useRef)(new Map),Ve=(0,Q.useMemo)(()=>{let e=Be.current;return ze.forEach((t,n)=>{let r=gg(t.path);e.has(r)||e.set(r,n)}),[...ze].sort((t,n)=>{let r=gg(t.path),i=gg(n.path);return(e.get(r)??0)-(e.get(i)??0)})},[ze]),[He,Ue]=(0,Q.useState)(()=>new Set),[We,Ke]=(0,Q.useState)(()=>new Set),[Ye,Xe]=(0,Q.useState)({}),[Ze,Qe]=(0,Q.useState)(()=>new Set),$e=(0,Q.useCallback)(e=>{let t=gg(e);return t===gg(ce)?!We.has(t):He.has(t)},[ce,We,He]),et=(0,Q.useCallback)(e=>{let t=gg(e);t===gg(ce)?Ke(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}):Ue(n=>{let r=new Set(n);return r.has(t)?r.delete(t):(r.add(t),p({type:`list_sessions`,path:e}),Qe(e=>new Set(e).add(t))),r})},[ce,p]),tt=(0,Q.useMemo)(()=>{if(Oe!==`split`||q||t.length===0)return new Set;let e=new Set;for(let n of t)n.sessionFile&&e.add(gg(n.sessionFile));return e},[Oe,q,t]),nt=(0,Q.useMemo)(()=>tt.size===0?i:i.filter(e=>!tt.has(gg(e.path))),[i,tt]);(0,Q.useMemo)(()=>{if(nt.length<=Le)return nt;let e=gg(ie),t=e?nt.findIndex(t=>gg(t.path)===e):-1,n=t>=Le?t+10:Le;return nt.slice(0,n)},[nt,Le,ie]);let X=(0,Q.useCallback)((e,t)=>{if(!t)return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==o).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!==o;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!==o&&r(e)).length},[o]),rt=(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},[]),it=(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},[]),at=(0,Q.useRef)(null),ot=(0,Q.useRef)(null),st=(0,Q.useRef)(()=>{}),ct=pa(v??[]).length>0,lt=(0,Q.useCallback)((e,r,a)=>{at.current={x:e,y:r,target:a};let o=a.kind===`running`?a.id:void 0,s=a.kind===`elsewhere`,c=o??(s&&a.id||void 0),l=o??(s?c:void 0),u=X(t,o),d=u===0?R(`noFinishedSubagents`):R(o?`dismissFinishedSubagentsScoped`:`dismissFinishedSubagents`,{n:u}),f=!!l&&ot.current===l;na({x:e,y:r,slot:`contextmenu.session`,target:a,entries:(v??[]).map(e=>{if(e.source!==`host`)return e;if(e.id===`host:conv-rename`)return a.kind===`running`||a.kind===`history`?e:{...e,hidden:!0};if(e.id===`host:conv-takeover`){let t=!!(a.pseudo&&a.owner?.startsWith(`scheduler:`)),r=n.some(e=>e.owner===a.owner&&e.convId===c&&e.independent===!1);return s&&c&&a.owner&&!t&&!r?e:{...e,hidden:!0}}if(s&&e.id===`host:conv-dismiss-subagents`)return{...e,hidden:!0};if(e.id===`host:conv-dismiss-subagents`)return{...e,label:d,...u===0?{when:[...e.when??[],`disabled`]}:{}};if(e.id===`host:conv-force-dismiss`)return l?{...e,...f?{label:R(`forceDismissConfirm`)}:{}}:{...e,hidden:!0};if(e.id===`host:conv-pin`){if(a.kind===`history`)return i.find(e=>e.path===a.id)?.pinned?{...e,label:R(`unpinConversation`)}:e;if(!o)return{...e,hidden:!0};let n=t.find(e=>e.id===o);return!n||n.isSubagent?{...e,hidden:!0}:n.pinned?{...e,label:R(`unpinConversation`)}:e}if(e.id===`host:conv-persist`){if(!o)return{...e,hidden:!0};let n=t.find(e=>e.id===o);return!n||!n.isSubagent&&n.sessionFile?{...e,hidden:!0}:n?.isEphemeral?{...e,label:R(`saveEphemeral`)}:e}if(e.id===`host:conv-copy-id`)return c?e:{...e,hidden:!0};if(e.id===`host:conv-copy-path`)return a.kind===`history`?e:o?t.some(e=>e.id===o&&e.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}:{...e,hidden:!0};if(e.id===`host:conv-copy-link`){if(a.kind===`history`)return i.find(e=>e.path===a.id)?.sessionId||Ts(a.id)?e:{...e,hidden:!0};if(!o)return{...e,hidden:!0};let n=t.find(e=>e.id===o);return n?.sessionId||Ts(n?.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}}return e.id===`host:conv-quote`?ne.conversationRef&&(c||a.kind===`history`)?e:{...e,hidden:!0}:e}),onHostAction:(e,t)=>st.current(e,t)})},[v,t,n,X,R,ne.conversationRef]);st.current=(0,Q.useCallback)((e,n)=>{let r=n.kind===`running`?n.id:void 0,a=r??(n.kind===`elsewhere`&&n.id||void 0);if(e.id===`host:conv-takeover`){n.kind===`elsewhere`&&a&&n.owner&&p({type:`take_over_conversation`,owner:n.owner,id:a});return}if(e.id===`host:conv-dismiss-subagents`){p(r?{type:`dismiss_finished_subagents`,parentId:r}:{type:`dismiss_finished_subagents`});return}if(e.id===`host:conv-force-dismiss`){let e=at.current,t=r??(n.kind===`elsewhere`?a:void 0);if(!t||!e)return;if(ot.current!==t)return ot.current=t,lt(e.x,e.y,e.target),!0;ot.current=null,p({type:`dismiss_conversation`,id:t,force:!0,...n.kind===`elsewhere`&&n.owner?{owner:n.owner}:{}});return}if(e.id===`host:conv-persist`){r&&p({type:`persist_conversation`,id:r});return}if(e.id===`host:conv-pin`){if(n.kind===`history`){let e=i.find(e=>e.path===n.id);p({type:`pin_session`,path:n.id,pinned:!e?.pinned});return}r&&p({type:`pin_conversation`,id:r,pinned:!t.find(e=>e.id===r)?.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:r&&t.find(e=>e.id===r)?.sessionFile||void 0;e&&navigator.clipboard?.writeText(e).catch(()=>{});return}if(e.id===`host:conv-copy-link`){let e=n.kind===`history`?i.find(e=>e.path===n.id)?.sessionId||Ts(n.id):r?t.find(e=>e.id===r)?.sessionId||Ts(t.find(e=>e.id===r)?.sessionFile):null;if(e){let t=ws(window.location.href,{sessionId:e});navigator.clipboard?.writeText(t).catch(()=>{})}return}if(e.id===`host:conv-quote`){n.kind===`history`&&n.id?Gt({attachments:[{path:``,key:`conv||${n.id}`,name:n.label||n.id,mode:`conversation`,sessionPath:n.id}]}):a&&Gt({attachments:[{path:``,key:`conv|${a}|`,name:n.label||a,mode:`conversation`,conversationId:a}]});return}if(e.id===`host:conv-rename`){if(pe(null),r){let e=t.find(e=>e.id===r);_e(e?.title??n.label??``),ge(`conv:${r}`)}else if(n.kind===`history`&&n.id){let e=i.find(e=>e.path===n.id);_e(e?.name??n.label??``),ge(n.id)}return}},[p,lt,t,i]);let ut=(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(),P?.(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?P?.(e,void 0,n):P?.(e)},children:e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):(0,$.jsx)(`span`,{children:i})},r)})}),dt=(0,Q.useCallback)((e,t)=>{Eg(e.target)||ct&&(e.preventDefault(),e.stopPropagation(),ot.current=null,lt(e.clientX,e.clientY,t))},[ct,lt]),ft=(0,Q.useRef)(null),[pt,mt]=(0,Q.useState)(()=>Bg());(0,Q.useEffect)(()=>{try{localStorage.setItem(Fg,JSON.stringify(pt))}catch{}},[pt]);let ht=(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.convId&&t.independent!==!1&&(t.sessionFile&&e.has(t.sessionFile)||r.has(`${t.cwd}\0${t.title}`)))continue;let n=t.convId?`conv:${t.owner}:${t.convId}`:t.sessionFile?`file:${t.sessionFile}`:`title:${t.cwd}\0${t.title}`;a.has(n)||(a.add(n),i.push({id:t.convId&&t.owner?`elsewhere:${t.owner}:${t.convId}`:t.sessionFile?`elsewhere:${t.owner}:${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,independent:t.independent,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]),gt=(0,Q.useMemo)(()=>{let e=new Map,t=new Map;for(let t of ht)e.set(t.id,t);for(let n of ht)if(n.parentId&&e.has(n.parentId)){let e=t.get(n.parentId)??[];e.push(n),t.set(n.parentId,e)}let n=e=>{let n=[],r=[...t.get(e)??[]],i=new Set;for(;r.length>0;){let e=r.shift();if(i.has(e.id))continue;i.add(e.id),n.push(e);let a=t.get(e.id);a&&r.push(...a)}return n},r=new Map;for(let e of ht){let t=n(e.id),i=t.some(e=>e.isStreaming||e.completionPending),a=t.some(e=>!!e.hasQuestion),o=t.some(e=>!!e.error),s={conv:e,isStreaming:!!(e.isStreaming||e.completionPending||i),hasQuestion:!!(e.hasQuestion||a),hasError:!!(e.error||o),error:e.error};if(e.sessionFile){let t=gg(e.sessionFile);r.set(`file:${t}`,s);let n=t.split(`/`).pop();n&&r.set(`fn:${n}`,s);let i=Ts(e.sessionFile);i&&r.set(`sid:${i.toLowerCase()}`,s)}e.sessionId&&r.set(`sid:${e.sessionId.trim().toLowerCase()}`,s),r.set(`conv:${e.id}`,s)}return r},[ht]),_t=(0,Q.useCallback)(e=>{if(e.path.startsWith(`conv:`)&&gt.has(e.path))return gt.get(e.path);let t=gg(e.path);if(gt.has(`file:${t}`))return gt.get(`file:${t}`);if(e.sessionId&&gt.has(`sid:${e.sessionId.trim().toLowerCase()}`))return gt.get(`sid:${e.sessionId.trim().toLowerCase()}`);let n=t.split(`/`).pop();if(n&&gt.has(`fn:${n}`))return gt.get(`fn:${n}`);let r=Ts(e.path);if(r&&gt.has(`sid:${r.toLowerCase()}`))return gt.get(`sid:${r.toLowerCase()}`)},[gt]),yt=di(ui(E)).filter(e=>e.shown),bt=(0,Q.useMemo)(()=>yt.filter(e=>!(e.key===`convs`||e.key===`sessions`||Ae!==`split`&&yt.some(e=>e.key===`projects`)&&e.key===`groups`)),[yt,Ae]),xt=(0,Q.useCallback)(e=>e===`projects`?ve||Ae===`projects`&&a.length===0:e===`convs`?q:e===`sessions`?xe:e===`groups`?we:J.has(e),[ve,Ae,a.length,q,xe,we,J]),St=(O??[]).reduce((e,t)=>e+t.items.length,0),Ct=ht.length+St;(0,Q.useEffect)(()=>{Ct===0&&Oe===`running`&&ke(`stream`)},[Ct,Oe]);let wt=(0,Q.useMemo)(()=>bt.filter(e=>e.key===`projects`?Ae===`split`?a.length>0:a.length>0||Fe>0:e.key!==`convs`&&e.key!==`sessions`).map(e=>e.key),[bt,Ae,a.length,Fe]),Tt=()=>{let e=O??[];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:[R(`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:()=>k?.(e,t),children:[(0,$.jsx)(`span`,{className:`lp-plugin-dot st-${t.status}`,title:R(Rg[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}`))},Et=(0,Q.useMemo)(()=>[...y??[],...M??[]],[y,M]),Dt=(0,Q.useMemo)(()=>[...y??[],...N??[]],[y,N]),Ot=(0,Q.useCallback)((e,t)=>n=>{n.preventDefault();let r=n.currentTarget,i=n.clientY,a={...pt},o=ft.current;if(!o)return;let s=wt.filter(e=>xt(e)).length,c=wt.filter(e=>!xt(e)).reduce((e,t)=>e+(a[t]??1),0)||1,l=Math.max(120,o.clientHeight-s*Lg);r.classList.add(`dragging`),document.body.classList.add(`lp-resizing`);let u=n=>{let{above:r,below:o}=ys({start:{above:a[e]??1,below:a[t]??1},deltaPx:n.clientY-i,availablePx:l,totalWeight:c,minAbovePx:zg,minBelowPx:zg});mt(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)},[pt,wt,xt]);(0,Q.useEffect)(()=>{m&&ae&&V===`open`&&oe&&(p({type:`list_sessions`}),p({type:`list_projects`}))},[m,ae,V,oe,p]);let kt=e=>{let t=e.displayName||e.name||e.firstMessage?.trim();return t&&t.length>0?t:R(`emptyChat`)},At=e=>e.split(/[\\/]/).pop()||e,jt=pa(b??[]).length>0,Mt=(0,Q.useCallback)((e,t)=>{Eg(e.target)||jt&&(e.preventDefault(),e.stopPropagation(),na({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.path,kind:`project`,label:At(t.path)},entries:b??[]}))},[jt,b]),Nt=(e,t,n,i,a)=>{let o=de===e;return(0,$.jsx)(`button`,{type:`button`,className:`lp-del ${o?`confirm`:``}`,title:o?n:t,onClick:t=>{t.stopPropagation(),o?(pe(null),i()):pe(e)},children:o?(0,$.jsx)(r,{}):a??(0,$.jsx)(Ge,{})})},Pt=(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:R(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)(A,{}):(0,$.jsx)(S,{})})]}),i||a?(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[i,a]}):null]}),Ft=wt.filter(e=>!xt(e)),It=Ft.reduce((e,t)=>e+(pt[t]??1),0)||1,Lt=e=>Ft.length<=1?1:(pt[e]??1)/It*Ft.length,Rt=new Map(fi(wt,xt).map(([e,t])=>[e,(0,$.jsx)(`div`,{className:`lp-sash`,role:`separator`,"aria-orientation":`horizontal`,onPointerDown:Ot(e,t),onDoubleClick:()=>mt({...Ig}),title:R(`dragToResize`)},`sash-${e}`)])),zt=(0,Q.useCallback)(e=>{let t=e.target;t&&(t.closest(`.lp-row`)||t.closest(`button, input, select, textarea, a`)||(p({type:`new_chat`}),cn()))},[p]),Bt=(e,t)=>{let n=gg(ie),r=gg(e.path),i=!!(n&&n===r),a=L?.kind===`session`&&gg(L.target)===r,o=_t(e),s=!!o?.isStreaming,c=!!o?.hasQuestion,l=!!(o?.hasError||o?.error),u=!!(s||c||o?.conv?.completionPending||o?.conv?.isStreaming),d=!i&&!u&&B({id:o?.conv?.id,sessionId:e.sessionId,sessionFile:e.path,path:e.path}),f=kt(e),m=f,h=null,g=m.match(/^\[(微信|feishu|飞书|dingtalk|钉钉|wechat|qq|telegram)[^\]]*\]\s*(.*)$/i);if(g){let e=g[1].toLowerCase();h={key:`wechat`,label:e.includes(`微信`)||e===`wechat`?`微信`:e.includes(`飞书`)||e===`feishu`?`飞书`:e.includes(`钉钉`)||e===`dingtalk`?`钉钉`:e.toUpperCase()},g[2]?.trim()&&(m=g[2].trim())}else e.parentSessionPath||o?.conv?.forkFrom?h={key:`fork`,label:`🌿分支`}:o?.conv?.elsewhere&&o.conv.owner?.startsWith(`scheduler:`)?h={key:`scheduler`,label:`调度`}:e.source===`tui`&&(h={key:`tui`,label:`TUI`});return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>pe(t=>t===`sess:${e.path}`?null:t),onContextMenu:t=>dt(t,{id:e.path,kind:`history`,label:f}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-tree-session-item ${i?`active`:``} ${a?`switching`:``}${u?` is-running`:``}${d?` is-unread`:``}`,title:e.path,disabled:a,onClick:()=>{if(!(he||a)){if(gs(e.path),e.sessionId&&gs(e.sessionId),o?.conv?.id&&gs(o.conv.id),o?.conv?.id&&!o.conv.elsewhere){i||p({type:`switch_conversation`,id:o.conv.id});return}i||p({type:`switch_session`,path:e.path})}},children:[he===e.path?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:U,placeholder:R(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>_e(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=U.trim();t&&p({type:`rename_session`,path:e.path,name:t}),ge(null)}else t.key===`Escape`&&ge(null)},onBlur:()=>ge(null)}):(0,$.jsxs)(`span`,{className:`conv-title-text`,title:f,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:R(`pinnedConversation`),children:`📌`}),m]}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[a?(0,$.jsx)(xs,{className:`status-spinner-right`}):c?(0,$.jsx)(`span`,{className:`status-question-right`,title:R(`waitingQuestionBadge`),children:`?`}):s?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:R(`streaming`)}):l?(0,$.jsx)(`span`,{className:`status-error-right`,title:o?.error,children:`!`}):u?(0,$.jsx)(`span`,{className:`status-pulse-right`,title:R(`tabRunning`)}):d?(0,$.jsx)(`span`,{className:`status-unread-right`,title:R(`completedUnreadTooltip`),children:(0,$.jsx)(`span`,{className:`status-unread-dot`})}):null,h&&(0,$.jsx)(`span`,{className:`category-badge-pill ${h.key}`,children:h.label}),(0,$.jsx)(`span`,{className:`conv-time ${a?`switching-pct`:``}`,children:a?`${L.progress}%`:Tg(e.modified)})]})]}),de!==`sess:${e.path}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:R(`renameSession`),onClick:t=>{t.stopPropagation(),pe(null),_e(e.name??``),ge(e.path)},children:(0,$.jsx)(fe,{})}),!s&&Nt(`sess:${e.path}`,R(`deleteSession`),R(`deleteSessionConfirm`),()=>{Sg(e.path,ce),p({type:`delete_session`,path:e.path})}),ut(Dt,`lp-slot-sessions`)]},e.path)},Vt=({c:e,depth:n,hasKids:i,isCollapsed:a,descendantCount:c,hasStreaming:l,hasError:u,hasQuestion:d},m)=>{if(e.elsewhere){let t=e.owner,n=e.convId,r=!!e.pseudo,i=!!e.ownerOffline&&!r,a=!!(typeof t==`string`&&t.startsWith(`scheduler:`)),c=e.independent===!1,u=!!(t&&n)&&(c||a),d=u||!!(t&&n)&&!a&&!c,m=s===t&&o===n,h=!!(e.isStreaming||l||e.completionPending),g=!m&&!h&&B({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),_=!c&&!a&&me===e.id,v=c?e.cwd:a?`${R(`schedulerViewTip`)}\n${e.cwd}`:_?R(`takeoverConfirm`):r?`点击直接在电脑端打开此对话\n${e.cwd}`:`${R(i?`elsewhereOfflineTip`:`elsewhereTip`)}\n${e.cwd}`;return(0,$.jsxs)(`div`,{className:`lp-row`,onMouseLeave:()=>{H(t=>t===e.id?null:t),pe(t=>t===`else:${e.id}`?null:t)},onContextMenu:i=>dt(i,{id:n??e.id,kind:`elsewhere`,label:e.title,...t?{owner:t}:{},...r?{pseudo:!0}:{}}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item elsewhere-item${m?` active`:``}${d?``:` elsewhere-static`}${_?` confirm`:``}${h?` is-running`:``}${g?` is-unread`:``}`,title:v,tabIndex:d?0:-1,onClick:d?()=>{if(u){p({type:`open_shared_conversation`,owner:t,id:n});return}if(r){p({type:`take_over_conversation`,owner:t,id:n});return}if(!_){H(e.id);return}H(null),p({type:`take_over_conversation`,owner:t,id:n})}:void 0,children:[(0,$.jsx)(`span`,{className:`session-icon-wrap`,children:e.hasQuestion?(0,$.jsx)(`span`,{className:`session-icon`,style:{color:`var(--amber)`,fontWeight:800,fontSize:`12px`,display:`inline-flex`,alignItems:`center`,justifyContent:`center`},title:R(`takeoverHasQuestion`),children:`?`}):e.isStreaming||l?(0,$.jsx)(be,{className:`session-icon streaming-pulse`,style:{color:`var(--green)`},title:R(`streaming`)}):a?(0,$.jsx)(vt,{className:`session-icon`,title:R(`scheduledTaskBadge`)}):(0,$.jsx)(f,{className:`session-icon`})}),(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsxs)(`span`,{className:`session-title`,children:[a?(0,$.jsx)(`span`,{className:`elsewhere-badge scheduled-badge`,children:R(`scheduledTaskBadge`)}):c?null:(0,$.jsx)(`span`,{className:`elsewhere-badge`,children:R(r?`elsewherePseudoBadge`:`elsewhereBadge`)}),i&&(0,$.jsx)(`span`,{className:`elsewhere-badge offline`,title:R(`elsewhereOfflineTip`),children:R(`elsewhereOfflineBadge`)}),e.hasQuestion&&t&&n&&!r&&(0,$.jsx)(`span`,{className:`question-badge clickable`,title:R(`takeoverHasQuestion`),onClick:e=>{e.stopPropagation(),p({type:`peek_elsewhere_question`,owner:t,id:n})},children:`?`}),_?R(`takeoverConfirm`):e.title]}),(0,$.jsxs)(`span`,{className:`session-sub`,children:[e.hasQuestion?(0,$.jsxs)(`span`,{style:{color:`var(--amber)`,fontWeight:600},children:[R(`waitingQuestionShort`),` · `]}):e.isStreaming||l?(0,$.jsxs)(`span`,{style:{color:`var(--green)`,fontWeight:500},children:[R(`streaming`),` · `]}):null,At(e.cwd)]})]})]}),ct&&de!==`else:${e.id}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-elsewhere-act`,style:{right:32},title:R(`elsewhereActions`),onClick:i=>{i.stopPropagation(),ot.current=null;let a=i.currentTarget.getBoundingClientRect();lt(a.left,a.bottom+4,{id:n??e.id,kind:`elsewhere`,label:e.title,...t?{owner:t}:{},...r?{pseudo:!0}:{}})},children:(0,$.jsx)(j,{})}),Nt(`else:${e.id}`,R(`dismissConversation`),R(`dismissConversationConfirm`),()=>p({type:`dismiss_conversation`,id:n??e.id,force:!0,...t?{owner:t}:{}}),(0,$.jsx)(Z,{}))]},e.id)}let h=!s&&o===e.id,g=!!(e.isStreaming||l||e.completionPending),_=!h&&!g&&B({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),v=`conv:${e.id}`,y=de===v,b=e.title,x=null,S=b.match(/^\[(微信|feishu|飞书|dingtalk|钉钉|wechat|qq|telegram)[^\]]*\]\s*(.*)$/i);if(S){let e=S[1].toLowerCase();x={key:`wechat`,label:e.includes(`微信`)||e===`wechat`?`微信`:e.includes(`飞书`)||e===`feishu`?`飞书`:e.includes(`钉钉`)||e===`dingtalk`?`钉钉`:e.toUpperCase()},S[2]?.trim()&&(b=S[2].trim())}else e.forkFrom?x={key:`fork`,label:`🌿分支`}:e.elsewhere&&e.owner?.startsWith(`scheduler:`)&&(x={key:`scheduler`,label:`调度`});return(0,$.jsxs)(`div`,{className:`lp-row${n>0?` lp-sub`:``}${i?` lp-has-kids`:``}`,style:n>0?{"--depth":Math.min(n,4)}:void 0,onMouseLeave:()=>pe(e=>e===v?null:e),onContextMenu:t=>dt(t,{id:e.id,kind:`running`,label:e.title}),children:[i&&(0,$.jsx)(`button`,{type:`button`,className:`lp-tree-caret`,title:R(a?`expandSubagents`:`collapseSubagents`),"aria-label":R(a?`expandSubagents`:`collapseSubagents`),onClick:t=>{t.stopPropagation(),De(e.id)},children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 12 12`,fill:`currentColor`,style:{display:`block`},children:(0,$.jsx)(`path`,{d:a?`M4 2.5v7l5-3.5z`:`M2.5 4h7l-3.5 5z`})})}),(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-tree-session-item ${h?`active`:``}${g?` is-running`:``}${_?` is-unread`:``}`,title:`${e.title}${m?``:` — ${e.cwd}`}`,onClick:()=>{gs(e.id),e.sessionId&&gs(e.sessionId),e.sessionFile&&gs(e.sessionFile),h||p({type:`switch_conversation`,id:e.id})},children:[he===`conv:${e.id}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:U,placeholder:R(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>_e(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=U.trim();t&&p({type:`rename_conversation`,id:e.id,name:t}),ge(null)}else t.key===`Escape`&&ge(null)},onBlur:()=>ge(null)}):(0,$.jsxs)(`span`,{className:`conv-title-text`,title:e.title,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:R(`pinnedConversation`),children:`📌`}),b]}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[d||e.hasQuestion?(0,$.jsx)(`span`,{className:`status-question-right`,title:R(`waitingQuestionBadge`),children:`?`}):g?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:R(`streaming`)}):e.error?(0,$.jsx)(`span`,{className:`status-error-right`,title:e.error,children:`!`}):_?(0,$.jsx)(`span`,{className:`status-unread-right`,title:R(`completedUnreadTooltip`),children:(0,$.jsx)(`span`,{className:`status-unread-dot`})}):null,x&&(0,$.jsx)(`span`,{className:`category-badge-pill ${x.key}`,children:x.label}),e.agentPreset&&e.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.agentPreset,children:I?.[e.agentPreset]??e.agentPreset})]})]}),!y&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:R(`renameSession`),onClick:t=>{t.stopPropagation(),pe(null),_e(e.title),ge(v)},children:(0,$.jsx)(fe,{})}),(()=>{let n=v,i=y,a=X(t,e.id),o=it(t,e.id),s=rt(t,e.id);return s===0&&!e.isStreaming?e.hasUserTerminals?Nt(n,R(`dismissConversation`),R(`dismissTerminalsConfirm`),()=>p({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Z,{})):Nt(n,R(`dismissConversation`),R(`dismissConversationConfirm`),()=>p({type:`dismiss_conversation`,id:e.id}),(0,$.jsx)(Z,{})):s===0?Nt(n,R(`dismissConversation`),R(`dismissStreamingConfirm`),()=>p({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Z,{})):i?(0,$.jsxs)(`span`,{className:`lp-del-group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt danger`,title:R(`forceDismissTitle`,{n:s,m:o}),onClick:t=>{t.stopPropagation(),pe(null),p({type:`dismiss_conversation`,id:e.id,force:!0})},children:R(`dismissForceAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del confirm`,title:o>0&&a>0?R(`dismissFinishedSubagentsScoped`,{n:a}):R(`dismissConversationConfirm`),onClick:t=>{t.stopPropagation(),pe(null),p({type:`dismiss_conversation`,id:e.id,withFinishedSubagents:!0})},children:(0,$.jsx)(r,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`lp-del`,title:R(`dismissConversation`),onClick:e=>{e.stopPropagation(),pe(n)},children:(0,$.jsx)(Z,{})})})(),ut(Et,`lp-slot-sessions`)]},e.id)},Ht={projects:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section panel-projects ${ve||Ae===`projects`&&a.length===0?`collapsed`:``}`,style:ve?void 0:{flex:`${Lt(`projects`)} 1 0px`},children:[(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,onClick:G,title:R(ve?`expandSection`:`collapseSection`),children:(0,$.jsxs)(`span`,{className:`lp-section-title-text`,style:{display:`inline-flex`,alignItems:`center`},children:[(0,$.jsx)(`span`,{style:{display:`none`},children:R(`recentProjects`)}),(0,$.jsxs)(`span`,{className:`lp-conv-tabs`,style:{display:`inline-flex`,gap:`5px`,userSelect:`none`,alignItems:`center`},onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`span`,{role:`button`,tabIndex:0,className:`lp-conv-tab ${Ae===`groups`?``:`active`}`,onClick:e=>{e.stopPropagation(),je(`projects`)},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),je(`projects`))},title:R(`tabProjects`),children:[(0,$.jsx)(Je,{style:{fontSize:`12.5px`}}),(0,$.jsx)(`span`,{children:R(`tabProjects`)}),(0,$.jsxs)(`span`,{style:{fontSize:`11px`,opacity:.85},children:[`(`,a.length,`)`]})]}),(0,$.jsxs)(`span`,{role:`button`,tabIndex:0,className:`lp-conv-tab ${Ae===`groups`?`active`:``}`,onClick:e=>{e.stopPropagation(),je(`groups`)},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),je(`groups`))},title:R(`deviceGroups`),children:[(0,$.jsx)(K,{style:{fontSize:`12.5px`}}),(0,$.jsx)(`span`,{children:R(`deviceGroups`)}),Fe>0&&(0,$.jsxs)(`span`,{style:{fontSize:`11px`,opacity:.85},children:[`(`,Fe,`)`]})]})]})]})}),(0,$.jsxs)(`div`,{className:`lp-section-actions`,ref:Pe,style:{position:`relative`},children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action ${Y?`active`:``}`,title:Y?void 0:R(`openProject`),"aria-label":R(`openProject`),"aria-expanded":Y,onClick:e=>{e.stopPropagation(),Ne(e=>!e)},children:(0,$.jsx)(te,{})}),ut(x,`lp-slot-section`),Y&&(0,$.jsxs)(`div`,{className:`lp-workspace-menu`,role:`menu`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-manage-projects-btn`,onClick:()=>{Ne(!1),ue(!0)},children:[(0,$.jsx)(Je,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:R(`openProject`)})]}),ee&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item`,onClick:()=>{Ne(!1),ee()},children:[(0,$.jsx)(Zn,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:R(`sandboxNewShort`)})]}),(0,$.jsx)(`div`,{className:`lp-workspace-menu-divider`}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item`,onClick:()=>{Ne(!1),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{create:!0}}))},children:[(0,$.jsx)(K,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:R(`createGroup`)})]})]})]})]}),!ve&&(Ae===`groups`?(0,$.jsx)(ls,{entry:E?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,hideHeader:!0,onRoomCountChange:Ie}):Ve.length>0?(0,$.jsxs)(`div`,{className:`lp-section-body projects-scroll`,onDoubleClick:zt,children:[(()=>{let e=new Set,t=new Set;return Ve.map(n=>{let a=gg(n.path),o=a===gg(ce),s=!$e(n.path),c=L?.kind===`cwd`&&gg(L.target)===a,d=n.sandbox,f=d?d.name:At(n.path),m=ht.filter(e=>gg(e.cwd)===a),h=bs(m,Ee);for(let n of m)n.sessionFile&&e.add(gg(n.sessionFile)),n.sessionId&&t.add(n.sessionId.trim().toLowerCase());let g=l?.[a],_=o?i:g??yg(n.path,u)??[],v=Ze.has(a)&&_.length===0,y=_.filter(r=>{if(!bg(r.path,n.path))return!1;let i=gg(r.path);if(i&&e.has(i))return!1;let a=r.sessionId?.trim().toLowerCase()||Ts(r.path)?.toLowerCase();return a&&t.has(a)?!1:(i&&e.add(i),a&&t.add(a),!0)}),b=m.filter(e=>e.isStreaming||e.hasQuestion||e.completionPending).length,x=b>0,S=y.length>0,w=m.filter(e=>!e.isStreaming&&!e.completionPending&&B({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile})).length+y.filter(e=>B({sessionId:e.sessionId,sessionFile:e.path,path:e.path})).length,T=w>0,E=Ye[a]??8,D=y.slice(0,E),O=!s&&y.length>E;return(0,$.jsxs)(`div`,{className:`lp-project-node`,children:[(0,$.jsxs)(`div`,{className:`lp-row lp-project-head-row${x?` has-running`:``}${T?` has-unread`:``}`,onMouseLeave:()=>pe(e=>e===`proj:${n.path}`?null:e),onContextMenu:e=>Mt(e,n),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-project-header-item project-item ${o?`active`:``} ${c?`switching`:``}${x?` has-running`:``}${T?` has-unread`:``}`,title:d?.sourcePath?`${f}\n${R(`sandboxSourceLabel`)}: ${d.sourcePath}\n${n.path}`:n.path,disabled:c,onClick:()=>{c||(o||p({type:`set_cwd`,path:n.path}),et(n.path))},onDoubleClick:e=>{e.stopPropagation(),!c&&(o||p({type:`set_cwd`,path:n.path}),p({type:`new_chat`}),cn())},children:[(0,$.jsx)(`span`,{className:`lp-project-chevron`,onClick:e=>{e.stopPropagation(),et(n.path)},title:R(s?`expandSection`:`collapseSection`),children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 12 12`,fill:`currentColor`,style:{display:`block`},children:(0,$.jsx)(`path`,{d:s?`M4 2.5v7l5-3.5z`:`M2.5 4h7l-3.5 5z`})})}),c?(0,$.jsx)(xs,{className:`project-icon spin`}):d?(0,$.jsx)(Zn,{className:`project-icon sandbox-icon`}):null,(0,$.jsx)(`span`,{className:`lp-project-name`,title:f,children:f}),d&&(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${d.ephemeral?`ephemeral`:`permanent`}`,children:d.ephemeral?R(`sandboxBadgeEphemeral`):R(`sandboxBadgePermanent`)}),x&&(0,$.jsxs)(`span`,{className:`lp-project-running-badge`,title:R(`tabRunning`),children:[(0,$.jsx)(`span`,{className:`lp-project-running-dot`}),(0,$.jsx)(`span`,{children:b})]}),T&&(0,$.jsxs)(`span`,{className:`lp-project-unread-badge`,title:R(`completedUnreadBadge`),children:[(0,$.jsx)(`span`,{className:`lp-project-unread-dot`}),(0,$.jsx)(`span`,{children:w})]}),(0,$.jsx)(`span`,{className:`project-time ${c?`switching-pct`:``}`,children:c?`${L.progress}%`:Tg(n.lastUsed)})]}),(0,$.jsxs)(`div`,{className:`lp-project-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-new-chat-btn`,title:R(`newChat`)||`新建对话`,onClick:e=>{e.stopPropagation(),o||p({type:`set_cwd`,path:n.path}),p({type:`new_chat`}),cn()},children:(0,$.jsx)(te,{})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-del-btn ${de===`proj:${n.path}`?`confirm danger`:``}`,title:de===`proj:${n.path}`?R(d?`sandboxActionDestroy`:`deleteProjectConfirm`):R(d?`sandboxActionDestroyTip`:`deleteProject`),onClick:e=>{e.stopPropagation(),de===`proj:${n.path}`?(pe(null),dg(n.path),hg(n.path),p(d?{type:`destroy_sandbox`,path:n.path}:{type:`remove_project`,path:n.path})):pe(`proj:${n.path}`)},children:de===`proj:${n.path}`?(0,$.jsx)(r,{}):(0,$.jsx)(Ge,{})}),ut(C,`lp-slot-project`,{id:n.path,kind:`project`,label:f})]})]}),(s&&(h.length>0||T)||!s)&&(0,$.jsxs)(`div`,{className:`lp-project-tree-children`,children:[h.map(e=>Vt(e,n.path)),!s&&D.map(e=>Bt(e,n.path)),!s&&h.length===0&&y.length===0&&(0,$.jsx)(`div`,{className:`lp-project-empty-tip`,children:v?(0,$.jsx)(`span`,{children:R(`loadingSessions`)||`正在读取会话…`}):(0,$.jsx)(`span`,{children:R(`noSessionsYet`)||`暂无历史会话`})}),s&&S&&(0,$.jsxs)(`div`,{className:`lp-collapsed-history-tip`,onClick:e=>{e.stopPropagation(),et(n.path)},title:R(`expandSection`),children:[(0,$.jsxs)(`span`,{children:[`+ 已收起 `,y.length,` 条历史`]}),(0,$.jsx)(`span`,{children:`›`})]}),!s&&O&&(0,$.jsx)(`div`,{className:`lp-show-more-row`,onClick:e=>{e.stopPropagation(),Xe(e=>({...e,[a]:(e[a]??8)+20}))},children:(0,$.jsxs)(`span`,{children:[`显示更多 · `,y.length-E]})})]})]},n.path)})})(),Tt()]}):null)]})}),convs:null,sessions:null},Ut=e=>{let t=yt.find(t=>t.key===e)?.entry;if(!t)return null;let n=xt(e);return(0,$.jsxs)(`div`,{className:`lp-section lp-section-plugin ${n?`collapsed`:``}`,style:n?void 0:{flex:`${Lt(e)} 1 0px`},children:[Pt(t.label,n,()=>Ce(e)),!n&&(0,$.jsx)(`div`,{className:`lp-section-body lp-plugin-section-body`,children:D?.(t)??null})]})},Wt=e=>e===`groups`?Ae!==`split`&&yt.some(e=>e.key===`projects`)?(0,$.jsx)(`section`,{className:`lp-section dg-side-section`,style:{display:`none`},children:(0,$.jsx)(ls,{entry:E?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,hideHeader:!0,onRoomCountChange:Ie})}):(0,$.jsx)(ls,{entry:E?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,flex:Lt(`groups`),onCollapsedChange:Te,onRoomCountChange:Ie}):e===`projects`||e===`convs`||e===`sessions`?Ht[e]:Ut(e);return(0,$.jsxs)(`aside`,{ref:ft,className:`panel panel-left lp-panel`,children:[h&&g&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:R(`collapsePanel`),onClick:g,children:(0,$.jsx)(F,{})}),bt.map(({key:e})=>(0,$.jsxs)(Q.Fragment,{children:[Wt(e),Rt.get(e)??null]},e)),(0,$.jsx)(Ta,{open:le,currentCwd:ce,pathCompletions:_??[],workspaceRoots:se,onClose:()=>ue(!1),onSelectDirectory:e=>p({type:`set_cwd`,path:e}),onCreateProject:e=>p({type:`make_dir`,path:e,setAsCwd:!0})})]})}),qg=e=>/\.(zip|tar|tar\.gz|tgz|gz)$/i.test(e);function Jg(e,t={}){let n={archive:d(`/api/file-transfer/archive`),upload:d(`/api/file-transfer/upload`)},r=new URL(z(`${n[e]}?${new URLSearchParams({clientId:sg(),...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 Yg(e,t,n){let r=await fetch(Jg(`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 hd(await r.blob(),i);if(!a.ok&&!a.cancelled)throw Error(a.error)}}async function Xg(){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 Zg(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=Jg(`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 Qg({request:e,onClose:t,onComplete:n}){let r=W(),i=Me(`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 Xg();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 Zg(e.dir,l,f,i):await Yg(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,Fn.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)(Z,{})})]}),(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 $g(e){return e.startsWith(`.`)&&e!==`..`}function e_(e,t){return t?e:e.filter(e=>!$g(e.name))}function t_(e){return e instanceof Error?e.message:String(e)}function n_(e,t,n,r){let i=c(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 r_({plugin:e,epoch:t,send:n,className:r}){let i=(0,Q.useRef)(null),{locale:a}=st(),o=W(),[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 bh(e,t),r)return;let i=await qt(e.id,()=>Qs(()=>import(hh(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}=Qm(n,{isolated:c});a=s.mount(u,Sh(e.id,e=>l.current(e)))}catch(t){if(r)return;console.error(`[plugin:${e.id}] 页面${o?`挂载`:`加载`}失败:`,t),c({kind:o?`mount`:`load`,detail:t_(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:n_(s,e.name,a,o)})]})}function i_(e){return`pi-web-ui:${e}:tab`}function a_(e,t){try{let n=localStorage.getItem(i_(e));return n&&t.some(e=>e.id===n)?n:null}catch{return null}}function o_(e,t){try{localStorage.setItem(i_(e),t)}catch{}}function s_(e){return e.length>0&&!/[a-z]/i.test(e)}function c_(e){if(e.label)return e.label;let t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function l_({storageKey:e,tabs:t,epoch:n,send:r,extra:i,className:a}){let o=(0,Q.useId)(),[s,c]=(0,Q.useState)(()=>a_(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,o_(e,f.id))},[f,s,e]);let m=t=>{c(t.id),u.current=`${e}:${t.id}`,o_(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??c_(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)(ii,{iconSvg:e.iconSvg,className:`slot-tab-icon`}):e.icon&&s_(e.icon)?(0,$.jsx)(`span`,{className:`slot-tab-icon`,children:e.icon}):null,(0,$.jsx)(`span`,{className:`slot-tab-label`,children:c_(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)(r_,{plugin:f.pluginPage.plugin,epoch:n,send:r}):f.element??null})]})}var u_=`@root`,d_=`pi-web-ui:rp-sizes`,f_=`pi-web-ui:files-show-hidden`,p_={files:4,widgets:1},m_=120,h_=56;function g_(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}var __=`files`,v_=[],y_=()=>{};function b_(e){let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n<0?``:n===0?`/`:t.slice(0,n)}function x_(e){return e===u_||e===`/`||/^[A-Za-z]:$/.test(e)}function S_(e){return e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)}var C_=(0,Q.memo)(function({files:e,fileChanged:t,widgets:n,panelSend:i,onAttach:a,onPreview:o,onNotice:s,collapsible:c,onToggleCollapse:l,uiRightPanelTabs:u,uiContextFile:d,plugins:f,pluginsEpoch:p,send:m}){let h=W(),_=f??v_,v=Me(`cwd`),y=Me(`workspaceRoots`),x=Me(`homeDir`),S=Me(`desktopDir`),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),A=(0,Q.useRef)(null),j=(0,Q.useRef)(null),[M,N]=(0,Q.useState)(()=>{try{return vs(localStorage.getItem(d_),p_)}catch{return{...p_}}});(0,Q.useEffect)(()=>{try{localStorage.setItem(d_,JSON.stringify(M))}catch{}},[M]);let[P,F]=(0,Q.useState)(()=>{try{return localStorage.getItem(f_)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{localStorage.setItem(f_,P?`1`:`0`)}catch{}},[P]);let I=n.some(e=>e.lines.length>0),L=(0,Q.useCallback)(e=>{e.preventDefault();let t=A.current;if(!t)return;let n=e.currentTarget,r=e.clientY,i={above:M.files,below:M.widgets},a=Math.max(120,t.clientHeight-g_(t,j.current));n.classList.add(`dragging`),document.body.classList.add(`rp-resizing`);let o=e=>{let{above:t,below:n}=ys({start:i,deltaPx:e.clientY-r,availablePx:a,totalWeight:i.above+i.below,minAbovePx:m_,minBelowPx:h_});N({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)},[M.files,M.widgets]),ee=(0,Q.useRef)(null),te=(0,Q.useRef)(0),ne=(0,Q.useCallback)(e=>{ee.current=e,e&&(e.scrollTop=te.current)},[]),[re,z]=(0,Q.useState)(null),ie=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ie.current&&clearTimeout(ie.current)},[]);let ae=(0,Q.useCallback)(e=>{z(e),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>z(null),1200)},[]),V=(0,Q.useCallback)((e,t)=>{e&&Ec(e).then(e=>{e?ae(t):s(`error`,h(`slashCopyFailed`))})},[ae,s,h]),oe=(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]),se=(0,Q.useCallback)(e=>{if(gn(v)){let t=mn(v),n=t?t.remotePath:`/`;if(!e)return n;if(e.startsWith(`/`))return e;let r=n.replace(/\/+$/,``)||`/`;return r===`/`?`/${e}`:`${r}/${e}`}return oe(e)},[v,oe]),ce=(0,Q.useCallback)(e=>!e||e===u_?null:e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)?e:`${v.replace(/\\/g,`/`).replace(/\/+$/,``)}/${e}`,[v]),ue=Me(`workspaceUploadMaxMb`)*1024*1024,[de,fe]=(0,Q.useState)([]),pe=Me(`status`);(0,Q.useEffect)(()=>{pe!==`open`&&fe(e=>e.some(e=>e.phase===`waiting`)?e.map(e=>e.phase===`waiting`?{...e,phase:`unknown`}:e):e)},[pe]);let me=(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`&&fe(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=me.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 H=(0,Q.useCallback)((e,t)=>{for(let n of t){if(n.size>ue){s(`warning`,h(`fileTooLarge`,{name:n.name,size:ue/1024/1024}));continue}let t=crypto.randomUUID(),r=e=>fe(n=>n.map(n=>n.id===t?{...n,...e}:n));fe(r=>[...r,{id:t,name:n.name,dir:e,phase:`reading`,percent:0}]);let a=new FileReader;me.current.set(t,a);let o=()=>{me.current.delete(t),r({phase:`error`,error:h(`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(me.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:h(`fileUploadSendFailed`,{name:n.name})})};try{a.readAsDataURL(n)}catch{o()}}},[i,s,h,ue]),he=(0,Q.useRef)(null),[ge,U]=(0,Q.useState)(null),_e=(0,Q.useRef)(null),G=(0,Q.useCallback)(()=>{let e=he.current?.project;e&&i({type:`set_cwd`,path:e.path})},[i]),K=(0,Q.useCallback)(()=>{_e.current&&(_e.current.value=``),_e.current?.click()},[]),[q,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(null),[Se,Ce]=(0,Q.useState)(``),[we,Ee]=(0,Q.useState)(null),[De,Oe]=(0,Q.useState)(``),ke=(0,Q.useCallback)((e,t)=>{md(e,t).then(e=>{e.ok||e.cancelled||s(`error`,h(`downloadFailed`,{error:e.error===`FILE_NOT_FOUND`?h(`fileNotFoundShort`):e.error}))})},[s,h]),Ae=(0,Q.useCallback)(()=>{let e=he.current?.target;e&&e.kind!==`list`&&!x_(e.id)&&(Ee(null),Ce(e.label),xe(e.id))},[]),je=(0,Q.useCallback)(()=>{if(!be)return;let e=Se.trim();xe(null),e&&i({type:`file_rename`,path:be,newName:e})},[be,Se,i]),Y=(0,Q.useCallback)(e=>{let t=he.current?.dir??C;xe(null),Oe(``),Ee({dir:t,kind:e})},[C]),Ne=(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]),Pe=(e,t,n,r)=>(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:e,placeholder:h(`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}),Fe=(0,Q.useCallback)(()=>{let e=he.current?.target;e&&e.kind!==`list`&&!x_(e.id)&&window.confirm(h(`fileDeleteConfirm`,{name:e.label}))&&(q?.src===e.id&&ye(null),be===e.id&&xe(null),i({type:`file_delete`,path:e.id}))},[i,h,q,be]),Ie=(0,Q.useCallback)(()=>{let e=he.current?.target;e&&e.kind!==`list`&&!x_(e.id)&&i({type:`file_copy`,src:e.id,destDir:b_(e.id)})},[i]),Le=(0,Q.useCallback)(e=>{let t=he.current?.target;t&&t.kind!==`list`&&!x_(t.id)&&ye({src:t.id,cut:e})},[]),Re=(0,Q.useCallback)(()=>{if(!q)return;let e=he.current?.dir??C;q.cut?(i({type:`file_copy`,src:q.src,destDir:e,move:!0}),ye(null)):i({type:`file_copy`,src:q.src,destDir:e})},[q,i,C]),ze=(0,Q.useCallback)(()=>{i({type:`list_files`,path:C===``?void 0:C})},[i,C]),[Be,Ve]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!Be)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)}},[Be]);let He=(0,Q.useCallback)(e=>{i({type:`set_workspace_roots`,roots:e})},[i]),We=(0,Q.useCallback)(()=>{let e=he.current?.target;if(!e||e.kind!==`dir`)return;let t=ce(e.id);t&&!y.includes(t)&&He([...y,t])},[y,ce,He]),Ge=(0,Q.useCallback)(e=>{H(he.current?.dir??C,Array.from(e.target.files??[]))},[H,C]),Ke=(0,Q.useCallback)(e=>{let t=he.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`;U({action:n,path:se(t.id),dir:se(n===`upload`?he.current?.dir??C:b_(t.id))});break}case`host:file-open-project`:G();break;case`host:file-upload`:K();break;case`host:file-add-root`:We();break;case`host:file-open`:t?.kind===`file`&&o(t.id,t.label);break;case`host:file-enter`:t?.kind===`dir`&&at(t.id);break;case`host:file-download`:t?.kind===`file`&&ke(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`:Y(`file`);break;case`host:file-new-dir`:Y(`dir`);break;case`host:file-paste`:Re();break;case`host:file-rename`:Ae();break;case`host:file-duplicate`:Ie();break;case`host:file-cut`:Le(!0);break;case`host:file-copy`:Le(!1);break;case`host:file-copy-name`:t&&t.kind!==`list`&&V(t.label,`name:${t.id}`);break;case`host:file-copy-path`:t&&t.kind!==`list`&&V(oe(t.id),`path:${t.id}`);break;case`host:file-copy-rel`:t&&t.kind!==`list`&&V(t.id,`rel:${t.id}`);break;case`host:file-refresh`:ze();break;case`host:file-delete`:Fe()}},[G,C,K,We,o,a,V,oe,ke,Y,Re,Ae,Ie,Le,ze,Fe]),qe=(0,Q.useCallback)((e,t)=>{let n=t.kind===`dir`?ce(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&&x_(t.id),l=!s&&S_(t.id),u=C===u_,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&&qg(t.label)?e:{...e,hidden:!0};case`host:file-upload`:return u?{...e,hidden:!0}:{...e,label:r.dir===C?h(`uploadToCurrentDir`):h(`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!==u_?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&&q?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}});pa(f).length!==0&&(e.preventDefault(),e.stopPropagation(),he.current=r,na({x:e.clientX,y:e.clientY,slot:`contextmenu.file`,target:t,entries:f,onHostAction:Ke}))},[d,C,ce,h,Ke,v,y,q]),Ye=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),Xe=(0,Q.useCallback)(()=>{ee.current?.querySelectorAll(`.file-item.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),ee.current?.classList.remove(`drop-root`)},[]),Ze=(0,Q.useCallback)(e=>{if(Xe(),e==null)return;let t=ee.current?.querySelector(`.file-item[data-path="${CSS.escape(e)}"]`);t?t.classList.add(`drop-target`):ee.current?.classList.add(`drop-root`)},[Xe]),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}))},[]),tt=(0,Q.useRef)(0),nt=(0,Q.useRef)(void 0),X=(0,Q.useCallback)((e,t)=>{let n=++tt.current;w(e),t?.silent||O(!0),i({type:`list_files`,path:e===``?void 0:e})||tt.current===n&&O(!1)},[i]),rt=(0,Q.useCallback)(e=>{let t=y.filter(t=>t!==e);He(t),(C===e||C.startsWith(`${e}/`))&&X(``)},[y,He,C,X]);(0,Q.useEffect)(()=>{e&&e.path===C&&O(!1)},[e,C]),(0,Q.useEffect)(()=>{if(v!==nt.current){let e=nt.current===void 0;nt.current=v,e?X(``,{silent:!0}):w(``);return}let e=setInterval(()=>{document.visibilityState!==`hidden`&&X(C,{silent:!0})},1e4);return()=>clearInterval(e)},[v,C,X]),(0,Q.useEffect)(()=>{t&&t.path===C&&X(C,{silent:!0})},[t,C,X]);let at=e=>X(e),ot=()=>{e?.parent!==null&&e?.parent!==void 0&&X(e.parent)},st=(()=>{if(C===``||C===u_)return[];let e=C.split(`/`).filter(e=>!!e&&e!==u_);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:A,children:[c&&l&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:h(`collapsePanel`),onClick:l,children:(0,$.jsx)(g,{})}),(0,$.jsx)(`div`,{ref:j,style:{display:`flex`,flexDirection:`column`,flex:I?`${M.files} 1 0`:`1 1 0`,minHeight:I?m_:0},children:(0,$.jsx)(l_,{storageKey:`rightpanel`,epoch:p??0,send:m??y_,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===__?`host:right-files`:e)??1e9;return[...e].sort((e,t)=>r(e.id)-r(t.id))})([...lt?[]:[{id:__,label:h(`openFiles`),element:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`panel-crumbs`,children:[(0,$.jsx)(`button`,{type:`button`,className:`crumb ${C===``?`active`:``}`,onClick:()=>X(``),children:h(`rootDir`)}),(0,$.jsx)(dn,{className:`crumb ${C===u_?`active`:``}`,tip:h(`computer`),onClick:()=>X(u_),children:(0,$.jsx)(Te,{})}),x!==``&&(0,$.jsx)(dn,{className:`crumb ${C===x||C.startsWith(`${x}/`)?`active`:``}`,tip:h(`homeDir`),onClick:()=>X(x),children:(0,$.jsx)(Ue,{})}),S!==``&&(0,$.jsx)(dn,{className:`crumb ${C===S||C.startsWith(`${S}/`)?`active`:``}`,tip:h(`desktopDir`),onClick:()=>X(S),children:(0,$.jsx)(k,{})}),(0,$.jsx)(dn,{className:`crumb ${P?`active`:``}`,tip:h(P?`filesHideHidden`:`filesShowHidden`),"aria-pressed":P,onClick:()=>F(e=>!e),children:P?(0,$.jsx)(J,{}):(0,$.jsx)(it,{})}),(0,$.jsx)(pn,{text:h(`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":Be,title:h(`workspaceRoots`),onClick:()=>Ve(e=>!e),children:[(0,$.jsx)(Je,{}),(0,$.jsx)(`span`,{className:`root-picker-label`,children:h(`workspaceRoots`)}),(0,$.jsx)(`span`,{className:`set-count`,children:y.length+1}),`▾`]}),Be&&(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),X(``)},children:[h(`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),X(e)},children:(0,$.jsx)(`span`,{className:`root-picker-path`,children:e})}),(0,$.jsx)(`button`,{type:`button`,className:`root-picker-remove`,title:h(`removeWorkspaceRoot`),"aria-label":h(`removeWorkspaceRoot`),onClick:()=>rt(e),children:(0,$.jsx)(Z,{})})]},e)),(0,$.jsx)(`div`,{className:`root-picker-hint`,children:h(`workspaceRootsHint`)})]})]}),st.map(e=>(0,$.jsxs)(`span`,{className:`crumb-seg`,children:[(0,$.jsx)(g,{}),(0,$.jsx)(`button`,{type:`button`,className:`crumb ${e.path===C?`active`:``}`,onClick:()=>X(e.path),children:e.label})]},e.path))]}),(0,$.jsxs)(`div`,{ref:ne,className:`panel-body`,onScroll:e=>{te.current=e.currentTarget.scrollTop},onContextMenu:e=>qe(e,{id:C,kind:`list`,label:C===``?h(`rootDir`):C===u_?h(`computer`):C}),onDragOver:e=>{Ye(e)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,$e(),Ze(Qe(e.target)))},onDragLeave:e=>{e.relatedTarget&&e.currentTarget.contains(e.relatedTarget)||Xe()},onDrop:e=>{if(Xe(),!Ye(e))return;e.preventDefault(),e.stopPropagation(),$e();let t=Array.from(e.dataTransfer?.files??[]);if(t.length===0){s(`warning`,h(`foldersNotSupported`));return}H(Qe(e.target),t)},onDragEnd:Xe,children:[(0,$.jsx)(`input`,{ref:_e,type:`file`,multiple:!0,hidden:!0,onChange:Ge}),de.length>0&&(0,$.jsx)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`4px 8px`},children:de.map(e=>{let t=e.phase===`reading`?h(`fileUploadReading`,{name:e.name,percent:e.percent}):e.phase===`waiting`?h(`fileUploadWaiting`,{name:e.name}):e.phase===`success`?h(`fileUploadConfirmed`):e.phase===`unknown`?h(`fileUploadOutcomeUnknown`):h(`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":`${h(`fileUploadDismiss`)}: ${e.name}`,title:h(`fileUploadDismiss`),onClick:()=>fe(t=>t.filter(t=>t.id!==e.id)),style:{flex:`none`,padding:2},children:(0,$.jsx)(Z,{"aria-hidden":`true`})})]}),e.phase===`reading`&&(0,$.jsx)(`progress`,{max:100,value:e.percent,"aria-label":h(`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)})}),ge&&(0,$.jsx)(Qg,{request:ge,onClose:()=>U(null),onComplete:ze}),we&&(0,$.jsxs)(`div`,{className:`file-item dir`,children:[we.kind===`dir`?(0,$.jsx)(Je,{className:`file-icon`}):(0,$.jsx)(et,{className:`file-icon`}),Pe(De,Oe,Ne,()=>Ee(null))]}),D&&(0,$.jsx)(`div`,{className:`panel-empty`,children:h(`loading`)}),!D&&e&&e.path===C&&(0,$.jsxs)($.Fragment,{children:[e.parent!=null&&(0,$.jsxs)(`button`,{type:`button`,className:`file-item dir`,onClick:ot,children:[(0,$.jsx)(Je,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:`..`})]}),e_(e.entries,P).map(e=>e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir${q?.cut&&q.src===e.path?` cut`:``}`,"data-type":`dir`,"data-path":e.path,onClick:t=>{be!==e.path&&(t.target.closest(`.file-attach`)||at(e.path))},onContextMenu:t=>qe(t,{id:e.path,kind:`dir`,label:e.name}),children:[be===e.path?Pe(Se,Ce,je,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:t=>{t.stopPropagation(),at(e.path)},children:[(0,$.jsx)(Je,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":h(`linkFolderTip`),"aria-label":h(`linkFolderTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`,!0)},children:(0,$.jsx)(ve,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${re===`name:${e.path}`?` copied`:``}`,"data-tip":h(`copyName`),"aria-label":h(`copyName`),onClick:t=>{t.stopPropagation(),V(e.name,`name:${e.path}`)},children:re===`name:${e.path}`?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${re===`path:${e.path}`?` copied`:``}`,"data-tip":h(`copyPath`),"aria-label":h(`copyPath`),onClick:t=>{t.stopPropagation(),V(oe(e.path),`path:${e.path}`)},children:re===`path:${e.path}`?(0,$.jsx)(r,{}):(0,$.jsx)(R,{})})]},e.path):(0,$.jsxs)(`div`,{className:`file-item file${q?.cut&&q.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=>qe(t,{id:e.path,kind:`file`,label:e.name}),children:[be===e.path?Pe(Se,Ce,je,()=>xe(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-name`,title:`${e.path} — ${h(`previewFile`)}`,onClick:t=>{t.stopPropagation(),o(e.path,e.name)},children:[(0,$.jsx)(et,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name-text`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach download`,"data-tip":h(`downloadFile`),onClick:t=>{t.stopPropagation(),ke(e.path,e.name)},children:(0,$.jsx)(le,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":h(`referenceTip`),"aria-label":h(`referenceTip`),onClick:t=>{t.stopPropagation(),a(e.path,e.name,`reference`)},children:(0,$.jsx)(ve,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${re===`name:${e.path}`?` copied`:``}`,"data-tip":h(`copyName`),"aria-label":h(`copyName`),onClick:t=>{t.stopPropagation(),V(e.name,`name:${e.path}`)},children:re===`name:${e.path}`?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${re===`path:${e.path}`?` copied`:``}`,"data-tip":h(`copyPath`),"aria-label":h(`copyPath`),onClick:t=>{t.stopPropagation(),V(oe(e.path),`path:${e.path}`)},children:re===`path:${e.path}`?(0,$.jsx)(r,{}):(0,$.jsx)(R,{})})]},e.path)),e.truncated&&(0,$.jsx)(`div`,{className:`panel-empty files-truncated`,children:h(`filesTruncated`)})]}),!D&&!e&&(0,$.jsx)(`div`,{className:`panel-empty`,children:h(`noFiles`)})]})]})}],...ct])})}),I&&(0,$.jsx)(`div`,{className:`rp-sash`,onPointerDown:L,onDoubleClick:()=>N({...p_}),title:h(`dragToResize`)}),I&&(0,$.jsx)(`div`,{className:`panel-widgets`,style:{flexGrow:M.widgets,minHeight:h_},children:n.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:h(`widgetExpand`),onClick:()=>E(e.key),children:[(0,$.jsx)(`span`,{children:e.key}),(0,$.jsx)(B,{})]}),(0,$.jsx)(`pre`,{className:`widget-lines`,children:e.lines.join(`
68
- `)})]},e.key))}),T&&(()=>{let e=n.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:h(`close`),onClick:()=>E(null),children:(0,$.jsx)(Z,{})})]}),(0,$.jsx)(`pre`,{className:`widget-expand-lines`,children:e.lines.join(`
69
- `)})]})}):null})()]})});function w_(e,t,n){let r=!1;for(let i of t){let t=i;if(t.type!==`image`||typeof t.dataUrl!=`string`)continue;if(/^\/api\/attachment\/[a-f0-9]{64}$/.test(t.dataUrl)){r=!0,e.push({path:``,imageUrl:t.dataUrl,mimeType:t.mimeType,name:n??`image`});continue}if(!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 T_(e){let t=e.details??{};if(t.mode===`quote`){let e=Ps(t.quote);return e?{path:``,mode:`quote`,quote:e}:null}let n=[];if(w_(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 E_(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.imageUrl)return`image-url:${e.imageUrl}`;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 D_(e){let t=new Set,n=[];for(let r of e){let e=E_(r);t.has(e)||(t.add(e),n.push(r))}return n}function O_(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=[];w_(i,r.content);let a=r.details?.quotes;for(let e of Array.isArray(a)?a:[]){let t=Ps(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=T_(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=T_(e[t]);n&&i.push(n)}let s=D_(i);s.length>0&&t.set(r.id,s)}return t}function k_(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 A_=(0,Q.memo)(function({message:e,onExpand:t,summary:n}){let r=W(),i=bp(),a=hp(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=Ip(t);if(e&&e.text.trim()){let t=Df(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)Lp(t)?l++:Rp(t)?u++:Bp(t)?d++:zp(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:()=>wp(e.id)}),(0,$.jsx)(`span`,{className:`msg-collapsed-role role-${e.role}`,children:e.role===`custom`&&e.customType===`file`?r(`attachment`):em(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:j_(e.timestamp)}):null,(0,$.jsx)(`span`,{className:`msg-collapsed-action`,children:r(`expandMsg`)})]})});function j_(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}var M_=`[goal-review]`;function N_(e){for(let t of e.content??[]){let e=Ip(t);if(e&&e.text.trim())return e.text}return``}function P_(e){if(e.role!==`assistant`)return;let t=N_(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 F_(e){if(e.role===`user`&&N_(e).includes(M_))return{kind:`prompt`};let t=P_(e);if(t)return{kind:`verdict`,verdict:t}}var I_=`--flow-inline-stream`;function L_(){if(typeof window>`u`||typeof document>`u`)return!1;let e=getComputedStyle(document.documentElement).getPropertyValue(I_).trim();return e===`1`||e===`true`}function R_(){let[e,t]=(0,Q.useState)(L_);return(0,Q.useEffect)(()=>{let e=()=>t(L_());return e(),window.addEventListener(jt,e),()=>window.removeEventListener(jt,e)},[]),e}var z_=(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 B_(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 V_(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 H_(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)??U_(n.role,n.customType)}return r}function U_(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 W_=[`text`,`thinking`,`argumentsText`,`output`,`command`];function G_(e){let t=0;for(let n of e.content){n.type===`image`&&(t+=1);for(let e of W_){let r=n[e];typeof r==`string`&&(t+=r.length)}}return t}function K_(e,t,n,r){let i=n.get(e);return i&&i.len===t?i.h:r}function q_(e){let t=[];for(let n of e.content)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
70
- `)}function J_(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=q_(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(`
71
- `)}function Y_(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function X_(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=Y_(J_(n,r).toLowerCase(),a);e>0&&i.set(n.id,e)}return i}function Z_(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 Q_(e,t,n,r,i){let a=X_(n,r,t,i),o=new Map;for(let n of Z_(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 $_(e,t){return e.findIndex(e=>e.msgId===t.msgId&&e.k===t.k)}function ev(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 tv(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 nv(e,t){let n=t.startContainer.parentElement;for(let r of tv(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 rv({containerRef:e,messages:t,collapsedIds:n,toolResults:r,onExpand:i,onProgrammaticScroll:a,open:o,onClose:s}){let c=W(),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(0),[,g]=(0,Q.useState)(0),_=(0,Q.useDeferredValue)(u),v=o?_.trim():``,y=(0,Q.useRef)(null);y.current=f;let b=(0,Q.useRef)([]),x=(0,Q.useRef)({key:null}),C=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{o&&(p(null),requestAnimationFrame(()=>l.current?.select()))},[o]),(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),s())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[o,s]),(0,Q.useEffect)(()=>(o||(ev(`msg-search`,[]),ev(`msg-search-active`,[])),()=>{ev(`msg-search`,[]),ev(`msg-search-active`,[])}),[o]),(0,Q.useLayoutEffect)(()=>{let s=()=>{h(0),p(null),g(0),b.current=[],ev(`msg-search`,[]),ev(`msg-search-active`,[]),x.current={key:null},C.current=``};if(!o||!v){s();return}let c=e.current;if(!c)return;let l=!1,u=0;return u=requestAnimationFrame(()=>{if(l)return;let e=Q_(c,v,t,n,r);b.current=e;let o=e.length;if(h(o),o===0){p(null),g(0),ev(`msg-search`,[]),ev(`msg-search-active`,[]),x.current={key:null},C.current=v;return}let s=y.current,u;if(s){if(u=$_(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)&&p({msgId:e[u].msgId,k:e[u].k}),g(u);let d=e[u],f=x.current,m=f.key?.msgId!==d.msgId||f.key?.k!==d.k||f.kind===`folded`&&d.kind===`dom`||v!==C.current;if(x.current={key:{msgId:d.msgId,k:d.k},kind:d.kind},C.current=v,ev(`msg-search`,e.filter(e=>e.kind===`dom`).map(e=>e.range)),d.kind===`folded`){ev(`msg-search-active`,[]),m&&i(d.msgId);return}ev(`msg-search-active`,[d.range]),m&&(a?.(),nv(c,d.range))}),()=>{l=!0,cancelAnimationFrame(u)}},[o,v,t,e,f,n,r,i,a]);let w=(0,Q.useCallback)(e=>{let t=b.current,n=t.length;if(n===0)return;let r=y.current,i=t[((r?$_(t,r):0)+e+n)%n];p(i.kind===`dom`||i.kind===`folded`?{msgId:i.msgId,k:i.k}:null)},[]);if(!o)return null;let T=f?(()=>{let e=$_(b.current,f);return e===-1?0:e})():0;return(0,$.jsxs)(`div`,{className:`search-bar`,role:`search`,children:[(0,$.jsx)(`input`,{ref:l,className:`search-input`,type:`text`,value:u,placeholder:c(`searchPlaceholder`),onChange:e=>{d(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w(e.shiftKey?-1:1))}}),(0,$.jsx)(`span`,{className:`search-count ${m===0?`empty`:``}`,children:m===0?c(`searchNoResults`):`${Math.min(T+1,m)}/${m}`}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:c(`searchPrev`),disabled:m===0,onClick:()=>w(-1),children:(0,$.jsx)(S,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:c(`searchNext`),disabled:m===0,onClick:()=>w(1),children:(0,$.jsx)(A,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:c(`searchClose`),onClick:s,children:(0,$.jsx)(Z,{})})]})}function iv(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 av(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 ov(e){let{wasStreaming:t,isStreaming:n,escaped:r,hasJumpTarget:i}=e;return i?!1:!t&&n?!r:!1}function sv(e){let{convChanged:t,lastQuestionId:n,prevLastQuestionId:r,escaped:i,hasJumpTarget:a}=e;return a?{shouldScroll:!1,reason:`none`}:t?{shouldScroll:!0,reason:`conv_changed`}:n!==null&&r!==null&&n!==r?{shouldScroll:!i,reason:`question_added`}:r===null&&n!==null?{shouldScroll:!i,reason:`initial_load`}:{shouldScroll:!1,reason:`none`}}function cv(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 lv(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,userPromptNonce:h}=e,g=(0,Q.useRef)(null),_=e.scrollRef??g,v=(0,Q.useRef)(null),[y,b]=(0,Q.useState)(!0),x=(0,Q.useRef)(!0),S=e.stickRef??x,C=(0,Q.useRef)(!1),w=e.escapedRef??C,T=(0,Q.useRef)(0),E=(0,Q.useRef)(0),D=(0,Q.useRef)(0),O=(0,Q.useRef)(0),k=(0,Q.useRef)(!1),A=(0,Q.useRef)(!1),j=(0,Q.useRef)(0),M=(0,Q.useRef)([]),N=(0,Q.useCallback)(()=>{for(let e of M.current)clearTimeout(e);M.current=[]},[]),P=(0,Q.useCallback)(()=>{N(),w.current=!0,S.current=!1,b(!1)},[N]),F=(0,Q.useCallback)(()=>{N(),O.current=Date.now(),D.current=0,w.current=!0,S.current=!1,b(!1)},[N]),I=(0,Q.useCallback)(()=>{let e=_.current;e&&(w.current||!S.current||Date.now()-O.current<500||(D.current=Date.now()+250,e.scrollTop=e.scrollHeight,T.current=e.scrollTop,E.current=e.scrollHeight))},[_]),L=(0,Q.useCallback)(()=>{_.current&&(N(),O.current=0,S.current=!0,w.current=!1,b(!0),I(),requestAnimationFrame(()=>requestAnimationFrame(I)),M.current.push(setTimeout(I,120)),M.current.push(setTimeout(I,300)),M.current.push(setTimeout(I,600)))},[I,N,_]),ee=(0,Q.useRef)(d);ee.current=d;let R=(0,Q.useRef)(f);R.current=f;let te=(0,Q.useCallback)(e=>{let t=_.current;t&&cv({scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,hasEarlier:ee.current,isMovingUp:e})&&R.current()},[_]),ne=(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;O.current=Date.now(),F(),te(!0)}else if(e.deltaY>0){O.current=0;let e=_.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(w.current=!1,S.current=!0,b(!0))}},[F,te,_]),re=(0,Q.useCallback)(e=>{e.touches.length>0&&(j.current=e.touches[0].clientY)},[]),z=(0,Q.useCallback)(e=>{if(e.touches.length>0){let t=e.touches[0].clientY-j.current;if(t>8)F(),te(!0);else if(t<-8){O.current=0;let e=_.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(w.current=!1,S.current=!0,b(!0))}}},[F,te,_]),B=(0,Q.useCallback)(e=>{if(e.button===1){O.current=Date.now(),F();return}if(e.button!==0)return;let t=e.currentTarget;e.target===t&&e.clientX>=t.getBoundingClientRect().left+t.clientWidth&&(k.current=!0)},[F]);(0,Q.useEffect)(()=>{let e=e=>{k.current=!1,(!e||e.button===1)&&(A.current=!1)},t=e=>{e.button===1&&(A.current=!0,O.current=Date.now(),F())},n=e=>{let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.key===`PageUp`||e.key===`ArrowUp`||e.key===`Home`?F():e.key===`End`&&(O.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)}},[F]);let ie=(0,Q.useCallback)(()=>{let e=_.current;if(!e)return;let t=e.scrollTop-T.current,n=e.scrollHeight-E.current;T.current=e.scrollTop,E.current=e.scrollHeight;let r=e.scrollHeight-e.scrollTop-e.clientHeight<36,i=Date.now()<D.current;A.current&&t<0&&(O.current=Date.now(),F());let a=Date.now()-O.current<800||k.current&&t<0||A.current,o=iv({dSt:t,dSh:n,escaped:w.current,graceActive:i,stuck:S.current});o.reassert&&!a&&I();let{shouldEscape:s,shouldReassert:c}=av({decisionFlipEscape:o.flipEscape,hasUserUpwardIntent:a,stuck:S.current,escaped:w.current});s?(w.current=!0,S.current=!1):c&&I(),!i&&!a&&(t<0||r&&(t>0||!w.current)&&(S.current=!0,w.current=!1));let l=t<0||Date.now()-O.current<800;te(l),b(e=>e===S.current?e:S.current),p(),m()},[p,m,I,F,te,_]),ae=(0,Q.useRef)(!!n);(0,Q.useEffect)(()=>{let e=ae.current;if(ae.current=!!n,ov({wasStreaming:e,isStreaming:!!n,escaped:w.current,hasJumpTarget:!!(l||u)})){L();return}if(e&&!n&&!w.current){let e=()=>{_.current&&!w.current&&(S.current=!0,b(!0),I())};requestAnimationFrame(()=>requestAnimationFrame(e))}},[n,l,u,L,I,_]);let V=c.length>0?c[c.length-1].id:null,oe=(0,Q.useRef)(`${o??``}:${s??``}`),se=(0,Q.useRef)(V);(0,Q.useEffect)(()=>{let e=`${o??``}:${s??``}`,t=e!==oe.current,n=_.current,r=!n||n.scrollHeight-n.scrollTop-n.clientHeight<36,i=!!(V&&sm(V)),{shouldScroll:a}=sv({convChanged:t,lastQuestionId:V,prevLastQuestionId:se.current,escaped:w.current,nearBottom:r,hasJumpTarget:!!(l||u)});oe.current=e,se.current=V,(a||i)&&L()},[o,s,V,l,u,L]);let ce=(0,Q.useRef)(h??0);(0,Q.useEffect)(()=>{let e=h??0;e>ce.current&&(ce.current=e,L())},[h,L]),(0,Q.useLayoutEffect)(()=>{_.current&&S.current&&!w.current&&I()},[t,n,r,i,I,_]);let le=a?a.steering.join(`\0`)+``+a.followUp.join(`\0`):``,ue=a?a.steering.length+a.followUp.length:0,de=(0,Q.useRef)(ue);return(0,Q.useLayoutEffect)(()=>{let e=ue>de.current;if(de.current=ue,e){L();return}_.current&&S.current&&!w.current&&I()},[le,ue,L,I,_]),(0,Q.useEffect)(()=>{let e=_.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()},[_]),(0,Q.useEffect)(()=>{let e=_.current;if(!e||typeof MutationObserver>`u`)return;let t=!1,n=new MutationObserver(()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1,_.current&&S.current&&!w.current&&(I(),b(!0))}))});return n.observe(e,{childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()},[I,_]),(0,Q.useEffect)(()=>{let e=v.current,t=_.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?F():n.deltaY>0&&(O.current=0,t.scrollHeight-t.scrollTop-t.clientHeight<96&&(w.current=!1,S.current=!0,b(!0))),t.scrollTop+=n.deltaY};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)},[F,_]),(0,Q.useEffect)(()=>()=>N(),[N]),{scrollRef:_,railRef:v,stickBottom:y,escapedRef:w,stickRef:S,scrollToBottom:L,pinToBottom:I,disengageStick:F,pauseForSelection:P,handleWheel:ne,handleTouchStart:re,handleTouchMove:z,handlePointerDown:B,onScroll:ie}}var uv=[{key:`{{input}}`,label:`{{input}} 参数`,desc:`快捷命令传入的参数,如 /pr 798 中的 798`},{key:`{{clipboard}}`,label:`{{clipboard}} 剪贴板`,desc:`自动提取剪贴板文本`},{key:`{{date}}`,label:`{{date}} 日期`,desc:`当前日期 (YYYY-MM-DD)`},{key:`{{time}}`,label:`{{time}} 时间`,desc:`当前时间 (HH:mm:ss)`},{key:`{{datetime}}`,label:`{{datetime}} 日期时间`,desc:`当前完整日期时间`},{key:`{{selection}}`,label:`{{selection}} 选中文本`,desc:`当前编辑器中选中的文本`}];function dv(e,t=new Date){if(!e.includes(`{{`))return e;let n=e=>String(e).padStart(2,`0`),r=t.getFullYear(),i=n(t.getMonth()+1),a=n(t.getDate()),o=n(t.getHours()),s=n(t.getMinutes()),c=n(t.getSeconds()),l=`${r}-${i}-${a}`,u=`${o}:${s}:${c}`,d=`${l} ${u}`;return e.replaceAll(`{{date}}`,l).replaceAll(`{{time}}`,u).replaceAll(`{{datetime}}`,d).replaceAll(`{{year}}`,String(r))}function fv(e){return e.trim().replace(/^\//,``).toLowerCase()}function pv(e){return/^[a-z][a-z0-9_-]*$/.test(e)}function mv(e,t){let n=new Set([`help`,`copy`,...t.map(e=>e.name.toLowerCase())]);return e.filter(e=>{let t=fv(e.command??``);return!pv(t)||n.has(t)?!1:(n.add(t),!0)})}function hv(e,t,n=new Date){let r=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!r)return e;let i=t.find(e=>fv(e.command??``)===r[1].toLowerCase());if(!i)return e;let a=r[2]??``;return dv(i.prompt.includes(`{{input}}`)?i.prompt.replaceAll(`{{input}}`,()=>a):[i.prompt,a].filter(Boolean).join(`
72
-
73
- `),n)}var gv=[{id:`clarify`,command:`clarify`,icon:`🎯`,titleKey:`tpl.sk.clarify`,descKey:`tpl.sk.clarify.desc`,promptKey:`tpl.sk.clarify.prompt`},{id:`to-plan`,command:`plan`,icon:`📋`,titleKey:`tpl.sk.toplan`,descKey:`tpl.sk.toplan.desc`,promptKey:`tpl.sk.toplan.prompt`},{id:`implement`,command:`tdd`,icon:`🧪`,titleKey:`tpl.sk.implement`,descKey:`tpl.sk.implement.desc`,promptKey:`tpl.sk.implement.prompt`},{id:`code-review`,command:`review`,icon:`🧹`,titleKey:`tpl.sk.codeview`,descKey:`tpl.sk.codeview.desc`,promptKey:`tpl.sk.codeview.prompt`},{id:`diagnosing-bugs`,command:`debug`,icon:`🐛`,titleKey:`tpl.sk.debug`,descKey:`tpl.sk.debug.desc`,promptKey:`tpl.sk.debug.prompt`},{id:`resolving-merge-conflicts`,command:`merge`,icon:`🔀`,titleKey:`tpl.sk.merge`,descKey:`tpl.sk.merge.desc`,promptKey:`tpl.sk.merge.prompt`},{id:`prototype`,command:`spike`,icon:`🔬`,titleKey:`tpl.sk.prototype`,descKey:`tpl.sk.prototype.desc`,promptKey:`tpl.sk.prototype.prompt`},{id:`research`,command:`research`,icon:`📚`,titleKey:`tpl.sk.research`,descKey:`tpl.sk.research.desc`,promptKey:`tpl.sk.research.prompt`}],_v=`pi-web-ui:prompt-templates`;function vv(){try{let e=localStorage.getItem(_v);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 yv(e){return gv.some(t=>t.id===e)}function bv(e){return typeof e.title==`string`}var xv=(0,Q.createContext)(null);function Sv(){let e=(0,Q.useContext)(xv);if(!e)throw Error(`useTemplates must be used within TemplateProvider`);return e}function Cv({children:e,currentModelId:t}){let n=W(),r=Me(`status`),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(``),c=(0,Q.useRef)(!1),l=(0,Q.useRef)(0),u=(0,Q.useCallback)(async e=>{if(c.current)return!1;c.current=!0,l.current++;try{let t=await fetch(d(`/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 a(n.templates),s(``),!0}catch(e){return s(String(e)),!1}finally{c.current=!1}},[]),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(r!==`open`)return;let e=!1,t=async()=>{if(c.current)return;let t=++l.current;try{let n=await fetch(d(`/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&&!c.current&&t===l.current&&(a(r.templates),s(``))}catch(n){!e&&!c.current&&t===l.current&&s(String(n))}};return(async()=>{let e=vv();if(e.length&&await u({action:`migrate`,templates:e}))try{localStorage.removeItem(_v)}catch{}await t()})(),window.addEventListener(`focus`,t),window.addEventListener(`online`,t),()=>{e=!0,window.removeEventListener(`focus`,t),window.removeEventListener(`online`,t)}},[u,r]);let S=(0,Q.useMemo)(()=>{let e=new Map,t=new Set;for(let n of i)n.hidden?t.add(n.id):(bv(n)&&!yv(n.id)||bv(n))&&e.set(n.id,n);let r=gv.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:t.command??``,prompt:r?.prompt??n(t.promptKey),builtin:!0}}),a=i.filter(e=>bv(e)&&!yv(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[...r,...a]},[i,n]),C=(0,Q.useCallback)(()=>p(!0),[]),w=(0,Q.useCallback)(e=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:e}))},[]),T=(0,Q.useCallback)((e,t=!1)=>{x(t),e?(_(!1),h({...e})):(_(!0),h({id:Tt(),icon:`📌`,title:``,desc:``,prompt:``}))},[]),E=(0,Q.useCallback)(()=>{p(!1),h(null),x(!1)},[]),D=(0,Q.useCallback)(()=>{v?(u({action:`reset`}),y(!1)):y(!0)},[v,u]);(0,Q.useEffect)(()=>{if(!v)return;let e=setTimeout(()=>y(!1),5e3);return()=>clearTimeout(e)},[v]);let O=(0,Q.useCallback)(e=>{p(!1),w(e.prompt)},[w]),k=(0,Q.useCallback)(e=>{p(!1),T(e,!0)},[T]),A=(0,Q.useCallback)(()=>{p(!1),T(void 0,!0)},[T]),j=(0,Q.useCallback)(async e=>{await u({action:`upsert`,template:e})&&(h(null),b&&(p(!0),x(!1)))},[b]),M=(0,Q.useCallback)(async e=>{await u(e.builtin?{action:`upsert`,template:{id:e.id,hidden:!0}}:{action:`remove`,id:e.id})&&(h(null),b&&(p(!0),x(!1)))},[b]),N=(0,Q.useCallback)(async e=>{await u({action:`remove`,id:e.id})&&(h(null),b&&(p(!0),x(!1)))},[b]),P=(0,Q.useMemo)(()=>({templates:S,fill:w,openPicker:C,openEdit:T,resetConfirm:v,toggleReset:D}),[S,w,C,T,v,D]),F=m?i.some(e=>e.id===m.id&&!e.hidden&&bv(e)):!1;return(0,$.jsxs)(xv.Provider,{value:P,children:[e,o&&(0,$.jsxs)(`div`,{className:`template-error`,role:`alert`,children:[n(`tpl.storageError`),`: `,o]}),f&&(0,$.jsx)(Ev,{templates:S,resetConfirm:v,onFill:O,onEditTpl:k,onNew:A,onResetToggle:D,onClose:E}),m&&(0,$.jsx)(Ov,{editing:m,isNew:g,hasOverride:F,storageError:o,templates:S,onDraft:h,onSave:j,onRestore:()=>N(m),onRemove:()=>M(m),onFill:()=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:m.prompt})),E()},onSend:()=>{let e=dv(m.prompt.trim());e&&X({type:`prompt`,text:e,queue:!1})&&(t&&qo(t),E())},onClose:E})]})}function wv(){let e=W(),{templates:t,fill:n,openEdit:r,toggleReset:i,resetConfirm:a}=Sv();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)(Tv,{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)(te,{})}),(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)(o,{}),e(a?`tpl.resetConfirm`:`tpl.reset`)]})})]})}function Tv({tpl:e,title:t,onFill:n,onEdit:r,editTitle:i}){let a=W();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)(fe,{})})]})}function Ev({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:i,onResetToggle:a,onClose:s}){let c=W();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&s()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:s,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:c(`tpl.pickerTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:c(`close`),onClick:s,children:(0,$.jsx)(Z,{})})]}),(0,$.jsx)(`div`,{className:`template-picker-hint`,children:c(`tpl.pickerHint`)})]}),(0,$.jsx)(`div`,{className:`template-picker-scroll`,children:(0,$.jsxs)(`div`,{className:`template-picker-grid`,children:[e.map(e=>(0,$.jsx)(Tv,{tpl:e,title:c(`tpl.clickCard`),onFill:()=>n(e),onEdit:()=>r(e),editTitle:c(`tpl.editTpl`)},e.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:i,title:c(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(te,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:c(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:c(`tpl.addDesc`)})]})]})]})}),(0,$.jsx)(`div`,{className:`template-picker-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:a,children:[(0,$.jsx)(o,{}),c(t?`tpl.resetConfirm`:`tpl.reset`)]})})]})})}var Dv=[`📌`,`🚀`,`⚡`,`📝`,`🔍`,`🛠️`,`🎯`,`💡`,`🤖`,`🌐`,`📦`,`🎨`,`🐛`,`🧪`,`✨`];function Ov({storageError:e,templates:t,editing:n,isNew:r,hasOverride:i,onDraft:a,onSave:o,onRestore:s,onRemove:c,onFill:l,onSend:u,onClose:d}){let f=W(),p=(0,Q.useRef)(null),m=(0,Q.useRef)(null),[h,g]=(0,Q.useState)(!1),_=(0,Q.useCallback)(()=>{let e=n.title.trim(),r=n.prompt.trim();if(!e||!r){a({...n,error:f(`tpl.required`)});return}let i=fv(n.command??``);if(i&&!pv(i)){a({...n,error:f(`tpl.commandInvalid`)});return}if(i&&t.some(e=>e.id!==n.id&&fv(e.command??``)===i)){a({...n,error:f(`tpl.commandDuplicate`)});return}o({id:n.id,command:i,icon:n.icon.trim()||`📌`,title:e,desc:n.desc.trim(),prompt:r})},[n,a,o,f,t]);(0,Q.useEffect)(()=>{let e=e=>{if(e.key===`Escape`){if(h){g(!1),e.stopPropagation();return}d()}else(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),_())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[d,h,_]),(0,Q.useEffect)(()=>{if(!h)return;let e=e=>{m.current&&!m.current.contains(e.target)&&g(!1)};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[h]),(0,Q.useEffect)(()=>{let e=p.current;if(!e)return;e.style.height=`auto`;let t=e.scrollHeight>340;e.style.height=`${Math.min(e.scrollHeight,340)}px`,e.style.overflowY=t?`auto`:`hidden`},[n.prompt]);let v=e=>{let t=p.current;if(!t){a({...n,prompt:n.prompt+e});return}let r=t.selectionStart??n.prompt.length,i=t.selectionEnd??n.prompt.length,o=n.prompt,s=o.slice(0,r)+e+o.slice(i);a({...n,prompt:s}),requestAnimationFrame(()=>{t.focus();let n=r+e.length;t.setSelectionRange(n,n)})},y=!!n.builtin&&!r;return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:d,children:(0,$.jsxs)(`div`,{className:`modal template-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-modal-head`,children:[(0,$.jsxs)(`div`,{className:`template-head-left`,ref:m,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-icon-btn`,title:f(`tpl.fieldIcon`),onClick:()=>g(e=>!e),children:(0,$.jsx)(`span`,{className:`template-modal-icon`,children:n.icon||`📌`})}),h&&(0,$.jsxs)(`div`,{className:`template-icon-dropdown`,children:[(0,$.jsx)(`div`,{className:`template-icon-grid`,children:Dv.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`template-icon-opt ${n.icon===e?`active`:``}`,onClick:()=>{a({...n,icon:e}),g(!1)},children:e},e))}),(0,$.jsx)(`div`,{className:`template-icon-custom`,children:(0,$.jsx)(`input`,{className:`template-icon-custom-input`,value:n.icon,maxLength:4,placeholder:`Emoji`,onChange:e=>a({...n,icon:e.target.value})})})]}),(0,$.jsx)(`input`,{className:`template-head-title-input`,value:n.title,placeholder:f(`tpl.fieldTitlePh`),onChange:e=>a({...n,title:e.target.value})}),(0,$.jsx)(`span`,{className:`template-modal-badge`,children:f(y?`tpl.builtin`:`tpl.custom`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:f(`close`),onClick:d,children:(0,$.jsx)(Z,{})})]}),(0,$.jsxs)(`div`,{className:`template-modal-body`,children:[(0,$.jsxs)(`div`,{className:`template-grid-2col`,children:[(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`div`,{className:`template-field-label-row`,children:(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldCommand`)})}),(0,$.jsxs)(`div`,{className:`template-cmd-input-wrap`,children:[(0,$.jsx)(`span`,{className:`template-cmd-prefix`,children:`/`}),(0,$.jsx)(`input`,{className:`template-field-input template-cmd-input`,value:n.command?n.command.replace(/^\//,``):``,placeholder:`pr`,onChange:e=>a({...n,command:e.target.value.replace(/^\//,``),error:void 0})})]})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`div`,{className:`template-field-label-row`,children:(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldDesc`)})}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.desc,placeholder:f(`tpl.fieldDescPh`),onChange:e=>a({...n,desc:e.target.value})})]})]}),(0,$.jsxs)(`div`,{className:`template-field template-prompt-field`,children:[(0,$.jsxs)(`div`,{className:`template-field-label-row`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldPrompt`)}),(0,$.jsxs)(`span`,{className:`template-field-subhint`,children:[n.prompt.length,` 字符`]})]}),(0,$.jsxs)(`div`,{className:`template-prompt-container`,children:[(0,$.jsxs)(`div`,{className:`template-prompt-toolbar`,children:[(0,$.jsx)(`span`,{className:`template-vars-label`,children:`插入变量:`}),(0,$.jsx)(`div`,{className:`template-vars-chips`,children:uv.map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`template-var-chip`,title:e.desc,onClick:()=>v(e.key),children:[`+ `,e.label]},e.key))})]}),(0,$.jsx)(`textarea`,{ref:p,className:`template-field-prompt`,value:n.prompt,placeholder:f(`tpl.fieldPromptPh`),onChange:e=>a({...n,prompt:e.target.value})})]}),(0,$.jsx)(`span`,{className:`template-picker-hint`,children:f(`tpl.commandHint`)})]})]}),(n.error||e)&&(0,$.jsx)(`div`,{className:`template-error`,role:`alert`,children:n.error||`${f(`tpl.storageError`)}: ${e}`}),(0,$.jsxs)(`div`,{className:`template-modal-actions`,children:[(0,$.jsxs)(`div`,{className:`template-modal-actions-left`,children:[!r&&y&&i&&(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn ghost`,title:f(`tpl.restoreTip`),onClick:s,children:f(`tpl.restore`)}),!r&&y&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:f(`tpl.removeTip`),onClick:c,children:[(0,$.jsx)(Ge,{}),` `,f(`tpl.remove`)]}),!r&&!y&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:f(`tpl.deleteTip`),onClick:c,children:[(0,$.jsx)(Ge,{}),` `,f(`tpl.delete`)]})]}),(0,$.jsxs)(`div`,{className:`template-modal-actions-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn`,onClick:_,children:f(`tpl.save`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn fill`,onClick:l,title:f(`tpl.fillTip`),children:f(`tpl.fill`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn send`,onClick:u,title:f(`tpl.sendTip`),children:[(0,$.jsx)(ce,{}),` `,f(`tpl.sendNow`)]})]})]})]})})}var kv=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 Av(e,t){return!e||e.length===0?null:(0,$.jsx)(`span`,{className:`slot-toolbar`,children:e.map((e,n)=>(0,$.jsx)(kv,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:jv(e,n,t)},`${e.id}#${n}`))})}function jv(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 Mv(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)(kv,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:jv(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 Nv=`#ffffff`,Pv=`#1e1e1e`,Fv=`.msg-actions, .msg-text-copy, .chead-copy, .stream-cursor, .msg-editor, .msg-collapse-btn, .msg-export-check, .toolcall-kill, .toolcall-open`,Iv=16384;function Lv(e,t=800,n=2){let r=Math.max(e,t,1);return r*n<=Iv?n:+(r<=Iv)}function Rv(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=Bv(t.trim())}else if(r.includes(`,`)){let e=r.split(`,`).map(e=>e.trim());e.length===4&&(a=Bv(e.pop())),i=e}else i=r.split(/\s+/).filter(Boolean),i.length===4&&(a=Bv(i.pop()));if(i.length!==3)return null;let o=zv(i[0]),s=zv(i[1]),c=zv(i[2]);return[o,s,c,a].some(e=>Number.isNaN(e))?null:{r:o,g:s,b:c,a}}function zv(e){return e.endsWith(`%`)?Math.round(Vv(Number.parseFloat(e),0,100)*2.55):Math.round(Vv(Number.parseFloat(e),0,255))}function Bv(e){return e.endsWith(`%`)?Vv(Number.parseFloat(e)/100,0,1):Vv(Number.parseFloat(e),0,1)}function Vv(e,t,n){return Math.min(n,Math.max(t,e))}function Hv(e){let t=Vv(Math.round(e.r),0,255),n=Vv(Math.round(e.g),0,255),r=Vv(Math.round(e.b),0,255);return e.a<.996?`rgba(${t}, ${n}, ${r}, ${Math.round(Vv(e.a,0,1)*1e3)/1e3})`:`rgb(${t}, ${n}, ${r})`}function Uv(e,t){let n=Vv(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 Wv(e,t){let n=Rv(t)??{r:255,g:255,b:255,a:1},r=Rv(e);return!r||r.a<=.004?Hv({...n,a:1}):Hv(Uv(r,{...n,a:1}))}function Gv(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 Kv(e){return Gv(e)>.45}function qv(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 Jv(){return getComputedStyle(document.documentElement).colorScheme.split(/\s+/).includes(`light`)?Nv:Pv}function Yv(e){let t=Jv(),n=t;try{n=Wv(qv(`var(--bg)`),t)}catch{n=t}try{let e=Wv(qv(`var(--card-bg, var(--msgs-bg, var(--bg)))`),n),t=Rv(e);if(t&&Gv(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=Wv(e,n),r=Rv(e);if(r&&r.a>.04)return t}r=r.parentElement}return n}function Xv(e){return e instanceof HTMLElement||e instanceof SVGElement?e.style:null}function Zv(e,t){let n=Rv(e);return n?n.a<=.004?`transparent`:n.a>=.996?Hv({...n,a:1}):Hv(Uv(n,{...Rv(t)??{r:255,g:255,b:255,a:1},a:1})):null}function Qv(e,t,n){let r=getComputedStyle(e),i=Xv(t),a=n;if(i){let e=Zv(r.backgroundColor,n);e===`transparent`?i.backgroundColor=`transparent`:e&&(i.backgroundColor=e,a=e);let t=Zv(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=Zv(r[e],a);t&&t!==`transparent`&&(i[e]=t)}let o=Zv(r.fill,a);o&&o!==`transparent`&&r.fill!==`none`&&(i.fill=o);let s=Zv(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++)Qv(o[e],s[e],a)}function $v(e){e.querySelectorAll(Fv).forEach(e=>e.remove())}function ey(e,t={}){t.includeThinking||e.querySelectorAll(`.thinking`).forEach(e=>e.remove()),t.includeTools||e.querySelectorAll(`.toolcall`).forEach(e=>e.remove())}function ty(e,t,n={}){let r=e.cloneNode(!0);return Qv(e,r,t),ey(r,n),$v(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 ny(e,t={}){let{toBlob:n}=await Qs(async()=>{let{toBlob:e}=await import(`./es-DWMIuDU2.js`);return{toBlob:e}},[],import.meta.url),r=t.backgroundColor??Yv(e),i=Rv(r),a=await n(e,{pixelRatio:t.pixelRatio??2,backgroundColor:r,cacheBust:!1,style:{colorScheme:i&&!Kv(i)?`dark`:`light`}});if(!a)throw Error(`toBlob returned null`);return a}function ry(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function iy(e){return document.querySelector(`.msg[data-msg-id="${ry(e)}"]`)??document.querySelector(`[data-msg-id="${ry(e)}"]`)}function ay(){let e=W(),t=bp(),[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),x=(0,Q.useRef)(`#ffffff`);if((0,Q.useEffect)(()=>{t.open&&(d(!1),h(!1),_(``))},[t.open]),wt(()=>{xp()},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=iy(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=Yv(s??void 0);x.current=c;let l=document.createDocumentFragment();for(let e of i)l.appendChild(ty(e,c,{includeThinking:t.includeThinking,includeTools:t.includeTools}));y.current.replaceChildren(l);let u=v.current;if(u){u.style.backgroundColor=c;let e=Rv(c);if(u.style.colorScheme=e&&!Kv(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 S=async()=>{let n=v.current;if(n&&!u&&t.selectedIds.length!==0){d(!0),_(``);try{let t=Lv(n.scrollHeight,n.scrollWidth);if(t===0){_(e(`exportTooLong`));return}let r=await ny(n,{backgroundColor:x.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:()=>xp(),children:(0,$.jsx)(Z,{})})]}),(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=>Cp({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=>Cp({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 S(),disabled:u||f||t.selectedIds.length===0,title:e(`copyImageBtn`),children:[u||f?(0,$.jsx)(xs,{className:`saveimg-spin`}):m?(0,$.jsx)(Pe,{}):(0,$.jsx)(b,{}),(0,$.jsx)(`span`,{children:e(u||f?`savingImage`:m?`copied`:`copyImageBtn`)})]})]})]}),g?(0,$.jsx)(`div`,{className:`saveimg-error`,children:g}):null]})]})}var oy=`.msg-text, .attachcard-content, .toolcall-output pre, .bashblock-output, .quote-content`,sy=`button, input, textarea, [contenteditable], .msg-meta, .msg-actions, .chead, .toolcall-output-label`;function cy(e){return e.nodeType===1?e:e.parentElement}function ly(e,t,n){if(!t||t.isCollapsed||t.rangeCount!==1)return null;let r=t.getRangeAt(0),i=cy(r.startContainer),a=cy(r.endContainer);if(!i||!a||!e.contains(i)||!e.contains(a)||!i.closest(oy)||!a.closest(oy)||i.closest(sy)||a.closest(sy))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(sy))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 uy({rootRef:e,sessionId:t,enabled:n=!0,onSelect:r}){let i=W(),[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=ly(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,Fn.createPortal)((0,$.jsxs)(`button`,{type:`button`,className:`quote-selection-button`,style:{left:a.left,top:a.top},onMouseDown:e=>e.preventDefault(),onClick:()=>{Gt({attachments:[{path:``,name:i(`quoteText`),mode:`quote`,quote:a.quote,key:Tt()}]})&&(o(null),window.getSelection()?.removeAllRanges(),cn())},children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),` `,i(`quoteSelection`)]}),document.body)}var dy=new Map,fy=new Set,py=new Map,my=15,hy=5,gy=100,_y=30,vy=1200,yy=2400,by=1600;function xy({kind:e,text:t,index:n,id:r,onRemoveQueued:i,onRecallQueued:a}){let o=W(),s=zs(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)(Ws,{quote:e},`quote-${t}`)),s.attachments&&s.attachments.length>0&&(0,$.jsx)(`div`,{className:`queued-attachments`,children:s.attachments.map((e,t)=>{let n=!!(e.path&&e.type!==`page`&&e.type!==`conversation`&&e.type!==`canvas`),r=!!(e.url||n),i=()=>{e.url?Pf({src:e.url.startsWith(`/`)?d(e.url):e.url,alt:e.name}):n&&e.path&&bl({path:e.path,name:e.name})};return(0,$.jsxs)(`span`,{className:`queued-att-chip${r?` previewable`:``}`,title:r?`${e.name} (${e.url?o(`toolImageZoom`):o(`fileOpenPreview`)})`:e.name,onClick:r?i:void 0,role:r?`button`:void 0,tabIndex:r?0:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,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)(Pl,{text:s.text,hardBreaks:!0}):null]})})]})}function Sy({compaction:e}){let t=W(),[,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 Cy(e){return e.content.some(e=>e.type===`toolCall`)}function wy(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 Ty(e){return Array.isArray(e.content)?e.content.some(e=>{let t=Ip(e);return t&&t.text.trim().length>0}):!1}function Ey(e){return e.role&&e.role!==`assistant`||e.customType||!Array.isArray(e.content)||e.content.length===0||Ty(e)?!1:e.content.some(e=>e.type===`toolCall`||e.type===`thinking`)}function Dy(e){return e.customType?!1:e.role===`assistant`||!e.role}function Oy(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=F_(a),s=Dy(a),c=Ey(a),l=!c&&!!i&&s&&!o&&t===e.length-1&&!Ty(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 ky(e,t=!1){return t?Math.max(48,Math.ceil(e.length/4)*30):Math.max(48,e.length*52)}var Ay=(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 jy({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,userPromptNonce:y,messageLabels:b,readOnly:x=!1,uiMessageActions:S,uiContextMessage:C,uiContextToolCall:w,uiToolCardFooter:T,uiChatEmpty:E,onUiAction:D}){let O=W(),k=bp(),A=(0,Q.useRef)(null),j=(0,Q.useRef)(!0),M=(0,Q.useRef)(!1),[N,P]=(0,Q.useState)(()=>new Set),[F,I]=(0,Q.useState)(!1),L=(0,Q.useMemo)(()=>e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,[e.messages,e.streamingMessage]),ee=(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]),R=(0,Q.useMemo)(()=>O_(e.messages),[e.messages]),te=(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]),[ne,re]=(0,Q.useState)(null),z=(0,Q.useMemo)(()=>{for(let e=L.length-1;e>=0;e--)if(L[e].role!==`system`)return L[e].id;return null},[L]),B=Math.min(gy,Math.max(hy,Math.floor(Number(d)||my))),ie=(0,Q.useMemo)(()=>{let t=new Set;for(let n of e.messages)n.role!==`toolResult`&&F_(n)&&!N.has(n.id)&&t.add(n.id);return t},[e.messages,N]),ae=R_(),V=(0,Q.useMemo)(()=>({mergeTurns:!0}),[]),[oe,se]=(0,Q.useState)(()=>{if(f||e.messages.length<=_y)return new Set;let t=H_(e.messages,new Map,Math.max(by,B*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Oy(e.messages,V))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);return n}),[ce,le]=(0,Q.useState)(()=>new Set),ue=(0,Q.useRef)(new Map),de=(0,Q.useRef)(new Map),fe=(0,Q.useRef)(new Map),pe=(0,Q.useRef)(0),H=(0,Q.useRef)(0),he=(0,Q.useRef)(0),ge=(0,Q.useRef)(null),U=Math.max(ae?240:60,B*2),_e=ae?120:30,ve=Math.min(U,10),[G,K]=(0,Q.useState)(()=>ve),q=`${e.conversationId??``}:${e.sessionFile??``}`,ye=(0,Q.useRef)(q),be=(0,Q.useRef)(L.length),xe=(0,Q.useRef)(L[0]?.id),Se=(0,Q.useRef)(null),J=(0,Q.useRef)(null),Ce=(0,Q.useRef)(!1),[we,Te]=(0,Q.useState)(!1),Ee=(0,Q.useRef)(!1),De=(0,Q.useCallback)(e=>{Ee.current=e,Te(e)},[]),Oe=(0,Q.useRef)(0),ke=(0,Q.useRef)(null),Ae=(0,Q.useCallback)(()=>{let e=A.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},[]),je=(0,Q.useCallback)(()=>{Oe.current&&=(cancelAnimationFrame(Oe.current),0),ke.current=null},[]),Me=(0,Q.useCallback)(()=>{let e=A.current,t=Ae();J.current={sh:e?e.scrollHeight:0,st:e?e.scrollTop:0,id:t?.id??null,top:t?.top??0,msgLen:L.length,firstId:L[0]?.id}},[Ae,L]),Y=(0,Q.useCallback)(e=>{let t=A.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)}},[]),Ne=(0,Q.useCallback)(()=>{let e=J.current,t=A.current;if(!t||!e)return;je(),De(!0),Y(e);let n=Ae();ke.current={id:n?.id??null,top:n?.top??0,sh:t.scrollHeight,st:t.scrollTop};let r=0,i=0,a=()=>{Oe.current=0;let e=A.current,t=ke.current;if(!e||!t){De(!1);return}if(Math.abs(e.scrollTop-t.st)>2){let t=Ae();ke.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),ke.current={...t,sh:e.scrollHeight,st:e.scrollTop};else{n=e.scrollHeight-t.sh;let r=Ae();n!==0&&(e.scrollTop+=n),ke.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){ke.current=null,De(!1);return}Oe.current=requestAnimationFrame(a)};Oe.current=requestAnimationFrame(a)},[je,Ae,Y,De]);ye.current!==q&&(ye.current=q,Se.current=null,K(ve),be.current=L.length,xe.current=L[0]?.id,J.current=null,je(),Ee.current&&De(!1),Ce.current=!1),(0,Q.useLayoutEffect)(()=>{let e=L.length-be.current;be.current=L.length;let t=L[0]?.id,n=t!==xe.current;xe.current=t,!(e<=0)&&(K(t=>t+e),n&&(Ce.current=!1))},[L.length]),(0,Q.useLayoutEffect)(()=>{let e=J.current;if(!e)return;let t=L[0]?.id!==e.firstId,n=L.length===e.msgLen&&!t;if(t||n){if(Ce.current&&n){Ne(),Me();return}J.current=null,Ne()}},[G]);let Pe=!!f&&!k.open&&!F;(0,Q.useEffect)(()=>{if(!Pe||G>=U)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{(0,Q.startTransition)(()=>K(e=>e<U?U:e))})});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[Pe,G,U,q]);let Fe=Pe?Math.min(L.length,G):L.length;(0,Q.useEffect)(()=>{Ce.current=!1},[e.historyStart,e.historyTotal]);let Ie=Math.max(0,e.historyStart??0),Le=(0,Q.useRef)(Ie);Le.current=Ie;let Re=Fh({isPagingActive:Pe,totalMessages:L.length,visibleCount:G,historyStart:Ie}),ze=!v&&!k.open&&!F&&Re>0,Be=Pe&&Fe<L.length?L.slice(-Fe):L,Ve=(0,Q.useCallback)(t=>{if(v||x||Ce.current)return;Ce.current=!0,je(),Me();let n=L[0]?.id,r=Le.current;X(t.all?{type:`load_earlier_messages`,all:!0,conversationId:e.conversationId??void 0,beforeId:n,before:r}:{type:`load_earlier_messages`,count:t.count??_e,conversationId:e.conversationId??void 0,beforeId:n,before:r}),setTimeout(()=>{Ce.current=!1},3e3)},[v,x,L,_e,je,Me,e.conversationId]),He=(0,Q.useCallback)(e=>{if(v)return;let t=e??_e;if(je(),Pe&&L.length-G>=t){Me(),K(e=>Math.min(L.length,e+t));return}Pe&&L.length>G&&(Me(),K(L.length)),Le.current>0&&Ve({count:t})},[Pe,L,G,Ve,_e,je,Me]),Ue=(0,Q.useRef)(ze);Ue.current=ze;let We=(0,Q.useRef)(He);We.current=He,(0,Q.useEffect)(()=>{let t=e.conversationId;if(!t||Se.current===t||!ze||v)return;let n=setTimeout(()=>{Se.current!==t&&(Se.current=t,Ue.current&&He())},150);return()=>clearTimeout(n)},[e.conversationId,ze,v,He]);let Ge=!v&&(F||k.open);(0,Q.useEffect)(()=>{Ge&&Le.current>0&&Ve({all:!0})},[Ge,Ve]);let Ke=(0,Q.useMemo)(()=>Oy(Be,V),[Be,V]),qe=!f&&e.messages.length>_y&&!F,Je=(0,Q.useRef)(qe);Je.current=qe;let Ye=(0,Q.useMemo)(()=>qe?H_(L,ue.current,Math.max(by,B*120)):fy,[qe,L,B]),Xe=(0,Q.useMemo)(()=>{let e=new Set(Ye);for(let t of Ke)t.type===`tool_cluster`&&t.messages.some(e=>Ye.has(e.id))&&e.add(t.id);return e},[Ye,Ke]),Ze=(0,Q.useRef)(Xe);Ze.current=Xe;let Qe=(0,Q.useMemo)(()=>{if(!qe)return py;let t=new Map;for(let n of e.messages)t.set(n.id,G_(n));for(let e of Ke)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},[qe,e.messages,Ke]),$e=(0,Q.useRef)(oe),et=oe,tt=(0,Q.useRef)(q);if(tt.current!==q){if(tt.current=q,fe.current.clear(),!f&&e.messages.length>_y){let t=H_(e.messages,ue.current,Math.max(by,B*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of Oy(e.messages,V))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);et=n,se(n),$e.current=n}else if(oe.size>0){let e=new Set;et=e,se(e),$e.current=e}}$e.current=et;let nt=(0,Q.useRef)(Qe);nt.current=Qe;let rt=wy((0,Q.useRef)({convKey:q,pending:null,finalizedMap:new Map}).current,q,e.messages,e.streamingMessage,(e,t)=>{let n=ue.current.get(e);n!==void 0&&!ue.current.has(t)&&ue.current.set(t,n)}),it=(0,Q.useCallback)((e,t,n)=>{n!==void 0&&(de.current.set(e,{h:t,len:n}),ue.current.set(e,t))},[]),at=(0,Q.useCallback)((e,t)=>{it(e,t,nt.current.get(e))},[it]),Z=(0,Q.useCallback)((t=!1)=>{let n=A.current;if(!n)return;if(!Je.current){se(e=>e.size?new Set:e);return}if(!t&&Math.abs(n.scrollTop-H.current)<200&&e.messages.length===he.current)return;H.current=n.scrollTop,he.current=e.messages.length;let r=n.getBoundingClientRect(),i={top:r.top-vy,bottom:r.bottom+vy},a={top:r.top-yy,bottom:r.bottom+yy},o=[];for(let[e,t]of fe.current){let n=t.getBoundingClientRect();o.push({id:e,top:n.top,bottom:n.bottom}),$e.current.has(e)||it(e,n.bottom-n.top,nt.current.get(e))}let s=B_(o,i,Ze.current,$e.current,a);for(let e of s.hide){let t=fe.current.get(e);t&&it(e,t.offsetHeight,nt.current.get(e))}se(e=>V_(e,s))},[it,e.messages.length]),ot=(0,Q.useCallback)(()=>{ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{ge.current=null,Z(!0)},120),!pe.current&&(pe.current=requestAnimationFrame(()=>{pe.current=0,Z(!1)}))},[Z]);(0,Q.useEffect)(()=>{ot()},[ot,e.conversationId,e.sessionFile,e.messages.length]);let st=(0,Q.useRef)(F);(0,Q.useLayoutEffect)(()=>{st.current&&!F&&Z(!0),st.current=F},[F,Z]);let ct=(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 Ke)e.type===`tool_cluster`&&t.add(e.id);for(let e of fe.current.keys())t.has(e)||(fe.current.delete(e),ue.current.delete(e),de.current.delete(e));se(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,Ke,N]),(0,Q.useEffect)(()=>()=>{cancelAnimationFrame(pe.current),je(),ge.current&&clearTimeout(ge.current)},[]);let lt=(0,Q.useMemo)(()=>{let t=[];for(let n of e.messages){if(n.role!==`user`)continue;let e=n.content.map(e=>Ip(e)?.text??``).filter(Boolean).join(` `),r=Df(e),i=r?r.userMessage??`skill:${r.name}`:e.trim();i&&t.push({id:n.id,text:i})}return t},[e.messages]),ut=(0,Q.useMemo)(()=>{let e=new Map;return lt.forEach((t,n)=>e.set(t.id,n)),e},[lt]),[dt,ft]=(0,Q.useState)(-1),pt=(0,Q.useRef)(-1),mt=(0,Q.useRef)(0),ht=(0,Q.useRef)(lt);(0,Q.useEffect)(()=>{ht.current=lt},[lt]);let gt=(0,Q.useCallback)(()=>{let e=A.current,t=ht.current;if(!e||t.length===0)return;if(j.current&&!M.current){let e=t.length-1;e!==pt.current&&(pt.current=e,ft(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!==pt.current&&(pt.current=r,ft(r))},[]),_t=(0,Q.useCallback)(()=>{mt.current||=requestAnimationFrame(()=>{mt.current=0,gt()})},[gt]);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(mt.current),[]),(0,Q.useEffect)(()=>{gt()},[lt,gt]);let vt=(0,Q.useCallback)(e=>{P(t=>t.has(e)?t:new Set(t).add(e))},[]);(0,Q.useLayoutEffect)(()=>{_p(e.messages.filter(hp).map(e=>({id:e.id,role:e.role,content:e.content})))},[e.messages]),(0,Q.useEffect)(()=>{if(k.open){for(let e of k.selectedIds)vt(e);le(e=>{let t=!1,n=new Set(e);for(let e of k.selectedIds)n.has(e)||(n.add(e),t=!0);return t?n:e})}},[k.open,k.selectedIds,vt]),(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(),I(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let yt=(0,Q.useCallback)(e=>{P(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),bt=(0,Q.useCallback)(e=>{if(Pe){let t=L.findIndex(t=>t.id===e);t!==-1&&t<L.length-G&&(0,Fn.flushSync)(()=>{K(L.length-t+5)})}(0,Fn.flushSync)(()=>{vt(e),le(t=>t.has(e)?t:new Set(t).add(e))});let t=ht.current.findIndex(t=>t.id===e);pt.current=t,ft(t),requestAnimationFrame(()=>{let t=A.current?.querySelector(`[data-msg-id="${e}"]`);t&&(A.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!==A.current?.lastElementChild&&(M.current=!0))})},[vt]),xt=(0,Q.useCallback)(t=>{let n=te.get(t);n&&r&&(bt(n),re({id:n,session:e.sessionFile}))},[te,r,bt,e.sessionFile]),[St,Ct]=(0,Q.useState)(null),wt=(0,Q.useRef)(null),Tt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let t=wt.current;if(!t||t.convId!==e.conversationId){wt.current={convId:e.conversationId,ids:new Set(e.messages.filter(e=>e.role===`compactionSummary`).map(e=>e.id))},Tt.current=null,Ct(null);return}for(let n of e.messages)if(n.role===`compactionSummary`&&!t.ids.has(n.id)){t.ids.add(n.id),Ct(n.id);break}},[e.messages,e.conversationId]),(0,Q.useEffect)(()=>{St&&Tt.current!==St&&(Tt.current=St,bt(St))},[St,bt]);let Et=(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(Et){bt(Et),h?.();return}e.sessionFile===m.path&&e.messages.length>0&&h?.()}},[Et,bt,h,m,e.sessionFile,e.messages.length]),(0,Q.useEffect)(()=>{if(!g)return;let t=Es(e.messages,g);if(t){bt(t),_?.();return}e.messages.length>0&&_?.()},[g,e.messages,bt,_]);let{railRef:Dt,stickBottom:Ot,scrollToBottom:kt,pauseForSelection:At,handleWheel:jt,handleTouchStart:Mt,handleTouchMove:Nt,handlePointerDown:Pt,onScroll:Ft}=lv({scrollRef:A,stickRef:j,escapedRef:M,messages:L,isStreaming:e.isStreaming,liveOutputs:t,toolStatuses:n,queue:e.queue,conversationId:e.conversationId,sessionFile:e.sessionFile,questions:lt,jumpTarget:m,urlJumpMessageId:g,hasEarlier:ze,loadEarlier:He,scheduleActiveFromScroll:_t,scheduleSweep:ot,userPromptNonce:y}),[It,Lt]=(0,Q.useState)(0),Rt=lt.length>0;(0,Q.useLayoutEffect)(()=>{let e=Dt.current;if(!e)return;let t=()=>Lt(e.clientHeight);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[Rt,Dt]),(0,Q.useEffect)(()=>(window.addEventListener(`resize`,ot),()=>window.removeEventListener(`resize`,ot)),[ot]);let{indices:zt,gap:Bt,many:Vt}=(0,Q.useMemo)(()=>k_(lt.length,It,dt),[lt.length,It,dt]);return(0,$.jsxs)(`div`,{className:`messages-wrap${k.open?` messages-exporting`:``}`,children:[(0,$.jsx)(uy,{rootRef:A,sessionId:e.sessionId,enabled:!k.open,onSelect:At}),(0,$.jsxs)(`div`,{className:`messages${F||we||Ot&&!M.current?``:` anchor-live`}`,ref:A,onScroll:Ft,onWheel:jt,onTouchStart:Mt,onTouchMove:Nt,onPointerDown:Pt,children:[e.messages.length===0&&!e.streamingMessage&&!p&&(0,$.jsxs)(`div`,{className:`empty-state`,children:[(0,$.jsx)(wv,{}),!x&&E&&E.length>0&&(0,$.jsx)(`div`,{className:`chat-empty-slots`,children:Av(E,D)})]}),Ke.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===z),f=o.messages.some(e=>ce.has(e.id)),p=o.messages.some(e=>Xe.has(e.id)),m=et.has(o.id),h=!ae&&!o.messages.every(Ey),g=!qe||d||f||p||!m,_=o.messages.filter(Ey).length>=4;return(0,$.jsx)(Ay,{id:o.id,show:g,placeholderHeight:K_(o.id,Qe.get(o.id)??-1,de.current,ky(o.messages,ae)),attachEl:ct,onMeasured:at,variant:ae?`flow`:h?`contents`:`trail`,children:o.messages.map(o=>{let s=(e.streamingMessage?o.id===e.streamingMessage.id:e.isStreaming&&o.id===z)&&(o.role===`assistant`||!o.role),d=rt.get(o.id)??o.id,f=_?s?l:!1:l;return(0,$.jsx)(qp,{uiMessageActions:S,uiContextMessage:C,uiContextToolCall:w,uiToolCardFooter:T,onUiAction:x?void 0:D,message:o,toolResults:ee,liveOutputs:Cy(o)?t:dy,toolStatuses:n,streaming:s,onKillBash:x?void 0:i,onRetry:!x&&o.id===z?a:void 0,toolsWrap:f,toolImages:u,thinkingWrap:c,isLast:o.id===z,onEdit:x?void 0:r,readOnly:x,messageLabel:b?.get(o.id),onRollbackEdit:xt,canRollbackEdit:!x&&!!r&&te.has(o.id),questionAttachments:R.get(o.id),editRequest:ne&&ne.session===e.sessionFile&&ne.id===o.id?ne:void 0,searchActive:F},d)})},`cluster-${rt.get(o.messages[0].id)??o.messages[0].id}`)}let s=o.message,d=F_(s);if(d&&!N.has(s.id))return(0,$.jsx)(A_,{message:s,onExpand:vt,summary:d.kind===`prompt`?O(`goalBarReviewing`):d.verdict===`pass`?O(`goalBarPassed`):O(`goalBarFailed`)},s.id);let f=s.role===`user`?ut.get(s.id):void 0,p=!qe||Xe.has(s.id)||ce.has(s.id)||!et.has(s.id),m=(e.streamingMessage?s.id===e.streamingMessage.id:e.isStreaming&&s.id===z)&&(s.role===`assistant`||!s.role),h=rt.get(s.id)??s.id;return(0,$.jsx)(z_,{id:s.id,show:p,height:K_(s.id,Qe.get(s.id)??-1,de.current,U_(s.role,s.customType)),containerRef:A,onMeasured:at,lazyRef:ct,children:(0,$.jsx)(qp,{uiMessageActions:S,uiContextMessage:C,uiContextToolCall:w,uiToolCardFooter:T,onUiAction:x?void 0:D,message:s,qnIndex:f,qnActive:f===void 0?void 0:f===dt,onJump:bt,toolResults:ee,liveOutputs:Cy(s)?t:dy,toolStatuses:n,streaming:m,onKillBash:x?void 0:i,onRetry:!x&&s.id===z?a:void 0,toolsWrap:l,toolImages:u,thinkingWrap:c,isLast:s.id===z,onEdit:x?void 0:r,readOnly:x,messageLabel:b?.get(s.id),onRollbackEdit:xt,canRollbackEdit:!x&&!!r&&te.has(s.id),editRequest:ne&&ne.session===e.sessionFile&&ne.id===s.id?ne:void 0,questionAttachments:R.get(s.id),onCollapse:d?yt:void 0,searchActive:F,autoExpand:s.id===St},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?O(`retryingApi`,{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):O(`retryingApiSoon`,{error:e.retry.errorMessage})})]}),e.compaction&&(0,$.jsx)(Sy,{compaction:e.compaction}),e.isStreaming&&L.length===0&&(0,$.jsx)(`div`,{className:`streaming-wait`,children:O(`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)(xy,{kind:`steer`,text:r,index:t,id:i,onRemoveQueued:x?void 0:o,onRecallQueued:x?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)(xy,{kind:`followUp`,text:r,index:t,id:i,onRemoveQueued:x?void 0:o,onRecallQueued:x?void 0:s},i||`q-fu-${t}`)}),!x&&e.actionSuggestions&&e.actionSuggestions.length>0&&(0,$.jsx)(`div`,{className:`action-suggestions`,"aria-label":O(`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:O(`actionSuggestionsTip`,{prompt:t.prompt}),disabled:e.isStreaming,onClick:()=>{kt(),X({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))})})]}),!Ot&&(0,$.jsxs)(`button`,{type:`button`,className:`scroll-bottom`,title:O(`backToBottom`),"aria-label":O(`backToBottom`),onClick:kt,children:[(0,$.jsx)(me,{}),(0,$.jsx)(`span`,{className:`scroll-bottom-label`,children:O(`backToBottom`)})]}),(0,$.jsx)(rv,{containerRef:A,messages:L,collapsedIds:ie,toolResults:ee,onExpand:vt,onProgrammaticScroll:()=>{At()},open:F,onClose:()=>I(!1)}),lt.length>0&&(0,$.jsxs)(`div`,{className:`qn-rail ${Vt?`many`:``}`,ref:Dt,"aria-label":O(`questionNavTitle`),style:{"--rail-gap":`${Bt}px`},children:[zt.map(e=>{let t=lt[e];return(0,$.jsx)(`button`,{type:`button`,className:`qn-bar ${e===dt?`active`:``}`,"aria-label":`${e+1}. ${t.text}`,onClick:()=>bt(t.id),children:(0,$.jsxs)(`span`,{className:`qn-bar-text`,children:[e+1,`. `,t.text]})},t.id)}),Vt&&(0,$.jsx)(`div`,{className:`qn-list`,children:lt.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`qn-list-item ${t===dt?`active`:``}`,"aria-label":`${t+1}. ${e.text}`,onClick:()=>bt(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)(ay,{})]})}function My(e,t){return t?e.trim()?`${e.replace(/\s+$/,``)}\n${t}`:t:e}function Ny(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 Py(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 Fy(e,t){return t?e?{key:t,clear:e!==t}:{key:t,clear:!1}:{key:e,clear:!1}}function Iy(e,t){if(t.length===0)return e;if(e.length===0)return[...t];let n=new Set(e.map(Py).filter(e=>e!==null)),r=[...e];for(let e of t){let t=Py(e);if(t!==null){if(n.has(t))continue;n.add(t)}r.push(e)}return r}function Ly(e,t,n,r,i=!1){return!e||!e.trim()?!1:!!(t||i)}function Ry(e,t){if(!t||!t.trim())return!1;let n=e.trim();return!(!n||n===t.trim())}function zy(e,t,n){switch(n){case`cancel`:return null;case`append`:return My(e,t);case`overwrite`:return t}}function By(e){let t=Number.parseFloat(getComputedStyle(e).lineHeight)||0;return t>0?Math.max(2,t/2):2}var Vy=`​`;function Hy(e,t,n=1){return{first:e<=n,last:Math.abs(t-e)<=n}}function Uy(e,t){return{first:!e.slice(0,t).includes(`
74
- `),last:!e.slice(t).includes(`
75
- `)}}var Wy=null;function Gy(){if(Wy?.isConnected)return Wy;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),Wy=e,e}function Ky(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 qy(e,t){e.textContent=t;let n=document.createElement(`span`);return n.textContent=Vy,e.appendChild(n),n.offsetTop}function Jy(e){let t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};let r=Uy(t,n);if(!r.first&&!r.last||typeof document>`u`||typeof getComputedStyle!=`function`)return r;let i=Gy();if(Ky(e,i)<=0)return r;let a=qy(i,t.slice(0,n)),o=qy(i,t),s=i.offsetHeight>0;return i.textContent=``,!s&&t!==``?r:Hy(a,o,By(e))}function Yy(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 Xy=`pi-web-ui:prompt-history`,Zy=`pi-web-ui:prompt-history-settings`,Qy={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function $y(e){let t=Qy;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 eb(){try{let e=localStorage.getItem(Zy);return e?$y(JSON.parse(e)):{...Qy}}catch{return{...Qy}}}function tb(e){let t=$y(e);try{localStorage.setItem(Zy,JSON.stringify(t))}catch{}try{let e=ib();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)),ab(e)}catch{}}function nb(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 rb(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 ib(){try{let e=localStorage.getItem(Xy);return e?nb(JSON.parse(e)):[]}catch{return[]}}function ab(e){let t=e;for(;t;)try{localStorage.setItem(Xy,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 ob(e){let t=e.trim();if(!t)return;let n=eb();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));let r=ib(),i=rb(r,t,n.maxEntries);i!==r&&ab(i)}function sb(){try{localStorage.removeItem(Xy)}catch{}}var cb=`skill:`,lb=/[\s\-_./:]/;function ub(e,t){let n=e.toLowerCase();return t===`skill`&&n.startsWith(`skill:`)?[n,n.slice(6)]:[n]}function db(e,t){let n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r===-1)return-1;if(r>0&&lb.test(t[r-1]))return r;n=r+1}return-1}function fb(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=db(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||lb.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||lb.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 pb(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=ub(i.name,i.source),o=null;for(let e of a){let t=fb(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 mb=new Set([`p`,`page`,`pages`,`web`,`网页`,`页面`]);function hb(e,t,n,r=10){if(!Array.isArray(t))return[];let i=String(n??``).toLowerCase(),a=i===``||mb.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 gb(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 _b(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 vb(e,t,n,r=15,i){if(!Array.isArray(t)||r<=0)return[];let a=String(n??``).toLowerCase(),o=a.startsWith(cb),s=o?a.slice(cb.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(cb.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 yb(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 bb(e){return e===void 0||!(e===`@`||/[A-Za-z0-9_]/.test(e))}function xb(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||!bb(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 Sb(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 Cb(){return typeof window>`u`||typeof navigator>`u`||typeof window.matchMedia!=`function`?!1:Sb({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}var wb=`pi-web-send-key`;function Tb(e,t){return e===`enter`||e===`mod-enter`?e:t?`mod-enter`:`enter`}function Eb(e){return e.key===`Enter`?Tb(e.pref,!!e.isTouch)===`enter`?e.shiftKey?`newline`:`send`:(e.ctrlKey||e.metaKey)&&!e.shiftKey?`send`:`newline`:`ignore`}function Db(){try{let e=localStorage.getItem(wb);return e===`enter`||e===`mod-enter`?e:null}catch{return null}}function Ob(e){try{localStorage.setItem(wb,e)}catch{}kb=e;for(let e of Ab)e()}var kb=null,Ab=new Set;function jb(e){return Ab.add(e),()=>{Ab.delete(e)}}function Mb(){return kb===null&&(kb=Db()),kb}function Nb(){return(0,Q.useSyncExternalStore)(jb,Mb)}function Pb(e=Cb()){return Tb(Nb(),e)}function Fb(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 Ib(e,t=0,n=Date.now()){return!!(e.isComposing||e.keyCode===229||t>0&&n-t<50)}function Lb(){let e=(0,Q.useRef)(0);return{onCompositionEnd:()=>{e.current=Date.now()},isImeKey:t=>Ib(t,e.current)}}var Rb=1;function zb(){return++Rb}var Bb=(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=W(),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=(f?.id??``).toLowerCase(),E=w.includes(`claude`)||w.includes(`gemini`)||w.includes(`sonnet`)||f?.provider===`anthropic`||f?.provider===`google`,D=w.includes(`r1`)||w.includes(`reasoner`)||w.includes(`qwq`),O=e?.availableThinkingLevels&&e.availableThinkingLevels.length>0?new Set(e.availableThinkingLevels):null,k=ka.map(e=>({value:e,label:Na(e,d(`thinking.${e}`),void 0,E),supported:!O||O.has(e)})),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(null),P=()=>{let e=parseInt(A.trim(),10);if(!Number.isFinite(e)||e<=0)return;N(e);let t=[{lvl:`minimal`,budget:1024},{lvl:`low`,budget:2048},{lvl:`medium`,budget:8192},{lvl:`high`,budget:16384},{lvl:`xhigh`,budget:32e3},{lvl:`max`,budget:64e3}].filter(e=>!O||O.has(e.lvl)),n=t[0]?.lvl??`medium`,r=1/0;for(let i of t){let t=Math.abs(i.budget-e);t<r&&(r=t,n=i.lvl)}l?l(n):X({type:`set_thinking`,level:n}),_(!1)},F=e=>M&&e!==`off`?`${d(`thinkingCustomized`)} (${M.toLocaleString()} tokens)`:k.find(t=>t.value===e)?.label??e,I=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{m||(I.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 L=(0,$.jsx)(Yo,{models:t,modelsLoading:n,providerKeys:i,defaultModel:a,currentModelId:p,active:m,onEnsureModels:()=>{I.current||t.length>0||n||(I.current=!0,C(!0),X({type:`list_models`})||C(!1))},loading:S,onRefresh:()=>{C(!0),X({type:`list_models`})},onManageModels:r?()=>{h(!1),r()}:void 0,onPickModel:(e,t)=>{if(c){c(e),h(!1);return}t&&!t.active&&X({type:`activate_provider_key`,provider:e.provider,keyName:t.name}),p!==e.id&&f?.id!==e.id&&X({type:`set_model`,modelId:e.id}),h(!1)},onToggleDefault:(e,t)=>{X(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}),ee=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:d(`thinkingLevel`)}),D&&(0,$.jsxs)(`div`,{className:`dd-item-notice`,style:{padding:`4px 10px`,fontSize:`11px`,opacity:.7},children:[`🧠 `,d(`thinkingFixedNotice`)]}),k.filter(e=>e.supported).map(t=>(0,$.jsx)(Et,{active:e?.thinkingLevel===t.value&&!M,onClick:()=>{if(N(null),l){l(t.value),_(!1);return}e?.thinkingLevel!==t.value&&X({type:`set_thinking`,level:t.value}),_(!1)},children:t.label},t.value)),!D&&(0,$.jsxs)(`div`,{className:`dd-custom-token-row`,children:[(0,$.jsx)(`div`,{className:`dd-custom-token-label`,children:(0,$.jsx)(`span`,{children:d(`thinkingCustomBudgetTitle`)})}),(0,$.jsxs)(`div`,{className:`dd-custom-token-group`,children:[(0,$.jsx)(`input`,{type:`number`,className:`dd-custom-token-input`,placeholder:d(`thinkingCustomBudgetPlaceholder`),value:A,onChange:e=>j(e.target.value),onKeyDown:e=>{e.key===`Enter`&&P()}}),(0,$.jsx)(`button`,{type:`button`,className:`dd-custom-token-btn`,onClick:P,children:d(`thinkingCustomBudgetBtn`)})]})]})]}),R=(0,$.jsx)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(T,{}),(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:L}),te=(0,$.jsx)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(be,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:d(`thinkingChip`,{level:e?F(e.thinkingLevel):`—`})})]}),tip:d(`thinkingLevel`),open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:ee});if(s===`model`)return R;if(s===`thinking`)return te;let ne=e?.thinkingLevel&&e.thinkingLevel!==`off`;return(0,$.jsxs)(`div`,{className:`model-thinking-capsule`,children:[(0,$.jsx)(Dt,{className:`capsule-dropdown capsule-model-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(T,{}),(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:L}),(0,$.jsx)(`div`,{className:`capsule-divider`}),(0,$.jsx)(Dt,{className:`capsule-dropdown capsule-thinking-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-pulse-dot ${ne?`on`:``}`}),(0,$.jsx)(`span`,{className:`capsule-thinking-text`,children:e?F(e.thinkingLevel):`—`})]}),triggerClassName:`capsule-segment capsule-thinking`,open:g,onOpenChange:_,align:`left`,portal:!0,direction:u,children:ee})]})}),Vb=[`standard`,`ptc`,`minimal`,`cordis`],Hb={standard:`preset.standard`,minimal:`preset.minimal`,code:`preset.code`,reader:`preset.reader`,ask:`preset.ask`},Ub={standard:`preset.standardDesc`,minimal:`preset.minimalDesc`,code:`preset.codeDesc`,reader:`preset.readerDesc`,ask:`preset.askDesc`};function Wb(e){return Hb[e]??null}function Gb(e){return Ub[e]??null}function Kb(e,t,n){let r=c(t),i=Wb(e.id),a=Gb(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 qb(e){return[...e].sort((e,t)=>{let n=Number.isSafeInteger(e.order)?e.order:Vb.indexOf(e.id),r=Number.isSafeInteger(t.order)?t.order:Vb.indexOf(t.id),i=n>=0?n:1e3,a=r>=0?r:1e3;return i===a?e.id.localeCompare(t.id):i-a})}var Jb=(0,Q.memo)(function({preset:e,presets:t,defaultPreset:n,blank:r,conversationId:i,compact:a=!1}){let o=W(),{locale:s}=st(),[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=qb(t),m=p.find(t=>t.id===e?.id),h=p.find(e=>e.id===u)??m,g=e=>Kb(e,s,o),_=m?g(m):void 0,v=t=>{d(t),l(!1),r&&t!==e?.id&&X({type:`dsh_preset_select`,preset:t})};if(a){let t=_?.description??m?.id??o(`dshPreset`);return(0,$.jsx)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ue,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:f?`${t}(${o(`dshPresetLocked`)})`:t,children:[_?.name??m?.id??e?.name??o(`dshPreset`),f&&(0,$.jsx)(re,{style:{marginLeft:3}})]})]}),open:c&&!f,onOpenChange:l,direction:`up`,align:`left`,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(Et,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>v(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)(ue,{}),o(`dshPreset`)]}),(0,$.jsx)(Dt,{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)(re,{}),` `,o(`dshPresetLocked`)]})]}),open:c&&!f,onOpenChange:l,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(Et,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>v(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:()=>{X({type:`new_chat`,preset:h?.id??u}),cn()},children:[(0,$.jsx)(te,{}),` `,o(`dshPresetNewChat`)]})]})}),Yb=[`read-only`,`workspace-write-never`,`danger-full-access`],Xb=[`read-only`,`workspace-write-never`,`danger-full-access`];function Zb(e){return e===`read-only`?`dshPermReadOnly`:e===`danger-full-access`?`dshPermFullAccess`:`dshPermWorkspaceWrite`}function Qb(e){return e===`read-only`?`dshPermReadOnlyDesc`:e===`danger-full-access`?`dshPermFullAccessDesc`:`dshPermWorkspaceWriteDesc`}var $b=(0,Q.memo)(function({current:e,options:t,defaultPreset:n,conversationId:r,compact:i=!1}){let a=W(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{l(!1),s(!1)},[r]);let u=Yb.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&&X({type:`dsh_permission_set`,preset:e})};if(i){let t=a(f?`dshPermCustom`:Zb(d)),r=f?e??t:a(Qb(d));return(0,$.jsxs)(Dt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(w,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r,children:[t,d===`danger-full-access`&&(0,$.jsx)(Ye,{style:{marginLeft:3}})]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},direction:`up`,align:`left`,children:[u.map(e=>(0,$.jsxs)(Et,{active:e===d,title:a(Qb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(Zb(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(Qb(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)(w,{}),a(`dshPerm`)]}),(0,$.jsx)(Dt,{trigger:(0,$.jsxs)(`span`,{title:f?e:a(Qb(d)),children:[a(f?`dshPermCustom`:Zb(d)),d===`danger-full-access`&&(0,$.jsxs)(`span`,{className:`dd-preset-tag warn`,children:[(0,$.jsx)(Ye,{}),` `,a(`dshPermFullAccessTag`)]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},children:u.map(e=>(0,$.jsxs)(Et,{active:e===d,title:a(Qb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(Zb(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(Qb(e))})]},e))}),c&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:a(`dshPermConfirmFull`)})]})}),ex=Cb(),tx=40,nx=320,rx=`pi-web-ui:composer-height`;function ix(){return typeof window>`u`?nx:Math.max(160,Math.min(nx,Math.floor(window.innerHeight*.42)))}var ax=(0,Q.memo)(function({groupDevices:e,groupReady:t,groupPrimaryBotName:n,groupConversationError:r,groupConversations:i=[],onGroupSend:a,onAbort:o,streaming:s,planMode:l,messages:u,slashCommands:d,modelState:f,models:m,modelsLoading:h,attachments:g,onRemoveAttachment:v,onAddImageFiles:y,onAddLocalFiles:b,onAddPathAttachment:x,fileSearch:S,onSearchFiles:C,onNotice:w,onSent:T,onManageModels:E,providerKeys:D,defaultModel:O,quickPhrases:k,quickPhrasesEnabled:A,recallDrafts:j,composerLeading:M,composerActions:N,onUiAction:F,dshPermCurrent:I,dshPermOptions:L,dshPermDefault:ee,dshPreset:R,dshPresets:te,dshPresetDefault:ne,dshBlank:re,conversationId:z,sessionDraft:B,sessionId:ie,preserveDraftAcrossConversations:ae=!1}){let V=W(),oe=Me(`ready`),se=e?!!t:oe,ce=G(),le=qe(),ue=!!(l&&le.planMode),{locale:de}=st(),fe=Pb(ex),me=fe===`mod-enter`,{openPicker:H,templates:he}=Sv(),ge=mv(he,d),U=[...d,...ge.map(e=>({name:fv(e.command??``),description:e.desc||e.title,source:`prompt`}))],_e=e=>!c(de)&&e.descriptionEn?e.descriptionEn:e.description??``,ve=e=>!c(de)&&e.argumentHintEn?e.argumentHintEn:e.argumentHint??``,[K,q]=(0,Q.useState)(``),[ye,be]=(0,Q.useState)(()=>{try{let e=Number(localStorage.getItem(rx));if(Number.isFinite(e)&&e>44)return Math.min(e,nx)}catch{}return null}),xe=(0,Q.useRef)(null),[Se,J]=(0,Q.useState)(null),[Ce,we]=(0,Q.useState)(0),Te=(0,Q.useRef)(0),Ee=(0,Q.useRef)(new Map),De=(0,Q.useRef)(``),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(void 0),Y=(0,Q.useRef)(null),Ne=(0,Q.useRef)(null),Pe=(0,Q.useRef)(null),Fe=(0,Q.useRef)(-1),Le=(0,Q.useRef)(``),[Re,ze]=(0,Q.useState)(!1),Be=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!j||j.length===0)return;let e=j.filter(e=>e.text&&e.seq>Be.current);e.length!==0&&(Be.current=e[e.length-1].seq,J(null),q(t=>{let n=e.reduce((e,t)=>My(e,t.text),t);return De.current=n,n}),Fe.current=-1,Le.current=``,requestAnimationFrame(()=>{let e=Y.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}))},[j]),(0,Q.useEffect)(()=>{if(!e)return zt(e=>{J(null),q(t=>{let n=My(t,e);return De.current=n,n}),Fe.current=-1,Le.current=``,requestAnimationFrame(()=>{let e=Y.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})}),()=>zt(null)},[]),(0,Q.useEffect)(()=>(Rt(()=>{ex||requestAnimationFrame(()=>{Y.current?.focus()})}),()=>Rt(null)),[]);let Ve=(0,Q.useRef)(``);Ve.current=K,(0,Q.useEffect)(()=>{if(!e)return Bt(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(Ve.current))return}let t=Y.current;if(!t){q(t=>{let n=t+(t&&!t.endsWith(` `)?` `:``)+e;return De.current=n,n});return}let n=t.selectionStart??Ve.current.length,r=t.selectionEnd??Ve.current.length,i=Ve.current,a=(n>0&&!/[\s([{]$/.test(i.slice(0,n))?` `:``)+e,o=i.slice(0,n)+a+i.slice(r);De.current=o,q(o);let s=n+a.length;requestAnimationFrame(()=>{t.focus(),t.selectionStart=t.selectionEnd=s})}),()=>Bt(null)},[]),(0,Q.useEffect)(()=>{if(!e)return Zt(e=>{q(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(),De.current=a,a})}),()=>Zt(null)},[]);let He=2e4,Ue=ie?`${z??``}${ie}`:null,We=Ue&&ie?`pi-web-ui:composer-draft:${ie}`:null,Ge=(0,Q.useRef)(``),Ke=(0,Q.useRef)(0),Je=(0,Q.useRef)(!1),Ye=(0,Q.useRef)(0),Xe=(0,Q.useRef)(null),Ze=(0,Q.useRef)(null),Qe=(0,Q.useRef)(null),$e=(0,Q.useRef)(ae);$e.current=ae;let et=Lb(),tt=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,He),ts:n.ts}}catch{return null}},nt=(t,n,r,i)=>{let a=r.slice(0,He);try{a.trim()?localStorage.setItem(n,JSON.stringify({text:a,ts:i})):localStorage.removeItem(n)}catch{}e||X({type:`draft_update`,sessionId:t,text:a,ts:i})},rt=()=>{Xe.current&&=(clearTimeout(Xe.current),null),Je.current&&Ue&&We&&ie&&Tt&&nt(ie,We,Ge.current,Ke.current)},it=(0,Q.useRef)(new Set),at=(0,Q.useRef)([]),Z=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(at.current=[],Z.current=Ve.current,e&&ie?.startsWith(`device-group:`))return Io(ie.slice(13),e=>{if(at.current.find(t=>t.member.id===e.id)){Y.current?.focus();return}let t=Y.current,n=Lo(Ve.current,t?.selectionStart??Ve.current.length,e);at.current=Ao(Ve.current,n.text,at.current),at.current.push({start:n.cursor-e.name.length-2,end:n.cursor-1,member:e}),Z.current=n.text,Ge.current=n.text,Ve.current=n.text,De.current=n.text,q(n.text),requestAnimationFrame(()=>{Y.current?.focus(),Y.current?.setSelectionRange(n.cursor,n.cursor)})})},[ie,!!e]);let ot=t=>{if(e){at.current=Ao(Z.current,t,at.current),Z.current=t;let n=new Set(Eo(t,e));for(let e of it.current)n.has(e)||it.current.delete(e)}if(Ge.current=t,Je.current=!0,Ke.current=Date.now(),We){let e=t.slice(0,He);try{e.trim()?localStorage.setItem(We,JSON.stringify({text:e,ts:Ke.current})):localStorage.removeItem(We)}catch{}}if(Ue&&ie&&Tt){Xe.current&&clearTimeout(Xe.current);let e=ie,t=We,n=Ke.current,r=Ue;Xe.current=setTimeout(()=>{Xe.current=null,r===Ze.current&&t&&nt(e,t,Ge.current,n)},2e3)}},ct=(e,t)=>{Fe.current=-1,q(e),dt(e,t),ot(e)};(0,Q.useEffect)(()=>{let e=Ue,t=ie,n=We;return()=>{Xe.current&&=(clearTimeout(Xe.current),null);let r=Ge.current;if(Je.current&&r.trim()){e&&t&&n&&nt(t,n,r,Ke.current);let i=Vt(),a=i>0&&Ke.current>i;Qe.current={text:r,userEditedAfterSwitch:a}}else Qe.current=null}},[Ue]),(0,Q.useEffect)(()=>{Ze.current=Ue;let e=Qe.current;Qe.current=null;let t=e?.text??null,n=e?.userEditedAfterSwitch??!1,r=We?tt(We):null,i=!!(B&&B.text?.trim()&&B.ts>0||r&&r.text?.trim());Ly(t,n,u.length,i,$e.current)&&t!==null&&We&&ie?(Je.current=!0,Ye.current=Date.now(),Ge.current=t,Ke.current=Ye.current,q(t),i||nt(ie,We,t,Ke.current)):(Je.current=!1,Ye.current=0,Ge.current=``,Ke.current=0,q(``)),J(null),Fe.current=-1},[Ue]);let lt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=u.length===0,t=lt.current!==null&&lt.current!==Ue,n=lt.current===null&&e;lt.current=Ue,se&&!ex&&(t||n)&&requestAnimationFrame(()=>{Y.current?.focus()})},[Ue,u.length,se]),(0,Q.useEffect)(()=>{if(!Ue||!We||Je.current||Ge.current!==``)return;let e=Ny(B&&B.text?{text:B.text.slice(0,He),ts:B.ts}:null,tt(We),Ye.current);e&&(Ye.current=e.ts,Ge.current=e.text,Ke.current=e.ts,q(e.text),dt(e.text,null))});let ut={builtin:V(`slashBuiltin`),extension:V(`slashExtension`),prompt:V(`slashPrompt`),skill:V(`slashSkill`),plugin:V(`slashPlugin`)},dt=(t,n)=>{De.current=t;let r=t.match(/^\/([^\s]*)$/);if(r&&se&&!e){let e=r[1].toLowerCase(),t=pb(U,e);J(t.length>0?{kind:`slash`,items:t}:null),we(0);return}if(n===null||!se){J(null);return}let a=xb(t,n);if(!a){J(null);return}if(e){let t=xo(e,i,a.query,c(de));J(t.length?{kind:`at`,start:a.start,end:n,items:t}:null),we(0);return}let o=[];try{o=an()}catch{o=[]}let s=++Te.current,l=t,u=a.start,f=a.query,p=u+1+f.length,m=o.map(e=>({id:e.id,label:e.label,run:()=>{let t;try{t=tn(e.id)?.search}catch{t=void 0}return typeof t==`function`?t(f):Promise.resolve([])}}));m.push({id:`host:canvases`,label:V(`canvasTab`),run:async()=>js(await Ms(()=>X({type:`canvas_list`})),f,V(`canvasTab`))}),f&&typeof C==`function`&&m.push({id:`host:files`,label:V(`openFiles`),run:()=>pt(f)});let h=[];if(le.pageRef&&(ir(),h=hb(V(`browserControl`),rr(),f),m.push({id:`host:pages`,label:V(`browserControl`),run:()=>Promise.resolve(h)})),m.length===0){J(null);return}let g=vb(V(`slashSkill`),d,f,15,_e),_=yb({pages:h,skills:g},f,30),v=!1;_.length>0&&(v=!0,J({kind:`at`,start:u,end:p,items:_}),we(0)),Promise.allSettled(m.map(e=>Promise.race([e.run(),new Promise((e,t)=>setTimeout(()=>t(Error(`at-mention timeout`)),2e3))]))).then(e=>{if(Te.current!==s||De.current!==l)return;let t=[],n=[],r=[],i=[];e.forEach((e,a)=>{e.status===`fulfilled`&&(m[a].id===`host:pages`&&Array.isArray(e.value)?n.push(...e.value):m[a].id===`host:canvases`&&Array.isArray(e.value)?t.push(...e.value):m[a].id===`host:files`?r.push(...gb(m[a].label,e.value)):i.push(..._b(m[a].id,m[a].label,e.value)))});let a=yb({canvases:t,pages:n,skills:g,files:r,plugins:i},f,30);J(a.length>0?{kind:`at`,start:u,end:p,items:a}:null),!v&&a.length>0&&we(0)})},pt=e=>{if(typeof C!=`function`)return Promise.resolve([]);let t=zb();return new Promise(n=>{Ee.current.set(t,n);try{C(t,e)}catch{Ee.current.delete(t),n([]);return}setTimeout(()=>{Ee.current.get(t)===n&&(Ee.current.delete(t),n([]))},3e3)})};(0,Q.useEffect)(()=>{if(!S||!S.ok)return;let e=Ee.current.get(S.reqId);e&&(Ee.current.delete(S.reqId),e(S.results??[]))},[S]);let ht=e=>dt(e,null);(0,Q.useEffect)(()=>{(Pe.current?.querySelector(`.slash-item.active`))?.scrollIntoView({block:`nearest`})},[Ce,Se]);let gt=e=>{let t=Se?.kind===`slash`?Se.items:[],n=e??t[Ce%Math.max(t.length,1)];if(!n){J(null);return}let r=K.match(/^\/([^\s]*)([\s\S]*)$/),i=r?r[2]:``,a=`/${n.name} ${i}`;De.current=a,q(a),ot(a),J(null),Y.current?.focus()},_t=(t,n)=>{let r=Se?.kind===`at`?Se:null,a=r?.items??[],o=t??a[Ce%Math.max(a.length,1)],s=n??r?.start;if(!o||s===void 0){J(null);return}let c=Y.current,l=c?c.selectionStart??K.length:K.length,u=r?.end!==void 0&&r.end>=s?r.end:l,d=o.attachments??[],f=o.providerId===`host:group-conversations`?i.find(e=>e.id===o.hint):void 0,p=e?.find(e=>o.providerId===`host:group-devices`?e.id===o.hint:e.id===f?.botId),m=o.text??(p?`@${p.name}`:o.title);e&&o.providerId===`host:group-devices`&&o.hint&&it.current.add(o.hint);let h=d.length>0&&!m.startsWith(`@`)?`@${m} `:`${m} `,g=`${K.slice(0,s)}${h}${K.slice(u)}`;De.current=g,q(g),ot(g),p&&at.current.push({start:s,end:s+m.length,member:p,conversationId:f?.id}),J(null);for(let e of d)try{x?.({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=Y.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=s+h.length)})},vt=()=>Se?.kind===`slash`?Se.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===Ce?` active`:``}`,onMouseEnter:()=>we(t),onClick:()=>bt(e),children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:ut[e.source]}),(0,$.jsxs)(`span`,{className:`slash-desc`,children:[_e(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:ve(e)})]})]},e.name)):null,yt=()=>Se?.kind===`at`?Se.items.map((t,n)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${n===Ce?` active`:``}`,onMouseEnter:()=>we(n),onClick:()=>bt(t),title:e?t.title:t.hint??t.title,children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`@`,t.title]}),(0,$.jsx)(`span`,{className:`slash-source ${t.providerId===`host:skills`?`skill`:`plugin`}`,children:t.providerLabel}),t.hint&&!e&&(0,$.jsx)(`span`,{className:`slash-desc`,children:t.hint})]},`${t.providerId}:${t.title}:${n}`)):null,bt=e=>{Se&&(Se.kind===`slash`?gt(e):_t(e,Se.start))},xt=async()=>{let e=[...u].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(`
76
- `);if(!e){w(`warning`,V(`slashCopyEmpty`));return}await Ec(e)?w(`info`,V(`slashCopied`)):w(`error`,V(`slashCopyFailed`))},St=t=>{if(e)return;if(!t||t.length===0){w(`warning`,V(`foldersNotSupported`));return}let n=Array.from(t).filter(e=>Af(e.type)),r=Array.from(t).filter(e=>!Af(e.type)),i=wt();n.length>0&&i?w(`warning`,i):n.length>0&&y(n),r.length>0&&b(r)},Ct=e=>{let t=Yy(e.clipboardData?.items,e.clipboardData?.files);t.length!==0&&(e.preventDefault(),St(t))},wt=()=>{let e=f?.model;if(!e?.id)return null;let t=m.find(t=>t.id===e.id);return t&&t.vision===!1?V(`modelNoVision`,{name:t.name}):null},Tt=se,Et=se&&!!ie,Dt=(0,Q.useRef)(K);(0,Q.useEffect)(()=>{Dt.current=K},[K]),(0,Q.useEffect)(()=>{!e&&/^\/[^\s]*$/.test(Dt.current)&&ht(Dt.current)},[d]);let[Ot,kt]=(0,Q.useState)(null),At=e=>{let t=Ot;if(kt(null),t===null)return;let n=zy(Dt.current,t,e);n!==null&&(J(null),De.current=n,q(n)),requestAnimationFrame(()=>Y.current?.focus())};(0,Q.useEffect)(()=>{if(e)return;let t=e=>{let t=e.detail;if(typeof t==`string`){if(Ry(Dt.current,t)){kt(t);return}J(null),De.current=t,q(t),Y.current?.focus()}};return window.addEventListener(`pi-web:fill`,t),()=>window.removeEventListener(`pi-web:fill`,t)},[]),(0,Q.useEffect)(()=>{if(!Oe&&Ot===null)return;let e=e=>{e.key===`Escape`&&(Ot===null?ke(!1):(kt(null),requestAnimationFrame(()=>Y.current?.focus())))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Oe,Ot]);let jt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Y.current,t=jt.current;if(!e||!t)return;let n=e.closest(`main`)?.querySelector(`.messages`),r=t.getBoundingClientRect().height,i=n?.scrollTop??0,a=ix();e.style.maxHeight=`${a}px`;let o=ye!=null&&ye>44,s;e.style.height=`auto`;let c=e.scrollHeight;s=Math.min(o?ye:Math.max(c,tx),a),e.style.height=`${s}px`,e.style.overflowY=c>s?`auto`:`hidden`,n&&(n.scrollTop=i+(t.getBoundingClientRect().height-r))},[K,ye]);let Mt=(0,Q.useRef)(null),Nt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Mt.current,t=Nt.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`)}},[g.length,A,k.length]);let Pt=()=>g.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}:{}}:{}}),Ft=()=>{if(We)try{localStorage.removeItem(We)}catch{}Xe.current&&=(clearTimeout(Xe.current),null),Je.current=!1,Ye.current=Date.now(),Ge.current=``,Ke.current=0},It=(0,Q.useRef)(!1),Lt=(t=!1)=>{let n=K.trim(),r=g.length>0;if(n||r){if(!Tt){w(`error`,V(`netDisconnected`));return}if(!Et){w(`warning`,V(`sessionInitializingNotice`));return}if(e){if(!a||It.current)return;let t;try{t=ko(at.current)}catch(e){w(`error`,e.message);return}It.current=!0;let r=jo(K,at.current);a(r.text.trim(),[...new Set([...r.targets,...Eo(n,e).filter(e=>it.current.has(e))])],t,{planOnly:Re}).then(e=>{e&&Ge.current.trim()===n&&(q(``),it.current.clear(),at.current=[],Z.current=``,Ft(),T())}).catch(e=>w(`error`,String(e))).finally(()=>{It.current=!1});return}if(!le.conversationRef&&g.some(e=>e.mode===`conversation`)){w(`warning`,c(de)?`当前底层智能体不支持跨对话引用(缺少 conversation_read 工具),请移除会话引用后再发送。`:`The current agent engine does not support conversation references (conversation_read tool unavailable). Remove conversation references before sending.`);return}if(n===`/help`){let e=Y.current?.closest(`.inputbox`)?.getBoundingClientRect();je(e?.width),ke(!0),q(``),Ft(),Y.current?.focus();return}if(n===`/copy`){q(``),Ft(),Y.current?.focus(),xt();return}if(X({type:`prompt`,text:hv(n,ge),queue:t,attachments:Pt()})){n&&ob(n),Fe.current=-1,Le.current=``,q(``),Ft(),T();let e=f?.model;e&&qo(`${e.provider}/${e.id}`),Y.current?.focus()}else w(`error`,V(`netDisconnected`))}},Ht=(t,n=!1)=>{if(e)return;let r=t.trim();if(r){if(!Tt){w(`error`,V(`netDisconnected`));return}if(!Et){w(`warning`,V(`sessionInitializingNotice`));return}if(X({type:`prompt`,text:r,queue:n,attachments:Pt()})){r&&ob(r),Fe.current=-1,Le.current=``,rt(),T();let e=f?.model;e&&qo(`${e.provider}/${e.id}`),ex||Y.current?.focus()}else w(`error`,V(`netDisconnected`))}},Ut=t=>{if(!et.isImeKey(t.nativeEvent)){if(Se&&Se.items.length>0){let e=Se.items.length;switch(t.key){case`ArrowDown`:t.preventDefault(),we(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),we(t=>(t-1+e)%e);return;case`Tab`:case`Enter`:t.preventDefault(),bt();return;case`Escape`:t.preventDefault(),J(null);return}}if(e&&(t.key===`Backspace`||t.key===`Delete`)&&!t.nativeEvent.isComposing){let e=Y.current;if(e){let n=Mo(K,e.selectionStart,e.selectionEnd,t.key,at.current);if(n){t.preventDefault();let r=K.slice(0,n.start)+K.slice(n.end);ot(r),q(r),Ve.current=r,requestAnimationFrame(()=>e.setSelectionRange(n.start,n.start));return}}}if(t.key===`Backspace`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=Y.current;if(e&&e.selectionStart===e.selectionEnd&&e.selectionStart>0){let n=e.selectionStart,r=Fb(K.slice(0,n),n,g);if(r&&r.tokenStart>=0&&r.tokenStart<n){t.preventDefault();let e=r.tokenStart,i=K.slice(0,e)+K.slice(n);De.current=i,q(i),requestAnimationFrame(()=>{Y.current&&(Y.current.selectionStart=Y.current.selectionEnd=e)});let a=r.attachment;a&&v(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=Y.current;if(!e)return;let n=t.key===`ArrowUp`,r=Jy(e);if(n&&!r.first||!n&&!r.last||!n&&Fe.current===-1)return;let i=ib();if(i.length===0)return;if(t.preventDefault(),n){if(Fe.current===-1){Le.current=K;let e=i.length-1;Fe.current=e;let t=i[e];q(t),ht(t),requestAnimationFrame(()=>{let e=Y.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else if(Fe.current>0){let e=Fe.current-1;Fe.current=e;let t=i[e];q(t),ht(t),requestAnimationFrame(()=>{let e=Y.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}}else{let e=Fe.current+1;if(e<i.length){Fe.current=e;let t=i[e];q(t),ht(t),requestAnimationFrame(()=>{let e=Y.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else{Fe.current=-1;let e=Le.current;q(e),ht(e),requestAnimationFrame(()=>{let t=Y.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}}return}if(t.key===`Escape`&&Fe.current!==-1){t.preventDefault();let e=Le.current;Fe.current=-1,q(e),ht(e),requestAnimationFrame(()=>{let t=Y.current;t&&(t.selectionStart=t.selectionEnd=e.length)});return}if(Eb({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,isTouch:ex,pref:fe})===`send`){t.preventDefault(),Lt();return}}},Wt=Et&&(K.trim()!==``||g.length>0),Gt=(0,Q.useMemo)(()=>Ki((N??[]).filter(e=>e.source!==`host`&&!e.hidden)),[N]),Kt=(0,Q.useMemo)(()=>(M??[]).filter(e=>e.source!==`host`&&!e.hidden),[M]),qt=N!==void 0,Jt=(0,Q.useMemo)(()=>Ki((N??[]).filter(e=>!e.hidden)),[N]),Yt=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=>F?.(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)(P,{}):e.icon===`camera`?(0,$.jsx)(Ie,{}):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:()=>F?.(e),children:t},e.id)},Xt=le.steer!==!1&&!ce,Qt=()=>(0,$.jsx)(`div`,{className:`inputbox-actions`,children:s?Wt?(0,$.jsxs)(`div`,{className:`split-send${Xt?``:` single`}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`split-queue`,title:V(`supplementTip`),"aria-label":V(`queueFollowTag`),onClick:()=>Lt(!0),children:(0,$.jsx)(mt,{})}),Xt&&(0,$.jsx)(`button`,{type:`button`,className:`split-steer`,title:V(me?`steerTipMod`:`steerTip`),"aria-label":V(`queueSteerTag`),onClick:()=>Lt(),children:(0,$.jsx)(ft,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`btn stop`,title:V(`stopAgent`),onClick:()=>o?o():X({type:`abort`}),children:(0,$.jsx)(pe,{})}):(0,$.jsx)(`button`,{type:`button`,className:`btn send`,title:V(Tt?Et?me?`sendTipMod`:`sendTip`:`sessionInitializingNotice`:`netDisconnected`),disabled:!Wt,onClick:()=>Lt(),children:(0,$.jsx)(ft,{})})}),$t={"host:composer-upload":(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:V(`uploadFile`),disabled:!Tt,onClick:()=>Ne.current?.click(),children:(0,$.jsx)(_,{})}),"host:composer-templates":(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:V(`tpl.openPicker`),onClick:H,children:(0,$.jsx)(p,{})}),"host:composer-model":(0,$.jsx)(Bb,{only:`model`,state:f,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,defaultModel:O,compact:!0}),"host:composer-thinking":(0,$.jsx)(Bb,{only:`thinking`,state:f,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,compact:!0}),"host:composer-dsh-perm":L&&L.length>0&&ee!==void 0?(0,$.jsx)($b,{compact:!0,current:I??null,options:L,defaultPreset:ee,conversationId:z??``}):null,"host:composer-dsh-preset":te&&te.length>0&&ne!==void 0?(0,$.jsx)(Jb,{compact:!0,preset:R??null,presets:te,defaultPreset:ne,blank:re??!1,conversationId:z??``}):null,"host:composer-send":Qt()},en=e=>e.source===`host`?(0,$.jsx)(Q.Fragment,{children:$t[e.id]??null},e.id):Yt(e);return(0,$.jsxs)(`div`,{ref:jt,className:`inputbar`,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault(),e.stopPropagation(),St(e.dataTransfer?.files??null)},children:[g.length>0&&(0,$.jsxs)(`div`,{className:`attach-row`,ref:Mt,children:[g.map(e=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(Ws,{quote:e.quote,onRemove:()=>v(e.key??``)},e.key);let t=!!(e.imageData||e.path&&/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.path)),n=!(!e.path||e.isDir||e.mode===`conversation`||e.mode===`page`||e.mode===`canvas`),r=!!(e.imageData||n),i=e.imageData?e.imageData.startsWith(`data:`)?e.imageData:`data:${e.mimeType??`image/png`};base64,${e.imageData}`:void 0,a=()=>{i?Pf({src:i,alt:e.name}):n&&e.path&&bl({path:e.path,name:e.name})},o=e.imageData?V(`attachImage`,{name:e.name}):e.fileData?V(`attachFile`,{name:e.name}):e.isDir?V(`folderRef`,{path:e.path}):e.mode===`page`?V(`attachPage`,{name:e.name}):e.mode===`canvas`?`${V(`canvasTab`)} · ${e.name}`:e.mode===`conversation`?V(`attachConversation`,{name:e.name}):e.mode===`reference`?V(`refOnly`,{path:e.path}):e.mode===`lines`&&e.lines?V(`attachLines`,{path:e.path,start:e.lines.start,end:e.lines.end}):V(`attachContent`,{path:e.path});return(0,$.jsxs)(`span`,{className:`attach-chip ${e.imageData?`image`:e.fileData?`file`:e.mode}${r?` previewable`:``}`,title:o+(r?` (${V(t?`toolImageZoom`:`fileOpenPreview`)})`:``),onClick:r?a:void 0,role:r?`button`:void 0,tabIndex:r?0:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),a())}:void 0,children:[i?(0,$.jsx)(`img`,{src:i,alt:e.name,className:`attach-thumb`}):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:V(`removeAttachment`),onClick:t=>{t.stopPropagation(),v(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:V(`attachHint`)})]}),Se&&Se.items.length>0&&(0,$.jsxs)(`div`,{className:`slash-menu`,role:`listbox`,ref:Pe,"aria-label":Se.kind===`slash`?V(`slashCommands`):V(`atMentions`),"data-menu-kind":Se.kind,children:[(0,$.jsxs)(`div`,{className:`slash-menu-hint`,children:[(0,$.jsx)(`span`,{children:Se.kind===`slash`?V(`slashMenuHint`):V(`atMenuHint`)}),(0,$.jsx)(`span`,{className:`slash-menu-close`,onClick:()=>J(null),children:`Esc`})]}),Se.kind===`slash`?vt():yt(),e&&Se.kind===`at`&&r&&(0,$.jsx)(`div`,{className:`slash-desc`,role:`status`,children:r})]}),Ot!==null&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>At(`cancel`),children:(0,$.jsxs)(`div`,{className:`slash-help`,role:`dialog`,"aria-modal":`true`,"aria-label":V(`tpl.confirmFillTitle`),style:{maxWidth:420},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`div`,{className:`slash-help-head`,children:(0,$.jsx)(`span`,{children:V(`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:V(`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:()=>At(`cancel`),children:V(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>At(`append`),children:V(`tpl.confirmFillAppend`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>At(`overwrite`),children:V(`tpl.confirmFillOverwrite`)})]})]})]})}),Oe&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>ke(!1),children:(0,$.jsxs)(`div`,{className:`slash-help`,style:Ae?{width:Ae}:void 0,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`slash-help-head`,children:[(0,$.jsxs)(`span`,{children:[`⚡ `,V(`slashHelpTitle`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>ke(!1),children:V(`close`)})]}),(0,$.jsx)(`div`,{className:`slash-help-body`,children:U.length===0?(0,$.jsx)(`div`,{className:`slash-help-empty`,children:V(`slashLoading`)}):U.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:ut[e.source]}),(0,$.jsxs)(`span`,{className:`slash-help-desc`,children:[_e(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:ve(e)})]})]},e.name))})]})}),A&&k.length>0&&(0,$.jsx)(`div`,{className:`quick-row`,"aria-label":V(`quickPhrases`),ref:Nt,children:k.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`quick-chip`,title:`${V(`quickPhrasesTip`,{text:e})}(${V(`quickPhrasesSendTip`)})`,disabled:!Tt,onClick:()=>Ht(e),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),Ht(e,!0)},children:e},e))}),(0,$.jsxs)(`div`,{className:`inputbox`,"data-pi-anchor":`composer`,children:[(0,$.jsx)(`div`,{className:`composer-resize${ye!=null&&ye>44?` is-manual`:``}`,"aria-label":V(ye!=null&&ye>44?`composerResizeFixed`:`composerResize`),role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":Math.round(ye??tx),"aria-valuemin":tx,"aria-valuemax":nx,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId);let t=Y.current?.getBoundingClientRect().height;xe.current={startY:e.clientY,startH:typeof t==`number`&&Number.isFinite(t)?t:ye??tx,next:null}},onPointerMove:e=>{let t=xe.current;if(!t)return;let n=ix(),r=Math.min(n,Math.max(tx,t.startH+(t.startY-e.clientY)));t.next=r,be(r<=44?null:r)},onPointerUp:()=>{let e=xe.current?.next;if(xe.current=null,e!=null)try{if(e<=44)be(null),localStorage.removeItem(rx);else{let t=Math.round(e);be(t),localStorage.setItem(rx,String(t))}}catch{}},onPointerCancel:()=>{xe.current=null},onDoubleClick:()=>{be(null);try{localStorage.removeItem(rx)}catch{}},children:(0,$.jsx)(`span`,{className:`composer-resize-tip`,children:V(ye!=null&&ye>44?`composerResizeFixed`:`composerResize`)})}),(0,$.jsx)(`input`,{ref:Ne,type:`file`,multiple:!0,hidden:!0,onChange:e=>{St(e.target.files),e.target.value=``}}),(0,$.jsx)(`textarea`,{ref:Y,value:K,rows:1,placeholder:e?n?c(de)?`直接发送给 ${n},或 @ 其他 Bot`:`Message ${n}, or @ another Bot`:c(de)?`输入 @,选择 Bot 开始新对话或继续之前的对话`:`Type @ to start or continue a Bot conversation`:V(Tt?s?ce?`placeholderStreamingQueued`:`placeholderStreaming`:ue?`placeholderPlanMode`:me?`placeholderIdleMod`:`placeholderIdle`:`placeholderConnecting`),disabled:!Tt,onChange:e=>{ct(e.target.value,e.target.selectionStart??e.target.value.length)},onSelect:e=>{if(Se?.kind===`at`){let t=e.target.selectionStart;(t<Se.start||t>Se.end)&&J(null)}},onCompositionEnd:et.onCompositionEnd,onBlur:rt,onKeyDown:Ut,onPaste:Ct}),ue&&(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:()=>X({type:`set_plan_mode`,enabled:!1}),title:V(`planModeTip`),children:[`📋 `,V(`planModeBadge`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),e&&Re&&(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:()=>ze(!1),title:c(de)?`群计划模式(只规划,不实施写操作)`:`Group plan mode (planning only)`,children:[`📋 `,c(de)?`群计划模式`:`Group Plan Mode`,` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),(0,$.jsx)(`div`,{className:`composer-tools`,children:e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn group-at-btn`,title:c(de)?`选择或 @ 群成员 Bot`:`Mention a Bot (@)`,onClick:()=>{let e=Y.current,t=e?e.selectionStart:K.length,n=K.slice(0,t)+`@`+K.slice(t);ct(n,t+1),e?.focus()},children:`@`}),(0,$.jsxs)(`button`,{type:`button`,className:`btn group-plan-toggle ${Re?`active`:``}`,title:c(de)?`群任务计划模式(只规划不实施)`:`Group task plan mode (plan only)`,onClick:()=>ze(e=>!e),children:[(0,$.jsx)(`span`,{className:`group-plan-icon`,children:`📋`}),(0,$.jsx)(`span`,{className:`group-plan-label`,children:c(de)?`只规划`:`Plan Only`})]})]}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Qt()})]}):qt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Kt.map(Yt),Jt.start.map(en)]}),Jt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:Jt.center.map(en)}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Jt.end.map(en)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Kt.map(Yt),(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:V(`uploadFile`),disabled:!Tt,onClick:()=>Ne.current?.click(),children:(0,$.jsx)(_,{})}),Gt.start.map(Yt),(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:V(`tpl.openPicker`),onClick:H,children:(0,$.jsx)(p,{})}),(0,$.jsx)(Bb,{state:f,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,defaultModel:O,compact:!0}),L&&L.length>0&&ee!==void 0&&(0,$.jsx)($b,{compact:!0,current:I??null,options:L,defaultPreset:ee,conversationId:z??``}),te&&te.length>0&&ne!==void 0&&(0,$.jsx)(Jb,{compact:!0,preset:R??null,presets:te,defaultPreset:ne,blank:re??!1,conversationId:z??``})]}),Gt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:Gt.center.map(Yt)}),(0,$.jsxs)(`div`,{className:`composer-tools-right`,children:[Gt.end.map(Yt),Qt()]})]})})]})]})}),ox=(0,Q.memo)(function({goal:e,models:t,modelsLoading:r,activeConversationId:i,uiGoalbarActions:a,onUiAction:o}){let l=W(),{locale:u}=st(),d=!c(u)&&e.statusEn?e.statusEn:e.status||``,f=!c(u)&&e.wizard?.statusEn?e.wizard.statusEn:e.wizard?.status||``,p=G(),m=qe(),h=!e.conversationId||e.conversationId===i,g=e.goal!==null&&h,_=h?e.roles?.executor:void 0,v=_?.convId,y=_?.activity?!c(u)&&_.activityEn?_.activityEn:_.activity:_?.streaming?`…`:void 0,b=e.locked&&e.maxRounds>0?e.maxRounds:0,x=b>0?c(u)?l(`goalBarRound`,{n:`${e.round}/${b}`}):`Round ${e.round}/${b}`:`${l(`goalBarRound`,{n:e.round})}${e.locked?` · ${l(`goalBarUnlimitedShort`)}`:``}`,C=(e.usage?.inputTokens??0)+(e.usage?.outputTokens??0),w=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,T=!p&&e.execModel===void 0,[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(e.reviewModel??``),[A,j]=(0,Q.useState)(e.maxRounds),[M,N]=(0,Q.useState)(e.locked),[P,F]=(0,Q.useState)(e.execModel??``),[I,L]=(0,Q.useState)(!1),[ee,R]=(0,Q.useState)(!1),[te,ne]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(!0);(0,Q.useEffect)(()=>{k(e.reviewModel??``),j(e.maxRounds||0),N(e.locked),F(e.execModel??``)},[e.goal,e.reviewModel,e.maxRounds,e.locked,e.execModel]),(0,Q.useEffect)(()=>{I&&t.length===0&&!z&&!r&&(B(!0),X({type:`list_models`}))},[I,t.length,z,r]),(0,Q.useEffect)(()=>{t.length>0&&B(!1)},[t.length]);let V=()=>O?t.find(e=>e.id===O)?.name??O:l(`goalBarUseMainModel`),oe=()=>P?t.find(e=>e.id===P)?.name??P:l(`goalBarUseMainModel`),se=()=>{let e=E.trim();e&&(X({type:`set_goal`,goal:e,...O?{reviewModel:O}:{},maxRounds:A,locked:M,...P?{execModel:P}:{}}),D(``),ae(!1))},ce=()=>{let e=E.trim();X({type:`set_plan_mode`,enabled:!0}),e&&(X({type:`prompt`,text:e}),D(``))},le=()=>{let e=E.trim();e&&(X({type:`start_goal_wizard`,text:e,...O?{wizardModel:O}:{},maxRounds:A,locked:M}),D(``),ae(!1))},ue=a===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`})):a.filter(e=>!e.hidden),de=e=>{let t=new Set(e);return ue.filter(e=>t.has(e.id)||e.source!==`host`)},fe=(e,t)=>{let n=ue.find(t=>t.id===e);return n?.labelExplicit?n.label:t},me={"host:goal-pill":(0,$.jsxs)(`button`,{type:`button`,className:`goalbar-hint`,title:l(`goalBarPlaceholder`),onClick:()=>ae(!1),children:[(0,$.jsx)(n,{}),` `,(0,$.jsx)(`span`,{children:fe(`host:goal-pill`,l(`goalBarTitle`))})]}),"host:goal-set":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn`,disabled:!E.trim(),onClick:se,children:fe(`host:goal-set`,l(`goalBarSet`))}),"host:goal-wizard":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action wizard`,disabled:!E.trim(),title:l(`goalWizardTip`),onClick:le,children:fe(`host:goal-wizard`,l(`goalWizardBtn`))}),"host:goal-plan":m.planMode?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action plan`,disabled:!E.trim(),title:l(`planActionTip`),onClick:ce,children:fe(`host:goal-plan`,l(`planActionBtn`))}):null,"host:goal-lock":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:l(M?`goalBarLocked`:`goalBarUnlocked`),onClick:()=>N(e=>(X({type:`set_goal_prefs`,locked:!e}),!e)),children:M?(0,$.jsx)(re,{}):(0,$.jsx)(Y,{})}),"host:goal-collapse":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:l(`goalBarClear`),onClick:()=>ae(!0),children:(0,$.jsx)(S,{})}),"host:goal-model":p?(0,$.jsx)(`p`,{className:`goalbar-dsh-note`,children:l(`dshNoReviewModel`)}):(0,$.jsx)(Dt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${l(`goalBarReviewModel`)}: ${V()}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-model`,l(`goalBarReviewModel`))}:`}),(0,$.jsx)(`b`,{children:V()})]}),open:I,onOpenChange:L,direction:`up`,children:(0,$.jsx)(Yo,{models:t,modelsLoading:r,currentModelId:O||null,active:I,onEnsureModels:()=>{t.length===0&&!r&&!z&&(B(!0),X({type:`list_models`}))},loading:z,onRefresh:()=>X({type:`list_models`}),onPickModel:e=>{k(e.id),L(!1),X({type:`set_goal_prefs`,reviewModel:e.id})},isRowActive:e=>Jo(e,O),extraTopRow:(0,$.jsx)(Et,{active:O===``,onClick:()=>{k(``),L(!1),X({type:`set_goal_prefs`,reviewModel:``})},children:l(`goalBarUseMainModel`)})})}),"host:goal-rounds":(0,$.jsxs)(`label`,{className:`goalbar-round`,title:l(`goalBarMaxRoundsTip`),children:[(0,$.jsx)(`span`,{children:fe(`host:goal-rounds`,l(`goalBarMaxRounds`))}),(0,$.jsx)(`input`,{type:`number`,min:0,step:1,value:A,placeholder:l(`goalBarUnlimitedShort`),onChange:e=>{let t=parseInt(e.target.value,10);if(Number.isNaN(t)||t<0){j(0);return}j(t)},onBlur:()=>X({type:`set_goal_prefs`,maxRounds:A}),onKeyDown:e=>{e.key===`Enter`&&(X({type:`set_goal_prefs`,maxRounds:A}),e.target.blur())}})]}),"host:goal-execmodel":p?null:(0,$.jsx)(Dt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${l(`goalBarExecModel`)}: ${oe()} · ${l(`goalBarExecModelTip`)}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${fe(`host:goal-execmodel`,l(`goalBarExecModel`))}:`}),(0,$.jsx)(`b`,{children:oe()})]}),open:ee,onOpenChange:R,direction:`up`,children:(0,$.jsx)(Yo,{models:t,modelsLoading:r,currentModelId:P||null,active:ee,onEnsureModels:()=>{t.length===0&&!r&&!z&&(B(!0),X({type:`list_models`}))},loading:z,onRefresh:()=>X({type:`list_models`}),onPickModel:e=>{F(e.id),R(!1),X({type:`set_goal_prefs`,execModel:e.id})},isRowActive:e=>Jo(e,P),extraTopRow:(0,$.jsx)(Et,{active:P===``,onClick:()=>{F(``),R(!1),X({type:`set_goal_prefs`,execModel:``})},children:l(`goalBarUseMainModel`)})})})},H=(e.wizard?.active??!1)&&h;if(H)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${H?`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:[l(`goalWizardRunning`),`: `,e.wizard?.draft]}),(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[l(`goalBarRound`,{n:(e.wizard?.step??0)+1}),` / `,e.wizard?.maxSteps??6]}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:f||l(`goalBarReviewing`)}),Mv(de([`host:goal-clear`]),{...me,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x`,title:l(`goalBarClear`),onClick:()=>{X({type:`clear_goal`}),ae(!0)},children:(0,$.jsx)(Z,{})})},o)]})});if(g)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`?l(`goalBarExecuting`):l(`goalBarReviewing`),` `,x]}):(0,$.jsx)(`span`,{className:`goalbar-chip ${e.verdict===`pass`?`pass`:e.verdict===`fail`?`fail`:e.verdict===`blocked`?`blocked`:``}`,children:e.verdict===`pass`?l(`goalBarPassed`):e.verdict===`fail`?l(`goalBarFailed`):e.verdict===`blocked`?l(`goalBarBlocked`):`${l(`goalBarRound`,{n:e.round||1})} · ${e.locked?l(`goalBarLocked`):l(`goalBarUnlocked`)}`}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:d}),y&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:_?.convId,children:[`· `,y]}),C>0&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:`${e.usage?.inputTokens??0} in / ${e.usage?.outputTokens??0} out`,children:[`· `,w(C),` tokens`]}),T&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:l(`goalBarStaleBackend`)}),Mv(de([`host:goal-openrole`,`host:goal-clear`]),{...me,"host:goal-openrole":v?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:l(`goalBarOpenExecTip`),onClick:()=>X({type:`switch_conversation`,id:v}),children:(0,$.jsx)(s,{})}):null,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x${e.reviewing?` stopping`:``}`,title:fe(`host:goal-clear`,e.reviewing?l(`goalBarStop`):l(`goalBarClear`)),onClick:()=>{e.goal&&D(e.goal),X({type:`clear_goal`}),ae(!1)},children:e.reviewing?(0,$.jsx)(pe,{}):(0,$.jsx)(Z,{})})},o)]})});if(ie){let e=Mv(de([`host:goal-pill`]),me,o);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)(n,{})}),(0,$.jsx)(`input`,{className:`goalbar-input`,autoFocus:!0,value:E,placeholder:l(`goalBarPlaceholder`),title:l(`goalBarPlaceholder`),onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&se()}}),Mv(de([`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`]),me,o)]}),(0,$.jsxs)(`div`,{className:`goalbar-opts`,children:[de([`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`]).filter(e=>e.source===`host`).map(e=>(0,$.jsx)(Q.Fragment,{children:me[e.id]},e.id)),e.history&&e.history.length>0&&(0,$.jsxs)(Dt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:l(`goalHistory`),children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${l(`goalHistory`)}:`}),(0,$.jsx)(`b`,{children:e.history.length})]}),open:te,onOpenChange:ne,direction:`up`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:l(`goalHistory`)}),e.history.map((e,t)=>(0,$.jsx)(Et,{onClick:()=>{D(e.goal),ne(!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:[l(`goalBarRound`,{n:e.rounds}),` · `,new Date(e.finishedAt).toLocaleString()]})})]})},`${e.finishedAt}-${t}`))]}),(0,$.jsx)(`span`,{className:`goalbar-lock-hint`,children:l(M?`goalBarLocked`:`goalBarUnlocked`)}),T&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:l(`goalBarStaleBackend`)})]})]})});function sx(e){return e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e}function cx(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 lx(e){return!!(e&&!e.error&&e.expectedRevision&&e.added.length+e.modified.length+e.deleted.length>0)}function ux({mode:e,currentCwd:t,currentSandbox:n,sandboxDiff:i,projects:a,send:o,onClose:s}){let c=W(),l=n?.sourcePath||(!n&&t?t:a.find(e=>!e.sandbox)?.path||t||``),[d,f]=(0,Q.useState)(l?`import`:`blank`),[p,m]=(0,Q.useState)(l),[h,g]=(0,Q.useState)(!0),[_,v]=(0,Q.useState)(``),y=n?.sourcePath?`${n.sourcePath}-exp`:`~/projects/${(n?.name||`sandbox-app`).replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-|-$/g,``)||`sandbox-app`}`,[b,x]=(0,Q.useState)(y),[S,C]=(0,Q.useState)(!0),[w,T]=(0,Q.useState)(null),E=()=>{if(!n)return;let e={requestId:Tt(),path:n.path};T(e),o({type:`diff_sandbox`,...e})};(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&s()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,Q.useEffect)(()=>{if(T(null),e===`apply`&&n?.path){let e={requestId:Tt(),path:n.path};T(e),o({type:`diff_sandbox`,...e})}},[e,n?.path,o]);let D=a.filter(e=>!e.sandbox),O=e=>{e.preventDefault();let t=d===`import`?p.trim():void 0;(d!==`import`||t)&&(o({type:`create_sandbox`,name:_.trim()||void 0,sourcePath:t,ephemeral:h}),s())},k=e=>{e.preventDefault();let t=b.trim();t&&(o({type:`promote_sandbox`,path:n?.path,targetPath:t,switchToTarget:S}),s())},A=e=>{e.preventDefault(),n?.path&&j&&lx(i)&&i.expectedRevision&&(T(null),o({type:`apply_sandbox_to_source`,path:n.path,expectedRevision:i.expectedRevision}),s())},j=e===`apply`&&cx(i,n,w),M=j?i.added.length+i.modified.length+i.deleted.length:0,N=c(e===`create`?`sandboxModalTitle`:e===`promote`?`sandboxPromoteTitle`:`sandboxApplyTitle`);return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:s,children:(0,$.jsxs)(`div`,{className:`modal sandbox-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,onClick:s,title:c(`close`),"aria-label":c(`close`),children:(0,$.jsx)(Z,{})}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:(0,$.jsx)(Zn,{})}),(0,$.jsx)(`h2`,{children:N})]}),e===`create`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:O,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:c(`sandboxModalSubtitle`)}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:c(`sandboxModeLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${d===`import`?`active`:``}`,onClick:()=>f(`import`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(I,{"aria-hidden":!0}),` `,c(`sandboxModeImport`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:c(`sandboxModeImportDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${d===`blank`?`active`:``}`,onClick:()=>f(`blank`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(Ne,{"aria-hidden":!0}),` `,c(`sandboxModeBlank`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:c(`sandboxModeBlankDesc`)})]})]})]}),d===`import`&&(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:c(`sandboxSourceLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:p,onChange:e=>m(e.target.value),placeholder:c(`sandboxSourcePlaceholder`),required:!0}),D.length>0&&(0,$.jsx)(`div`,{className:`sandbox-source-chips`,children:D.slice(0,6).map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-source-chip ${p===e.path?`active`:``}`,onClick:()=>m(e.path),title:e.path,children:[(0,$.jsx)(Je,{"aria-hidden":!0,style:{marginRight:4,verticalAlign:`-1px`}}),sx(e.path)]},e.path))})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:c(`sandboxLifecycleLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${h?`active`:``}`,onClick:()=>g(!0),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(vt,{"aria-hidden":!0}),` `,c(`sandboxLifecycleEphemeral`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:c(`sandboxLifecycleEphemeralDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${h?``:`active`}`,onClick:()=>g(!1),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(u,{"aria-hidden":!0}),` `,c(`sandboxLifecyclePermanent`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:c(`sandboxLifecyclePermanentDesc`)})]})]})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:c(`sandboxNameLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:_,onChange:e=>v(e.target.value),placeholder:d===`import`&&p.trim()?`${sx(p.trim())} (Sandbox)`:c(`sandboxNamePlaceholder`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:s,children:c(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:d===`import`&&!p.trim(),children:[(0,$.jsx)(Zn,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),c(`sandboxCreateSubmit`)]})]})]}):e===`promote`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:k,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:c(`sandboxPromoteSubtitle`,{name:n?.name||``})}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:c(`sandboxPromoteTargetLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:b,onChange:e=>x(e.target.value),placeholder:c(`sandboxPromoteTargetPlaceholder`),autoFocus:!0,required:!0})]}),(0,$.jsxs)(`label`,{className:`sandbox-checkbox-row`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>C(e.target.checked)}),(0,$.jsx)(`span`,{children:c(`sandboxPromoteSwitchLabel`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:s,children:c(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!b.trim(),children:[(0,$.jsx)(ge,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),c(`sandboxPromoteSubmit`)]})]})]}):(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:A,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:c(`sandboxActionApplyConfirm`,{name:n?.name||``,source:n?.sourcePath||``})}),j?i.error?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:i.error}):(0,$.jsxs)(`div`,{className:`sandbox-diff-box`,children:[(0,$.jsx)(`div`,{className:`sandbox-diff-stats`,children:c(`sandboxDiffStats`,{added:i.added.length,modified:i.modified.length,deleted:i.deleted.length,unchanged:i.unchangedCount})}),i.added.length+i.modified.length+i.deleted.length===0?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:c(`sandboxDiffEmpty`)}):(0,$.jsxs)(`div`,{className:`sandbox-diff-list`,children:[i.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}`)),i.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}`)),i.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:c(`sandboxDiffDeletedNote`)})]}):(0,$.jsx)(`div`,{className:`sandbox-diff-loading`,children:c(`loading`)}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:s,children:c(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:E,children:c(`sandboxDiffRefresh`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!j||!lx(i),children:[(0,$.jsx)(r,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),c(`sandboxApplySubmit`,{count:M})]})]})]})]})})}function dx(e,t){(0,Q.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&t()};e();let n=window.setInterval(e,3e4);return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.clearInterval(n),window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[e,t])}function fx({worktree:e,onRefresh:t,onSwitch:n,onRemove:r,onBack:i}){let a=W(),o=e?.linkedWorktrees??[],s=e?[{path:e.mainPath,branch:e.mainBranch,isMain:!0,isDirty:void 0},...o.map(e=>({...e,isMain:!1}))]:[];return e?.isLinkedWorktree&&!s.some(t=>t.path===e.currentPath)&&s.push({path:e.currentPath,branch:e.branch,isMain:!1,isDirty:void 0}),(0,$.jsxs)(`section`,{className:`worktree-view`,"aria-label":a(`worktreeViewTitle`),children:[(0,$.jsxs)(`div`,{className:`worktree-view-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:i,children:[(0,$.jsx)(ht,{}),a(`worktreeBackToChat`)]}),(0,$.jsx)(`h2`,{children:a(`worktreeViewTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,"aria-label":a(`worktreeRefresh`),title:a(`worktreeRefresh`),children:(0,$.jsx)(yt,{})})]}),(0,$.jsx)(`p`,{className:`worktree-view-hint`,children:a(`worktreeViewHint`)}),!e&&(0,$.jsx)(`p`,{children:a(`worktreeEmpty`)}),(0,$.jsx)(`div`,{className:`worktree-view-list`,children:s.map(t=>{let i=t.path===e?.currentPath,o=t.branch||a(`worktreeDetached`);return(0,$.jsxs)(`article`,{className:`worktree-card${i?` current`:``}`,children:[(0,$.jsxs)(`div`,{className:`worktree-card-title`,children:[(0,$.jsx)(q,{}),(0,$.jsx)(`strong`,{children:o}),i&&(0,$.jsx)(`span`,{className:`worktree-current`,children:a(`worktreeCurrent`)})]}),(0,$.jsx)(`div`,{className:`worktree-card-path`,children:t.path}),(0,$.jsxs)(`div`,{className:`worktree-card-actions`,children:[(0,$.jsx)(`span`,{className:t.isDirty?`worktree-dirty`:`worktree-status`,children:t.isMain?a(`worktreeMain`):t.isDirty===void 0?a(`worktreeBadgeLinked`):t.isDirty?a(`worktreeHasChanges`):a(`worktreeClean`)}),!i&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>n(t.path),children:t.isMain?a(`worktreeActionSwitchMain`):a(`worktreeSwitch`)})]}),!t.isMain&&(0,$.jsxs)(`details`,{className:`worktree-card-details`,children:[(0,$.jsx)(`summary`,{children:a(`worktreeManage`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn danger`,onClick:()=>{window.confirm(a(`worktreeActionRemoveConfirm`,{path:t.path}))&&r(t.path)},children:[(0,$.jsx)(Ge,{}),a(`worktreeActionRemove`)]})]})]},t.path)})})]})}var px=[{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 mx({chat:e,bottombarItems:t,onUiAction:n,onOpenSettings:r,onViewChange:i,onOpenGlobalSearch:a,onOpenBgTasks:o}){let s=Me(`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`})):px.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)(po,{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)(Ta,{open:!0,currentCwd:c.cwd,pathCompletions:e.pathCompletions,workspaceRoots:s,onClose:()=>u(!1),onSelectDirectory:e=>{e&&e!==c.cwd&&X({type:`set_cwd`,path:e}),u(!1)},mode:`folder`})]})}var hx=[{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}],gx=`__tray`,_x=[`start`,`center`,`end`];function vx(e,t){return e(t===`start`?`uiLayoutAlignTop`:t===`end`?`uiLayoutAlignBottom`:`uiLayoutAlignMiddle`)}function yx(e,t=new Set){let n={},r=[],i=new Set;for(let a of hx){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 bx(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 xx(e){return(e??[]).filter(e=>!e.hidden)}function Sx(e,t){let n=xx(e);return t===void 0?n:n.filter(e=>(e.align??`start`)===t)}function Cx(e){return[...new Set(e)]}function wx(e,t,n){let r=e??{},i=bx(t,n.id);if(!i)return r;let a={...r};i.hidden&&(a.hidden=(r.hidden??[]).filter(e=>e!==n.id),a.shown=Cx([...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=xx(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=Cx([...(r.order??[]).filter(e=>!p.has(e)&&e!==n.id),...u,...f]),a}function Tx(e,t){let n=e??{};return{...n,hidden:Cx([...n.hidden??[],t]),shown:(n.shown??[]).filter(e=>e!==t)}}function Ex({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:_,plugins:v,onOpenPluginMenu:y,isPluginMenuOpen:b}){let{t:x}=st(),[S,C]=(0,Q.useState)(!1),w=(0,Q.useRef)(null),T=n.settings?.uiLayout?.sideDockFloat===!0,E=T?` side-dock-float`:``,D=t.filter(e=>!e.hidden);if(D.length===0)return null;if(T&&S)return(0,$.jsx)(`div`,{ref:w,className:`side-dock side-dock-${e} side-dock-collapsed${E}`,children:(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-toggle-btn`,"data-tip":`${x(`sideDockExpand`)} (${D.length})`,onClick:()=>C(!1),"aria-label":x(`sideDockExpand`),children:e===`left`?(0,$.jsx)(g,{}):(0,$.jsx)(F,{})})});let O=Ki(D),k=t=>(0,$.jsx)(po,{entry:t,bar:e,chat:n,view:r,plugins:v,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenGlobalSearch:c,onOpenBgTasks:s,onOpenProjectPicker:d,onOpenPluginMenu:y,isPluginMenuOpen:b,onUiAction:l,uiContextEntries:u,zenMode:m,onToggleZenMode:h,dropdownProps:_},t.id);return(0,$.jsxs)(`div`,{ref:w,className:`side-dock side-dock-${e}${E}`,children:[T&&(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-collapse-btn`,"data-tip":x(`sideDockCollapse`),onClick:()=>C(!0),"aria-label":x(`sideDockCollapse`),children:e===`left`?(0,$.jsx)(F,{}):(0,$.jsx)(g,{})}),_x.map(e=>(0,$.jsx)(`div`,{className:`side-dock-slot side-dock-slot-${e}`,children:O[e].length>0&&(0,$.jsx)(`div`,{className:`side-dock-seg`,children:O[e].map(k)})},e))]})}function Dx(e){let t=e.trim().toLowerCase();return/^(yes|allow|approve|confirm|ok|是|允许|同意|确认|放行)/i.test(t)}function Ox(e){let t=e.trim().toLowerCase();return/^(no|deny|reject|cancel|block|否|拒绝|取消|阻止)/i.test(t)}function kx(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(`
77
- `),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(`
78
- `).trim(),n=r.slice(i,a+1).map(e=>e.startsWith(`$ `)?e.slice(2):e.startsWith(` `)?e.trimStart():e).join(`
79
- `).trim(),o=r.slice(a+1).join(`
80
- `).trim();if(n.length>0)return{hasRisk:t,intro:e,command:n,outro:o}}return{hasRisk:t,intro:e,command:null,outro:``}}function Ax({command:e,hasRisk:t}){let n=W(),{copied:i,copy:a}=Dc({duration:2e3}),[o,s]=(0,Q.useState)(!1),c=(0,Q.useMemo)(()=>e.split(`
81
- `),[e]),l=c.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)(Ye,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorRisk`)})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-head`,children:[(0,$.jsxs)(`div`,{className:`dialog-cmd-tag`,children:[(0,$.jsx)(Se,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorTitle`)}),(0,$.jsx)(`span`,{className:`dialog-cmd-badge`,children:n(`cmdInspectorLines`,{n:c.length})})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-actions`,children:[l&&(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>s(e=>!e),title:n(o?`cmdInspectorCollapse`:`cmdInspectorExpand`),children:[o?(0,$.jsx)(S,{}):(0,$.jsx)(A,{}),(0,$.jsx)(`span`,{children:n(o?`cmdInspectorCollapse`:`cmdInspectorExpand`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>{a(e)},title:n(`copy`),children:[i?(0,$.jsx)(r,{}):(0,$.jsx)(b,{}),(0,$.jsx)(`span`,{children:n(i?`cmdCopied`:`copy`)})]})]})]}),(0,$.jsx)(`div`,{className:`dialog-cmd-code ${o?`expanded`:``}`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:c.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 jx({text:e,structuredCode:t}){let n=(0,Q.useMemo)(()=>t?{hasRisk:t.hasRisk??!1,intro:e,command:t.content,outro:``}:kx(e),[e,t]);return n.command?(0,$.jsxs)(`div`,{className:`dialog-prompt dialog-body`,children:[n.intro&&(0,$.jsx)(Pl,{text:n.intro,rawHtml:!0,disableMath:!0}),(0,$.jsx)(Ax,{command:n.command,hasRisk:n.hasRisk}),n.outro&&(0,$.jsx)(Pl,{text:n.outro,rawHtml:!0,disableMath:!0})]}):(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(Pl,{text:e,rawHtml:!0,disableMath:!0})})}function Mx({dialog:e}){let t=W(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(0),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(``),u=t=>{X({type:`dialog_response`,id:e.id,value:t})};(0,Q.useEffect)(()=>{r(``),a(0),s(!1),l(``)},[e.id]),wt(()=>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(`
82
- `)[0].trim():``,h=d.some(Ox),g=d.find(Ox)??d[d.length-1]??`No`,_=()=>{let e=c.trim();e&&(Gt({text:`${t(`rejectFeedbackPrefix`)}${e}\n`}),cn()),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(Dx);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(Ox);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)(jx,{text:p,structuredCode:e.code}),e.kind===`confirm`&&(0,$.jsxs)($.Fragment,{children:[p&&(p.includes(`
83
- `)||p.length>50||!f||e.code)&&(0,$.jsx)(jx,{text:p,structuredCode:e.code}),f&&(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(Pl,{text:f,rawHtml:!0,disableMath:!0})})]}),e.kind===`input`&&(0,$.jsxs)($.Fragment,{children:[p&&(0,$.jsx)(jx,{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=Dx(e),r=Ox(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)(Pl,{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)(se,{}),(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 Nx(e){if(e.global&&e.owner&&e.conversationId)return{type:`open_shared_conversation`,owner:e.owner,id:e.conversationId};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 Px(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 Fx(e,t,n,r=[],i){let a=r.map(e=>({...e,global:!0,audience:`user`,createdAt:e.createdAt??0})),o=e=>Ix(e,a,i);if(e!==null)return o(e.filter(e=>e.audience===`user`));let s=[];for(let e of[t&&{...t,createdAt:0,audience:`user`},n&&{...n,conversationId:n.convId,createdAt:0,audience:`user`}])e&&(s.some(t=>t.id===e.id&&(`owner`in e?t.owner===e.owner:!e.conversationId||t.conversationId===e.conversationId))||s.push(e));return o(s)}function Ix(e,t,n){let r=new Map;for(let i of[...e.map(e=>n&&!e.owner?{...e,owner:n,global:!0}:e),...t])r.set(JSON.stringify([i.owner??``,i.id]),i);return[...r.values()]}function Lx(e){return JSON.stringify([e.owner??``,e.conversationId??``,e.id])}function Rx(e,t){return!!t&&(e.conversationId===t||e.rootConversationId===t)}var zx=150;function Bx({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),zx)},[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=fn(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,Fn.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 Vx=`pi_web_qdraft_`,Hx=864e5,Ux=new Map;function Wx(e){return`${Vx}${e}`}function Gx(e){if(!e)return null;try{if(typeof window<`u`&&window.sessionStorage){let t=window.sessionStorage.getItem(Wx(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>Hx?(qx(e),null):n}}}catch{}let t=Ux.get(e);return t?t.updatedAt&&Date.now()-t.updatedAt>Hx?(Ux.delete(e),null):t:null}function Kx(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){qx(e);return}let a={selections:{...t.selections},customs:{...t.customs},step:t.step,updatedAt:Date.now()};Ux.set(e,a);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.setItem(Wx(e),JSON.stringify(a))}catch{}}function qx(e){if(e){Ux.delete(e);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.removeItem(Wx(e))}catch{}}}function Jx({question:e,owner:t,conversationTitle:n,onDefer:r,onNavigate:i}){let a=W(),o=e.global?JSON.stringify([t,e.id]):e.id,s=e.conversationTitle||n,[c,l]=(0,Q.useState)(()=>Gx(o)?.selections??{}),[u,d]=(0,Q.useState)(()=>Gx(o)?.customs??{}),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi-web:question-auto-submit-last`)===`1`}catch{return!1}}),g=Lb(),[_,v]=(0,Q.useState)(()=>Gx(o)?.step??0),[y,b]=(0,Q.useState)(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1),[x,C]=(0,Q.useState)(Date.now),w=(0,Q.useRef)(!1),[T,E]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{w.current=!1;let t=Gx(o);t?(l(t.selections),d(t.customs),v(t.step)):(l({}),d({}),v(0)),p(!1);let n=e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1;b(n),C(Date.now())},[e.id,e.deadline,e.createdAt,t]),(0,Q.useEffect)(()=>{w.current||Kx(o,{selections:c,customs:u,step:_})},[e.id,c,u,_]),(0,Q.useEffect)(()=>{if(!e.deadline&&!e.createdAt)return;C(Date.now());let t=setInterval(()=>{let t=Date.now();C(t),e.deadline&&b(Math.max(0,Math.ceil((e.deadline-t)/1e3)))},1e3);return()=>clearInterval(t)},[e.id,e.deadline,e.createdAt]);let D=(0,Q.useCallback)(n=>{w.current=!0,qx(o),Am({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...e.global?{global:!0}:{},...n?.trim()?{cancelReason:n.trim()}:{},...t?{owner:t}:{}})},[e.id,t]);wt(()=>{r?r():D()},!f);let O=(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))},k=e.questions.filter(e=>O(e,c)),j=k.length;(0,Q.useEffect)(()=>{if(e.questions.length===0||j>0)return;let n=setTimeout(()=>{Am({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...e.global?{global:!0}:{},...t?{owner:t}:{}})},1500);return()=>clearTimeout(n)},[e.id,e.questions.length,j,t]);let M=Math.min(_,Math.max(0,j-1)),N=k[M];if(!N)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`)}),s&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:s,children:s}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:`cancel`),onClick:()=>r?r():D(),children:`✕`})]}),(0,$.jsx)(`div`,{className:`set-section`,children:(0,$.jsx)(`div`,{className:`set-hint`,children:a(`questionNoneAvailable`)})})]});let P=(()=>{if(!N)return[];if(N.optionsMap&&N.dependsOn){let e=c[N.dependsOn.questionId]??[];for(let t of e)if(N.optionsMap[t])return N.optionsMap[t]}return N.options??[]})(),F=n=>{w.current=!0,qx(o);let r=e.questions.filter(e=>O(e,n)).map(e=>{let t=n[e.id]??[],r=(u[e.id]??``).trim();return{id:e.id,selected:t,...r?{custom:r}:{}}});Am({type:`question_answer`,id:e.id,answers:r,...e.global?{global:!0}:{},...t?{owner:t}:{}})||E(!0)},I=(e,t)=>{l(n=>{let r=n[e]??[];return{...n,[e]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}})},L=(t,n,r)=>{if(r){I(t,n);return}let i=(c[t]??[]).includes(n),a={...c,[t]:i?[]:[n]};if(l(a),i)return;let o=e.questions.filter(e=>O(e,a)),s=o.findIndex(e=>e.id===t)+1;s<o.length?v(s):m&&F(a)},ee=()=>{M>=j-1?F(c):v(M+1)},R=t=>{let n=e.questions.find(e=>e.id===t);return P.length===0&&(n?.options?.length??0)===0||(c[t]?.length??0)>0||(u[t]??``).trim()!==``},te=P.filter(e=>(c[N.id]??[]).includes(e.label)&&e.preview).map(e=>e.preview),ne=(N.header||N.question).replace(/\s+/g,` `).trim(),re=(u[N.id]??``).trim(),z=Object.values(u).map(e=>e?.trim()).filter(Boolean).join(`;
84
- `),B=re.length>0||z.length>0,ie=re||z;return(0,Q.useEffect)(()=>{if(f)return;let e=e=>{let t=e.target;if(!(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable||g.isImeKey(e))&&!(e.key===`Enter`&&t?.closest?.(`button, select, label`))){if(e.key>=`1`&&e.key<=`9`){let t=parseInt(e.key,10)-1;if(t<P.length){e.preventDefault(),L(N.id,P[t].label,!!N.multiSelect);return}}if(e.key===`ArrowLeft`&&M>0){e.preventDefault(),v(M-1);return}if(e.key===`ArrowRight`&&M<j-1&&R(N.id)){e.preventDefault(),v(M+1);return}e.key===`Enter`&&R(N.id)&&(e.preventDefault(),ee())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f,P,N.id,N.multiSelect,M,j,R,ee,L]),(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`)}),s&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:s,children:s}),j>1&&(0,$.jsx)(`span`,{className:`question-progress`,children:a(`questionStep`,{cur:M+1,total:j})}),T&&(0,$.jsx)(`span`,{className:`question-timer`,title:`connection lost`,children:a(`questionQueuedOffline`)}),y>=0?(0,$.jsx)(`span`,{className:`question-timer`,children:y>0?a(`questionTimeout`,{s:y}):a(`questionTimeoutExpired`)}):Px(e.createdAt??0,x)?(0,$.jsxs)(`span`,{className:`question-timer question-queue-wait`,children:[`⏱ `,Px(e.createdAt??0,x)]}):null,f&&(0,$.jsx)(`span`,{className:`question-collapsed-preview`,title:ne,children:ne}),(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)(A,{})}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:B?`modelQuestionRejectWithNoteTip`:`cancel`),onClick:e=>{e.stopPropagation(),r?r():D(B?ie:void 0)},children:`✕`})]})]}),!f&&(0,$.jsxs)($.Fragment,{children:[j>1&&(0,$.jsx)(`div`,{className:`question-step-pills`,role:`tablist`,children:k.map((e,t)=>{let n=t===M,r=R(e.id),i=e.header||`${a(`modelQuestion`)} ${t+1}`;return(0,$.jsxs)(`button`,{type:`button`,className:`question-step-pill${n?` active`:``}${r?` done`:``}`,onClick:()=>v(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:N.header??`${a(`modelQuestion`)} ${M+1}`}),(0,$.jsx)(`div`,{className:`question-head`,children:(0,$.jsx)(Pl,{text:N.question,rawHtml:!0})}),N.detail&&(0,$.jsx)(`div`,{className:`set-hint`,children:(0,$.jsx)(Pl,{text:N.detail,rawHtml:!0})}),P.length>0&&(0,$.jsx)(`div`,{className:`set-list`,children:P.map((e,t)=>{let n=(c[N.id]??[]).includes(e.label),r=e.recommended??(t===0&&P.length>1),i=t<9?t+1:void 0;return(0,$.jsx)(Yx,{label:e.label,description:e.description,mark:N.multiSelect?n?`☑ `:`☐ `:n?`● `:`○ `,active:n,keyNumber:i,recommended:r,onPick:()=>L(N.id,e.label,!!N.multiSelect)},e.label)})}),te.length>0&&(0,$.jsxs)(`div`,{className:`question-preview`,children:[(0,$.jsx)(`div`,{className:`question-preview-label`,children:a(`optionPreview`)}),te.map((e,t)=>(0,$.jsx)(`div`,{className:`question-preview-body`,children:(0,$.jsx)(Pl,{text:e,rawHtml:!0})},t))]}),(0,$.jsx)(`input`,{className:`set-prompt-input question-custom`,placeholder:a(`modelQuestionCustom`),value:u[N.id]??``,onChange:e=>d(t=>({...t,[N.id]:e.target.value})),onCompositionEnd:g.onCompositionEnd,onKeyDown:e=>{g.isImeKey(e.nativeEvent)||e.key===`Enter`&&(e.preventDefault(),R(N.id)&&ee())}})]},N.id),(0,$.jsxs)(`label`,{className:`question-auto-submit`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>{let t=e.target.checked;h(t);try{localStorage.setItem(`pi-web:question-auto-submit-last`,t?`1`:`0`)}catch{}}}),(0,$.jsx)(`span`,{children:a(`questionAutoSubmitLast`)}),m&&M===j-1&&!N.multiSelect&&P.length>0&&(0,$.jsx)(`span`,{className:`question-auto-submit-hint`,children:a(`questionPickSubmits`)})]}),(0,$.jsxs)(`div`,{className:`dialog-nav`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss-inline${B?` reject-note`:``}`,onClick:()=>D(B?ie:void 0),title:a(B?`modelQuestionRejectWithNoteTip`:`cancel`),children:a(B?`modelQuestionRejectWithNote`:`cancel`)}),(0,$.jsxs)(`div`,{className:`dialog-nav-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-prev`,disabled:M===0,onClick:()=>v(M-1),children:a(`previous`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-submit`,disabled:!R(N.id),onClick:ee,children:M===j-1?a(`modelQuestionSubmit`):a(`next`)})]})]})]})]})}function Yx({label:e,description:t,mark:n,active:r,keyNumber:i,recommended:a,onPick:o}){let s=(0,Q.useRef)(null),c=W();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)(Pl,{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)(Pl,{text:t,rawHtml:!0})}),(0,$.jsx)(Bx,{anchorRef:s,enabled:un(),className:`question-desc-tip`,children:(0,$.jsx)(Pl,{text:t,rawHtml:!0})})]})]})}function Xx({items:e,itemKey:t,title:n,summary:r,canAutoOpen:i,createdAt:a,onNavigate:o,canNavigate:s,children:c}){let l=W(),[u,d]=(0,Q.useState)(()=>new Set),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(Date.now),g=Ds(e,t,f,u,i),_=g?t(g):null;(0,Q.useEffect)(()=>{p(_)},[_]);let v=e.some(e=>a(e)>0);if((0,Q.useEffect)(()=>{if(!v)return;h(Date.now());let e=setInterval(()=>h(Date.now()),1e3);return()=>clearInterval(e)},[v]),!e.length)return null;let y=e.filter(e=>e!==g);return(0,$.jsxs)(`section`,{className:`question-queue`,"aria-label":n,children:[y.length>0&&(0,$.jsxs)(`div`,{className:`question-queue-list`,children:[(0,$.jsxs)(`div`,{children:[n,` · `,e.length]}),y.map(e=>(0,$.jsxs)(`div`,{className:`question-queue-item`,children:[(0,$.jsx)(`div`,{className:`question-queue-summary`,children:r(e)}),Px(a(e),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,Px(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,$.jsx)(`div`,{className:`question-queue-dialog`,children:c(g,()=>{d(e=>new Set(e).add(t(g))),p(null)})},_)]})}function Zx({questions:e,activeConversationId:t,mode:n}){let r=W(),i=e=>{let t=Nx(e);t&&X(t)};return(0,$.jsx)(Xx,{items:e.filter(e=>e.audience===`user`),itemKey:Lx,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`&&(e.global||n===`all`||e.conversationId===t||!e.conversationId),onNavigate:i,canNavigate:e=>!!(e.rootConversationId||e.conversationId)&&(!!e.owner||(e.conversationId?e.conversationId!==t:!Rx(e,t))),children:(e,t)=>(0,$.jsx)(Jx,{question:e,owner:e.owner,onDefer:t,onNavigate:e.rootConversationId||e.conversationId?()=>i(e):void 0},Lx(e))})}function Qx({entry:e}){let t=(0,Q.useRef)(null),n=W();return(0,Q.useEffect)(()=>{let r=t.current;if(!r)return;let{container:i,cleanup:a}=Qm(r,{isolated:!!(e.info.isolated||e.module.isolated||e.module.shadow)}),o;try{o=e.module.mount(i,Sh(e.info.id,e=>X(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 $x({pluginId:e,info:t,epoch:n,failed:r}){let i=W(),[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),fh(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 eS({onAction:e}){let t=oa(),n=(0,Q.useMemo)(()=>t?pa(t.entries):[],[t]),{items:r,selectParents:i}=(0,Q.useMemo)(()=>fa(n),[n]),a=(0,Q.useMemo)(()=>ma(r),[r]),o=(0,Q.useMemo)(()=>typeof window>`u`?!1:a.length>14&&window.innerWidth>=640,[a.length]),s=(0,Q.useMemo)(()=>t?la(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?pa(r[m]?.children??[]):[],[r,m]),C=(0,Q.useMemo)(()=>ma(S),[S]),w=e=>{let n=r[e];if(t&&n&&!da(n,s)){if(n.children?.length){h(e);return}T(n,t)||ra()}},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=ga(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(ca(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)||ra()},r=t=>{e(t.target)||ra()},i=()=>ra();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=ga(r,b.current,e,s);b.current=t,p(t)},n=t=>{switch(t.key){case`Escape`:t.preventDefault(),ra();return;case`Tab`:ra();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(da(n.parent,s))return;t&&!T(n.parent,t,n.value)&&ra();return}da(e,s)||T(e,t)||ra()},O=(e,t,n)=>{let r=da(e,s),i=!!e.children?.length,a=va(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,Fn.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 tS=0,nS=[],rS=new Map,iS=new Set;function aS(){for(let e of iS)try{e()}catch{}}function oS(e){let t=rS.get(e);t!==void 0&&(clearTimeout(t),rS.delete(e))}function sS(e){let t=e.id||`banner-${Date.now()}-${++tS}`,n={...e,id:t,type:e.type||`info`,persistent:!!e.persistent,timeoutMs:e.timeoutMs??5e3,dismissible:e.dismissible!==!1};if(oS(t),!n.persistent&&n.timeoutMs&&n.timeoutMs>0){let e=setTimeout(()=>{cS(t)},n.timeoutMs);rS.set(t,e)}let r=nS.findIndex(e=>e.id===t);if(r>=0){let e=[...nS];e[r]=n,nS=e}else nS=[...nS,n];return aS(),t}function cS(e,t){oS(e);let n=nS.find(t=>t.id===e);if(n){if(nS=nS.filter(t=>t.id!==e),!t?.silent)try{n.onClose?.()}catch{}aS()}}function lS(e,t){let n=nS.filter(e);if(n.length!==0){for(let e of n)if(oS(e.id),!t?.silent)try{e.onClose?.()}catch{}nS=nS.filter(t=>!e(t)),aS()}}function uS(){return nS}function dS(e){return iS.add(e),()=>{iS.delete(e)}}function fS(){return(0,Q.useSyncExternalStore)(dS,uS,uS)}function pS({type:e}){switch(e){case`question`:return(0,$.jsx)(Xe,{className:`banner-icon banner-icon-question`});case`warning`:return(0,$.jsx)(Ye,{className:`banner-icon banner-icon-warning`});case`error`:return(0,$.jsx)(Ce,{className:`banner-icon banner-icon-error`});case`success`:return(0,$.jsx)(Pe,{className:`banner-icon banner-icon-success`});default:return(0,$.jsx)(Oe,{className:`banner-icon banner-icon-info`})}}var mS=(0,Q.memo)(function({banner:e}){let t=W(),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)(pS,{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(),cS(e.id)},"aria-label":`Close banner`,title:t(`close`),children:(0,$.jsx)(Z,{})})]})}),hS=(0,Q.memo)(function(){let e=fS();return e.length===0?null:(0,$.jsx)(`aside`,{className:`banner-container`,"aria-label":`Notifications`,children:e.map(e=>(0,$.jsx)(mS,{banner:e},e.id))})});function gS({slots:e,layout:t,exclude:n,onClose:r}){let i=W(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useMemo)(()=>yx(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`?Tx(n,e):wx(n,f.current,{id:e,slot:t.slot,...t.align===void 0?{}:{align:t.align},index:t.index});m.current=r,X({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]),wt(()=>{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:Ia(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)(Z,{})})]}),(0,$.jsxs)(`div`,{className:`icon-editor-body`,children:[hx.map(e=>{let t=l.zones[e.slot]??[],n=xx(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?_x.map(n=>y(e.slot,n,e.vertical?vx(i,n):n,Sx(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(gx,void 0,null,l.tray)]})]})]})]})}function _S(e,t){let n=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let r=Fy(n.current,e);n.current=r.key,r.clear&&t()},[e,t])}var vS=new Map,yS=-1;function bS(e){let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}function xS(e){let t=e.replace(/\\/g,`/`).split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(n).toLowerCase():``}function SS(e,t){yS!==t&&(yS=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=bS(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));vS=n}function CS(e){return vS.get(xS(e))?.[0]??null}async function wS(e){let t=await vh(e.plugin,yS);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 TS=(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=W();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)(Z,{})})})]}),(0,$.jsx)(Yo,{models:n,modelsLoading:r,providerKeys:i,defaultModel:a,currentModelId:t,active:e,onEnsureModels:()=>{n.length===0&&!r&&X({type:`list_models`})},onRefresh:()=>X({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}),ES=null,DS=new Set;function OS(){for(let e of DS)e()}function kS(e){ES=e,OS()}function AS(){ES=null,OS()}function jS(e){ES&&(X({type:`rollback_session`,messageId:ES.messageId,conversationId:ES.conversationId,restoreWorkspace:e}),ES=null,OS())}function MS(){return(0,Q.useSyncExternalStore)(e=>(DS.add(e),()=>DS.delete(e)),()=>ES)}function NS(){let e=W(),t=MS(),[n,i]=(0,Q.useState)(!0),a=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{t&&i(!0)},[t]),wt(()=>{t&&AS()},!!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||a.current?.contains(t))&&(e.preventDefault(),jS(n))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]),t?(0,Fn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:AS,children:(0,$.jsxs)(`div`,{ref:a,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)(Ye,{}),e(`rollbackSession`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`cancel`),onClick:AS,children:(0,$.jsx)(Z,{})})]}),(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=>i(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:AS,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:()=>jS(n),children:[(0,$.jsx)(r,{}),e(`confirm`)]})]})]})]})}),document.body):null}function PS({approvals:e,activeConversationId:t,mode:n=`all`}){let r=W();return(0,$.jsx)(Xx,{items:e,itemKey:e=>`${e.owner??`local`}:${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`&&(e.global||n===`all`||e.conversationId===t||!e.conversationId),onNavigate:e=>{e.conversationId&&X(e.global&&e.owner?{type:`open_shared_conversation`,owner:e.owner,id:e.conversationId}:{type:`switch_conversation`,id:e.conversationId})},canNavigate:e=>!!e.conversationId,children:(e,t)=>(0,$.jsx)(FS,{approval:e,onDefer:t},`${e.owner??`local`}:${e.id}`)})}function FS({approval:e,onDefer:t}){let n=W(),{locale:i}=st(),[a,o]=(0,Q.useState)(``),[s,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(Date.now);if((0,Q.useEffect)(()=>{if(!e?.createdAt)return;d(Date.now());let t=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(t)},[e?.id,e?.createdAt]),(0,Q.useEffect)(()=>{if(e){let t=e.params;o(typeof t==`object`&&t?JSON.stringify(t,null,2):t==null?`{}`:String(t)),l(null)}},[e?.id]),!e)return null;let f=t=>{X({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`approve`,...t&&t!==`once`?{scope:t}:{}})},p=()=>{X({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`deny`,reason:`Operation rejected by user`})};return(0,Fn.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)(Ye,{}),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}),e.createdAt&&Px(e.createdAt,u)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,style:{marginLeft:`auto`},children:[`⏱ `,Px(e.createdAt,u)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,children:n(`pendingQueueDefer`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalDeny`),onClick:p,children:(0,$.jsx)(Z,{})})]}),(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:c(i)?e.reason||e.reasonEn:e.reasonEn||e.reason}),e.category&&(0,$.jsxs)(`div`,{style:{marginTop:6,fontSize:12,opacity:.85},children:[n(`toolApprovalCategory`),`:`,c(i)?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:c(i)?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:Us(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:a,onChange:e=>{o(e.target.value),s&&l(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:s?`1px solid var(--red, #ef4444)`:`1px solid var(--border-subtle, rgba(255,255,255,0.1))`,boxSizing:`border-box`,resize:`vertical`}}),s&&(0,$.jsx)(`div`,{style:{color:`var(--red, #ef4444)`,fontSize:12,marginTop:4},children:s})]}),(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:()=>f(`category`),children:[(0,$.jsx)(ct,{}),n(`toolApprovalAllowCategory`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowConversationHint`),onClick:()=>f(`all`),children:[(0,$.jsx)(Pe,{}),n(`toolApprovalAllowConversation`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,style:{color:`var(--red, #ef4444)`},onClick:p,children:[(0,$.jsx)(Z,{}),n(`toolApprovalDeny`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>f(),style:{fontWeight:500},children:[(0,$.jsx)(r,{}),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(a):a,l(null),X({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`edit`,editedParams:n})}catch(e){l(c(i)?`JSON 格式错误:${e.message}`:`JSON parse error: ${e.message}`)}},children:[(0,$.jsx)(L,{}),n(`toolApprovalEditAndRun`)]})]})]})]})}),document.body)}var IS={pending:`in_progress`,in_progress:`done`,done:`failed`,failed:`pending`};function LS({plan:e}){let t=W(),n=c(gt()),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Dc({duration:2e3}),[l,u]=(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,g=h.filter(e=>e.status===`done`).length,_=h.length,v=Math.round(g/_*100),y=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?`)&&X({type:`plan_update`,steps:[]})},C=()=>{X({type:`set_plan_mode`,enabled:!1}),X({type:`prompt`,text:t(`planImplementRequest`)})},w=()=>{let e=h.map((e,t)=>`${t+1}. ${e.title}${e.description?` (${e.description})`:``}`).join(`
85
- `);X({type:`plan_clean_handoff`,steps:h,prompt:`${t(`planCleanHandoffPrompt`)}\n\n${e}`})},T=async()=>{let e=[`# ${t(`planBoardTitle`)} (${g}/${_})`,``,...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 s(e.join(`
86
- `))},E=e=>{u(e.id),f(e.title),m(e.description||``)},O=()=>{u(null),f(``),m(``)},k=e=>{let t=d.trim();if(!t)return;let n={title:t};n.description=p.trim()?p.trim():void 0,X({type:`plan_step_update`,stepId:e,patch:n}),u(null)},j=e=>{X({type:`plan_step_delete`,stepId:e})},M=e=>{let t=h.find(t=>t.id===e);t&&X({type:`plan_step_update`,stepId:e,patch:{status:IS[t.status]}})},N=()=>{let e={id:`step-${Date.now()}`,title:t(`planBoardAddStep`),status:`pending`};X({type:`plan_step_add`,step:e}),E(e)},P=(e,r)=>{let i=(()=>{switch(e){case`done`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Pe,{}),t(`planBoardCompleted`)]});case`in_progress`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(vt,{}),t(`planBoardInProgress`)]});case`failed`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ce,{}),t(`planBoardFailed`)]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(D,{}),t(`planBoardPending`)]})}})();return(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),M(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 ${i?``:`plan-board-collapsed`}`.trim(),children:[(0,$.jsxs)(`div`,{className:`plan-board-head`,onClick:()=>a(!i),children:[(0,$.jsxs)(`div`,{className:`plan-board-head-main`,children:[(0,$.jsx)(mt,{className:`plan-board-icon`}),(0,$.jsx)(`span`,{className:`plan-board-title`,children:t(`planBoardTitle`)}),(0,$.jsxs)(`span`,{className:`plan-board-count ${v===100?`plan-board-count-done`:``}`.trim(),children:[g,`/`,_]}),!i&&y&&(0,$.jsx)(`span`,{className:`plan-board-active`,title:y.title,children:y.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(),C()},children:t(`planImplementBtn`)}),i&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-clean-handoff`,title:t(`planCleanHandoffTip`),onClick:e=>{e.stopPropagation(),w()},children:t(`planCleanHandoffBtn`)}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(o?`planBoardExportSuccess`:`planBoardExportMarkdown`),onClick:e=>{e.stopPropagation(),T()},children:o?(0,$.jsx)(r,{style:{color:`var(--green, #22c55e)`}}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`clear`),onClick:e=>{e.stopPropagation(),x()},children:(0,$.jsx)(Ge,{})})]}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(i?`collapseSection`:`expandSection`),children:i?(0,$.jsx)(S,{}):(0,$.jsx)(A,{})})]}),i&&(0,$.jsx)(`div`,{className:`plan-board-head-divider`,children:(0,$.jsx)(`div`,{className:`plan-board-head-divider-fill`,style:{width:`${v}%`,backgroundColor:v===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})})]}),!i&&(0,$.jsx)(`div`,{className:`plan-board-progress-line`,children:(0,$.jsx)(`div`,{className:`plan-board-progress-line-fill`,style:{width:`${v}%`,backgroundColor:v===100?`var(--green, #22c55e)`:`var(--accent, #38bdf8)`}})}),i&&(0,$.jsxs)(`div`,{className:`plan-board-steps`,style:{marginTop:8,display:`flex`,flexDirection:`column`,gap:8},children:[h.map((n,i)=>{let a=n.id===e.activeStepId||n.status===`in_progress`;return l===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(),k(n.id)):e.key===`Escape`&&O()}}),(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(),k(n.id)):e.key===`Escape`&&O()}}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:6,marginTop:2},children:[(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-iconbtn`,onClick:O,title:t(`cancel`),style:{padding:`3px 8px`,fontSize:12},children:[(0,$.jsx)(Z,{}),` `,t(`cancel`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-implement`,onClick:()=>k(n.id),title:t(`confirm`),style:{padding:`3px 10px`,fontSize:12},children:[(0,$.jsx)(r,{}),` `,t(`confirm`)]})]})]},n.id||i):(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`flex-start`,justifyContent:`space-between`,flexWrap:`wrap`,rowGap:4,minWidth:0,padding:`6px 10px`,borderRadius:6,backgroundColor:a?`rgba(56, 189, 248, 0.08)`:`var(--bg-elev2, rgba(0, 0, 0, 0.2))`,border:a?`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:a?`var(--accent, #38bdf8)`:`var(--text-dim, #9aa1b4)`,minWidth:16},children:[i+1,`.`]}),(0,$.jsx)(`span`,{style:{fontWeight:a?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:[P(n.status,n.id),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardEditStep`),onClick:()=>E(n),children:(0,$.jsx)(fe,{size:12})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardDeleteStep`),onClick:()=>j(n.id),children:(0,$.jsx)(Ge,{size:12})})]})]},n.id||i)}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-add-btn`,onClick:N,children:[(0,$.jsx)(te,{}),` `,t(`planBoardAddStep`)]})]})]})}var RS=3,zS=200;function BS(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VS(e){return typeof e==`string`&&e.trim()||void 0}function HS(e,t){let n=[];for(let r of e){let e=WS(r,t);if(n.includes(e)||n.push(e),n.length>=4){n.push(`…`);break}}return n.join(` | `)||`any`}function US(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 WS(e,t=0){if(t>6||!BS(e))return`any`;if(VS(e.$ref))return`ref`;let n=VS(e.type);if(n===`array`){let n=e.items;return`array<${n===void 0?`any`:WS(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 HS(r,t+1)}return BS(e.properties)?`object`:BS(e.additionalProperties)?`record<${WS(e.additionalProperties,t+1)}>`:`any`}function GS(e){let t=[],n=e.enum;if(Array.isArray(n)&&n.length>0){let e=US(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 KS(e,t={}){let n=t.maxDepth??RS,r=t.maxRows??zS,i=e;if(!BS(i))return[];let a=i.properties;if(!BS(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=BS(l)?l:{},u=t?`${t}.${s}`:s,d={name:u,type:WS(e,i),required:a.has(s),depth:i},f=VS(e.description);f&&(d.description=f);let p=GS(e);if(p&&(d.hint=p),o.push(d),i+1<n&&BS(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 qS(){let e=W(),t=vu();return wt(()=>{mu()},!!t),t?(0,Fn.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:mu,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)(Oe,{}),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:mu,children:(0,$.jsx)(Z,{})})]}),(0,$.jsx)(`div`,{className:`tool-info-body`,children:(0,$.jsx)(JS,{info:t})})]})}),document.body):null}function JS({info:e}){let t=W();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?[]:KS(e.parameters),r=e.parameters===void 0?``:XS(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)(YS,{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 YS({rows:e}){let t=W();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 XS(e){try{return JSON.stringify(e,null,2)??``}catch{return``}}var ZS={bash:(0,$.jsx)(Se,{}),skill:(0,$.jsx)(p,{}),read:(0,$.jsx)(U,{}),write:(0,$.jsx)(L,{}),edit:(0,$.jsx)(fe,{}),edit_soft:(0,$.jsx)(fe,{}),grep:(0,$.jsx)(ae,{}),find:(0,$.jsx)(V,{}),codemode:(0,$.jsx)(be,{}),eval:(0,$.jsx)(a,{}),lsp:(0,$.jsx)(a,{}),tool_search:(0,$.jsx)(ae,{}),conversation:(0,$.jsx)(K,{}),subagent:(0,$.jsx)(K,{}),delegate_task:(0,$.jsx)(ct,{}),present_files:(0,$.jsx)(I,{}),browser_search:(0,$.jsx)(ae,{}),browser_use:(0,$.jsx)(ot,{}),ask_user_question:(0,$.jsx)(Xe,{}),conversation_read:(0,$.jsx)(f,{})};function QS(e,t,n){let r=e.isError??!1,i=e.statusClass===`run`&&!r,a=r?`err`:i?`run`:`ok`,o=r?`✕`:i?`⟳`:`✓`,s;s=r?e.duration?`${t(`error`)} (${e.duration})`:t(`error`):i?e.status||(n?`执行中...`:`Running...`):e.duration?`${t(`done`)} (${e.duration})`:e.status||t(`done`);let c;return c=r?e.exitHint||(n?`命令执行失败`:`Execution failed`):i?e.exitHint||(n?`执行中...`:`Running...`):e.exitHint||(n?`执行完成`:`Execution completed`),{isRunning:i,badgeClass:a,statusIcon:o,badgeText:s,footerText:c}}function $S(){let e=ml();return!e||typeof document>`u`?null:(0,Fn.createPortal)((0,$.jsx)(eC,{state:e}),document.body)}function eC({state:e}){let[t,n]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),ul())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let r=()=>n(e=>!e);if(e.isThinking)return(0,$.jsx)(tC,{state:e,isMaximized:t,onToggleMaximize:r});let i=e.name||``;return i===`edit`||i===`write`||i===`edit_soft`||i===`patch`?(0,$.jsx)(iC,{state:e,isMaximized:t,onToggleMaximize:r}):i===`bash`?(0,$.jsx)(nC,{state:e,isMaximized:t,onToggleMaximize:r}):i===`read`||i===`ls`||i===`grep`||i===`find`||i===`tool_search`?(0,$.jsx)(rC,{state:e,isMaximized:t,onToggleMaximize:r}):(0,$.jsx)(aC,{state:e,isMaximized:t,onToggleMaximize:r})}function tC({state:e,isMaximized:t,onToggleMaximize:n}){let a=W(),{copy:o,copied:s}=Dc({duration:1200}),c=e.thinking||e.output||``,l=c.length,u=c?c.split(`
87
- `).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&ul()},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)(T,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,children:a(`toolInspectorThinkingSection`).replace(/^💭\s*/,``)}),(0,$.jsx)(`span`,{className:`file-diff-lang`,children:a(`toolInspectorStats`,{chars:l,lines:u})}),(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${s?` copied`:``}`,title:a(s?`toolInspectorCopied`:`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),o(c)},children:s?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(i,{}):(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),ul()},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:(0,$.jsx)(`div`,{className:`thinking-inspector-content`,children:c?(0,$.jsx)(`div`,{className:`markdown thinking-markdown`,children:(0,$.jsx)(Pl,{text:c})}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:a(`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?`思考分析链路生成中...`:`分析记录共 ${u} 行`})]}),e.duration&&(0,$.jsx)(`div`,{className:`file-diff-footer-meta`,children:(0,$.jsxs)(`span`,{children:[`耗时: `,e.duration]})})]})]})})}function nC({state:e,isMaximized:t,onToggleMaximize:n}){let o=W(),s=c(gt()),[l,u]=(0,Q.useState)(`preview`),d=Dc({duration:1200}),f=Dc({duration:1200}),{args:p=``,output:m=``,details:h,isError:g=!1,status:_,duration:v,exitHint:y}=e,x=(e.hints||ku(p)).command||(p&&!p.startsWith(`{`)?p:``),S=(0,Q.useMemo)(()=>{if(!h||typeof h!=`object`)return``;try{return JSON.stringify(h,null,2)}catch{return``}},[h]),C=QS(e,o,s),w=m?m.split(`
88
- `).length:0,T=h&&typeof h==`object`?Object.keys(h).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&ul()},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)(Se,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:x||`bash`,children:x?`$ ${x}`:`bash`}),y&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:y}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${C.badgeClass}`,children:[C.statusIcon,` `,C.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[C.isRunning&&e.onKillBash&&(0,$.jsxs)(`button`,{type:`button`,className:`file-diff-action-btn kill-btn`,title:s?`结束此 bash 命令 (Stop)`:`Stop bash command`,onClick:t=>{t.stopPropagation(),e.onKillBash?.()},children:[(0,$.jsx)(pe,{}),(0,$.jsx)(`span`,{className:`kill-btn-label`,children:s?`结束`:`Stop`})]}),(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`preview`)},children:s?`终端输出`:`Terminal`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`raw`)},children:o(`diffViewRaw`)})]}),x&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${d.copied?` copied`:``}`,title:d.copied?o(`toolInspectorCopied`):o(`toolInspectorCopyArgs`),onClick:e=>{e.stopPropagation(),d.copy(x)},children:d.copied?(0,$.jsx)(r,{}):(0,$.jsx)(a,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${f.copied?` copied`:``}`,title:f.copied?o(`toolInspectorCopied`):o(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),f.copy(m)},children:f.copied?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:o(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(i,{}):(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${o(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),ul()},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:l===`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:[`⚡ `,o(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:p||`(无入参参数 / No arguments)`})]}),S&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,o(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[T,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:S})]})]}):(0,$.jsxs)(`div`,{className:`bash-terminal-viewport`,onContextMenu:t=>{let n=window.getSelection?.()?.toString();if(n&&n.trim().length>0)return;t.preventDefault(),t.stopPropagation();let r=[];e.onKillBash&&r.push(Mi({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:s?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:C.isRunning?void 0:[`disabled`]})),x&&r.push(Mi({id:`host:copy-command`,slot:`contextmenu.toolcall`,label:s?`复制执行命令`:`Copy command`,icon:`copy`,kind:`action`,order:1})),m&&r.push(Mi({id:`host:copy-output`,slot:`contextmenu.toolcall`,label:s?`复制终端输出`:`Copy output`,icon:`copy`,kind:`action`,order:2})),r.push(Mi({id:`host:tool-info`,slot:`contextmenu.toolcall`,label:s?`工具详细信息`:`Tool Details`,icon:`info`,kind:`action`,order:3})),na({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.toolCallId||`bash`,kind:`toolcall`,label:`bash`},entries:r,onHostAction:t=>{if(t.id===`host:kill-bash`){e.onKillBash?.();return}if(t.id===`host:copy-command`){d.copy(x);return}if(t.id===`host:copy-output`){f.copy(m);return}if(t.id===`host:tool-info`){pu(`bash`);return}}})},children:[x&&(0,$.jsx)(uf,{command:x}),(0,$.jsx)(`pre`,{className:`bash-output-pre`,children:m||(e.statusClass===`run`?o(`toolInspectorRunningOutput`):o(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${C.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${C.isRunning?` spin`:``}`,children:C.statusIcon}),(0,$.jsxs)(`span`,{className:`file-diff-status-text`,children:[C.footerText,` · `,w,` 行输出 · `,m.length,` 字符`]})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[T>0&&(0,$.jsxs)(`span`,{children:[`details: `,T,` keys`]}),T>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),u(l===`raw`?`preview`:`raw`)},children:l===`raw`?s?`返回终端输出`:`Back to terminal`:s?`查看完整日志与详情`:`View raw & details`})]})]})]})})}function rC({state:e,isMaximized:t,onToggleMaximize:n}){let a=W(),o=c(gt()),[s,l]=(0,Q.useState)(`preview`),u=Dc({duration:1200}),{name:f=`read`,args:p=``,output:m=``,details:h,isError:g=!1,status:_,duration:v,images:y}=e,x=e.hints||ku(p),S=x.path||``,C=x.query||``,w=C?S?`${C} (${S})`:C:S||f,T=(0,Q.useMemo)(()=>{if(y&&y.length>0)return!0;if(S){let e=S.split(`.`).pop()?.toLowerCase();return e&&[`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`,`bmp`].includes(e)}return!1},[y,S]),E=(0,Q.useMemo)(()=>{if(!p)return 1;try{let e=JSON.parse(p);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(p);if(e){let t=parseInt(e[1],10);if(t>0)return t}}return 1},[p]),D=(0,Q.useMemo)(()=>{if(!h||typeof h!=`object`)return``;try{return JSON.stringify(h,null,2)}catch{return``}},[h]),O=QS(e,a,o),k=m?m.split(`
89
- `).length:0,A=h&&typeof h==`object`?Object.keys(h).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&ul()},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:ZS[f]??(0,$.jsx)(U,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:w,children:w}),C&&(0,$.jsx)(`span`,{className:`file-diff-pattern`,title:o?`搜索表达式: ${C}`:`Pattern: ${C}`,children:f===`grep`?`REGEX`:`QUERY`}),S&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:S.split(`.`).pop()?.toUpperCase()||`FILE`}),E>1&&(0,$.jsxs)(`span`,{className:`file-diff-lang`,title:`起始偏移量: 第 ${E} 行`,children:[`L`,E,`~L`,E+k-1]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${O.badgeClass}`,children:[O.statusIcon,` `,O.badgeText]})]}),(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${s===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`preview`)},children:o?`内容查看`:`Content`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:a(`diffViewRaw`)})]}),S&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!S)return;let t=S.split(`/`).pop()||S;bl({path:S,name:t})},children:(0,$.jsx)(Je,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${u.copied?` copied`:``}`,title:u.copied?a(`toolInspectorCopied`):a(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),u.copy(m)},children:u.copied?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(i,{}):(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),ul()},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:s===`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:[`⚡ `,a(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:p||`(无入参参数 / No arguments)`})]}),D&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,a(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[A,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:D})]})]}):(0,$.jsxs)(`div`,{className:`read-inspector-viewport`,children:[f===`tool_search`&&(0,$.jsx)(df,{details:h}),T&&y&&y.length>0?(0,$.jsxs)(`div`,{className:`read-image-viewport`,children:[y.map((e,t)=>{let n=e.startsWith(`/`)?d(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:S||`Image ${t+1}`,className:`read-image-item`})})},t)}),m&&(0,$.jsx)(`div`,{className:`read-image-caption`,children:m})]}):m?(0,$.jsx)(Jd,{content:m,startLine:E}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:e.statusClass===`run`?a(`toolInspectorRunningOutput`):a(`toolInspectorEmptyOutput`)})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${O.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${O.isRunning?` spin`:``}`,children:O.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:O.isRunning?O.footerText:a(`toolInspectorStats`,{chars:m.length,lines:k})})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[A>0&&(0,$.jsxs)(`span`,{children:[`details: `,A,` keys`]}),A>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),l(s===`raw`?`preview`:`raw`)},children:s===`raw`?o?`返回内容`:`Back to content`:o?`查看完整参数`:`View raw`})]})]})]})})}function iC({state:e,isMaximized:t,onToggleMaximize:n}){let a=W(),o=c(gt()),[s,l]=(0,Q.useState)(`unified`),{copied:u,copy:d}=Dc({duration:1200}),{name:f=`edit`,args:p=``,details:m,output:h=``,isError:g=!1,status:_,duration:v}=e,y=f===`edit`||f===`edit_soft`||f===`patch`,x=(0,Q.useMemo)(()=>Kd(f,p,m,h),[f,p,m,h]),S=m&&typeof m==`object`?Object.keys(m).length:0,C=(0,Q.useMemo)(()=>{if(!m||typeof m!=`object`)return``;try{return JSON.stringify(m,null,2)}catch{return``}},[m]),w=QS(e,a,o);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&ul()},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)(U,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:x?.filePath||f,children:x?.filePath||f}),x?.language&&x.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:x.language}),x?.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:a(`diffNewFile`)}):x?.stats.additions!==void 0&&(x.stats.additions>0||x.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[x.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,x.stats.additions]}),x.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,x.stats.deletions]})]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${w.badgeClass}`,children:[w.statusIcon,` `,w.badgeText]})]}),(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${s===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`unified`)},children:a(`diffViewUnified`)}),!x?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`split`)},children:a(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:a(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${u?` copied`:``}`,title:x?.isWrite?a(`diffCopyContent`):a(`diffCopyPatch`),"aria-label":x?.isWrite?a(`diffCopyContent`):a(`diffCopyPatch`),onClick:e=>{e.stopPropagation(),x?.isWrite&&x.content?d(x.content):p&&d(p)},children:u?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),x?.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(`diffOpenFile`),"aria-label":a(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!x?.filePath)return;let t=x.filePath.split(`/`).pop()||x.filePath;bl({path:x.filePath,name:t})},children:(0,$.jsx)(Je,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),"aria-label":a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(i,{}):(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,"aria-label":a(`close`),onClick:e=>{e.stopPropagation(),ul()},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:s===`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:[`⚡ `,a(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:p||`(无入参参数 / 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:[`⚙ `,a(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[S,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:C})]})]}):x?.isWrite?(0,$.jsx)(Jd,{content:x.content||``}):s===`split`?(0,$.jsx)(Zd,{hunks:x?.hunks||[],isStreaming:x?.isStreamingPartial,fallbackText:p}):(0,$.jsx)(Yd,{hunks:x?.hunks||[],isStreaming:x?.isStreamingPartial,fallbackText:p})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${w.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${w.isRunning?` spin`:``}`,children:w.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:w.isRunning?w.footerText:h||(y?o?`补丁已应用`:`Patch applied`:o?`文件已写入`:`File written`)})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[S>0&&(0,$.jsxs)(`span`,{children:[`details: `,S,` keys`]}),S>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),l(s===`raw`?`unified`:`raw`)},children:s===`raw`?o?`返回差异对比`:`Back to diff`:o?`查看完整日志`:`View raw logs`})]})]})]})})}function aC({state:e,isMaximized:t,onToggleMaximize:n}){let a=W(),o=c(gt()),[s,l]=(0,Q.useState)(`preview`),u=Dc({duration:1200}),{name:d=`tool`,args:f=``,details:p,output:m=``,isError:h=!1,status:g,duration:_,images:v}=e,y=Ou({name:d,argumentsText:f,hints:e.hints||ku(f)}),x=y?`${d}(${y.text})`:d?`${d}()`:a(`toolInspectorTitle`),S=(0,Q.useMemo)(()=>{if(!p||typeof p!=`object`)return``;try{return JSON.stringify(p,null,2)}catch{return``}},[p]),C=QS(e,a,o),w=p&&typeof p==`object`?Object.keys(p).length:0,T=d===`present_files`,E=(0,Q.useMemo)(()=>T&&f?Xu(f):null,[T,f]),D=d===`delegate_task`,O=(0,Q.useMemo)(()=>D&&f?Nu(f):{},[D,f]),k=d===`codemode`,A=(0,Q.useMemo)(()=>k&&f?Bu(f):null,[k,f]),j=d===`ask_user_question`,M=(0,Q.useMemo)(()=>j&&f?Wu(f):null,[j,f]),N=!!(T&&E||D&&Object.keys(O).length>0||k&&A?.code||j&&M);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&ul()},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:ZS[d]??(0,$.jsx)(I,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:x,children:x}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${C.badgeClass}`,children:[C.statusIcon,` `,C.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[N&&(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`preview`)},children:o?`视图`:`View`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),l(`raw`)},children:a(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${u.copied?` copied`:``}`,title:u.copied?a(`toolInspectorCopied`):a(`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),u.copy(`[Arguments]\n${f}\n\n[Output]\n${m}`)},children:u.copied?(0,$.jsx)(r,{}):(0,$.jsx)(b,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(i,{}):(0,$.jsx)(B,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),ul()},children:(0,$.jsx)(Z,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:s===`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:[`⚡ `,a(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:f||`(无入参参数 / No arguments)`})]}),S&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,a(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[w,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:S})]})]}):(0,$.jsxs)(`div`,{className:`generic-inspector-viewport`,children:[T&&E&&(0,$.jsx)(Md,{args:E,details:p,toolCallId:e.toolCallId??``,resultTimestamp:e.resultTimestamp}),D&&(0,$.jsx)(ff,{args:O}),k&&A?.code&&(0,$.jsx)(pf,{code:A.code,options:A.options,details:p,output:m}),j&&M&&(0,$.jsx)(Ld,{questions:M.questions,details:p,output:m,isError:h,waiting:e.statusClass===`run`}),v&&v.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:[a(`toolInspectorImages`),` (`,v.length,`)`]})}),(0,$.jsx)(`div`,{className:`tool-inspector-images`,children:v.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))})]}),!N&&(0,$.jsx)(`pre`,{className:`generic-output-pre`,children:m||(e.statusClass===`run`?a(`toolInspectorRunningOutput`):a(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${C.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${C.isRunning?` spin`:``}`,children:C.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:C.isRunning?C.footerText:m?`${m.split(`
90
- `).length} 行输出 · ${m.length} 字符`:C.footerText})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[w>0&&(0,$.jsxs)(`span`,{children:[`details: `,w,` keys`]}),w>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),l(s===`raw`?`preview`:`raw`)},children:s===`raw`?o?`返回视图`:`Back to view`:o?`查看完整参数与详情`:`View raw & details`})]})]})]})})}function oC({entry:e,pluginView:t,onUiAction:n,onClose:r}){let i=W(),a=e.label||e.id,o=e.kind===`view`;return(0,$.jsx)(Va,{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)(Qx,{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 sC({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 cC({file:e,plugin:t,declaration:n,epoch:r,send:i,onClose:a,onFallback:o}){let s=W(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),m=(0,Q.useRef)(o);m.current=o;let h=n.label??t.name;(0,Q.useEffect)(()=>{let r=c.current;if(!r)return;let a=!1,o;return u(null),p(!1),(async()=>{try{let s=await wS({plugin:t,declaration:n});if(a)return;if(!s)throw Error(`插件没有提供可用的文件查看器`);let c=`/plugins-api/${encodeURIComponent(t.id)}`,l={...Sh(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`,sg());let i=r.toString();return z(d(`${c}${n}${i?`?${i}`:``}`))}};o=s.handler.mount(r,e,l),a||p(!0)}catch(e){a||(console.error(`[plugin:${t.id}] file handler failed:`,e),m.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 g=(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}),h?(0,$.jsx)(`span`,{className:`plugin-file-preview-badge`,children:h}):null]});return(0,$.jsx)(Va,{className:`plugin-file-preview`,title:g,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&&!f?(0,$.jsx)(`div`,{className:`plugin-file-preview-loading`,children:s(`loading`)}):null,(0,$.jsx)(`div`,{ref:c,className:`plugin-file-preview-host`})]})})}var lC=.4,uC=1.05;function dC(e){return Math.min(300,e*.86)}function fC(e,t,n){return n||(t<=144?null:e<=72?`left`:t-e<=72?`right`:null)}function pC(e,t){let n=Math.abs(e),r=Math.abs(t);return n<12&&r<12?`none`:n>r*1.2?`horizontal`:`vertical`}function mC(e,t){return e===`left`?t:-t}function hC(e,t){return Math.max(-e,Math.min(0,-e+t))}function gC(e,t,n){let r=n?e+t:t;return Math.max(0,Math.min(1,r/e))}function _C(e){let{wasOpen:t,pull:n,width:r,durationMs:i}=e;return i<=320&&Math.abs(n)>=48?n>0:gC(r*uC,n,t)>=lC}var vC=new Set([`auto`,`scroll`,`overlay`]);function yC(e,t){let n=e instanceof Element?e:null;for(;n;){if(n instanceof HTMLElement&&n.scrollWidth>n.clientWidth+4&&vC.has(getComputedStyle(n).overflowX))return!0;if(n===t)break;n=n.parentElement}return!1}function bC(){let e=e=>{e.stopPropagation(),e.preventDefault()};window.addEventListener(`click`,e,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,e,{capture:!0}),400)}function xC(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=fC(r.clientX,window.innerWidth,n);i&&!yC(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=pC(d,v);if(t===`none`)return;if(t===`vertical`){s=null;return}c=`horizontal`,p=n===r,m=dC(window.innerWidth),h=m*uC;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=mC(r,d);let b=hC(h,f);y.style.transform=`translateX(${r===`left`?b:-b}px)`,_&&(_.style.opacity=String(gC(h,f,p))),t.preventDefault()},x=()=>{let e=s,t=c===`horizontal`&&e!==null&&g!==null,i=f,a=Date.now()-d,o=t?_C({wasOpen:p,pull:i,width:m,durationMs:a}):!1;v(),t&&e&&o!==(n===e)&&(bC(),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 SC={revision:0},CC=new Set;function wC(e){SC={...e,revision:SC.revision+1};for(let e of CC)e()}var TC={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`]},EC=`pi-web-sounds`,DC={enabled:!0,question:!0,done:!0,subagentDone:!0,start:!1,error:!0,approval:!0,volume:100};function OC(){try{let e=localStorage.getItem(EC);if(!e)return{...DC};let t=JSON.parse(e),n={...DC,...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]=DC[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?DC.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...DC}}}function kC(e){try{localStorage.setItem(EC,JSON.stringify(e))}catch{}}var AC=null;function jC(){try{if(!AC){let e=window.AudioContext??window.webkitAudioContext;if(!e)return null;AC=new e}return AC.state===`suspended`&&AC.resume(),AC}catch{return null}}var MC=[{type:`sine`,freq:587.33,start:0,dur:.13,peak:.5},{type:`sine`,freq:880,start:.11,dur:.24,peak:.5}],NC=[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],PC={question:MC,done:NC,subagentDone:NC,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 FC(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 IC(e,t=OC()){if(!t.enabled||!t[e])return;let n=jC();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));for(let t of PC[e])FC(n,t,r)}var LC=[`question`,`done`,`subagentDone`,`start`,`error`,`approval`];function RC(e,t,n){if(!t.enabled)return!1;let r=t.events?.[e];return r===`on`||r!==`off`&&n[e]}var zC=`pi-web-notify`,BC={enabled:!1};function VC(){try{let e=localStorage.getItem(zC);if(!e)return{...BC};let t=JSON.parse(e),n={};for(let e of LC){let r=t.events?.[e];(r===`follow`||r===`on`||r===`off`)&&(n[e]=r)}return{enabled:typeof t.enabled==`boolean`?t.enabled:BC.enabled,events:n}}catch{return{...BC}}}function HC(e){try{localStorage.setItem(zC,JSON.stringify(e))}catch{}}function UC(){return typeof window<`u`&&`Notification`in window}function WC(){return UC()?null:typeof window<`u`&&window.isSecureContext===!1?`insecure`:`unsupported`}function GC(e){let{screenX:t,screenY:n,outerWidth:r,outerHeight:i}=e;return Number.isFinite(t)&&KC(t)||Number.isFinite(n)&&KC(n)?!0:r>0&&r<=400&&i>0&&i<=40}function KC(e){return e<=-1e4}function qC(e){return!(e.visibility!==`visible`||e.minimized||!e.hasFocus||e.windows&&e.idleMs>12e4)}var JC=Date.now(),YC=!1;function XC(){JC=Date.now()}function ZC(){return Math.max(0,Date.now()-JC)}function QC(){if(YC||typeof window>`u`)return;YC=!0;let e={passive:!0,capture:!0};for(let t of[`pointerdown`,`pointermove`,`keydown`,`wheel`,`touchstart`,`focus`,`scroll`])window.addEventListener(t,XC,e);typeof document<`u`&&document.addEventListener(`visibilitychange`,XC,e)}function $C(){return typeof navigator>`u`?!1:/windows/i.test(navigator.userAgent??``)}function ew(){return QC(),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:GC({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:ZC(),windows:$C()}}function tw(){return UC()?Notification.permission:`denied`}async function nw(){if(!UC())return`denied`;try{return await Notification.requestPermission()}catch{return`denied`}}function rw(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function iw(e,t=!1){return{body:e,requireInteraction:t,icon:d(`/icons/icon-192.png`),badge:d(`/icons/icon-192.png`),data:{url:typeof location<`u`?location.href:d(`/`)}}}async function aw(e,t,n=!1){if(!UC())return{path:`none`,error:`unsupported`};if(Notification.permission!==`granted`)return{path:`none`,error:`permission: ${Notification.permission}`};let r=iw(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=rw(e)}try{return new Notification(e,r),{path:`page`,error:i}}catch(e){return{path:`none`,error:`${i}; page: ${rw(e)}`}}}async function ow(e,t,n=`done`){UC()&&(qC(ew())||RC(n,VC(),OC())&&await aw(e,t))}var sw=`pi-web-ui:wide-chat`,cw={wide:!1};function lw(e){if(!e||typeof e!=`object`)return{...cw};let t=e;return{wide:typeof t.wide==`boolean`?t.wide:cw.wide}}function uw(){try{let e=localStorage.getItem(sw);return e?lw(JSON.parse(e)):{...cw}}catch{return{...cw}}}function dw(e){let t=lw(e);try{localStorage.setItem(sw,JSON.stringify(t))}catch{}fw=t;for(let e of pw)e()}var fw=null,pw=new Set;function mw(e){return pw.add(e),()=>{pw.delete(e)}}function hw(){return fw||=uw(),fw.wide}function gw(){return(0,Q.useSyncExternalStore)(mw,hw)}var _w=`pi-web-ui:hide-model-row`,vw={hide:!1};function yw(e){if(!e||typeof e!=`object`)return{...vw};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:vw.hide}}function bw(){try{let e=localStorage.getItem(_w);return e?yw(JSON.parse(e)):{...vw}}catch{return{...vw}}}function xw(e){let t=yw(e);try{localStorage.setItem(_w,JSON.stringify(t))}catch{}Sw=t;for(let e of Cw)e()}var Sw=null,Cw=new Set;function ww(e){return Cw.add(e),()=>{Cw.delete(e)}}function Tw(){return Sw||=bw(),Sw.hide}function Ew(){return(0,Q.useSyncExternalStore)(ww,Tw)}function Dw({src:e,alt:t,onClose:n}){let r=W();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),n())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]),(0,$.jsxs)(`div`,{className:`img-lightbox`,role:`dialog`,"aria-modal":`true`,"aria-label":r(`toolImageZoom`),onClick:n,children:[(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-close`,title:r(`close`),"aria-label":r(`close`),onClick:e=>{e.stopPropagation(),n()},children:(0,$.jsx)(Z,{})}),(0,$.jsx)(`img`,{src:e,alt:t??`image preview`})]})}var Ow=`pi-web-ui:project-title`,kw={projectName:!0};function Aw(e){if(!e||typeof e!=`object`)return{...kw};let t=e;return{projectName:typeof t.projectName==`boolean`?t.projectName:kw.projectName}}function jw(e){return e?e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``:``}function Mw(){try{let e=localStorage.getItem(Ow);return e?Aw(JSON.parse(e)):{...kw}}catch{return{...kw}}}function Nw(e){let t=Aw(e);try{localStorage.setItem(Ow,JSON.stringify(t))}catch{}Pw=t;for(let e of Fw)e()}var Pw=null,Fw=new Set;function Iw(e){return Fw.add(e),()=>{Fw.delete(e)}}function Lw(){return Pw||=Mw(),Pw.projectName}function Rw(){return(0,Q.useSyncExternalStore)(Iw,Lw)}var zw=`pi-web-ui:favicon-settings`,Bw=[{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`}],Vw=`#8b5cf6`,Hw={color:`default`,customHex:``,instanceName:``};function Uw(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 Ww(e){if(!e||typeof e!=`object`)return{...Hw};let t=e;return{color:typeof t.color==`string`&&t.color.trim()?t.color.trim():Hw.color,customHex:typeof t.customHex==`string`?t.customHex.trim():``,instanceName:typeof t.instanceName==`string`?t.instanceName.trim():``}}function Gw(e,t=Bw){if(!e||t.length===0)return Vw;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 Kw(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 qw(e){let t=Kw(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 Jw={};function Yw(e){Jw={...Jw,...e},tT();for(let e of iT)e()}async function Xw(){if(typeof window<`u`&&typeof fetch<`u`)try{let e=await fetch(d(`/api/health`));if(!e.ok)return;let t=await e.json();t&&(t.instanceName||t.faviconColor)&&Yw({instanceName:t.instanceName,faviconColor:t.faviconColor})}catch{}}function Zw(e,t=typeof window<`u`?window.location.host:``,n=Jw.faviconColor){if(e.color===`custom`&&e.customHex){let t=Uw(e.customHex);if(t)return t}if(e.color===`auto`)return Gw(t||`localhost`);let r=Bw.find(t=>t.id===e.color);if(r)return r.hex;let i=Uw(e.color);if(i)return i;if(e.color==="default"&&n){let e=Bw.find(e=>e.id===n.toLowerCase());if(e)return e.hex;let t=Uw(n);if(t)return t}return Vw}function Qw(e,t=Jw.instanceName){return e.instanceName&&e.instanceName.trim()?e.instanceName.trim():t&&t.trim()?t.trim():``}function $w(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=qw(e);t.href=`data:image/svg+xml;utf8,${encodeURIComponent(n)}`}function eT(){try{let e=localStorage.getItem(zw);return e?Ww(JSON.parse(e)):{...Hw}}catch{return{...Hw}}}function tT(){$w(Zw(rT??eT(),typeof window<`u`?window.location.host:``))}function nT(e){let t=Ww(e);try{localStorage.setItem(zw,JSON.stringify(t))}catch{}rT=t,tT();for(let e of iT)e()}var rT=null,iT=new Set;function aT(e){return iT.add(e),()=>{iT.delete(e)}}function oT(){return rT||=eT(),rT}function sT(){return(0,Q.useSyncExternalStore)(aT,oT)}function cT(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 lT=`pi-web-ui:wallpaper`,uT=`has-wallpaper`,dT={url:``,dim:78,blur:0},fT=2e3,pT=28e5;function mT(e){if(typeof e!=`string`)return``;let t=e.trim();if(!t)return``;let n=t.toLowerCase().startsWith(`data:image/`)?pT:fT;return t.length>n?``:/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)?t:``}var hT=(e,t,n,r)=>typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function gT(e){if(!e||typeof e!=`object`)return{...dT};let t=e;return{url:mT(t.url),dim:hT(t.dim,0,95,dT.dim),blur:hT(t.blur,0,24,dT.blur)}}function _T(){try{let e=localStorage.getItem(lT);return e?gT(JSON.parse(e)):{...dT}}catch{return{...dT}}}function vT(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\r\n]/g,``)}async function yT(e){let t=await jf(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function bT(){let e=ST??_T(),t=document.documentElement;e.url?(t.style.setProperty(`--bg-image`,`url("${vT(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(uT,e.url!==``||n!==``&&n!==`none`)}function xT(e){let t=gT(e);ST=t;try{localStorage.setItem(lT,JSON.stringify(t))}catch{}for(let e of CT)e();bT()}var ST=null,CT=new Set;function wT(e){return CT.add(e),()=>{CT.delete(e)}}function TT(){return ST||=_T(),ST}function ET(){return(0,Q.useSyncExternalStore)(wT,TT)}function DT(){let e=ET();(0,Q.useEffect)(()=>{bT()},[e]),(0,Q.useEffect)(()=>{let e=()=>bT();return window.addEventListener(jt,e),bT(),()=>window.removeEventListener(jt,e)},[])}var OT=(0,Q.lazy)(()=>Qs(()=>import(`./TerminalPanel-0CYvD72B.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([6,1,7,3,8,9,10,11]),import.meta.url)),kT=(0,Q.lazy)(()=>Qs(()=>import(`./SCMPanel-B8_EDxNr.js`).then(e=>({default:e.ScmPanel})),__vite__mapDeps([12,1,7,3,8]),import.meta.url)),AT=(0,Q.lazy)(()=>Qs(()=>import(`./DeviceCenter-DfAHKcid.js`).then(e=>({default:e.DeviceCenter})),__vite__mapDeps([13,1,7,3,14]),import.meta.url)),jT=(0,Q.lazy)(()=>Qs(()=>import(`./DeviceGroups-CI14_SRb.js`).then(e=>({default:e.DeviceGroupCreateDialog})),__vite__mapDeps([15,1,7,3,16,17]),import.meta.url)),MT=(0,Q.lazy)(()=>Qs(()=>import(`./CanvasStudio-zSxyIx1R.js`).then(e=>({default:e.CanvasStudio})),__vite__mapDeps([18,1,7,3,8,19,20,9,21,22]),import.meta.url)),NT=(0,Q.lazy)(()=>Qs(()=>import(`./PiSetupModal-BmMrrgB9.js`).then(e=>({default:e.PiSetupModal})),__vite__mapDeps([23,1,7,3,20,9,24]),import.meta.url)),PT=(0,Q.lazy)(()=>Qs(()=>import(`./ModelConfigModal-YVEgyy34.js`).then(e=>({default:e.ModelConfigModal})),__vite__mapDeps([25,1,7,3,24]),import.meta.url)),FT=(0,Q.lazy)(()=>Qs(()=>import(`./SettingsModal-OBmGTh-5.js`).then(e=>({default:e.SettingsModal})),__vite__mapDeps([26,1,7,3,16,8,19,20,9,27,14]),import.meta.url)),IT=(0,Q.lazy)(()=>Qs(()=>import(`./BgTasksModal-C0i3O1FT.js`).then(e=>({default:e.BgTasksModal})),__vite__mapDeps([28,1,7,3]),import.meta.url)),LT=(0,Q.lazy)(()=>Qs(()=>import(`./TuiOverlayModal-BsA-QTvN.js`).then(e=>({default:e.TuiOverlayModal})),__vite__mapDeps([29,1,7,3,9,10,11]),import.meta.url)),RT=(0,Q.lazy)(()=>Qs(()=>import(`./GlobalSearchModal-F7fNimKk.js`).then(e=>({default:e.GlobalSearchModal})),__vite__mapDeps([30,1,7,3,19,8,20,9]),import.meta.url)),zT=(0,Q.lazy)(()=>Qs(()=>import(`./FilePreview-D4NrhF-U.js`).then(e=>({default:e.FilePreview})),__vite__mapDeps([31,1,7,3]),import.meta.url)),BT=(0,Q.lazy)(()=>Qs(()=>import(`./GroupConversation-Dh71Pdb-.js`).then(e=>({default:e.GroupConversation})),__vite__mapDeps([32,1,7,3,8,17,22]),import.meta.url));function VT({notice:e,onDismiss:t}){let n=W(),{locale:r}=st(),i=!c(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),Ih(e.level));return()=>clearTimeout(n)},[a,e.id,e.level,t]);let s=e.level===`error`?Ce:e.level===`warning`?Ye:Oe;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)(Z,{})})]})}var HT=[],UT=180,WT=520,GT=240,KT=e=>`pi-web-ui:${e}-panel-width`;function qT(e){try{let t=Number(localStorage.getItem(KT(e)));return Number.isFinite(t)&&t>=UT&&t<=WT?t:GT}catch{return GT}}var JT=e=>`pi-web-ui:${e}-panel-collapsed`;function YT(e){try{return localStorage.getItem(JT(e))===`1`}catch{return!1}}function XT({side:e,width:t,onResize:n}){let r=W(),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(WT,Math.max(UT,Math.round(a+r))),n(o)},c=()=>{window.removeEventListener(`pointermove`,s),window.removeEventListener(`pointerup`,c),document.body.classList.remove(`panel-resizing`);try{localStorage.setItem(KT(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(GT)})}function ZT({side:e,onClick:t}){let n=W();return(0,$.jsx)(`button`,{type:`button`,className:`panel-rail panel-rail-${e}`,title:n(`expandPanel`),onClick:t,children:e===`left`?(0,$.jsx)(g,{}):(0,$.jsx)(F,{})})}var QT=`pi-web-ui:plugin-path-grants`,$T=e=>e?`${QT}:${e}`:QT;function eE(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function tE(e){try{let t=$T(e);if(localStorage.getItem(t)!==null)return eE(localStorage.getItem(t));if(!e)return[];let n=eE(localStorage.getItem(QT));return localStorage.setItem(t,JSON.stringify(n)),n}catch{return[]}}function nE(e,t){try{let n=[...new Set([...tE(t),e])];localStorage.setItem($T(t),JSON.stringify(n))}catch{}}function rE(){let e=W(),{locale:t}=st(),{chat:n,send:i,dismissNotice:a,pushNotice:o,terminal:s}=wg(),l=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{n.ready&&n.settings&&(l.current||n.settings.quickPhrasesSeeded||(l.current=!0,n.settings.quickPhrases.length===0&&i({type:`set_settings`,quickPhrases:TC[t]??TC.en,quickPhrasesSeeded:!0})))},[n.ready,n.settings,i,t]);let f=n.state?.cwd??``,p=Rw(),m=Qw(sT());(0,Q.useEffect)(()=>{Xw()},[]),(0,Q.useEffect)(()=>{let t=p?jw(f):``,n=t?`${t} — pi-web-ui`:e(`docTitle`);document.title=m?`[${m}] ${n}`:n},[f,p,m,e]);let[h,g]=(0,Q.useState)([]);(0,Q.useEffect)(()=>(Ht(e=>g(t=>Iy(t,e))),()=>Ht(null)),[]);let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),x=(0,Q.useRef)(!1),S=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{x.current=_!==null,S.current=y},[_,y]);let C=(0,Q.useCallback)((e,t)=>{let n=CS(t);if(n){v(null),b({file:{path:e,name:t},plugin:n.plugin,declaration:n.declaration});return}b(null),v({path:e,name:t})},[]);(0,Q.useEffect)(()=>(vl({open:e=>C(e.path,e.name),isOpen:()=>x.current||S.current!==null}),()=>vl(null)),[C]);let[w,T]=(0,Q.useState)(null),E=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{E.current=w!==null},[w]),(0,Q.useEffect)(()=>(Nf({open:e=>T(e),close:()=>T(null),isOpen:()=>E.current}),()=>Nf(null)),[]);let[D,O]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=()=>O(!1);return window.addEventListener(`drop`,e,!0),()=>window.removeEventListener(`drop`,e,!0)},[]);let[k,A]=(0,Q.useState)(()=>new URLSearchParams(window.location.search).get(`view`)===`devices`?`devices`:`chat`),[j,M]=(0,Q.useState)(null),[N,P]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>(It(()=>{M(null),A(`chat`)}),()=>It(null)),[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(t&&typeof t==`object`){if(t.create===!0){P(!0);return}wC({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?(M(t.roomId),A(`chat`)):(M(null),A(`devices`))}};return window.addEventListener(`pi-web-ui:device-group-open`,e),()=>window.removeEventListener(`pi-web-ui:device-group-open`,e)},[]);let F=(e=>!n.tabs||e===`chat`||e===`devices`||e===`worktrees`||n.tabs.includes(e))(k.startsWith(`plugin:`)?`plugins`:k)?k:`chat`,I=(0,Q.useCallback)(()=>i({type:`refresh_worktrees`}),[i]);dx(n.state?.worktree?.mainPath,I);let L=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=L.current;if(e&&n.state?.cwd){if(F!==`worktrees`){L.current=null;return}n.state.cwd===e.target||n.state.worktree?.currentPath===e.target?(L.current=null,A(`chat`),cn()):n.state.cwd!==e.source&&(L.current=null)}},[n.state?.cwd,n.state?.worktree?.currentPath,F]);let ee=(0,Q.useMemo)(()=>n.plugins.filter(e=>!n.settings?.disabledPlugins?.includes(e.id)),[n.plugins,n.settings?.disabledPlugins]),[R,te]=(0,Q.useMemo)(()=>{let r=[];return[Ui(ji(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]),ne=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let e=te.map(e=>`${e.level}:${e.pluginId??``}:${e.entryId??``}:${e.message}`).join(`
91
- `);if(e!==ne.current){ne.current=e;for(let e of te){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}`)}}},[te]);let re=(0,Q.useMemo)(()=>R[`topbar.primary`].filter(e=>!e.hidden),[R]),z=(0,Q.useMemo)(()=>[...R[`topbar.primary`].filter(e=>e.hidden),...R[`topbar.overflow`]],[R]),B=(0,Q.useMemo)(()=>R[`leftpanel.sessions`].filter(e=>!e.hidden),[R]),ie=(0,Q.useMemo)(()=>R[`leftpanel.projects.actions`].filter(e=>!e.hidden),[R]),ae=(0,Q.useMemo)(()=>R[`leftpanel.project`].filter(e=>!e.hidden),[R]),V=(0,Q.useMemo)(()=>R[`leftpanel.running.actions`].filter(e=>!e.hidden),[R]),oe=(0,Q.useMemo)(()=>R[`leftpanel.history.actions`].filter(e=>!e.hidden),[R]),se=R[`leftpanel.sections`],ce=(0,Q.useMemo)(()=>R[`leftpanel.running`].filter(e=>!e.hidden),[R]),le=(0,Q.useMemo)(()=>R[`leftpanel.history`].filter(e=>!e.hidden),[R]),ue=(0,Q.useMemo)(()=>R[`terminal.toolbar`].filter(e=>!e.hidden),[R]),de=(0,Q.useMemo)(()=>R[`scm.toolbar`].filter(e=>!e.hidden),[R]),fe=(0,Q.useMemo)(()=>R[`goalbar.actions`].filter(e=>!e.hidden),[R]),pe=(0,Q.useMemo)(()=>R[`chat.header`].filter(e=>!e.hidden),[R]),me=(0,Q.useMemo)(()=>R[`chat.empty`].filter(e=>!e.hidden),[R]),H=(0,Q.useMemo)(()=>R[`file.preview.toolbar`].filter(e=>!e.hidden),[R]),he=(0,Q.useMemo)(()=>Object.fromEntries((n.dshPresets?.presets??[]).map(n=>[n.id,Kb(n,t,e).name])),[n.dshPresets,t]),U=(0,Q.useMemo)(()=>R[`notice.actions`].filter(e=>!e.hidden),[R]),_e=(0,Q.useMemo)(()=>R[`sidebar.left`]??[],[R]),ve=(0,Q.useMemo)(()=>R[`sidebar.right`]??[],[R]),G=(0,Q.useCallback)((t,n,r)=>{if(t.id===`host:msg-fork`){r?.id&&i({type:`fork_session`,messageId:r.id,position:`before`});return}if(t.id===`host:msg-rollback`){r?.id&&kS({messageId:r.id});return}let a=(t.action??``).trim();if(t.kind===`view`||(!a||a===`view`)&&t.source!==`host`){A(t.view??`plugin:${t.source.startsWith(`plugin:`)?t.source.slice(7):``}`);return}if(!a)return;let s=t.source.startsWith(`plugin:`)?t.source.slice(7):``;Jt(s,a,t.id,{...n===void 0?{}:{value:n},...r===void 0?{}:{target:r},loadBundle:async e=>{let t=Ae.current.plugins.find(t=>t.id===e);return t?bh(t,Ae.current.pluginsEpoch):!1}}).then(t=>{t||o(`info`,e(`pluginUiNoHandler`))})},[e,o]),K=(0,Q.useCallback)(e=>{let t=n.plugins.find(t=>t.id===e.source.slice(7));return t?(0,$.jsx)(r_,{plugin:t,epoch:n.pluginsEpoch,send:i,className:`lp-plugin-page`}):null},[n.plugins,n.pluginsEpoch,i]),q=(0,Q.useCallback)((t,n)=>{n.action&&Jt(t.pluginId,n.action,n.id,{target:{id:n.id,kind:`plugin-running`,label:n.title},loadBundle:async e=>{let t=Ae.current.plugins.find(t=>t.id===e);return t?bh(t,Ae.current.pluginsEpoch):!1}}).then(t=>{t||o(`info`,e(`pluginUiNoHandler`))})},[e,o]),[ye,be]=(0,Q.useState)([]);(0,Q.useEffect)(()=>ph(be),[]);let[xe,Se]=(0,Q.useState)([]);(0,Q.useEffect)(()=>dh(Se),[]);let[J,Ce]=(0,Q.useState)(null),[we,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)(null),Oe=J?R[`modal.dialog`].find(e=>e.id===J&&!e.hidden):void 0,ke=(0,Q.useMemo)(()=>{if(!Oe||Oe.kind!==`view`)return``;let e=Oe.view??``;return e.startsWith(`plugin:`)?e.slice(7):Oe.source.startsWith(`plugin:`)?Oe.source.slice(7):``},[Oe]);(0,Q.useEffect)(()=>{if(!Oe||!ke||ye.some(e=>e.info.id===ke))return;let e=Ae.current.plugins.find(e=>e.id===ke);e&&bh(e,Ae.current.pluginsEpoch)},[Oe,ke,ye,n.pluginsEpoch]),(0,Q.useEffect)(()=>{Jc(i),Yc(ee,n.pluginsEpoch),nl(ee,n.pluginsEpoch),SS(ee,n.pluginsEpoch),xh(ee,n.pluginsEpoch)},[ee,n.pluginsEpoch,i]);let Ae=(0,Q.useRef)(n);Ae.current=n;let je=(0,Q.useRef)(A);je.current=A;let Y=(0,Q.useRef)(R);Y.current=R,(0,Q.useEffect)(()=>(Qt(rn({send:i,isReady:()=>!!Ae.current.state,setView:e=>je.current(e),getCwd:()=>Ae.current.state?.cwd??``,getWorkspaceRoots:()=>Ae.current.state?.workspaceRoots??[],listSessions:()=>{let e=Ae.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:JSON.stringify([e.owner,e.convId]),conversationId:e.convId,title:e.title,cwd:e.cwd||t,kind:`elsewhere`,owner:e.owner,independent:e.independent,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:()=>Ae.current.state?.conversationId??null,getConversationOwner:()=>Ae.current.state?.sharedConversation?.owner??null,isConversationBlank:()=>(Ae.current.state?.messages.length??0)===0,listModels:()=>Ae.current.models.map(e=>({id:e.id,provider:e.provider,name:e.name,vision:e.vision,reasoning:e.reasoning})),getCurrentModelId:()=>{let e=Ae.current.state?.model;return e?`${e.provider}/${e.id}`:null},listProjects:()=>Ae.current.projects.map(e=>e.path),grantedPaths:tE,grantPath:nE,confirm:e=>new Promise(t=>{if(ft.current){t(!1);return}let n={path:e.path,resolve:t};ft.current=n,dt(n)}),openModal:e=>{let t=String(e??``).trim();if(!t)return!1;let n=Y.current[`modal.dialog`].find(e=>e.id===t);return!n||n.hidden?!1:(Ce(t),!0)},closeModal:()=>Ce(null),pickDirectory:e=>new Promise(t=>{Te({initialPath:e?.initialPath,resolve:t})}),pickModel:e=>new Promise(t=>{De({currentModelId:e?.currentModelId,resolve:t})}),dialogConfirm:e=>new Promise(t=>{if(ht.current){t(!1);return}let n={kind:`confirm`,title:e.title,resolve:t};ht.current=n,mt(n)}),select:e=>new Promise(t=>{if(ht.current){t({ok:!1,error:`busy`});return}let n={kind:`select`,title:e.title,options:e.options,...e.multi?{multi:!0}:{},resolve:t};ht.current=n,_t([]),mt(n)}),input:e=>new Promise(t=>{if(ht.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};ht.current=n,bt(e.initial??``),mt(n)}),notifyAction:e=>new Promise(t=>{try{let n=Ct.current;Ct.current=null,St(null);try{n?.resolve(null)}catch{}let r={text:e.text,actions:e.actions,resolve:t};Ct.current=r,St(r)}catch{t(null)}}),loadPluginBundle:e=>{let t=Ae.current.plugins.find(t=>t.id===e);return t?bh(t,Ae.current.pluginsEpoch):Promise.resolve(!1)},openFileContextMenu:t=>{let n=String(t.path??``).replace(/\\/g,`/`).replace(/^\/+|\/+$/g,``),r=!n,a=t.kind??(t.path.endsWith(`/`)||r?`dir`:`file`),s=t.label??(n?n.split(`/`).pop()??n:`workspace`),c={id:n,kind:a,label:s},l=a===`file`,u=a===`dir`||r,d=a===`list`,f=(Y.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&&qg(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&&!r?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}});na({x:t.x,y:t.y,slot:`contextmenu.file`,target:c,entries:f,onHostAction:(n,r)=>{if(t.onHostAction){let e=t.onHostAction(n.id,r);if(e!==void 0)return e}switch(n.id){case`host:file-reveal`:i({type:`file_reveal`,path:r.id});break;case`host:file-open-default`:r.kind===`file`&&i({type:`file_open_default`,path:r.id});break;case`host:file-copy-name`:navigator.clipboard?.writeText(r.label??r.id),o(`info`,e(`copied`));break;case`host:file-copy-rel`:navigator.clipboard?.writeText(r.id),o(`info`,e(`copied`));break;case`host:file-copy-path`:{let t=Ae.current.state?.cwd??``,n=t?`${t.replace(/\\/g,`/`).replace(/\/+$/,``)}/${r.id}`:r.id;navigator.clipboard?.writeText(n),o(`info`,e(`copied`));break}}}})}})),()=>Qt(null)),[i]);let[Ne,Pe]=(0,Q.useState)(()=>qT(`left`)),[Fe,Ie]=(0,Q.useState)(()=>qT(`right`)),Le=(0,Q.useCallback)(e=>Pe(e),[]),Re=(0,Q.useCallback)(e=>Ie(e),[]),[ze,Be]=(0,Q.useState)(()=>YT(`left`)),[Ve,He]=(0,Q.useState)(()=>YT(`right`)),Ue=(0,Q.useCallback)(()=>{Be(e=>{try{localStorage.setItem(JT(`left`),e?`0`:`1`)}catch{}return!e})},[]),We=(0,Q.useCallback)(()=>{He(e=>{try{localStorage.setItem(JT(`right`),e?`0`:`1`)}catch{}return!e})},[]),[qe,Je]=(0,Q.useState)(null),Ye=_s(),Xe=(0,Q.useRef)(null),[Ze,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)},[]),xC({enabled:Ze&&F===`chat`,open:qe,onOpenChange:Je,container:Xe,backdropSelector:`.drawer-backdrop.persistent`});let[$e,et]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_web_setup_dismissed`)===`1`}catch{return!1}}),tt=()=>{et(!0);try{localStorage.setItem(`pi_web_setup_dismissed`,`1`)}catch{}},[nt,X]=(0,Q.useState)(!1),[rt,it]=(0,Q.useState)(!1),[at,ot]=(0,Q.useState)(),[ct,lt]=(0,Q.useState)(null),[ut,dt]=(0,Q.useState)(null),ft=(0,Q.useRef)(null),[pt,mt]=(0,Q.useState)(null),ht=(0,Q.useRef)(null),[gt,_t]=(0,Q.useState)([]),[vt,bt]=(0,Q.useState)(``),[xt,St]=(0,Q.useState)(null),Ct=(0,Q.useRef)(null),[Et,Dt]=(0,Q.useState)(()=>new Set),kt=(e,t)=>{i({type:`plugin_path_response`,id:e,ok:t}),Dt(t=>new Set(t).add(e))},At=n.pathRequests.find(e=>!Et.has(e.id))??null,[jt,Mt]=(0,Q.useState)(()=>new Set),Nt=(e,t,n=!1)=>{i({type:`plugin_permission_response`,id:e,ok:t,...n?{remember:!0}:{}}),Mt(t=>new Set(t).add(e))},Ft=n.permRequests.find(e=>!jt.has(e.id))??null,Rt=gw(),zt=Ew(),Bt=!!n.settings?.minimalNewChat&&(n.state?.messages?.length??0)===0&&!n.state?.streamingMessage,[Vt,Ut]=(0,Q.useState)(!1),[Gt,Kt]=(0,Q.useState)(!1),[qt,Zt]=(0,Q.useState)(!1),[$t,tn]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!$t)return;let e=setTimeout(()=>tn(null),15e3);return()=>clearTimeout(e)},[$t]);let[an,on]=(0,Q.useState)(null),sn=(0,Q.useRef)(null),ln=(0,Q.useRef)(null),un=n.state?.sessionId??``,dn=(0,Q.useRef)(un);dn.current=un;let fn=(0,Q.useRef)(n.ready);fn.current=n.ready,(0,Q.useEffect)(()=>{let e=()=>{let e=Ss(window.location.hash);if(e){if(e.messageId?on({sessionId:e.sessionId,messageId:e.messageId}):on(null),!fn.current||!dn.current){sn.current=e.sessionId;return}dn.current===e.sessionId||dn.current&&e.sessionId&&(dn.current.includes(e.sessionId)||e.sessionId.includes(dn.current))||(ln.current=e.sessionId,A(`chat`),i({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)}},[i]),(0,Q.useEffect)(()=>{let e=ln.current;if(e&&n.notices.some(t=>t.text.includes(e)&&(t.text.includes(`未找到会话`)||t.text.includes(`Session not found`)))&&(ln.current=null,on(null),un)){let e=Cs({sessionId:un});window.location.hash!==e&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${e}`)}},[n.notices,un]),(0,Q.useEffect)(()=>{if(!n.ready||!un)return;if(sn.current){let e=sn.current;if(sn.current=null,!(e===un||e&&un&&(e.includes(un)||un.includes(e)))){ln.current=e,A(`chat`),i({type:`switch_session`,path:``,sessionId:e});return}}if(ln.current){if(un===ln.current||un&&ln.current&&(un.includes(ln.current)||ln.current.includes(un)))ln.current=null;else return}let e=Ss(window.location.hash),t=e?.sessionId===un?e.messageId:void 0,r=Cs({sessionId:un,...t?{messageId:t}:{}});window.location.hash!==r&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${r}`)},[n.ready,un,i]),(0,Q.useEffect)(()=>{let t=t=>{let r=t.detail,a=r?.title||e(`pluginCommandFallback`),o=r?.command;if(!o||!n.ready)return;let c={name:a,command:o,cwd:"${pwd}"},l=n.terminals.find(e=>e.title===a),u;l?(s.restart(l.id),i({type:`run_command`,terminalId:l.id,conversationId:l.conversationId,command:c,cols:80,rows:24}),u=l.id):(u=Tt(),s.create({id:u,conversationId:n.activeConversationId||n.state?.conversationId||``,title:a,cwd:n.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:c})),s.select(u),A(`terminal`)};window.addEventListener(`pi-web-ui:plugin-run-command`,t),window.addEventListener(`pi-web-ui:run-command`,t);let r=e=>{let t=e.detail;typeof t==`string`&&t&&(A(e=>e===`chat`?e:`chat`),i({type:`switch_conversation`,id:t}),cn())};return window.addEventListener(`pi-web-ui:switch-conversation`,r),()=>{window.removeEventListener(`pi-web-ui:plugin-run-command`,t),window.removeEventListener(`pi-web-ui:run-command`,t),window.removeEventListener(`pi-web-ui:switch-conversation`,r)}},[n,s,i]),(0,Q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),Kt(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let[pn,mn]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_zen_mode`)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{pn?localStorage.setItem(`pi_zen_mode`,`1`):localStorage.removeItem(`pi_zen_mode`)}catch{}},[pn]);let hn=(0,Q.useCallback)(()=>{mn(e=>{let t=!e;return t&&F!==`chat`&&A(`chat`),t})},[F]);wt(()=>pn?(mn(!1),!0):!1,pn),(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(),hn())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[hn]);let[gn,_n]=(0,Q.useState)(OC),[vn,yn]=(0,Q.useState)(Uf),{themes:bn,theme:xn,switchTheme:Sn,reloadThemes:Cn}=Ot();DT(),(0,Q.useEffect)(()=>{try{typeof Yt==`function`&&Yt(xn??``)}catch{}},[xn]),(0,Q.useEffect)(()=>{try{typeof en==`function`&&en(t)}catch{}},[t]),(0,Q.useEffect)(()=>{try{typeof Wt==`function`&&Wt(F)}catch{}},[F]),(0,Q.useEffect)(()=>{try{let e=n.state?.model,t=e?`${e.provider}/${e.id}`:null;typeof nn==`function`&&nn(t)}catch{}},[n.state?.model?.provider,n.state?.model?.id]),(0,Q.useEffect)(()=>{if(!pt)return;let e=e=>{if(e.key!==`Escape`)return;let t=ht.current;ht.current=null,mt(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)},[pt]),(0,Q.useEffect)(()=>{if(!xt)return;let e=setTimeout(()=>{let e=Ct.current;Ct.current=null,St(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[xt]);let wn=(0,Q.useRef)(null),Tn=(0,Q.useRef)(null),En=(0,Q.useRef)(n.state?.messages);En.current=n.state?.messages;let Dn=(0,Q.useRef)(new Set),On=(0,Q.useRef)(new Set),kn=(0,Q.useRef)(new Set),An=(0,Q.useRef)(0),jn=(0,Q.useRef)(!1),Mn=(0,Q.useRef)(n.terminals);(0,Q.useEffect)(()=>{kC(gn)},[gn]),(0,Q.useEffect)(()=>{Wf(vn)},[vn]),(0,Q.useEffect)(()=>{let e=Mn.current;Mn.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 `)?i({type:`extensions_reload`}):n.startsWith(`pi-web-ui install `)||n.startsWith(`pi-web-ui uninstall `)?i({type:`plugins_reload`}):n.startsWith(`npm i -g `)&&(i({type:`extensions_reload`}),i({type:`plugins_reload`}),i({type:`check_updates_all`,force:!0}),i({type:`check_engines`,force:!0})))}},[n.terminals,i]),(0,Q.useEffect)(()=>{let t=n.state?.conversationId??null,r=cT(wn.current,t,n.state?.isStreaming??!1,n.conversations,Tn.current,!!n.state?.completionPending||!!n.state?.queue?.steering.length||!!n.state?.queue?.followUp.length);wn.current=r.nextMap,Tn.current=t;for(let[e,t]of r.nextMap.entries())t&&gs(e);if(r.startCue&&(IC(`start`,gn),ow(e(`notifyStartTitle`),e(`notifyStartBody`),`start`)),r.finishedConvs.length>0){let t=typeof document<`u`&&document.hasFocus?document.hasFocus():!0,i=[];for(let e of r.finishedConvs)if(!e.isActive||!t){let t=n.conversations.find(t=>t.id===e.id);i.push({id:e.id,sessionId:t?.sessionId,sessionFile:t?.sessionFile})}i.length>0&&hs(i),r.finishedConvs.some(e=>!e.isSubagent&&gn.done)?IC(`done`,gn):r.finishedConvs.some(e=>e.isSubagent)&&IC(`subagentDone`,gn);let a=r.finishedConvs.find(e=>e.isActive);if(a&&(ow(e(`notifyDoneTitle`),e(`notifyDoneBody`),a.isSubagent?`subagentDone`:`done`),vn.enabled)){if(vn.readReplies){if(!vn.streamReplies){let t=Yf(En.current);t?op(t,vn):vn.announce&&!qC(ew())&&op(e(`ttsAnnounceDone`),vn)}}else vn.announce&&!qC(ew())&&op(e(`ttsAnnounceDone`),vn)}for(let t of r.finishedConvs.filter(e=>!e.isActive)){let n=t.title?`${t.title}:${e(`notifyDoneBody`)}`:e(`notifyDoneBody`);ow(e(`notifyDoneTitle`),n,t.isSubagent?`subagentDone`:`done`)}!a&&vn.enabled&&vn.announce&&!qC(ew())&&op(e(`ttsAnnounceDone`),vn)}},[n.state?.conversationId,n.state?.isStreaming,n.state?.completionPending,n.state?.queue,n.conversations,gn,vn,e]),(0,Q.useEffect)(()=>{let e=n.state?.conversationId??null;e&&(gs(e),n.state?.sessionId&&gs(n.state.sessionId),n.state?.sessionFile&&gs(n.state.sessionFile))},[n.state?.conversationId,n.state?.sessionId,n.state?.sessionFile]),(0,Q.useEffect)(()=>{let e=()=>{let e=n.state?.conversationId;e&&(gs(e),n.state?.sessionId&&gs(n.state.sessionId),n.state?.sessionFile&&gs(n.state.sessionFile))};return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[n.state?.conversationId,n.state?.sessionId,n.state?.sessionFile]);let Nn=(0,Q.useRef)(null),Pn=(0,Q.useRef)(null),Fn=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let e=n.state?.isStreaming??!1,t=n.state?.conversationId;if(!(vn.enabled&&vn.readReplies&&vn.streamReplies)||!e){if(Nn.current){let e=En.current,t=Array.isArray(e)&&e.length>0?e[e.length-1]:null;if(t&&t.role===`assistant`&&Pn.current){let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
92
- `);Pn.current.flush(e)}Nn.current.finish(),Nn.current=null,Pn.current=null,Fn.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-Fn.current<150)return;if(Fn.current=a,!Nn.current){let e=lp(vn,t);Nn.current=e,Pn.current=new Jf(t=>{e.push(t)})}let o=(i.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
93
- `);Pn.current?.feed(o)},[n.state?.messages,n.state?.isStreaming,n.state?.conversationId,vn]),(0,Q.useEffect)(()=>{let t=n.dialog?.id??null;if(t!==null&&!Dn.current.has(t)){if(Dn.current.add(t),Dn.current.size>64){let e=Dn.current.values().next().value;e!==void 0&&Dn.current.delete(e)}IC(`question`,gn),ow(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),vn.enabled&&vn.announce&&!qC(ew())&&op(e(`ttsAnnounceQuestion`),vn)}},[n.dialog,gn,vn,e]),(0,Q.useEffect)(()=>{let t=n.question?.id??null,r=n.remoteQuestion?`${n.remoteQuestion.owner}:${n.remoteQuestion.id}`:null,i=!1;t!==null&&!On.current.has(t)&&(On.current.add(t),i=!0),r!==null&&!On.current.has(r)&&(On.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}`;On.current.has(n)||(On.current.add(n),e.questionId&&On.current.add(e.questionId),t!==e.questionId&&(i=!0))}if(On.current.size>64){let e=On.current.values().next().value;e!==void 0&&On.current.delete(e)}i&&(IC(`question`,gn),ow(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),vn.enabled&&vn.announce&&!qC(ew())&&op(e(`ttsAnnounceQuestion`),vn))},[n.question,n.remoteQuestion,n.conversations,gn,vn,e]),(0,Q.useEffect)(()=>{let t=n.approval,r=t?.id??null;if(r!==null&&!kn.current.has(r)){if(kn.current.add(r),kn.current.size>64){let e=kn.current.values().next().value;e!==void 0&&kn.current.delete(e)}IC(`approval`,gn);let n=typeof t?.toolName==`string`?t.toolName:``;ow(e(`notifyApprovalTitle`),n?e(`notifyApprovalBodyTool`,{tool:n}):e(`notifyApprovalBody`),`approval`),vn.enabled&&vn.announce&&!qC(ew())&&op(e(`ttsAnnounceApproval`),vn)}},[n.approval,gn,vn,e]),(0,Q.useEffect)(()=>{let t=[...n.notices].reverse().find(e=>e.level===`error`);t&&t.id!==An.current&&(An.current=t.id,IC(`error`,gn),ow(e(`notifyErrorTitle`),e(`notifyErrorBody`),`error`),vn.enabled&&vn.announce&&!qC(ew())&&op(e(`ttsAnnounceError`),vn))},[n.notices,gn,vn,e]);let In=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{let e=n.state?.messages??[];for(let t of e){if(t.toolName!==`live_preview`||In.current.has(t.id))continue;In.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(d(e),window.location.href);t.origin===window.location.origin&&document.hasFocus()&&(n=window.open(t.href,`_blank`,`noopener`))}catch{n=null}n||o(`info`,e)}},[n.state?.messages,o]);let Ln=(e,t,n,r=!1,i,a=!1)=>{let o=`${e}|${n}|${i?`${i.start}-${i.end}`:``}`;g(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&&Lt(`@${s} `)},Rn=e=>{let t=``;g(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&&Xt(`@${t}`)},zn=(0,Q.useCallback)(e=>(!e.type.startsWith(`list_`)&&!e.type.startsWith(`get_`)&&Je(null),i(e)),[i]),Bn=(0,Q.useRef)(new Set),Vn=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 Bn.current)i.has(e)||Bn.current.delete(e);for(let n of t){let t=`question-${n.id}`;if(n.id===Vn){cS(t,{silent:!0});continue}n.questionId&&Bn.current.has(n.questionId)||sS({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&&Bn.current.add(n.questionId)},onClick:()=>{zn({type:`switch_conversation`,id:n.id}),cS(t,{silent:!0})}})}lS(e=>{let t=e.data?.conversationId;return t?!r.has(t)||t===Vn:!1},{silent:!0})},[n.conversations,Vn,zn,e]);let Hn=Me(`chatUploadMaxMb`),[Un,Wn]=(0,Q.useState)({}),Gn=(0,Q.useRef)(0),Kn=(0,Q.useRef)(0),qn=(0,Q.useRef)(0),Jn=(0,Q.useCallback)(t=>{let r=Date.now();n.state?.model&&!n.state.model.vision&&r-qn.current>1e4&&(qn.current=r,o(`warning`,e(`imageNotSupported`)));let i=`paste-${++Kn.current}`;g(e=>[...e,{path:``,key:i,name:t.name,imageData:t.data,mimeType:t.mimeType}])},[n.state?.model,o,e]),Yn=(0,Q.useCallback)(async t=>{for(let n of t){if(n.size>Hn*1024*1024){o(`warning`,e(`fileTooLarge`,{name:n.name,size:Hn}));continue}let t=String(++Gn.current);Wn(e=>({...e,[t]:{name:n.name}}));try{let t=await jf(n);t?Jn(t):o(`error`,e(`imageLoadFailed`,{name:n.name}))}catch{o(`error`,e(`imageLoadFailed`,{name:n.name}))}finally{Wn(e=>{let n={...e};return delete n[t],n})}}},[Jn,o,e,Hn]),Xn=Hn*1024*1024,Qn=(0,Q.useRef)(0),$n=(0,Q.useCallback)(async t=>{if(t.size>Xn){o(`warning`,e(`fileTooLarge`,{name:t.name,size:Xn/1024/1024}));return}let n=String(++Gn.current);Wn(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&&Wn(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{o(`error`,e(`fileLoadFailed`,{name:t.name}));return}finally{Wn(e=>{let t={...e};return delete t[n],t})}let i=`upload-${++Qn.current}`;g(e=>[...e,{path:``,key:i,name:t.name,fileData:r,size:t.size,mimeType:t.type||void 0}])},[Xn,o,e]),er=(0,Q.useCallback)(async e=>{for(let t of e)Af(t.type)?await Yn([t]):await $n(t)},[Yn,$n]),tr=(0,Q.useCallback)((e,t,n)=>{i({type:`edit_message`,messageId:e,text:t,attachments:n})},[i]),nr=(0,Q.useCallback)((e,t,n,r)=>{i({type:`queue_remove`,kind:e,text:t,index:n,id:r})},[i]),[rr,ir]=(0,Q.useState)([]),ar=(0,Q.useRef)(0),or=(0,Q.useCallback)((e,t,n,r)=>{i({type:`queue_remove`,kind:e,text:t,index:n,id:r}),ar.current+=1;let a=zs(t),o={text:a.text,seq:ar.current};if(a.quotes.length&&g(e=>Iy(e,a.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:Tt()})))),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:Tt()}));e.length&&g(t=>Iy(t,e))}ir(e=>[...e.slice(-9),o])},[i]),sr=(0,Q.useCallback)(()=>X(!0),[]),cr=(0,Q.useCallback)(()=>g([]),[]),[lr,ur]=(0,Q.useState)(0),dr=(0,Q.useCallback)(()=>{cr(),ur(e=>e+1)},[cr]),fr=(0,Q.useCallback)(()=>{let e=n.state?.queue?.steering??[],t=n.state?.queue?.followUp??[],r=[...e,...t];for(let e of r){ar.current+=1;let t=zs(e);if(t.quotes?.length&&g(e=>Iy(e,t.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:Tt()})))),t.attachments?.length){let e=t.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:Tt()}));e.length&&g(t=>Iy(t,e))}ir(e=>[...e.slice(-9),{text:t.text,seq:ar.current}])}i({type:`abort`})},[n.state?.queue?.steering,n.state?.queue?.followUp,i]);_S(n.state?.sessionId??``,cr);let pr=(0,Q.useCallback)(Rn,[]),mr=Yn,hr=er,gr=(0,Q.useCallback)((e,t)=>i({type:`search_files`,reqId:e,query:t}),[i]),_r=(0,Q.useCallback)(e=>Ln(e.path,e.name,e.mode??`reference`,e.isDir??!1,e.lines,e.silent??!1),[]),vr=n.state?.model,yr=n.state?.thinkingLevel,br=n.state?.availableThinkingLevels,xr=(0,Q.useMemo)(()=>vr?{model:vr,thinkingLevel:yr??`off`,availableThinkingLevels:br??[]}:null,[vr,yr,br]),Sr=(0,Q.useCallback)(()=>!n.ready||n.terminals.length!==0?!1:(s.create({id:Tt(),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,s]);(0,Q.useEffect)(()=>{if(jn.current){if(F!==`terminal`||n.terminals.length!==0){jn.current=!1;return}Sr()&&(jn.current=!1)}},[n.terminals.length,Sr,F]);let Cr=(0,Q.useCallback)((e,t)=>{t?.skipAutoCreate?jn.current=!1:(jn.current=e===`terminal`&&n.terminals.length===0,jn.current&&Sr()&&(jn.current=!1)),A(e),Je(null)},[n.terminals.length,Sr]);return(0,$.jsxs)(`div`,{className:`app${pn?` zen-mode`:``}`,"data-pi-anchor":`app`,onDragOver:e=>{Array.from(e.dataTransfer?.types??[]).includes(`Files`)&&(e.preventDefault(),O(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||O(!1)},onDrop:t=>{if(O(!1),!Array.from(t.dataTransfer?.types??[]).includes(`Files`))return;t.preventDefault();let n=Array.from(t.dataTransfer?.files??[]);if(n.length===0){o(`warning`,e(`foldersNotSupported`));return}let r=n.filter(e=>Af(e.type)),i=n.filter(e=>!Af(e.type));r.length>0&&Yn(r),i.length>0&&er(i)},children:[(0,$.jsx)(yo,{}),pn&&(0,$.jsxs)(`button`,{type:`button`,className:`zen-exit-pill`,onClick:hn,title:e(`zenModeExitTip`),"aria-label":e(`zenModeExit`),children:[(0,$.jsx)(Ke,{}),(0,$.jsx)(`span`,{children:e(`zenModeExit`)})]}),D&&(0,$.jsx)(`div`,{className:`app-drop-overlay`,"aria-hidden":!0,children:(0,$.jsxs)(`span`,{children:[`📎 `,e(`dropHereToAttach`)]})}),(0,$.jsx)(vo,{chat:n,terminal:s,view:F,plugins:ee,uiPrimary:re,uiOverflow:z,uiContextTopbar:R[`contextmenu.topbar`],onUiAction:G,zenMode:pn,onToggleZenMode:hn,onViewChange:Cr,onOpenPanel:Je,onOpenSettings:()=>{ot(void 0),it(!0)},onManagePlugins:()=>{ot(`plugins`),it(!0)},onOpenBgTasks:()=>Ut(!0),onOpenGlobalSearch:()=>Kt(!0),onOpenIconEdit:()=>Zt(!0),onOpenSandboxModal:()=>lt(`create`),themes:bn,theme:xn,onThemeChange:Sn,reloadThemes:Cn}),qt&&(0,$.jsx)(gS,{slots:R,layout:n.settings?.uiLayout,exclude:Ci,onClose:()=>Zt(!1)}),n.protocolMismatch&&(0,$.jsxs)(`div`,{className:`protocol-banner`,children:[`⚠ `,e(`protocolMismatch`)]}),(0,$.jsxs)(`div`,{className:`notices`,children:[n.notices.map(e=>(0,$.jsx)(VT,{notice:e,onDismiss:a},e.id)),xt&&(0,$.jsxs)(`div`,{className:`notice notice-info`,role:`status`,children:[(0,$.jsx)(`span`,{className:`notice-text`,children:xt.text}),xt.actions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let t=Ct.current;Ct.current=null,St(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=Ct.current;Ct.current=null,St(null);try{e?.resolve(null)}catch{}},children:(0,$.jsx)(Z,{})})]}),U.length>0&&(0,$.jsx)(`div`,{className:`notice-actions`,role:`toolbar`,children:U.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=>G(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:()=>G(e),children:[e.icon?`${e.icon} `:``,e.badge??e.label]},e.id))})]}),(0,$.jsxs)(Cv,{currentModelId:vr?`${vr.provider}/${vr.id}`:null,children:[(0,$.jsx)(eS,{onAction:(e,t,n)=>G(e,n,t)}),(0,$.jsxs)(`div`,{ref:Xe,className:`layout`,style:{"--left-w":`${Ne}px`,"--right-w":`${Fe}px`},children:[Ze?(0,$.jsx)(`div`,{className:`drawer-backdrop persistent${qe?` on`:``}`,onClick:()=>Je(null)}):qe&&(0,$.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>Je(null)}),(0,$.jsx)(Ex,{side:`left`,items:_e,chat:n,view:F,plugins:ee,dropdownProps:{theme:xn,themes:bn,onThemeChange:Sn,reloadThemes:Cn},onViewChange:Cr,onOpenPanel:Je,onOpenSettings:e=>{ot(e),it(!0)},onOpenBgTasks:()=>Ut(!0),onOpenGlobalSearch:()=>Kt(!0),onUiAction:G,uiContextTopbar:R[`contextmenu.topbar`],onThemeToggle:()=>Sn(xn===`light`?null:`light`),onSoundToggle:()=>_n({...gn,enabled:!gn.enabled}),zenMode:pn,onToggleZenMode:hn}),(0,$.jsxs)(`div`,{className:`view-pane ${F===`chat`?``:`hidden`}`,children:[!Ze&&ze&&(0,$.jsx)(ZT,{side:`left`,onClick:Ue}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-left ${qe===`left`?`open`:``}${Ze?``:ze?` hidden`:``}`,children:(0,$.jsx)(Kg,{collapsible:!Ze,onToggleCollapse:Ue,panelSend:zn,active:!Ze||qe===`left`,unreadConvKeys:Ye,sessionFile:j?null:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,projectSessions:n.projectSessions,engine:n.engine,pathCompletions:n.pathCompletions,activeConversationId:j?``:n.activeConversationId,sharedConversationOwner:n.state?.sharedConversation?.owner,activeGroupId:j,uiContextSession:R[`contextmenu.session`],uiLeftSessions:B,uiContextProject:R[`contextmenu.project`],uiProjectsActions:ie,uiLeftProject:ae,uiRunningActions:V,uiHistoryActions:oe,uiSections:se,renderPluginSectionBody:K,uiLeftRunning:ce,uiLeftHistory:le,uiPluginRunning:n.pluginPanelGroups,onPluginRunningAction:q,onUiAction:G,presetNames:he,transition:n.transition,onOpenSandboxModal:()=>lt(`create`)})}),!Ze&&!ze&&(0,$.jsx)(XT,{side:`left`,width:Ne,onResize:Le}),(0,$.jsx)(`main`,{className:`${Rt?`main wide-chat`:`main`}${zt?` hide-model-row`:``}${n.transition&&!n.transition.previewMessages?.length?` main-transitioning`:``}${Bt?` main-minimal-empty`:``}`,children:j?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(BT,{roomId:j,active:F===`chat`,onBack:()=>M(null)},j)}):(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:!c(t)&&n.transition.textEn?n.transition.textEn:n.transition.text}),(0,$.jsxs)(`span`,{className:`workspace-transition-pct`,children:[n.transition.progress,`%`]})]})]}),pe.length>0&&(0,$.jsx)(`div`,{className:`chat-header`,role:`toolbar`,children:Av(pe,G)}),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)(Zn,{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:()=>i({type:`persist_sandbox`,path:n.state?.sandbox?.path}),children:[(0,$.jsx)(u,{"aria-hidden":!0}),` `,e(`sandboxActionPersist`)]}),n.state.sandbox.sourcePath&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn primary`,title:e(`sandboxActionApplySourceTip`),onClick:()=>lt(`apply`),children:[(0,$.jsx)(r,{"aria-hidden":!0}),` `,e(`sandboxActionApplySource`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPromoteTip`),onClick:()=>lt(`promote`),children:[(0,$.jsx)(ge,{"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}))&&i({type:`reset_sandbox`,path:t.path})},children:[(0,$.jsx)(yt,{"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}))&&i({type:`destroy_sandbox`,path:t.path})},children:[(0,$.jsx)(Ge,{"aria-hidden":!0}),` `,e(`sandboxActionDestroy`)]})]})]}),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:()=>i({type:`persist_conversation`,id:Vn}),children:[`💾 `,e(`saveEphemeral`)]})]}),(0,$.jsx)(jy,{uiMessageActions:R[`message.actions`],uiContextMessage:R[`contextmenu.message`],uiContextToolCall:R[`contextmenu.toolcall`],uiToolCardFooter:R[`tool.card.footer`],uiChatEmpty:me,onUiAction:G,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:tr,onKillBash:()=>{let e=n.state?.conversationId;e&&!n.transition&&i({type:`abort_bash`,conversationId:e})},onRetry:()=>{if(i({type:`retry_last`})){let e=n.state?.model;e&&qo(`${e.provider}/${e.id}`)}},onRemoveQueued:nr,onRecallQueued:or,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:$t,onJumpDone:()=>tn(null),urlJumpMessageId:an&&an.sessionId===n.state.sessionId?an.messageId:null,onUrlJumpDone:()=>on(null),userPromptNonce:lr},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)(ox,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId,uiGoalbarActions:fe,onUiAction:G})}),n.dialog&&(0,$.jsx)(Mx,{dialog:n.dialog}),pt&&(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":pt.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),pt.title&&(0,$.jsx)(`span`,{className:`dialog-title`,children:pt.title}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{let e=ht.current;ht.current=null,mt(null);try{e?.kind===`confirm`?e.resolve(!1):e?.resolve({ok:!1})}catch{}},children:`✕`})]}),pt.kind===`select`&&(0,$.jsxs)(`div`,{className:`dialog-options`,children:[(pt.options??[]).map((e,t)=>{let n=pt.multi?gt.includes(t):!1;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${n?`sel`:``}`,title:e.description,onClick:()=>{if(pt.multi){_t(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);return}let n=ht.current;ht.current=null,mt(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)}),(pt.options??[]).length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:e(`noOptions`)}),pt.multi&&(0,$.jsx)(`div`,{className:`dialog-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ht.current,t=(e?.options??[]).filter((e,t)=>gt.includes(t)).map(e=>e.label);ht.current=null,mt(null);try{e?.resolve({ok:!0,selected:t})}catch{}},children:e(`ok`)})})]}),pt.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=ht.current;ht.current=null,mt(null);try{e?.resolve(!1)}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ht.current;ht.current=null,mt(null);try{e?.resolve(!0)}catch{}},children:e(`ok`)})]})}),pt.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-body`,children:[(0,$.jsx)(`input`,{className:`dialog-input`,value:vt,placeholder:pt.placeholder||e(`inputPlaceholder`),autoFocus:!0,onChange:e=>bt(e.target.value),onKeyDown:e=>{if(e.key===`Enter`&&!e.nativeEvent.isComposing){let e=ht.current;ht.current=null,mt(null);try{e?.resolve({ok:!0,value:vt})}catch{}}}}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=ht.current;ht.current=null,mt(null);try{e?.resolve({ok:!1})}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=ht.current;ht.current=null,mt(null);try{e?.resolve({ok:!0,value:vt})}catch{}},children:e(`ok`)})]})]})]}),(0,$.jsx)(Zx,{questions:Fx(n.questionQueue,n.question,n.remoteQuestion,n.globalQuestions,n.state?.sharedConversation?.owner),activeConversationId:Vn,mode:n.settings?.questionPresentation??`queue`}),(0,$.jsx)(PS,{approvals:Ix(n.approvals,n.globalApprovals,n.state?.sharedConversation?.owner),activeConversationId:Vn,mode:n.settings?.toolApprovalPresentation??`all`}),(0,$.jsx)(LS,{plan:n.activeConversationId&&n.state?.conversationId!==n.activeConversationId?null:n.state?.plan}),Object.entries(Un).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)(ax,{composerLeading:R[`composer.leading`],composerActions:R[`composer.actions`],onUiAction:G,streaming:n.state?.isStreaming??!1,onAbort:fr,planMode:n.state?.planMode??!1,messages:n.state?.messages??HT,slashCommands:n.slashCommands,modelState:xr,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,defaultModel:n.defaultModel??void 0,attachments:h,onRemoveAttachment:pr,onAddImageFiles:mr,onAddLocalFiles:hr,onAddPathAttachment:_r,fileSearch:n.fileSearch,onSearchFiles:gr,onNotice:o,onManageModels:sr,onSent:dr,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:!pn&&(n.settings?.quickPhrasesEnabled??!0)&&(!n.settings?.minimalNewChat||(n.state?.messages?.length??0)>0||!!n.state?.streamingMessage),recallDrafts:rr,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})]})}),!Ze&&!Ve&&(0,$.jsx)(XT,{side:`right`,width:Fe,onResize:Re}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-right ${qe===`right`?`open`:``}${Ze?``:Ve?` hidden`:``}`,children:(0,$.jsx)(C_,{collapsible:!Ze,onToggleCollapse:We,panelSend:zn,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(e,t,n,r)=>{Je(null),Ln(e,t,n,r)},onPreview:(e,t)=>{Je(null),C(e,t)},onNotice:(e,t)=>o(e,t),uiRightPanelTabs:R[`rightpanel.tabs`],uiContextFile:R[`contextmenu.file`],plugins:ee,pluginsEpoch:n.pluginsEpoch,send:i})}),!Ze&&Ve&&(0,$.jsx)(ZT,{side:`right`,onClick:We})]}),(0,$.jsx)(`div`,{className:`view-pane ${F===`terminal`?``:`hidden`}`,children:(0,$.jsx)(sC,{active:F===`terminal`,children:(0,$.jsx)(OT,{chat:n,terminal:s,uiTerminalToolbar:ue,onUiAction:G})})}),(0,$.jsx)(`div`,{className:`view-pane ${F===`git`?``:`hidden`}`,children:(0,$.jsx)(sC,{active:F===`git`,children:(0,$.jsx)(kT,{chat:n,terminal:s,active:F===`git`,onSwitchToTerminal:()=>A(`terminal`),uiScmToolbar:de,onUiAction:G})})}),(0,$.jsx)(`div`,{className:`view-pane ${F===`canvas`?``:`hidden`}`,children:(0,$.jsx)(sC,{active:F===`canvas`,children:(0,$.jsx)(MT,{send:i,active:F===`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||`.`})})}),F===`worktrees`&&(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsx)(fx,{worktree:n.state?.worktree,onRefresh:I,onSwitch:e=>{L.current={source:n.state?.cwd??``,target:e},i({type:`switch_worktree`,path:e})},onRemove:e=>i({type:`remove_worktree`,path:e}),onBack:()=>{A(`chat`),cn()}})}),(0,$.jsx)(`div`,{className:`view-pane ${F===`devices`?``:`hidden`}`,children:(0,$.jsx)(sC,{active:F===`devices`,children:(0,$.jsx)(AT,{pathCompletions:n.pathCompletions})})}),ye.map(e=>{let t=`plugin:${e.info.id}`;return(0,$.jsx)(`div`,{className:`view-pane ${F===t?``:`hidden`}`,children:(0,$.jsx)(Qx,{entry:e})},e.info.id)}),F.startsWith(`plugin:`)&&!ye.some(e=>`plugin:${e.info.id}`===F)&&(0,$.jsx)($x,{pluginId:F.slice(7),info:n.plugins.find(e=>`plugin:${e.id}`===F),epoch:n.pluginsEpoch,failed:xe.includes(F.slice(7))}),(0,$.jsx)(Ex,{side:`right`,items:ve,chat:n,view:F,plugins:ee,dropdownProps:{theme:xn,themes:bn,onThemeChange:Sn,reloadThemes:Cn},onViewChange:Cr,onOpenPanel:Je,onOpenSettings:e=>{ot(e),it(!0)},onOpenBgTasks:()=>Ut(!0),onOpenGlobalSearch:()=>Kt(!0),onUiAction:G,uiContextTopbar:R[`contextmenu.topbar`],onThemeToggle:()=>Sn(xn===`light`?null:`light`),onSoundToggle:()=>_n({...gn,enabled:!gn.enabled}),zenMode:pn,onToggleZenMode:hn})]})]}),(0,$.jsx)(mx,{chat:n,bottombarItems:R.bottombar,onUiAction:G,onOpenSettings:()=>{ot(void 0),it(!0)},onViewChange:Cr,onOpenGlobalSearch:()=>Kt(!0),onOpenBgTasks:()=>Ut(!0)}),_&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(zT,{file:_,content:n.fileContent,onAddLines:(e,t,n,r)=>Ln(e,t,`lines`,!1,{start:n,end:r}),onAttach:(e,t,n)=>Ln(e,t,n),onClose:()=>v(null),uiFilePreviewToolbar:H,onUiAction:G})}),y&&(0,$.jsx)(cC,{file:y.file,plugin:y.plugin,declaration:y.declaration,epoch:n.pluginsEpoch,send:i,onClose:()=>b(null),onFallback:()=>{b(null),v(y.file)}}),w&&(0,$.jsx)(Dw,{src:w.src,alt:w.alt,onClose:()=>T(null)}),n.ready&&n.state&&n.state.piConfigured===!1&&!$e&&!nt&&!Pt()&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(NT,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,installResult:n.installResult,onClose:tt})}),nt&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(PT,{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:()=>X(!1)})}),rt&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(FT,{chat:n,terminal:s,initialSection:at,onSwitchToTerminal:()=>A(`terminal`),onClose:()=>it(!1),onOpenIconEdit:()=>Zt(!0),onOpenManageModels:()=>{it(!1),X(!0)},sound:gn,onSoundChange:_n,tts:vn,onTtsChange:yn})}),Vt&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(IT,{servers:n.bgServers,plugins:n.plugins,epoch:n.pluginsEpoch,send:i,onUiAction:G,autoCleanupMin:n.settings?.bgAutoCleanupMin??0,onClose:()=>Ut(!1)})}),(0,$.jsx)(qS,{}),(0,$.jsx)($S,{}),(0,$.jsx)(NS,{}),n.tuiOverlay&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(LT,{overlay:n.tuiOverlay})}),Oe&&(0,$.jsx)(oC,{entry:Oe,pluginView:ke?ye.find(e=>e.info.id===ke):void 0,onUiAction:(e,t)=>{G(e,t),Ce(null)},onClose:()=>Ce(null)}),(0,$.jsx)(sC,{active:Gt,children:(0,$.jsx)(RT,{open:Gt,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>Kt(!1),onSwitchSession:(e,t)=>{i({type:`switch_session`,path:e});let n=t&&t[0];tn(n?{path:e,role:n.role,timestamp:n.timestamp}:null)},onSwitchProject:e=>{i({type:`set_cwd`,path:e})},onPreviewFile:(e,t)=>{C(e,t)}})}),we&&(0,$.jsx)(wa,{currentCwd:we.initialPath||n.state?.cwd||``,pathCompletions:n.pathCompletions,workspaceRoots:n.state?.workspaceRoots??[],onClose:()=>{we.resolve({ok:!1,canceled:!0}),Te(null)},onSelectDirectory:e=>{we.resolve({ok:!0,path:e}),Te(null)},onCreateProject:e=>{i({type:`make_dir`,path:e}),we.resolve({ok:!0,path:e}),Te(null)},mode:`project`,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:e(`projectPickerTitle`)}),Ee&&(0,$.jsx)(TS,{currentModelId:Ee.currentModelId,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,onManageModels:()=>X(!0),defaultModel:n.defaultModel,onClose:()=>{Ee.resolve({ok:!1,canceled:!0}),De(null)},onSelect:(e,t)=>{Ee.resolve({ok:!0,modelId:e,name:t?.name,provider:t?.provider}),De(null)}}),N&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(jT,{onClose:()=>P(!1)})}),(Ft||At||ut)&&(0,$.jsxs)(`div`,{className:`modal-backdrop perm-modal-backdrop`,children:[Ft&&(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:()=>Nt(Ft.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[Ft.family===`net`?e(`pluginPermBodyNet`).replace(`{plugin}`,Ft.pluginId).replace(`{hosts}`,(Ft.hosts??[]).join(`, `)):e(`pluginPermBodyLlm`).replace(`{plugin}`,Ft.pluginId).replace(`{models}`,(Ft.models??[]).length>0?` ${(Ft.models??[]).join(`, `)}`:``),Ft.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:Ft.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Nt(Ft.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Nt(Ft.id,!0),children:e(`pluginPermOnce`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>Nt(Ft.id,!0,!0),children:e(`pluginPermAlways`)})]})]})]}),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(`pluginGrantRequestTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>kt(At.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginGrantRequestBody`).replace(`{plugin}`,At.pluginId).replace(`{path}`,At.path),At.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:At.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>kt(At.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>kt(At.id,!0),children:e(`pluginGrantAllow`)})]})]})]}),ut&&(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:()=>{ft.current=null,ut.resolve(!1),dt(null)},children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginSessionGrantBody`).replace(`{path}`,ut.path),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{ft.current=null,ut.resolve(!1),dt(null)},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{ft.current=null,ut.resolve(!0),dt(null)},children:e(`ok`)})]})]})]})]}),!rt&&Object.values(n.pluginJobs??{}).some(e=>e.phase!==`done`)&&(0,$.jsxs)(`div`,{className:`active-plugin-jobs-bar`,onClick:()=>{ot(`plugins`),it(!0)},title:e(`pluginJobRunning`),children:[(0,$.jsx)(yt,{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})()]}),ct&&(0,$.jsx)(ux,{mode:ct,currentCwd:n.state?.cwd,currentSandbox:n.state?.sandbox,sandboxDiff:n.sandboxDiff,projects:n.projects,send:i,onClose:()=>lt(null)}),(0,$.jsx)(hS,{})]})}function iE(){typeof document<`u`&&(aE(oE()),cE())}function aE(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty(`--msgs-gutter`,`${Math.round(e*100)/100}px`)}function oE(){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 sE(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 cE(){let e=()=>{let e=document.querySelector(`.messages`);return e?(aE(sE(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 lE(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 uE(e,t){let n=!1;return r=>{if(!lE(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 dE(e){let t=uE(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 fE=dE(`20261104T17521`),pE=class extends Q.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){fE(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}};ut(),At(kt()),tT(),Mt(),iE(),(0,In.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(pE,{children:(0,$.jsx)(Ae,{children:(0,$.jsx)(rE,{})})})})),!Pn&&`serviceWorker`in navigator&&window.addEventListener(`load`,()=>{let e=m();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(e=>{console.warn(`Service worker registration failed:`,e)})});export{Zm as $,Zb as A,Ui as At,tb as B,Gr as Bt,IC as C,Va as Ct,ax as D,ka as Dt,vx as E,Ma as Et,Ob as F,zr as Ft,sg as G,Mv as H,Rn as Ht,Pb as I,Vr as It,Th as J,Ch as K,sb as L,mr as Lt,qb as M,qi as Mt,Bb as N,ji as Nt,Xb as O,Ci as Ot,zb as P,ii as Pt,qm as Q,ib as R,Jr as Rt,HC as S,Ha as St,_x as T,ja as Tt,Av as U,jy as V,Gn as Vt,r_ as W,Ah as X,wh as Y,Ym as Z,$C as _,Bo as _t,Vw as a,op as at,WC as b,Oo as bt,nT as c,Sd as ct,Rw as d,hd as dt,Vm as et,dw as f,Pl as ft,LC as g,es as gt,gw as h,Ms as ht,ET as i,Kf as it,Kb as j,Ji as jt,Qb as k,Si as kt,sT as l,Od as lt,Ew as m,Dc as mt,mT as n,Hf as nt,Bw as o,zf as ot,xw as p,Oc as pt,jh as q,xT as r,Gf as rt,Uw as s,Bf as st,yT as t,qp as tt,Nw as u,md as ut,VC as v,wo as vt,TC as w,Aa as wt,nw as x,oo as xt,tw as y,Do as yt,eb as z,Yr as zt};