pi-web-ui 0.118.0 → 0.120.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +143 -1
- package/bin/hub-upgrade.mjs +33 -15
- package/bin/lib/atomic-file.mjs +90 -0
- package/dist/server/agent-service-daemon.js +44 -10
- package/dist/server/agent-service.js +930 -166
- package/dist/server/approval-default-rules.js +4 -4
- package/dist/server/ask-user-question-tool.js +3 -40
- package/dist/server/atomic-file.js +130 -5
- package/dist/server/background-executors.js +235 -0
- package/dist/server/bash-timeout.js +47 -0
- package/dist/server/bash-tool.js +72 -5
- package/dist/server/bg-servers.js +19 -13
- package/dist/server/browser-page-tool.js +38 -29
- package/dist/server/browser-script-tool.js +119 -0
- package/dist/server/canvas/canvas-agent-tool.js +46 -35
- package/dist/server/canvas/canvas-dispatch.js +12 -1
- package/dist/server/claim-files-tool.js +6 -7
- package/dist/server/client-state.js +457 -41
- package/dist/server/communicate-tool.js +59 -77
- package/dist/server/compact-context-tool.js +4 -13
- package/dist/server/conversation-communication.js +23 -1
- package/dist/server/conversation-read-tool.js +14 -23
- package/dist/server/conversation-rows.js +17 -0
- package/dist/server/conversation-tool-names.js +2 -2
- package/dist/server/conversation-tool.js +23 -15
- package/dist/server/conversation-touches.js +1 -1
- package/dist/server/delegate-mode.js +0 -1
- package/dist/server/delegate-task.js +18 -39
- package/dist/server/device-center/approval-summary.js +0 -1
- package/dist/server/device-center/bot-execution.js +0 -1
- package/dist/server/device-center/group-router-runtime.js +2 -0
- package/dist/server/device-center/hub-upgrade.js +5 -10
- package/dist/server/device-center/task-progress.js +2 -2
- package/dist/server/dispatch-domain-handlers.js +97 -24
- package/dist/server/dispatch-plugin-handlers.js +10 -0
- package/dist/server/dsh/dsh-agent-service.js +21 -19
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/edit-tool.js +293 -0
- package/dist/server/engine-catalog.js +8 -2
- package/dist/server/engine-cli.js +29 -7
- package/dist/server/engine-probe.js +11 -6
- package/dist/server/eval-tool.js +5 -19
- package/dist/server/files-service.js +41 -19
- package/dist/server/fs-copy.js +93 -0
- package/dist/server/goal-review-gate.js +2 -3
- package/dist/server/index.js +92 -3
- package/dist/server/job-runner.js +345 -0
- package/dist/server/lsp-tool.js +10 -28
- package/dist/server/marker-service.js +42 -30
- package/dist/server/mcp-agent-tool.js +22 -47
- package/dist/server/model-session.js +16 -0
- package/dist/server/native-cli-session-hooks.js +3 -2
- package/dist/server/native-cli-session.js +27 -2
- package/dist/server/patch-tool.js +2 -8
- package/dist/server/phone-tool.js +167 -0
- package/dist/server/plan-mode.js +7 -4
- package/dist/server/plan-update-tool.js +5 -8
- package/dist/server/plugin-api-catalog.js +13 -1
- package/dist/server/plugin-bundled.js +35 -28
- package/dist/server/plugin-catalog.js +6 -0
- package/dist/server/plugin-delivery.js +358 -0
- package/dist/server/plugin-inbox.js +152 -0
- package/dist/server/plugin-installer.js +15 -0
- package/dist/server/plugin-ledger.js +183 -0
- package/dist/server/plugin-manifest-validate.js +19 -0
- package/dist/server/plugin-materialize.js +161 -0
- package/dist/server/plugin-paths.js +60 -0
- package/dist/server/plugin-removal.js +16 -3
- package/dist/server/plugin-schedule.js +8 -7
- package/dist/server/plugin-secrets.js +7 -3
- package/dist/server/plugin-updater.js +2 -4
- package/dist/server/plugins.js +205 -48
- package/dist/server/present-files-tool.js +7 -13
- package/dist/server/preset-fields.js +23 -12
- package/dist/server/preset-share.js +1 -1
- package/dist/server/process-utils.js +11 -0
- package/dist/server/project-scripts.js +38 -0
- package/dist/server/prompt-composer.js +40 -21
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/question-params.js +98 -0
- package/dist/server/quick-ask-settings.js +0 -1
- package/dist/server/quick-ask.js +3 -0
- package/dist/server/read-tool.js +10 -17
- package/dist/server/remote-ssh-service.js +40 -1
- package/dist/server/sandbox-runtime-gate.js +1 -1
- package/dist/server/sandbox-service.js +0 -1
- package/dist/server/sandbox-tool.js +25 -34
- package/dist/server/schedule-agent-tool.js +9 -19
- package/dist/server/scm-commitmsg.js +2 -1
- package/dist/server/serialize.js +8 -0
- package/dist/server/session-list-index.js +246 -0
- package/dist/server/session-list-scan.js +5 -0
- package/dist/server/session-parser.js +16 -0
- package/dist/server/settings-service.js +49 -19
- package/dist/server/skill-tool.js +4 -6
- package/dist/server/subagent-budget.js +68 -0
- package/dist/server/subagent-evidence.js +297 -0
- package/dist/server/subagent-helpers.js +12 -0
- package/dist/server/subagent-ledger.js +401 -0
- package/dist/server/subagent-notify.js +6 -2
- package/dist/server/subagent-security-gate.js +2 -3
- package/dist/server/subagent-settle.js +71 -0
- package/dist/server/subagents.js +566 -211
- package/dist/server/tabs.js +8 -1
- package/dist/server/terminals.js +34 -28
- package/dist/server/tool-approval.js +15 -1
- package/dist/server/tool-guards.js +0 -91
- package/dist/server/tool-manager.js +127 -47
- package/dist/server/tool-overrides.js +8 -1
- package/dist/server/tool-prompt-overrides.js +3 -6
- package/dist/server/tool-prompts.js +60 -17
- package/dist/server/universal/driver-base.js +2 -0
- package/dist/server/universal/drivers/claude-code.js +210 -211
- package/dist/server/universal/drivers/codex.js +29 -24
- package/dist/server/universal/engine-mcp.js +107 -0
- package/dist/server/universal/universal-attachments.js +77 -1
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +106 -69
- package/dist/server/vision-bridge.js +2 -0
- package/dist/server/workspace-handle.js +119 -17
- package/dist/server/workspace-queue.js +37 -0
- package/dist/server/worktree-tool.js +13 -20
- package/docs/README.md +40 -36
- package/docs/architecture-plugins.md +64 -35
- package/docs/device-center.md +1 -1
- package/package.json +16 -4
- package/plugin-sdk/index.d.ts +102 -0
- package/plugins/catalog.json +23 -51
- package/themes/bases/flow-base.css +8 -17
- package/themes/dark-teal.css +0 -3
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
- package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
- package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
- package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
- package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
- package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
- package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
- package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
- package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
- package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
- package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
- package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
- package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
- package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
- package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
- package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
- package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
- package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
- package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
- package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
- package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
- package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
- package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
- package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
- package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
- package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
- package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
- package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
- package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
- package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
- package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
- package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
- package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
- package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
- package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
- package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
- package/web/dist/assets/index-BD29OL9L.js +404 -0
- package/web/dist/assets/index-BlCxbqqr.js +404 -0
- package/web/dist/assets/index-DB55rbKC.css +1 -0
- package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
- package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
- package/web/dist/assets/theme-CpQk_Agp.js +1 -0
- package/web/dist/index.html +10 -10
- package/web/dist/sw.js +1 -1
- package/dist/server/edit-soft-tool.js +0 -297
- package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
- package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
- package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
- package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
- package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
- package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
- package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
- package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
- package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
- package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
- package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
- package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
- package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
- package/web/dist/assets/index-CQc3VrWa.css +0 -1
- package/web/dist/assets/index-D_AGu4Zv.js +0 -404
- package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
- package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
- package/web/dist/assets/theme-DGL7hLUs.js +0 -1
|
@@ -0,0 +1,404 @@
|
|
|
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-vdSIOPjD.js","./app-globals-CBEscsYP.js","./uuid-BzDIGCwP.js","./TermXterm-SYc-MUk2.js","./theme-CpQk_Agp.js","./xterm-Cf5xxe4g.js","./xterm-B1njb2Cr.css","./NativeCliPanel-B108d697.js","./composer-bridge-CImnjDHq.js","./SCMPanel-DluNcd2-.js","./DeviceCenter-By1zVTSY.js","./DeviceExecutionSettings-qJzbI0Cf.js","./GroupWorkItems-BYJv2XFj.js","./DeviceGroups-DPrQxW6B.js","./shortcut-stack-hhrDyRBn.js","./group-view-state-CGCzYF8k.js","./CanvasStudio-DU6O3N4u.js","./canvas-client-Clsypfs6.js","./es-DWMIuDU2.js","./PiSetupModal-D0HitBfd.js","./desktop-C6D9a8HZ.js","./ProviderOAuthControls-BLKUEDde.js","./ModelConfigModal-D2Ro-jUZ.js","./SettingsModal-Dm_haPme.js","./plugin-host-VWBcq-LQ.js","./HintTip-DFhoclDw.js","./SettingsModal-Cy5lRC97.css","./BgTasksModal-SAH2XCkY.js","./TuiOverlayModal-Cy1jYYIw.js","./GlobalSearchModal-CiT6wBmR.js","./FilePreview-CC76Z6an.js","./GroupConversation-HeiyW_O_.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,An as r,At as i,B as a,Bn as o,C as s,Cn as c,Ct as l,D as u,Dn as d,Dt as f,E as p,Et as m,F as h,Fn as g,Ft as _,G as v,Gn as y,Gt as b,H as x,Hn as S,Ht as C,I as w,In as T,It as E,J as D,Jt as O,K as k,Kn as A,Kt as j,L as M,Ln as N,M as P,Mn as F,Mt as I,N as L,Nn as R,Nt as z,O as B,On as ee,Ot as V,P as te,Pn as ne,Pt as re,Q as ie,Qt as H,R as ae,Rn as U,Rt as oe,Sn as se,St as ce,Tn as W,Tt as le,U as G,Un as K,Ut as ue,V as de,Vn as fe,W as pe,Wn as q,Wt as me,X as he,Xt as ge,Y as _e,Yt as ve,Z as J,_ as ye,_n as be,_t as xe,a as Se,an as Ce,at as Y,b as we,bn as Te,bt as Ee,c as De,cn as Oe,ct as ke,d as Ae,dt as je,en as Me,et as Ne,f as Pe,fn as Fe,ft as Ie,g as Le,gn as Re,h as ze,hn as Be,ht as Ve,i as He,in as Ue,it as We,j as Ge,jn as X,jt as Ke,k as qe,kn as Je,kt as Ye,l as Xe,ln as Ze,lt as Qe,m as $e,mn as et,mt as tt,n as nt,nn as rt,nt as it,o as at,on as ot,ot as st,p as ct,pn as lt,pt as ut,q as dt,qt as ft,r as pt,rn as mt,rt as ht,s as gt,sn as _t,st as vt,t as Z,tn as yt,tt as bt,u as xt,un as St,ut as Ct,vn as wt,w as Tt,wn as Et,wt as Dt,x as Ot,xn as kt,xt as At,y as jt,yn as Mt,yt as Nt,z as Pt,zn as Ft,zt as It}from"./app-globals-CBEscsYP.js";import{i as Lt,n as Rt,r as zt,t as Bt}from"./react-CR5VJ85Q.js";import{t as Vt}from"./shortcut-stack-hhrDyRBn.js";import{t as Ht}from"./uuid-BzDIGCwP.js";import{n as Ut,t as Wt}from"./Dropdown-kj_NIj6e.js";import{a as Gt,i as Kt,n as qt,t as Jt}from"./theme-CpQk_Agp.js";import{i as Yt,n as Xt,r as Zt,t as Qt}from"./desktop-C6D9a8HZ.js";import{a as $t,c as en,d as tn,f as nn,h as rn,i as an,m as on,n as sn,p as cn,r as ln,s as un,t as dn,u as fn}from"./composer-bridge-CImnjDHq.js";import{C as pn,E as mn,T as hn,_ as gn,a as _n,b as vn,c as yn,d as bn,f as xn,g as Sn,h as Cn,i as wn,l as Tn,m as En,n as Dn,o as On,p as kn,r as An,t as jn,v as Mn,w as Nn,y as Pn}from"./plugin-host-VWBcq-LQ.js";import{i as Fn,n as In,r as Ln,t as Rn}from"./HintTip-DFhoclDw.js";import{a as zn,c as Bn,i as Vn,l as Hn,n as Un,o as Wn,r as Gn,s as Kn,t as qn,u as Jn}from"./remote-ssh-client-C2eab5Kw.js";import{a as Yn,c as Xn,d as Zn,h as Qn,l as $n,m as er,s as tr,t as nr,u as rr}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 ir(e){let t=new Map;return{get length(){return t.size},clear(){let n=[...t.keys()];t.clear();for(let t of n)e?.(t,null)},getItem(e){return t.get(String(e))??null},key(e){return[...t.keys()][Number(e)>>>0]??null},removeItem(n){n=String(n),t.delete(n)&&e?.(n,null)},setItem(n,r){n=String(n),r=String(r),t.set(n,r),e?.(n,r)}}}function ar(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:ir(t===`localStorage`?(t,n)=>{t===`pi-theme`&&e.parent.postMessage({type:`device-portal-theme-write`,value:n},e.location.origin)}:void 0)})}if(!n)return!1;try{e.navigator.serviceWorker}catch{try{Object.defineProperty(e.navigator,"serviceWorker",{configurable:!0,get:()=>void 0})}catch{}}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}function or(e,t=500){return new Promise(n=>{let r=()=>{clearTimeout(a),e.removeEventListener(`message`,i),n()},i=t=>{if(t.source!==e.parent||t.origin!==e.location.origin||t.data?.type!==`device-portal-theme`)return;let n=t.data.value;n===null?e.localStorage.removeItem(`pi-theme`):typeof n==`string`&&/^[A-Za-z0-9_-]{1,256}$/.test(n)&&e.localStorage.setItem(`pi-theme`,n),r()},a=setTimeout(r,t);e.addEventListener(`message`,i),e.parent.postMessage({type:`device-portal-theme-read`},e.location.origin)})}var sr=typeof window<`u`&&ar(window),cr=zt(),lr=Rt(),Q=e(Lt(),1);function ur(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 dr(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=ur(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]),Vt(()=>{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 fr=null,pr=new Set,mr=e=>(pr.add(e),()=>{pr.delete(e)}),hr=()=>fr;function gr(e){fr===e&&(fr=null,pr.forEach(e=>e()))}async function _r(e,t,n,r,i=!1){let a=K();if(a){if(!a.deviceAdapter)throw Error(`Native device access is unavailable`);await a.deviceAdapter.openDevice(e,t);return}let s=n&&!i,c=window.piDesktop,l=s||c?.openHub?null:window.open(`about:blank`,`_blank`);if(!s&&!c?.openHub&&!l)throw Error(r?`请允许弹出窗口后重试。`:`Allow popups and try again.`);l&&(l.opener=null);try{let i=await fetch(o(g(`/api/device-center/devices/${encodeURIComponent(e)}/open`)),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({preferLan:!0,desktop:n,basePath:new URL(g(`/`),window.location.href).pathname}),credentials:`same-origin`,signal:AbortSignal.timeout(15e3)});if(!i.ok)throw Error(r?`无法打开设备,请确认设备在线且本机绑定有效。`:`Could not open the device. Check connectivity and local pairing.`);let a=await i.json(),u=a.transport===`lan`,d=u?new URL(g(a.url),window.location.href):new URL(a.url),f=new URL(t),p=new URL(g(`/device-lan/${e}/__open`),window.location.href),m=u?typeof a.url==`string`&&/^\/device-lan\/[a-z0-9][a-z0-9-]{0,62}\/__open\?ticket=[a-f0-9]{64}$/.test(a.url)&&d.origin===p.origin&&d.pathname===p.pathname:d.hostname===f.hostname&&(d.pathname===`/__device/open`||d.origin===f.origin&&d.pathname===`/device/${encodeURIComponent(e)}/__open`);if(![`http:`,`https:`].includes(d.protocol)||d.username||d.password||!m)throw Error(`Invalid device access URL`);if(d.searchParams.delete(`next`),n&&d.searchParams.set(`next`,`/desktop`),s)fr={id:e,hubUrl:t,url:d.href,zh:r,transport:u?`lan`:`hub`},pr.forEach(e=>e());else if(c?.openHub){if(u&&(d.searchParams.set(`hub`,f.origin),typeof a.fallbackOrigin==`string`&&d.searchParams.set(`portal`,a.fallbackOrigin)),!await c.openHub(d.href))throw Error(r?`无法打开设备窗口。`:`Could not open device window.`)}else l&&l.location.replace(d.href)}catch(e){throw l?.close(),e}}var $=Bt();function vr({hubUrl:e,currentDeviceId:r,onRemarkUpdated:i}){let{locale:a}=c(),s=X(a),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(0),[h,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(o(g(`/api/device-center/devices`)),{signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]),credentials:`same-origin`});if(!n.ok)throw Error(n.status===409?s?`请重新绑定本机以读取设备列表。`:`Pair this computer again to read the device list.`:s?`无法读取设备列表,请重试。`:`Could not load devices. Try again.`);let r=await n.json();if(!Array.isArray(r.devices))throw Error(s?`设备列表格式异常。`:`Invalid device list.`);e||(u(r.devices),f(``))}catch(t){e||(u([]),f(t instanceof Error?t.message:String(t)))}finally{e||(n=setTimeout(r,5e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[e,r,p,s]);function S(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 C(t,n,r=!1){t.preventDefault();try{await _r(n,e,r,s),f(``)}catch(e){f(e instanceof Error?e.message:String(e))}}async function w(e,t){x(e);let n=t.trim();try{let t=await fetch(o(g(`/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||(s?`保存备注失败`:`Failed to save remark`))}u(t=>t.map(t=>t.id===e?{...t,remark:n||void 0}:t)),_(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{x(null)}}return(0,$.jsxs)(`section`,{className:`dc-card`,"aria-label":s?`所有设备`:`All devices`,children:[(0,$.jsxs)(`div`,{className:`dc-card-header`,children:[(0,$.jsx)(`span`,{className:`dc-icon`,children:(0,$.jsx)(re,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{children:[s?`所有设备`:`All devices`,` · `,l.length]}),(0,$.jsx)(`p`,{children:s?`同一账号下的设备,使用本机绑定授权直接访问。`:`Devices in your account. Access is authorized through this computer's pairing.`})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-icon-button`,"aria-label":s?`刷新设备`:`Refresh devices`,onClick:()=>m(e=>e+1),children:(0,$.jsx)(ue,{})})]}),d&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:d}),(0,$.jsx)(`div`,{className:`dd-list`,children:l.map(e=>{let i=!!e.remark?.trim(),a=i?e.remark.trim():e.name,o=h===e.id;return(0,$.jsxs)(`div`,{className:`dd-device`,style:o?{flexWrap:`wrap`}:void 0,children:[(0,$.jsx)(`span`,{className:`dc-device-icon`,children:(0,$.jsx)(re,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`dd-identity`,children:[(0,$.jsx)(`strong`,{children:a}),(0,$.jsxs)(`span`,{children:[i?`${e.name} · `:``,e.id===r?s?`本机`:`This device`:e.id]})]}),(0,$.jsx)(`span`,{className:`dc-status ${e.online?`is-online`:`is-offline`}`,children:e.online?s?`在线`:`Online`:s?`离线`:`Offline`}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,title:s?i?`修改备注`:`设置备注`:i?`Edit remark`:`Set remark`,onClick:()=>{o?_(null):(_(e.id),y(e.remark??``))},children:[(0,$.jsx)(J,{"aria-hidden":!0}),s?i?`修改备注`:`设置备注`:i?`Edit remark`:`Set remark`]}),S(e.id)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`a`,{className:`dc-button`,href:S(e.id),target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void C(t,e.id),children:[(0,$.jsx)(t,{"aria-hidden":!0}),s?`打开设备`:`Open device`]}),(0,$.jsxs)(`a`,{className:`dc-button`,href:`${S(e.id)}/desktop`,target:`_blank`,rel:`noopener noreferrer`,onClick:t=>void C(t,e.id,!0),children:[(0,$.jsx)(re,{"aria-hidden":!0}),s?`远程桌面`:`Remote desktop`]})]})]}),o&&(0,$.jsxs)(`form`,{className:`dd-remark-form`,style:{display:`flex`,alignItems:`center`,gap:`8px`,width:`100%`,paddingTop:`8px`,paddingBottom:`4px`},onSubmit:t=>{t.preventDefault(),w(e.id,v)},children:[(0,$.jsx)(`input`,{type:`text`,maxLength:80,autoFocus:!0,disabled:b===e.id,placeholder:s?`输入设备备注(留空清除)`:`Device remark (leave blank to clear)`,value:v,onChange:e=>y(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:b===e.id,children:[(0,$.jsx)(n,{"aria-hidden":!0}),b===e.id?s?`保存中…`:`Saving…`:s?`保存`:`Save`]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:b===e.id,onClick:()=>_(null),children:[(0,$.jsx)(Be,{"aria-hidden":!0}),s?`取消`:`Cancel`]})]})]},e.id)})})]})}function yr({label:e=`pi-web-ui`,barItem:t=!1,onContextMenu:n}){let{locale:r}=c(),i=X(r),[a,s]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(!1),d=(0,Q.useRef)(null),{panelRef:f,style:p}=dr({open:l&&!!a,anchor:d,align:`left`,onClose:()=>u(!1)});(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(o(g(`/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;s(e?{hubUrl:r.hubUrl,deviceId:r.deviceId}:null),e||u(!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:`${F()}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:d,"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":l,onClick:()=>u(e=>!e),children:m}),l&&(0,cr.createPortal)((0,$.jsx)(`div`,{ref:f,style:p,className:`brand-device-panel`,role:`dialog`,"aria-label":i?`设备列表`:`Devices`,children:(0,$.jsx)(vr,{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 br(e){return Mt({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 xr(e){return Mt({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 Sr(e){return Mt({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8`},child:[]},{tag:`path`,attr:{d:`M10 19v-3.96 3.15`},child:[]},{tag:`path`,attr:{d:`M7 19h5`},child:[]},{tag:`rect`,attr:{width:`6`,height:`10`,x:`16`,y:`12`,rx:`2`},child:[]}]})(e)}function Cr(e){return Mt({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`},child:[]},{tag:`path`,attr:{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`},child:[]}]})(e)}function wr(e){return Mt({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 Tr(e){return Mt({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`m5 8 6 6`},child:[]},{tag:`path`,attr:{d:`m4 14 6-6 2-3`},child:[]},{tag:`path`,attr:{d:`M2 5h12`},child:[]},{tag:`path`,attr:{d:`M7 2h1`},child:[]},{tag:`path`,attr:{d:`m22 22-5-10-5 10`},child:[]},{tag:`path`,attr:{d:`M14 18h6`},child:[]}]})(e)}function Er(e){return Mt({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 Dr(e){return Mt({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`},child:[]},{tag:`path`,attr:{d:`M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`},child:[]},{tag:`path`,attr:{d:`M3 5a2 2 0 0 0 2 2h3`},child:[]},{tag:`path`,attr:{d:`M3 3v13a2 2 0 0 0 2 2h3`},child:[]}]})(e)}function Or(e){return Mt({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 kr(e){return Mt({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`},child:[]},{tag:`circle`,attr:{cx:`12`,cy:`12`,r:`10`},child:[]}]})(e)}function Ar(e){return e.map(e=>e.kind===`package`?`pi update npm:${e.name}`:e.kind===`git-extension`?`pi update ${jr(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 jr(e){return e.startsWith(`git:`)?e:`git:${e}`}function Mr(){let e=window.__piBrowser;return e?.version===1&&typeof e.pageCall==`function`?e:void 0}var Nr=()=>{let e=Mr();if(e)return t=>e.pageCall({...t,timeoutMs:t.timeoutMs??3e4});let t=window.__piWebUiHost;return t?.pageCall?.bind(t)},Pr=null,Fr=0;function Ir(){return Pr?.available===!0?Pr.pages??[]:[]}function Lr(){Date.now()-Fr<5e3||Rr().catch(()=>{})}async function Rr(){if(Zt()&&!Mr())return{available:!1,pages:[],desktop:!0,error:`此桌面版尚未提供原生浏览器桥:请升级到支持 AI Browser 的桌面版,或在系统浏览器中使用 page-picker 扩展`};let e=Nr();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,...Mr()?{native:!0}:{},aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,...typeof n.activeTabId==`string`?{activeTabId:n.activeTabId}:{},...typeof n.activeOrigin==`string`?{activeOrigin:n.activeOrigin}:{},pages:Array.isArray(n.pages)?n.pages:[]};return r.available&&(Pr=r,Fr=Date.now()),r}catch(e){return{available:!1,pages:[],error:e instanceof Error?e.message:String(e)}}}function zr(e){let t=e.tabId??e.origin;return{path:t,name:e.title?.trim()||e.origin,mode:`page`,key:`page:${t}`}}async function Br(){let e=Nr();if(!e)return!1;try{return(await e({op:`openOptions`,timeoutMs:5e3})).ok===!0}catch{return!1}}function Vr(e=45e3){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(!0),i=(0,Q.useCallback)(async e=>{let t=await Rr();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 Hr(){let e=W(),{locale:t}=c(),n=X(t),{status:r,refresh:i}=Vr(),[a,o]=(0,Q.useState)(!1),[s,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),p=typeof window<`u`?window.piDesktop?.browser:void 0;(0,Q.useEffect)(()=>{if(!p)return;p.getState().then(e=>{e&&typeof e==`object`&&f(e)});let e=p.onState(e=>{e&&typeof e==`object`&&f(e)});return()=>{e?.()}},[p]);let m=e=>{l(e),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>l(null),2600)},h=t=>{let n=dn({attachments:[zr(t)]});m(e(n?`browserControlCited`:`browserControlCiteFailed`))},g=()=>{o(!0),i(),p&&p.getState().then(e=>{e&&typeof e==`object`&&f(e)})};if(p){let t=d?.mode===`split`,c=d?.mode===`browser`,l=()=>{let e=t||c?`agent`:`split`;p.setMode(e)},u=t?n?`收起浏览器分栏 (Ctrl+Shift+2) · 右键打开选项`:`Collapse browser split (Ctrl+Shift+2) · Right-click for options`:n?`打开浏览器分栏 (Ctrl+Shift+3) · 右键打开选项`:`Open browser split (Ctrl+Shift+3) · Right-click for options`;return(0,$.jsxs)(`span`,{className:`bc-anchor`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${t?` active`:``}`,"data-tip":u,title:u,onClick:l,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),g()},children:[(0,$.jsx)(kr,{size:14,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:e(`browserControl`)})]}),s&&(0,$.jsx)(`span`,{className:`bc-flash`,children:s}),a&&(0,$.jsx)(Ur,{status:r,desktop:p,desktopState:d,onRefresh:i,onCite:h,onClose:()=>o(!1)})]})}let _=r?.pages??[],v=r?.available===!0&&(_.length===0||r.aiControl===!1);return(0,$.jsxs)(`span`,{className:`bc-anchor`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${v?` attention`:``}`,"data-tip":r?.error??e(v?`browserControlEmpty`:`browserControlTip`),title:r?.error??e(v?`browserControlEmpty`:`browserControlTip`),onClick:g,children:[(0,$.jsx)(kr,{size:14,"aria-hidden":!0}),(0,$.jsxs)(`span`,{children:[e(`browserControl`),_.length>0?` · ${_.length}`:``]})]}),s&&(0,$.jsx)(`span`,{className:`bc-flash`,children:s}),a&&(0,$.jsx)(Ur,{status:r,desktop:p,desktopState:d,onRefresh:i,onCite:h,onClose:()=>o(!1)})]})}function Ur({status:e,desktop:t,desktopState:n,onRefresh:r,onCite:i,onClose:a}){let o=W(),{locale:s}=c(),l=X(s),[u,d]=(0,Q.useState)(!1),f=e?.pages??[],p=async()=>{d(!0);try{await Br()||r()}finally{d(!1)}},h=async e=>{t&&(await t.setMode(e),a())},g=async()=>{t&&(await t.createTab(),a())};return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:a,children:(0,$.jsxs)(`div`,{className:`modal browser-control-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":o(`close`),onClick:a,children:`✕`}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(kr,{size:16,"aria-hidden":!0}),(0,$.jsx)(`h2`,{children:o(`browserControl`)})]}),(0,$.jsx)(`div`,{className:`modal-desc`,children:t?l?`桌面内置浏览器已就绪,可在右侧并列分栏浏览网页,或切换到独立浏览器。`:`Desktop browser ready: view web pages side-by-side in split view or switch to full browser.`:o(e?.native?`browserControlNativeLead`:`browserControlTip`)}),t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:l?`视图模式`:`View Mode`}),(0,$.jsxs)(`div`,{className:`bc-actions`,style:{marginTop:0,marginBottom:12},children:[(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`split`?`primary`:``,onClick:()=>void h(`split`),children:[(0,$.jsx)(Me,{size:14,style:{marginRight:6}}),l?`并列分栏 (Split)`:`Split View`]}),(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`browser`?`primary`:``,onClick:()=>void h(`browser`),children:[(0,$.jsx)(m,{size:14,style:{marginRight:6}}),l?`完整浏览器 (Browser)`:`Full Browser`]}),(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`agent`?`primary`:``,onClick:()=>void h(`agent`),children:[(0,$.jsx)(Fe,{size:14,style:{marginRight:6}}),l?`仅 Agent 模式`:`Agent Only`]})]}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0,marginBottom:12},children:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void g(),children:[(0,$.jsx)(C,{size:14,style:{marginRight:6}}),l?`新建网页标签`:`New Browser Tab`]})})]}),t&&n?.tabs&&n.tabs.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:l?`已打开的网页标签`:`Open Browser Tabs`}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:n.tabs.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`bc-title`,title:e.title||e.url,children:e.title||(l?`新标签页`:`New Tab`)}),(0,$.jsx)(`span`,{className:`bc-origin`,title:e.url,children:e.url}),e.id===n.activeTabId&&(0,$.jsx)(`span`,{className:`bc-open current`,children:o(`current`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,onClick:()=>{h(`split`)},children:l?`跳转`:`Open`})]},e.id))})]}),!t&&e===null&&(0,$.jsx)(`div`,{className:`bc-note`,children:o(`browserControlChecking`)}),!t&&e?.available===!1&&!e.desktop&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:o(`browserControlOffline`)}),!t&&e?.desktop===!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-note warn`,children:o(`browserControlDesktop`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:o(`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:o(`browserControlOpenInBrowser`)})})]}),!t&&e?.available===!1&&!e.desktop&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:o(`browserControlInstall`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:o(`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:o(`browserControlInstallDownload`)})}),(0,$.jsxs)(`ol`,{className:`bc-steps`,children:[(0,$.jsx)(`li`,{children:o(`browserControlInstallStep1`)}),(0,$.jsx)(`li`,{children:o(`browserControlInstallStep2`)}),(0,$.jsx)(`li`,{children:o(`browserControlInstallStep3`)}),(0,$.jsx)(`li`,{children:o(`browserControlInstallStep4`)})]})]}),e?.available===!0&&e.aiControl===!1&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:o(e.native?`browserControlNativeDisabled`:`browserControlDisabled`)}),e?.available===!0&&f.length===0&&!t&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:o(e.native?`browserControlNativeEmpty`:`browserControlEmpty`)}),f.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:o(`browserControlPages`)}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:f.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?o(`browserControlPageOpen`):o(`browserControlPageClosed`)}),e.active===!0&&(0,$.jsx)(`span`,{className:`bc-open current`,children:o(`current`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,title:o(`browserControlCiteTip`,{name:e.title||e.origin}),onClick:()=>i(e),children:o(`browserControlCite`)})]},e.tabId??e.origin))}),(0,$.jsx)(`div`,{className:`bc-note`,children:o(`browserControlCiteNote`)})]}),(0,$.jsxs)(`div`,{className:`bc-actions`,children:[!t&&e?.desktop!==!0&&(0,$.jsx)(`button`,{type:`button`,className:`primary`,disabled:u,onClick:()=>void p(),children:o(e?.native?`settings`:`browserControlOpenOptions`)}),(0,$.jsx)(`button`,{type:`button`,onClick:r,children:o(`browserControlRefresh`)})]})]})})}var Wr=`canvas`,Gr=`terminal`,Kr=[Gr],qr=[`terminal_create`,`terminal_list`,`terminal_close`,`terminal_input`,`terminal_key`,`terminal_read`,`terminal_wait`],Jr=`conversation`,Yr=`communicate`,Xr=[`subagent`,`subagent_spawn`,`subagent_get_result`,`subagent_steer`,`subagent_list`,`subagent_stop`,`subagent_wait_all`,`subagent_templates`,`subagent_handoff`],Zr=`delegate_task`,Qr=`ask_user_question`,$r=`browser_page`,ei=`browser_script`,ti=`phone`,ni=`skill`,ri=`schedule`,ii=[`schedule_task`,`schedule_list`,`schedule_cancel`],ai=`eval`,oi=`present_files`,si=`claim_files`,ci=`plan_update`,li=`compact_context`,ui=`patch`,di=`mcp_manage`,fi=`sandbox`,pi=`worktree`,mi=`device_collab`,hi=`codemode`,gi=`tool_search`,_i=`load_tools`,vi=[`bash`,`read`,`edit`,`write`],yi=[...Kr.map(e=>({name:e,group:`terminal`,defaultOn:!1,dshVisible:!0})),{name:Jr,group:`subagent`,defaultOn:!0,dshVisible:!1},{name:Yr,group:`subagent`,defaultOn:!0,dshVisible:!1,descKey:`communicateEnabledDesc`,offHintKey:`communicateOffHint`},{name:Zr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`delegateTaskEnabledDesc`,offHintKey:`delegateTaskOffHint`},{name:Qr,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`questionnaireEnabledDesc`,offHintKey:`questionnaireOffHint`},{name:$r,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`browserPageEnabledDesc`,offHintKey:`browserPageOffHint`},{name:ei,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`browserScriptEnabledDesc`,offHintKey:`browserScriptOffHint`},{name:ti,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`phoneEnabledDesc`,offHintKey:`phoneOffHint`},{name:si,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`claimFilesEnabledDesc`,offHintKey:`claimFilesOffHint`},{name:ci,group:`other`,defaultOn:!0,dshVisible:!0,descKey:`planUpdateEnabledDesc`,offHintKey:`planUpdateOffHint`},{name:ui,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`patchToolEnabledDesc`,offHintKey:`patchToolOffHint`},{name:`lsp`,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`lspToolEnabledDesc`,offHintKey:`lspToolOffHint`},{name:oi,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`presentFilesEnabledDesc`,offHintKey:`presentFilesOffHint`},{name:ni,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`skillEnabledDesc`,offHintKey:`skillOffHint`},{name:ai,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`evalEnabledDesc`,offHintKey:`evalOffHint`},{name:hi,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`codemodeEnabledDesc`,offHintKey:`codemodeOffHint`},{name:gi,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolSearchEnabledDesc`,offHintKey:`toolSearchOffHint`},{name:ri,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`scheduleTaskEnabledDesc`,offHintKey:`scheduleTaskOffHint`},{name:li,group:`other`,defaultOn:!0,dshVisible:!1,descKey:`compactContextEnabledDesc`,offHintKey:`compactContextOffHint`},{name:di,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`mcpManageEnabledDesc`,offHintKey:`mcpManageOffHint`},{name:fi,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`sandboxEnabledDesc`,offHintKey:`sandboxOffHint`},{name:pi,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`toolsWorktreeDesc`,offHintKey:`toolsWorktreeOffHint`},{name:Wr,group:`other`,defaultOn:!1,dshVisible:!1,descKey:`canvasToolEnabledDesc`,offHintKey:`canvasToolOffHint`}],bi=[{name:mi,group:`other`,defaultOn:!1,allowAgentToggle:!1,dshVisible:!1,descKey:`toolsDeviceCollabDesc`,offHintKey:`toolsDeviceCollabOffHint`}],xi=[{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:!1,allowAgentToggle:!1,descKey:`toolCoreLsDesc`},{name:`grep`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreGrepDesc`},{name:`find`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreFindDesc`}],Si=[...xi.map(e=>({name:e.name,group:`core`,defaultOn:e.defaultOn,platform:e.platform,allowAgentToggle:e.allowAgentToggle,dshVisible:!1,descKey:e.descKey})),...yi,...bi];new Map(Si.map(e=>[e.name,e]));var Ci=new Set(Si.map(e=>e.name)),wi=Si.map(e=>e.name);function Ti(e){let t=new Set(Ei(e));return wi.filter(e=>!t.has(e))}function Ei(e){if(!Array.isArray(e))return Di();let t=[];for(let n of e){let e=n;typeof e==`string`&&qr.includes(e)&&(e=Gr),typeof e==`string`&&Xr.includes(e)&&(e=Jr),e===`conversation_read`&&(e=Jr),typeof e==`string`&&ii.includes(e)&&(e=ri),typeof e==`string`&&Ci.has(e)&&!t.includes(e)&&t.push(e)}return t}function Di(){return Si.filter(e=>!e.defaultOn).map(e=>e.name)}function Oi(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`]);return n.filter(t=>e.has(t))}if(t===`reader`){let e=new Set([`write`,`edit`,`bash`,`powershell`,`terminal_create`,`terminal_input`,`terminal_close`,`terminal_key`,`codemode`]);return n.filter(t=>!e.has(t))}return n}function ki(e){return Oi([ni],e).includes(ni)}var Ai=new Set([`svg`,`g`,`path`,`circle`,`rect`,`line`,`polyline`,`polygon`,`ellipse`,`use`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`]),ji=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(`.`)),Mi=new Set([`script`,`style`,`title`,`desc`,`foreignobject`]),Ni=new Set([...Ai].map(e=>e.toLowerCase())),Pi=new Set([...ji].map(e=>e.toLowerCase()));function Fi(e){return Ni.has(e.toLowerCase())}function Ii(e){return Pi.has(e.toLowerCase())}function Li(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(!Fi(e)){Mi.has(e)?t.remove():(i(t),t.replaceWith(...t.childNodes));continue}for(let e of Array.from(t.attributes)){let n=e.name.toLowerCase();(!Ii(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();(!Ii(t)||/^on/i.test(t))&&r.removeAttribute(e.name)}return i(r),new XMLSerializer().serializeToString(r)}function Ri({icon:e,iconSvg:t,className:n}){let r=Li(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 zi={projects:`host:lp-projects`,groups:`host:lp-groups`,convs:`host:lp-running`,sessions:`host:lp-history`},Bi=[`projects`,`convs`,`sessions`],Vi=new Map(Object.keys(zi).map(e=>[zi[e],e])),Hi=`plugin:`;function Ui(e){return e.startsWith(Hi)&&e.length>7}function Wi(e){let t=[],n=new Set;for(let r of e??[]){let e=null,i,a=Vi.get(r.id);a?e=a:r.source?.startsWith(`plugin:`)&&r.kind===`view`&&(e=`${Hi}${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 Bi)n.has(e)||t.push({key:e,shown:!0});return t}function Gi(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 Ki(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 qi(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||Ui(e))&&typeof i==`number`&&Number.isFinite(i)&&i>0&&(n[e]=i)}catch{}return n}var Ji=[`superagent`];function Yi(e){return Ji.some(t=>t===e)}function Xi(e){return e.filter(e=>!Yi(e.id))}var Zi=new Set([`view`,`action`,`badge`,`menu`,`page`,`organizer`,`divider`,`toggle`,`input`,`progress`,`select`]),Qi=new Set([`disabled`,`always`,`never`,`file.isDir`,`file.isFile`,`session.isRunning`,`message.hasSelection`]),$i=`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(`,`),ea=$i.map(e=>({slot:e,cardinality:`list`}));function ta(e){return ea.find(t=>t.slot===e)?.cardinality??`list`}function na(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 ra=[{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-screenshot`,slot:`composer.actions`,labelKey:`screenshotCapture`,icon:`cut`,kind:`action`,order:20,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-external`,slot:`file.preview.toolbar`,labelKey:`openInNewTab`,icon:`open`,kind:`action`,order:25},{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:conv-quick-ask`,slot:`contextmenu.session`,labelKey:`quickAskReference`,icon:`chat`,kind:`action`,context:`session`,order:55},{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-quick-ask`,slot:`contextmenu.file`,labelKey:`quickAskReference`,icon:`chat`,kind:`action`,context:`file`,order:34,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}],ia=`__view`,aa=new Set([`host:settings`,`host:history`,`host:files`]),oa=new Set([`host:history`,`host:files`,`host:lp-running`,`host:lp-history`]);function sa(e){return`${e}:${ia}`}function ca(e){return e.source.startsWith(`plugin:`)?e.id===sa(e.source.slice(7)):!1}function la(e,t,n){let r=sa(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 ua(e,t){let n=t.map(sa),r=new Set(n),i=(e?.order??[]).filter(e=>!r.has(e));return{...e,order:[...i,...n]}}var da=`host:brand`,fa=[`host:brand-logo`,`host:brand-name`];function pa(e){if(!((e.hidden??[]).some(e=>fa.includes(e))||(e.shown??[]).some(e=>fa.includes(e))||(e.order??[]).some(e=>fa.includes(e))||fa.some(t=>e.align?.[t]!==void 0)||fa.some(t=>e.groups?.[t]!==void 0)||fa.some(t=>e.labels?.[t]!==void 0)||fa.some(t=>e.slots?.[t]!==void 0)))return e;let t=e=>{if(!e)return;let t=[];for(let n of e){let e=fa.includes(n)?da: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))fa.includes(t)||(n[t]=r);if(n[da]===void 0){let r=t?e[fa[0]]??e[fa[1]]:e[fa[1]]??e[fa[0]];r!==void 0&&(n[da]=r)}return n},r=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))fa.includes(n)||(t[n]=r);if(t[da]===void 0){let n=e[fa[0]]??e[fa[1]];n!==void 0&&(t[da]=n)}return t},i=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))fa.includes(n)||(t[n]=r);if(t[da]===void 0){let n=e[fa[0]]??e[fa[1]];n!==void 0&&(t[da]=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 ma(e){return Xi(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:ia,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 ha(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 ga(e){return typeof e==`string`&&$i.includes(e)}function _a(e,t){return t?e.label:e.labelEn??e.label}function va(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function ya(e,t,n,r,i){let a=`${e}#${r.id}`,o=ba(a,t,n,r.children,i),s=va(r,i),c=xa(r.options,i),l=Sa(r.progress);return{id:a,slot:t,source:n,label:_a(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 ba(e,t,n,r,i){return r?.length?r.map((r,a)=>({entry:ya(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 xa(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 Sa(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function Ca(e,t,n,r,i,a){let o=ba(e,t,n,r.children,i),s=va(r,i),c=Sa(r.progress),l=xa(r.options,i);return{id:e,slot:t,source:n,label:_a(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 wa(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 Ta(e,t){let n=e.filter(e=>ca(e)&&!t.has(e.id));if(n.length===0)return e;let r=e.filter(e=>!ca(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 Ea(e,t){let n=X(t.locale),r=new Set(t.disabledPlugins??[]),i=pa(t.layout??{}),a=e=>{t.diagnostics?.push({level:e.level??`warn`,...e})},o=new Map,s=0;for(let e of ra)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(!ga(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&&!Zi.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)Qi.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,Ca(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);Oa(o,e,t.id),n||a({pluginId:t.id,entryId:e.id,message:`arrange target "${e.id}" does not exist — op ignored (is the providing plugin installed / not disabled?)`})}let c=new Map,l=(e,t)=>{let n=c.get(e)??[];n.includes(t)||n.push(t),c.set(e,n)};for(let e of i.hidden??[]){let t=o.get(e);t&&(t.hidden=!0,l(e,`hidden`))}for(let e of i.shown??[]){let t=o.get(e);t&&(t.hidden=!1,l(e,`hidden`))}for(let[e,t]of Object.entries(i.groups??{})){let n=o.get(e);n&&(n.group=t,l(e,`group`))}for(let[e,t]of Object.entries(i.align??{})){let n=o.get(e);!n||t!==`start`&&t!==`center`&&t!==`end`||(n.align=t,l(e,`align`))}for(let[e,t]of Object.entries(i.labels??{})){let n=o.get(e);n&&(n.label=t,n.labelExplicit=!0,l(e,`label`))}for(let[e,t]of Object.entries(i.slots??{})){let n=o.get(e);n&&ga(t)&&n.slot!==t&&(n.movedFrom=n.movedFrom??n.slot,n.slot=t,l(e,`slot`))}for(let e of aa){let t=o.get(e);t&&(i.slots?.[e]||(t.slot=`topbar.primary`),t.hidden=!1)}let u=new Map;(i.order??[]).forEach((e,t)=>{o.has(e)&&(u.has(e)||u.set(e,t),l(e,`order`))});for(let e of Object.values(zi)){let t=o.get(e);t&&t.slot!==`leftpanel.sections`&&(a({entryId:e,slot:t.slot,message:`"${e}" must stay in leftpanel.sections — the move is ignored`}),t.slot=`leftpanel.sections`,delete t.movedFrom)}let d=new Map;for(let e of $i)d.set(e,[]);for(let e of o.values())d.get(e.slot)?.push(e);let f={};for(let e of $i){let t=wa(d.get(e)??[],u),n=na(e===`topbar.primary`?Ta(t,u):t,ta(e));if(n.winner&&n.conflicts.length>0)for(let t of n.conflicts)a({level:`error`,pluginId:t.source.startsWith(`plugin:`)?t.source.slice(7):void 0,entryId:t.id,slot:e,message:`slot "${e}" is single-cardinality; "${n.winner.id}" won and "${t.id}" was hidden`});f[e]=n.entries.map(e=>Da(e,c.get(e.id)??[]))}return f}function Da(e,t){let n={...e,userOverrides:t};return delete n.seq,n}function Oa(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&&ga(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 ka(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 Aa(e,t){let n=e??{},r={},i=t===da?[t,...fa]:[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=Ma(n.groups,t),l=Ma(n.labels,t),u=Ma(n.align,t),d=Ma(n.slots,t);if(t===da)for(let e of fa)c=Ma(c,e),l=Ma(l,e),u=Ma(u,e),d=Ma(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 ja(){return{}}function Ma(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 Na=new Set([`host:files`]);function Pa(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 Fa(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 Ia=null,La=new Set;function Ra(){for(let e of La)e()}function za(e){Ia={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}:{}},Ra()}function Ba(){Ia!==null&&(Ia=null,Ra())}function Va(e){return La.add(e),()=>{La.delete(e)}}function Ha(){return Ia}function Ua(){return(0,Q.useSyncExternalStore)(Va,Ha,Ha)}function Wa(e){return Number.isFinite(e)?e:0}function Ga(e,t,n,r,i,a){let o=Math.max(0,Wa(n)),s=Math.max(0,Wa(r)),c=Math.max(8,Wa(i)-o-8),l=Math.max(8,Wa(a)-s-8);return{x:Math.min(Math.max(8,Wa(e)),c),y:Math.min(Math.max(8,Wa(t)),l)}}function Ka(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 qa(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 Ja(e,t){return!e||qa(e.when,t)}function Ya(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 Xa(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 Za(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 Qa(e,t){return!e||e.kind===`divider`||e.hidden===!0?!1:!Ja(e,t)}function $a(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,Qa(e[o],r))return o;return-1}var eo={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 to(e){let t=(e??``).trim();return t?eo[t.toLowerCase()]||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:``):``}var no=`@root`,ro=e=>e.endsWith(`/`)?e:e+`/`;function io(e,t){let n=t.trim(),r=e.replace(/\\/g,`/`);return r.endsWith(`/`)?r+n:(/^[A-Za-z]:$/.test(r),r+`/`+n)}function ao(e){let t=e.trim();return!(!t||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`))}var oo=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)?no:null;if(n===0)return`/`;let r=t.slice(0,n);return/^[A-Za-z]:$/.test(r)?r+`/`:r},so=`pi-web-ui:project-picker-tab`;function co(){try{let e=localStorage.getItem(so);return e===`local`||e===`remote`?e:null}catch{return null}}function lo({currentCwd:e,pathCompletions:t,workspaceRoots:r,onClose:i,onSelectDirectory:a,mode:o=`folder`,onCreateProject:s,className:c,backdropClassName:l,role:d,ariaLabel:f,localOnly:p=!1,initialTab:m,portalContainer:h}){let g=W(),_=X(Et()),v=at().remoteSsh&&!p,y=He(`homeDir`),b=He(`desktopDir`),[x,S]=(0,Q.useState)(()=>v?m===`local`||m===`remote`?m:co()||(Vn(e)?`remote`:`local`):`local`),C=e=>{S(e);try{localStorage.setItem(so,e)}catch{}};(0,Q.useEffect)(()=>{!v&&x===`remote`&&C(`local`)},[v,x]);let[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(-1),I=(0,Q.useRef)(null),L=(0,Q.useRef)(null),[R,z]=(0,Q.useState)([]),[B,ee]=(0,Q.useState)(``),[V,te]=(0,Q.useState)(`22`),[ne,ie]=(0,Q.useState)(``),[H,ae]=(0,Q.useState)(`password`),[U,oe]=(0,Q.useState)(``),[se,ce]=(0,Q.useState)(`~/.ssh/id_rsa`),[le,G]=(0,Q.useState)(!0),[K,ue]=(0,Q.useState)(``),[de,fe]=(0,Q.useState)(!1),[pe,q]=(0,Q.useState)(null),[me,he]=(0,Q.useState)(!1),[ge,_e]=(0,Q.useState)(!1),[J,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(null),[Se,Ce]=(0,Q.useState)(null),[Y,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)([]),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(`/`),[Me,Ne]=(0,Q.useState)(`/`),[Pe,Fe]=(0,Q.useState)([]),[Le,Re]=(0,Q.useState)(!1),[ze,Ve]=(0,Q.useState)(!1),[Ue,We]=(0,Q.useState)(``),[Ge,Ke]=(0,Q.useState)(null),qe=t.filter(e=>e.type===`dir`);(0,Q.useEffect)(()=>{if(Vn(e)){let t=zn(e);t&&(ee(t.host),te(String(t.port)),ie(t.username),je(t.remotePath),Ne(t.remotePath))}else{let t=(e||``).replace(/\\/g,`/`);T(t),D(t)}k(!1),j(``),N(null),F(-1)},[e]),(0,Q.useEffect)(()=>{let e=requestAnimationFrame(()=>{I.current?.focus()});return()=>cancelAnimationFrame(e)},[x]),Vt(()=>{O||ze?(k(!1),j(``),N(null),Ve(!1),We(``),Ke(null)):i()}),(0,Q.useEffect)(()=>{if(x!==`local`)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:ro(w)})},60);return()=>clearTimeout(e)},[w,x]),(0,Q.useEffect)(()=>{if(x!==`local`||E===w)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:E})},150);return()=>clearTimeout(e)},[E,w,x]);let Je=e=>{let t=e.trim();t&&t!==`@root`&&a(t)},Ye=e=>{T(e),D(e),F(-1),N(null)},Xe=()=>{let e=A.trim();if(e&&w!==`@root`){if(o===`project`){if(!ao(e)){N(g(`invalidProjectName`));return}let t=io(w,e);s?s(t):(Z({type:`make_dir`,path:t}),a(t)),k(!1),j(``),N(null),i()}else Z({type:`make_dir`,path:`${ro(w)}${e}`}),setTimeout(()=>{Z({type:`complete_path`,path:ro(w)})},80),j(``),k(!1)}},Ze=e=>{if(e.key===`Escape`)e.stopPropagation(),O?(k(!1),j(``),N(null)):i();else if(e.key===`Enter`&&!e.nativeEvent.isComposing)Je(E);else if(e.key===`Tab`){if(qe.length===0)return;e.preventDefault();let t=P>=0?(P+1)%qe.length:0;F(t),D(qe[t].path),T(qe[t].path)}},Qe=async t=>{let n=(t?.host??B).trim(),r=t?.port??(parseInt(V,10)||22),i=(t?.username??ne).trim();if(!n||!i){q(_?`请填写主机地址和用户名`:`Please provide host address and username`);return}fe(!0),q(null);let a=t?.auth??(H===`password`?{type:`password`,password:U}:H===`key`?{type:`key`,privateKeyPath:se}:{type:`agent`}),o=await Bn({host:n,port:r,username:i,auth:a,saveProfile:le,profileName:t?.profileName||K.trim()||void 0});if(fe(!1),!o.ok||!o.connectionId){ye(o.hostTrust??null),he(!1),q(o.error||(_?`连接远程服务器失败`:`Failed to connect to remote server`));return}xe(o.connectionId),Ce(o.system??null),Te(o.tools??null),De(o.suggestedInstall??[]);let s=Vn(e)?zn(e)?.remotePath:null,c=s&&s!==`/`?s:o.system?.homeDir||`/`;je(c),Ne(c),et(o.connectionId,c),Hn().then(e=>z(e))},$e=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{x===`remote`&&Hn().then(t=>{if(z(t),!$e.current&&!be&&!de&&Vn(e)){let n=zn(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&&($e.current=!0,ee(e.host),te(String(e.port)),ie(e.username),ae(e.authType),e.privateKeyPath&&ce(e.privateKeyPath),Qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}}))}}})},[x,e,be,de]);let et=async(e,t)=>{Re(!0),q(null);let n=await Kn(e,t);Re(!1),n.ok?(je(n.path),Ne(n.path),Fe(n.items)):q(n.error||(_?`读取远程目录失败`:`Failed to read remote directory`))},nt=async e=>{if(!be)return;ke(!0),q(null);let t=await Wn(be,[e]);ke(!1),t.ok?(De(t=>t.filter(t=>t!==e)),Y&&e===`git`&&Te({...Y,git:{installed:!0,version:_?`已安装`:`Installed`}})):q(t.error||(_?`安装 ${e} 失败,可能需要远端 sudo 权限`:`Failed to install ${e}, remote sudo permissions may be required`))},rt=e=>{let t=parseInt(V,10)||22,n=Se?.homeDir||`/`,r=(e||``).trim()||Ae||`/`;r===`~`?r=n:(r.startsWith(`~/`)||r.startsWith(`~\\`))&&(r=`${n.replace(/\/+$/,``)}/${r.slice(2).replace(/\\/g,`/`)}`),a(Gn(ne,B,t,r)),i()},it=()=>{let e=Ue.trim();if(!e||!be)return;if(!ao(e)){Ke(g(`invalidProjectName`));return}let t=parseInt(V,10)||22,n=Ae.replace(/\/+$/,``)||`/`,r=n===`/`?`/${e}`:`${n}/${e}`,c=Gn(ne,B,t,r);if(o===`project`)s?s(c):(Z({type:`make_dir`,path:c}),a(c)),Ve(!1),We(``),Ke(null),i();else{Z({type:`make_dir`,path:c}),We(``),Ve(!1),Ke(null);let e=be,t=Ae;setTimeout(()=>{et(e,t)},300)}},ot=oo(w),ct=oo(Ae),lt=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);return/^[A-Za-z]:/.test(t)?t.toLowerCase():t},ut=lt(w),dt=!!w&&w!==`@root`&&ut!==lt(e)&&!r.some(e=>lt(e)===ut);return(0,cr.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`status-cwd-backdrop ${l??``}`.trim(),onClick:i,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation()}),(0,$.jsxs)(`div`,{className:`cwd-picker ${c??``}`.trim(),role:d,"aria-label":f,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 ${x===`local`?`active`:``}`,onClick:()=>C(`local`),children:[`💻 `,g(`workspaceModeLocal`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${x===`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)(Be,{})})]}):(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)(Be,{})})]}),x===`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)(Ie,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{children:w===`@root`?g(`computer`):w})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":g(`projectPickerTitle`),children:[(0,$.jsx)(In,{className:`cwd-jump ${w===`@root`?`active`:``}`,tip:g(`computer`),onClick:()=>Ye(`@root`),children:(0,$.jsx)(Ie,{})}),y!==``&&(0,$.jsx)(In,{className:`cwd-jump ${lt(w)===lt(y)?`active`:``}`,tip:`${g(`homeDir`)} ${y}`,onClick:()=>Ye(y),children:(0,$.jsx)(tt,{})}),b!==``&&(0,$.jsx)(In,{className:`cwd-jump ${lt(w)===lt(b)?`active`:``}`,tip:`${g(`desktopDir`)} ${b}`,onClick:()=>Ye(b),children:(0,$.jsx)(re,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-sep`,"aria-hidden":`true`}),(0,$.jsx)(In,{className:`cwd-jump tool-up`,tip:ot?`${g(`cwdGoUp`)} · ${ot}`:`${g(`cwdGoUp`)} · ${_?`已在顶层`:`already at top`}`,"aria-disabled":!ot,onClick:()=>{ot&&Ye(ot)},children:(0,$.jsx)(Ot,{})}),(0,$.jsx)(In,{className:`cwd-jump tool-root`,tip:dt?g(`addWorkspaceRootHint`):w===`@root`?`${g(`addWorkspaceRoot`)} · ${_?`此电脑本身不是目录`:`This PC is not a directory`}`:ut===lt(e)?`${g(`addWorkspaceRoot`)} · ${_?`已是当前项目目录`:`Already the current project`}`:`${g(`addWorkspaceRoot`)} · ${_?`已在工作区根中`:`Already a workspace root`}`,"aria-disabled":!dt,onClick:()=>{dt&&Z({type:`set_workspace_roots`,roots:[...r,w]})},children:(0,$.jsx)(u,{})}),(0,$.jsx)(In,{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?(k(!1),j(``),N(null)):(j(``),N(null),k(!0)))},children:(0,$.jsx)(vt,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`}),(0,$.jsx)(In,{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:()=>Je(w),children:(0,$.jsx)(n,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{ref:I,className:`status-cwd-input cwd-picker-input`,value:E,placeholder:g(`enterPath`),spellCheck:!1,onChange:e=>{D(e.target.value),F(-1)},onKeyDown:Ze}),E.trim()!==``&&E!==w&&(0,$.jsx)(In,{className:`cwd-jump tool-enter`,tip:`${g(`cwdEnter`)} · ${E.trim()}`,onClick:()=>{T(E.trim()),F(-1)},children:(0,$.jsx)(we,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[ot&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${g(`cwdGoUp`)} · ${ot}`,onClick:()=>Ye(ot),children:[(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),qe.length===0&&!ot&&(0,$.jsx)(`div`,{className:`cwd-empty`,children:g(`cwdEmpty`)}),qe.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),F(-1)},children:[(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),(0,$.jsx)(In,{className:`cwd-jump tool-choose`,tip:`${g(`cwdChoose`)} · ${e.path}`,onClick:()=>Je(e.path),children:(0,$.jsx)(n,{})})]},e.path))]}),O&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{ref:L,value:A,autoFocus:!0,spellCheck:!1,placeholder:g(`cwdNewName`),onChange:e=>{j(e.target.value),M&&N(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),Xe()):e.key===`Escape`&&(e.stopPropagation(),k(!1),j(``),N(null))}}),(0,$.jsx)(In,{className:`cwd-jump primary`,tip:g(`cwdCreate`),onClick:Xe,children:(0,$.jsx)(n,{})}),(0,$.jsx)(In,{className:`cwd-jump`,tip:g(`cwdCancel`),onClick:()=>{k(!1),j(``),N(null)},children:(0,$.jsx)(Be,{})})]}),M&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:M})]})]}),x===`remote`&&(0,$.jsx)(`div`,{className:`cwd-ssh-container`,children:be?(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:[`🌐 `,ne,`@`,B,` (`,Se?.os,` `,Se?.arch,`)`]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,onClick:()=>{xe(null),Ce(null),Te(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 ${Y?.git.installed?`ok`:`missing`}`,children:[`Git: `,Y?.git.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.node.installed?`ok`:`missing`}`,children:[`Node: `,Y?.node.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${Y?.bash.installed?`ok`:`missing`}`,children:[`Bash: `,Y?.bash.installed?`✓`:`✗`]})]}),Ee.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:Oe,onClick:()=>void nt(Ee[0]),children:Oe?g(`sshInstalling`):`⚡ ${g(`sshInstallTool`)} ${Ee[0]}`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>De([]),children:g(`sshSkipAndBrowse`)})]})]})]}),(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:Ae,children:[(0,$.jsx)(Ct,{}),(0,$.jsx)(`span`,{children:Ae})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":g(`workspaceModeRemote`),children:[(0,$.jsx)(In,{className:`cwd-jump tool-up`,tip:Ae===`/`?`${g(`cwdGoUp`)} · ${_?`已在顶层`:`already at top`}`:`${g(`cwdGoUp`)} · ${oo(Ae)||`/`}`,"aria-disabled":Ae===`/`||Le,onClick:()=>{if(Le)return;let e=oo(Ae);e&&be&&et(be,e)},children:(0,$.jsx)(Ot,{})}),(0,$.jsx)(In,{className:`cwd-jump tool-new ${ze?`active`:``}`,tip:g(ze?`cwdCancel`:`cwdNewFolder`),onClick:()=>Ve(e=>!e),children:(0,$.jsx)(vt,{})}),(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:Me,placeholder:g(`enterPath`),spellCheck:!1,onChange:e=>Ne(e.target.value),onKeyDown:e=>{e.key===`Enter`&&be&&et(be,Me)}}),Me.trim()&&Me.trim()!==Ae&&be&&(0,$.jsx)(In,{className:`cwd-jump tool-enter`,tip:`${g(`cwdEnter`)} · ${Me.trim()}`,onClick:()=>void et(be,Me),children:(0,$.jsx)(we,{})}),(0,$.jsx)(In,{className:`cwd-jump primary tool-pick`,tip:`${g(`sshOpenRemoteWorkspace`)} · ${Me.trim()||Ae}`,onClick:()=>rt(Me.trim()||Ae),children:(0,$.jsx)(n,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[!Le&&ct&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${g(`cwdGoUp`)} · ${ct}`,onClick:()=>{be&&et(be,ct)},children:[(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),Le?(0,$.jsx)(`div`,{className:`cwd-empty`,children:_?`正在加载远程目录…`:`Loading remote directory…`}):Pe.length===0?(0,$.jsx)(`div`,{className:`cwd-empty`,children:g(`cwdEmpty`)}):Pe.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`&&be&&et(be,e.path)},children:[e.type===`dir`?(0,$.jsx)(st,{}):(0,$.jsx)(`span`,{children:`📄`}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),e.type===`dir`&&(0,$.jsx)(In,{className:`cwd-jump tool-choose`,tip:`${g(`cwdChoose`)} · ${e.path}`,onClick:()=>rt(e.path),children:(0,$.jsx)(n,{})})]},e.path))]}),be&&ze&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{value:Ue,autoFocus:!0,spellCheck:!1,placeholder:g(`cwdNewName`),onChange:e=>{We(e.target.value),Ge&&Ke(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),it()):e.key===`Escape`&&(e.stopPropagation(),Ve(!1),We(``),Ke(null))}}),(0,$.jsx)(In,{className:`cwd-jump primary`,tip:g(`cwdCreate`),onClick:it,children:(0,$.jsx)(n,{})}),(0,$.jsx)(In,{className:`cwd-jump`,tip:g(`cwdCancel`),onClick:()=>{Ve(!1),We(``),Ke(null)},children:(0,$.jsx)(Be,{})})]}),Ge&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:Ge})]})]}):(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:()=>{ee(e.host),te(String(e.port)),ie(e.username),ae(e.authType),e.privateKeyPath&&ce(e.privateKeyPath),Qe({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}})},children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-meta`,children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-name`,children:[(0,$.jsx)(ve,{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`))&&(qn(e.name),z(t=>t.filter(t=>t.name!==e.name)))},children:(0,$.jsx)(_t,{})})]},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:B,placeholder:`192.168.1.100`,onChange:e=>ee(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:V,onChange:e=>te(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:ne,placeholder:`root / ubuntu`,onChange:e=>ie(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:H,onChange:e=>ae(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`)})]})]}),H===`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:U,placeholder:`••••••••`,onChange:e=>oe(e.target.value)})]}),H===`key`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`sshKeyPath`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:se,placeholder:`~/.ssh/id_rsa`,onChange:e=>ce(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:le,onChange:e=>G(e.target.checked),style:{marginRight:`4px`}}),g(`sshSaveProfile`)]})}),le&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[g(`sshProfileName`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:K,placeholder:`my-server`,onChange:e=>ue(e.target.value)})]}),J&&(0,$.jsxs)(`div`,{style:{border:`1px solid #d97706`,borderRadius:`8px`,padding:`8px`,marginTop:`6px`},children:[(0,$.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,marginBottom:`4px`},children:J.status===`changed`?_?`主机密钥已变更`:`Host key changed`:_?`新主机密钥待确认`:`New host key`}),(0,$.jsxs)(`div`,{style:{fontSize:`11px`,wordBreak:`break-all`,marginBottom:`4px`},children:[J.host,`:`,J.port,` `,J.algorithm,` `,J.fingerprint]}),(0,$.jsx)(`div`,{style:{fontSize:`11px`,color:`var(--text-dim)`,marginBottom:`6px`},children:_?`请先去服务器控制台核对指纹,确认一致再勾选。`:`Verify fingerprint on server console first.`}),(0,$.jsxs)(`label`,{style:{fontSize:`11px`,display:`flex`,gap:`6px`,marginBottom:`6px`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:me,onChange:e=>he(e.target.checked)}),(0,$.jsx)(`span`,{children:_?`我已核对过,该指纹正确`:`I verified this fingerprint`})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`8px`},children:[(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,disabled:!me||ge,onClick:async()=>{_e(!0);let e=await Jn({host:J.host,port:J.port,fingerprint:J.fingerprint,replace:J.status===`changed`});if(_e(!1),!e.ok){q(e.error||`fail`);return}ye(null),Qe()},children:_?`信任并重试`:`Trust & retry`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>{ye(null),he(!1)},children:_?`取消`:`Cancel`})]})]}),pe&&(0,$.jsxs)(`div`,{style:{color:`var(--red)`,fontSize:`11px`,padding:`2px 0`},children:[`⚠️ `,pe]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,style:{marginTop:`4px`},disabled:de,onClick:()=>void Qe(),children:g(de?`sshConnecting`:`sshConnectAndProbe`)})]})})]})]}),h??document.body)}function uo({open:e,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,onCreateProject:o,mode:s=`project`,localOnly:c,initialTab:l,portalContainer:u}){let d=W();return e?(0,$.jsx)(lo,{portalContainer:u,localOnly:c,initialTab:l,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:d(`projectPickerTitle`)}):null}function fo(e){return Mt({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 po(e){return Mt({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 mo({anchorRect:e,anchorEl:t,plugins:n,pinnedIds:r,orderedPluginIds:i,onTogglePin:a,onReorder:o,onOpenView:s,onOpenPluginSettings:l,onManagePlugins:u,onClose:d}){let{t:p}=c(),{panelRef:m,style:h,measure:g}=dr({anchor:e,anchorEl:t,onClose:d}),[,_]=(0,Q.useState)(null),v=(0,Q.useRef)(null),[y,b]=(0,Q.useState)(null),x=(0,Q.useMemo)(()=>{let e=new Map((i??[]).map((e,t)=>[e,t]));return Xi(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:S,extPlugins:C}=(0,Q.useMemo)(()=>{let e=[],t=[];for(let n of x)n.view!==!1&&!n.error?e.push(n):t.push(n);return{viewPlugins:e,extPlugins:t}},[x]);(0,Q.useLayoutEffect)(()=>{g()},[x,g]);let w=(e,t)=>{let n=x.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))},T=(e,t)=>{if(!e||e===t)return;let n=x.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))},E=(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${y===e.id?` drop-target`:``}${t?` pm-row-ext`:``}`,role:`none`,onDragOver:t=>{!n&&v.current&&(t.preventDefault(),b(e.id))},onDrop:t=>{t.preventDefault(),T(t.dataTransfer.getData(`text/plain`)||v.current,e.id),v.current=null,_(null),b(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":p(`pluginMenuReorder`),title:p(`pluginMenuReorderHint`),onDragStart:t=>{_(e.id),v.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:()=>{v.current=null,_(null),b(null)},onKeyDown:t=>{(t.key===`ArrowUp`||t.key===`ArrowDown`)&&(t.preventDefault(),w(e.id,t.key===`ArrowUp`?-1:1))},children:(0,$.jsx)(f,{"aria-hidden":!0})}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-row-main`,disabled:n,title:e.error??(n?p(`pluginMenuNoView`):e.name),onClick:()=>s(e.id),children:[o||e.iconSvg?(0,$.jsx)(Ri,{icon:o,iconSvg:e.iconSvg,className:`pm-icon`}):(0,$.jsx)(B,{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:p(`pluginPhaseFailed`)}):t?(0,$.jsx)(`span`,{className:`pm-ext-tag`,title:p(`pluginMenuNoView`),children:p(`pluginBadgeBg`)}):null]}),(0,$.jsxs)(`div`,{className:`pm-row-actions`,children:[e.hasSettings&&l&&(0,$.jsx)(`button`,{type:`button`,className:`pm-action-btn`,title:p(`pluginQuickSettings`),onClick:()=>{d(),l(e.id)},children:(0,$.jsx)(yt,{"aria-hidden":!0})}),!n&&(0,$.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":i,"aria-label":p(i?`pluginMenuUnpin`:`pluginMenuPin`),title:p(i?`pluginMenuUnpin`:`pluginMenuPin`),className:`pm-pin${i?` on`:``}`,onClick:()=>a(e.id,!i),children:i?(0,$.jsx)(po,{"aria-hidden":!0}):(0,$.jsx)(fo,{"aria-hidden":!0})})]})]},e.id)};return(0,cr.createPortal)((0,$.jsxs)(`div`,{ref:m,className:`pm-panel`,role:`menu`,"aria-label":p(`pluginMenuTitle`),style:h,children:[(0,$.jsxs)(`div`,{className:`pm-head`,"aria-hidden":`true`,children:[(0,$.jsxs)(`div`,{className:`pm-head-left`,children:[(0,$.jsx)(B,{className:`pm-head-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-head-title`,children:p(`pluginMenuTitle`)}),(0,$.jsx)(`span`,{className:`pm-head-count`,children:x.length})]}),l&&(0,$.jsxs)(`button`,{type:`button`,className:`pm-head-btn`,title:p(`pluginManagerDesc`),onClick:()=>{d(),l()},children:[(0,$.jsx)(yt,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:p(`pluginMenuSettings`)})]})]}),(0,$.jsx)(`div`,{className:`pm-list`,children:x.length===0?(0,$.jsx)(`div`,{className:`pm-empty`,children:p(`pluginMenuEmpty`)}):(0,$.jsxs)($.Fragment,{children:[S.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[C.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:p(`pluginGroupViews`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:S.length})]}),S.map(e=>E(e,!1))]}),C.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[S.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:p(`pluginGroupExtensions`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:C.length})]}),C.map(e=>E(e,!0))]})]})}),(0,$.jsxs)(`div`,{className:`pm-footer`,children:[l&&(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn primary`,onClick:()=>{d(),l()},children:[(0,$.jsx)(yt,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:p(`pluginMenuSettings`)})]}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn pm-manage`,onClick:()=>{d(),u()},children:[(0,$.jsx)(oe,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:p(`pluginMenuManage`)})]})]})]}),document.body)}var ho=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],go={off:0,minimal:1024,low:2048,medium:8192,high:16384,xhigh:32e3,max:64e3},_o=[{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 对象)`}],vo=[{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 yo(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 go){let n=go[e];if(n&&n>0)return`${t} (${n>=1024?`${Math.round(n/1024)}K`:`${n}`} tokens)`}return t}function bo(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 ho)i(e);let a=typeof n==`string`?n:n==null?``:String(n);return a&&i(a),r}var xo={activity:(0,$.jsx)(Ae,{}),aperture:(0,$.jsx)(ze,{}),branch:(0,$.jsx)(ke,{}),browser:(0,$.jsx)(Ct,{}),chat:(0,$.jsx)(Ye,{}),check:(0,$.jsx)(n,{}),"chevron-up":(0,$.jsx)(w,{}),clock:(0,$.jsx)(Pt,{}),code:(0,$.jsx)(a,{}),coins:(0,$.jsx)(_e,{}),copy:(0,$.jsx)(x,{}),cpu:(0,$.jsx)(k,{}),cut:(0,$.jsx)(j,{}),database:(0,$.jsx)(D,{}),dot:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`●`}),download:(0,$.jsx)(he,{}),edit:(0,$.jsx)(J,{}),engine:(0,$.jsx)(ze,{}),eye:(0,$.jsx)(Ne,{}),feather:(0,$.jsx)(it,{}),file:(0,$.jsx)(ht,{}),folder:(0,$.jsx)(st,{}),folders:(0,$.jsx)(Er,{}),gauge:(0,$.jsx)(Ae,{}),git:(0,$.jsx)(ke,{}),github:(0,$.jsx)(Qe,{}),globe:(0,$.jsx)(Ct,{}),grid:(0,$.jsx)(je,{}),hash:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`#`}),image:(0,$.jsx)(Ve,{}),info:(0,$.jsx)(xe,{}),layers:(0,$.jsx)(Nt,{}),link:(0,$.jsx)(At,{}),list:(0,$.jsx)(ce,{}),lock:(0,$.jsx)(l,{}),markdown:(0,$.jsx)(Y,{}),maximize:(0,$.jsx)(m,{}),menu:(0,$.jsx)(f,{}),minimize:(0,$.jsx)(I,{}),message:(0,$.jsx)(Ye,{}),open:(0,$.jsx)(t,{}),paste:(0,$.jsx)(ae,{}),pin:(0,$.jsx)($e,{}),plus:(0,$.jsx)(C,{}),refresh:(0,$.jsx)(ue,{}),sandbox:(0,$.jsx)(Or,{}),save:(0,$.jsx)(b,{}),share:(0,$.jsx)(xr,{}),search:(0,$.jsx)(ft,{}),send:(0,$.jsx)(O,{}),settings:(0,$.jsx)(ge,{}),sound:(0,$.jsx)(et,{}),sun:(0,$.jsx)(mt,{}),target:(0,$.jsx)(dt,{}),terminal:(0,$.jsx)(Ce,{}),text:(0,$.jsx)(Oe,{}),trash:(0,$.jsx)(_t,{}),undo:(0,$.jsx)(v,{}),upload:(0,$.jsx)(St,{}),users:(0,$.jsx)(lt,{}),volume:(0,$.jsx)(et,{}),wrap:(0,$.jsx)(G,{}),x:(0,$.jsx)(Be,{}),zap:(0,$.jsx)(Re,{}),zoom:(0,$.jsx)(be,{})};Object.keys(xo);function So(e){if(e.iconSvg)return(0,$.jsx)(Ri,{icon:e.icon,iconSvg:e.iconSvg});if(!e.icon)return null;let t=xo[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 Co=0,wo=``;function To(){typeof document<`u`&&(Co===0&&(wo=document.body.style.overflow,document.body.style.overflow=`hidden`),Co++)}function Eo(){typeof document<`u`&&(Co=Math.max(0,Co-1),Co===0&&(document.body.style.overflow=wo))}function Do({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(Vt(()=>a&&S?(y||x(!1),s?.(!1),!0):p?(v.current(),!0):!1,e),(0,Q.useEffect)(()=>{if(e&&g)return To(),()=>{Eo()}},[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,cr.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)(Ke,{}):(0,$.jsx)(le,{})}),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 Oo({plugin:e,models:t=[]}){let n=W(),r=Et(),i=X(r),a=e.settingsSchema??[],[o,s]=(0,Q.useState)(()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);return t}),[c,l]=(0,Q.useState)(!1);if(a.length===0)return null;let u=(e,t)=>s(n=>({...n,[e]:t})),d=e=>bo(e,t,o[e.key]).map(r=>{if(r===``)return{value:``,label:n(`pluginSettingsInherit`)};if(e.optionsFrom===`thinkingLevels`&&ho.includes(r))return{value:r,label:n(`thinking.${r}`)};if(e.optionsFrom===`models`){let e=t.find(e=>`${e.provider}/${e.id}`===r);if(e)return{value:r,label:e.label}}let a=e.options?.find(e=>(typeof e==`string`?e:e.value)===r);return a&&typeof a==`object`?{value:r,label:i?a.label??a.labelEn??a.value:a.labelEn??a.label??a.value}:{value:r,label:r}}),f=a.some(t=>t.type===`secret`?String(o[t.key]??``)!==``:o[t.key]!==e.settingsValues?.[t.key]);return(0,$.jsxs)(`div`,{className:`plugin-settings-form`,children:[(0,$.jsx)(`div`,{className:`plugin-settings-fields`,children:a.map(t=>(0,$.jsxs)(`label`,{className:`plugin-settings-field`,"data-key":t.key,title:t.hint,children:[(0,$.jsxs)(`span`,{className:`plugin-settings-label`,children:[(0,$.jsx)(`span`,{className:`plugin-settings-label-text`,title:t.label,children:t.label}),t.hint&&(0,$.jsx)(`span`,{className:`plugin-settings-hint`,children:t.hint})]}),(0,$.jsx)(`span`,{className:`plugin-settings-control`,children:t.type===`boolean`?(0,$.jsx)(`input`,{type:`checkbox`,checked:!!o[t.key],onChange:e=>u(t.key,e.target.checked)}):t.type===`secret`?(0,$.jsx)(`input`,{type:`password`,value:String(o[t.key]??``),placeholder:n(e.settingsValues?.[t.key]?`pluginSecretSet`:`pluginSecretUnset`),autoComplete:`new-password`,onChange:e=>u(t.key,e.target.value)}):t.type===`select`?(0,$.jsx)(`select`,{value:String(o[t.key]??``),onChange:e=>u(t.key,e.target.value),children:d(t).map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,$.jsx)(`input`,{type:t.type===`password`?`password`:t.type===`number`?`number`:`text`,value:String(o[t.key]??``),min:t.min,max:t.max,onChange:e=>u(t.key,t.type===`number`?Number(e.target.value):e.target.value)})})]},t.key))}),(0,$.jsxs)(`div`,{className:`plugin-settings-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-save`,disabled:!f||c,onClick:()=>{l(!0),Z({type:`plugin_settings`,pluginId:e.id,values:o}),setTimeout(()=>l(!1),800)},children:n(c?`pluginSettingsSaving`:`pluginSettingsSave`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-settings-reset`,onClick:()=>{let t={...e.settingsValues};for(let e of a)e.type===`secret`&&(t[e.key]=``);s(t)},children:n(`pluginSettingsReset`)})]})]})}function ko({plugin:e}){if(e.iconSvg)return(0,$.jsx)(Ri,{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=So({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)(yt,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(B,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0}):(0,$.jsx)(Ee,{className:`plugin-mgr-fallback-icon`,"aria-hidden":!0})}function Ao({open:e=!0,onClose:r,focusPluginId:i,plugins:a,disabledPlugins:o,models:s=[],onTogglePlugin:c,onOpenView:l,onOpenMarketplace:u}){let d=W(),f=(0,Q.useMemo)(()=>Xi(a),[a]),[p,m]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(`all`),[v,y]=(0,Q.useState)({}),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(!1),w=(0,Q.useRef)(new Map),T=(0,Q.useMemo)(()=>new Set(o),[o]),E=(0,Q.useMemo)(()=>{let e=0,t=0,n=0;for(let r of f){let i=!!(r.settingsSchema&&r.settingsSchema.length>0),a=T.has(r.id),o=!!r.error;i&&e++,!a&&!o&&t++,a&&n++}return{total:f.length,configurable:e,enabled:t,disabled:n}},[f,T]);(0,Q.useEffect)(()=>{if(!e||!i)return;y(e=>({...e,[i]:!0})),x(i),f.find(e=>e.id===i)&&_(`all`);let t=setTimeout(()=>{let e=w.current.get(i);e&&e.scrollIntoView({behavior:`smooth`,block:`nearest`})},120),n=setTimeout(()=>{x(null)},2600);return()=>{clearTimeout(t),clearTimeout(n)}},[e,i,f]);let D=(0,Q.useCallback)(e=>{y(t=>({...t,[e]:!t[e]}))},[]),O=(0,Q.useCallback)(()=>{let e=f.some(e=>e.settingsSchema?.length&&!v[e.id]),t={};for(let n of f)n.settingsSchema?.length&&(t[n.id]=e);y(t)},[f,v]),k=(0,Q.useMemo)(()=>{let e=p.trim().toLowerCase();return f.filter(t=>{let n=!!(t.settingsSchema&&t.settingsSchema.length>0),r=T.has(t.id),i=!!t.error;if(g===`configurable`&&!n||g===`enabled`&&(r||i)||g===`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})},[f,g,p,T]),A=(0,Q.useCallback)(()=>{C(!0),Z({type:`plugins_reload`}),setTimeout(()=>C(!1),800)},[]);return(0,$.jsxs)(Do,{open:e,onClose:r,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:E.total,enabled:E.enabled,configurable:E.configurable}),children:[(0,$.jsx)(B,{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:A,disabled:S,children:[(0,$.jsx)(ue,{className:S?`spin`:``,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:d(`pluginRescan`)})]}),u&&(0,$.jsxs)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{r(),u()},children:[(0,$.jsx)(oe,{"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:r,children:(0,$.jsx)(Be,{"aria-hidden":!0})})]})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-toolbar`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-search-wrap`,children:[(0,$.jsx)(ft,{className:`plugin-mgr-search-icon`,"aria-hidden":!0}),(0,$.jsx)(`input`,{type:`text`,className:`plugin-mgr-search-input`,placeholder:d(`pluginSearchPlaceholder`),value:p,onChange:e=>m(e.target.value)}),p&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-search-clear`,onClick:()=>m(``),"aria-label":`Clear`,children:(0,$.jsx)(Be,{"aria-hidden":!0})})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-filters`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${g===`all`?` active`:``}`,onClick:()=>_(`all`),children:[d(`pluginFilterAll`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:E.total})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${g===`configurable`?` active`:``}`,onClick:()=>_(`configurable`),children:[(0,$.jsx)(yt,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),d(`pluginFilterConfigurable`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:E.configurable})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${g===`enabled`?` active`:``}`,onClick:()=>_(`enabled`),children:[(0,$.jsx)(n,{className:`plugin-mgr-chip-icon`,"aria-hidden":!0}),d(`pluginFilterEnabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:E.enabled})]}),(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-chip${g===`disabled`?` active`:``}`,onClick:()=>_(`disabled`),children:[d(`pluginFilterDisabled`),(0,$.jsx)(`span`,{className:`plugin-mgr-chip-count`,children:E.disabled})]})]}),E.configurable>0&&(0,$.jsx)(`div`,{className:`plugin-mgr-expand-action`,children:(0,$.jsx)(`button`,{type:`button`,className:`plugin-mgr-text-btn`,onClick:O,children:f.some(e=>e.settingsSchema?.length&&!v[e.id])?d(`pluginExpandAll`):d(`pluginCollapseAll`)})})]})]}),(0,$.jsx)(`div`,{className:`plugin-mgr-body`,children:k.length===0?(0,$.jsxs)(`div`,{className:`plugin-mgr-empty`,children:[(0,$.jsx)(B,{className:`plugin-mgr-empty-icon`,"aria-hidden":!0}),(0,$.jsx)(`p`,{children:d(p||g!==`all`?`pluginEmptyFilter`:`pluginMenuEmpty`)}),(p||g!==`all`)&&(0,$.jsx)(`button`,{type:`button`,className:`btn plugin-mgr-btn-subtle`,onClick:()=>{m(``),_(`all`)},children:d(`pluginFilterAll`)})]}):(0,$.jsx)(`div`,{className:`plugin-mgr-list`,children:k.map(e=>{let n=!!(e.settingsSchema&&e.settingsSchema.length>0),i=T.has(e.id),a=!!e.error,o=!!v[e.id],u=e.view!==!1&&!a,f=b===e.id,p=e.homepage||(e.source?.startsWith(`http`)?e.source:void 0);return(0,$.jsxs)(`div`,{ref:t=>{t?w.current.set(e.id,t):w.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)(ko,{plugin:e})}),(0,$.jsxs)(`div`,{className:`plugin-mgr-card-names`,children:[(0,$.jsxs)(`div`,{className:`plugin-mgr-card-name-row`,children:[(0,$.jsx)(`span`,{className:`plugin-mgr-card-name`,children:e.name}),e.version&&(0,$.jsxs)(`span`,{className:`plugin-mgr-card-ver`,children:[`v`,e.version]}),(0,$.jsx)(`span`,{className:`plugin-mgr-card-id`,children:e.id})]}),(0,$.jsxs)(`div`,{className:`plugin-mgr-badges`,children:[n&&(0,$.jsxs)(`span`,{className:`plugin-badge config`,title:d(`pluginBadgeConfig`),children:[(0,$.jsx)(yt,{"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)(ct,{"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:()=>{r(),l(e.id)},title:d(`pluginOpenView`),children:[(0,$.jsx)(Ne,{"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)(ct,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:e.error})]}),n&&(0,$.jsxs)(`div`,{className:`plugin-mgr-settings-section`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`plugin-mgr-settings-toggle`,onClick:()=>D(e.id),"aria-expanded":o,children:[o?(0,$.jsx)(L,{"aria-hidden":!0}):(0,$.jsx)(h,{"aria-hidden":!0}),(0,$.jsx)(yt,{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)(Oo,{plugin:e,models:s})})]})]},e.id)})})})]})}function jo({onClose:e}){let t=W(),{locale:n,setLocale:r,reloadPacks:i}=c(),[a,s]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``);async function p(){try{let e=await fetch(o(g(`/api/locales`)));if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();s(t.packs??[]),u(``)}catch(e){u(t(`localeListFailed`,{error:e instanceof Error?e.message:String(e)}))}}(0,Q.useEffect)(()=>{p()},[]);async function m(e){f(e),u(``);try{let t=await fetch(o(g(`/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 p()}catch(e){u(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{f(``)}}async function h(e){f(e),u(``);try{let t=await fetch(o(g(`/api/locales/${e}`)),{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);se(e),n===e&&r(`zh`),await i(),await p()}catch(e){u(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{f(``)}}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)(Ct,{}),` `,t(`localePacks`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:t(`close`),onClick:e,children:(0,$.jsx)(Be,{})})]}),l&&(0,$.jsx)(`div`,{className:`bg-task-empty`,children:l}),a===null&&!l?(0,$.jsx)(`div`,{className:`bg-task-empty`,children:t(`loading`)}):(0,$.jsx)(`ul`,{className:`bg-task-list`,children:(a??[]).map(e=>{let n=d===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 h(e.code),children:[(0,$.jsx)(_t,{}),(0,$.jsx)(`span`,{children:t(n?`localeRemoving`:`localeRemove`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:n,title:t(`localeInstall`),onClick:()=>void m(e.code),children:[(0,$.jsx)(he,{}),(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 p(),children:[(0,$.jsx)(ue,{}),(0,$.jsx)(`span`,{children:t(`bgTaskRefresh`)})]})})]})})}var Mo=`xing-shuyin/pi-web-ui`,No={state:`idle`,version:null,percent:0,message:null};function Po(e){return typeof e==`number`&&Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Fo(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:Po(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 Io(e){if(!Zt(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 Lo(e){return e instanceof Error?e.message:String(e)}function Ro(e){let t=(e??``).trim().replace(/^v/,``);return t?`https://github.com/${Mo}/releases/tag/v${t}`:`https://github.com/${Mo}/releases/latest`}function zo(){let[e]=(0,Q.useState)(()=>Io()),[t,n]=(0,Q.useState)(No);(0,Q.useEffect)(()=>{if(e)return e.onEvent(e=>n(t=>Fo(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:Lo(e)}))))},[e]),i=(0,Q.useCallback)(()=>{e&&(n(e=>({...e,state:`downloading`,message:null})),e.download().catch(e=>n(t=>({...t,state:`error`,message:Lo(e)}))))},[e]),a=(0,Q.useCallback)(()=>{e&&e.quitAndInstall().catch(e=>n(t=>({...t,state:`error`,message:Lo(e)})))},[e]);return{...t,bridge:e,check:r,download:i,quitAndInstall:a}}function Bo({anchor:e,content:t,onClose:n}){let r=(0,Q.useRef)(null),{panelRef:i,style:a,measure:o}=dr({anchor:e,side:`top`,align:`right`,gap:6,onClose:n});return(0,Q.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let n=t.render(e);return o(),()=>{typeof n==`function`&&n(),e.innerHTML=``}},[t]),(0,Q.useEffect)(()=>{let e=i.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>o());return t.observe(e),()=>t.disconnect()},[]),(0,Q.useEffect)(()=>{let t=i.current;return(t?.querySelector(`button`)??t)?.focus({preventScroll:!0}),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[e,i]),(0,cr.createPortal)((0,$.jsx)(`div`,{ref:i,className:`footer-slot-popover`,style:a,role:`dialog`,"aria-modal":`false`,tabIndex:-1,"data-pi-popover":`footer-slot`,children:(0,$.jsx)(`div`,{ref:r,className:`footer-slot-popover-body`})}),document.body)}var Vo=new Map,Ho=new Set,Uo=new Map;function Wo(){Uo=new Map(Vo);for(let e of Ho)try{e()}catch{}}function Go(e,t){let n=String(e??``).trim();if(!n)return!1;let r=Vo.get(n);if(t===null)return r?(Vo.delete(n),Wo(),!0):!1;let i=String(t.text??``).trim();if(!i)return r?(Vo.delete(n),Wo(),!0):!1;let a={text:i,...t.tip?{tip:t.tip}:{},...t.pluginId?{pluginId:t.pluginId}:{},...t.action?{action:t.action}:{},...typeof t.content?.render==`function`?{content:t.content}:{}};return r&&r.text===a.text&&r.tip===a.tip&&r.action===a.action&&r.content?.render===a.content?.render?!1:(Vo.set(n,a),Wo(),!0)}function Ko(e){let t=!1;for(let[n,r]of Vo)r.pluginId===e&&(Vo.delete(n),t=!0);t&&Wo()}function qo(e){return Ho.add(e),()=>Ho.delete(e)}function Jo(){return(0,Q.useSyncExternalStore)(qo,()=>Uo,()=>Uo)}function Yo(e){let t=Jo();if(e)return t.get(e)??null;for(let e of t.values())return e;return null}function Xo(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 Zo=2e3;function Qo(e,t,n=Zo){return e.filter(e=>t-e.t<=n)}function $o(e,t=Zo){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 es(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 ts(e){let t=0;for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text?t+=es(n.text):n.type===`thinking`&&typeof n.thinking==`string`&&n.thinking&&(t+=es(n.thinking));return t}var ns={pi:{id:`pi`,name:`Pi`,packageName:`@earendil-works/pi-coding-agent`,cliPackageName:null,installCommand:`npm i -g @earendil-works/pi-coding-agent`,cliCommand:`pi`,cliModelArgs:`provider-model`,cliRequiresArgs:!1},dsh:{id:`dsh`,name:`DSH`,packageName:`@deepseek-ai/dsh`,cliPackageName:`@deepseek-harness-tui/dsh-tui`,installCommand:`npm i -g @deepseek-ai/dsh @deepseek-harness-tui/dsh-tui`,cliCommand:`dsh-tui`,cliModelArgs:null,cliRequiresArgs:!1},claude:{id:`claude`,name:`Claude Code`,packageName:`@anthropic-ai/claude-code`,cliPackageName:null,installCommand:`npm i -g @anthropic-ai/claude-code`,cliCommand:`claude`,cliModelArgs:`model`,cliRequiresArgs:!1},codex:{id:`codex`,name:`Codex`,packageName:`@openai/codex`,cliPackageName:null,installCommand:`npm i -g @openai/codex`,cliCommand:`codex`,cliModelArgs:`model`,cliRequiresArgs:!1},agy:{id:`agy`,name:`Antigravity`,packageName:null,cliPackageName:null,installCommand:`https://antigravity.google/docs/getting-started?tab=cli`,cliCommand:`agy`,cliModelArgs:`model`,cliRequiresArgs:!1},durable:{id:`durable`,name:`Pi Durable`,packageName:`@earendil-works/pi-durable`,cliPackageName:null,installCommand:`npm i -g @earendil-works/pi-durable`,cliCommand:null,cliModelArgs:null,cliRequiresArgs:!1}},rs=[{id:`pi`,titleKey:`settingsEnginePiTitle`,badge:`PI`,tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-pi`},{id:`dsh`,titleKey:`settingsEngineDshTitle`,badge:`DSH`,tagKey:`engineTagFast`,descKey:`settingsEngineDshDesc`,colorClass:`engine-dsh`},{id:`claude`,titleKey:`settingsEngineClaudeTitle`,badge:`CLAUDE`,tagKey:`engineTagUniversal`,descKey:`settingsEngineClaudeDesc`,colorClass:`engine-claude`},{id:`codex`,titleKey:`settingsEngineCodexTitle`,badge:`CODEX`,tagKey:`engineTagUniversal`,descKey:`settingsEngineCodexDesc`,colorClass:`engine-codex`},{id:`durable`,titleKey:`settingsEngineDurableTitle`,badge:`DURABLE`,tagKey:`engineTagDurable`,descKey:`settingsEngineDurableDesc`,colorClass:`engine-durable`}].map(e=>{let t=ns[e.id];return{...e,...t.packageName?{packageName:t.packageName}:{},...t.installCommand?{installCommand:t.installCommand}:{}}});function is({direction:e,align:t,className:r,label:i,caret:a=!1,bar:o,portal:s}){let{engine:l}=Se(),u=gt(),{t:d}=c(),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),g=(0,Q.useRef)(null),_=e??(o===`left`?`right`:o===`right`?`left`:o===`bottom`?`up`:`down`),v=s??(o===`left`||o===`right`||o===`bottom`),y=e=>{e?Z({type:`check_engines`}):h(null),p(e)},b=rs.find(e=>e.id===l)??{id:l,titleKey:`settingsEnginePiTitle`,badge:l.toUpperCase(),tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-${l}`},x=d(b.titleKey),S=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ze,{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 ${b.colorClass}`,children:b.badge})]}):(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${b.colorClass}`,children:b.badge})]});return(0,$.jsx)(`div`,{ref:g,className:`engine-picker-wrap ${b.colorClass} ${r??``}`,"data-bar-item":`host:engine`,children:(0,$.jsxs)(Wt,{trigger:S,open:f,onOpenChange:y,direction:_,align:t??(o===`right`?`right`:`left`),fit:!0,caret:a,portal:v,triggerClassName:`bar-item chip engine-picker-btn ${b.colorClass}`,menuClassName:`engine-picker-menu`,tip:`${d(`engineBadge`)}: ${i??x} — ${d(`engineSwitchTip`)}`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-header`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-title`,children:[(0,$.jsx)(ze,{}),(0,$.jsx)(`span`,{children:d(`settingsEngineSection`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-subtitle`,children:d(`enginePickerDesc`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-list`,role:`menu`,children:rs.map(e=>{let t=e.id===l,r=u.find(t=>t.id===e.id),i=e.id===`pi`||(r?r.installed:!1),a=!!r?.updating,o=!!r?.uninstalling,s=!!(i&&r?.hasUpdate&&r?.latestVersion),c=s||a,f=e.id!==`pi`&&i,g=t=>{t.stopPropagation(),p(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:d(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}))},_=t=>{t.stopPropagation(),!(a||o)&&(p(!1),Z({type:`update_engine`,engineId:e.id}))},v=n=>{n.stopPropagation(),!(o||a)&&(t||(m===e.id?(h(null),Z({type:`uninstall_engine`,engineId:e.id})):h(e.id)))},y=()=>{if(!i){p(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:d(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}));return}p(!1),t||Z({type:`switch_engine`,engine:e.id})};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,title:i?void 0:d(`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)(ze,{className:`engine-picker-item-icon`}),(0,$.jsx)(`span`,{className:`engine-badge ${e.colorClass}`,children:e.badge}),d(e.titleKey)!==e.badge&&(0,$.jsx)(`span`,{className:`engine-picker-item-name`,children:d(e.titleKey)}),(0,$.jsx)(`span`,{className:`engine-picker-item-tag${i?o?` uninstalling`:a||s?` update-available`:``:` uninstalled`}`,title:s?d(`engineUpdateTip`,{current:r?.version??``,latest:r?.latestVersion??``}):void 0,children:d(i?o?`engineUninstalling`:a?`engineUpdating`:s?`engineUpdateAvailable`:e.tagKey:`engineNotInstalled`)}),!i&&e.installCommand&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-install-btn`,title:d(`engineInstallTip`),onClick:g,children:[(0,$.jsx)(he,{className:`engine-install-icon`}),(0,$.jsx)(`span`,{children:d(`engineInstall`)})]}),c&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-update-btn`,disabled:a||o,title:a?d(`engineUpdating`):d(`engineUpdateTip`,{current:r?.version??``,latest:r?.latestVersion??``}),onClick:_,children:[(0,$.jsx)(ue,{className:`engine-update-icon${a?` spinning`:``}`}),(0,$.jsx)(`span`,{children:d(a?`engineUpdating`:`engineUpdate`)})]}),f&&(0,$.jsxs)(`button`,{type:`button`,"data-testid":`engine-uninstall-${e.id}`,className:`engine-picker-uninstall-btn${m===e.id?` confirm`:``}`,disabled:o||a||t,title:t?d(`engineActiveNoUninstall`):o?d(`engineUninstalling`):m===e.id?d(`engineUninstallConfirm`):d(`engineUninstallTip`),onClick:v,children:[(0,$.jsx)(_t,{className:`engine-uninstall-icon`}),(0,$.jsx)(`span`,{children:o?d(`engineUninstalling`):m===e.id?d(`engineUninstallConfirm`):d(`engineUninstall`)})]}),t&&(0,$.jsx)(n,{className:`engine-picker-check`})]}),(0,$.jsx)(`div`,{className:`engine-picker-item-desc`,children:d(e.descKey)})]},e.id)})})]})})}function as(e){return/^ssh:\/\//i.test(e.trim())}function os(e){return e.split(/\r?\n/).filter(e=>e.length>0)}var ss=262144,cs=300,ls=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,us=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,ds=/"(?:name|skill)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,fs=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,ps=/"(query|q|search|pattern)"\s*:\s*"((?:[^"\\\n]|\\.){0,400})"/,ms=1e9;function hs(e){let t=e.split(`
|
|
3
|
+
`),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 gs(e){let{name:t,argumentsText:n,isCollapsed:r=!1}=e,i=e.hints??_s(n);switch(t){case`bash`:{if(!r||!i.command)return null;let e=hs(i.command);return e?{text:e,title:i.command,prefix:`$ `,className:`toolcall-cmd`}:null}case`read`:case`write`:case`edit`:case`patch`:case`ls`:return i.path?{text:Ss(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:Ss(i.path),title:i.path,className:`toolcall-path`}:i.query?{text:i.query,title:i.query,className:`toolcall-query`}:null}}function _s(e){if(!e)return{};let t=e.length>ss?e.slice(0,ss):e;return{path:Cs(t),timeout:ws(t),command:Es(e),agent:vs(t),skillName:ys(t),codeLines:ks(e),query:Ts(t),questionTitle:js(t)}}function vs(e){let t=us.exec(e);if(!t)return;let n=t[1].replace(/[\u0000-\u001f\u007f]/g,``).trim();if(n)return n.length>cs?`${n.slice(0,cs)}…`:n}function ys(e){let t=ds.exec(e);if(!t)return;let n=Ds(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>cs?`${n.slice(0,299)}…`:n}var bs=[`task`,`expected_outcome`,`required_tools`,`must_do`,`must_not_do`,`context`];function xs(e){if(!e||e.length>ss)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r={};for(let e of[...bs,`agent`,`model`])typeof n[e]==`string`&&n[e].trim()&&(r[e]=n[e]);return r}catch{return{}}}function Ss(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 Cs(e){let t=ls.exec(e);if(!t)return;let n=Ds(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>cs?`${n.slice(0,299)}…`:n}function ws(e){let t=fs.exec(e);if(!t)return;let n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>ms)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 Ts(e){let t=ps.exec(e);if(!t)return;let n=Ds(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>60?`${n.slice(0,57)}…`:n}function Es(e){if(!(e.length>ss))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 Ds(e){try{let t=JSON.parse(`"${e}"`);return typeof t==`string`?t:e}catch{return e}}function Os(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=Ds(e[1]))}else n&&(t=e);if(!t)return{};let r=t.indexOf(`
|
|
4
|
+
`),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 ks(e){let t=Os(e);if(!t.code)return;let n=t.code.split(`
|
|
5
|
+
`).length;return n>0?n:void 0}var As=/"(?:header|question)"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/;function js(e){let t=As.exec(e);if(!t)return;let n=Ds(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>40?`${n.slice(0,38)}…`:n}function Ms(e){if(!e||e.length>ss)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 Ns=30,Ps=56,Fs=e=>/[^\x00-\x7f]/.test(e)?Math.round(Ns/2):Ns;function Is(e){return(0,$.jsx)(Ls,{...e},e.cwd??``)}function Ls({cwd:e,onClose:t,onCreate:n,disabled:r=!1}){let i=W(),a=(0,Q.useId)(),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)({}),f=as(e??``),p=f?zn(e??``):null,[m,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(0),[S,C]=(0,Q.useState)(!1),w=f&&m?.persistence?.available===!0,T=e=>S&&w?{...e,keepAlive:!0}:e,E=(0,Q.useRef)(null),D=!!e&&!m&&v===null;(0,Q.useEffect)(()=>{if(!e)return;let t=new AbortController;return E.current=t,(async()=>{try{let n=await fetch(g(`/api/native-cli/discovery?cwd=${encodeURIComponent(e)}`),{signal:t.signal}),r=await n.json();if(t.signal.aborted)return;if(!n.ok)throw Error(r.error||``);if(r.cwd!==e||r.target!==(f?`ssh`:`local`)||!Array.isArray(r.clis))throw Error();_(r)}catch(e){t.signal.aborted||y(e instanceof Error?e.message:``)}})(),()=>t.abort()},[e,f,b]);let O=()=>{E.current?.abort(),t()},k=e=>e===`custom`?void 0:m?.clis.find(t=>t.preset===e),A=e=>{if(r||e===`custom`)return r;let t=k(e);return f?!t?.available:t?.available===!1},j=e=>{let t=k(e.id),n=e.cliCommand??e.name;if(t?.available){let e=t.executable??n;return{text:Ss(e,Fs(e)),full:e}}return f?{text:t?.error??i(D?`nativeCliRemoteDetecting`:`nativeCliRemoteUnavailable`)}:t?{text:i(`nativeCliNotInstalled`)}:D?{text:i(`nativeCliDetecting`)}:{text:e.cliRequiresArgs?i(`nativeCliConfigureArgs`):n}},M=(e,t)=>{window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:i(`installEngineTabTitle`,{name:e}),command:t}})),O()},N=Object.values(ns).filter(e=>e.cliCommand),P=[`claude`,`codex`,`pi`];N.sort((e,t)=>{let n=e=>P.includes(e)?P.indexOf(e):P.length;return n(e.id)-n(t.id)});let F=o?u[o]??``:``,I=os(F),L=o!==null&&o!==`custom`&&ns[o].cliRequiresArgs,R=o!==null&&!A(o)&&(o!==`custom`||!!c.trim())&&(!L||!!I[0]?.trim()),z=e=>{let t=e.installCommand;return t?/^https?:\/\//i.test(t)?`docs`:`terminal`:null},B=e=>{if(!A(e)){if(e===`custom`||ns[e].cliRequiresArgs){s(e);return}n(T({preset:e}))}};return(0,$.jsx)(Do,{title:i(`nativeCliCreate`),icon:(0,$.jsx)(Ce,{size:18}),onClose:O,className:`native-cli-create-modal`,closeOnBackdropClick:!r,closeOnEscape:!r,showCloseButton:!r,children:(0,$.jsxs)(`div`,{className:`native-cli-create-body`,"aria-busy":r||D,children:[(0,$.jsx)(`p`,{className:`native-cli-create-hint`,children:i(`nativeCliChooseEngine`)}),e&&(0,$.jsx)(`div`,{className:`native-cli-create-cwd`,title:e,children:p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{children:i(`nativeCliRemoteLocation`,{host:`${p.username}@${p.host}:${p.port}`})}),(0,$.jsx)(`div`,{children:i(`nativeCliRemotePath`,{path:Ss(p.remotePath,Ps)})})]}):Ss(e,Ps)}),D&&(0,$.jsx)(`p`,{className:`native-cli-create-hint`,role:`status`,children:i(f?`nativeCliRemoteDetecting`:`nativeCliDetecting`)}),v!==null&&(0,$.jsxs)(`div`,{role:`alert`,className:`native-cli-create-hint`,children:[(0,$.jsx)(`p`,{children:v||i(f?`nativeCliRemoteDiscoveryFailed`:`nativeCliDiscoveryFailed`)}),f&&(0,$.jsx)(`p`,{children:i(`nativeCliRemoteConnectHint`)})]}),e&&(0,$.jsx)(`div`,{children:(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:r||D,onClick:()=>{E.current?.abort(),_(null),C(!1),y(null),x(e=>e+1)},children:i(`nativeCliRemoteRetry`)})}),f&&(0,$.jsxs)(`div`,{className:`native-cli-persistence`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S&&w,disabled:r||!w,onChange:e=>C(e.target.checked),"aria-describedby":`${a}-persistence-hint`}),i(`nativeCliSession.keepAlive`)]}),(0,$.jsx)(`p`,{id:`${a}-persistence-hint`,className:`native-cli-create-hint`,children:w?i(`nativeCliSession.keepAliveHint`):m?.persistence?.error||i(`nativeCliSession.persistenceUnavailable`)})]}),(0,$.jsxs)(`div`,{className:`native-cli-create-options`,children:[N.map(e=>{let t=k(e.id),n=j(e),s=!f&&t?.available===!1?z(e):null,c=e.installCommand??``;return(0,$.jsxs)(`div`,{className:`native-cli-create-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-option`,disabled:A(e.id),"aria-expanded":e.cliRequiresArgs?o===e.id:void 0,"aria-controls":e.cliRequiresArgs?`${a}-config`:void 0,onClick:()=>B(e.id),children:[(0,$.jsx)(Ce,{size:18}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`small`,{className:n.full?`native-cli-create-path`:void 0,title:n.full,children:n.text})]}),(0,$.jsx)(h,{size:16})]}),s===`terminal`&&(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-install`,disabled:r,title:c,onClick:()=>M(e.name,c),children:[(0,$.jsx)(he,{size:13}),i(`nativeCliInstall`)]}),s===`docs`&&(0,$.jsxs)(`a`,{className:`native-cli-create-install`,href:c,target:`_blank`,rel:`noreferrer`,children:[(0,$.jsx)(he,{size:13}),i(`nativeCliInstallDocs`)]})]},e.id)}),(0,$.jsx)(`div`,{className:`native-cli-create-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-option`,disabled:r,"aria-expanded":o===`custom`,"aria-controls":`${a}-config`,onClick:()=>B(`custom`),children:[(0,$.jsx)(Ce,{size:18}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:i(`nativeCliCustom`)}),(0,$.jsx)(`small`,{children:i(`nativeCliExecutable`)})]}),(0,$.jsx)(h,{size:16})]})})]}),o&&(0,$.jsxs)(`form`,{id:`${a}-config`,className:`native-cli-create-config`,onSubmit:e=>{e.preventDefault(),R&&n(T(o===`custom`?{preset:`custom`,executable:c.trim(),args:I}:{preset:o,args:I}))},children:[(0,$.jsx)(`strong`,{children:o===`custom`?i(`nativeCliCustom`):ns[o].name}),o===`custom`&&(0,$.jsxs)(`label`,{htmlFor:`${a}-executable`,children:[i(f?`nativeCliRemoteExecutable`:`nativeCliExecutable`),(0,$.jsx)(`input`,{id:`${a}-executable`,value:c,onChange:e=>l(e.target.value),disabled:r,required:!0,autoFocus:!0,autoComplete:`off`})]}),f&&o===`custom`&&(0,$.jsx)(`p`,{className:`native-cli-create-hint`,children:i(`nativeCliRemoteExecutableHint`)}),(0,$.jsxs)(`label`,{htmlFor:`${a}-args`,children:[i(`nativeCliArgs`),(0,$.jsx)(`textarea`,{id:`${a}-args`,value:F,onChange:e=>d(t=>({...t,[o]:e.target.value})),disabled:r,rows:4,required:!!L,"aria-describedby":`${a}-args-hint`})]}),(0,$.jsx)(`p`,{id:`${a}-args-hint`,className:`native-cli-create-hint`,children:i(`nativeCliArgsHint`)}),(0,$.jsx)(`div`,{className:`native-cli-create-actions`,children:(0,$.jsx)(`button`,{type:`submit`,className:`btn primary`,disabled:!R,children:i(`nativeCliStart`)})})]})]})})}function Rs({children:e,cwd:t,onCreateCli:n}){let r=W(),i=He(`tabs`),a=!!n&&(!i||i.includes(`terminal`)),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(!1);if((0,Q.useLayoutEffect)(()=>{let e=o.current,t=e?.querySelector(`:scope > button`);if(!e||!t)return;let n=()=>{let n=t.getBoundingClientRect().height;n>0&&e.style.setProperty(`--native-cli-action-width`,`${n}px`)};if(n(),typeof ResizeObserver>`u`)return;let r=new ResizeObserver(n);return r.observe(t),()=>r.disconnect()},[a]),!a||!n)return e;let u=(0,Q.isValidElement)(e)?(0,Q.cloneElement)(e,{title:e.props.title??r(`newChat`),"aria-label":e.props[`aria-label`]??r(`newChat`)}):e;return(0,$.jsxs)(`span`,{ref:o,className:`native-cli-create-entry`,role:`group`,"aria-label":r(`newChat`),"data-cli-expanded":c||void 0,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onFocus:()=>l(!0),onBlur:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||l(!1)},onKeyDown:e=>{e.key===`ArrowLeft`&&c?(e.preventDefault(),s.current?.focus()):(e.key===`ArrowRight`||e.key===`Escape`)&&(e.preventDefault(),o.current?.querySelector(`:scope > button`)?.focus(),e.key===`Escape`&&l(!1))},children:[u,(0,$.jsx)(`span`,{className:`native-cli-create-hover`,"aria-hidden":!c,inert:!c,children:(0,$.jsx)(`button`,{ref:s,type:`button`,className:`native-cli-create-hover-button`,title:r(`nativeCliCreate`),"aria-label":r(`nativeCliCreate`),tabIndex:c?0:-1,onClick:e=>{e.stopPropagation(),l(!1),n(t)},children:(0,$.jsx)(Ce,{size:12})})})]})}function zs(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}var Bs={systemPrompt:`settingsSystemPrompt`,memoryFiles:`contextMemoryFiles`,tools:`contextTools`,skills:`contextSkills`,toolResults:`contextToolResults`,messages:`messages`,other:`contextOther`};function Vs({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}=dr({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 Bs)??[],x=b.length>0,S=b.map(e=>({...e,label:a(Bs[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,cr.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":`${zs(_)} / ${zs(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:zs(_),total:zs(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:zs(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:zs(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:zs(m),max:zs(p)})})]}):(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextUsageUnavailable`)})]}),document.body)]})}function Hs(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 Us({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:h,onUiAction:g,uiContextEntries:_,dropdownProps:v,zenMode:y,onToggleZenMode:b,onOpenSandboxModal:x,onCreateCli:S}){let w=W(),{locale:T,packs:E,setLocale:O}=c(),{engine:A}=Se(),j=A===`dsh`,[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),R=n.settings?.uiLayout,z=n.state,ee=z?.stats,V=z?.isStreaming??!1,te=z?.turnTiming,ne=!!te&&te.finishedAt===void 0,[re,ie]=(0,Q.useState)(Date.now);(0,Q.useEffect)(()=>{if(e.id!==`host:working`||!ne)return;ie(Date.now());let t=window.setInterval(()=>ie(Date.now()),1e3);return()=>window.clearInterval(t)},[e.id,ne,te?.startedAt]);let H=mn(ee?.cost??0),ae=Yo(),[U,oe]=(0,Q.useState)(!1),se=(0,Q.useRef)(null),ce=ae?.content??null;(0,Q.useEffect)(()=>{ce||oe(!1)},[ce]);let le=(0,Q.useRef)([]),G=z?.streamingMessage?ts(z.streamingMessage.content):0;(0,Q.useEffect)(()=>{if(!V){le.current=[];return}let e=Date.now(),t=le.current,n=t[t.length-1];n&&e-n.t<250||(le.current=Qo([...t,{t:e,out:G}],e))},[V,G]);let K=V?$o(le.current):0,ue=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ue.current!==null&&window.clearTimeout(ue.current)},[]);let de=n=>{n.preventDefault(),n.stopPropagation();let r=t=>{let n={...R?.slots,[e.id]:t},r={...R?.align};(t===`sidebar.left`||t===`sidebar.right`)&&!r[e.id]&&(r[e.id]=`center`),Z({type:`set_settings`,uiLayout:{...R,slots:n,...r[e.id]?{align:r}:{}}})},i=()=>{let t=new Set(R?.hidden??[]);t.add(e.id);let n=(R?.shown??[]).filter(t=>t!==e.id);Z({type:`set_settings`,uiLayout:{...R,hidden:[...t],shown:n}})},a=()=>{Z({type:`set_settings`,uiLayout:Aa(R,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:[]}),aa.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||R?.slots?.[e.id]||R?.labels?.[e.id]||R?.align?.[e.id]||R?.order?.includes(e.id))&&o.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:w(`uiLayoutRestore`),kind:`action`,order:60,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),_&&_.length>0&&o.push(..._),za({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()}})},fe=e.id,pe=e.labelExplicit?e.label:``,q=e=>pe||e,me=e=>pe?`${pe} ${e}`:e;if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`bar-item bar-item-select`,title:e.hint??e.label,"data-tip":e.hint??e.label,"aria-label":e.label,value:t,onChange:t=>g?.(e,t.target.value),onContextMenu:de,"data-bar-item":fe,children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})}if(fe===`host:brand`)return(0,$.jsx)(yr,{label:q(`pi-web-ui`),barItem:!0,onContextMenu:de});if(fe===`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:de,"data-bar-item":fe,children:[(0,$.jsx)(`span`,{className:`status-dot ${e}`}),(0,$.jsx)(`span`,{className:`status-conn-label bar-item-text`,children:me(t)}),i&&(0,$.jsx)(`span`,{className:`status-latency ${a}`,children:i})]})}if(fe===`host:engine`)return(0,$.jsx)(`span`,{onContextMenu:de,"data-bar-item":fe,className:`bar-item-engine-wrap`,style:{display:`inline-flex`,alignItems:`center`},children:(0,$.jsx)(is,{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(fe===`host:ctx`){let e=ee?.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?zs(e.tokens):null,c=a>0?zs(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`)}: ${zs(e?.tokens??0)} / ${zs(r)} (${w(`softCapMarker`)}, max ${zs(e?.contextWindow??0)})`:r!==null&&r>0?`${w(`contextUsage`)}: ${l} · ${w(`softCapMarker`)}: ${zs(r)}`:`${w(`contextUsage`)}: ${l}`,f=o!==null&&o>0?+(31.42*(1-Math.min(o,100)/100)).toFixed(2):31.42;return(0,$.jsxs)(Vs,{context:e,bar:t,title:d,onContextMenu:de,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:[pe?`${pe} `:``,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}:${z?.conversationId??z?.sessionId??``}`)}if(fe===`host:cache`){let e=Xo(ee?.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:zs(e.read),write:zs(e.write),miss:zs(e.miss),input:zs(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:de,"data-bar-item":fe,children:[(0,$.jsx)(D,{className:`bar-item-icon`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[pe?`${pe} `:``,(0,$.jsx)(`b`,{className:`cache-pct ${n}`,children:r})]})]})}if(fe===`host:cost`){let t=ee?.cost??0,n=H.tooltip||w(`cumulativeCost`),r=t<=0,i=ae,a=!!i?.text&&!!(i?.content||i?.action),o=()=>{if(i?.content){oe(e=>!e);return}i?.action&&g?.({...e,action:i.action,source:`plugin:${i.pluginId??``}`})};return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cost bar-item-cost${r?` is-zero`:``}${pe?` has-name`:``}`,title:n,"data-tip":n,onContextMenu:de,"data-bar-item":fe,children:[pe?(0,$.jsx)(`span`,{className:`bar-item-text`,children:pe}):null,H.symbol?(0,$.jsx)(`span`,{className:`bar-item-char`,children:H.symbol}):null,(0,$.jsx)(`span`,{className:`bar-item-text`,children:H.value}),i?(0,$.jsxs)(`span`,{ref:se,className:`cost-quota${a?` is-clickable`:``}`,"data-bar-item":`host:cost-quota`,"data-plugin":i.pluginId??``,title:i.tip||i.text,"data-tip":i.tip||i.text,role:a?`button`:void 0,tabIndex:a?0:void 0,"aria-haspopup":i?.content?`dialog`:void 0,"aria-expanded":i?.content?U:void 0,onClick:a?o:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),o())}:void 0,children:[(0,$.jsx)(`span`,{className:`bar-item-char`,children:`/`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:i.text})]}):null,i?.content&&U?(0,$.jsx)(Bo,{anchor:se.current,content:i.content,onClose:()=>oe(!1)}):null]})}if(fe===`host:msg-count`){let e=ee?.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:de,"data-bar-item":fe,children:[(0,$.jsx)(Cr,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:me(String(e))})]})}if(fe===`host:working`){if(!V&&!te)return null;let e=V||ne,t=w(e?`working`:`done`),n=te?Math.max(0,Math.floor(((te.finishedAt??re)-te.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=(z?.queue?.steering?.length??0)+(z?.queue?.followUp?.length??0);return(0,$.jsxs)(`span`,{className:`bar-item status-item bar-item-working${e?` working`:``}`,title:`${t}${te?` · ${r}`:``}`,"data-tip":`${t}${te?` · ${r}`:``}`,onContextMenu:de,"data-bar-item":fe,children:[e&&(0,$.jsx)(`span`,{className:`working-spin`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[q(t),i>0&&` ⏳ ${i}`]}),te&&(0,$.jsx)(`span`,{className:`bar-item-duration`,children:r}),e&&K>0&&(0,$.jsx)(`span`,{className:`status-rate bar-item-rate`,title:w(`rateTip`),children:`${Math.round(K)}${w(`tps`)}`})]})}if(fe===`host:status-delegate`)return z?.delegateMode?(0,$.jsxs)(`span`,{className:`bar-item status-item delegate-badge bar-item-delegate`,title:z.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),"data-tip":z.delegateConvId?w(`delegateModeOpenTip`):w(`delegateModeBadgeTip`),onContextMenu:de,"data-bar-item":fe,children:[(0,$.jsx)(`span`,{className:`bar-item-icon`,children:`🔎`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:q(w(`delegateModeBadge`))}),z.delegateConvId?(0,$.jsx)(`button`,{type:`button`,className:`delegate-badge-open`,title:w(`delegateModeOpenTip`),onClick:()=>Z({type:`switch_conversation`,id:z.delegateConvId}),children:`↗`}):null]}):null;if(fe===`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:de,"data-bar-item":fe,children:[(0,$.jsx)(k,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:me(`${t} · ${r}`)})]})}if(fe===`host:browser`)return!Zt()&&n.settings?.disabledAgentTools?.includes(`browser_page`)?null:(0,$.jsx)(`span`,{className:`bar-item-wrap`,onContextMenu:de,"data-bar-item":fe,children:(0,$.jsx)(Hr,{})});let _e=t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`;if(fe===`host:language`)return(0,$.jsxs)(Wt,{direction:_e,align:t===`right`?`right`:`left`,portal:!0,open:M,onOpenChange:N,tip:q(w(`language`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:de,dataBarItem:fe,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Tr,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:me(Hs(T))})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`language`)}),E.map(e=>(0,$.jsx)(Ut,{active:T===e.code,onClick:()=>{O(e.code),N(!1)},children:e.nativeName},e.code)),v?.onLocaleModalOpen?(0,$.jsxs)(Ut,{onClick:()=>{N(!1),v.onLocaleModalOpen?.()},children:[(0,$.jsx)(he,{}),` `,w(`localeGetMore`)]}):null]});if(fe===`host:theme`){let e=v?.themes??[],n=v?.theme??null;return(0,$.jsx)(Wt,{direction:_e,align:t===`right`?`right`:`left`,portal:!0,open:P,onOpenChange:t=>{F(t),t&&e.length===0&&v?.reloadThemes?.()},tip:q(w(`theme`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:de,dataBarItem:fe,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(mt,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:q(w(`theme`))})]}),children:(()=>{let t=e.filter(e=>e.group===`classic`),r=e.filter(e=>e.group!==`classic`),i=e=>{let t=X(T)?e.name:e.nameEn??e.name,n=e.scheme===`light`?w(`themeLight`):e.scheme===`dark`?w(`themeDark`):``;return n?X(T)?`${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)(Ut,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:t.length>0?w(`themeGroupBuiltin`):w(`theme`)}),(0,$.jsx)(Ut,{active:n===null,onClick:()=>{v?.onThemeChange?.(null),F(!1)},children:w(`themeDefault`)}),r.map(e=>(0,$.jsx)(Ut,{active:n===e.id,onClick:()=>{v?.onThemeChange?.(e.id),F(!1)},children:i(e)},e.id))]})})()})}if(fe===`host:update`){let e=v?.updatesCount??0;return v?.managed?(0,$.jsxs)(`span`,{className:`bar-item chip`,title:w(`updatesManaged`),"data-tip":w(`updatesManaged`),onContextMenu:de,"data-bar-item":fe,children:[(0,$.jsx)(he,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:me(`v${v?.appVersion??n.update?.current??`…`}`)})]}):(0,$.jsxs)(Wt,{direction:_e,align:t===`right`?`right`:`left`,portal:!0,open:I,onOpenChange:e=>{L(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},tip:q(w(`update`)),fit:!0,caret:!1,triggerClassName:`bar-item chip`,onContextMenu:de,dataBarItem:fe,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(he,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:me(`v${n.update?.current??`…`}`)}),n.update&&!n.update.upToDate&&(0,$.jsx)(`span`,{className:`update-dot`}),e>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:e})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:w(`update`)}),v?.renderUpdateBody?.(),v?.renderAllUpdatesBody?.()]})}let ve=null,J=e.label,ye=null,be=!1,xe=!1,Y=``,we,Te,Ee;switch(fe){case`host:chat`:if(!r||r===`chat`||r===`native-cli`)return null;ve=(0,$.jsx)(Ye,{className:`bar-item-icon`}),J=q(w(`chat`)),xe=!0,Te=()=>a?.(`chat`);break;case`host:native-cli`:return null;case`host:terminal`:ve=(0,$.jsx)(Ce,{className:`bar-item-icon`}),J=q(w(`terminal`)),be=r===`terminal`,xe=!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),ve=(0,$.jsx)(Er,{className:`bar-item-icon`}),J=q(w(`worktreeViewTitle`)),Y=`chip worktree-entry`,be=r===`worktrees`,xe=!0,we=w(`worktreeEntryTip`,{count:t.size}),ye=(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`:ve=(0,$.jsx)(ke,{className:`bar-item-icon`}),J=q(w(`scmTab`)),be=r===`git`,xe=!0,Te=()=>a?.(`git`);break;case`host:canvas`:ve=(0,$.jsx)(xr,{className:`bar-item-icon`}),J=q(w(`canvasTab`)),be=r===`canvas`,xe=!0,Te=()=>a?.(`canvas`);break;case`host:new-chat`:ve=(0,$.jsx)(C,{className:`bar-item-icon`}),J=q(w(`newChat`)),Y=`chip newchat`,Te=()=>{a?.(`chat`),Z({type:`new_chat`}),sn()};break;case`host:new-ephemeral-chat`:if(j)return null;ve=(0,$.jsx)(wr,{className:`bar-item-icon`}),J=q(w(`newChatEphemeral`)),Y=`chip newchat ephemeral-chat-btn`,Te=()=>{a?.(`chat`),Z({type:`new_chat`,ephemeral:!0}),sn()};break;case`host:new-sandbox`:ve=(0,$.jsx)(Or,{className:`bar-item-icon`}),J=q(w(`newSandbox`)),Y=`chip newchat sandbox-chip`,Te=()=>x?.();break;case`host:history`:if(r&&r!==`chat`)return null;ve=(0,$.jsx)(f,{className:`bar-item-icon`}),J=q(w(`openHistory`)),Y=`panel-toggle`,Te=()=>o?.(`left`);break;case`host:files`:if(r&&r!==`chat`)return null;ve=(0,$.jsx)(Dr,{className:`bar-item-icon`}),J=q(w(`openFiles`)),Y=`panel-toggle has-label`,Te=()=>o?.(`right`);break;case`host:open-project`:ve=(0,$.jsx)(vt,{className:`bar-item-icon`}),J=q(w(`openProject`)),Y=`chip open-project`,be=!!h,Te=()=>d?.();break;case`host:search`:ve=(0,$.jsx)(ft,{className:`bar-item-icon`}),J=q(w(`searchGlobal`)),Y=`chip`,Te=()=>l?.();break;case`host:tasks`:ve=(0,$.jsx)(Nt,{className:`bar-item-icon`}),J=q(w(`bgTasks`)),Y=`chip bg-task-chip`,n.bgServers.length>0&&(ye=(0,$.jsx)(`span`,{className:`bg-task-badge bar-item-badge`,children:n.bgServers.length})),Te=()=>u?.();break;case`host:zen-mode`:ve=(0,$.jsx)(it,{className:`bar-item-icon`}),J=q(w(`zenMode`)),Y=`chip chip-zen`,be=!!y,we=w(`zenModeTip`),Te=()=>b?.();break;case`host:device-center`:ve=(0,$.jsx)(Sr,{className:`bar-item-icon`}),J=q(w(`deviceCenter`)),Y=`chip`,we=w(`deviceCenterTip`),xe=!0,be=r===`devices`,Te=()=>a?.(`devices`);break;case`host:settings`:ve=(0,$.jsx)(ge,{className:`bar-item-icon`}),J=q(w(`settings`)),Y=`chip`,Te=()=>s?.();break;case`host:plugins`:ve=(0,$.jsx)(B,{className:`bar-item-icon`}),J=q(w(`pluginMenuTitle`)),Y=`chip`,Te=e=>{p?p(e.currentTarget):s?.(`plugins`)};break;case`host:github`:ve=(0,$.jsx)(Qe,{className:`bar-item-icon`}),J=q(`GitHub`),Y=`chip github`,Te=()=>window.open(`https://github.com/xing-shuyin/pi-web-ui`,`_blank`,`noreferrer,noopener`);break;case`host:cwd`:ve=(0,$.jsx)(st,{className:`bar-item-icon`}),J=me(z?.cwd?z.cwd.split(/[/\\]/).pop()||z.cwd:w(`openProject`)),Y=`status-item status-cwd`,be=!!h,Te=()=>{ue.current!==null&&(window.clearTimeout(ue.current),ue.current=null),ue.current=window.setTimeout(()=>{d?.(),ue.current=null},220)},Ee=e=>{e.preventDefault(),e.stopPropagation(),ue.current!==null&&(window.clearTimeout(ue.current),ue.current=null),Z({type:`new_chat`}),sn()};break;case`host:plugin-status`:if(n.statuses.length===0)return null;ve=(0,$.jsx)(Ae,{className:`bar-item-icon`}),J=me(n.statuses.map(e=>e.text).join(` · `)),Y=`status-item ext-status`;break;default:if(e.kind===`view`){let t=e.view??``;be=r===t,xe=!0;let o=(i??n.plugins??[]).find(t=>`plugin:${t.id}`===e.source);Y=`plugin-tab${o?.error?` broken`:``}`,o?.error&&(we=`${e.label}: ${o.error}`);let s=e.iconSvg||o?.iconSvg,c=e.icon||o?.icon;ve=s?(0,$.jsx)(Ri,{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;Y=t===`bottom`?`status-item status-action chip`:`chip`,ve=n?(0,$.jsx)(Ri,{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&&(ye=(0,$.jsx)(`span`,{className:`bar-item-badge`,children:e.badge})),Te=()=>g?.(e)}}let De=we??e.hint??J,Oe=[`bar-item`,xe?`tb-tab${be?` active`:``}`:``,Y,be&&!xe?`active`:``].filter(Boolean).join(` `),je=(0,$.jsxs)(`button`,{type:`button`,role:xe?`tab`:void 0,"aria-selected":xe?be:void 0,"aria-haspopup":fe===`host:plugins`?`menu`:void 0,"aria-expanded":fe===`host:plugins`?!!m:void 0,className:Oe,title:De,"data-tip":De,"aria-label":J,onClick:Te,onDoubleClick:Ee,onContextMenu:de,"data-bar-item":fe,children:[ve,!(fe===`host:worktrees`&&t===`top`&&!e.labelExplicit)&&(0,$.jsx)(`span`,{className:`bar-item-text`,children:J}),ye]});return fe===`host:new-chat`?(0,$.jsx)(Rs,{onCreateCli:S,children:je}):je}function Ws(){let{locale:e}=c(),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(()=>typeof window<`u`),[a,o]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{i(!0);let e=Xt();if(!e)return;e.isMaximized().then(n);let t=e.onMaximizedChange(e=>{n(e)});return()=>t()},[]),(0,Q.useEffect)(()=>{let e=window.piDesktop?.browser;if(!e)return;e.getState?.().then(e=>{e&&typeof e==`object`&&`mode`in e&&typeof e.mode==`string`&&o(e.mode)});let t=e.onState?.(e=>{e&&typeof e==`object`&&`mode`in e&&typeof e.mode==`string`&&o(e.mode)});return()=>t?.()},[]),!r||!Zt()||a===`split`||Qt()===`darwin`)return null;let s=Xt();if(!s)return null;let l=X(e);return(0,$.jsxs)(`div`,{className:`window-controls`,"aria-label":`Window controls`,children:[(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void s.minimize(),title:l?`最小化`:`Minimize`,"aria-label":l?`最小化`:`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 s.toggleMaximize(),title:t?l?`向下还原`:`Restore`:l?`最大化`:`Maximize`,"aria-label":t?l?`向下还原`:`Restore`:l?`最大化`:`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 s.close(),title:l?`关闭`:`Close`,"aria-label":l?`关闭`:`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 Gs={name:`@earendil-works/pi-coding-agent`,kind:`pi-core`,current:``,latest:null,upToDate:!1};function Ks({anchorRef:e,open:t,onClose:n,children:r}){let{panelRef:i,style:a,measure:o}=dr({open:t,anchor:e,onClose:n});return(0,Q.useLayoutEffect)(()=>{t&&o()},[t,r,o]),t?(0,cr.createPortal)((0,$.jsx)(`div`,{ref:i,className:`plugin-topbar-menu portal`,role:`menu`,style:a,children:r}),document.body):null}function qs(){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 Js({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:h,themes:g,theme:_,onThemeChange:v,reloadThemes:y,onOpenIconEdit:b,zenMode:x,onToggleZenMode:S,onOpenSandboxModal:w,onCreateCli:T}){let{locale:E,setLocale:D,t:O,packs:k}=c(),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(null),[I,L]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),ee=He(`cwd`),V=He(`workspaceRoots`),te=De(),ne=at().ephemeralChat!==!1&&!te,re=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{re.current!==null&&window.clearTimeout(re.current)},[]);let ie=(0,Q.useRef)(null),H=t=>!e.tabs||t===`chat`||e.tabs.includes(t),ae=[...a??[]].filter(e=>(e.source!==`host`||e.id!==`host:brand`)&&!ca(e)),U=new Set([...i??[],...a??[]].filter(e=>ca(e)&&!e.hidden).map(e=>e.source.slice(7))),oe=new Map((e.settings?.uiLayout?.order??[]).map((e,t)=>[e,t])),se=r.map((e,t)=>({id:e.id,index:t})).sort((e,t)=>(oe.get(`${e.id}:__view`)??1e6+e.index)-(oe.get(`${t.id}:__view`)??1e6+t.index)).map(e=>e.id),ce=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})),W=(H(`plugins`)?r:[]).filter(e=>e.view!==!1&&e.error&&!ce.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:[]})),le=e=>{if(e.source!==`host`)return!1;switch(e.id){case`host:history`:return u(`left`),!0;case`host:files`:return u(`right`),!0;case`host:new-chat`:return l(`chat`),Z({type:`new_chat`}),sn(),!0;case`host:new-ephemeral-chat`:return l(`chat`),Z({type:`new_chat`,ephemeral:!0}),sn(),!0;case`host:new-sandbox`:return w?.(),!0;case`host:open-project`:return N(!0),!0;case`host:search`:return h(),!0;case`host:tasks`:return m(),!0;case`host:zen-mode`:return S?.(),!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 F(ie.current?{rect:ie.current.getBoundingClientRect(),el:ie.current}:null),!0;default:return!1}},G=(t,n,r)=>{t.preventDefault(),t.stopPropagation();let i=e.settings?.uiLayout,a=e=>{let t={...i?.slots,[n]:e},r={...i?.align};(e===`sidebar.left`||e===`sidebar.right`)&&!r[n]&&(r[n]=`center`),Z({type:`set_settings`,uiLayout:{...i,slots:t,...r[n]?{align:r}:{}}})},s=()=>{let e=new Set(i?.hidden??[]);e.add(n);let t=(i?.shown??[]).filter(e=>e!==n);Z({type:`set_settings`,uiLayout:{...i,hidden:[...e],shown:t}})},c=()=>{Z({type:`set_settings`,uiLayout:Aa(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:[]}];aa.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),za({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:K}=Se(),ue=Xe(),de=xt(),[fe,pe]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{fe&&e.status===`open`&&pe(!1)},[fe,e.status]);let[q,me]=(0,Q.useState)(!1),[_e,ve]=(0,Q.useState)(!1),[ye,be]=(0,Q.useState)(!1),xe=Zt(),Y=zo(),[we,Te]=(0,Q.useState)(!1),Ee=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{if(Ee.current.size===0)return;let t=!1;for(let n of Array.from(Ee.current)){let r=e.terminals.find(e=>e.id===n);r&&!r.running&&(Ee.current.delete(n),t=!0)}t&&e.ready&&(Z({type:`check_update`}),Z({type:`check_updates_all`,force:!0}))},[e.terminals,e.ready]);let Oe=()=>{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:Ht();i?(Ee.current.add(i.id),t.restart(i.id),Z({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:r,cols:80,rows:24})):(Ee.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})),be(!1),t.select?.(a),l(`terminal`,{skipAutoCreate:!0})},Ae=(n,r)=>{if(!e.ready||n.length===0)return;let i={name:r,command:Ar(n),cwd:"${pwd}"},a=e.terminals.find(e=>e.title===r),o=a?a.id:Ht();a?(Ee.current.add(a.id),t.restart(a.id),Z({type:`run_command`,terminalId:a.id,conversationId:a.conversationId,command:i,cols:80,rows:24})):(Ee.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})),be(!1),t.select?.(o),l(`terminal`,{skipAutoCreate:!0})},je=e.updatesAll??[],Me=e.updatesSdk,Ne=Me&&Me.newerInstalled?{running:Me.running,installed:Me.newerInstalled}:null,Pe=Me?.bundledInUse===!0,Fe=je.find(e=>e.kind===`pi-core`&&!e.error),Ie=Pe&&(!Fe||!Fe.upToDate),Le=Ie&&!Fe,Re=je.filter(e=>!e.upToDate&&!e.error).length,ze=je.filter(e=>!e.upToDate&&!e.error&&e.kind!==`webui`),Be=e=>e.kind===`git-extension`&&e.source?e.source:e.name,Ve=e=>e.kind===`git-extension`&&e.source&&e.source!==e.name?`${e.source} (${e.name})`:e.name,Ue=e=>{let t=e.replace(/ \([0-9a-f]{7}\)$/,``);return/^[0-9a-f]{7}$/.test(t)?``:t},We=e=>(e.match(/\(([0-9a-f]{7})\)$/)??e.match(/^([0-9a-f]{7})$/))?.[1]??null,Ge=(e,t)=>{if(!t)return Ue(e);let n=Ue(e),r=Ue(t);if(n!==r)return`${n} → ${r}`;let i=We(e),a=We(t);return i&&a&&i!==a?n?`${n} (${i} → ${a})`:`${i} → ${a}`:n},Ke=()=>(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`)}):je.length===0?(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updatesAllUpToDate`)}):(0,$.jsx)(`ul`,{className:`dd-all-list`,children:je.map(e=>{let t=Ne!=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:()=>Ae([e],O(`updatePkgTabTitle`,{name:e.name})),children:O(`updateBtn`)}),(0,$.jsx)(`span`,{className:`dd-all-name`,title:Ve(e),children:Be(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?Ue(e.current):Ge(e.current,e.latest):e.kind===`plugin`?e.upToDate?e.current.startsWith(`v`)?e.current:Ue(e.current):Ge(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:Ne.running})})]})]},`${e.kind}:${e.name}`)})}),Ne&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`piSdkSplitNote`,{running:Ne.running,installed:Ne.installed})}),Ie&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`piSdkBundledNote`,{running:Me.running})}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[Le&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Ae([Gs],O(`installGlobalEngineTabTitle`)),children:O(`installGlobalEngineBtn`)}),ze.length>0&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,style:{flex:1},onClick:()=>Ae(ze,O(`updateAllTabTitle`)),children:O(`updateAllBtn`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,style:ze.length>0?{flex:1}:void 0,onClick:()=>Z({type:`check_updates_all`,force:!0}),children:O(`updatesAllRefresh`)})]})]}),qe=()=>{let t=Ro(e.update?.latest??Y.version),n=(0,$.jsx)(`a`,{className:`dd-refresh dd-more-link`,href:t,target:`_blank`,rel:`noreferrer noopener`,children:O(`updateDesktopManual`)});if(!Y.bridge)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note warn`,children:O(`updateDesktopNoBridge`)}),n]});switch(Y.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:Y.version??e.update?.latest??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>Y.download(),children:O(`updateDesktopDownload`)}),n]});case`downloading`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopDownloading`,{n:Y.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:()=>Y.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:Y.message??``})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>Y.check(),children:O(`updateDesktopCheck`)}),n]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:()=>Y.check(),children:O(`updateDesktopCheck`)}),n]})}},Je=()=>(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&&!xe&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateTerminalHint`)}),e.update&&!e.update.upToDate&&e.update.latest&&xe&&(0,$.jsx)(`div`,{className:`dd-note`,children:O(`updateDesktopNote`)})]}),(0,$.jsxs)(`div`,{className:`dd-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh`,onClick:()=>Z({type:`check_update`}),children:e.update===null?O(`checkingUpdate`):O(`checkUpdate`)}),e.update&&!e.update.upToDate&&e.update.latest&&!xe&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,onClick:Oe,children:O(`updateNow`)}),e.update&&!e.update.upToDate&&e.update.latest&&xe&&qe(),de&&(0,$.jsx)(`button`,{type:`button`,className:`dd-refresh accent`,disabled:fe,title:O(`restartServiceTip`,{name:de.name}),onClick:()=>{fe||(pe(!0),Z({type:`restart_service`}))},children:O(fe?`restartingService`:`restartService`)})]})]}),Ze=qs(),$e={"host:brand":(0,$.jsx)(yr,{}),"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)(Er,{}),(0,$.jsx)(`span`,{children:O(`worktreeViewTitle`)})]}):null,"host:open-project":(0,$.jsxs)(`button`,{type:`button`,className:`chip open-project`,"data-tip":O(`openProject`),onClick:()=>N(!0),children:[(0,$.jsx)(vt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`openProject`)})]}),"host:history":n===`chat`&&H(`history`)?(0,$.jsx)(`button`,{type:`button`,className:`panel-toggle`,"data-tip":O(`openHistory`),"aria-label":O(`openHistory`),onClick:()=>u(`left`),children:(0,$.jsx)(f,{})}):null,"host:files":n===`chat`&&H(`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)(Dr,{}),(0,$.jsx)(`span`,{children:O(`openFiles`)})]}):null,"host:new-chat":H(`new-chat`)?(0,$.jsx)(Rs,{onCreateCli:T,children:(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat`,"data-tip":O(`newChatTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`}),sn()},children:[(0,$.jsx)(C,{}),(0,$.jsx)(`span`,{children:O(`newChat`)})]})}):null,"host:new-ephemeral-chat":ne?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat ephemeral-chat-btn`,"data-tip":O(`newChatEphemeralTip`),onClick:()=>{l(`chat`),Z({type:`new_chat`,ephemeral:!0}),sn()},children:[(0,$.jsx)(wr,{}),(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)(Or,{}),(0,$.jsx)(`span`,{children:O(`newSandbox`)})]}),"host:chat":n!==`chat`&&n!==`native-cli`?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`tb-tab`,"data-tip":O(`chat`),onClick:()=>l(`chat`),children:[(0,$.jsx)(Ye,{}),(0,$.jsx)(`span`,{children:O(`chat`)})]}):null,"host:native-cli":null,"host:terminal":H(`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)(Ce,{}),(0,$.jsx)(`span`,{children:O(`terminal`)})]}):null,"host:git":H(`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)(ke,{}),(0,$.jsx)(`span`,{children:O(`scmTab`)})]}):null,"host:canvas":H(`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)(xr,{}),(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":P!==null,onClick:e=>{let t=e.currentTarget;F(e=>e?.el===t?null:{rect:t.getBoundingClientRect(),el:t})},children:[(0,$.jsx)(B,{"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:h,children:[(0,$.jsx)(ft,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`searchGlobal`)})]}),"host:browser":Zt()||!(e.settings?.disabledAgentTools?.includes(`browser_page`)??!1)?(0,$.jsx)(Hr,{}):null,"host:tasks":(0,$.jsxs)(`button`,{type:`button`,className:`chip bg-task-chip`,"data-tip":O(`bgTasksTip`),onClick:m,children:[(0,$.jsx)(Nt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`bgTasks`)}),e.bgServers.length>0&&(0,$.jsx)(`span`,{className:`bg-task-badge`,children:e.bgServers.length})]}),"host:zen-mode":(0,$.jsxs)(`button`,{type:`button`,className:`chip chip-zen${x?` active`:``}`,"data-tip":O(`zenModeTip`),onClick:S,"aria-label":O(`zenMode`),"aria-pressed":x,children:[(0,$.jsx)(it,{}),(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)(Sr,{}),(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)(ge,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`settings`)})]}),"host:language":(0,$.jsxs)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Tr,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:kt(E)})]}),tip:O(`language`),open:q,onOpenChange:me,caret:!1,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`language`)}),k.map(e=>(0,$.jsx)(Ut,{active:E===e.code,onClick:()=>{D(e.code),me(!1)},children:e.nativeName},e.code)),(0,$.jsxs)(Ut,{onClick:()=>{me(!1),Te(!0)},children:[(0,$.jsx)(he,{}),` `,O(`localeGetMore`)]})]}),"host:theme":(0,$.jsx)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(mt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:O(`theme`)})]}),tip:O(`theme`),open:_e,caret:!1,onOpenChange:e=>{ve(e),e&&g.length===0&&y()},children:(()=>{let e=g.filter(e=>e.group===`classic`),t=g.filter(e=>e.group!==`classic`),n=e=>{let t=X(E)?e.name:e.nameEn??e.name,n=e.scheme===`light`?O(`themeLight`):e.scheme===`dark`?O(`themeDark`):``;return n?X(E)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[e.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`themeGroupClassics`)}),e.map(e=>(0,$.jsx)(Ut,{active:_===e.id,onClick:()=>{v(e.id),ve(!1)},children:n(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:e.length>0?O(`themeGroupBuiltin`):O(`theme`)}),(0,$.jsx)(Ut,{active:_===null,onClick:()=>{v(null),ve(!1)},children:O(`themeDefault`)}),t.map(e=>(0,$.jsx)(Ut,{active:_===e.id,onClick:()=>{v(e.id),ve(!1)},children:n(e)},e.id))]})})()}),"host:update":ue?(0,$.jsxs)(`span`,{className:`chip`,"data-tip":O(`updatesManaged`),children:[(0,$.jsx)(he,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,K??e.update?.current??`…`]})]}):(0,$.jsxs)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(he,{}),(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??``})}),Re>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:O(`updatesAllBadge`,{n:Re})})]}),tip:O(`update`),open:ye,caret:!1,onOpenChange:e=>{be(e),e&&(Z({type:`check_update`}),Z({type:`check_updates_all`}))},fit:!0,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:O(`update`)}),Je(),Ke()]}),"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)(Qe,{})}),"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)(is,{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=hn(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:()=>{re.current!==null&&(window.clearTimeout(re.current),re.current=null),re.current=window.setTimeout(()=>{N(!0),re.current=null},220)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),re.current!==null&&(window.clearTimeout(re.current),re.current=null),Z({type:`new_chat`}),sn()},children:[(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.state?.cwd?.split(/[/\\]/).pop()||e.state?.cwd})]})},et=new Set([`host:search`,`host:tasks`,`host:settings`,`host:plugins`]),tt=new Set([`host:language`,`host:theme`,`host:update`,`host:browser`,`host:engine`]),nt=e=>et.has(e)&&!H(e.slice(5)),rt=e=>{if(e.kind===`view`){if(!H(`plugins`))return null;let t=e.view??``,i=r.find(t=>`plugin:${t.id}`===e.source),a=i?.error?`${e.label}: ${i.error}`:e.hint??e.label;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===t,className:`tb-tab plugin-tab${n===t?` active`:``}${i?.error?` broken`:``}`,"data-tip":a,onClick:()=>l(t),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ri,{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=>G(t,e.id,e.label),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`plugin-topbar-item`,"data-tip":e.hint??e.label,onClick:()=>s?.(e),onContextMenu:t=>G(t,e.id,e.label),children:[(0,$.jsx)(Ri,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)},ot=[];for(let t of ce){if(t.id===`host:native-cli`||t.id===`host:chat`&&(n===`chat`||n===`native-cli`)||!(t.id===`host:browser`&&Zt())&&t.entry?.hidden||nt(t.id)||t.id===`host:worktrees`&&!e.state?.worktree)continue;let i=null;t.entry?i=(0,$.jsx)(Us,{entry:t.entry,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onOpenPanel:u,onOpenSettings:d,onOpenGlobalSearch:h,onOpenBgTasks:m,onOpenProjectPicker:()=>N(!0),isProjectPickerOpen:M,onOpenPluginMenu:e=>F(t=>t?.el===e?null:{rect:e.getBoundingClientRect(),el:e}),isPluginMenuOpen:P!==null,onUiAction:s,uiContextEntries:o,zenMode:x,onToggleZenMode:S,onOpenSandboxModal:w,onCreateCli:T,dropdownProps:{theme:_,themes:g,onThemeChange:v,reloadThemes:y,onLocaleModalOpen:()=>Te(!0),renderUpdateBody:Je,renderAllUpdatesBody:Ke,updatesCount:Re,managed:ue,appVersion:K}},t.id):t.id.startsWith(`host:`)&&$e[t.id]&&(i=$e[t.id]),i&&ot.push({id:t.id,entry:t.entry,node:i})}for(let t of W){let i=(0,$.jsx)(Us,{entry:t,bar:`top`,chat:e,view:n,plugins:r,onViewChange:l,onUiAction:s,uiContextEntries:o},t.id);i&&ot.push({id:t.id,entry:t,node:i})}let ct=e=>e.entry?.align??`start`,[lt,ut]=(0,Q.useState)(()=>new Set),dt=(0,Q.useRef)(null),pt=(0,Q.useRef)(new Map),ht=ot.filter(e=>!lt.has(e.id)),gt=Ze?ht.filter(e=>Na.has(e.id)):[],_t=Ze?ht.filter(e=>!Na.has(e.id)):ht,yt=Ze?ot.filter(e=>!Na.has(e.id)):ot,bt=[...yt.filter(e=>ct(e)===`start`),...yt.filter(e=>ct(e)===`center`),...yt.filter(e=>ct(e)===`end`)],St=bt.filter(e=>!lt.has(e.id)),Ct=(0,Q.useRef)(bt),wt=(0,Q.useRef)(St);(0,Q.useLayoutEffect)(()=>{Ct.current=bt,wt.current=St});let Tt=()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`)),n=wt.current;t.length===n.length&&n.forEach((e,n)=>pt.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=Ct.current,a=Fa(i.map(e=>({id:e.id,width:e.entry?pt.current.get(e.id)??0:0})),e.clientWidth,r,0,new Set([...aa,`host:worktrees`,...Zt()?[`host:browser`]:[]]));ut(e=>e.size===a.size&&[...a].every(t=>e.has(t))?e:a)},Et=`${ht.map(e=>`${e.id}:${e.entry?.label??``}`).join(`|`)}|${n}|${(e.tabs??[]).join(`,`)}|${Ze?`m`:`d`}`;(0,Q.useLayoutEffect)(Tt,[Et]),(0,Q.useEffect)(()=>{let e=dt.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>Tt());return t.observe(e),()=>t.disconnect()},[Et]);let Dt=_t.filter(e=>ct(e)===`start`),Ot=_t.filter(e=>ct(e)===`center`),At=_t.filter(e=>ct(e)===`end`),jt=ot.filter(e=>lt.has(e.id)&&e.entry).map(e=>e.entry),Mt=new Map;[...i??[],...a??[]].forEach((e,t)=>{Mt.has(e.id)||Mt.set(e.id,t)});let Pt=Pa([...ae,...jt],e=>Mt.get(e)??999999),Ft=e=>e.icon&&!/[a-z]/i.test(e.icon)?e.icon:null,It=e.settings?.uiLayout?.topbarText===!1;return(0,$.jsxs)(`header`,{className:`topbar${It?` no-labels`:``}`,"data-pi-anchor":`topbar`,children:[(0,$.jsxs)(`div`,{className:`topbar-flow`,ref:dt,role:`toolbar`,"aria-label":O(`viewSwitch`),children:[Dt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(Ot.length>0||At.length>0)&&(0,$.jsx)(`span`,{className:`tb-spacer${Ot.length===0&&At.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Ot.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),Ot.length>0&&(0,$.jsx)(`span`,{className:`tb-spacer${At.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),At.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id))]}),(Pt.length>0||ot.length>0)&&(0,$.jsxs)(`div`,{className:`plugin-topbar-more`,children:[(0,$.jsx)(`button`,{ref:ie,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)(br,{})}),(0,$.jsxs)(Ks,{anchorRef:ie,open:A,onClose:()=>j(!1),children:[Pt.map(e=>{let t=e.source===`host`&&tt.has(e.id)?$e[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)(Qe,{}),(0,$.jsx)(`span`,{children:`GitHub`})]},e.id);if(e.source===`host`){let t=$e[e.id];if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>j(!1),children:t},e.id)}else{let t=rt(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:[Ft(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Ft(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),le(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),le(e)||s?.(e)},children:[Ft(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:Ft(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label})]},e.id)}),(0,$.jsx)(`div`,{className:`tb-menu-divider`,"aria-hidden":`true`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,onClick:()=>{j(!1),b()},children:[(0,$.jsx)(J,{}),(0,$.jsx)(`span`,{className:`tb-row-text`,children:O(`uiIconEdit`)})]})]})]}),gt.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(0,$.jsx)(Ws,{}),we&&(0,$.jsx)(jo,{onClose:()=>Te(!1)}),P&&(0,$.jsx)(mo,{anchorRect:P.rect,anchorEl:P.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:U,orderedPluginIds:se,onTogglePin:(t,n)=>Z({type:`set_settings`,uiLayout:la(e.settings?.uiLayout,t,n)}),onReorder:t=>Z({type:`set_settings`,uiLayout:ua(e.settings?.uiLayout,t)}),onOpenView:e=>{F(null),l(`plugin:${e}`)},onOpenPluginSettings:e=>{z(e??null),L(!0)},onManagePlugins:p,onClose:()=>F(null)}),I&&(0,$.jsx)(Ao,{open:I,onClose:()=>{L(!1),z(null)},focusPluginId:R,plugins:e.plugins??[],disabledPlugins:e.settings?.disabledPlugins??[],models:e.settings?.subagentModels??[],onTogglePlugin:t=>{let n=new Set(e.settings?.disabledPlugins??[]);n.has(t.id)?n.delete(t.id):n.add(t.id),Z({type:`set_settings`,disabledPlugins:[...n]})},onOpenView:e=>{L(!1),l(`plugin:${e}`)},onOpenMarketplace:()=>{L(!1),p()}}),M&&(0,$.jsx)(uo,{open:!0,currentCwd:ee,pathCompletions:e.pathCompletions??[],workspaceRoots:V,onClose:()=>N(!1),onSelectDirectory:e=>Z({type:`set_cwd`,path:e}),onCreateProject:e=>Z({type:`make_dir`,path:e,setAsCwd:!0})})]})}function Ys(){let e=(0,Q.useSyncExternalStore)(mr,hr);return e?(0,$.jsx)(Xs,{access:e},e.url):null}function Xs({access:e}){let{zh:t}=e,n=(0,Q.useRef)(null),[r,i]=(0,Q.useState)(e.transport);(0,Q.useEffect)(()=>{let e=e=>{e.source===n.current?.contentWindow&&e.origin===`null`&&e.data?.type===`device-access-transport`&&(e.data.transport===`lan`||e.data.transport===`hub`)&&i(e.data.transport)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[]);let[a,o]=(0,Q.useState)({x:24,y:64,width:Math.min(960,window.innerWidth-32),height:Math.min(640,window.innerHeight-88)}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{let e=()=>o(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 h(e,t){if(l||e.button!==0||e.target.closest(`button`))return;e.preventDefault();let n=e.currentTarget;n.setPointerCapture(e.pointerId);let r={...a,px:e.clientX,py:e.clientY},i=e=>{let n=e.clientX-r.px,i=e.clientY-r.py;o(t?{...a,width:Math.max(Math.min(320,window.innerWidth),Math.min(window.innerWidth-a.x,r.width+n)),height:Math.max(Math.min(200,window.innerHeight),Math.min(window.innerHeight-a.y,r.height+i))}:{...a,x:Math.max(0,Math.min(window.innerWidth-Math.min(a.width,240),r.x+n)),y:Math.max(0,Math.min(window.innerHeight-40,r.y+i))})},s=()=>{n.removeEventListener(`pointermove`,i),n.removeEventListener(`lostpointercapture`,s)};n.addEventListener(`pointermove`,i),n.addEventListener(`lostpointercapture`,s)}async function g(){f(!0),m(``);try{await _r(e.id,e.hubUrl,!0,t,!0),gr(e)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}let _=t?`远程桌面`:`Remote desktop`,v=!!window.piDesktop?.openHub;return(0,cr.createPortal)((0,$.jsxs)(`div`,{className:`remote-desktop-window${l?` is-fullscreen`:``}${s?` is-minimized`:``}`,role:`dialog`,"aria-label":_,style:l?void 0:{left:a.x,top:a.y,width:s?Math.min(420,a.width):a.width,height:s?`auto`:a.height},children:[(0,$.jsxs)(`div`,{className:`remote-desktop-titlebar`,onPointerDown:e=>h(e,!1),children:[(0,$.jsxs)(`strong`,{children:[_,` · `,e.id,r===`lan`?t?` · 局域网`:` · LAN`:``]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:d,onClick:()=>void g(),children:v?t?`独立窗口`:`Separate window`:t?`独立标签页`:`Separate tab`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":s?t?`还原`:`Restore`:t?`最小化`:`Minimize`,onClick:()=>{c(!s),u(!1)},children:s?`▢`:`−`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":l?t?`退出全屏`:`Exit fullscreen`:t?`全屏`:`Fullscreen`,onClick:()=>{u(!l),c(!1)},children:l?`⤡`:`⤢`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":t?`关闭`:`Close`,onClick:()=>gr(e),children:`×`})]}),p&&(0,$.jsx)(`div`,{role:`alert`,className:`remote-desktop-error`,children:p}),(0,$.jsx)(`iframe`,{ref:n,title:_,src:e.url,sandbox:`allow-scripts allow-forms allow-pointer-lock`,allow:`fullscreen`,allowFullScreen:!0,hidden:s}),!l&&!s&&(0,$.jsx)(`div`,{className:`remote-desktop-resize`,onPointerDown:e=>h(e,!0),"aria-hidden":`true`})]}),document.body)}var Zs=`pi-web-ui:project-click-switch`,Qs=new Set;function $s(){for(let e of Qs)e()}function ec(e){return Qs.add(e),()=>{Qs.delete(e)}}function tc(){try{let e=localStorage.getItem(Zs);return e===null||e!==`0`}catch{return!0}}var nc=null;function rc(){return nc===null&&(nc=tc()),nc}function ic(e){try{localStorage.setItem(Zs,e?`1`:`0`)}catch{}nc=e,$s()}function ac(){return(0,Q.useSyncExternalStore)(ec,rc)}function oc(){return rc()}var sc=`pi-web-ui:project-order-manual`,cc=`pi-web-ui:lp-project-order`,lc=400,uc=new Set;function dc(){for(let e of uc)e()}function fc(e){return uc.add(e),()=>{uc.delete(e)}}function pc(){try{let e=localStorage.getItem(cc);if(e){let t=JSON.parse(e),n=Array.isArray(t.order)?t.order.filter(e=>typeof e==`string`&&e.length>0):[],r={},i=t.firstSeen;if(i&&typeof i==`object`)for(let[e,t]of Object.entries(i))typeof t==`number`&&Number.isFinite(t)&&t>0&&(r[e]=t);return{order:n,firstSeen:r}}}catch{}return{order:[],firstSeen:{}}}function mc(e){try{localStorage.setItem(cc,JSON.stringify(e))}catch{}}function hc(){return(0,Q.useSyncExternalStore)(fc,gc)}function gc(){try{return localStorage.getItem(sc)===`1`}catch{return!1}}function _c(e){try{localStorage.setItem(sc,e?`1`:`0`)}catch{}dc()}function vc(){return pc().order}function yc(e){let t=pc();t.order.length===e.length&&t.order.every((t,n)=>t===e[n])||mc({...t,firstSeen:t.firstSeen,order:[...e]})}function bc(e){let t=pc(),n=new Map(Object.entries(t.firstSeen)),r=Date.now(),i=!1;for(let t of e)n.has(t)||(n.set(t,r),i=!0);if(!i)return n;let a=[...n.entries()].sort((e,t)=>t[1]-e[1]).slice(0,lc);return mc({...t,firstSeen:Object.fromEntries(a)}),new Map(a)}function xc(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 Sc(e){return`@${e.name}(${e.id})`}function Cc(e){return e.replace(/@([^\s()]+)\([a-f0-9-]{8,}\)/g,`@$1`)}function wc(e,t){let n=Cc(e),r=n.match(/^@([^\s()]+)\s*(.*)$/);return r?{botPrefix:`@${r[1]}`,summary:r[2].trim()||n}:{botPrefix:t?`@${t}`:``,summary:n}}function Tc(e,t=!0){if(!e.includes(`Device task failed`))return Cc(e);let n=e.match(/Device task failed\s*\[phase=([^;]+);\s*category=([^\]]+)\]\.\s*(.*)/s);if(!n)return Cc(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(`
|
|
6
|
+
`):[`> ⚠️ **Task Interrupted · ${o}**`,`>`,`> **Phase**: \`${r}\` · **Category**: \`${i}\``,`>`,`> ${s||`Remote agent execution failed; task session is safely retained on target device.`}`].join(`
|
|
7
|
+
`)}function Ec(e,t){return[...new Set(t.filter(t=>e.includes(Sc(t))).map(e=>e.id))]}function Dc(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:`排队中`,waiting:`等待依赖`,running:`运行中`,completed:`已完成`,failed:`失败`,interrupted:`已中断`}:{queued:`Queued`,waiting:`Waiting`,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?Tc(d,r):Cc(d),p=e.replyToMessageId?t?.messages.find(t=>t.id===e.replyToMessageId):void 0;if(p){let e=Cc(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),d=!!(e.parentTaskId||e.sourceBotId&&e.sourceBotId!==e.botId),f=r?`协同子代理`:`Worker Subagent`,p=u(e.botId,n?.name??e.botId,e.deviceId),m=e.status===`waiting`?e.dependsOnTaskId?r?`等待前序任务`:`Waiting for upstream`:r?`等待依赖`:`Waiting`:s[e.status]??e.status;i.set(t,d?`${p} [${f}] · ${m}`:`${p} · ${m}`);let h=e.report,g=Cc(e.text),_;if(h){if(d){let t=r?`📋 展开查看工作内容与交付详情`:`📋 View Detailed Delivery & Evidence`;_=[`🤖 **${r?`协同子代理交付完成`:`Worker Subagent Completed`}** · \`@${n?.name??e.botId}\``,`🎯 **${r?`分配指令`:`Instruction`}**:${g}`,``,`<details>`,`<summary>${t}</summary>`,``,Tc(h,r),``,`</details>`].join(`
|
|
8
|
+
`)}else _=Tc(h,r)}else if(e.status===`running`){let t=d?r?`协同子代理执行中`:`Worker Subagent Running`:r?`任务执行中`:`Task Running`,i=e.progress?.phase,a=e.progress?.toolName,o=e.progress?.text?.trim();_=[`⏳ **${t}**${d?` · \`@${n?.name??e.botId}\``:``}`,`🎯 **${r?d?`分配指令`:`目标指令`:`Instruction`}**:${g}`,...i?[`⚙️ **${r?`执行阶段`:`Phase`}**:\`${i}\`${a?` · \`${a}\``:``}`]:[],...o?[``,`> ${o}`]:[]].join(`
|
|
9
|
+
`)}else if(e.status===`waiting`){let t=e.dependsOnTaskId?c.get(e.dependsOnTaskId):void 0,i=t?o.get(t.botId)?.name??t.botId:void 0,a=t?wc(t.text,i).summary:e.dependsOnTaskId;_=[`⏳ **${r?`⏳ 等待前序任务交付中`:`⏳ Waiting for upstream task delivery`}**${d?` · \`@${n?.name??e.botId}\``:``}`,`🎯 **${r?d?`分配指令`:`目标指令`:`Instruction`}**:${g}`,...e.dependsOnTaskId?[`🔗 **${r?`依赖任务`:`Depends on`}**:${i?`@${i} · `:``}${a||e.dependsOnTaskId}`]:[]].join(`
|
|
10
|
+
`)}else _=e.status===`queued`?[`⏱️ **${d?r?`协同子代理排队等待调度`:`Worker Subagent Queued`:r?`任务排队等待调度`:`Task Queued`}**${d?` · \`@${n?.name??e.botId}\``:``}`,`🎯 **${r?d?`分配指令`:`目标指令`:`Instruction`}**:${g}`].join(`
|
|
11
|
+
`):e.status===`failed`&&d?[`❌ **${r?`协同子代理执行失败`:`Worker Subagent Failed`}** · \`@${n?.name??e.botId}\``,`🎯 **${r?`分配指令`:`Instruction`}**:${g}`,...h?[``,Tc(h,r)]:[]].join(`
|
|
12
|
+
`):`${s[e.status]||e.status}\n\n${g}`;a.push({id:t,role:`assistant`,timestamp:e.createdAt,content:[{type:`text`,text:_}]})}return a.sort((e,t)=>(e.timestamp??0)-(t.timestamp??0)),{state:{clientId:`device-group`,cwd:``,sessionId:`device-group:${e}`,conversationId:`device-group:${e}`,rev:0,messages:a,streamingMessage:null,isStreaming:!1,model:null,thinkingLevel:``,availableThinkingLevels:[],queue:{steering:[],followUp:[]},tools:[],version:0,piConfigured:!0,piAgentInstalled:!0,stats:{totalMessages:a.length,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,contextUsage:{tokens:null,contextWindow:0,percent:null}}},labels:i}}function Oc(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 kc(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 Ac(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 jc(e,t){let n=e;for(let e of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e.start)+Sc(e.member)+n.slice(e.end);return{text:n,targets:[...new Set(t.map(e=>e.member.id))]}}function Mc(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 Nc=new Map,Pc=new Map;function Fc(e,t){let n=Pc.get(e);if(n)n(t);else{let n=Nc.get(e)??[];n.some(e=>e.id===t.id)||n.push(t),Nc.set(e,n)}window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{roomId:e}}))}function Ic(e,t){Pc.set(e,t);let n=Nc.get(e)??[];Nc.delete(e);for(let e of n)t(e);return()=>{Pc.get(e)===t&&Pc.delete(e)}}function Lc(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 Rc({botIds:e,roomId:n}){let{locale:r}=c(),i=X(r),[a,s]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),[d,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(o(g(`/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||(s({hubUrl:r.hubUrl,deviceId:r.deviceId,bots:a.bots}),u(``))}catch(t){e||u(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&&!d){f(!0);try{await _r(e.deviceId,a.hubUrl,t,i),u(``)}catch(e){u(e instanceof Error?e.message:String(e))}finally{f(!1)}}}return(0,$.jsxs)(`div`,{className:`dg-side-members`,children:[l&&(0,$.jsx)(`div`,{className:`dg-side-error`,role:`alert`,children:l}),!a&&!l&&(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:()=>Fc(n,r),children:(0,$.jsx)(Tt,{"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:d||!r?.deviceId,onClick:()=>r&&void p(r,!0),children:(0,$.jsx)(re,{"aria-hidden":!0})}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:i?`访问设备`:`Open device`,"aria-label":i?`访问设备`:`Open device`,disabled:d||!r?.deviceId,onClick:()=>r&&void p(r,!1),children:(0,$.jsx)(t,{"aria-hidden":!0})})]})]})},e)})]})}function zc(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 Bc({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)(st,{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)(L,{})})]}),(0,$.jsx)(In,{className:`universal-path-browse-btn`,tip:C(`projectPickerTitle`),disabled:f,onClick:E,children:(0,$.jsx)(vt,{})}),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)(Pt,{}),` 最近项目`]}),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)(uo,{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 Vc=`pi-web-model-usage`;function Hc(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 Uc(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function Wc(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 Gc(){try{let e=localStorage.getItem(Vc);return e?Hc(JSON.parse(e)):{}}catch{return{}}}function Kc(e){try{localStorage.setItem(Vc,JSON.stringify(e))}catch{}}function qc(e){let t=Uc(Gc(),e);return Kc(t),t}function Jc(e,t){return t?t===e.id||`${e.provider}/${e.id}`===t||t.includes(`/`)&&t.split(`/`)[1]===e.id:!1}function Yc(e,t){return(e?t?.find(t=>t.id===e)?.name?.trim():``)||e}function Xc(e,t,n,r){let i=e?.trim();if(!i)return null;let a=i.indexOf(`/`),o=a>0?i.slice(0,a):``,s=a>0?i.slice(a+1):i,c=e=>e.includes(`/`)?e.slice(e.indexOf(`/`)+1):e,l=t.find(e=>e.id===i)??t.find(e=>`${e.provider}/${c(e.id)}`===i)??t.find(e=>e.provider===o&&c(e.id)===s)??null,u=l?.provider||o,d=u?r?.[u]:void 0;return{modelName:l?.name||s,modelId:l?c(l.id):s,provider:u,providerLabel:Yc(u,n),keyName:d&&d.length>1?d.find(e=>e.active)?.name??null:null}}function Zc({models:e,modelsLoading:t=!1,providerKeys:n={},providers:r,defaultModel:i,currentModelId:a,active:o,onEnsureModels:s,loading:c=!1,onRefresh:l,onManageModels:u,onPickModel:d,onToggleDefault:f,isRowActive:p,extraTopRow:m,listRef:h,autoFocusSearch:g=!1,hideTitle:_=!1,bodyStyle:v,scrollStyle:y}){let b=W(),[x,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)({}),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(s);k.current=s;let A=(0,Q.useRef)(null),j=(0,Q.useCallback)(e=>{A.current=e,h&&(h.current=e)},[h]),M=(0,Q.useMemo)(()=>Xc(a,e,r,n),[a,e,r,n]),N=()=>{S(``),w(null),requestAnimationFrame(()=>{let e=A.current?.querySelector(`.dd-item.active`);e&&typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`})})};(0,Q.useEffect)(()=>{if(!o){S(``),w(null),O(!1);return}E(Gc()),k.current()},[o]);let P=(0,Q.useMemo)(()=>e.filter(e=>e.enabled!==!1).length,[e]),F=e.some(e=>e.enabled===!1),I=(0,Q.useMemo)(()=>!F||D?e:e.filter(e=>e.enabled!==!1||Jc(e,a)),[e,F,D,a]),L=(0,Q.useMemo)(()=>{let e=x.trim().toLowerCase(),t=I;return C&&(t=t.filter(e=>e.provider===C.provider)),Wc(e?t.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):t,T)},[I,x,C,T]),R=(0,Q.useMemo)(()=>{let e=new Map;for(let t of I)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},[I,n]),z=(0,Q.useMemo)(()=>{let e=[];for(let t of L){let r=null,i=n[t.provider];if(i&&i.length>1&&(r=i.find(e=>e.active)??i[0],C?.provider===t.provider&&C.keyName)){let e=i.find(e=>e.name===C.keyName);e&&(r=e)}let o=p?p(t,r):Jc(t,a)&&(!r||r.active);e.push({model:t,key:r,active:o})}return e},[L,n,C,p,a]);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,children:[!_&&(0,$.jsx)(`span`,{className:`dd-header-title`,children:b(`availableModels`)}),(0,$.jsxs)(`div`,{className:`dd-header-actions`,style:_?{marginLeft:`auto`}:void 0,children:[!!i&&(0,$.jsxs)(`div`,{className:`dd-header-default`,title:`默认模型: ${i}`,children:[(0,$.jsx)(`span`,{className:`dd-header-default-star`,children:`★`}),(0,$.jsx)(`span`,{className:`dd-header-default-name`,children:i.includes(`/`)?i.split(`/`).slice(1).join(`/`):i}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-default-clear`,title:`清除全局默认模型`,onClick:e=>{e.stopPropagation(),Z({type:`clear_default_model`})},children:`✕`})]}),F&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-toggle ${D?`active`:``}`,onClick:()=>O(e=>!e),title:D?b(`showEnabledModelsTitle`,{n:P}):b(`showAllModelsTitle`,{n:e.length}),children:D?b(`showEnabledModels`,{n:P}):b(`showAllModels`,{n:e.length})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-refresh-btn`,onClick:l,title:b(`refreshModels`),"aria-label":b(`refreshModels`),children:(0,$.jsx)(ue,{className:c||t?`spin`:``})}),u&&(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-manage-btn`,onClick:u,title:b(`manageModels`),"aria-label":b(`manageModels`),children:(0,$.jsx)(ge,{})})]})]}),(0,$.jsxs)(`div`,{className:`dd-search-row`,children:[(0,$.jsx)(ft,{}),(0,$.jsx)(`input`,{className:`dd-search`,type:`text`,autoFocus:g,placeholder:b(`searchModels`),value:x,onChange:e=>S(e.target.value)})]}),M&&(0,$.jsxs)(`button`,{type:`button`,className:`dd-current-row`,title:b(`currentModelHint`),onClick:N,children:[(0,$.jsx)(`span`,{className:`dd-current-tag`,children:b(`currentModelLabel`)}),(0,$.jsx)(`span`,{className:`dd-current-name`,children:M.modelName}),(0,$.jsx)(`span`,{className:`dd-current-provider`,title:M.provider,children:M.providerLabel}),M.keyName&&(0,$.jsx)(`span`,{className:`dd-current-key`,children:M.keyName})]}),(0,$.jsxs)(`div`,{className:`dd-model-body`,style:v,children:[R.length>1&&(0,$.jsxs)(`div`,{className:`dd-provider-col`,children:[(0,$.jsx)(`div`,{className:`dd-provider-head`,children:b(`providers`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-provider-item ${C===null?`active`:``}`,onClick:()=>w(null),children:(0,$.jsx)(`span`,{children:b(`allProviders`)})}),R.map(e=>{let t=C?.provider===e.provider&&C?.keyName===e.keyName;return(0,$.jsxs)(`button`,{type:`button`,className:`dd-provider-item ${t?`active`:``}`,onClick:()=>w(t?null:{provider:e.provider,keyName:e.keyName}),title:e.keyName?`${Yc(e.provider,r)} (${e.provider}) · ${e.keyName}`:`${Yc(e.provider,r)} (${e.provider}) · ${e.count}`,children:[(0,$.jsxs)(`span`,{className:`dd-provider-txt`,children:[(0,$.jsx)(`span`,{className:`dd-provider-name`,children:Yc(e.provider,r)}),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:j,style:y,children:[(c||t)&&(0,$.jsx)(`div`,{className:`dd-loading`,children:b(`loading`)}),e.length===0&&!c&&!t&&(0,$.jsx)(`div`,{className:`dd-loading`,children:b(`noModels`)}),m,L.length===0&&I.length>0&&(0,$.jsxs)(`div`,{className:`dd-loading`,children:[(0,$.jsx)(`div`,{children:b(`noModelMatches`)}),F&&!D&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-switch-link`,onClick:()=>O(!0),children:b(`searchAllModelsHint`,{n:e.length})})]}),z.map(e=>{let t=e.model,n=i!==void 0&&i===t.id;return(0,$.jsxs)(Ut,{active:e.active,onClick:()=>d(t,e.key),children:[(0,$.jsxs)(`span`,{className:`dd-model-cell`,children:[(0,$.jsxs)(`span`,{className:`dd-model-head`,children:[(0,$.jsx)(`span`,{className:`dd-model-name`,children:t.name}),e.active&&(0,$.jsx)(`span`,{className:`dd-model-current`,children:b(`currentModelBadge`)})]}),(0,$.jsxs)(`span`,{className:`dd-model-meta`,children:[(0,$.jsx)(`span`,{className:`dd-model-provider`,title:t.provider,children:Yc(t.provider,r)}),(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]}),(T[t.id]??0)>0&&(0,$.jsx)(`span`,{className:`dd-model-usage`,children:b(`modelUsedCount`,{n:T[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:b(`reasoning`)}),t.vision&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:b(`vision`)}),D&&t.enabled===!1&&(0,$.jsx)(`span`,{className:`dd-model-badge out-of-scope`,children:b(`notInScopeBadge`)})]})]})]}),i!==void 0&&(f?(0,$.jsx)(`button`,{type:`button`,className:`dd-star-btn ${n?`active`:``}`,title:n?`当前全局默认模型(点击取消默认)`:`设为全局默认模型`,onClick:e=>{e.stopPropagation(),f(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 Qc({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 $c=e=>e.id.startsWith(`${e.provider}/`)?e.id.slice(e.provider.length+1):e.id,el=()=>({name:``,description:``,systemPrompt:``,cwd:``,tools:[],skills:[],mcpServers:[],enabled:!0});async function tl(e,t,n){let r=await fetch(o(g(`/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 nl({pathCompletions:e=[],createOnly:t=!1,onCreated:n,onCancel:r}){let i=W(),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(()=>t?el():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 tl(`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),tl(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]),Vt(()=>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 tl(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&&$c(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(el()),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)(Bc,{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:zc(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)(Qc,{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,cr.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)(Zc,{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:$c(e)}}),T(!1)},isRowActive:e=>e.provider===s.model?.provider&&$c(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 rl({room:e,onClose:t}){let{locale:n}=c(),r=X(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()};Vt(S),(0,Q.useEffect)(()=>()=>x.current?.abort(),[]),(0,Q.useEffect)(()=>{let t=new AbortController;return m(!0),Promise.all([sl(`bots`,t.signal),sl(`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 sl(i,r.signal);if(r.signal.aborted||(await sl(`${i}/members`,r.signal,{botIds:[...new Set([...a.room.botIds,...n])]}),r.signal.aborted))return;window.dispatchEvent(new CustomEvent(il)),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,cr.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)(nl,{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 il=`pi-web-ui:device-groups-changed`,al={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`}},ol=class extends Error{status;code;constructor(e,t){super(`Device group request failed (${e})`),this.status=e,this.code=t}};async function sl(e,t,n){let r=await fetch(o(g(`/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 ol(r.status,typeof i?.code==`string`?i.code:``);return i}function cl(e){return e instanceof ol?[`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 ll(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 ul(e){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:e}))}function dl({active:e=!0,entry:t,selectedRoomId:n,flex:r,onCollapsedChange:i,hideHeader:a=!1,onRoomCountChange:o}){let{locale:s}=c(),l=al[X(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,S]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(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=ll(async e=>{let n=await sl(`chat-status`,e);if(t=!!(n.hubUrl&&n.deviceId),!t)return[];let r=await sl(`rooms`,e);if(!Array.isArray(r.rooms))throw Error(`Invalid rooms response`);return r.rooms},e=>{b(t),v(e),o?.(e.length),E(null),S(!1)},e=>{E(cl(e)),S(!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(il,r),document.addEventListener(`visibilitychange`,i),()=>{n.stop(),N.current=null,window.clearInterval(a),window.removeEventListener(il,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),E(null);try{if(await sl(`rooms/${encodeURIComponent(e.id)}/${t}`,n.signal,t===`rename`?{name:k.trim()}:{}),!F.current||n.signal.aborted)return;O(null),window.dispatchEvent(new CustomEvent(il))}catch(e){F.current&&!n.signal.aborted&&E(cl(e))}finally{P.current=null,F.current&&M(!1)}},R=(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:[]}));za({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`?(O(t.id),A(t.name)):e.action===`members`?ul({roomId:t.id,manage:!0}):(e.action===`clear`||e.action===`delete`)&&I(t,e.action))}})};if(y===!1||y===null&&x)return null;let z=(0,$.jsxs)(`div`,{className:`lp-section-body dg-side-body`,children:[T&&(0,$.jsxs)(`div`,{className:`dg-side-error`,role:`status`,children:[l[T],T===`bind`?(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>ul({}),children:l.settings}):(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>N.current?.refresh(),children:l.retry})]}),!T&&_.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} · ${X(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)(w,{}):(0,$.jsx)(L,{})}),(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:()=>ul({roomId:e.id}),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),ul({roomId:e.id}))},onContextMenu:t=>R(t,e),children:[(0,$.jsx)(lt,{}),(0,$.jsx)(`span`,{className:`dg-side-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-label":`${e.name} · ${X(s)?`添加 Bot`:`Add Bot`}`,title:X(s)?`添加或新建 Bot`:`Add or create Bot`,onClick:()=>m(e),children:(0,$.jsx)(C,{})})]}),h.has(e.id)&&(0,$.jsx)(Rc,{botIds:e.botIds,roomId:e.id}),D===e.id&&(0,$.jsxs)(`form`,{className:`dg-side-rename`,onSubmit:t=>{t.preventDefault(),k.trim()&&I(e,`rename`)},children:[(0,$.jsx)(`input`,{className:`dc-input`,"aria-label":l.name,value:k,maxLength:120,autoFocus:!0,disabled:j,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&O(null)}}),(0,$.jsx)(`button`,{type:`submit`,className:`dc-button`,disabled:j||!k.trim(),children:l.save}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:j,onClick:()=>O(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:[z,p&&(0,$.jsx)(rl,{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&&So(t),` `,u,` (`,_.length,`)`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:d?(0,$.jsx)(L,{}):(0,$.jsx)(w,{})})]}),(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:()=>ul({create:!0}),children:(0,$.jsx)(C,{})})})]}),!d&&z,p&&(0,$.jsx)(rl,{room:p,onClose:()=>m(null)})]})}var fl=`pi.unread_conversations`,pl=6048e5;function ml(){if(typeof window>`u`||!window.sessionStorage)return[];try{let e=window.sessionStorage.getItem(fl);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)<pl)}catch{return[]}}function hl(e){if(typeof window<`u`&&window.sessionStorage)try{let t=Array.from(e);t.length===0?window.sessionStorage.removeItem(fl):window.sessionStorage.setItem(fl,JSON.stringify(t))}catch{}}var gl=new class{entries=new Map;keyToPrimaryId=new Map;cachedKeySet=new Set;listeners=new Set;constructor(){let e=ml();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(),hl(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 _l(e){gl.markUnread(e)}function vl(e){gl.clearUnread(e)}function yl(){return(0,Q.useSyncExternalStore)(gl.subscribe,gl.getSnapshot,gl.getSnapshot)}function bl(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 xl(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 Sl(e,t,n){let r=new Map(e.map(e=>[e.id,e])),i=new Map,a=e=>{let t=[],n=new Map,a=e,o;for(;;){let e=i.get(a.id);if(e!==void 0){o=e;break}let s=n.get(a.id);if(s!==void 0){o=t.slice(s).reduce((e,t)=>e.id<t.id?e:t).cwd;break}n.set(a.id,t.length),t.push(a);let c=a.parentId?r.get(a.parentId):void 0;if(!c){o=a.cwd;break}a=c}for(let e of t)i.set(e.id,o);return o},o=e.find(e=>e.id===n),s=o?a(o):t,c=new Map;for(let t of e){let e=a(t),n=c.get(e)??[];n.push(t),c.set(e,n)}let l=[...c.entries()].map(([e,t])=>({cwd:e,isCurrent:e===s,convs:t}));return l.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:e.cwd<t.cwd?-1:+(e.cwd>t.cwd)),l}function Cl(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}var wl=e=>e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),Tl=(e=`pi`,t)=>JSON.stringify([e,wl(t)]),El=new class{positions=new Map;initialized=new Set;bottom=new Map;nextKey=0;version=0;listeners=new Set;submittedEvents=new Set;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.version;aliases(e,t){return[t.sessionId?`session:${wl(t.sessionId)}`:``,t.sessionFile||t.path?`file:${wl(t.sessionFile||t.path)}`:``,t.id?`conversation:${t.id}`:``].filter(Boolean).map(t=>`${e}:${t}`)}remember(e,t){let n=this.aliases(e,t),r=n.flatMap(e=>this.positions.get(e)??[]),i=t.sessionId?wl(t.sessionId):r.find(e=>e.sessionId)?.sessionId,a=[...new Set(r.filter(e=>!i||!e.sessionId||e.sessionId===i))].sort((e,t)=>e.key-t.key),o=this.initialized.has(e)?(this.bottom.get(e)??0)-1:t.modified??Date.now(),s=a[0]??{key:this.nextKey++,modified:o,promoted:0};i&&(s.sessionId=i),!this.initialized.has(e)&&t.modified!=null&&(s.modified=t.modified),this.bottom.set(e,Math.min(this.bottom.get(e)??s.modified,s.modified));for(let e of a.slice(1)){s.promoted=Math.max(s.promoted,e.promoted);for(let[t,n]of this.positions)n===e&&this.positions.set(t,s),n.parent===e&&(n.parent=s)}for(let e of n)this.positions.set(e,s);return t.parentId?s.parent=this.positions.get(`${e}:conversation:${t.parentId}`):t.id&&delete s.parent,this.promoteAncestors(s),s}promoteAncestors(e){let t=new Set;for(let n=e.parent;n&&!t.has(n);n=n.parent)t.add(n),n.promoted=Math.max(n.promoted,e.promoted)}observe(e,t,n=!0){for(let n of t)this.remember(e,n);n&&t.length>0&&this.initialized.add(e)}sort(e,t,n,r=!0){let i=t.map(e=>({item:e,target:n(e)}));this.observe(e,i.map(e=>e.target),r);let a=i.map(({item:t,target:n})=>({item:t,position:this.remember(e,n)}));return a.sort((e,t)=>t.position.promoted-e.position.promoted||t.position.modified-e.position.modified||e.position.key-t.position.key),a.map(({item:e})=>e)}key(e,t){return this.remember(e,t).key}promote(e,t,n){let r=this.remember(e,t);if(n){let r=JSON.stringify([e,t.sessionId||t.id,n]);if(this.submittedEvents.has(r))return;this.submittedEvents.add(r),this.submittedEvents.size>512&&this.submittedEvents.delete(this.submittedEvents.values().next().value)}r.promoted=++this.version,this.promoteAncestors(r);for(let e of this.listeners)e()}clear(){this.positions.clear(),this.initialized.clear(),this.bottom.clear(),this.submittedEvents.clear(),this.nextKey=0,this.version++;for(let e of this.listeners)e()}};function Dl(e,t,n){let r=new Map(t.map(e=>[e.id,e])),i=r.get(e.conversationId),a={...i,id:e.conversationId,sessionId:e.sessionId||i?.sessionId,sessionFile:e.sessionFile||i?.sessionFile},o=[a],s=new Set([a.id]),c=i;for(;c?.parentId&&!s.has(c.parentId);){let e=r.get(c.parentId);if(!e)break;s.add(c.parentId),o.push(e),c=e}let l=Tl(e.engine,c?.cwd??e.cwd);El.observe(l,o,!1),El.promote(l,a,n)}function Ol(){return(0,Q.useSyncExternalStore)(El.subscribe,El.getSnapshot)}function kl({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`})})}var Al=`pi:quick-ask-open`;function jl(e={}){window.dispatchEvent(new CustomEvent(Al,{detail:e}))}function Ml(e,t){return(e?.trim()||`解释下: {{input}}`).replaceAll(`{{input}}`,()=>t)}var Nl={zh:`Simplified Chinese`,"zh-CN":`Simplified Chinese`,"zh-TW":`Traditional Chinese`,"zh-HK":`Traditional Chinese`,"zh-Hant":`Traditional Chinese`,en:`English`,ja:`Japanese`,ko:`Korean`,de:`German`,fr:`French`,es:`Spanish`,ru:`Russian`,pt:`Portuguese`,it:`Italian`,tr:`Turkish`},Pl={auto:`Auto`,"zh-CN":`简体中文`,"zh-TW":`繁體中文`,en:`English`,ja:`日本語`,ko:`한국어`,de:`Deutsch`,fr:`Français`,es:`Español`,ru:`Русский`,pt:`Português`,it:`Italiano`,tr:`Türkçe`};function Fl(e,t,n,r=e?.quickAskTranslateTarget||`auto`){let i=r===`auto`?n:r,a=Nl[i]||Nl[i.split(`-`)[0]]||`English`,o=e?.quickAskTranslatePrompt?.trim()||`将以下文字翻译成{{targetLanguage}},只输出译文,保留代码与专有名词。
|
|
13
|
+
{{input}}`,s={natural:`Use natural, fluent phrasing while preserving the original meaning.`,literal:`Translate faithfully and stay close to the original wording.`,technical:`Use precise technical terminology and preserve code and identifiers.`}[e?.quickAskTranslateStyle||`natural`];return o.replace(/\{\{(input|targetLanguage)\}\}/g,(e,n)=>n===`input`?t:a)+`\n\nTranslation style: ${s}`}async function Il(e,t){if(!e.ok||!e.headers.get(`content-type`)?.includes(`application/x-ndjson`)){let n=await e.json();if(!e.ok)throw Error(n.error||`HTTP ${e.status}`);if(!n.text?.trim())throw Error(`Model returned no answer`);t({type:`done`,text:n.text,model:n.model??``});return}if(!e.body)throw Error(`Model response has no body`);let n=e.body.getReader(),r=new TextDecoder,i=``,a=!1,o=e=>{if(!e.trim())return;let n=JSON.parse(e);if(!n||typeof n!=`object`)throw Error(`Invalid quick ask stream event`);switch(n.type){case`start`:if(typeof n.model!=`string`)throw Error(`Invalid model in stream`);break;case`delta`:if(typeof n.text!=`string`)throw Error(`Invalid text in stream`);break;case`done`:if(typeof n.text!=`string`||!n.text.trim()||typeof n.model!=`string`)throw Error(`Model returned no answer`);a=!0;break;case`error`:throw Error(typeof n.error==`string`?n.error:`Quick ask failed`);default:throw Error(`Invalid quick ask stream event`)}t(n)};try{for(;!a;){let{done:e,value:t}=await n.read();i+=e?r.decode():r.decode(t,{stream:!0});let s;for(;!a&&(s=i.indexOf(`
|
|
14
|
+
`))!==-1;)o(i.slice(0,s)),i=i.slice(s+1);if(i.length>1048576)throw Error(`Quick ask stream frame is too large`);if(e){a||o(i);break}}if(!a)throw Error(`Model stream ended before completion`)}finally{await n.cancel().catch(()=>{}),n.releaseLock()}}function Ll(e,t,n=[]){let r=e.at(-1)?.role===`user`?e.slice(0,-1):e,i=n.filter(e=>!r.some(t=>t.attachments?.some(t=>Rl(t,e))));return[...r,{role:`user`,content:t,...i.length?{attachments:i}:{}}]}function Rl(e,t){return e.id===t.id&&e.content===t.content&&e.image?.data===t.image?.data&&e.image?.mimeType===t.image?.mimeType}function zl(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 Bl(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 Vl(e,t){let n=Bl(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 Hl(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 Ul(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}var Wl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Gl=e=>e?e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase():``,Kl=e=>e.endsWith(`.jsonl`);function ql(e){if(!Kl(e))return null;let t=Hl(e)?.trim()??``;return Wl.test(t)?t.toLowerCase():null}function Jl(e){let t=[],n=e.id?.trim();n&&t.push(`conv:${n.replace(/\\/g,`/`).toLowerCase()}`);let r=e.sessionId?.trim();r&&t.push(`sid:${r.toLowerCase()}`);let i=Gl(e.sessionFile||e.path);if(i){t.push(`file:${i}`);let e=ql(i);e?t.push(`sid:${e}`):i.includes(`/`)||t.push(`conv:${i}`)}return[...new Set(t)]}function Yl(e){let t=Jl(e),n=Gl(e.sessionFile||e.path).split(`/`).pop();return n?[...t,`fn:${n}`]:t}var Xl=class{items=new Map;add(e,t,n=Jl(e)){for(let e of n)this.items.set(e,t);return t}get(e,t=Jl(e)){for(let e of t){let t=this.items.get(e);if(t!==void 0)return t}}has(e){return this.get(e)!==void 0}get size(){return this.items.size}};function Zl(e,t,n,r,i){return e.find(e=>t(e)===n)??e.find(e=>!r.has(t(e))&&i(e))}function Ql(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 $l=`pi:canvas-list-result`,eu=new Set([`canvas`,`canvases`,`画布`,`工作流`,`workflow`,`workflows`]);function tu(e,t,n,r=10){let i=t.toLowerCase();return e.filter(e=>!i||eu.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 nu(e,t=1800){return new Promise(n=>{let r=e=>{clearTimeout(a),window.removeEventListener($l,i),n(e)},i=e=>{let t=e.detail;r(t.graphs)},a=setTimeout(()=>r([]),t);window.addEventListener($l,i);try{e()||r([])}catch{r([])}})}function ru(e){return e.type===`terminal_list`||(e.type===`terminal_output`||e.type===`terminal_exit`)&&e.ownerKind===`client`}function iu(){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(-2e6),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()}}}var au=`pi-web-sounds`,ou={enabled:!0,question:!0,done:!0,subagentDone:!0,start:!1,error:!0,approval:!0,volume:100};function su(){try{let e=localStorage.getItem(au);if(!e)return{...ou};let t=JSON.parse(e),n={...ou,...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]=ou[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?ou.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...ou}}}function cu(e){try{localStorage.setItem(au,JSON.stringify(e))}catch{}y()&&typeof window<`u`&&window.dispatchEvent(new Event(`pi-web-ui:sound-settings`))}var lu=null;function uu(){try{if(!lu){let e=window.AudioContext??window.webkitAudioContext;if(!e)return null;lu=new e}return lu.state===`suspended`&&lu.resume(),lu}catch{return null}}var du=[{type:`sine`,freq:587.33,start:0,dur:.13,peak:.5},{type:`sine`,freq:880,start:.11,dur:.24,peak:.5}],fu=[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],pu={question:du,done:fu,subagentDone:fu,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 mu(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 hu(e,t=su()){if(!t.enabled||!t[e])return;let n=uu();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));for(let t of pu[e])mu(n,t,r)}var gu=`pi-web-ui:notification-click`;function _u(e){let t=t=>{let n=t instanceof CustomEvent?t.detail:t.data;if(n?.type===gu&&typeof n.url==`string`)try{let t=y()?new URL(n.url,window.location.href):new URL(n.url),r=new URL(F(),window.location.href);if(t.origin!==r.origin||!t.pathname.startsWith(r.pathname))return;y()&&t.searchParams.delete(`token`),e(t.href)}catch{}};return window.addEventListener(gu,t),y()||navigator.serviceWorker?.addEventListener(`message`,t),()=>{window.removeEventListener(gu,t),y()||navigator.serviceWorker?.removeEventListener(`message`,t)}}var vu=[`question`,`done`,`subagentDone`,`start`,`error`,`approval`];function yu(e,t,n){if(!t.enabled)return!1;let r=t.events?.[e];return r===`on`||r!==`off`&&n[e]}var bu=`pi-web-notify`,xu={enabled:!1};function Su(){let e=K(),t=e?.pushAdapter?.getState(),n=e?t?.enabled??!1:void 0;if(t?.kinds)return{enabled:t.enabled,events:Object.fromEntries(vu.map(e=>[e,t.kinds.includes(e)?`on`:`off`]))};try{let e=localStorage.getItem(bu);if(!e)return{enabled:n??xu.enabled};let t=JSON.parse(e),r={};for(let e of vu){let n=t.events?.[e];(n===`follow`||n===`on`||n===`off`)&&(r[e]=n)}return{enabled:n??(typeof t.enabled==`boolean`?t.enabled:xu.enabled),events:r}}catch{return{enabled:n??xu.enabled}}}function Cu(e){return K()?.pushAdapter?.subscribe(e)??(()=>{})}async function wu(e=Su()){let t=K()?.pushAdapter;if(!t?.setKinds)return;let n=su(),r=vu.filter(t=>yu(t,{...e,enabled:!0},n));await t.setKinds(r)}async function Tu(e){let t=e?await Bu():zu(),n=e&&t===`granted`,r=K();if(r){let e=r.pushAdapter;return e?(n&&await wu(),await e.setEnabled(n),e.getState().enabled):!1}return n}function Eu(e){try{localStorage.setItem(bu,JSON.stringify(e))}catch{}wu(e).catch(e=>console.warn(`Push event settings failed:`,e))}function Du(){return y()?K()?.pushAdapter?.getState().supported??!1:typeof window<`u`&&`Notification`in window}function Ou(){return Du()?null:y()?`unsupported`:typeof window<`u`&&window.isSecureContext===!1?`insecure`:`unsupported`}function ku(e){let{screenX:t,screenY:n,outerWidth:r,outerHeight:i}=e;return Number.isFinite(t)&&Au(t)||Number.isFinite(n)&&Au(n)?!0:r>0&&r<=400&&i>0&&i<=40}function Au(e){return e<=-1e4}function ju(e){return!(e.visibility!==`visible`||e.minimized||!e.hasFocus||e.windows&&e.idleMs>12e4)}var Mu=Date.now(),Nu=!1;function Pu(){Mu=Date.now()}function Fu(){return Math.max(0,Date.now()-Mu)}function Iu(){if(Nu||typeof window>`u`)return;Nu=!0;let e={passive:!0,capture:!0};for(let t of[`pointerdown`,`pointermove`,`keydown`,`wheel`,`touchstart`,`focus`,`scroll`])window.addEventListener(t,Pu,e);typeof document<`u`&&document.addEventListener(`visibilitychange`,Pu,e)}function Lu(){return typeof navigator>`u`?!1:/windows/i.test(navigator.userAgent??``)}function Ru(){return Iu(),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:ku({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:Fu(),windows:Lu()}}function zu(){return y()?K()?.pushAdapter?.getState().permission??`denied`:Du()?Notification.permission:`denied`}async function Bu(){if(y())return K()?.pushAdapter?.requestPermission()??`denied`;if(!Du())return`denied`;try{return await Notification.requestPermission()}catch{return`denied`}}function Vu(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function Hu(e,t=!1,n){let r=typeof location<`u`?location.href:F();try{let e=new URL(r);e.searchParams.delete(`token`),e.searchParams.delete(`view`),n&&(e.hash=Bl({sessionId:n})),r=e.href}catch{}return{body:e,requireInteraction:t,icon:U(`/icons/icon-192.png`,F()),badge:U(`/icons/icon-192.png`,F()),data:{url:r}}}async function Uu(e,t,n=!1,r){if(y())return{path:`none`,error:`native push`};if(!Du())return{path:`none`,error:`unsupported`};if(Notification.permission!==`granted`)return{path:`none`,error:`permission: ${Notification.permission}`};let i=Hu(t,n,r),a;try{let t=await navigator.serviceWorker?.getRegistration();if(t?.active&&typeof t.showNotification==`function`)return await t.showNotification(e,i),{path:`sw`};a=t?`service worker not active`:`no service worker registration`}catch(e){a=Vu(e)}try{let t=new Notification(e,i);return t.onclick=()=>{t.close(),window.focus(),window.dispatchEvent(new CustomEvent(gu,{detail:{type:gu,url:i.data.url}}))},{path:`page`,error:a}}catch(e){return{path:`none`,error:`${a}; page: ${Vu(e)}`}}}async function Wu(e,t,n=`done`,r){!y()&&Du()&&(ju(Ru())||yu(n,Su(),su())&&await Uu(e,t,!1,r))}var Gu=new Map;function Ku(e,t,n={}){return new Promise(r=>{if(n.signal?.aborted){r({ok:!1,reason:`cancelled`});return}let i=Ht(),a=e=>{Gu.delete(i)&&(clearTimeout(s),n.signal?.removeEventListener(`abort`,o),r(e))},o=()=>a({ok:!1,reason:`cancelled`}),s=setTimeout(()=>a({ok:!1,reason:`timeout`}),n.timeoutMs??(t.action===`reconnect`?12e4:t.action===`stop`?6e4:15e3));Gu.set(i,{...t,finish:a}),n.signal?.addEventListener(`abort`,o,{once:!0});try{e({type:`terminal_cli_control`,requestId:i,ownerKind:`conversation`,...t})||a({ok:!1,reason:`unavailable`})}catch{a({ok:!1,reason:`unavailable`})}})}function qu(e){let t=Gu.get(e.requestId);return!t||t.terminalId!==e.terminalId||t.conversationId!==e.conversationId?!1:(t.finish({ok:e.ok,error:e.error}),!0)}var Ju=new Set,Yu=512,Xu={done:[`nativeCliSession.doneTitle`,`nativeCliSession.doneBody`],error:[`nativeCliSession.errorTitle`,`nativeCliSession.errorBody`],question:[`nativeCliSession.questionTitle`,`nativeCliSession.questionBody`],approval:[`nativeCliSession.approvalTitle`,`nativeCliSession.approvalBody`]};function Zu(e){if(!e.eventId?.trim()||!e.conversationId?.trim()||!e.sessionId?.trim()||!Number.isFinite(e.occurredAt)||!Object.hasOwn(Xu,e.kind))return;let t=JSON.stringify([e.conversationId,e.eventId]);if(Ju.has(t))return;Ju.add(t),Ju.size>Yu&&Ju.delete(Ju.values().next().value);let n=X(r())?ee:d,[i,a]=Xu[e.kind];hu(e.kind),Wu(n[i],n[a],e.kind,e.sessionId)}function Qu(){let e=globalThis.__piPhoneHost;return typeof e?.phoneCall==`function`?e.phoneCall.bind(e):void 0}function $u(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 ed(e){return`<quoted-text>\n${JSON.stringify(e)}\n</quoted-text>`}function td(e){let t=/^<quoted-text>\n([^\n]*)\n<\/quoted-text>$/.exec(e);if(!t)return null;try{return $u(JSON.parse(t[1]))}catch{return null}}function nd(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function rd(e,t=[],n=[],r=[]){let i=[],a=(e??``).trim();a&&i.push(a);for(let e of r)e&&i.push(`<attached-image name="${nd(e)}" />`);for(let e of t){let t=(e??``).trim();t&&i.push(t)}for(let e of n)i.push(ed(e));return i.join(`
|
|
15
|
+
|
|
16
|
+
`)}function id(e){let t=e,n=[];for(;;){let e=/(?:^|\n\n)(<quoted-text>\n[^\n]*\n<\/quoted-text>)$/.exec(t),r=e?td(e[1]):null;if(!e||!r)break;n.unshift(r),t=t.slice(0,e.index)}let r=[];return t=t.replace(/(?:^|\n\n)?<attached-image name="([^"]*)"\s*\/>/g,(e,t)=>(r.push({type:`image`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<file path="([^"]*)"(?:\s+size="[^"]*")?(?:\s+lines="(\d+)-(\d+)")?\s*\/>/g,(e,t,n,i)=>{let a=t.split(/[\\/]/).pop()??t,o=n&&i?{start:Number(n),end:Number(i)}:void 0;return r.push({type:`file`,name:a,path:t,lines:o}),``}),t=t.replace(/(?:^|\n\n)?<folder path="([^"]*)"\s*\/>/g,(e,t)=>{let n=t.split(/[\\/]/).pop()??t;return r.push({type:`folder`,name:n,path:t}),``}),t=t.replace(/(?:^|\n\n)?<browser-page url="([^"]*)" title="([^"]*)">[\s\S]*?<\/browser-page>/g,(e,t,n)=>(r.push({type:`page`,name:n||t,url:t}),``)),t=t.replace(/(?:^|\n\n)?<conversation-ref[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/conversation-ref>/g,(e,t)=>(r.push({type:`conversation`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<canvas-ref id="([^"]*)" title="([^"]*)">[\s\S]*?<\/canvas-ref>/g,(e,t,n)=>{let i=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`);return r.push({type:`canvas`,path:i(t),name:i(n)||i(t)}),``}),t=t.replace(/(?:^|\n\n)?<vision-bridge>[\s\S]*?<\/vision-bridge>/g,()=>(r.push({type:`vision-bridge`,name:`视觉转写`}),``)),r.length>0&&(t=t.trim()),{text:t,quotes:n,...r.length?{attachments:r}:{}}}var ad=[{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`,`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`,`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`,`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`,`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 od(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 sd(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 od(n)}let n=[];for(let t of ad){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 od(n)}function cd(e,t){let n=sd(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 ld({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 ud=function(){let e=this.data();(e.micromarkExtensions??=[]).push({flow:{92:dd(!0)},text:{92:dd(!1)}});let t={enter:{backslashMathInline:fd,backslashMathDisplay:fd,backslashMathBlock:fd},exit:{backslashMathInline:pd,backslashMathDisplay:pd,backslashMathBlock:pd}};(e.fromMarkdownExtensions??=[]).push(t)};function dd(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 fd=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)},pd=function(e){this.exit(e)},md=`modulepreload`,hd=function(e,t){return new URL(e,t).href},gd={},_d=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=hd(t,n),t=s(t),t in gd)return;gd[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`:md,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)})},vd,yd,bd=new Set,xd={load:()=>_d(()=>import(`./math-1uRJCsA9.js`).then(e=>e.t),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)};function Sd(){return vd}function Cd(e){return bd.add(e),()=>{bd.delete(e)}}function wd(){return vd?Promise.resolve():(yd||=xd.load().then(e=>{vd=e.default,yd=void 0;for(let e of bd)e()},()=>{yd=void 0}),yd)}var Td=[`ariaDescribedBy`,`ariaLabel`,`ariaLabelledBy`],Ed={ancestors:{tbody:[`table`],td:[`table`],th:[`table`],thead:[`table`],tfoot:[`table`],tr:[`table`]},attributes:{a:[...Td,`dataFootnoteBackref`,`dataFootnoteRef`,[`className`,`data-footnote-backref`],`href`],blockquote:[`cite`],code:[[`className`,/^language-./]],del:[`cite`],div:[`itemScope`,`itemType`],dl:[...Td],h2:[[`className`,`sr-only`]],img:[...Td,`longDesc`,`src`],input:[[`disabled`,!0],[`type`,`checkbox`]],ins:[`cite`],li:[[`className`,`task-list-item`]],ol:[...Td,[`className`,`contains-task-list`]],q:[`cite`],section:[`dataFootnotes`,[`className`,`footnotes`]],source:[`srcSet`],summary:[...Td],table:[...Td],ul:[...Td,[`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(`.`)},Dd={}.hasOwnProperty;function Od(e,t){let n={type:`root`,children:[]},r=kd({schema:t?{...Ed,...t}:Ed,stack:[]},e);return r&&(Array.isArray(r)?r.length===1?n=r[0]:n.children=r:n=r),n}function kd(e,t){if(t&&typeof t==`object`){let n=t;switch(typeof n.type==`string`?n.type:``){case`comment`:return Ad(e,n);case`doctype`:return jd(e,n);case`element`:return Md(e,n);case`root`:return Nd(e,n);case`text`:return Pd(e,n)}}}function Ad(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 Vd(r,t),r}}function jd(e,t){if(e.schema.allowDoctypes){let e={type:`doctype`};return Vd(e,t),e}}function Md(e,t){let n=typeof t.tagName==`string`?t.tagName:``;e.stack.push(n);let r=Fd(e,t.children),i=Id(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&&Dd.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 Vd(o,t),o}function Nd(e,t){let n={type:`root`,children:Fd(e,t.children)};return Vd(n,t),n}function Pd(e,t){let n={type:`text`,value:typeof t.value==`string`?t.value:``};return Vd(n,t),n}function Fd(e,t){let n=[];if(Array.isArray(t)){let r=t,i=-1;for(;++i<r.length;){let t=kd(e,r[i]);t&&(Array.isArray(t)?n.push(...t):n.push(t))}}return n}function Id(e,t){let n=e.stack[e.stack.length-1],r=e.schema.attributes,i=e.schema.required,a=r&&Dd.call(r,n)?r[n]:void 0,o=r&&Dd.call(r,`*`)?r[`*`]:void 0,s=t&&typeof t==`object`?t:{},c={},l;for(l in s)if(Dd.call(s,l)){let t=s[l],n=Ld(e,Hd(a,l),l,t);n??=Ld(e,Hd(o,l),l,t),n!=null&&(c[l]=n)}if(i&&Dd.call(i,n)){let e=i[n];for(l in e)Dd.call(e,l)&&!Dd.call(c,l)&&(c[l]=e[l])}return c}function Ld(e,t,n,r){return t?Array.isArray(r)?Rd(e,t,n,r):zd(e,t,n,r):void 0}function Rd(e,t,n,r){let i=-1,a=[];for(;++i<r.length;){let o=zd(e,t,n,r[i]);(typeof o==`number`||typeof o==`string`)&&a.push(o)}return a}function zd(e,t,n,r){if((typeof r==`boolean`||typeof r==`number`||typeof r==`string`)&&Bd(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 Bd(e,t,n){let r=e.schema.protocols&&Dd.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 Vd(e,t){let n=Qn(t);t.data&&(e.data=er(t.data)),n&&(e.position=n)}function Hd(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 Ud(e){return function(t){return Od(t,e)}}function Wd(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 Gd(e){if(typeof navigator<`u`&&navigator.clipboard&&typeof navigator.clipboard.writeText==`function`)try{return await navigator.clipboard.writeText(e),!0}catch{return Wd(e)}return Wd(e)}function Kd(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 Gd(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 qd=(0,Q.memo)(function({text:e}){let t=W(),{copied:r,copy:i}=Kd({duration:1200});return e?(0,$.jsx)(`button`,{type:`button`,className:`copy-btn`,title:t(`copy`),onClick:()=>void i(e),children:r?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}):null});function Jd(e){let t=e.trim();return t?t.split(/\r?\n/).map(e=>e.replace(/^\s*[$%>]\s+/,``)).join(`
|
|
17
|
+
`).trim():``}function Yd(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 Xd(e,t){if(typeof window>`u`)return!1;let n=Jd(e);if(!n)return!1;let r=t||Yd(n);return window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:r,command:n}})),!0}var Zd=(0,Q.memo)(function({code:e,title:t}){let r=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)(()=>{Xd(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:r(i?`executedInTerminal`:`runInTerminal`),"aria-label":r(`runInTerminal`),onClick:s,children:i?(0,$.jsx)(n,{}):(0,$.jsx)(Ce,{})})});function Qd(e){let t=e=>{if(typeof e==`string`||typeof e==`number`){let t=String(e);return t===``?[[]]:t.split(`
|
|
18
|
+
`).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 $d(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map($d).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return $d(t?.children)}return``}function ef(e){let t=Array.isArray(e)?e[0]:e;return!t||typeof t!=`object`||!(`props`in t)?null:t}function tf(e){let t=ef(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 nf=`pi-web-ui:plugin-data`,rf=new Map,af=new Map,of=new Set,sf=-1,cf=0,lf=new Set;function uf(){cf++;for(let e of lf)e()}function df(e){return lf.add(e),()=>{lf.delete(e)}}function ff(){return cf}var pf=null;function mf(e){pf=e}function hf(e,t){y()&&(e=[]),t!==sf&&(sf=t,af.clear(),of.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!==rf.size;if(!r){for(let[e,t]of n)if(rf.get(e)!==t){r=!0;break}}if(r){for(let e of af.keys())n.has(e)||af.delete(e);for(let e of of)n.has(e)||of.delete(e);rf=n,uf()}}async function gf(e,t){if(y())return null;let n=rf.get(e);if(!n)return null;let r=af.get(e);if(!r&&!of.has(e))try{let t=(await _d(()=>import(g(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${sf}`)),[],import.meta.url)).default?.renderers?.[e];typeof t==`function`?(r={pluginId:n,renderer:t},af.set(e,r)):(of.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(t){of.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,t)}if(!r)return null;let i={pluginId:r.pluginId,send:e=>{pf?.({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(nf,t),()=>window.removeEventListener(nf,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 _f(e){return rf.has(e)}var vf=new Map,yf=new Map,bf=new Set,xf=-1;function Sf(e,t){y()&&(e=[]),t!==xf&&(xf=t,yf.clear(),bf.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(vf.keys()))n.has(e)||vf.delete(e);for(let[e,t]of n)vf.set(e,t);for(let e of yf.keys())n.has(e)||yf.delete(e);for(let e of bf)n.has(e)||bf.delete(e)}function Cf(e){return vf.has(e)}async function wf(e){if(y())return null;let t=vf.get(e);if(!t)return null;let n=yf.get(e);if(!n&&!bf.has(e))try{let r=(await _d(()=>import(g(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${xf}`)),[],import.meta.url)).default?.messageWidgets?.[e];typeof r==`function`?(n={pluginId:t,renderer:r},yf.set(e,n)):(bf.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(n){bf.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,n)}return n?.renderer??null}function Tf({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),gf(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)(Zd,{code:t}),(0,$.jsx)(qd,{text:t})]}),(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:t})})]})}var Ef=null,Df=new Set;function Of(){for(let e of Df)e()}function kf(e){Ef=e,Of()}function Af(){Ef!==null&&(Ef=null,Of())}function jf(e,t,n=`tool`){if(!Ef||Ef.toolCallId!==e||Ef.isThinking!==(n===`thinking`))return;let r=!1,i=Ef;for(let[e,n]of Object.entries(t))if(i[e]!==n){r=!0;break}r&&(Ef={...Ef,...t},Of())}function Mf(e,t){return!Ef||e===t||Ef.toolCallId!==e?!1:(Ef={...Ef,toolCallId:t},Of(),!0)}function Nf(){return Ef}function Pf(e){return Df.add(e),()=>{Df.delete(e)}}function Ff(){return(0,Q.useSyncExternalStore)(Pf,Nf,Nf)}function If(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 Lf=null,Rf=null,zf=null;function Bf(e){Lf=e?.open??null,Rf=e?.openList??null,zf=e?.isOpen??null}function Vf(){return zf?zf():!1}function Hf(e){return!Lf&&!Rf||!e?.path?!1:(Af(),Rf?(Rf([e],0),!0):(Lf?.(e),!0))}function Uf(e,t=0){let n=(Array.isArray(e)?e:[]).filter(e=>e&&typeof e.path==`string`&&e.path);if(n.length===0||!Lf&&!Rf)return!1;let r=Math.min(Math.max(0,t|0),n.length-1);return Af(),Rf?(Rf(n,r),!0):(Lf?.(n[r]),!0)}function Wf(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 Gf(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 Kf(e,t){return(t===`href`||t===`src`)&&/^(?:[a-z]:[\\/]|file:\/\/|pi-file:\/\/)/i.test(e)?e:Zn(e)}function qf(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 Jf(e){let t=e.split(`?`)[0]?.split(`#`)[0]?.toLowerCase()??``;return t.endsWith(`.html`)||t.endsWith(`.htm`)||t.endsWith(`.xhtml`)}function Yf(e,t){let n=qf(e,t),r=yy();if(Jf(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 o(g(`${i}?clientId=${encodeURIComponent(r)}&allowJs=1`))}let i=new URLSearchParams({clientId:r,path:n});return o(g(`/api/file?${i}`))}var Xf=[$n,tr,ud],Zf=[$n],Qf=[$n,Xn,tr,ud],$f=[$n,Xn],ep=[[Yn,{detect:!1,ignoreMissing:!0}]];function tp(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 np({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){let i=(0,Q.useSyncExternalStore)(Cd,Sd,Sd),a=!r&&(t||/[$\\\\]|math/i.test(e));(0,Q.useEffect)(()=>{a&&!i&&wd()},[a,i]);let o=!r&&i?[[i,{strict:!1,throwOnError:!1}],...ep]:ep,s=t?[nr,Ud,...o]:o,c=(0,Q.useMemo)(()=>tp(e),[e]);return(0,$.jsx)(rr,{remarkPlugins:r?n?$f:Zf:n?Qf:Xf,rehypePlugins:s,urlTransform:Kf,components:{pre:op,a:ip,img:ap},children:c})}var rp=(0,Q.memo)(function({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){return(0,$.jsx)(`div`,{className:`md`,children:(0,$.jsx)(np,{text:e,rawHtml:t,hardBreaks:n,disableMath:r})})});function ip({node:e,href:t,children:n,...r}){let i=String(t??``),a=X(Et()),o=He(`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(),Hf({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(!Gf(i)){let e=qf(i,o),t=e.split(`/`).pop()||e,s=Yf(i,o);return(0,$.jsx)(`a`,{...r,href:s,onClick:n=>{n.button===0&&!n.ctrlKey&&!n.metaKey&&!n.shiftKey&&!n.altKey&&Hf({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 ap({node:e,src:t,alt:n,...r}){let i=String(t??``),a=He(`cwd`),o=i;return y()&&i.startsWith(`/api/`)?o=ne(i):i&&!Gf(i)&&!i.startsWith(`data:`)&&!i.startsWith(`blob:`)&&(o=Yf(i,a)),R(o)&&(o=ne(o)),(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,"aria-label":n||`Image preview`,onClick:e=>{e.preventDefault(),e.stopPropagation(),pn({src:o,alt:n})},children:(0,$.jsx)(`img`,{...r,crossOrigin:R(o)??r.crossOrigin,src:o,alt:n,loading:`lazy`})})}function op({children:e,...t}){(0,Q.useSyncExternalStore)(df,ff,ff);let n=tf(e);return n&&_f(n)?(0,$.jsx)(Tf,{lang:n,code:$d(e)}):(0,$.jsx)(sp,{children:e,...t})}function sp({children:e,...t}){let n=Qd(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=cp(e);return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(Zd,{code:a}),(0,$.jsx)(qd,{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 cp(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(cp).join(``);if(e&&typeof e==`object`&&`props`in e){let t=e.props;return cp(t?.children)}return``}function lp({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),Cf(e))return wf(e).then(async r=>{if(!n&&r)try{let i=await r(t,{pluginId:vf.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 up=/^\s{0,3}(`{3,}|~{3,})/,dp=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function fp(e){return e.trim()===``}function pp(e){let t=up.exec(e);return t?t[1]:null}function mp(e){let t=e.split(`
|
|
19
|
+
`),n=[],r=[],i=null;for(let e=0;e<t.length;e++){let a=t[e];if(i!==null){let e=pp(a);e&&e[0]===i[0]&&e.length>=i.length&&(i=null),r.push(a);continue}let o=pp(a);if(o&&!fp(a)){i=o,r.push(a);continue}if(fp(a)){let i=e;for(;i<t.length&&fp(t[i]);)i++;if(!(i<t.length&&dp.test(t[i]))&&r.length>0){n.push(r.join(`
|
|
20
|
+
`)),r=[];continue}r.push(a);continue}r.push(a)}return{frozen:n,active:r.join(`
|
|
21
|
+
`),inFence:i!==null}}function hp(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 gp=22,_p=14,vp=()=>typeof document<`u`&&document.hidden;function yp(e,t=!0,n=!1,r){let[i,a]=(0,Q.useState)(()=>!t||vp()||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(vp()){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?_p:gp;if(f.current>0&&e-f.current<t){d.current=requestAnimationFrame(r);return}f.current=e;let n=o.current,i=hp(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 bp=600,xp=32,Sp=(0,Q.memo)(function({text:e,active:t,inFence:n}){let r=t&&!n&&e.length>=bp,[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>=xp){n();return}return s.current=setTimeout(n,xp-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)(np,{text:r?i:e})}),Cp=(0,Q.memo)(function({text:e,finishing:t=!1,onSettled:n}){let r=yp(e,!0,t,n),{frozen:i,active:a,inFence:o}=(0,Q.useMemo)(()=>mp(r),[r]);return(0,$.jsx)(`div`,{className:`md`,children:[...i,...a.length>0?[a]:[]].map((e,t)=>(0,$.jsx)(Sp,{text:e,active:t===i.length,inFence:t===i.length&&o},t))})});function wp({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)(L,{}):(0,$.jsx)(h,{})}):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]})}function Tp(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`}function Ep(e){return String(e).padStart(2,`0`)}function Dp(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=`${Ep(t.getHours())}:${Ep(t.getMinutes())}:${Ep(t.getSeconds())}`;return r?i:`${Ep(t.getMonth()+1)}-${Ep(t.getDate())} ${i}`}function Op(e,t,n){let r=typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.round(t):typeof n==`number`&&Number.isFinite(n)&&n>=0?Math.round(n):void 0,i=typeof e==`number`&&Number.isFinite(e)?e:void 0;return{start:i!==void 0&&r!==void 0?i-r:void 0,end:i,durationMs:r}}function kp(e,t){let n=typeof e==`number`&&Number.isFinite(e)?e:void 0,r=typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.round(t):void 0;return{start:n,end:n!==void 0&&r!==void 0?n+r:void 0,durationMs:r}}var Ap=300;function jp(e){let t=e.split(`
|
|
22
|
+
`),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(`
|
|
23
|
+
`)}function Mp(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 Np(e){let t=Mp(e).replace(/\r\n/g,`
|
|
24
|
+
`).replace(/[ \t]+\n/g,`
|
|
25
|
+
`),n=jp(t).trim()||t.trim();return n?n.replace(/\n{3,}/g,`
|
|
26
|
+
|
|
27
|
+
`):``}function Pp(e){let t=Mp(e),n=jp(t).trim()||t.trim();return n?n.split(/\n+/).map(e=>e.trim()).filter(Boolean).join(` `):``}function Fp(e,t){let n=Pp(e);return n?t?n.slice(-300):n.slice(0,Ap):``}function Ip({thinking:e,streaming:t,wrap:r=!0,forceOpen:i=!1,startTimestamp:a,endTimestamp:o,durationMs:s,thinkingId:c}){let l=W(),[u,d]=(0,Q.useState)(null),f=u??r,p=f||i,m=!!t,h=(0,Q.useRef)(m);h.current=m;let g=()=>typeof document<`u`&&document.hidden,[_,v]=(0,Q.useState)(()=>m&&!g());(0,Q.useEffect)(()=>{m&&!g()?v(!0):!m&&g()&&v(!1)},[m]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{h.current||v(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let y=(0,Q.useCallback)(()=>{h.current||v(!1)},[]),b=m||_,S=yp(e,b,!m&&_,y),C=Np(S),w=Fp(S,b),{copied:T,copy:E}=Kd({duration:1200}),D=()=>{E(e)},O=p?l(`collapseMsg`):w?`${l(`expandMsg`)} · ${w}`:l(`expandMsg`),A=(0,Q.useRef)(null),j=If(A.current),M=kp(a,s??(o!==void 0&&a!==void 0?o-a:void 0)),N=M.durationMs===void 0?``:Tp(M.durationMs),[P,F]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{if(!b||M.start===void 0)return;let e=window.setInterval(()=>F(Date.now()),1e3);return()=>window.clearInterval(e)},[b,M.start]);let I=b&&M.start!==void 0?Math.max(0,P-M.start):void 0,L=N?`${l(`done`)} (${N})`:l(`done`),R={status:b?l(`thinkingNow`):L,statusClass:b?`run`:`ok`,duration:N,durationMs:M.durationMs,startTimestamp:M.start,endTimestamp:M.end,output:C||e,thinking:S||e,streaming:b},z=(0,Q.useRef)(R);z.current=R;let B=(0,Q.useRef)(L);B.current=L;let ee=(0,Q.useRef)(e);ee.current=e;let V=(0,Q.useRef)(new Set);c&&V.current.add(c);let te=()=>{kf({isThinking:!0,title:l(`toolInspectorThinkingTitle`),...R,toolCallId:c})};return(0,Q.useEffect)(()=>{if(!c)return;let t=Nf();if(!t||!t.isThinking)return;let n=t.toolCallId;if(n){if(n!==c){let r=Np(t.thinking||t.output||``),i=!!r&&(C||e).startsWith(r);if(!V.current.has(n)&&!i)return;Mf(n,c)}jf(c,z.current,`thinking`)}},[c,S,C,e,b,N,M.start,M.end,M.durationMs,l]),(0,Q.useEffect)(()=>()=>{let e=Nf();if(!e||!e.isThinking||!e.streaming)return;let t=e.toolCallId;if(!t||!V.current.has(t))return;let n=Np(ee.current);jf(t,{...z.current,thinking:ee.current||z.current.thinking,output:n||z.current.output,status:B.current,statusClass:`ok`,streaming:!1},`thinking`)},[]),j?(0,$.jsx)(`div`,{ref:A,className:`thinking ${b?`live run`:`ok`}`,"data-thinking":e,onClick:e=>{e.preventDefault(),e.stopPropagation(),te()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),te())},role:`button`,tabIndex:0,title:l(`toolInspectorThinkingTitle`),children:(0,$.jsxs)(`div`,{className:`thinking-head chead`,children:[(0,$.jsx)(`span`,{className:`thinking-icon chead-icon`,children:(0,$.jsx)(k,{})}),(0,$.jsx)(`span`,{className:`thinking-name chead-title`,children:l(`thinking`)}),(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:l(b?`thinkingNow`:`done`),"aria-label":l(b?`thinkingNow`:`done`),children:b?(0,$.jsx)(kl,{className:`spin`}):(0,$.jsx)(n,{})})]})}):(0,$.jsxs)(`div`,{ref:A,className:`thinking ${p?`open`:``} ${b?`live`:``} ${b?`run`:`ok`}`,"data-thinking":e,onClick:e=>{If(A.current)&&(e.target?.closest(`.chead-copy, .toolcall-copy, .thinking-copy, a`)||(e.preventDefault(),e.stopPropagation(),te()))},children:[(0,$.jsx)(wp,{open:!j&&p,headClassName:`thinking-head${b?` thinking-live`:``}`,toggleClassName:`thinking-toggle`,titleText:O,onToggle:()=>{if(If(A.current)){te();return}d(!f)},icon:(0,$.jsx)(k,{}),iconClassName:`thinking-icon`,titleClassName:`thinking-label`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:l(b?`thinkingNow`:`done`),"aria-label":l(b?`thinkingNow`:`done`),children:b?(0,$.jsx)(kl,{className:`spin`}):(0,$.jsx)(n,{})}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy thinking-copy${T?` copied`:``}`,title:l(T?`copied`:`copyMessage`),"aria-label":l(`copyMessage`),onClick:e=>{e.stopPropagation(),D()},children:T?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{})})]}),children:b&&p?(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[l(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):b?w?(0,$.jsx)(`span`,{className:`thinking-preview-live`,children:(0,$.jsx)(`span`,{className:`thinking-preview-viewport`,children:(0,$.jsxs)(`span`,{className:`thinking-preview-track`,children:[w,(0,$.jsx)(`span`,{className:`stream-cursor`})]})})}):(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[l(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):w?(0,$.jsx)(`span`,{className:`thinking-summary-text`,children:w}):null}),!j&&p&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`thinking-body`,children:[C,b&&(0,$.jsx)(`span`,{className:`stream-cursor`})]}),(0,$.jsxs)(`div`,{className:`toolcall-time-footer thinking-time-footer`,children:[(0,$.jsx)(Pt,{className:`toolcall-time-icon`}),(0,$.jsx)(`span`,{className:`toolcall-time-text`,children:M.start!==void 0&&M.end!==void 0&&M.durationMs!==void 0?l(`toolTimeRange`,{start:Dp(M.start),end:Dp(M.end),duration:Tp(M.durationMs)}):b&&M.start!==void 0&&I!==void 0?l(`toolTimeRunning`,{start:Dp(M.start),duration:Tp(I)}):M.start===void 0?``:Dp(M.start)})]})]})]})}function Lp(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 Rp=null,zp=new Set;function Bp(){for(let e of zp)e()}function Vp(e){let t=(e??``).trim();t&&(Rp={name:t,status:`loading`},Bp(),Z({type:`get_tool_info`,name:t}))}function Hp(){Rp!==null&&(Rp=null,Bp())}function Up(e){Rp!==null&&Rp.name===e.name&&(Rp=Lp(e),Bp())}function Wp(e){return zp.add(e),()=>{zp.delete(e)}}function Gp(){return Rp}function Kp(){return(0,Q.useSyncExternalStore)(Wp,Gp,Gp)}var qp=new Set([`image`,`video`,`audio`,`markdown`,`html`,`pdf`,`text`,`binary`,`dir`,`missing`]);function Jp(e){let t=String(e??``).trim().replace(/\\/g,`/`);return t.length>1?t.replace(/\/+$/,``):t}function Yp(e){let t=Jp(e).split(`/`);return(t[t.length-1]??``)||String(e??``)}function Xp(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Zp(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function Qp(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=Xp(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=Xp(e),n=t?Zp(t.path):void 0;if(!n)continue;let r={path:n},a=Zp(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=Zp(n.title);o&&(a.title=o);let s=Zp(n.note);return s&&(a.note=s),a}function $p(e,t){let n=Xp(t),r=Array.isArray(n?.items)?n.items.map(Xp):[],i=new Map;for(let e of r){if(!e)continue;let t=Jp(String(e.path??e.abs??``));t&&!i.has(t)&&i.set(t,e)}return e.items.map((e,t)=>{let n=i.get(Jp(e.path))??r[t]??null,a=Zp(n?.kind),o={path:e.path,target:Zp(n?.abs)??e.path,name:Yp(Zp(n?.name)??e.path),kind:a&&qp.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=Zp(n?.excerpt);return s&&(o.excerpt=s),n?.excerptTruncated===!0&&(o.excerptTruncated=!0),o})}function em(e,t){return Zp(Xp(t)?.title)??e.title}function tm(e,t){return Zp(Xp(t)?.note)??e.note}function nm(e){return e===`image`||e===`video`||e===`audio`?e:null}function rm(e){return e!==`dir`&&e!==`missing`}function im(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 am(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 om(e){return e.find(e=>e.focus&&rm(e.kind))}function sm(e){return om(e)??e.find(e=>rm(e.kind))}function cm(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 lm=209715200,um=/windows/i.test(navigator.userAgent),dm=/[<>:"/\\|?*\u0000-\u001f]/g,fm=/[. ]+$/,pm=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function mm(e){let t=e.replace(dm,`_`).replace(fm,``);return t?pm.test(t)?`_${t}`:t:`_`}function hm(e,t=!0){let n=new URLSearchParams({clientId:yy(),path:e,...t?{download:`1`}:{}});return o(g(`/api/file?${n}`))}async function gm(e,t){let n=um?mm(t):t;try{let t=await fetch(hm(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`)>lm)return window.location.assign(hm(e)),{ok:!0};let r=await t.blob();return window.showSaveFilePicker&&window.isSecureContext?vm(r,n):ym(r,n)}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}async function _m(e,t){let n=um?mm(t):t;return window.showSaveFilePicker&&window.isSecureContext?vm(e,n):ym(e,n)}async function vm(e,t){let n,r=window.showSaveFilePicker;if(!r)return ym(e,t);try{n=await r({suggestedName:t})}catch(n){return n instanceof DOMException&&n.name===`AbortError`?{ok:!1,cancelled:!0}:ym(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 ym(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 bm=`pi-web-ui:present-auto-open`,xm=3e4,Sm=`pi-web-ui:present-auto-opened`;function Cm(){try{return localStorage.getItem(bm)===`1`}catch{return!1}}function wm(e){try{localStorage.setItem(bm,e?`1`:`0`)}catch{}Om=e,Em()}var Tm=new Set;function Em(){for(let e of Tm)e()}function Dm(e){return Tm.add(e),()=>{Tm.delete(e)}}var Om=null;function km(){return Om===null&&(Om=Cm()),Om}function Am(){return(0,Q.useSyncExternalStore)(Dm,km)}function jm(){try{let e=sessionStorage.getItem(Sm);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function Mm(e){if(!e)return!1;let t=jm();if(t.includes(e))return!1;let n=[...t,e].slice(-200);try{sessionStorage.setItem(Sm,JSON.stringify(n))}catch{}return!0}function Nm(e,t,n=Date.now()){let r=typeof t==`number`&&Number.isFinite(t)?t:n;return cm({enabled:Cm(),seen:!1,timestamp:r,now:n,maxAgeMs:xm})?Mm(e):!1}var Pm=(0,Q.memo)(function({args:e,details:t,toolCallId:n,resultTimestamp:r}){let i=W(),a=Am(),o=(0,Q.useMemo)(()=>$p(e,t),[e,t]),s=em(e,t),c=tm(e,t),l=(0,Q.useMemo)(()=>sm(o),[o]),u=(0,Q.useMemo)(()=>o.filter(e=>rm(e.kind)).map(e=>({path:e.target,name:e.name})),[o]),d=(0,Q.useMemo)(()=>{if(!l)return 0;let e=u.findIndex(e=>e.path===l.target);return e>=0?e:0},[u,l]);return(0,Q.useEffect)(()=>{a&&l&&u.length!==0&&n&&(Vf()||Nm(n,r)&&Uf(u,d))},[a,l,u,d,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)(rp,{text:c,rawHtml:!0})}),(0,$.jsx)(`div`,{className:`present-items`,children:o.map((e,t)=>(0,$.jsx)(Im,{item:e,previewList:u,previewIndex:(()=>{let n=u.findIndex(t=>t.path===e.target);return n>=0?n:t})()},`${e.target}\u0000${e.path}`))})]})});function Fm(e){return typeof e.mtime==`number`?`${e.path}\n${new Date(e.mtime).toLocaleString()}`:e.path}function Im({item:e,previewList:n,previewIndex:r}){let i=W(),{copied:a,copy:o}=Kd({duration:1200}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=s?null:nm(e.kind),f=am(e.size),p=e.kind===`missing`,m=!Wf(),h=Yf(e.target);return(0,$.jsxs)(`div`,{className:`present-item${p?` missing`:``}`,children:[(0,$.jsxs)(`div`,{className:`present-item-head`,children:[(0,$.jsx)(`span`,{className:`present-item-icon`,"aria-hidden":`true`,children:im(e.kind)}),(0,$.jsx)(`span`,{className:`present-item-name`,title:Fm(e),children:e.name}),e.caption&&(0,$.jsx)(`span`,{className:`present-item-caption`,children:e.caption}),f&&!p&&(0,$.jsx)(`span`,{className:`present-item-meta`,children:f}),(0,$.jsx)(`span`,{className:`present-item-spacer`}),!p&&(0,$.jsxs)($.Fragment,{children:[rm(e.kind)&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:i(`previewFile`),"aria-label":i(`previewFile`),onClick:()=>Uf(n,r),children:(0,$.jsx)(Ne,{})}),m?(0,$.jsxs)(`a`,{className:`present-btn labeled`,href:h,target:`_blank`,rel:`noreferrer noopener`,title:i(`openInNewTab`),children:[(0,$.jsx)(t,{}),(0,$.jsx)(`span`,{children:i(`openInNewTab`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`present-btn labeled`,title:i(`fileOpenDefault`),onClick:()=>Z({type:`file_open_default`,path:e.target}),children:[(0,$.jsx)(t,{}),(0,$.jsx)(`span`,{children:i(`presentOpenLocal`)})]}),!m&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:i(`fileReveal`),"aria-label":i(`fileReveal`),onClick:()=>Z({type:`file_reveal`,path:e.target}),children:(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:i(`downloadFile`),"aria-label":i(`downloadFile`),onClick:()=>{u(``),gm(e.target,e.name).then(e=>{e.ok||e.cancelled||u(e.error===`FILE_NOT_FOUND`?i(`fileNotFoundShort`):e.error)})},children:(0,$.jsx)(he,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn${a?` on`:``}`,title:i(`copyPath`),"aria-label":i(`copyPath`),onClick:()=>{o(e.path)},children:(0,$.jsx)(x,{})})]})]}),p&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:i(`presentMissing`)}),l&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:i(`downloadFailed`,{error:l})}),d===`image`&&(0,$.jsx)(`button`,{type:`button`,className:`present-media`,title:i(`previewFile`),onClick:()=>Uf(n,r),children:(0,$.jsx)(`img`,{crossOrigin:R(hm(e.target,!1)),src:hm(e.target,!1),alt:e.name,loading:`lazy`,onError:()=>c(!0)})}),d===`video`&&(0,$.jsx)(`video`,{className:`present-media-video`,crossOrigin:R(hm(e.target,!1)),src:hm(e.target,!1),controls:!0,preload:`metadata`,onError:()=>c(!0)}),d===`audio`&&(0,$.jsx)(`audio`,{className:`present-media-audio`,crossOrigin:R(hm(e.target,!1)),src:hm(e.target,!1),controls:!0,preload:`metadata`,onError:()=>c(!0)}),e.excerpt&&(0,$.jsxs)(`pre`,{className:`present-excerpt`,children:[e.excerpt,e.excerptTruncated?`…`:``]})]})}function Lm(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(`
|
|
28
|
+
`).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 Rm(e){if(!e)return;let t=/(?:User note \/ 附言|附言)[::]\s*([^\n\r]+)/.exec(e);return t?t[1].trim():void 0}var zm=(0,Q.memo)(function({questions:e,details:t,output:r,isError:i=!1,waiting:a=!1}){let o=W(),s=(0,Q.useMemo)(()=>Lm(t,r),[t,r]),c=(0,Q.useMemo)(()=>i?Rm(r):void 0,[i,r]);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)(Be,{})}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:o(`questionCardCancelled`)}),c&&(0,$.jsxs)(`div`,{className:`qcard-reject-reason`,children:[(0,$.jsx)(pe,{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 r=s.get(e.id)??s.get(e.header??``),i=new Set(r?.selected??[]),a=r!==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)(rp,{text:e.question,rawHtml:!0})}),e.detail&&(0,$.jsx)(`div`,{className:`qcard-detail`,children:(0,$.jsx)(rp,{text:e.detail,rawHtml:!0})}),c.length>0&&(0,$.jsx)(`div`,{className:`qcard-options`,children:c.map((t,r)=>{let s=i.has(t.label),l=t.recommended??(r===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)(n,{className:`qcard-check-icon`}):`☐`:s?`●`:`○`}),(0,$.jsxs)(`div`,{className:`qcard-opt-content`,children:[(0,$.jsxs)(`div`,{className:`qcard-opt-label`,children:[(0,$.jsx)(rp,{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)(rp,{text:t.description,rawHtml:!0})})]})]},t.label)})}),a&&i.size===0&&!r.custom&&(0,$.jsx)(`div`,{className:`qcard-empty-sel`,children:o(`questionCardNoSelection`)}),r?.custom&&(0,$.jsxs)(`div`,{className:`qcard-custom-note`,children:[(0,$.jsx)(Ye,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{className:`qcard-custom-label`,children:[o(`questionCardUserCustom`),`:`]}),(0,$.jsx)(`span`,{className:`qcard-custom-text`,children:r.custom})]})]},e.id)})})]})}),Bm=1e5,Vm=100040,Hm=[],Um=new Set;function Wm(){for(let e of Um)e()}function Gm(e){return Math.min(Vm,Bm+(Number.isFinite(e)?Math.max(0,Math.floor(e)):0)*10)}function Km(e){let t=Hm.indexOf(e);return t<0?Hm.length:t}function qm(e){Hm.includes(e)||(Hm.push(e),Wm());let t=!1;return()=>{if(t)return;t=!0;let n=Hm.indexOf(e);n<0||(Hm.splice(n,1),Wm())}}function Jm(e=!0){let t=(0,Q.useRef)({}),[n,r]=(0,Q.useState)(()=>Gm(Hm.length));return(0,Q.useEffect)(()=>{if(!e)return;let n=t.current,i=()=>r(Gm(Km(n))),a=qm(n);return i(),Um.add(i),()=>{Um.delete(i),a()}},[e]),n}var Ym={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 Xm(e){if(!e)return`plaintext`;let t=e.split(`.`).pop()?.toLowerCase();return t&&Ym[t]||`plaintext`}var Zm=/\s+|[a-zA-Z0-9_$]+|[^\s\w]/g;function Qm(e){return e?e.replace(/\\([nrtbfv\\/"]|u[0-9a-fA-F]{4})/g,(e,t)=>{switch(t){case`n`:return`
|
|
29
|
+
`;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 $m(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(Zm)||[e],r=t.match(Zm)||[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 eh=/^([+\- ])(\s*\d+)?\s(.*)$/;function th(e){let t=[],n=null,r=0,i=0,a=1,o=1,s=e.split(`
|
|
30
|
+
`),c=[],l=[],u=()=>{if(c.length===1&&l.length===1){let{oldTokens:e,newTokens:t}=$m(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=eh.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 nh(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(`
|
|
31
|
+
`):[],c=o?o.split(`
|
|
32
|
+
`):[];r+=s.length,n+=c.length;let l=[];if(s.length===1&&c.length===1){let{oldTokens:e,newTokens:t}=$m(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 rh(e,t,n,r){let i=e===`write`;if(!i&&e!==`edit`&&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=Xm(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=Qm(i)}else n=Qm(t)}let r=n?n.split(`
|
|
33
|
+
`).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=th(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=th(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}=nh(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 ih=(0,Q.memo)(function({toolName:e,argumentsText:r,details:i,output:a,isError:o,onOpenInspector:s}){let c=W(),[l,u]=(0,Q.useState)(`unified`),[d,f]=(0,Q.useState)(!1),p=Jm(d),{copied:h,copy:g}=Kd({duration:1200}),_=(0,Q.useMemo)(()=>rh(e,r,i,a),[e,r,i,a]),v=(0,Q.useMemo)(()=>{if(!i||typeof i!=`object`)return``;try{return JSON.stringify(i,null,2)}catch{return``}},[i]);(0,Q.useEffect)(()=>{if(!d)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f(!1))};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},[d]);let y=e=>{e.stopPropagation(),_?.isWrite&&_.content?g(_.content):r&&g(r)},b=e=>{if(e.stopPropagation(),!_?.filePath)return;let t=_.filePath.split(`/`).pop()||_.filePath;Hf({path:_.filePath,name:t})},S=e=>{e.stopPropagation(),f(e=>!e),s?.()};if(!_||l===`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:_?.filePath||e}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`unified`)},children:c(`diffViewUnified`)}),!_?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`split`)},children:c(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`raw`)},children:c(`diffViewRaw`)}),s&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:c(`diffFullscreen`),"aria-label":c(`diffFullscreen`),onClick:S,children:(0,$.jsx)(m,{})})]})]}),(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:[`⚡ `,c(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:r||`(无入参参数 / No arguments)`})]}),v&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,c(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[Object.keys(i).length,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:v})]})]})]});let C=()=>_.isWrite?(0,$.jsx)(ah,{content:_.content||``}):l===`split`?(0,$.jsx)(ch,{hunks:_.hunks,isStreaming:_.isStreamingPartial,fallbackText:r}):(0,$.jsx)(oh,{hunks:_.hunks,isStreaming:_.isStreamingPartial,fallbackText:r});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`file-diff-card${o?` is-err`:``}`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(Y,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_.filePath,children:_.filePath||e}),_.language&&_.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:_.language}),_.isStreamingPartial&&(0,$.jsx)(`span`,{className:`file-diff-streaming-badge`,children:c(`diffStreaming`)}),_.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:c(`diffNewFile`)}):(_.stats.additions>0||_.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[_.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,_.stats.additions]}),_.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,_.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${l===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`unified`)},children:c(`diffViewUnified`)}),!_.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`split`)},children:c(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`raw`)},children:c(`diffViewRaw`)})]}),_.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:c(`diffOpenFile`),"aria-label":c(`diffOpenFile`),onClick:b,children:(0,$.jsx)(t,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:c(`diffFullscreen`),"aria-label":c(`diffFullscreen`),onClick:S,children:(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${h?` copied`:``}`,title:_.isWrite?c(`diffCopyContent`):c(`diffCopyPatch`),"aria-label":_.isWrite?c(`diffCopyContent`):c(`diffCopyPatch`),onClick:y,children:h?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-body`,children:C()})]}),d&&(0,cr.createPortal)((0,$.jsx)(`div`,{className:`file-diff-fullscreen-backdrop`,style:{zIndex:p},role:`dialog`,"aria-modal":`true`,onClick:e=>{e.target===e.currentTarget&&f(!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)(Y,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_.filePath,children:_.filePath||e}),_.language&&_.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:_.language}),_.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:c(`diffNewFile`)}):(_.stats.additions>0||_.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[_.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,_.stats.additions]}),_.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,_.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${l===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`unified`)},children:c(`diffViewUnified`)}),!_.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`split`)},children:c(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${l===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),u(`raw`)},children:c(`diffViewRaw`)})]}),_.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:c(`diffOpenFile`),"aria-label":c(`diffOpenFile`),onClick:b,children:(0,$.jsx)(t,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${h?` copied`:``}`,title:_.isWrite?c(`diffCopyContent`):c(`diffCopyPatch`),"aria-label":_.isWrite?c(`diffCopyContent`):c(`diffCopyPatch`),onClick:y,children:h?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${c(`diffRestoreScreen`)} (ESC)`,"aria-label":c(`diffRestoreScreen`),onClick:e=>{e.stopPropagation(),f(!1)},children:(0,$.jsx)(I,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${c(`close`)} (ESC)`,"aria-label":c(`close`),onClick:e=>{e.stopPropagation(),f(!1)},children:(0,$.jsx)(Be,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-fullscreen-body`,children:C()})]})}),document.body)]})});function ah({content:e,startLine:t=1}){let n=(0,Q.useMemo)(()=>e?e.split(`
|
|
34
|
+
`):[],[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 oh({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)(sh,{line:e},t))]},t))})}function sh({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 ch({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 lh={bash:(0,$.jsx)(Ce,{}),delegate_task:(0,$.jsx)(Nt,{}),conversation:(0,$.jsx)(lt,{}),read:(0,$.jsx)(Y,{}),write:(0,$.jsx)(ie,{}),edit:(0,$.jsx)(J,{}),patch:(0,$.jsx)(We,{}),grep:(0,$.jsx)(ft,{}),find:(0,$.jsx)(de,{}),ls:(0,$.jsx)(st,{}),codemode:(0,$.jsx)(Re,{}),eval:(0,$.jsx)(a,{}),lsp:(0,$.jsx)(a,{}),tool_search:(0,$.jsx)(ft,{}),load_tools:(0,$.jsx)(oe,{}),ask_user_question:(0,$.jsx)(ut,{}),[oi]:(0,$.jsx)(Ve,{}),browser_page:(0,$.jsx)(Ct,{}),conversation_read:(0,$.jsx)(Ye,{}),claim_files:(0,$.jsx)(l,{}),plan_update:(0,$.jsx)(P,{}),skill:(0,$.jsx)(p,{}),schedule:(0,$.jsx)(Pt,{}),compact_context:(0,$.jsx)(Le,{}),mcp_manage:(0,$.jsx)(B,{}),sandbox:(0,$.jsx)(B,{}),worktree:(0,$.jsx)(ke,{}),sftp:(0,$.jsx)(ve,{}),mail:(0,$.jsx)(Dt,{}),obs_recall:(0,$.jsx)(D,{})},uh=(0,$.jsx)(ot,{}),dh={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`,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`,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`,[oi]:`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`},fh=`toolcall-icon tc-tone-default`;function ph(e){return lh[e]??uh}function mh(e){return dh[e]??fh}function hh(e,t){let n=Qp(e);if(!n)return!1;let r=sm($p(n,t));return r?Hf({path:r.target,name:r.name}):!1}function gh({blockId:e,view:t,statusClass:n,statusLabel:r,duration:i,durationMs:a,startTimestamp:o,endTimestamp:s,exitHint:c,isError:l,isBash:u,onKillBash:d,t:f}){(0,Q.useEffect)(()=>{let p=Nf(),m=t.result?.toolCallId??e;if(!p||p.isThinking||p.toolCallId!==e&&p.toolCallId!==m)return;let h=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,g=h.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>f(`liveOutputOmitted`,{n:t})),_=(t.result?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`))).map(e=>e.dataUrl);jf(p.toolCallId,{status:r,statusClass:n,duration:i,durationMs:a,startTimestamp:o,endTimestamp:s,exitHint:c,rawOutput:h,output:g,details:t.result?.details,images:_,isError:l,resultTimestamp:t.result?.timestamp,onKillBash:u?d:void 0})},[e,t.liveOutput,t.result,t.status,n,r,i,a,o,s,c,l,u,d,f])}var _h=(0,Q.memo)(function({block:e,view:t,onKillBash:r,uiContextToolCall:i,onUiAction:a,rootRef:o}){let s=W(),c=X(Et()),l=e.name===oi,u=e.name===`bash`,d=!t.result&&t.streaming&&!t.status,f=u&&(d||!t.result),p=t.result!==void 0,m=!t.result&&!!t.status,h=t.result?.isError??t.status?.isError??!1,g=t.status?.durationMs,_=t.result?.durationMs,v=typeof _==`number`?_:g,y=Op(t.result?.timestamp,_,g),b=h?`err`:p?`ok`:d||m?`run`:`idle`,x=s(h?`error`:p?`done`:d?`running`:m?`toolDoneWaitingModel`:`toolQueued`),S=(m||p)&&v!==void 0?Tp(v):``;(m||p)&&S&&(x=`${x} · ${S}`);let C=m&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,w=_s(e.argumentsText),T=gs({name:e.name,argumentsText:e.argumentsText,hints:w}),E=T?`${e.name}(${T.text})`:`${e.name}()`;gh({blockId:e.id,view:t,statusClass:b,statusLabel:x,duration:S,durationMs:v,startTimestamp:y.start,endTimestamp:y.end,exitHint:C,isError:h,isBash:u,onKillBash:r,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 n=i??[],o=[];u&&r&&o.push(ha({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:c?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:f?void 0:[`disabled`]})),o.push(...n),o.length!==0&&(t.preventDefault(),t.stopPropagation(),za({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`){r?.();return}if(t.id===`host:tool-info`){Vp(e.name);return}a?.(t)}}))},A=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,i=n.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=l?Qp(e.argumentsText):null;kf({isThinking:!1,name:e.name,title:E,status:x,statusClass:b,duration:S,durationMs:v,startTimestamp:y.start,endTimestamp:y.end,exitHint:C,hints:w,args:e.argumentsText||``,rawOutput:n,output:i,details:t.result?.details,images:a,isError:h,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,onKillBash:u?r:void 0,presentData:l&&o?{title:o.title,note:o.note,items:o.items}:null})},j=n=>{l&&!n?.altKey&&hh(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 ${mh(e.name)}`,children:ph(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:h?(0,$.jsx)(Be,{}):p?(0,$.jsx)(n,{}):d||m?(0,$.jsx)(kl,{}):(0,$.jsx)(z,{})}),D&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:s(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ve,{})}),O&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:c?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(Y,{})})]})})}),vh=(0,Q.memo)(function({block:e,view:t,onKillBash:r,wrap:i=!0,showImages:a=!0,forceOpen:o=!1,uiContextToolCall:s,uiToolCardFooter:c,onUiAction:l,rootRef:u}){let d=W(),f=X(Et()),[p,m]=(0,Q.useState)(null),h=e.name===oi,g=p??(h?!0:i),_=g||o,{copied:v,copy:y}=Kd({duration:1200}),b=!t.result&&t.streaming&&!t.status,S=e.name===`bash`,C=S&&(b||!t.result),w=t.result!==void 0,T=!t.result&&!!t.status,E=t.result?.isError??t.status?.isError??!1,D=(0,Q.useRef)(null),O=(0,Q.useRef)(!0),k=(0,Q.useMemo)(()=>_?t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``:``,[_,t.result,t.liveOutput]),A=(0,Q.useMemo)(()=>!_||!k?``:k.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>d(`liveOutputOmitted`,{n:t})),[_,k,d]);(0,Q.useEffect)(()=>{_&&(b||T)&&O.current&&D.current&&(D.current.scrollTop=D.current.scrollHeight)},[_,A,b,T]);let j=(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]),M=e.name===`delegate_task`,N=(0,Q.useMemo)(()=>!M||!_?{}:xs(e.argumentsText),[M,_,e.argumentsText]),P=e.name===`codemode`,F=(0,Q.useMemo)(()=>P&&_?Os(e.argumentsText):null,[P,_,e.argumentsText]),I=e.name===`ask_user_question`,L=(0,Q.useMemo)(()=>I&&_?Ms(e.argumentsText):null,[I,_,e.argumentsText]),B=e.name===`edit`||e.name===`write`||e.name===`patch`,ee=(0,Q.useMemo)(()=>B?rh(e.name,e.argumentsText,t.result?.details,A):null,[B,e.name,e.argumentsText,t.result?.details,A]),V=j.length>0,te=(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]),re=(0,Q.useMemo)(()=>h&&_?Qp(e.argumentsText):null,[h,_,e.argumentsText]),ie=M&&t.result&&typeof t.result.details==`object`&&t.result.details!==null?t.result.details.convId:void 0,H=(0,Q.useMemo)(()=>{if(!M)return;if(ie)return ie;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]},[M,ie,t.result?.content]),ae=(0,Q.useRef)(void 0),U=t.status?.durationMs,oe=t.result?.durationMs;(0,Q.useEffect)(()=>{U!==void 0&&(ae.current=U),typeof oe==`number`&&(ae.current=oe)},[U,oe]);let se=typeof oe==`number`?oe:U??ae.current,ce=Op(t.result?.timestamp,oe,U??ae.current),le=E?`err`:w?`ok`:b||T?`run`:`idle`,G=d(E?`error`:w?`done`:b?`running`:T?`toolDoneWaitingModel`:`toolQueued`),K=(T||w)&&se!==void 0?Tp(se):``;(T||w)&&K&&(G=`${G} · ${K}`);let ue=T&&t.status?.exitCode!==void 0?`exit ${t.status.exitCode}`:``,de=_s(e.argumentsText),fe=e.name===`bash`?de.command:void 0,pe=gs({name:e.name,argumentsText:e.argumentsText,hints:de,isCollapsed:!_}),q=pe?`${e.name}(${pe.text})`:`${e.name}()`;gh({blockId:e.id,view:t,statusClass:le,statusLabel:G,duration:K,durationMs:se,startTimestamp:ce.start,endTimestamp:ce.end,exitHint:ue,isError:E,isBash:S,onKillBash:r,t:d});let me=()=>{e.argumentsText&&y(e.argumentsText)};(s??[]).some(e=>e&&e.hidden!==!0&&e.kind!==`divider`);let he=t=>{let n=t.target;if(n instanceof Element&&n.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=[];S&&r&&o.push(ha({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:f?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:C?void 0:[`disabled`]})),o.push(...a),o.length!==0&&(t.preventDefault(),t.stopPropagation(),za({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`){r?.();return}if(t.id===`host:tool-info`){Vp(e.name);return}l?.(t)}}))},ge=()=>{let n=t.result?t.result.content.map(e=>e.type===`text`?e.text:``).join(``):t.liveOutput??``,i=n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,t)=>d(`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=h?Qp(e.argumentsText):null;kf({isThinking:!1,name:e.name,title:q,status:G,statusClass:le,duration:K,durationMs:se,startTimestamp:ce.start,endTimestamp:ce.end,exitHint:ue,hints:de,args:e.argumentsText||``,rawOutput:n,output:i,details:t.result?.details,images:a,isError:E,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,onKillBash:S?r:void 0,presentData:h&&o?{title:o.title,note:o.note,items:o.items}:null})},_e=n=>{h&&!n?.altKey&&hh(e.argumentsText,t.result?.details)||ge()};return(0,$.jsxs)(`div`,{ref:u,className:`toolcall ${le}${j.length>0?` has-images`:``}`,onClick:e=>{If(u.current)&&(e.target?.closest(`button, a, .toolcall-kill, .toolcall-open, .toolcall-image, .file-diff-action-btn, .btn-tag`)||(e.preventDefault(),e.stopPropagation(),_e(e)))},children:[(0,$.jsx)(wp,{open:_,headClassName:`toolcall-head`,toggleClassName:`toolcall-toggle`,titleText:d(_?`collapseMsg`:`expandMsg`),onToggle:()=>{if(If(u.current)){_e();return}m(!g)},onHeadContextMenu:he,icon:ph(e.name),iconClassName:mh(e.name),titleClassName:`toolcall-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`toolcall-status`,title:ue?`${G} · ${ue}`:G,"aria-label":ue?`${G} · ${ue}`:G,children:E?(0,$.jsx)(Be,{}):w?(0,$.jsx)(n,{}):b||T?(0,$.jsx)(kl,{}):(0,$.jsx)(z,{})}),V&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:d(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(Ve,{})}),te&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:f?`包含 Markdown 输出`:`Contains Markdown output`,"aria-label":`markdown output`,children:(0,$.jsx)(Y,{})}),K&&(0,$.jsx)(`span`,{className:`toolcall-duration toolcall-timeout`,style:{marginLeft:-2,fontFamily:`var(--mono)`},title:ue?`${G} · ${ue}`:G,children:K}),pe&&(0,$.jsxs)(`span`,{className:pe.className,title:pe.title??pe.text,children:[pe.prefix,pe.text]}),ee&&(ee.stats.additions>0||ee.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`toolcall-diff-badge`,title:`+${ee.stats.additions} -${ee.stats.deletions}`,children:[ee.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,ee.stats.additions]}),ee.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,ee.stats.deletions]})]}),de.timeout&&(0,$.jsxs)(`span`,{className:`toolcall-timeout`,children:[`⏱ `,de.timeout]}),(0,$.jsx)(`span`,{className:`toolcall-spacer`}),C&&r&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-kill`,title:d(`stopBashTip`),onClick:e=>{e.stopPropagation(),r?.()},children:[(0,$.jsx)(rt,{}),(0,$.jsx)(`span`,{children:d(`stopBash`)})]}),M&&w&&H&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-open`,title:d(`delegateOpenSubagent`),onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:H}))},children:[(0,$.jsx)(we,{}),(0,$.jsx)(`span`,{children:d(`delegateOpenSubagent`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy${v?` copied`:``}`,title:d(`copyArgs`),"aria-label":d(`copyArgs`),onClick:e=>{e.stopPropagation(),me()},children:v?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{})})]}),children:e.name}),j.length>0&&(0,$.jsx)(`div`,{className:`toolcall-images`,children:j.map((e,t)=>{let n=e.dataUrl.startsWith(`/`)?ne(e.dataUrl):e.dataUrl;return(0,$.jsx)(`button`,{type:`button`,className:`toolcall-image`,title:d(`toolImageZoom`),"aria-label":d(`toolImageZoom`),onClick:e=>{e.stopPropagation(),pn({src:n,alt:`tool result image ${t+1}`})},children:(0,$.jsx)(`img`,{crossOrigin:R(n),src:n,loading:`lazy`,decoding:`async`,alt:`tool result image ${t+1}`})},t)})}),_&&(0,$.jsxs)(`div`,{className:`toolcall-body`,children:[h&&re?(0,$.jsx)(Pm,{args:re,details:t.result?.details,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp}):M?(0,$.jsx)(Sh,{args:N}):P&&F?.code?(0,$.jsx)(Ch,{code:F.code,options:F.options,details:t.result?.details,output:A}):I&&L?(0,$.jsx)(zm,{questions:L.questions,details:t.result?.details,output:A,isError:E,waiting:b||T}):B?(0,$.jsx)(ih,{toolName:e.name,argumentsText:e.argumentsText,details:t.result?.details,output:A,isError:E,onOpenInspector:ge}):e.argumentsText&&(0,$.jsx)(`div`,{className:`toolcall-args`,children:fe?(0,$.jsx)(bh,{command:fe}):(0,$.jsx)(`pre`,{children:e.argumentsText})}),e.name===`tool_search`&&(0,$.jsx)(xh,{details:t.result?.details}),A.length>0&&!(I&&L)&&(0,$.jsxs)(`div`,{className:`toolcall-output`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[d(E?`errorOutput`:`output`),(b||T)&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{ref:D,onWheel:e=>{if(e.deltaY<0)O.current=!1;else if(e.deltaY>0&&D.current){let e=D.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(O.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(O.current=!0)},children:A})]}),b&&A.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,d(`waitingOutput`)]}),T&&A.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,d(`waitingModel`)]}),(ce.start!==void 0||ce.end!==void 0)&&(0,$.jsxs)(`div`,{className:`toolcall-time-footer`,children:[(0,$.jsx)(Pt,{className:`toolcall-time-icon`}),(0,$.jsx)(`span`,{className:`toolcall-time-text`,children:ce.start!==void 0&&ce.end!==void 0&&ce.durationMs!==void 0?d(`toolTimeRange`,{start:Dp(ce.start),end:Dp(ce.end),duration:Tp(ce.durationMs)}):ce.end===void 0?ce.start===void 0?``:Dp(ce.start):Dp(ce.end)})]}),c&&c.length>0&&(0,$.jsx)(`div`,{className:`toolcall-footer`,children:c.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:()=>l?.(e),children:[e.icon&&Xg(e.icon),(0,$.jsx)(`span`,{children:n})]},`${e.id}#${t}`)})})]})]})}),yh=(0,Q.memo)(function(e){let t=(0,Q.useRef)(null);return If(t.current)?(0,$.jsx)(_h,{block:e.block,view:e.view,onKillBash:e.onKillBash,uiContextToolCall:e.uiContextToolCall,onUiAction:e.onUiAction,rootRef:t}):(0,$.jsx)(vh,{...e,rootRef:t})});function bh({command:e}){return(0,$.jsxs)(`div`,{className:`termline`,children:[(0,$.jsx)(Ce,{className:`termline-icon`}),(0,$.jsx)(`code`,{children:cd(e)})]})}function xh({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 Sh({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 Ch({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:wh(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)(Ve,{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)(x,{})})]},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 wh(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 Th=Object.freeze({status:`idle`,messages:[]}),Eh=new Map,Dh=new Set,Oh=16;function kh(){for(;Eh.size>Oh;){let e=Eh.keys().next().value;if(e===void 0)break;Eh.delete(e)}}function Ah(){for(let e of Dh)e()}function jh(e,t){let n=(e??``).trim();if(!n)return;let r=Eh.get(n);(!r||r.status!==`loading`&&r.status!==`ready`)&&(Eh.set(n,{status:`loading`,messages:r?.messages??[]}),kh(),Ah(),Z({type:`get_compacted_messages`,compactionMessageId:n,conversationId:t}))}function Mh(e){let t=e.compactionMessageId;t&&(e.error?Eh.set(t,{status:`error`,messages:[],error:e.error}):Eh.set(t,{status:`ready`,messages:e.messages??[]}),kh(),Ah())}function Nh(e){let t=Eh.get(e);return t?(Eh.delete(e),Eh.set(e,t),t):Th}function Ph(e){return Dh.add(e),()=>{Dh.delete(e)}}function Fh(e){return(0,Q.useSyncExternalStore)(Ph,()=>Nh(e),()=>Th)}var Ih=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Lh(e){let t=e.match(Ih);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}var Rh=1568,zh=2097152;function Bh(e){return e.startsWith(`image/`)&&e!==`image/svg+xml`&&e!==`image/svg`}async function Vh(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,Rh/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<=zh)return o}return o}finally{t.close()}}function Hh(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 Uh(e){return Hh(e).join(`
|
|
35
|
+
|
|
36
|
+
`)}function Wh(e){return Gh(Uh(e))}function Gh(e){let t=e.split(`
|
|
37
|
+
`),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(`
|
|
38
|
+
`).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(`
|
|
39
|
+
`).map(e=>e.replace(/[ \t]+/g,` `).replace(/^\s+|\s+$/g,``)).join(`
|
|
40
|
+
`).replace(/\n{3,}/g,`
|
|
41
|
+
|
|
42
|
+
`).trim()}function Kh(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 qh(e){return e==null||!Number.isFinite(e)?``:e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}var Jh=`pi-web-tts`,Yh={enabled:!1,announce:!0,readReplies:!1,streamReplies:!0,rate:1,voiceURI:``,engine:`builtin`};function Xh(){try{let e=localStorage.getItem(Jh);if(!e)return{...Yh};let{voiceCatalog:t,...n}=JSON.parse(e),r={...Yh,...n};r.engine===`builtin`&&t!==`server`&&(r.voiceURI=``);for(let e of[`enabled`,`announce`,`readReplies`,`streamReplies`])typeof r[e]!=`boolean`&&(r[e]=Yh[e]);return r.rate=typeof r.rate!=`number`||!Number.isFinite(r.rate)?Yh.rate:Math.round(Math.max(.5,Math.min(2,r.rate))*10)/10,typeof r.voiceURI!=`string`&&(r.voiceURI=Yh.voiceURI),typeof r.engine!=`string`&&(r.engine=Yh.engine),r}catch{return{...Yh}}}function Zh(e){try{localStorage.setItem(Jh,JSON.stringify({...e,voiceCatalog:`server`}))}catch{}}function Qh(){return typeof Audio<`u`&&typeof fetch==`function`}function $h(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 eg=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=$h(r,0);i&&this.onSentence(i)}}flush(e){if(e.length>this.cursor){let t=$h(e.slice(this.cursor),0);t&&this.onSentence(t),this.cursor=e.length}}reset(){this.cursor=0}};function tg(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 $h((n.content??[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
43
|
+
`))}return``}var ng=!1,rg=null,ig=null,ag=null,og=new Set;function sg(e,t=null){let n=!!e,r=n?t:null;if(ng!==n||rg!==r){ng=n,rg=r;for(let e of og)try{e(n)}catch{}}}function cg(){return ng}function lg(){return ng?rg:null}function ug(e){return og.add(e),()=>og.delete(e)}function dg(e,t=Xh(),n){if(!e)return;fg();let r=(t.engine||`builtin`).trim(),i=vn(r);if(i&&typeof i.play==`function`){let r=!1;sg(!0,n??null);try{let a=i.play({text:e,rate:t.rate,voiceURI:t.voiceURI,onStart:()=>{r||sg(!0,n??null)},onEnd:()=>{r||(r=!0,ig=null,sg(!1))},onError:()=>{r||(r=!0,ig=null,sg(!1))}});ig=()=>{r=!0;try{a?.()}catch{}}}catch{sg(!1)}return}}function fg(){if(ag&&=(ag.stop(),null),ig){try{ig()}catch{}ig=null}sg(!1)}var pg=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();sg(!0,this.sourceId??null),await new Promise(t=>{let n=(this.settings.engine||`builtin`).trim(),r=vn(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 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,ag===this&&(ag=null),sg(!1)}};function mg(e=Xh(),t){fg();let n=new pg(e,t);return ag=n,n}var hg={open:!1,triggerId:``,selectedIds:[],includeTools:!1,includeThinking:!1},gg=hg,_g=[],vg=new Set;function yg(){for(let e of vg)e()}function bg(e){return(e.role===`user`||e.role===`assistant`)&&Uh(e.content).length>0}function xg(e,t=_g){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 Sg(e){if(_g=e,gg.open){let e=xg(gg.selectedIds,_g);e.join(`\0`)!==gg.selectedIds.join(`\0`)&&(gg={...gg,selectedIds:e},yg())}}function Cg(){return gg}function wg(e){return vg.add(e),()=>{vg.delete(e)}}function Tg(){return(0,Q.useSyncExternalStore)(wg,Cg,Cg)}function Eg(){gg.open&&(gg=hg,yg())}function Dg(e){let t=_g.find(t=>t.id===e);if(t&&bg(t)){if(gg.open){gg={...gg,selectedIds:xg([...gg.selectedIds,e])},yg();return}gg={open:!0,triggerId:e,selectedIds:[e],includeTools:!1,includeThinking:!1},yg()}}function Og(e){gg.open&&(gg={...gg,includeTools:e.includeTools??gg.includeTools,includeThinking:e.includeThinking??gg.includeThinking},yg())}function kg(e){if(!gg.open||!_g.filter(bg).map(e=>e.id).includes(e))return;let t=gg.selectedIds.includes(e)?gg.selectedIds.filter(t=>t!==e):xg([...gg.selectedIds,e]);gg={...gg,selectedIds:t},yg()}function Ag({title:e,children:t,...n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(!1),o=(0,Q.useId)(),s=dr({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,cr.createPortal)((0,$.jsx)(`div`,{ref:s.panelRef,id:o,role:`tooltip`,className:`msg-action-tooltip`,style:s.style,children:e}),document.body)]})}var jg=/^(This operation was aborted|Request aborted)$/;function Mg(e){return e.stopReason===`aborted`||e.stopReason===`error`&&jg.test((e.errorMessage??``).trim())}var Ng=/\[\[\s*([A-Za-z][A-Za-z0-9_-]*)\s*:\s*([A-Za-z][A-Za-z0-9_-]*)\s*:(.*?)\s*\]\]/g,Pg=new Set([`todo`,`notify`,`conv`,`rename`,`title`,`action`,`suggest`]),Fg=new Set(Pg);function Ig(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Lg(e){let t=[...e].map(Ig).join(`|`);return RegExp(`[ \\t]*\\[\\[\\s*(?:${t})(?:\\s*:[^\\]]*)?$`,`i`)}var Rg=Lg(Fg);function zg(e){let t=new Set(Pg);for(let n of e)n&&t.add(n.toLowerCase());Fg.clear();for(let e of t)Fg.add(e);Rg=Lg(Fg)}function Bg(e,t=!1){if(!e||!e.includes(`[[`))return e;let n=e.replace(Ng,(e,t,n,r)=>r.includes(`[[`)||!Fg.has(t.toLowerCase())?e:``);return t&&(n=n.replace(Rg,``)),n===e?e:n.replace(/^[ \t]+\n/gm,`
|
|
44
|
+
`).replace(/\n{3,}/g,`
|
|
45
|
+
|
|
46
|
+
`).trim()}function Vg(e){return e.type===`text`&&typeof e.text==`string`?e:null}function Hg(e){return e.type===`thinking`&&typeof e.thinking==`string`?e:null}function Ug(e){return e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`?e:null}function Wg(e){return e.type===`image`&&typeof e.dataUrl==`string`?e:null}function Gg(e){return e.type===`bash`&&typeof e.command==`string`?e:null}function Kg(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(`
|
|
47
|
+
`).trim();return{isNotice:!1,sourceTitle:t,sourceRole:n,address:r,requestId:a,questions:s,userText:l}}return null}function qg(e){return e.imageData||e.imageUrl?`image`:e.uploadPath?`upload`:e.fileData?`file`:`path`}function Jg(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 Yg={edit:(0,$.jsx)(ie,{}),copy:(0,$.jsx)(x,{}),branch:(0,$.jsx)(ke,{}),text:(0,$.jsx)(Y,{}),markdown:(0,$.jsx)(a,{}),image:(0,$.jsx)(Ve,{}),undo:(0,$.jsx)(me,{}),volume:(0,$.jsx)(et,{}),refresh:(0,$.jsx)(ue,{}),x:(0,$.jsx)(Be,{})};function Xg(e){let t=(e??``).trim();return t?Yg[t.toLowerCase()]||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?(0,$.jsx)(`span`,{className:`msg-action-glyph`,children:t}):(0,$.jsx)(Re,{})):(0,$.jsx)(Re,{})}function Zg(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}var Qg=(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:d,messageLabel:f,onRollbackEdit:p,canRollbackEdit:m=!1,editRequest:h,qnIndex:g,qnActive:_,onJump:v,thinkingWrap:y,toolsWrap:b,toolImages:S,searchActive:C,autoExpand:T,uiMessageActions:E,uiContextMessage:D,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,readOnly:j=!1}){let M=W(),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(``),[z,B]=(0,Q.useState)([]),[ee,V]=(0,Q.useState)(!1),te=He(`chatUploadMaxMb`),re=He(`engine`),H=(0,Q.useRef)(0),[ae,U]=(0,Q.useState)([]),oe=e=>U(t=>t.filter(t=>t.id!==e)),[se,ce]=(0,Q.useState)(null),le=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{le.current&&clearTimeout(le.current)},[]);let G=e=>{ce(e),le.current&&clearTimeout(le.current),le.current=setTimeout(()=>ce(t=>t===e?null:t),4e3)};if(e.role===`toolResult`||e.role===`system`)return null;if(e.role===`compactionSummary`)return(0,$.jsx)(t_,{message:e,forceOpen:C,autoExpand:T});let K=e.role===`custom`&&e.customType===`file`,de=K&&e.details?.mode===`quote`?$u(e.details.quote):null,fe=e.details?.quotes,pe=e.role===`user`&&Array.isArray(fe)?fe.map($u).filter(e=>e!==null):[],q=e.details?.attachments,me=e.role===`user`&&Array.isArray(q)?q.filter(t=>t.type!==`image`||!e.content.some(e=>e.type===`image`)):[],he=e.content.map(e=>Vg(e)?.text??``).filter(Boolean).join(`
|
|
48
|
+
`),ge=e.role===`user`?Lh(he):null,_e=ge?ge.userMessage??`skill:${ge.name}`:he.split(`
|
|
49
|
+
`).join(` `).trim(),ve=i&&o&&e.role===`assistant`&&e.content.length===0,J=!j&&e.role===`user`&&!i&&!ve&&!!s,ye=!j&&re===`pi`&&!i&&!N&&(e.role===`user`||e.role===`assistant`),be=()=>{ye&&Z({type:`delete_message`,messageId:e.id})},xe=async e=>{let t=[];for(let n of e){if(!Bh(n.type))continue;if(n.size>te*1024*1024){G(M(`fileTooLarge`,{name:n.name,size:te}));continue}let e=++H.current;U(t=>[...t,{id:e,name:n.name,percent:null}]);try{let e=await Vh(n);if(!e){G(M(`fileLoadFailed`,{name:n.name}));continue}t.push({path:``,imageData:e.data,mimeType:e.mimeType,name:e.name})}catch{G(M(`fileLoadFailed`,{name:n.name}))}finally{oe(e)}}t.length>0&&B(e=>[...e,...t])},Se=async e=>{if(e.size>te*1024*1024){G(M(`fileTooLarge`,{name:e.name,size:te}));return}let t=++H.current;U(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;U(e=>e.map(e=>e.id===t?{...e,percent:n}:e))},i.readAsDataURL(e)})).replace(/^data:[^;]*;base64,/,``)}catch{G(M(`fileLoadFailed`,{name:e.name}));return}finally{oe(t)}B(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)Bh(n.type)?t.push(n):Se(n);t.length>0&&await xe(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),P(!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(ne(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),P(!1)}catch{P(!0),G(M(`fileLoadFailed`,{name:n.find(e=>e.imageUrl)?.name??`image`}))}finally{Ee.current=!1,Te(!1)}}},Oe=()=>{let t=(ge?`/skill:`+ge.name+(ge.userMessage?` `+ge.userMessage:``):e.content.map(e=>Vg(e)?.text??``).filter(Boolean).join(`
|
|
50
|
+
`)).trim(),n=!!(d&&d.length>0);(t||n)&&(I(t),B(d??[]),De(t,d??[]))},ke=()=>{I(ge?`/skill:${ge.name}${ge.userMessage?` ${ge.userMessage}`:``}`:e.content.map(e=>Vg(e)?.text??``).filter(Boolean).join(`
|
|
51
|
+
`)),B(d??[]),P(!0)};(0,Q.useEffect)(()=>{h&&J&&ke()},[h]);let Ae=()=>{J?ke():p?.(e.id)},je=!j&&!i&&!N&&(J||m),Me=()=>{let e=F.trim();(e||z.some(e=>e.mode===`quote`&&$u(e.quote)))&&De(e,z)},Ne=!E||E.some(e=>e?.id===`host:msg-copy`&&e.hidden!==!0),Pe=(0,Q.useRef)(null),[Fe,Ie]=(0,Q.useState)(null),Le=Tg(),Re=(0,Q.useRef)(0),ze=Uh(e.content),Ue=(e.role===`assistant`||e.role===`user`)&&ze.length>0,We=async t=>{try{let n=!1;if(t===`host:msg-copy-text`)n=await Gd(Wh(e.content));else if(t===`host:msg-copy-markdown`)n=await Gd(ze);else{Dg(e.id);return}window.clearTimeout(Re.current),Ie({id:t,ok:n}),Re.current=window.setTimeout(()=>Ie(null),1600)}catch{window.clearTimeout(Re.current),Ie({id:t,ok:!1}),Re.current=window.setTimeout(()=>Ie(null),1600)}},X=Zg(Wh(e.content),40)||a_(e.role,M),[Ke,qe]=(0,Q.useState)(cg());(0,Q.useEffect)(()=>ug(qe),[]);let Je=e.role===`assistant`&&Wh(e.content).trim().length>0&&!i&&Qh(),Ye=Je&&lg()===e.id,Xe=()=>{if(Ye){fg();return}dg($h(Wh(e.content),5e3),{...Xh(),enabled:!0},e.id)},[Ze,Qe]=(0,Q.useState)(!1),$e=(0,Q.useRef)(null),tt=dr({open:Ze,anchor:$e,onClose:()=>Qe(!1)}),nt=e=>Je?(0,$.jsxs)(Ag,{type:`button`,className:`msg-action${Ye?` msg-action-speaking`:``}`,title:M(Ye?`stopSpeakingMsg`:`speakMsg`),"aria-label":M(Ye?`stopSpeakingMsg`:`speakMsg`),onClick:Xe,children:[Ye?(0,$.jsx)(rt,{}):(0,$.jsx)(et,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:M(Ye?`stopSpeakingMsg`:`speakMsg`)})]},e):null,it=()=>ra.filter(e=>e.slot===`contextmenu.message`).map(e=>({id:e.id,slot:e.slot,source:`host`,label:M(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:[]})),at=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=(D&&D.length>0?D:it()).map(t=>{if(t.source!==`host`)return j?{...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=zl(window.location.hash)?.sessionId;return!j&&!i&&n&&e.id?t:{...t,hidden:!0}}case`host:msg-ctx-reask`:case`host:msg-ctx-edit-reask`:return J?t:{...t,hidden:!0};case`host:msg-ctx-rollback`:return je?t:{...t,hidden:!0};case`host:msg-ctx-fork`:return!j&&!i&&!N?t:{...t,hidden:!0};case`host:msg-ctx-delete`:return ye?t:{...t,hidden:!0};case`host:msg-ctx-speak`:return Je?Ye?{...t,label:M(`stopSpeakingMsg`),icon:`square`}:t:{...t,hidden:!0};default:return t}});Xa(a).length!==0&&(t.preventDefault(),za({x:t.clientX,y:t.clientY,slot:`contextmenu.message`,target:{id:e.id,kind:`message`,label:X},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=zl(window.location.hash)?.sessionId;t&&e.id&&Gd(Vl(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`:Z({type:`fork_session`,messageId:e.id,position:`at`});return;case`host:msg-ctx-rollback`:Ae();return;case`host:msg-ctx-delete`:be();return;case`host:msg-ctx-speak`:Xe();return;default:A?.(t);return}}}))},ot=(e,t)=>{if(!Ue)return null;let n=[{id:`host:msg-copy-markdown`,label:M(`copyMarkdown`),icon:(0,$.jsx)(a,{})},{id:`host:msg-copy-text`,label:M(`copyText`),icon:(0,$.jsx)(Y,{})},{id:`host:msg-copy-image`,label:M(`copyImage`),icon:(0,$.jsx)(Ve,{})}].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=Fe!==null,i=Fe?.ok;return(0,$.jsxs)(`div`,{ref:$e,className:`msg-copy-group${Ze?` has-open-dropdown`:``}`,children:[(0,$.jsxs)(Ag,{type:`button`,className:`msg-action msg-copy-main-btn${i?` msg-copy-success`:``}`,title:M(i?`copied`:r&&!i?`copyFailed`:`copyMarkdown`),"aria-label":M(`copyMarkdown`),onClick:()=>void We(`host:msg-copy-markdown`),children:[i?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{}),(0,$.jsx)(`span`,{className:`msg-action-label`,children:M(i?`copied`:`copy`)})]}),(0,$.jsx)(Ag,{type:`button`,className:`msg-action msg-copy-caret-btn${Ze?` active`:``}`,title:M(`moreCopyOptions`),"aria-label":M(`moreCopyOptions`),"aria-expanded":Ze,onClick:e=>{e.stopPropagation(),Qe(e=>!e)},children:(0,$.jsx)(L,{className:`msg-copy-caret-icon${Ze?` open`:``}`})}),Ze&&(0,cr.createPortal)((0,$.jsx)(`div`,{ref:tt.panelRef,style:tt.style,className:`msg-copy-dropdown`,role:`menu`,children:n.map(e=>(0,$.jsxs)(Ag,{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)},st=()=>{if(!E){let e=ot(`fb-copy`),t=nt(`fb-speak`);if(!J&&!e&&!t)return null;let n=[];return J&&n.push((0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`reaskDirectlyTip`),"aria-label":M(`reaskDirectly`),onClick:Oe,children:[(0,$.jsx)(ue,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:M(`reaskDirectly`)})]}),(0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`editReaskTip`),"aria-label":M(`editReask`),onClick:ke,children:[(0,$.jsx)(ie,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:M(`editReask`)})]})]},`fb-reask`)),e&&n.push(e),t&&n.push(t),n}let t=[],n=!1;return E.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=ot(`copy-dropdown`,E);e&&t.push(e)}return}if(r.id===`host:msg-speak`){let e=nt(o);e&&t.push(e);return}if(r.id===`host:msg-delete`){if(!ye)return;t.push((0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:be,children:[Xg(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-reask`){if(!J)return;t.push((0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`reaskDirectlyTip`),"aria-label":s,onClick:Oe,children:[Xg(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-edit-reask`){if(!J)return;t.push((0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`editReaskTip`),onClick:ke,children:[Xg(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-fork`){if(j||i||N)return;t.push((0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`forkSessionTip`),"aria-label":s,onClick:()=>Z({type:`fork_session`,messageId:e.id,position:`at`}),children:[Xg(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(r.id===`host:msg-rollback`){if(!je)return;t.push((0,$.jsxs)(Ag,{type:`button`,className:`msg-action`,title:M(`rollbackSessionTip`),"aria-label":s,onClick:()=>{Ae()},children:[Xg(r.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:s})]},o));return}if(!j){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=>A?.(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)(Ag,{type:`button`,className:`msg-action`,title:s,"aria-label":s,onClick:()=>A?.(r),children:[Xg(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},ct=()=>{let e=st();return e?(0,$.jsx)(`div`,{className:`msg-actions${Ze?` has-open-dropdown`:``}`,children:e}):null},lt=e.role===`custom`&&(e.customType===`goal-review`||e.customType===`goal-wizard`),ut=e.role===`custom`&&e.customType===`goal-wizard`,dt=e.role===`custom`&&!!e.customType&&e.customType!==`file`&&!lt&&Cf(e.customType),ft=dt?JSON.stringify({customType:e.customType,details:e.details??{}}):``,pt=Le.open&&Le.selectedIds.includes(e.id),mt=Le.open&&Ue,ht=pt&&Le.includeThinking,gt=pt&&Le.includeTools,_t=!N&&(e.role===`user`||Ue),vt=(0,Q.useMemo)(()=>{if(e.role!==`assistant`)return-1;for(let t=e.content.length-1;t>=0;t--)if(Vg(e.content[t]))return t;return-1},[e.role,e.content]),yt=(0,Q.useMemo)(()=>{if(e.role!==`user`)return null;for(let t of e.content){let e=Vg(t);if(e){let t=Kg(e.text);if(t)return t}}return null},[e.role,e.content]);return(0,$.jsxs)(`div`,{ref:Pe,className:`msg msg-${e.role}${yt?yt.isNotice?` msg-collab-notice`:` msg-collaboration`:``}${lt?` msg-goal-review`:``}${pt?` msg-export-selected`:``}${j?` msg-readonly`:``}${f&&e.id.startsWith(`group-`)?` msg-group`:``}`,"data-role":e.role,"data-msg-id":e.id,onContextMenu:at,children:[mt&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:pt,title:M(`copyImage`),"aria-label":M(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>kg(e.id)}),(0,$.jsxs)(`div`,{className:`msg-meta`,children:[u&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-collapse-btn`,title:M(`collapseMsg`),onClick:()=>u(e.id),children:[(0,$.jsx)(w,{}),` `,M(`collapseMsg`)]}),(0,$.jsx)(`span`,{className:`msg-role`,children:e.role===`custom`?ut?M(`goalWizardCard`):lt?M(`goalBarTitle`):e.customType===`file`?M(`attachment`):`${M(`plugin`)} · ${e.customType??M(`unknown`)}`:yt?yt.isNotice?`${M(`subagentBadge`)} · 完成通知`:`${M(`subagentBadge`)} · ${yt.sourceTitle||yt.sourceRole||M(`subagentBadge`)}`:a_(e.role,M)}),f&&(0,$.jsx)(`span`,{className:`msg-sender`,"data-initial":Array.from(f)[0],children:f}),e.model&&(0,$.jsx)(`span`,{className:`msg-model`,children:e.model}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:o_(e.timestamp)}),g!==void 0&&v&&(0,$.jsxs)(`button`,{type:`button`,className:`qn-tag ${_?`active`:``}`,title:`${g+1}. ${_e}`,"aria-label":`${g+1}. ${_e}`,onClick:()=>v(e.id),children:[(0,$.jsx)(`span`,{className:`qn-tag-bar`}),(0,$.jsx)(`span`,{className:`qn-tag-idx`,children:g+1})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:N?(0,$.jsxs)(`div`,{className:`msg-editor${ee?` drag-over`:``}`,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),V(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||V(!1)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),V(!1),Ce(Array.from(e.dataTransfer?.files??[]))},children:[z.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-images`,children:z.map((e,t)=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(ld,{quote:e.quote,onRemove:()=>B(e=>e.filter((e,n)=>n!==t))},`quote-${t}`);let n=qg(e),r=e.imageUrl,i=r?ne(r):`data:${e.mimeType??`image/png`};base64,${e.imageData}`;return(0,$.jsxs)(`span`,{className:`msg-editor-img ${n===`image`?``:`file-chip`}`,title:Jg(e,M),children:[n===`image`?(0,$.jsx)(`img`,{crossOrigin:R(i),src:i,alt:e.name,className:`msg-editor-img-clickable`,title:M(`toolImageZoom`),onClick:()=>pn({src:i,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:M(`removeAttachment`),onClick:()=>B(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(Be,{})})]},`${e.name??e.path??`att`}-${t}`)})}),ae.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:ae.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?M(`uploadPreparing`,{name:t}):M(`uploadReading`,{name:t,percent:n}),style:{width:64,flexShrink:0}}),(0,$.jsx)(`span`,{style:{overflowWrap:`anywhere`,minWidth:0},children:n===null?M(`uploadPreparing`,{name:t}):M(`uploadReading`,{name:t,percent:n})})]},e))}),se&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,children:se}),(0,$.jsx)(`textarea`,{className:`msg-editor-input`,value:F,autoFocus:!0,placeholder:M(`editPlaceholder`),rows:Math.max(2,Math.min(10,F.split(`
|
|
52
|
+
`).length+1)),onChange:e=>I(e.target.value),onPaste:e=>{let t=[];for(let n of e.clipboardData?.items??[])if(n.kind===`file`&&Bh(n.type)){let e=n.getAsFile();e&&t.push(e)}t.length!==0&&(e.preventDefault(),xe(t))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),Me()):e.key===`Escape`&&P(!1)}}),(0,$.jsxs)(`div`,{className:`msg-editor-actions`,children:[(0,$.jsxs)(`span`,{className:`msg-editor-hint`,children:[(0,$.jsx)(Ve,{}),` `,M(`editAttachmentHint`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn sm`,onClick:()=>P(!1),children:M(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary sm`,disabled:we||!F.trim()&&!z.some(e=>e.mode===`quote`&&$u(e.quote)),title:M(`reaskFromHere`),onClick:Me,children:[(0,$.jsx)(ie,{}),` `,M(`reaskFromHere`)]})]})]}):(0,$.jsxs)($.Fragment,{children:[Mg(e)?(0,$.jsx)(`div`,{className:`msg-stopped`,role:`status`,children:M(`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:M(`retryLastTip`),onClick:l,children:[(0,$.jsx)(ue,{}),` `,M(`retryNow`)]})]}),pe.map((e,t)=>(0,$.jsx)(ld,{quote:e,forceOpen:C},`quote-${t}`)),me.length>0&&(0,$.jsx)(`div`,{className:`msg-queued-atts-bar`,children:me.map((t,n)=>{let r;if(t.url)r=t.url.startsWith(`/`)?ne(t.url):t.url;else if(t.type===`image`||t.type===`vision-bridge`){let n=d?.find(e=>e.name===t.name||e.imageData||e.imageUrl);if(n?.imageUrl)r=ne(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(`/`)?ne(t.dataUrl):t.dataUrl)}}let i=!!(t.path&&t.type!==`page`&&t.type!==`conversation`&&t.type!==`canvas`),a=!!(r||i),o=()=>{r?pn({src:r,alt:t.name}):i&&t.path&&Hf({path:t.path,name:t.name})};return(0,$.jsxs)(`span`,{className:`queued-att-chip${a?` previewable`:``}`,title:a?`${t.name} (${M(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}`)})}),de?(0,$.jsx)(ld,{quote:de,forceOpen:C}):K?(0,$.jsx)($g,{message:e,forceOpen:C}):ge?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(r_,{block:ge,forceOpen:C}),ge.userMessage&&(0,$.jsx)(`div`,{className:`msg-text`,children:(0,$.jsx)(rp,{text:ge.userMessage,hardBreaks:!0})}),e.content.map((a,s)=>a.type===`text`?null:(0,$.jsx)(i_,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:b,toolImages:S,thinkingWrap:y,searchActive:C,forceThinking:ht,forceTools:gt,role:e.role,showCopy:Ne,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:s},s))]}):dt?(0,$.jsx)(lp,{type:e.customType??``,code:ft,children:e.content.map((a,s)=>(0,$.jsx)(i_,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:b,toolImages:S,thinkingWrap:y,searchActive:C,forceThinking:ht,forceTools:gt,role:e.role,showCopy:Ne,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:s},s))}):e.content.map((a,s)=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(i_,{block:a,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:o,isTrailingBlock:s===e.content.length-1,onKillBash:c,toolsWrap:b,toolImages:S,thinkingWrap:y,searchActive:C,forceThinking:ht,forceTools:gt,role:e.role,showCopy:Ne,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:s}),s===vt&&_t&&ct()]},s)),ve&&(0,$.jsx)(`div`,{className:`thinking-wait minimal`,title:M(`thinkingWait`),"aria-label":M(`thinkingWait`),role:`status`,children:(0,$.jsx)(`span`,{className:`dot`})})]})}),_t&&vt<0&&ct()]})});function $g({message:e,forceOpen:t=!1}){let n=W(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=Kd({duration:1200}),s=r||t,c=e.details??{},l=c.name??c.path??n(`attachment`),u=c.type===`folder`,d=c.mode===`canvas`,f=c.mode===`reference`||d,p=c.mode===`bridged`,m=c.mode===`page`,g=c.mode===`conversation`,_=c.path&&/^https?:\/\//i.test(c.path.trim())?c.path.trim():null,v=e_(e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
53
|
+
`)),y=e.content.find(e=>e.type===`image`),b=v.split(`
|
|
54
|
+
`).length,S=!f&&!m&&!g&&v.length>0;return(0,$.jsxs)(`div`,{className:`attachcard ${f?`reference`:``}${m?` page`:``}${g?` conversation`:``}`,children:[(0,$.jsx)(wp,{open:s,headClassName:`attachcard-head`,titleText:n(s?`collapseMsg`:`expandMsg`),onToggle:()=>i(e=>t?!0:!e),toggle:!f&&!m&&!g?(0,$.jsx)(`span`,{className:`chead-toggle`,children:s?(0,$.jsx)(L,{}):(0,$.jsx)(h,{})}):null,icon:d?`◈`:u?`📁`:m?`🌐`:g?`💬`:`📎`,iconClassName:`attachcard-icon`,titleClassName:`attachcard-name`,after:(0,$.jsxs)($.Fragment,{children:[c.path&&(m&&_?(0,$.jsx)(`a`,{className:`attachcard-path attachcard-link`,href:_,target:`_blank`,rel:`noreferrer`,children:c.path}):!m&&!g&&!u?(0,$.jsx)(`span`,{className:`attachcard-path attachcard-path-clickable`,title:n(`fileOpenPreview`),onClick:e=>{e.stopPropagation(),Hf({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`:f?`ref`:m?`page`:g?`conversation`:p?`bridged`:`inline`}`,children:d?n(`canvasTab`):m?n(`attachPageShort`):g?n(`attachConversationShort`):f?u?n(`folderRefShort`):`${n(`refOnlyShort`)} · ${qh(c.size)}`:p?n(`bridgedVision`):y?n(`image`):c.mode===`lines`?n(`inlineLinesRange`,{start:c.startLine??1,end:c.endLine??c.lines??1}):n(`inlineLines`,{n:c.lines??b})}),S&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(a?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:e=>{e.stopPropagation(),o(v)},children:a?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{})})]}),children:l}),!f&&s&&(()=>{let e=y?.dataUrl?y.dataUrl.startsWith(`/`)?ne(y.dataUrl):y.dataUrl:void 0;return p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`attachcard-bridgenote`,children:n(`bridgedVisionDetail`)}),e&&(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{crossOrigin:R(e),src:e,loading:`lazy`,decoding:`async`,alt:l,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>pn({src:e,alt:l})})}),v&&(0,$.jsx)(`pre`,{className:`attachcard-content`,children:v})]}):e?(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{crossOrigin:R(e),src:e,loading:`lazy`,decoding:`async`,alt:l,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>pn({src:e,alt:l})})}):(0,$.jsx)(`pre`,{className:`attachcard-content`,children:v})})(),f&&(0,$.jsxs)(`div`,{className:`attachcard-refnote`,children:[(0,$.jsx)(`span`,{children:u?n(`folderNotExpanded`):n(`fileNotExpanded`,{size:qh(c.size)})}),!u&&c.path&&(0,$.jsxs)(`button`,{type:`button`,className:`attachcard-ref-open`,onClick:()=>Hf({path:c.path,name:l}),children:[(0,$.jsx)(Ne,{}),` `,n(`fileOpenPreview`)]})]})]})}function e_(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 t_({message:e,forceOpen:t=!1,autoExpand:n=!1}){let r=W(),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Kd({duration:1200}),[c,l]=(0,Q.useState)(n);n!==c&&(l(n),n&&a(!0));let u=i||t,d=Fh(e.id),[f,p]=(0,Q.useState)(!1),m=()=>{f?p(!1):(p(!0),d.status===`idle`&&jh(e.id))},g=e.content.map(e=>Vg(e)?.text??``).filter(Boolean).join(`
|
|
55
|
+
`),_=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:o_(e.timestamp)})]}),(0,$.jsxs)(`div`,{className:`compaction-card${i?` expanded`:``}`,children:[(0,$.jsx)(wp,{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)(L,{}):(0,$.jsx)(h,{})}),icon:(0,$.jsx)(Le,{}),iconClassName:`compaction-icon`,titleClassName:`compaction-title`,after:g&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:r(o?`copied`:`copyMessage`),"aria-label":r(`copyMessage`),onClick:e=>{e.stopPropagation(),s(g)},children:o?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{})}),children:_?r(`compactionFrom`,{tokens:_}):r(`role.compaction`)}),u&&(0,$.jsxs)(`div`,{className:`compaction-body`,children:[(0,$.jsx)(rp,{text:g}),(0,$.jsx)(`div`,{className:`compaction-hint`,children:r(`compactionKeptHint`)}),(0,$.jsx)(`div`,{className:`compacted-history-action`,children:(0,$.jsxs)(`button`,{type:`button`,className:`compacted-history-toggle-btn`,onClick:m,"aria-expanded":f,children:[(0,$.jsx)(`span`,{className:`compacted-history-chevron`,children:f?(0,$.jsx)(L,{}):(0,$.jsx)(h,{})}),(0,$.jsx)(Pt,{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)(n_,{messages:d.messages})]})]})]})]})}function n_({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)(Le,{}),` `,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)(Qg,{message:e,toolResults:n,liveOutputs:r,toolStatuses:r,streaming:!1,isLast:!1,readOnly:!0},e.id))})]})}function r_({block:e,forceOpen:t=!1}){let n=W(),[r,i]=(0,Q.useState)(!1),{copied:a,copy:o}=Kd({duration:1200}),s=r||t;return(0,$.jsxs)(`div`,{className:`skillcard${r?` expanded`:``}`,children:[(0,$.jsx)(wp,{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)(L,{}):(0,$.jsx)(h,{})}),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)(Ge,{}):(0,$.jsx)(x,{})})]}),children:e.name}),s&&(0,$.jsx)(`div`,{className:`skillcard-body`,children:(0,$.jsx)(rp,{text:e.content})})]})}function i_({block:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:i,isLast:a,isTrailingBlock:o,onKillBash:s,thinkingWrap:c,toolsWrap:l,toolImages:u,searchActive:d,forceThinking:f,forceTools:p,role:m,showCopy:h,uiContextToolCall:g,uiToolCardFooter:_,onUiAction:v,parentTimestamp:y,parentDurationMs:b,parentId:S,blockIndex:C}){let w=W(),{copied:T,copy:E}=Kd({duration:1200}),D=o??!0,O=Vg(e),k=!!(O&&i&&a&&D),A=(0,Q.useRef)(k);A.current=k;let j=(0,Q.useRef)(k);k&&(j.current=!0);let M=()=>typeof document<`u`&&document.hidden,[N,P]=(0,Q.useState)(()=>k&&!M());(0,Q.useEffect)(()=>{k&&!M()?P(!0):!k&&M()&&P(!1)},[k]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{A.current||P(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let F=(0,Q.useCallback)(()=>{A.current||P(!1)},[]);if(O){let e=m===`user`?O.text:Bg(O.text,k);if(!e.trim())return null;let t=e===O.text?O:{...O,text:e},n=m===`user`?Kg(O.text):null,r=(m===`assistant`||m===`user`)&&h!==!1,i=r&&!t.text.includes(`
|
|
56
|
+
`)&&!t.truncated,a=n&&!n.isNotice?(0,$.jsxs)(`div`,{className:`collab-request-box`,children:[n.userText?(0,$.jsx)(rp,{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})]})]}):m===`user`?(0,$.jsx)(rp,{text:t.text,hardBreaks:!0}):k||N||j.current?(0,$.jsx)(Cp,{text:t.text,finishing:!k&&N,onSettled:F}):(0,$.jsx)(rp,{text:t.text}),o=r?(0,$.jsx)(`button`,{type:`button`,className:`msg-text-copy${T?` copied`:``}`,title:w(T?`copied`:`copyMessage`),"aria-label":w(`copyMessage`),onClick:()=>{E(t.text)},children:T?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{})},`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:w(`truncated`)})]})})}let I=Hg(e);if(I)return(0,$.jsx)(Ip,{thinking:I.thinking,streaming:i&&a&&D,wrap:c,forceOpen:d||f,startTimestamp:y,endTimestamp:y!==void 0&&b!==void 0?y+b:void 0,durationMs:b,thinkingId:S===void 0?void 0:`${S}:thinking:${C??0}`});let L=Ug(e);if(L){let e={result:t.get(L.id),liveOutput:n.get(L.id)?.text,streaming:i,status:r.get(L.id)};return(0,$.jsx)(yh,{block:L,view:e,onKillBash:s,wrap:l,showImages:u??!0,forceOpen:d||p,uiContextToolCall:g,uiToolCardFooter:_,onUiAction:v})}let z=Wg(e);if(z&&z.dataUrl){let e=z.dataUrl.startsWith(`/`)?ne(z.dataUrl):z.dataUrl;return(0,$.jsx)(`div`,{className:`msg-image`,children:(0,$.jsx)(`img`,{crossOrigin:R(e),src:e,loading:`lazy`,decoding:`async`,alt:`attachment`,className:`msg-image-clickable`,title:w(`toolImageZoom`),onClick:()=>pn({src:e,alt:`attachment`})})})}let B=Gg(e);return B?(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:cd(B.command)}),B.exitCode!==void 0&&(0,$.jsx)(`span`,{className:`bashblock-exit ${B.exitCode===0?`ok`:`err`}`,children:w(`exitCode`,{code:B.exitCode})}),B.cancelled&&(0,$.jsx)(`span`,{className:`bashblock-exit err`,children:w(`cancelled`)})]}),B.output&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:B.output}),B.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:w(`outputTruncated`)})]}):null}function a_(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 o_(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function s_(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 c_(e,t){let n=e.indexOf(t);return n<0?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function l_(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)]:c_(e,t)}var u_=`echo-`;function d_(e){return`${u_}${e}`}function f_(e){return typeof e==`string`&&e.startsWith(`echo-`)}function p_(){return{adds:[],removes:[],echoes:[]}}function m_(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function h_(e,t){let n=(t??[]).filter(e=>e.mode===`quote`).map(e=>$u(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="${m_(t)}" />`);continue}if(e.mode===`page`){let t=e.path||``,n=e.name||t;i.push(`<browser-page url="${m_(t)}" title="${m_(n)}"></browser-page>`);continue}if(e.mode===`canvas`){i.push(`<canvas-ref id="${m_(e.path)}" title="${m_(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="${m_(t)}"></conversation-ref>`);continue}if(e.path){let t=e.lines?` lines="${e.lines.start}-${e.lines.end}"`:``;i.push(`<file path="${m_(e.path)}"${t} />`)}}return rd(e,i,n,r)}function g_(e){let t=id(e);return`${t.text.trim()}\u0000${t.quotes.map(e=>`${e.role}:${e.messageId}:${e.text.trim()}`).join(`|`)}`}function __(e,t){return e===t||g_(e)===g_(t)}function v_(e,t){let n=0;for(let r of e)__(r,t)&&(n+=1);return n}function y_(e,t){let n=t.trim(),r=0;for(let t of e)t.role===`user`&&(f_(t.id)||(t.content.find(e=>e.type===`text`)?.text??``).trim()===n&&(r+=1));return r}function b_(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 x_(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 S_(e,t,n){let r=n.now??Date.now();if(!t||!x_({state:t,text:n.text,attachments:n.attachments}))return{tracker:e,state:t};let i=(n.text??``).trim(),a=w_(e),o={conversationId:t.conversationId,rawText:i,messageId:T_(a),baselineUserMsgMatches:y_(t.messages,i),createdAt:r},s=E_(o,r);return{tracker:{...e,echoes:[...C_(e),o]},state:{...t,messages:[...t.messages,s]}}}function C_(e){return e.echoes??[]}function w_(e){let t=0;for(let n of C_(e)){let e=Number.parseInt(n.messageId.slice(5),10);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function T_(e){return d_(e)}function E_(e,t){let n=[];return e.rawText&&n.push({type:`text`,text:e.rawText}),{id:e.messageId,role:`user`,content:n,timestamp:t}}function D_(e,t,n){let r=n.now??Date.now();if(!b_({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=h_(n.text,n.attachments),s=id(o).text.trim(),c=a===`steer`?t.queue.steering:t.queue.followUp,l=e.adds.filter(e=>e.conversationId===t.conversationId&&e.kind===a&&__(e.formattedText,o)).length,u=v_(c,o),d=Math.max(0,u-l),f=y_(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:C_(e)},state:{...t,queue:m}}}function O_(e,t,n){if(!t)return{tracker:e,state:t};let r=n.now??Date.now(),{kind:i,text:a,index:o}=n,s=l_(i===`steer`?t.queue.steering:t.queue.followUp,a,o),c=e.adds,l=c.findIndex(e=>e.conversationId===t.conversationId&&e.kind===i&&__(e.formattedText,a));l>=0&&(c=[...c.slice(0,l),...c.slice(l+1)]);let u=v_(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:C_(e)},state:{...t,queue:f}}}function k_(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(v_(e,t.text)>t.expectedRemainingMatches){let n=l_(e,t.text,t.index);if(n.length===e.length){let r=e.findIndex(e=>__(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}:${g_(s.formattedText)}`,d=l.get(u)??0,f=v_(e,s.formattedText),p=y_(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 A_(e,t){if(!t)return{tracker:e,state:t};let n=t.conversationId,r=e.adds.filter(e=>e.conversationId===n),i=C_(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=l_(a,e.formattedText):o=l_(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:C_(e).filter(e=>e.conversationId!==n)},state:{...t,queue:{steering:a,followUp:o},messages:c}}}function j_(e,t,n=Date.now()){if(C_(e).length===0)return{tracker:e,state:t};if(t.isStreaming){let r=new Set,i=[];for(let a of C_(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===C_(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 C_(e)){if(n-s.createdAt>=15e3){s.conversationId===r&&a.add(s.messageId);continue}if(s.conversationId!==r){i.push(s);continue}if(y_(t.messages,s.rawText)>s.baselineUserMsgMatches){a.add(s.messageId);continue}i.push(s),t.messages.some(e=>e.id===s.messageId)||o.push(E_(s,s.createdAt))}let s=i.length===C_(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 M_(e){let{current:t,source:n,snapshot:r,answered:i,activeConversationId:a,pendingDelivery:o}=e,s=!!(r?.conversationId&&a&&r.conversationId!==a),c=!!(t?.id&&(i.has(t.id)||o?.(t.id))),l=!!(r?.id&&(i.has(r.id)||o?.(r.id,r.owner)));return c||l&&t?.id===r?.id?{changed:!0,question:null,source:`live`}:r&&r.id&&!l&&!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 N_(e,t){return t?`${t}\u0000${e}`:e}var P_=new Map;function F_(e){let t=N_(e.id,e.owner);if(P_.delete(t),P_.set(t,e),P_.size>64){let e=P_.keys().next().value;e!==void 0&&P_.delete(e)}return Z(e)}function I_(e,t){if(t){P_.delete(N_(e,t));return}P_.delete(e);for(let t of P_.keys())t.endsWith(`\u0000${e}`)&&P_.delete(t)}function L_(e,t){if(P_.has(N_(e,t)))return!0;if(!t){for(let t of P_.keys())if(t===e||t.endsWith(`\u0000${e}`))return!0}return!1}function R_(){let e=Array.from(P_.values());for(let t of e)if(!Z(t))return}function z_(){P_.clear()}var B_=new Set,V_=1048576,H_=null,U_=[],W_=0;function G_(e=null){H_=e,U_=[],W_=0}function K_(e){if(B_.add(e),H_!==null&&U_.length){let t=H_,n=U_;U_=[],W_=0;for(let r of n)e(t,r)}return()=>{B_.delete(e)}}function q_(e,t){if(e===H_){if(!B_.size){W_+t.length>V_&&(U_=[],W_=0),t.length<=V_&&(U_.push(t),W_+=t.length);return}for(let n of B_)try{n(e,t)}catch(e){console.error(`[tui-overlay-bridge] listener error:`,e)}}}function J_(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 Y_={},X_=new Set;function Z_(){for(let e of X_)e()}function Q_(e){let t=(e??``).trim();t&&(Y_[t]&&Y_[t].status!==`loading`||(Y_={...Y_,[t]:{name:t,status:`loading`}},Z_(),Z({type:`get_tool_prompt`,name:t})))}function $_(e){let t=typeof e.name==`string`?e.name:``;t&&Y_[t]&&(Y_={...Y_,[t]:J_(e)},Z_())}function ev(e){if(!Y_[e])return;let t={...Y_};delete t[e],Y_=t,Z_()}function tv(e){return X_.add(e),()=>X_.delete(e)}function nv(e){return(0,Q.useSyncExternalStore)(tv,()=>e?Y_[e]??null:null)}function rv(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=`
|
|
57
|
+
:host {
|
|
58
|
+
display: block;
|
|
59
|
+
width: 100%;
|
|
60
|
+
height: 100%;
|
|
61
|
+
box-sizing: border-box;
|
|
62
|
+
color: var(--text, inherit);
|
|
63
|
+
font-family: inherit;
|
|
64
|
+
font-size: var(--text-base, 13.5px);
|
|
65
|
+
line-height: 1.5;
|
|
66
|
+
}
|
|
67
|
+
*, *::before, *::after {
|
|
68
|
+
box-sizing: inherit;
|
|
69
|
+
}
|
|
70
|
+
`,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 iv=`pi-web-ui:plugin-data`;function av(e,t){window.dispatchEvent(new CustomEvent(iv,{detail:{pluginId:e,payload:t}}))}function ov(e){let t=t=>{let n=t.detail;e(n.pluginId,n.payload)};return window.addEventListener(iv,t),()=>window.removeEventListener(iv,t)}var sv=new Map,cv=new Map;function lv(e){let t=cv.get(e);cv.delete(e);try{t?.()}catch(t){console.error(`[plugin:${e}] preload cleanup failed:`,t)}}var uv=new Set,dv=new Set,fv=new Set,pv=-1,mv=null;function hv(){return[...sv.values()]}function gv(){let e=hv();for(let t of uv)t(e)}function _v(){let e=[...dv];for(let t of fv)t(e)}function vv(e){return fv.add(e),e([...dv]),()=>fv.delete(e)}async function yv(e,t){dv.delete(e.id),xv.set(e.id,(xv.get(e.id)??0)+1),_v();let n=await Ev(e,t);return gv(),n}function bv(e){return uv.add(e),e(hv()),()=>uv.delete(e)}var xv=new Map;function Sv(e,t){let n=xv.get(e)??0;return g(`/plugins/${encodeURIComponent(e)}/client/entry.mjs?e=${t}${n>0?`&r=${n}`:``}`)}function Cv(e){let t=Promise.resolve();return(n,r)=>{if(y())return Promise.reject(Error(`Remote plugin clients are unavailable in the native app`));let i=t.then(()=>kn(n,()=>e(r)));return t=i.then(()=>void 0,()=>void 0),i}}var wv=Cv(e=>_d(()=>import(e),[],import.meta.url));async function Tv(e,t,n){if(y()||!e.hasClient||e.error)return null;n?.retry&&xv.set(e.id,(xv.get(e.id)??0)+1);try{let n=await wv(e.id,Sv(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 Ev(e,t){if(y())return!1;try{let n=await wv(e.id,Sv(e.id,t));if(pv!==-1&&t!==pv||mv&&!mv.has(e.id)){try{n.default?.dispose?.()}catch(t){console.error(`[plugin:${e.id}] stale bundle cleanup failed:`,t)}return Sn(e.id),!1}let r=n.default;return r&&typeof r.mount==`function`?(sv.set(e.id,{info:e,module:r}),!0):e.preload?(cv.set(e.id,typeof r?.dispose==`function`?()=>r.dispose?.():void 0),!0):(Sn(e.id),dv.add(e.id),_v(),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(t){return Sn(e.id),dv.add(e.id),_v(),console.error(`[plugin:${e.id}] 客户端加载失败:`,t),!1}}async function Dv(e,t){if(y())return!1;if(sv.has(e.id)||cv.has(e.id))return!0;if(dv.has(e.id)||!e.hasClient)return!1;let n=await Ev(e,t);return gv(),n}async function Ov(e,t){if(y())return;let n=new Set(e.filter(e=>!e.error).map(e=>e.id));if(mv)for(let e of mv)n.has(e)||Ko(e);if(mv=n,Pn(mv),t!==pv){pv=t,Sn(),sv.clear();for(let e of[...cv.keys()])lv(e);dv.clear(),xv.clear(),_v()}let r=new Set(e.map(e=>e.id));for(let t of[...sv.keys()])(!r.has(t)||e.find(e=>e.id===t)?.error)&&(Sn(t),sv.delete(t),xv.set(t,(xv.get(t)??0)+1));for(let t of[...cv.keys()])(!r.has(t)||e.find(e=>e.id===t)?.error)&&(Sn(t),lv(t),xv.set(t,(xv.get(t)??0)+1));for(let e of[...dv])r.has(e)||dv.delete(e);_v(),await Promise.all(e.filter(e=>e.hasClient&&(e.view!==!1||e.preload)&&!e.error&&!sv.has(e.id)&&!cv.has(e.id)&&!dv.has(e.id)).map(e=>Ev(e,t))),gv()}function kv(e,t){return{pluginId:e,send:n=>t({type:`plugin_message`,pluginId:e,payload:n}),onData:t=>ov((n,r)=>{n===e&&t(r)})}}var Av=[`debug`,`info`,`warn`,`error`];function jv(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`get`}}}function Mv(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`clear`}}}function Nv(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`&&Av.includes(String(e.level)))}var Pv=new Map,Fv=new Set;function Iv(){for(let e of[...Fv])try{e()}catch{}}function Lv(e){return Fv.add(e),()=>Fv.delete(e)}function Rv(e){return(Pv.get(e)??[]).map(e=>({...e}))}function zv(e,t){return Nv(t)?(Pv.set(e,t.logs.map(e=>({ts:e.ts,level:e.level,text:e.text}))),Iv(),!0):!1}var Bv=15e3;function Vv(e){return(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase()}function Hv(e,t,n=Date.now()){return t.type===`set_cwd`&&t.path?{path:t.path,at:n}:e}function Uv(e,t,n,r=Date.now()){return e.type!==`new_chat`||e.cwd||!t||r-t.at>Bv||Vv(t.path)===Vv(n)?e:{...e,cwd:t.path}}function Wv(e,t){return e&&(t.kind===`snapshot`?Vv(t.cwd)===Vv(e.path)?null:e:t.transitionKind!==`cwd`||t.phase!==`done`&&t.phase!==`error`?e:Vv(t.target)===Vv(e.path)?null:e)}function Gv(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 Kv(e,t){if(Gv(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 qv(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 Jv(e){switch(e){case`error`:return 6500;case`warning`:return 4200;default:return 2400}}var Yv=[/^(已在工作目录|正在切换到工作目录|已切换到工作目录)[::]/,/^(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 Xv(e){if(e.level!==`info`)return!1;let t=(e.text??``).trim(),n=(e.textEn??``).trim();return Yv.some(e=>t&&e.test(t)||n&&e.test(n))}function Zv(e,t,n=2){if(Xv(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 Qv(){return{flows:[],results:{}}}function $v(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 ey(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:$v(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:$v(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 ty(){return r()}var ny=typeof WebSocket<`u`&&WebSocket.OPEN!==void 0?WebSocket.OPEN:1,ry=typeof WebSocket<`u`&&WebSocket.CLOSING!==void 0?WebSocket.CLOSING:2,iy=typeof WebSocket<`u`&&WebSocket.CLOSED!==void 0?WebSocket.CLOSED:3,ay=e=>!!(e&&e.readyState===ny),oy=2e5,sy=`LIVE_OMIT`,cy={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 ly(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 uy(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 dy(e,t,n,r){let i=e.filter(e=>e.id!==t||e.owner!==n);return r&&i.push(r),i}function fy(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:jy(e.state?.cwd,t.engine),projectSessions:{},projectSessionsHasMore:{},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!==55}}case`snapshot`:{let n=e.state?.cwd,r=e.state?.conversationId,i=t.state.cwd,a=e.sessions;i&&i!==n&&(a=jy(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=j_(e.optimisticQueue,t.state),l=k_(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:ly(e.liveOutputs,l.state),toolStatuses:uy(e.toolStatuses,l.state)}}case`earlier_messages`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId)return e;let i=Kv(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=j_(e.optimisticQueue,i),o=k_(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:ly(e.liveOutputs,s),toolStatuses:uy(e.toolStatuses,s)}}case`optimistic_queue_add`:{let n=e.goal.reviewing&&!!(e.state?.conversationId&&e.goal.conversationId===e.state.conversationId),r=D_(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=O_(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=S_(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:Ql(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>oy?`…[${sy}:${r.length-oy}]…\n`+r.slice(r.length-oy):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:s_(n,t.msg)}}case`tool_status`:return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case`notice`:{let n=Zv(e.notices,t.notice),r=(t.notice.level===`error`||t.notice.level===`warning`)&&e.optimisticQueue.adds.length>0?A_(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??t.targetCwd,r=!n||Oy(n)===Oy(e.state?.cwd),i=n=>{let r=e.projectSessionsHasMore??{};if(!!r[n]==!!t.hasMore)return e.projectSessionsHasMore;let i={...r};return t.hasMore?i[n]=!0:delete i[n],i};if(r){Fy(e.state?.cwd,t.sessions,e.engine);let n=Oy(e.state?.cwd);return{...e,sessions:t.sessions,projectSessions:n?{...e.projectSessions??{},[n]:t.sessions}:e.projectSessions,projectSessionsHasMore:n?i(n):e.projectSessionsHasMore}}Fy(n,t.sessions,e.engine);let a=Oy(n);return{...e,projectSessions:{...e.projectSessions??{},[a]:t.sessions},projectSessionsHasMore:i(a)}}case`conversations`:return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case`projects`:{let n=t.projects,r=e.state?.cwd;if(r&&r!==`@root`&&r!==`machine-root`){let e=Oy(r);n.some(t=>Oy(t.path)===e)||(n=[{path:r,lastUsed:0},...n])}return Ey(n),{...e,projects:n}}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=ey({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:dy(e.globalQuestions,t.id,t.owner,t.question)};case`global_approval`:return{...e,globalApprovals:dy(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)??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`project_scripts`:return{...e,projectScripts:{cwd:t.cwd,scripts:t.scripts}};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_cli_paste_result`:return{...e,nativeCliPasteResult:t.result};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.map(e=>({...e,ownerKind:e.ownerKind??`client`,conversationId:r}));return r!==n&&i.push(...e.terminals.filter(e=>e.ownerKind===`conversation`&&e.conversationId===n)),{...e,terminals:i}}case`terminal_active`:return{...e,terminalActiveId:t.id};case`transition_start`:{let n=t.kind===`cwd`?jy(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,previewConversationId:n.conversationId??(r?.target===n.target?r.previewConversationId:void 0),previewSessionFile:n.sessionFile??(r?.target===n.target?r.previewSessionFile:void 0),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 py=`pi-web-client-id`,my=`pi-web-client-id:`,hy=`__PI_CID__:`,gy=null;function _y(){try{if(typeof window<`u`&&typeof window.name==`string`&&window.name){let e=window.name;if(e.startsWith(my)){let t=e.slice(17).trim();if(t)return t}let t=e.indexOf(hy);if(t!==-1){let n=e.slice(t+11).trim();if(n)return n}}}catch{}try{if(typeof sessionStorage<`u`){let e=sessionStorage.getItem(py);if(e)return e}}catch{}return null}function vy(e){try{if(typeof window<`u`){let t=typeof window.name==`string`?window.name:``;if(!t||t.startsWith(my))window.name=`${my}${e}`;else{let n=t.indexOf(hy),r=n===-1?t:t.slice(0,n);window.name=`${r}${hy}${e}`}}}catch{}try{typeof sessionStorage<`u`&&sessionStorage.setItem(py,e)}catch{}}function yy(){if(gy)return gy;let e=_y();return e||=Ht(),vy(e),gy=e,e}var by=`pi-web-last-cwd`;function xy(){try{return localStorage.getItem(by)}catch{return null}}function Sy(e){try{localStorage.setItem(by,e)}catch{}}function Cy(e){try{let t=localStorage.getItem(by);if(!t)return;let n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase();(t===e||n(t)===n(e))&&localStorage.removeItem(by)}catch{}}var wy=`pi-web-recent-projects`;function Ty(){try{let e=localStorage.getItem(wy);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Ey(e){try{localStorage.setItem(wy,JSON.stringify(e.slice(0,20)))}catch{}}function Dy(e){try{let t=Ty(),n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),r=n(e);Ey(t.filter(e=>n(e.path)!==r))}catch{}}var Oy=e=>e?e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase():``,ky=`pi-web-recent-sessions:`;function Ay(e,t){let n=t??`pi`;return e?`${ky}${n}:${Oy(e)}`:`pi-web-recent-sessions:${n}:default`}function jy(e,t){try{let n=e??xy(),r=Ay(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=Ay(n,e),i=localStorage.getItem(r);if(i){let e=JSON.parse(i);if(Array.isArray(e)&&e.length>0)return e}}let e=`:${Oy(n)}`;for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(ky)&&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[]}}var My=new Map;function Ny(e){let t=My.get(e);if(t)return t;let n=e.toLowerCase().replace(/\\/g,`/`).replace(/\/+$/,``),r=n.replace(/^\/+/,``);return t={normP:n,sdkSlug1:`--${r.replace(/[/:]/g,`-`)}--`,sdkSlugRoot:r.endsWith(`:`)?`--${r.replace(/[/:]/g,`-`)}----`:``,sdkSlug2:`--${r.replace(/[^a-zA-Z0-9]/g,`-`)}--`},My.size>=256&&My.clear(),My.set(e,t),t}function Py(e,t){if(!e||!t)return!0;if(typeof e==`object`&&e.cwd)return Oy(e.cwd)===Oy(t);let n=typeof e==`object`?e.path:e;if(!n||n.startsWith(`conv:`)||n.startsWith(`virtual:`))return!0;let r=n.toLowerCase().replace(/\\/g,`/`),{sdkSlug1:i,sdkSlugRoot:a,sdkSlug2:o}=Ny(t);if(!r.includes(`/`))return!0;let s=r.split(`/`).filter(Boolean).slice(0,-1).find(e=>e.startsWith(`--`)&&e.endsWith(`--`));return!s||s===i||!!a&&s===a||s===o}function Fy(e,t,n){try{let r=e??xy(),i=r?t.filter(e=>Py(e,r)):t,a=Ay(r,n);localStorage.setItem(a,JSON.stringify(i.slice(0,50)))}catch{}}function Iy(e,t,n){try{let r=jy(t,n),i=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),a=i(e);Fy(t,r.filter(e=>i(e.path)!==a),n)}catch{}}function Ly(){return o(T())}function Ry(){let[e,t]=(0,Q.useReducer)(fy,{status:`connecting`,ready:!1,state:null,hostMetrics:null,latencyMs:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:jy(),projectSessions:{},projectSessionsHasMore:{},conversations:[],elsewhere:[],activeConversationId:``,projects:Ty(),files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},defaultModel:null,providerOAuthFlows:[],providerOAuthResults:Qv().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:cy,bgServers:[],projectScripts:null,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:p_()}),n=(0,Q.useRef)(null),r=(0,Q.useRef)(iu()),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;ay(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=A.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 b=(0,Q.useRef)(null),x=(0,Q.useCallback)((e,r)=>{let i=n.current;if(!ay(i))return!1;let a=A.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 o=a.state;if(b.current=Hv(b.current,e),e=Uv(e,b.current,o?.cwd),e.type===`load_earlier_messages`&&o&&(!e.conversationId||e.conversationId===o.conversationId)&&(e={...e,conversationId:o.conversationId,historyGeneration:e.historyGeneration??o.historyGeneration,beforeId:e.beforeId??o.messages[0]?.id,before:e.before??o.historyStart}),(e.type===`new_chat`||e.type===`new_cli_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)&&un(),e.type===`set_cwd`&&e.path){let n=(o?.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(o?.sessionFile),i=n(o?.sessionId),a=n(o?.conversationId),s=n(e.path||e.sessionId),c=s===r||s===i||s===a||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`||e.type===`new_cli_chat`?o&&(e.type===`new_cli_chat`||o.nativeCli||o.messages.length>0||o.isStreaming)&&t({type:`transition_start`,kind:`new_chat`,target:o.cwd,progress:22,text:`正在初始化新对话…`,textEn:`Initializing new chat…`}):e.type===`switch_conversation`&&e.id&&o&&e.id!==o.conversationId&&t({type:`transition_start`,kind:`conversation`,target:e.id,progress:35,text:`正在切换对话…`,textEn:`Switching conversation…`});if(ay(i)){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`}),i.send(JSON.stringify(e)),e.type===`prompt`){if(r?.userInitiated&&(e.text.trim()||e.attachments?.length)){let t=e.targetConversationId||o?.conversationId,n=t?a.conversations.find(e=>e.id===t||e.sessionId===t):null;n?Dl({...n,engine:a.engine,conversationId:n.id},a.conversations):o&&t===o.conversationId&&Dl({...o,engine:a.engine},a.conversations)}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})}else if(e.type===`terminal_cli_paste`){if(e.data?.trim()||e.attachments?.length){let t=e.conversationId||o?.conversationId,n=t?a.conversations.find(e=>e.id===t||e.sessionId===t):null;n?Dl({...n,engine:a.engine,conversationId:n.id},a.conversations):o&&t===o.conversationId&&Dl({...o,engine:a.engine},a.conversations)}}else e.type===`queue_remove`&&t({type:`optimistic_queue_remove`,kind:e.kind,text:e.text,index:e.index});if(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}),p.current.add(e.id),p.current.size>64){let e=p.current.values().next().value;e!==void 0&&p.current.delete(e)}if(e.owner){A.current.chat.question?.id===e.id&&t({type:`question`,question:null});let n=A.current.chat.remoteQuestion;n&&n.id===e.id&&n.owner===e.owner&&t({type:`remote_question`,question:null})}else m.current=`live`,t({type:`question`,question:null})}return!0}return!1},[]),S=(0,Q.useCallback)((e,n)=>{let r=M_({current:A.current.chat.question,source:m.current,snapshot:e,answered:p.current,activeConversationId:n,pendingDelivery:L_});r.changed&&(m.current=r.source,t({type:`question`,question:r.question}))},[]);pt(x);let C=(0,Q.useCallback)(()=>{if(!o.current)return;t({type:`status`,status:`connecting`});let e=new WebSocket(Ly());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:yy(),locale:ty()})))};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)&&!ru(a)){let e=A.current.chat.activeConversationId||A.current.chat.state?.conversationId;if(e&&a.conversationId!==e)return}switch(a.type){case`ready`:{let n=A.current.chat.settings?.autoReload??!0;if(!y()&&n&&a.buildId&&a.buildId!==`20261112T05452`){let e=`pi-web-ui-reloaded-${a.buildId}`;if(!sessionStorage.getItem(e)){sessionStorage.setItem(e,`1`),location.reload();return}}let i=A.current.chat.engine;i&&a.engine&&i!==a.engine&&r.current.clear(),nt({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 o=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:o,engines:a.engines}),a.runId!==void 0&&a.runId!==h.current||a.runId===void 0?(h.current=a.runId??null,p.current.clear(),z_(),t({type:`question`,question:null})):(t({type:`question`,question:null}),R_()),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,b.current=Wv(b.current,{kind:`snapshot`,cwd:a.state.cwd}),t({type:`snapshot`,state:a.state}),S(a.state.pendingQuestion,a.state.conversationId);break;case`snapshot_delta`:{let e=A.current.chat.state;if(e)(e.conversationId!==a.conversationId||e.rev!==a.baseRev)&&g();else{let e=n.current;ay(e)&&e.send(JSON.stringify({type:`get_state`}))}let r=A.current.chat.activeConversationId||e?.conversationId;if(r&&a.conversationId!==r)break;t({type:`snapshot_delta`,msg:a}),S(a.state.pendingQuestion,r||a.conversationId);break}case`earlier_messages`:{let e=A.current.chat.state;if(e?.conversationId!==a.conversationId)break;if(Gv(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`:b.current=Wv(b.current,{kind:`transition`,transitionKind:a.kind,phase:a.phase,target:a.target}),t({type:`transition_progress`,msg:a});break;case`engines_status`:nt({engines:a.engines}),t({type:`engines_status`,engines:a.engines});break;case`sessions`:t({type:`sessions`,sessions:a.sessions,cwd:a.cwd,hasMore:a.hasMore});break;case`native_cli_prompt_submitted`:{let e=A.current.chat,t=e.conversations.find(e=>e.id===a.conversationId||e.sessionId===a.sessionId);t&&Dl({engine:e.engine,cwd:t.cwd,conversationId:t.id,sessionId:a.sessionId,sessionFile:t.sessionFile},e.conversations,a.eventId);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($l,{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`:Up(a);break;case`tool_prompt`:$_(a);break;case`compacted_messages_result`:Mh(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`:G_(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`:q_(a.id,a.ansi);break;case`tui_overlay_close`:G_(),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(I_(a.id,a.owner),t({type:`question_queue_answered`,id:a.id,owner:a.owner}),a.global){t({type:`global_question`,id:a.id,owner:a.owner});break}A.current.chat.remoteQuestion?.id===a.id&&t({type:`remote_question`,question:null});let e=A.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)}}x({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`phone_request`:(async()=>{let e=Qu(),t;if(!e)t={ok:!1,error:`当前页面没有手机操控桥:请在 pi 手机端打开(浏览器/桌面端不支持)。`};else try{t=await e({op:a.op,...a.args===void 0?{}:{args:a.args},timeoutMs:a.timeoutMs})}catch(e){t={ok:!1,error:e instanceof Error?e.message:String(e)}}x({type:`phone_response`,id:a.id,ok:t.ok===!0,...t.ok===!0?t.result===void 0?{}:{result:t.result}:{error:t.error??`手机操作失败`}})})();break;case`native_cli_event`:Zu(a);break;case`terminal_cli_control_result`:qu(a);break;case`terminal_cli_paste_result`:t({type:`terminal_cli_paste_result`,result:a});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??A.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&&zg(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`project_scripts`:t({type:`project_scripts`,cwd:a.cwd,scripts:a.scripts});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===yy()&&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`:Cn(a);break;case`plugin_catalog_sync_result`:bn(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`:zv(a.pluginId,a.payload)||av(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`:Un(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,C()},s)},e.onerror=()=>{}},[]);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail??ty();t&&x({type:`set_locale`,locale:t})};return window.addEventListener(Je,e),()=>window.removeEventListener(Je,e)},[x]),(0,Q.useEffect)(()=>{let n=n=>{let r=e.state?.cwd;r&&n.key&&n.key===Ay(r,e.engine)&&t({type:`sync_cached_sessions`,sessions:jy(r,e.engine)})};return window.addEventListener(`storage`,n),()=>window.removeEventListener(`storage`,n)},[e.state?.cwd,e.engine]),(0,Q.useEffect)(()=>{o.current=!0,C();let e=setInterval(()=>{if(!o.current)return;let e=n.current;ay(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===iy||e.readyState===ry){a.current&&=(clearTimeout(a.current),null),C();return}ay(e)&&(Date.now()-s.current>15e3||!A.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()}},[C]),(0,Q.useEffect)(()=>{let t=e.state?.cwd;if(t){if(!d.current){d.current=!0;let e=xy();if(e&&e!==t){x({type:`set_cwd`,path:e});return}}if(f.current!==t&&(f.current=t,Sy(t),t&&t!==`@root`&&t!==`machine-root`)){let e=Ty(),n=Oy(t);Ey([{path:t,lastUsed:0},...e.filter(e=>Oy(e.path)!==n)])}}},[e.state?.cwd,x]),(0,Q.useEffect)(()=>{nt({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 w=(0,Q.useCallback)(e=>t({type:`dismiss_notice`,id:e}),[]),T=(0,Q.useCallback)(e=>{let n=A.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?x({type:`run_command`,...i,command:e.command}):x({type:`terminal_create`,...i,ownerKind:`client`,title:e.title,cwd:e.cwd,agentBash:e.agentBash,nativeCli:e.nativeCli,locale:ty()}))&&t({type:`terminal_add`,meta:{...e,ownerKind:r}})},[x]),E=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_remove`,id:e,ownerKind:n,conversationId:r}),[]),D=(0,Q.useCallback)((e,n=`client`,r)=>t({type:`terminal_restart`,terminalId:e,ownerKind:n,conversationId:r}),[]),O=(0,Q.useCallback)(e=>t({type:`terminal_active`,id:e}),[]),k=(0,Q.useCallback)((e,t,n,i=`client`)=>r.current.register(e,t,n,i),[]),A=(0,Q.useRef)({chat:e,send:x,pushNotice:v,dismissNotice:w,terminal:{create:T,close:E,register:k,restart:D,select:O}});return A.current={chat:e,send:x,pushNotice:v,dismissNotice:w,terminal:{create:T,close:E,register:k,restart:D,select:O}},A.current}function zy({editing:e,children:t,className:n,title:r,...i}){return e?(0,$.jsx)(`div`,{className:`${n??``} renaming`,title:r,children:t}):(0,$.jsx)(`button`,{type:`button`,className:n,title:r,...i,children:t})}var By=/^\[(微信|feishu|飞书|dingtalk|钉钉|wechat|qq|telegram)[^\]]*\]\s*(.*)$/i;function Vy(e,t,n){let r=e.match(By);if(r){let t=r[1].toLowerCase(),i=t.includes(`微信`)||t===`wechat`?n(`lpChannelWechat`):t.includes(`飞书`)||t===`feishu`?n(`lpChannelFeishu`):t.includes(`钉钉`)||t===`dingtalk`?n(`lpChannelDingtalk`):t.toUpperCase();return{cleanTitle:r[2]?.trim()||e,categoryTag:{key:`wechat`,label:i}}}return t.fork?{cleanTitle:e,categoryTag:{key:`fork`,label:n(`lpBadgeFork`)}}:t.scheduler?{cleanTitle:e,categoryTag:{key:`scheduler`,label:n(`lpBadgeScheduler`)}}:t.tui?{cleanTitle:e,categoryTag:{key:`tui`,label:`TUI`}}:{cleanTitle:e,categoryTag:null}}function Hy(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 Uy(e,t){return e&&t.kind===`session`&&!!t.target.pinned}function Wy(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 Gy=`pi-web-ui:lp-collapse-projects`,Ky=`pi-web-ui:lp-collapse-convs`,qy=`pi-web-ui:lp-collapse-sessions`,Jy=`pi-web-ui:lp-collapse-subagents`;function Yy(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Jy);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(Jy,JSON.stringify([...n]))}catch{}return n})},[])]}function Xy(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 Zy=`pi-web-ui:lp-collapse-plugin-sections`;function Qy(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(Zy),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(Zy,JSON.stringify([...n]))}catch{}return n})},[])]}var $y=5,eb=10,tb=20;try{typeof localStorage<`u`&&localStorage.removeItem(`pi-web-ui:lp-visible-counts`)}catch{}var nb=`pi-web-ui:projects-order`;try{typeof localStorage<`u`&&localStorage.removeItem(nb)}catch{}var rb=`pi-web-ui:lp-sizes`,ib={projects:1,groups:1,convs:1,sessions:1},ab=32,ob={running:`pluginRunStatusRunning`,done:`pluginRunStatusDone`,error:`pluginRunStatusError`},sb=72;function cb(){try{return qi(localStorage.getItem(rb),ib)}catch{return{...ib}}}var lb=typeof process<`u`&&(!!{}.VITEST||!1),ub=`pi.leftpanel.conv_tab`;function db(){try{let e=localStorage.getItem(ub);if(e===`running`||e===`stream`||e===`split`)return e}catch{}return lb?`split`:`stream`}var fb=`pi.leftpanel.workspace_tab`;function pb(){try{let e=localStorage.getItem(fb);if(e===`projects`||e===`groups`||e===`split`)return e}catch{}return lb?`split`:`projects`}function mb(e,t){let n=e.subagentVerdict;if(!n||n===`pass`)return null;let r=n===`blocked`?{kind:`blocked`,label:t(`subagentVerdictBlocked`)}:n===`partial`?{kind:`partial`,label:t(`subagentVerdictPartial`)}:{kind:`unverified`,label:t(`subagentVerdictUnverified`)};return(0,$.jsx)(`span`,{className:`category-badge-pill evidence-${r.kind}`,title:t(`subagentVerdictHint`),children:r.label})}function hb({children:e,time:t}){return e?(0,$.jsx)(`span`,{className:`conv-indicator-slot`,children:e}):t?(0,$.jsx)(`span`,{className:`conv-time`,children:t}):null}var gb=(0,Q.memo)(function({sessionFile:e,conversations:t,elsewhere:r,sessions:i,projects:a,activeConversationId:o,sharedConversationOwner:s,activeGroupId:c,projectSessions:l,projectSessionsHasMore:u,engine:d,unreadConvKeys:f,panelSend:p,active:m,collapsible:g,onToggleCollapse:_,pathCompletions:v,uiContextSession:y,quickAskReferenceMenus:b=!0,uiLeftSessions:x,uiContextProject:S,uiProjectsActions:T,uiLeftProject:D,uiRunningActions:O,uiHistoryActions:k,uiSections:A,renderPluginSectionBody:j,uiPluginRunning:M,onPluginRunningAction:N,uiLeftRunning:P,uiLeftHistory:F,onUiAction:I,presetNames:R,transition:z,onOpenSandboxModal:B,onCreateCli:ee}){let V=W(),ne=at(),re=yl(),ie=f??re,H=(0,Q.useCallback)(e=>!ie||ie.size===0?!1:!!(e.id&&(ie.has(e.id)||ie.has(e.id.trim().toLowerCase()))||e.sessionId&&(ie.has(e.sessionId)||ie.has(e.sessionId.trim().toLowerCase()))||e.sessionFile&&(ie.has(e.sessionFile)||ie.has(e.sessionFile.trim().toLowerCase()))||e.path&&(ie.has(e.path)||ie.has(e.path.trim().toLowerCase()))),[ie]),ae=e,U=He(`ready`),oe=He(`tabs`),se=He(`status`),ce=He(`cwd`),le=He(`workspaceRoots`),G=ce,K=Ol(),[ue,de]=(0,Q.useState)(!1),[fe,pe]=(0,Q.useState)(void 0),[q,me]=(0,Q.useState)(null),[he,ge]=(0,Q.useState)(null),[_e,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(``),[Se,Y]=(0,Q.useState)({}),[we,Te]=(0,Q.useState)(``),Ee=(0,Q.useRef)(null);Ee.current=_e;let De=()=>{Ee.current=null,ye(null)},Oe=(e,t,n,r)=>{if(Ee.current!==e)return;Ee.current=null,ye(null);let i=be.trim();i&&i!==r&&(p({...t,name:i}),Y(e=>({...e,[n]:i})),setTimeout(()=>{Y(e=>{if(e[n]!==i)return e;let t={...e};return delete t[n],t})},1e4))};(0,Q.useEffect)(()=>{Y(e=>{let n=Object.keys(e);if(n.length===0)return e;let r={...e},a=!1,o=e=>(i.find(t=>t.path===e)??Object.values(l??{}).flat().find(t=>t.path===e))?.name;for(let i of n){let n=t.find(e=>e.id===i);(n&&n.title===e[i]||o(i)===e[i])&&(delete r[i],a=!0)}return a?r:e})},[i,l,t]);let[ke,Ae]=Xy(Gy,!1),[je,Me]=Xy(Ky,!1),[Ne,Pe]=Xy(qy,!1),[Fe,Le]=Qy(),[Re,ze]=(0,Q.useState)(!1),[Ve,Ue]=Yy(),[We,Ge]=(0,Q.useState)(()=>db());(0,Q.useEffect)(()=>{try{localStorage.setItem(ub,We)}catch{}},[We]);let[X,Ke]=(0,Q.useState)(()=>pb());(0,Q.useEffect)(()=>{try{localStorage.setItem(fb,X)}catch{}},[X]);let[qe,Je]=(0,Q.useState)(!1),Xe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!qe)return;let e=e=>{Xe.current&&!Xe.current.contains(e.target)&&Je(!1)};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[qe]);let[Ze,Qe]=(0,Q.useState)(0),[$e,et]=(0,Q.useState)(60);(0,Q.useEffect)(()=>{et(60)},[G]);let tt=(0,Q.useRef)(new Map),nt=(0,Q.useRef)(null),rt=(0,Q.useRef)(new Set);(0,Q.useLayoutEffect)(()=>{let e=nt.current;if(!e)return;let t=e.querySelectorAll(`.lp-row[data-session-key]`),n=new Map,r=tt.current;t.forEach(e=>{let t=e.getAttribute(`data-session-key`);if(!t)return;let r=!e.closest(`.lp-history-collapsible`),i=e.getBoundingClientRect();n.set(t,{top:i.top,isRunning:r,el:e})});let i=null,a=0;for(let[e,t]of n.entries()){let n=r.get(e);if(n&&!n.isRunning&&t.isRunning){let r=n.top-t.top;if(r>4){i=e,a=r;break}}}if(i){let e=n.get(i);if(e){let t=e.el;t.style.transform=`translateY(${a}px)`,t.style.transition=`none`,t.style.zIndex=`10`,t.style.willChange=`transform`,t.classList.add(`session-row-promoting`),t.offsetHeight,requestAnimationFrame(()=>{t.style.transition=`transform 0.38s cubic-bezier(0.16, 1, 0.3, 1)`,t.style.transform=`translateY(0)`;let e=()=>{t.style.transform=``,t.style.transition=``,t.style.zIndex=``,t.style.willChange=``,t.classList.remove(`session-row-promoting`),t.removeEventListener(`transitionend`,e)};t.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,420)})}for(let[e,t]of n.entries()){if(e===i)continue;let n=r.get(e);if(n&&!n.isRunning&&!t.isRunning){let e=n.top-t.top;if(e>4&&e<80){let n=t.el;n.style.transform=`translateY(${e}px)`,n.style.transition=`none`,n.offsetHeight,requestAnimationFrame(()=>{n.style.transition=`transform 0.32s cubic-bezier(0.16, 1, 0.3, 1)`,n.style.transform=`translateY(0)`;let e=()=>{n.style.transform=``,n.style.transition=``};n.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,360)})}}else if(n&&n.isRunning&&t.isRunning){let e=n.top-t.top;if(Math.abs(e)>4&&Math.abs(e)<120){let n=t.el;n.style.transform=`translateY(${e}px)`,n.style.transition=`none`,n.offsetHeight,requestAnimationFrame(()=>{n.style.transition=`transform 0.32s cubic-bezier(0.16, 1, 0.3, 1)`,n.style.transform=`translateY(0)`;let e=()=>{n.style.transform=``,n.style.transition=``};n.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,360)})}}}}let o=new Map;for(let[e,t]of n.entries())o.set(e,{top:t.top,isRunning:t.isRunning});tt.current=o});let it=(0,Q.useMemo)(()=>{let e=new Set,n=[];for(let t of a){let r=Oy(t.path);e.has(r)||(e.add(r),n.push(t))}if(G&&G!==`@root`&&G!==`machine-root`){let t=Oy(G);e.has(t)||(e.add(t),n.push({path:G,lastUsed:0}))}for(let r of Sl(t,G,o)){if(!r.cwd)continue;let t=Oy(r.cwd);e.has(t)||(e.add(t),n.push({path:r.cwd,lastUsed:0}))}for(let t of r){if(!t.cwd)continue;let r=Oy(t.cwd);e.has(r)||(e.add(r),n.push({path:t.cwd,lastUsed:0}))}return n},[a,G,t,r,o]),ot=hc(),[ct,ut]=(0,Q.useState)(0),dt=(0,Q.useMemo)(()=>{let e=e=>Oy(e.path),t=bc(it.map(e)),n=n=>n.lastUsed>0?n.lastUsed:t.get(e(n))??0,r;if(ot){let t=new Map(it.map(t=>[e(t),t])),n=[];for(let e of vc()){let r=t.get(e);r&&(n.push(r),t.delete(e))}r=[...t.values(),...n]}else r=[...it].sort((t,r)=>n(r)-n(t)||e(t).localeCompare(e(r)));return yc(r.map(e)),r},[it,ot,ct]),pt=(0,Q.useCallback)((e,t,n)=>{let r=Oy(e),i=Oy(t);if(r===i)return;let a=dt.map(e=>Oy(e.path)).filter(e=>e!==r),o=a.indexOf(i);o<0||(a.splice(n?o+1:o,0,r),yc(a),gc()||_c(!0),ut(e=>e+1))},[dt]),[mt,ht]=(0,Q.useState)(null),[gt,vt]=(0,Q.useState)(null),Z=dt,yt=(0,Q.useRef)(null),[bt,xt]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(`pi-web-ui:lp-expanded-projects`);if(e){let t=JSON.parse(e);if(Array.isArray(t))return yt.current=new Set(t),yt.current}}catch{}return new Set});(0,Q.useEffect)(()=>{try{localStorage.setItem(`pi-web-ui:lp-expanded-projects`,JSON.stringify([...bt]))}catch{}},[bt]);let[St,Ct]=(0,Q.useState)({}),wt=(0,Q.useCallback)(e=>{let t=St[Oy(e)]??$y;return Math.max(tb,t+eb)},[St]),[Tt,Et]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>{Et(e=>e.size===0?e:new Set)},[l,i]);let[Dt,Ot]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>{l&&Ot(e=>{if(e.size===0)return e;let t=!1,n=new Set(e);for(let r of e)l[r]!==void 0&&(n.delete(r),t=!0);return t?n:e})},[l]);let kt=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=Oy(G);if(e){if(!kt.current&&(kt.current=!0,yt.current))return;xt(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n}),Ot(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}},[G]);let At=(0,Q.useRef)(new Set),jt=(0,Q.useCallback)(e=>{let t=Oy(e),n=!bt.has(t);if(xt(e=>{let r=new Set(e);return n?r.add(t):r.delete(t),r}),n){let n=wt(e);U&&se===`open`&&p({type:`list_sessions`,path:e,limit:n})&&(At.current.add(t),Ot(e=>new Set(e).add(t)))}else Ot(e=>{if(!e.has(t))return e;let n=new Set(e);return n.delete(t),n})},[p,bt,wt,U,se]);(0,Q.useEffect)(()=>{if(!U||se!==`open`){At.current.clear();return}if(Z.length===0)return;let e=Oy(G);for(let t of Z){let n=Oy(t.path);if(n!==e&&bt.has(n)&&!At.current.has(n)){let e=wt(t.path);p({type:`list_sessions`,path:t.path,limit:e})&&(At.current.add(n),Ot(e=>e.has(n)?e:new Set(e).add(n)))}}},[Z,bt,G,p,wt,U,se]);let Mt=(0,Q.useMemo)(()=>{if(We!==`split`||je||t.length===0)return new Set;let e=new Set;for(let n of t)n.sessionFile&&e.add(Oy(n.sessionFile));return e},[We,je,t]),Nt=(0,Q.useMemo)(()=>Mt.size===0?i:i.filter(e=>!Mt.has(Oy(e.path))),[i,Mt]);(0,Q.useMemo)(()=>{if(Nt.length<=$e)return Nt;let e=Oy(ae),t=e?Nt.findIndex(t=>Oy(t.path)===e):-1,n=t>=$e?t+10:$e;return Nt.slice(0,n)},[Nt,$e,ae]);let Pt=(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]),Ft=(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},[]),Lt=(0,Q.useRef)(null),Rt=(0,Q.useRef)(null),zt=(0,Q.useRef)(()=>{}),Bt=Xa((y??[]).filter(e=>b||e.id!==`host:conv-quick-ask`)).length>0,Vt=(0,Q.useCallback)((e,n,a)=>{Lt.current={x:e,y:n,target:a};let o=a.kind===`running`?a.id:void 0,s=a.kind===`elsewhere`,c=o??(s&&a.id||void 0),l=o?{kind:`conversation`,conversationId:o}:a.kind===`history`&&a.id?{kind:`conversation`,sessionFile:a.id}:s&&c&&a.owner&&r.some(e=>e.owner===a.owner&&e.convId===c)?{kind:`conversation`,conversationId:c,owner:a.owner}:void 0,u=o??(s?c:void 0),d=Pt(t,o),f=d===0?V(`noFinishedSubagents`):V(o?`dismissFinishedSubagentsScoped`:`dismissFinishedSubagents`,{n:d}),p=!!u&&Rt.current===u,m=(y??[]).map(e=>{if(e.source!==`host`)return e;if(e.id===`host:conv-quick-ask`)return b&&l?e:{...e,hidden:!0};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:`)),n=r.some(e=>e.owner===a.owner&&e.convId===c&&e.independent===!1);return s&&c&&a.owner&&!t&&!n?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:f,...d===0?{when:[...e.when??[],`disabled`]}:{}};if(e.id===`host:conv-force-dismiss`)return u?{...e,...p?{label:V(`forceDismissConfirm`)}:{}}:{...e,hidden:!0};if(e.id===`host:conv-pin`){if(a.kind===`history`)return a.pinned??i.find(e=>e.path===a.id)?.pinned?{...e,label:V(`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:V(`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:V(`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||Hl(a.id)?e:{...e,hidden:!0};if(!o)return{...e,hidden:!0};let n=t.find(e=>e.id===o);return n?.sessionId||Hl(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});return Xa(m).length!==0&&(za({x:e,y:n,slot:`contextmenu.session`,target:a,entries:m,onHostAction:(e,t)=>{if(e.id===`host:conv-quick-ask`){l&&jl({reference:l});return}return zt.current(e,t)}}),!0)},[y,b,t,i,r,Pt,V,ne.conversationRef]);zt.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=Lt.current,t=r??(n.kind===`elsewhere`?a:void 0);if(!t||!e)return;if(Rt.current!==t)return Rt.current=t,Vt(e.x,e.y,e.target),!0;Rt.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=Lt.current?.target.pinned??i.find(e=>e.path===n.id)?.pinned;p({type:`pin_session`,path:n.id,pinned:!e});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||Hl(n.id):r?t.find(e=>e.id===r)?.sessionId||Hl(t.find(e=>e.id===r)?.sessionFile):null;if(e){let t=Vl(window.location.href,{sessionId:e});navigator.clipboard?.writeText(t).catch(()=>{})}return}if(e.id===`host:conv-quote`){n.kind===`history`&&n.id?dn({attachments:[{path:``,key:`conv||${n.id}`,name:n.label||n.id,mode:`conversation`,sessionPath:n.id}]}):a&&dn({attachments:[{path:``,key:`conv|${a}|`,name:n.label||a,mode:`conversation`,conversationId:a}]});return}if(e.id===`host:conv-rename`){if(me(null),r){let e=t.find(e=>e.id===r);xe(e?.title??n.label??``),ye(`conv:${r}`)}else if(n.kind===`history`&&n.id){let e=i.find(e=>e.path===n.id);xe(e?.name??n.label??``),ye(n.id)}return}},[p,Vt,t,i]);let Ht=(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(),I?.(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?I?.(e,void 0,n):I?.(e)},children:e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):(0,$.jsx)(`span`,{children:i})},r)})}),Ut=(0,Q.useCallback)((e,t)=>{Wy(e.target)||Bt&&(Rt.current=null,Vt(e.clientX,e.clientY,t)&&(e.preventDefault(),e.stopPropagation()))},[Bt,Vt]),Wt=(0,Q.useRef)(null),[Gt,Kt]=(0,Q.useState)(()=>cb());(0,Q.useEffect)(()=>{try{localStorage.setItem(rb,JSON.stringify(Gt))}catch{}},[Gt]);let qt=(0,Q.useMemo)(()=>{let e=new Set,n=new Set;for(let r of t)r.sessionFile&&e.add(r.sessionFile),n.add(`${r.cwd}\0${r.title}`);let i=[],a=new Set;for(let t of r){if(!t.convId&&t.independent!==!1&&(t.sessionFile&&e.has(t.sessionFile)||n.has(`${t.cwd}\0${t.title}`)))continue;let r=t.convId?`conv:${t.owner}:${t.convId}`:t.sessionFile?`file:${t.sessionFile}`:`title:${t.cwd}\0${t.title}`;a.has(r)||(a.add(r),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,...t.forked?{forked:!0}:{},ownerOffline:!!t.ownerOffline,sessionFile:t.sessionFile,...t.owner&&t.convId?{owner:t.owner,convId:t.convId}:{},...t.hasQuestion?{hasQuestion:!0}:{}}))}return[...t,...i]},[t,r]),Jt=(0,Q.useMemo)(()=>{let e=new Map,t=new Map;for(let t of qt)e.set(t.id,t);for(let n of qt)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 Xl;for(let e of qt){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};r.add(e,s,Yl(e))}return r},[qt]),Yt=(0,Q.useCallback)(e=>e.path.startsWith(`conv:`)&&Jt.has({id:e.path})?Jt.get({id:e.path}):Jt.get(e,Yl(e)),[Jt]),Xt=(0,Q.useMemo)(()=>{let e=Oy(G),t=new Map,n=new Set;for(let e of Sl(qt,G,o))t.set(Oy(e.cwd),e.convs);for(let e of qt)e.parentId&&n.add(e.parentId);let r=new Xl;return Z.map(a=>{let o=Oy(a.path),s=o===e,c=!bt.has(o),f=t.get(o)??[],p=l?.[o],m=!!(i&&i.length>0&&Py(i[0],a.path)),h=jy(a.path,d),g=m?i:p??(h&&h.length>0?h:void 0)??(s?i:[]),_=!s&&p===void 0&&Dt.has(o)&&g.length===0,v=null,y=()=>{if(v)return v;let e=new Xl;for(let t of g)e.add(t,!0);return v=e,e},b=e=>e.isStreaming||e.completionPending||e.hasQuestion||e.isSubagent||e.parentId||n.has(e.id)||e.pinned||e.nativeCli?!0:!e.sessionFile&&!y().has(e),x=Tl(d,a.path);El.observe(x,[...f,...g],!!(U&&(!l||o in l)));let S=El.sort(x,f,e=>e,!1),C=f.some(e=>e.rowKind!==void 0),w=S.filter(e=>e.elsewhere?!0:C?e.rowKind!==`history`:b(e)),T=Cl(w,Ve);for(let e of w)r.add(e,!0);let E=El.sort(x,g.filter(e=>!Py(e,a.path)||r.has(e)?!1:(r.add(e,!0),!0)),e=>e,!1),D=w.filter(e=>e.isStreaming||e.hasQuestion||e.completionPending||!!(e.nativeCli&&e.nativeCli.status?.phase!==`exited`&&e.nativeCli.status?.phase!==`error`&&e.nativeCli.status?.phase!==`disconnected`)).length,O=w.filter(e=>!e.isStreaming&&!e.completionPending&&H({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile})).length,k=E.filter(e=>H({sessionId:e.sessionId,sessionFile:e.path,path:e.path})).length,A=St[o]??$y,j=[];for(let e of T){let t=j.at(-1);e.depth>0&&t?.kind===`conversation`?t.rows.push(e):j.push({kind:`conversation`,target:e.c,rows:[e]})}for(let e of E)j.push({kind:`session`,target:e});let M=El.sort(x,j,e=>e.target,!1).map(e=>({...e,key:El.key(x,e.target)})),N=!!u?.[o];return{serverHasMore:N,p:a,pNorm:o,active:s,isCollapsed:c,isLoadingSessions:_,pRunningRows:T,idleSessions:E,orderedBlocks:M,maxVisible:A,hasMore:!c&&(E.length>A||N),actuallyRunningCount:D,unreadCount:O+k}})},[Z,G,qt,bt,l,i,d,Dt,o,Ve,H,St,u,K,U]),Zt=Gi(Wi(A)).filter(e=>e.shown),Qt=Zt.some(e=>e.key===`groups`),$t=(0,Q.useMemo)(()=>Zt.filter(e=>!(e.key===`convs`||e.key===`sessions`||X!==`split`&&Zt.some(e=>e.key===`projects`)&&e.key===`groups`)),[Zt,X]);(0,Q.useEffect)(()=>{!Qt&&X===`groups`&&Ke(`projects`)},[Qt,X]);let en=(0,Q.useCallback)(e=>e===`projects`?ke||X===`projects`&&a.length===0:e===`convs`?je:e===`sessions`?Ne:e===`groups`?Re:Fe.has(e),[ke,X,a.length,je,Ne,Re,Fe]),tn=(M??[]).reduce((e,t)=>e+t.items.length,0),nn=qt.length+tn;(0,Q.useEffect)(()=>{nn===0&&We===`running`&&Ge(`stream`)},[nn,We]);let rn=(0,Q.useMemo)(()=>$t.filter(e=>e.key===`projects`?X===`split`?a.length>0:a.length>0||Ze>0:e.key!==`convs`&&e.key!==`sessions`).map(e=>e.key),[$t,X,a.length,Ze]),an=()=>{let e=M??[];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:[V(`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:()=>N?.(e,t),children:[(0,$.jsx)(`span`,{className:`lp-plugin-dot st-${t.status}`,title:V(ob[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}`))},on=(0,Q.useMemo)(()=>[...x??[],...P??[]],[x,P]),cn=(0,Q.useMemo)(()=>[...x??[],...F??[]],[x,F]),ln=(0,Q.useCallback)((e,t)=>n=>{n.preventDefault();let r=n.currentTarget,i=n.clientY,a={...Gt},o=Wt.current;if(!o)return;let s=rn.filter(e=>en(e)).length,c=rn.filter(e=>!en(e)).reduce((e,t)=>e+(a[t]??1),0)||1,l=Math.max(120,o.clientHeight-s*ab);r.classList.add(`dragging`),document.body.classList.add(`lp-resizing`);let u=n=>{let{above:r,below:o}=xl({start:{above:a[e]??1,below:a[t]??1},deltaPx:n.clientY-i,availablePx:l,totalWeight:c,minAbovePx:sb,minBelowPx:sb});Kt(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)},[Gt,rn,en]);(0,Q.useEffect)(()=>{m&&U&&se===`open`&&ce&&(p({type:`list_sessions`,limit:wt(ce)}),p({type:`list_projects`}))},[m,U,se,ce,p]);let un=e=>{let t=e.displayName||e.name||e.firstMessage?.trim();return t&&t.length>0?t:V(`emptyChat`)},fn=e=>e.split(/[\\/]/).pop()||e,pn=e=>{let t=e.closest(`[role="tree"]`);return t?[...t.querySelectorAll(`[data-lp-nav]`)].filter(e=>!e.closest(`.lp-history-collapsible.collapsed`)&&!e.disabled):[]},mn=(e,t)=>{let n=pn(e);if(n.length===0)return;let r=n.indexOf(e);n[t===`first`?0:t===`last`?n.length-1:r<0?t>0?0:n.length-1:Math.min(n.length-1,Math.max(0,r+t))]?.focus()},hn=e=>{let t=e.target;if(!t.hasAttribute(`data-lp-nav`))return;let n=t.getAttribute(`data-project-path`);switch(e.key){case`ArrowDown`:case`ArrowUp`:if(e.preventDefault(),e.altKey&&n){let r=dt.map(e=>e.path),i=r.indexOf(n),a=e.key===`ArrowDown`?i+1:i-1;if(i<0||a<0||a>=r.length)return;pt(n,r[a],e.key===`ArrowDown`),requestAnimationFrame(()=>{let e=t.closest(`[role="tree"]`)??document;for(let t of e.querySelectorAll(`[data-project-path]`))t.getAttribute(`data-project-path`)===n&&t.focus()});return}mn(t,e.key===`ArrowDown`?1:-1);return;case`Home`:case`End`:e.preventDefault(),mn(t,e.key===`Home`?`first`:`last`);return;case`ArrowRight`:n&&!bt.has(Oy(n))&&(e.preventDefault(),jt(n));return;case`ArrowLeft`:e.preventDefault(),n?bt.has(Oy(n))&&jt(n):t.closest(`.lp-project-node`)?.querySelector(`[data-project-path]`)?.focus();return}},gn=Xa(S??[]).length>0,_n=(0,Q.useCallback)((e,t)=>{Wy(e.target)||gn&&(e.preventDefault(),e.stopPropagation(),za({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.path,kind:`project`,label:fn(t.path)},entries:S??[]}))},[gn,S]),vn=(e,t,r,i,a,o=!0)=>{let s=q===e;return(0,$.jsx)(`button`,{type:`button`,className:`lp-del ${s?`confirm`:``}`,title:s?r:t,onClick:t=>{t.stopPropagation(),!o||s?(me(null),i()):me(e)},children:s?(0,$.jsx)(n,{}):a??(0,$.jsx)(_t,{})})},yn=(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:V(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)(L,{}):(0,$.jsx)(w,{})})]}),i||a?(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[i,a]}):null]}),bn=rn.filter(e=>!en(e)),xn=bn.reduce((e,t)=>e+(Gt[t]??1),0)||1,Sn=e=>bn.length<=1?1:(Gt[e]??1)/xn*bn.length,Cn=new Map(Ki(rn,en).map(([e,t])=>[e,(0,$.jsx)(`div`,{className:`lp-sash`,role:`separator`,"aria-orientation":`horizontal`,onPointerDown:ln(e,t),onDoubleClick:()=>Kt({...ib}),title:V(`dragToResize`)},`sash-${e}`)])),wn=(0,Q.useCallback)(e=>{let t=e.target;t&&(t.closest(`.lp-row`)||t.closest(`button, input, select, textarea, a`)||(p({type:`new_chat`}),sn()))},[p]),Tn=(e,t)=>{let r=Oy(ae),i=Oy(e.path),a=Yt(e),c=!!(r&&r===i||!s&&o&&a?.conv?.id===o),l=z?.kind===`session`&&Oy(z.target)===i,u=!!a?.isStreaming,d=!!a?.hasQuestion,f=!!(a?.hasError||a?.error),m=!!(e.nativeCli||a?.conv?.nativeCli),h=a?.conv?.nativeCli?.status?.phase,g=!!a?.conv?.nativeCli&&(h===`running`||h===`working`||h===`starting`||!h&&!a?.conv?.error),_=!!a?.conv?.nativeCli&&(h===`waiting_input`||h===`waiting_approval`),v=m&&!g&&!_,y=!!(u||d||a?.conv?.completionPending||a?.conv?.isStreaming||g),b=!c&&!y&&H({id:a?.conv?.id,sessionId:e.sessionId,sessionFile:e.path,path:e.path}),x=Se[e.path]??un(e),{cleanTitle:S,categoryTag:C}=Vy(x,{fork:!!(e.parentSessionPath||a?.conv?.forkFrom||a?.conv?.forked),scheduler:!!(a?.conv?.elsewhere&&a.conv.owner?.startsWith(`scheduler:`)),tui:e.source===`tui`},V),w=i||Oy(e.sessionId)||e.path;return(0,$.jsxs)(`div`,{className:`lp-row`,"data-session-key":w,onMouseLeave:()=>me(t=>t===`sess:${e.path}`?null:t),onContextMenu:t=>Ut(t,{id:e.path,kind:`history`,label:x,pinned:e.pinned}),children:[(0,$.jsxs)(zy,{editing:_e===e.path,className:`session-item lp-tree-session-item ${c?`active`:``} ${l?`switching`:``}${y?` is-running`:``}${b?` is-unread`:``}`,title:e.path,disabled:l,"aria-current":c?`true`:void 0,"data-lp-nav":``,onClick:()=>{if(!(_e||l)){if(vl(e.path),e.sessionId&&vl(e.sessionId),a?.conv?.id&&vl(a.conv.id),a?.conv?.id&&!a.conv.elsewhere){c||p({type:`switch_conversation`,id:a.conv.id});return}c||p({type:`switch_session`,path:e.path})}},children:[c&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:V(`current`)}),m&&(0,$.jsx)(Ce,{size:13,className:`native-cli-conversation-icon${g?` is-running`:v?` is-exited`:_?` is-waiting`:``}`,title:h?`${V(`nativeCli`)} (${V(`nativeCliSession.${h===`waiting_input`?`waitingInput`:h===`waiting_approval`?`waitingApproval`:h}`)||h})`:V(`nativeCli`),"aria-label":V(`nativeCli`)}),_e===e.path?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:be,placeholder:V(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>xe(e.target.value),onKeyDown:t=>{t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing?Oe(e.path,{type:`rename_session`,path:e.path},e.path,x):t.key===`Escape`&&De()},onBlur:()=>Oe(e.path,{type:`rename_session`,path:e.path},e.path,x)}):(0,$.jsx)(`span`,{className:`conv-title-text`,title:x,children:S}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:V(`pinnedConversation`),children:`📌`}),a?.conv?.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:V(`newChatEphemeralTip`),children:V(`newChatEphemeral`)||`临时`}),C&&(0,$.jsx)(`span`,{className:`category-badge-pill ${C.key}`,children:C.label}),(0,$.jsx)(hb,{time:Hy(e.modified),children:l?(0,$.jsx)(kl,{className:`status-spinner-right`}):d||_?(0,$.jsx)(`span`,{className:`status-question-right`,title:h===`waiting_approval`?V(`nativeCliSession.waitingApproval`):V(`nativeCliSession.waitingInput`)||V(`waitingQuestionBadge`),children:`?`}):u||g?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:V(`streaming`)}):f||h===`error`?(0,$.jsx)(`span`,{className:`status-error-right`,title:a?.error||a?.conv?.nativeCli?.status?.error||V(`nativeCliSession.error`),children:`!`}):y?(0,$.jsx)(`span`,{className:`status-pulse-right`,title:V(`tabRunning`)}):b?(0,$.jsx)(`span`,{className:`status-unread-right`,title:V(`completedUnreadTooltip`),children:(0,$.jsx)(n,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})]})]}),q!==`sess:${e.path}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:V(`renameSession`),onClick:t=>{t.stopPropagation(),me(null),xe(e.name??``),ye(e.path)},children:(0,$.jsx)(J,{})}),!u&&vn(`sess:${e.path}`,V(`deleteSession`),V(`deleteSessionConfirm`),()=>{Iy(e.path,G),p({type:`delete_session`,path:e.path})}),Ht(cn,`lp-slot-sessions`)]},e.path)},En=({c:e,depth:r,hasKids:a,isCollapsed:c,descendantCount:u,hasStreaming:d,hasError:f,hasQuestion:m},g)=>{let _=Oy(e.sessionFile||e.sessionId||e.id),v=g?(l?.[Oy(g)]??(Oy(g)===Oy(G)?i:void 0))?.find(t=>!!(e.sessionFile&&Oy(t.path)===Oy(e.sessionFile)||e.sessionId&&t.sessionId&&t.sessionId.trim().toLowerCase()===e.sessionId.trim().toLowerCase())):void 0,y=e.nativeCli?.status?.lastActivityAt??e.nativeCli?.status?.updatedAt,b=Math.max(e.modified??0,v?.modified??0,y??0)||void 0;if(e.elsewhere){let t=e.owner,i=e.convId,l=!!e.pseudo,u=!!e.ownerOffline&&!l,f=!!(typeof t==`string`&&t.startsWith(`scheduler:`)),m=e.independent===!1,g=!!(t&&i)&&(m||f),v=g||!!(t&&i)&&!f&&!m,y=s===t&&o===i,x=!!(e.isStreaming||d||e.completionPending),S=!y&&!x&&H({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),C=!m&&!f&&he===e.id,w=m?e.cwd:f?`${V(`schedulerViewTip`)}\n${e.cwd}`:C?V(`takeoverConfirm`):l?`${V(`lpOpenOnDesktopTip`)}\n${e.cwd}`:`${V(u?`elsewhereOfflineTip`:`elsewhereTip`)}\n${e.cwd}`,{cleanTitle:T,categoryTag:D}=Vy(e.title,{fork:!!(e.forkFrom||e.forked),scheduler:f},V);return(0,$.jsxs)(`div`,{className:`lp-row${r>0?` lp-sub`:``}${a?` lp-has-kids`:``}`,"data-session-key":_,style:r>0?{"--depth":Math.min(r,4)}:void 0,onMouseLeave:()=>{ge(t=>t===e.id?null:t),me(t=>t===`else:${e.id}`?null:t)},onContextMenu:n=>Ut(n,{id:i??e.id,kind:`elsewhere`,label:e.title,...t?{owner:t}:{},...l?{pseudo:!0}:{}}),children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`lp-tree-caret`,title:V(c?`expandSubagents`:`collapseSubagents`),"aria-label":V(c?`expandSubagents`:`collapseSubagents`),"aria-expanded":!c,onClick:t=>{t.stopPropagation(),Ue(e.id)},children:c?(0,$.jsx)(h,{"aria-hidden":`true`}):(0,$.jsx)(L,{"aria-hidden":`true`})}),(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-tree-session-item elsewhere-item${y?` active`:``}${v?``:` elsewhere-static`}${C?` confirm`:``}${x?` is-running`:``}${S?` is-unread`:``}`,title:w,tabIndex:v?0:-1,onClick:v?()=>{if(g){p({type:`open_shared_conversation`,owner:t,id:i});return}if(l){p({type:`take_over_conversation`,owner:t,id:i});return}if(!C){ge(e.id);return}ge(null),p({type:`take_over_conversation`,owner:t,id:i})}:void 0,children:[y&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:V(`current`)}),(0,$.jsx)(`span`,{className:`conv-title-text`,title:e.title,children:C?V(`takeoverConfirm`):T}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:V(`pinnedConversation`),children:`📌`}),e.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:V(`newChatEphemeralTip`),children:V(`newChatEphemeral`)||`临时`}),D&&(0,$.jsx)(`span`,{className:`category-badge-pill ${D.key}`,children:D.label}),f?(0,$.jsx)(`span`,{className:`category-badge-pill scheduler`,children:V(`scheduledTaskBadge`)}):m?null:(0,$.jsx)(`span`,{className:`category-badge-pill elsewhere`,children:V(l?`elsewherePseudoBadge`:`elsewhereBadge`)}),u&&(0,$.jsx)(`span`,{className:`category-badge-pill elsewhere offline`,title:V(`elsewhereOfflineTip`),children:V(`elsewhereOfflineBadge`)}),e.agentPreset&&e.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.agentPreset,children:R?.[e.agentPreset]??e.agentPreset}),mb(e,V),(0,$.jsx)(hb,{time:b?Hy(b):void 0,children:e.hasQuestion?(0,$.jsx)(`span`,{className:`status-question-right${t&&i&&!l?` clickable`:``}`,style:t&&i&&!l?{cursor:`pointer`}:void 0,title:V(`takeoverHasQuestion`),onClick:t&&i&&!l?e=>{e.stopPropagation(),p({type:`peek_elsewhere_question`,owner:t,id:i})}:void 0,children:`?`}):x?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:V(`streaming`)}):e.error?(0,$.jsx)(`span`,{className:`status-error-right`,title:e.error,children:`!`}):S?(0,$.jsx)(`span`,{className:`status-unread-right`,title:V(`completedUnreadTooltip`),children:(0,$.jsx)(n,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})]})]}),Bt&&q!==`else:${e.id}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-elsewhere-act`,style:{right:32},title:V(`elsewhereActions`),onClick:n=>{n.stopPropagation(),Rt.current=null;let r=n.currentTarget.getBoundingClientRect();Vt(r.left,r.bottom+4,{id:i??e.id,kind:`elsewhere`,label:e.title,...t?{owner:t}:{},...l?{pseudo:!0}:{}})},children:(0,$.jsx)(E,{})}),vn(`else:${e.id}`,V(`dismissConversation`),V(`dismissConversationConfirm`),()=>p({type:`dismiss_conversation`,id:i??e.id,force:!0,...t?{owner:t}:{}}),(0,$.jsx)(Be,{}))]},e.id)}let x=!s&&o===e.id,S=!!e.nativeCli,C=e.nativeCli?.status?.phase,w=S&&(C===`running`||C===`working`||C===`starting`||!C&&!e.error),T=S&&(C===`waiting_input`||C===`waiting_approval`),D=S&&(C===`exited`||C===`disconnected`),O=!!(e.isStreaming||d||e.completionPending||w),k=!x&&!O&&H({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),A=`conv:${e.id}`,j=q===A,{cleanTitle:M,categoryTag:N}=Vy(Se[e.id]??e.title,{fork:!!(e.forkFrom||e.forked||v?.parentSessionPath),scheduler:!!(e.elsewhere&&e.owner?.startsWith(`scheduler:`))},V);return(0,$.jsxs)(`div`,{className:`lp-row${r>0?` lp-sub`:``}${a?` lp-has-kids`:``}`,"data-session-key":_,style:r>0?{"--depth":Math.min(r,4)}:void 0,onMouseLeave:()=>me(e=>e===A?null:e),onContextMenu:t=>Ut(t,{id:e.id,kind:`running`,label:e.title}),children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`lp-tree-caret`,title:V(c?`expandSubagents`:`collapseSubagents`),"aria-label":V(c?`expandSubagents`:`collapseSubagents`),"aria-expanded":!c,onClick:t=>{t.stopPropagation(),Ue(e.id)},children:c?(0,$.jsx)(h,{"aria-hidden":`true`}):(0,$.jsx)(L,{"aria-hidden":`true`})}),(0,$.jsxs)(zy,{editing:_e===`conv:${e.id}`,className:`session-item lp-tree-session-item ${x?`active`:``}${O?` is-running`:``}${k?` is-unread`:``}`,title:`${e.title}${g?``:` — ${e.cwd}`}`,"aria-current":x?`true`:void 0,"data-lp-nav":``,onClick:()=>{vl(e.id),e.sessionId&&vl(e.sessionId),e.sessionFile&&vl(e.sessionFile),x||p({type:`switch_conversation`,id:e.id})},children:[e.nativeCli&&(0,$.jsx)(Ce,{size:13,className:`native-cli-conversation-icon${w?` is-running`:D?` is-exited`:T?` is-waiting`:``}`,title:C?`${V(`nativeCli`)} (${V(`nativeCliSession.${C===`waiting_input`?`waitingInput`:C===`waiting_approval`?`waitingApproval`:C}`)||C})`:V(`nativeCli`),"aria-label":V(`nativeCli`)}),x&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:V(`current`)}),_e===`conv:${e.id}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:be,placeholder:V(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>xe(e.target.value),onKeyDown:t=>{t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing?Oe(`conv:${e.id}`,{type:`rename_conversation`,id:e.id},e.id,e.title):t.key===`Escape`&&De()},onBlur:()=>Oe(`conv:${e.id}`,{type:`rename_conversation`,id:e.id},e.id,e.title)}):(0,$.jsx)(`span`,{className:`conv-title-text`,title:e.title,children:M}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:V(`pinnedConversation`),children:`📌`}),e.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:V(`newChatEphemeralTip`),children:V(`newChatEphemeral`)||`临时`}),N&&(0,$.jsx)(`span`,{className:`category-badge-pill ${N.key}`,children:N.label}),e.agentPreset&&e.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.agentPreset,children:R?.[e.agentPreset]??e.agentPreset}),mb(e,V),(0,$.jsx)(hb,{time:b?Hy(b):void 0,children:m||e.hasQuestion||T?(0,$.jsx)(`span`,{className:`status-question-right`,title:C===`waiting_approval`?V(`nativeCliSession.waitingApproval`):V(`nativeCliSession.waitingInput`)||V(`waitingQuestionBadge`),children:`?`}):O?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:V(`streaming`)}):e.error||C===`error`?(0,$.jsx)(`span`,{className:`status-error-right`,title:e.error||e.nativeCli?.status?.error||V(`nativeCliSession.error`),children:`!`}):k?(0,$.jsx)(`span`,{className:`status-unread-right`,title:V(`completedUnreadTooltip`),children:(0,$.jsx)(n,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})]})]}),!j&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:V(`renameSession`),onClick:t=>{t.stopPropagation(),me(null),xe(e.title),ye(A)},children:(0,$.jsx)(J,{})}),(()=>{let r=A,i=j,a=Pt(t,e.id),o=It(t,e.id),s=Ft(t,e.id);return s===0&&!e.isStreaming?e.hasUserTerminals?vn(r,V(`dismissConversation`),V(`dismissTerminalsConfirm`),()=>p({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Be,{})):vn(r,V(`dismissConversation`),V(`dismissConversationConfirm`),()=>p({type:`dismiss_conversation`,id:e.id}),(0,$.jsx)(Be,{}),!e.nativeCli):s===0?vn(r,V(`dismissConversation`),V(`dismissStreamingConfirm`),()=>p({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Be,{})):i?(0,$.jsxs)(`span`,{className:`lp-del-group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt danger`,title:V(`forceDismissTitle`,{n:s,m:o}),onClick:t=>{t.stopPropagation(),me(null),p({type:`dismiss_conversation`,id:e.id,force:!0})},children:V(`dismissForceAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del confirm`,title:o>0&&a>0?V(`dismissFinishedSubagentsScoped`,{n:a}):V(`dismissConversationConfirm`),onClick:t=>{t.stopPropagation(),me(null),p({type:`dismiss_conversation`,id:e.id,withFinishedSubagents:!0})},children:(0,$.jsx)(n,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`lp-del`,title:V(`dismissConversation`),onClick:e=>{e.stopPropagation(),me(r)},children:(0,$.jsx)(Be,{})})})(),Ht(on,`lp-slot-sessions`)]},e.id)},Dn={projects:(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`lp-section panel-projects ${ke||X===`projects`&&a.length===0?`collapsed`:``}`,style:ke?void 0:{flex:`${Sn(`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:Ae,title:V(ke?`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:V(`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 ${X===`groups`?``:`active`}`,onClick:e=>{e.stopPropagation(),Ke(`projects`)},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),Ke(`projects`))},title:V(`tabProjects`),children:[(0,$.jsx)(st,{style:{fontSize:`12.5px`}}),(0,$.jsx)(`span`,{children:V(`tabProjects`)}),(0,$.jsxs)(`span`,{style:{fontSize:`11px`,opacity:.85},children:[`(`,a.length,`)`]})]}),Qt&&(0,$.jsxs)(`span`,{role:`button`,tabIndex:0,className:`lp-conv-tab ${X===`groups`?`active`:``}`,onClick:e=>{e.stopPropagation(),Ke(`groups`)},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),Ke(`groups`))},title:V(`deviceGroups`),children:[(0,$.jsx)(lt,{style:{fontSize:`12.5px`}}),(0,$.jsx)(`span`,{children:V(`deviceGroups`)}),Ze>0&&(0,$.jsxs)(`span`,{style:{fontSize:`11px`,opacity:.85},children:[`(`,Ze,`)`]})]})]})]})}),(0,$.jsxs)(`div`,{className:`lp-section-actions`,ref:Xe,style:{position:`relative`},children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-project-action ${qe?`active`:``}`,title:qe?void 0:V(`openProject`),"aria-label":V(`openProject`),"aria-expanded":qe,onClick:e=>{e.stopPropagation(),Je(e=>!e)},children:(0,$.jsx)(C,{})}),Ht(T,`lp-slot-section`),qe&&(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-new-chat-btn`,title:V(`newChatInCurrentProjectTip`),onClick:()=>{Je(!1),p({type:`new_chat`}),sn()},children:[(0,$.jsx)(Ye,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`newChatAction`)})]}),ee&&(!oe||oe.includes(`terminal`))&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-new-cli-btn`,onClick:()=>{Je(!1),ee(ce)},children:[(0,$.jsx)(Ce,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`nativeCliCreate`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-manage-projects-btn`,onClick:()=>{Je(!1),pe(`local`),de(!0)},children:[(0,$.jsx)(Ie,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`openLocalProject`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-manage-projects-btn`,onClick:()=>{Je(!1),pe(`remote`),de(!0)},children:[(0,$.jsx)(ve,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`openRemoteProject`)})]}),B&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item`,onClick:()=>{Je(!1),B()},children:[(0,$.jsx)(Or,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`sandboxNewShort`)})]}),(0,$.jsx)(`div`,{className:`lp-workspace-menu-divider`}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item`,onClick:()=>{Je(!1),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{create:!0}}))},children:[(0,$.jsx)(lt,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:V(`createGroup`)})]})]})]})]}),!ke&&(X===`groups`&&Qt?(0,$.jsx)(dl,{entry:A?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,hideHeader:!0,onRoomCountChange:Qe}):Z.length>0?(0,$.jsxs)(`div`,{className:`lp-section-body projects-scroll`,ref:nt,onDoubleClick:wn,role:`tree`,"aria-label":V(`lpProjectsTree`),onKeyDown:hn,children:[(0,$.jsxs)(`div`,{className:`lp-filter`,children:[(0,$.jsx)(ft,{"aria-hidden":`true`}),(0,$.jsx)(`input`,{type:`search`,value:we,placeholder:V(`lpFilterPlaceholder`),"aria-label":V(`lpFilterPlaceholder`),onChange:e=>Te(e.target.value),onKeyDown:e=>{e.key===`Escape`&&we?(e.stopPropagation(),Te(``)):e.key===`ArrowDown`&&(e.preventDefault(),mn(e.currentTarget,1))}}),we&&(0,$.jsx)(`button`,{type:`button`,className:`lp-filter-clear`,title:V(`lpFilterClear`),"aria-label":V(`lpFilterClear`),onClick:()=>Te(``),children:(0,$.jsx)(Be,{})})]}),(()=>{let e=z?.kind===`cwd`?Oy(z.target):null,t=we.trim().toLowerCase(),r=Xt.map(e=>{let n=new Set([...e.idleSessions.slice(0,e.maxVisible),...e.idleSessions.filter(e=>e.pinned)]),r={...e,orderedBlocks:e.orderedBlocks.filter(e=>e.kind===`conversation`||n.has(e.target))};if(!t||(e.p.sandbox?.name??fn(e.p.path)).toLowerCase().includes(t)||e.p.path.toLowerCase().includes(t))return r;let i=e.pRunningRows.filter(e=>(e.c.title??``).toLowerCase().includes(t)),a=e.idleSessions.filter(e=>(Se[e.path]??un(e)).toLowerCase().includes(t));if(i.length===0&&a.length===0)return null;let o=new Set(i.map(e=>e.c.id)),s=new Set(a.slice(0,50)),c=e.orderedBlocks.map(e=>{if(e.kind===`session`)return s.has(e.target)?e:null;let t=e.rows.filter(e=>o.has(e.c.id));return t.length>0?{...e,rows:t}:null}).filter(e=>e!==null);return{...e,isCollapsed:!1,pRunningRows:i,idleSessions:a,orderedBlocks:c,maxVisible:50,hasMore:!1}});return t&&r.every(e=>e===null)?(0,$.jsx)(`div`,{className:`lp-filter-empty`,children:V(`lpFilterNoMatch`)}):r.map(t=>{if(!t)return null;let{p:r,pNorm:i,active:a,isCollapsed:o,isLoadingSessions:s,pRunningRows:c,idleSessions:l,orderedBlocks:u,maxVisible:d,hasMore:f,actuallyRunningCount:m,unreadCount:h,serverHasMore:g}=t,_=e!==null&&e===i,v=r.sandbox,y=v?v.name:fn(r.path),b=m>0,x=l.length>0,S=h>0;o||rt.current.add(i);let w=l.some(e=>e.pinned),T=!o||c.length>0||S||a||w||rt.current.has(i),E=gt?.path===r.path&&mt&&mt!==r.path?gt.after?` drop-after`:` drop-before`:``;return(0,$.jsxs)(`div`,{className:`lp-project-node${mt===r.path?` dragging`:``}${E}`,role:`treeitem`,"aria-expanded":!o,"aria-selected":a,onDragOver:e=>{if(!mt||mt===r.path)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientY>t.top+Math.min(t.height,32)/2;(gt?.path!==r.path||gt.after!==n)&&vt({path:r.path,after:n})},onDrop:e=>{if(!mt)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();pt(mt,r.path,e.clientY>t.top+Math.min(t.height,32)/2),ht(null),vt(null)},children:[(0,$.jsxs)(`div`,{className:`lp-row lp-project-head-row${a?` active`:``}${_?` switching`:``}${o?` is-collapsed`:` is-expanded`}${b?` has-running`:``}${S?` has-unread`:``}`,draggable:!_,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,r.path),ht(r.path)},onDragEnd:()=>{ht(null),vt(null)},onMouseLeave:()=>me(e=>e===`proj:${r.path}`?null:e),onContextMenu:e=>_n(e,r),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-project-header-item project-item ${a?`active`:``} ${_?`switching`:``}${b?` has-running`:``}${S?` has-unread`:``}`,title:`${v?.sourcePath?`${y}\n${V(`sandboxSourceLabel`)}: ${v.sourcePath}\n${r.path}`:r.path}\n${V(`lpDragToReorder`)}`,disabled:_,"data-lp-nav":``,"data-project-path":r.path,"aria-current":a?`true`:void 0,"aria-keyshortcuts":`Alt+ArrowUp Alt+ArrowDown`,onClick:()=>{_||(!a&&oc()?(p({type:`set_cwd`,path:r.path}),xt(e=>{let t=Oy(r.path);if(e.has(t))return e;let n=new Set(e);return n.add(t),n})):jt(r.path))},onDoubleClick:e=>{e.stopPropagation(),!_&&(p({type:`new_chat`,cwd:r.path}),sn())},children:[(0,$.jsx)(`span`,{className:`lp-project-chevron`,"aria-hidden":`true`,onClick:e=>{e.stopPropagation(),jt(r.path)},title:V(o?`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:`M2.5 4h7l-3.5 5z`})})}),v&&(0,$.jsx)(Or,{className:`project-icon sandbox-icon`}),(0,$.jsx)(`span`,{className:`lp-project-name`,title:y,children:y}),v&&(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${v.ephemeral?`ephemeral`:`permanent`}`,children:v.ephemeral?V(`sandboxBadgeEphemeral`):V(`sandboxBadgePermanent`)}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[_&&(0,$.jsx)(kl,{className:`status-spinner-right`}),b&&(0,$.jsxs)(`span`,{className:`lp-project-running-badge`,title:V(`tabRunning`),children:[(0,$.jsx)(`span`,{className:`lp-project-running-dot`}),(0,$.jsx)(`span`,{children:m})]}),S&&(0,$.jsxs)(`span`,{className:`lp-project-unread-badge`,title:V(`completedUnreadBadge`),children:[(0,$.jsx)(`span`,{className:`lp-project-unread-dot`}),(0,$.jsx)(`span`,{children:h})]}),(0,$.jsx)(`span`,{className:`project-time ${_?`switching-pct`:``}`,children:_?`${z?.progress??0}%`:r.lastUsed>0?Hy(r.lastUsed):``})]})]}),(0,$.jsxs)(`div`,{className:`lp-project-actions`,children:[(0,$.jsx)(Rs,{cwd:r.path,onCreateCli:ee,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-new-chat-btn`,title:V(`newChat`)||`新建对话`,onClick:e=>{e.stopPropagation(),p({type:`new_chat`,cwd:r.path}),sn()},children:(0,$.jsx)(C,{})})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-del-btn ${q===`proj:${r.path}`?`confirm danger`:``}`,title:q===`proj:${r.path}`?V(v?`sandboxActionDestroy`:`deleteProjectConfirm`):V(v?`sandboxActionDestroyTip`:`deleteProject`),onClick:e=>{e.stopPropagation(),q===`proj:${r.path}`?(me(null),Cy(r.path),Dy(r.path),p(v?{type:`destroy_sandbox`,path:r.path}:{type:`remove_project`,path:r.path})):me(`proj:${r.path}`)},children:q===`proj:${r.path}`?(0,$.jsx)(n,{}):(0,$.jsx)(_t,{})}),Ht(D,`lp-slot-project`,{id:r.path,kind:`project`,label:y})]})]}),T&&(0,$.jsxs)(`div`,{className:`lp-project-tree-children${o?` is-collapsed`:` is-expanded`}${c.length>0?` has-running-rows`:``}`,children:[u.map(e=>{let t=Uy(o,e);return(0,$.jsx)(Q.Fragment,{children:e.kind===`conversation`?e.rows.map(e=>En(e,r.path)):(0,$.jsx)(`div`,{className:`lp-history-collapsible${o&&!t?` collapsed`:` expanded`}${t?` is-pinned-visible`:``}`,children:(0,$.jsx)(`div`,{className:`lp-history-collapsible-inner`,children:Tn(e.target,r.path)})})},e.key)}),(0,$.jsx)(`div`,{className:`lp-history-collapsible${o?` collapsed`:` expanded`}`,children:(0,$.jsxs)(`div`,{className:`lp-history-collapsible-inner`,children:[c.length===0&&l.length===0&&(0,$.jsx)(`div`,{className:`lp-project-empty-tip`,children:s?(0,$.jsx)(`span`,{children:V(`loadingSessions`)||`正在读取会话…`}):(0,$.jsx)(`span`,{children:V(`noSessionsYet`)||`暂无历史会话`})}),f&&(0,$.jsx)(`button`,{type:`button`,className:`lp-show-more-row`,"data-lp-nav":``,disabled:Tt.has(i),onClick:e=>{e.stopPropagation();let t=d+eb;if(Ct(e=>({...e,[i]:t})),g&&t>=l.length){let e=Math.max(tb,t+eb);p({type:`list_sessions`,path:r.path,limit:e}),Et(e=>new Set(e).add(i))}},children:(0,$.jsx)(`span`,{children:Tt.has(i)?V(`loadingSessions`):V(`lpShowMore`,{n:l.length>d?`${l.length-d}${g?`+`:``}`:`…`})})})]})}),o&&x&&(c.length>0||S)&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-collapsed-history-tip`,"data-lp-nav":``,onClick:e=>{e.stopPropagation(),jt(r.path)},title:V(`expandSection`),children:[(0,$.jsx)(`span`,{children:V(`lpCollapsedHistory`,{n:l.length})}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`›`})]})]})]},r.path)})})(),an()]}):null)]})}),convs:null,sessions:null},On=e=>{let t=Zt.find(t=>t.key===e)?.entry;if(!t)return null;let n=en(e);return(0,$.jsxs)(`div`,{className:`lp-section lp-section-plugin ${n?`collapsed`:``}`,style:n?void 0:{flex:`${Sn(e)} 1 0px`},children:[yn(t.label,n,()=>Le(e)),!n&&(0,$.jsx)(`div`,{className:`lp-section-body lp-plugin-section-body`,children:j?.(t)??null})]})},kn=e=>e===`groups`?X!==`split`&&Zt.some(e=>e.key===`projects`)?(0,$.jsx)(`section`,{className:`lp-section dg-side-section`,style:{display:`none`},children:(0,$.jsx)(dl,{entry:A?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,hideHeader:!0,onRoomCountChange:Qe})}):(0,$.jsx)(dl,{entry:A?.find(e=>e.id===`host:lp-groups`),active:m,selectedRoomId:c,flex:Sn(`groups`),onCollapsedChange:ze,onRoomCountChange:Qe}):e===`projects`||e===`convs`||e===`sessions`?Dn[e]:On(e);return(0,$.jsxs)(`aside`,{ref:Wt,className:`panel panel-left lp-panel`,children:[g&&_&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:V(`collapsePanel`),onClick:_,children:(0,$.jsx)(te,{})}),$t.map(({key:e})=>(0,$.jsxs)(Q.Fragment,{children:[kn(e),Cn.get(e)??null]},e)),(0,$.jsx)(uo,{open:ue,initialTab:fe,currentCwd:G,pathCompletions:v??[],workspaceRoots:le,onClose:()=>de(!1),onSelectDirectory:e=>p({type:`set_cwd`,path:e}),onCreateProject:e=>p({type:`make_dir`,path:e,setAsCwd:!0})})]})}),_b=e=>/\.(zip|tar|tar\.gz|tgz|gz)$/i.test(e);function vb(e,t={}){let n={archive:g(`/api/file-transfer/archive`),upload:g(`/api/file-transfer/upload`)},r=new URL(o(`${n[e]}?${new URLSearchParams({clientId:yy(),...t})}`),window.location.href),i=new URL(n[e],window.location.href);if(r.origin!==i.origin||r.pathname!==i.pathname)throw Error(`File transfers must use an allowlisted service endpoint`);return r}async function yb(e,t,n){let r=await fetch(vb(`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 _m(await r.blob(),i);if(!a.ok&&!a.cancelled)throw Error(a.error)}}async function bb(){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 xb(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=vb(`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 Sb({request:e,onClose:t,onComplete:n}){let r=W(),i=He(`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 bb();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 xb(e.dir,l,f,i):await yb(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,cr.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)(Be,{})})]}),(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 Cb(e){return e.startsWith(`.`)&&e!==`..`}function wb(e,t){return t?e:e.filter(e=>!Cb(e.name))}function Tb(e){return e instanceof Error?e.message:String(e)}function Eb(e,t,n,r){let i=X(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 Db({plugin:e,epoch:t,send:n,className:r}){let i=(0,Q.useRef)(null),{locale:a}=c(),o=W(),[s,l]=(0,Q.useState)(null),u=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{u.current=n},[n]),(0,Q.useEffect)(()=>{let n=i.current;if(!n)return;let r=!1,a,o=!1;if(l(null),!e.hasClient){l({kind:`no-client`});return}return(async()=>{try{if(await Dv(e,t),r)return;let i=await kn(e.id,()=>_d(()=>import(Sv(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:l}=rv(n,{isolated:c});a=s.mount(l,kv(e.id,e=>u.current(e)))}catch(t){if(r)return;console.error(`[plugin:${e.id}] 页面${o?`挂载`:`加载`}失败:`,t),l({kind:o?`mount`:`load`,detail:Tb(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 d=r?`plugin-page ${r}`:`plugin-page`;return(0,$.jsxs)(`div`,{className:d,children:[(0,$.jsx)(`div`,{className:`plugin-page-host`,ref:i}),s&&(0,$.jsx)(`div`,{className:`plugin-page-error`,role:`alert`,children:Eb(s,e.name,a,o)})]})}function Ob(e){return`pi-web-ui:${e}:tab`}function kb(e,t){try{let n=localStorage.getItem(Ob(e));return n&&t.some(e=>e.id===n)?n:null}catch{return null}}function Ab(e,t){try{localStorage.setItem(Ob(e),t)}catch{}}function jb(e){return e.length>0&&!/[a-z]/i.test(e)}function Mb(e){if(e.label)return e.label;let t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function Nb({storageKey:e,tabs:t,epoch:n,send:r,extra:i,className:a}){let o=(0,Q.useId)(),[s,c]=(0,Q.useState)(()=>kb(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,Ab(e,f.id))},[f,s,e]),(0,Q.useEffect)(()=>{let n=n=>{let r=n.detail;r&&r.group===e&&typeof r.id==`string`&&t.some(e=>e.id===r.id)&&(c(r.id),u.current=`${e}:${r.id}`,Ab(e,r.id))};return window.addEventListener(`pi:select-slot-tab`,n),()=>window.removeEventListener(`pi:select-slot-tab`,n)},[e,t]);let m=t=>{c(t.id),u.current=`${e}:${t.id}`,Ab(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??Mb(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)(Ri,{iconSvg:e.iconSvg,className:`slot-tab-icon`}):e.icon&&jb(e.icon)?(0,$.jsx)(`span`,{className:`slot-tab-icon`,children:e.icon}):null,(0,$.jsx)(`span`,{className:`slot-tab-label`,children:Mb(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)(Db,{plugin:f.pluginPage.plugin,epoch:n,send:r}):f.element??null})]})}var Pb=`@root`,Fb=`pi-web-ui:rp-sizes`,Ib=`pi-web-ui:files-show-hidden`,Lb={files:4,widgets:1},Rb=120,zb=56;function Bb(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}var Vb=`files`,Hb=[],Ub=()=>{};function Wb(e){let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n<0?``:n===0?`/`:t.slice(0,n)}function Gb(e){return e===Pb||e===`/`||/^[A-Za-z]:$/.test(e)}function Kb({nodes:e,depth:t,collapsed:n,onToggle:r,onOpenDir:i,onOpenFile:a}){return(0,$.jsx)($.Fragment,{children:e.map(e=>(0,$.jsxs)(Q.Fragment,{children:[e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir`,style:{paddingLeft:4+t*12},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,style:{padding:2,flex:`none`},onClick:()=>r(e.path),"aria-label":e.path,children:n.includes(e.path)?(0,$.jsx)(h,{"aria-hidden":`true`}):(0,$.jsx)(L,{"aria-hidden":`true`})}),(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:()=>i(e.path),title:e.path,children:[(0,$.jsx)(st,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,style:e.matched?void 0:{opacity:.65},children:e.name})]})]}):(0,$.jsxs)(`button`,{type:`button`,className:`file-item`,style:{paddingLeft:8+t*12},onClick:()=>a(e.path,e.name),title:e.path,children:[(0,$.jsx)(ht,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),e.type===`dir`&&!n.includes(e.path)&&(0,$.jsx)(Kb,{nodes:e.children,depth:t+1,collapsed:n,onToggle:r,onOpenDir:i,onOpenFile:a})]},e.path||e.name))})}function qb(e){return e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)}var Jb=(0,Q.memo)(function({files:e,fileSearch:t,fileChanged:r,widgets:i,panelSend:a,onAttach:o,onPreview:s,onNotice:c,collapsible:l,onToggleCollapse:u,uiRightPanelTabs:d,uiContextFile:f,quickAskReferenceMenus:p=!0,plugins:g,pluginsEpoch:_,send:v}){let y=W(),b=g??Hb,S=He(`cwd`),C=He(`workspaceRoots`),w=He(`homeDir`),T=He(`desktopDir`),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(!1),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),[P,F]=(0,Q.useState)(()=>{try{return bl(localStorage.getItem(Fb),Lb)}catch{return{...Lb}}});(0,Q.useEffect)(()=>{try{localStorage.setItem(Fb,JSON.stringify(P))}catch{}},[P]);let[I,L]=(0,Q.useState)(()=>{try{return localStorage.getItem(Ib)===`1`}catch{return!1}}),[R,z]=(0,Q.useState)(``),[B,ee]=(0,Q.useState)(!1),V=(0,Q.useRef)(0),[te,ne]=(0,Q.useState)([]),ie=R.trim();(0,Q.useEffect)(()=>{if(ie===``)return;let e=setTimeout(()=>{V.current+=1,a({type:`search_files`,reqId:V.current,query:ie,scope:E})},300);return()=>clearTimeout(e)},[ie,E,a]);let H=(ie!==``&&t&&t.reqId===V.current?t.results:[]).filter(e=>e.path!==E&&(E===``||E===`@root`||e.path===E||e.path.startsWith(`${E}/`)));(0,Q.useEffect)(()=>{ne([])},[ie,E]);let U=(0,Q.useMemo)(()=>{if(ie===``)return[];let t={name:``,path:``,type:`dir`,matched:!1,children:[]},n=E!==``&&E!==`@root`?`${E}/`:``,r=ie.toLowerCase(),i=(e,r)=>{let i=(n!==``&&e.startsWith(n)?e.slice(n.length):e).split(`/`).filter(Boolean);if(i.length===0)return;let a=t,o=n===``?``:n.slice(0,-1);i.forEach((e,t)=>{let n=t===i.length-1;o=o===``?e:`${o}/${e}`;let s=a.children.find(t=>t.name===e);s?n&&r===`dir`&&(s.type=`dir`):(s={name:e,path:o,type:n?r:`dir`,matched:!1,children:[]},a.children.push(s)),n&&(s.matched=!0),a=s})};if(e&&e.path===E)for(let t of wb(e.entries,I))t.type===`file`&&t.name.toLowerCase().includes(r)&&i(t.path,t.type);for(let e of H)i(e.path,e.type);let a=e=>{e.children.sort((e,t)=>e.type===t.type?e.name.localeCompare(t.name):e.type===`dir`?-1:1),e.children.forEach(a)};return a(t),t.children},[H,E,e,I,ie]),oe=(0,Q.useCallback)(e=>{ne(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]);(0,Q.useEffect)(()=>{try{localStorage.setItem(Ib,I?`1`:`0`)}catch{}},[I]);let se=i.some(e=>e.lines.length>0),ce=(0,Q.useCallback)(e=>{e.preventDefault();let t=M.current;if(!t)return;let n=e.currentTarget,r=e.clientY,i={above:P.files,below:P.widgets},a=Math.max(120,t.clientHeight-Bb(t,N.current));n.classList.add(`dragging`),document.body.classList.add(`rp-resizing`);let o=e=>{let{above:t,below:n}=xl({start:i,deltaPx:e.clientY-r,availablePx:a,totalWeight:i.above+i.below,minAbovePx:Rb,minBelowPx:zb});F({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)},[P.files,P.widgets]),le=(0,Q.useRef)(null),G=(0,Q.useRef)(0),K=(0,Q.useCallback)(e=>{le.current=e,e&&(e.scrollTop=G.current)},[]),[ue,de]=(0,Q.useState)(null),fe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{fe.current&&clearTimeout(fe.current)},[]);let pe=(0,Q.useCallback)(e=>{de(e),fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>de(null),1200)},[]),q=(0,Q.useCallback)((e,t)=>{e&&Gd(e).then(e=>{e?pe(t):c(`error`,y(`slashCopyFailed`))})},[pe,c,y]),me=(0,Q.useCallback)(e=>{if(!e)return S;if(/^[A-Za-z]:$/.test(e))return`${e}/`;if(e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e))return e;let t=S.replace(/\\/g,`/`).replace(/\/+$/,``);return t?`${t}/${e}`:e},[S]),ge=(0,Q.useCallback)(e=>{if(Vn(S)){let t=zn(S),n=t?t.remotePath:`/`;if(!e)return n;if(e.startsWith(`/`))return e;let r=n.replace(/\/+$/,``)||`/`;return r===`/`?`/${e}`:`${r}/${e}`}return me(e)},[S,me]),_e=(0,Q.useCallback)(e=>!e||e===Pb?null:e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)?e:`${S.replace(/\\/g,`/`).replace(/\/+$/,``)}/${e}`,[S]),ve=He(`workspaceUploadMaxMb`)*1024*1024,[J,ye]=(0,Q.useState)([]),be=He(`status`);(0,Q.useEffect)(()=>{be!==`open`&&ye(e=>e.some(e=>e.phase===`waiting`)?e.map(e=>e.phase===`waiting`?{...e,phase:`unknown`}:e):e)},[be]);let xe=(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`&&ye(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=xe.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 Se=(0,Q.useCallback)((e,t)=>{for(let n of t){if(n.size>ve){c(`warning`,y(`fileTooLarge`,{name:n.name,size:ve/1024/1024}));continue}let t=crypto.randomUUID(),r=e=>ye(n=>n.map(n=>n.id===t?{...n,...e}:n));ye(r=>[...r,{id:t,name:n.name,dir:e,phase:`reading`,percent:0}]);let i=new FileReader;xe.current.set(t,i);let o=()=>{xe.current.delete(t),r({phase:`error`,error:y(`fileUploadReadFailed`,{name:n.name})})};i.onprogress=e=>{e.lengthComputable&&e.total>0&&r({percent:Math.min(100,Math.floor(e.loaded/e.total*100))})},i.onerror=o,i.onabort=o,i.onload=()=>{if(xe.current.delete(t),typeof i.result!=`string`||!i.result.includes(`,`)){o();return}let s=i.result.slice(i.result.indexOf(`,`)+1);r({phase:`waiting`,percent:100});try{if(a({type:`upload_file`,dirPath:e,name:n.name,data:s,uploadId:t}))return}catch{}r({phase:`error`,error:y(`fileUploadSendFailed`,{name:n.name})})};try{i.readAsDataURL(n)}catch{o()}}},[a,c,y,ve]),Ce=(0,Q.useRef)(null),[Y,we]=(0,Q.useState)(null),Te=(0,Q.useRef)(null),Ee=(0,Q.useCallback)(()=>{let e=Ce.current?.project;e&&a({type:`set_cwd`,path:e.path})},[a]),De=(0,Q.useCallback)(()=>{Te.current&&(Te.current.value=``),Te.current?.click()},[]),[Oe,ke]=(0,Q.useState)(null),[Ae,je]=(0,Q.useState)(null),[Me,Pe]=(0,Q.useState)(``),[Fe,Le]=(0,Q.useState)(null),[Re,ze]=(0,Q.useState)(``),Ve=(0,Q.useCallback)((e,t)=>{gm(e,t).then(e=>{e.ok||e.cancelled||c(`error`,y(`downloadFailed`,{error:e.error===`FILE_NOT_FOUND`?y(`fileNotFoundShort`):e.error}))})},[c,y]),Ue=(0,Q.useCallback)(()=>{let e=Ce.current?.target;e&&e.kind!==`list`&&!Gb(e.id)&&(Le(null),Pe(e.label),je(e.id))},[]),We=(0,Q.useCallback)(()=>{if(!Ae)return;let e=Me.trim();je(null),e&&a({type:`file_rename`,path:Ae,newName:e})},[Ae,Me,a]),Ge=(0,Q.useCallback)(e=>{let t=Ce.current?.dir??E;je(null),ze(``),Le({dir:t,kind:e})},[E]),X=(0,Q.useCallback)(()=>{if(!Fe)return;let e=Re.trim();Le(null),e&&a({type:`file_create`,dir:Fe.dir,name:e,kind:Fe.kind})},[Fe,Re,a]),Ke=(e,t,n,r)=>(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:e,placeholder:y(`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}),qe=(0,Q.useCallback)(()=>{let e=Ce.current?.target;e&&e.kind!==`list`&&!Gb(e.id)&&window.confirm(y(`fileDeleteConfirm`,{name:e.label}))&&(Oe?.src===e.id&&ke(null),Ae===e.id&&je(null),a({type:`file_delete`,path:e.id}))},[a,y,Oe,Ae]),Je=(0,Q.useCallback)(()=>{let e=Ce.current?.target;e&&e.kind!==`list`&&!Gb(e.id)&&a({type:`file_copy`,src:e.id,destDir:Wb(e.id)})},[a]),Ye=(0,Q.useCallback)(e=>{let t=Ce.current?.target;t&&t.kind!==`list`&&!Gb(t.id)&&ke({src:t.id,cut:e})},[]),Xe=(0,Q.useCallback)(()=>{if(!Oe)return;let e=Ce.current?.dir??E;Oe.cut?(a({type:`file_copy`,src:Oe.src,destDir:e,move:!0}),ke(null)):a({type:`file_copy`,src:Oe.src,destDir:e})},[Oe,a,E]),Ze=(0,Q.useCallback)(()=>{a({type:`list_files`,path:E===``?void 0:E})},[a,E]),[Qe,$e]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!Qe)return;let e=e=>{e.target?.closest(`.root-picker`)||$e(!1)},t=e=>{e.key===`Escape`&&$e(!1)};return window.addEventListener(`mousedown`,e,!0),window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`mousedown`,e,!0),window.removeEventListener(`keydown`,t)}},[Qe]);let et=(0,Q.useCallback)(e=>{a({type:`set_workspace_roots`,roots:e})},[a]),nt=(0,Q.useCallback)(()=>{let e=Ce.current?.target;if(!e||e.kind!==`dir`)return;let t=_e(e.id);t&&!C.includes(t)&&et([...C,t])},[C,_e,et]),rt=(0,Q.useCallback)(e=>{Se(Ce.current?.dir??E,Array.from(e.target.files??[]))},[Se,E]),it=(0,Q.useCallback)(e=>{let t=Ce.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`;we({action:n,path:ge(t.id),dir:ge(n===`upload`?Ce.current?.dir??E:Wb(t.id))});break}case`host:file-open-project`:Ee();break;case`host:file-upload`:De();break;case`host:file-add-root`:nt();break;case`host:file-open`:t?.kind===`file`&&s(t.id,t.label);break;case`host:file-enter`:t?.kind===`dir`&&vt(t.id);break;case`host:file-download`:t?.kind===`file`&&Ve(t.id,t.label);break;case`host:file-reveal`:t&&a({type:`file_reveal`,path:t.id});break;case`host:file-open-default`:t?.kind===`file`&&a({type:`file_open_default`,path:t.id});break;case`host:file-attach-ref`:t?.kind===`file`&&o(t.id,t.label,`reference`);break;case`host:file-attach-folder`:t?.kind===`dir`&&o(t.id,t.label,`reference`,!0);break;case`host:file-new-file`:Ge(`file`);break;case`host:file-new-dir`:Ge(`dir`);break;case`host:file-paste`:Xe();break;case`host:file-rename`:Ue();break;case`host:file-duplicate`:Je();break;case`host:file-cut`:Ye(!0);break;case`host:file-copy`:Ye(!1);break;case`host:file-copy-name`:t&&t.kind!==`list`&&q(t.label,`name:${t.id}`);break;case`host:file-copy-path`:t&&t.kind!==`list`&&q(me(t.id),`path:${t.id}`);break;case`host:file-copy-rel`:t&&t.kind!==`list`&&q(t.id,`rel:${t.id}`);break;case`host:file-refresh`:Ze();break;case`host:file-delete`:qe()}},[Ee,E,De,nt,s,o,q,me,Ve,Ge,Xe,Ue,Je,Ye,Ze,qe]),at=(0,Q.useCallback)((e,t)=>{let n=t.kind===`dir`?_e(t.id):null,r={target:t,dir:t.kind===`dir`?t.id:E,project:n?{path:n,name:t.label}:null},i=t.kind,a=i===`file`,o=i===`dir`,s=i===`list`,c=!s&&Gb(t.id),l=!s&&qb(t.id),u=E===Pb,d=!s&&t.id!==Pb&&(S||l)?{kind:o?`directory`:`file`,path:me(t.id),cwd:S}:void 0,m=(f??[]).map(e=>{if(e.source!==`host`)return e;switch(e.id){case`host:file-quick-ask`:return p&&d?e:{...e,hidden:!0};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&&_b(t.label)?e:{...e,hidden:!0};case`host:file-upload`:return u?{...e,hidden:!0}:{...e,label:r.dir===E?y(`uploadToCurrentDir`):y(`uploadToFolder`)};case`host:file-open-project`:return n?e:{...e,hidden:!0};case`host:file-add-root`:return n&&n!==S&&!C.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!==Pb?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&&Oe?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}});Xa(m).length!==0&&(e.preventDefault(),e.stopPropagation(),Ce.current=r,za({x:e.clientX,y:e.clientY,slot:`contextmenu.file`,target:t,entries:m,onHostAction:e=>{if(e.id===`host:file-quick-ask`){d&&jl({reference:d});return}it(e)}}))},[f,p,E,_e,me,y,it,S,C,Oe]),ot=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),ct=(0,Q.useCallback)(()=>{le.current?.querySelectorAll(`.file-item.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),le.current?.classList.remove(`drop-root`)},[]),lt=(0,Q.useCallback)(e=>{if(ct(),e==null)return;let t=le.current?.querySelector(`.file-item[data-path="${CSS.escape(e)}"]`);t?t.classList.add(`drop-target`):le.current?.classList.add(`drop-root`)},[ct]),ut=e=>{let t=e instanceof Element?e.closest(`.file-item`):null;return t?.dataset.type===`dir`?t.dataset.path??E:E},dt=(0,Q.useCallback)(()=>{let e=document.querySelector(`.app`);e&&e.dispatchEvent(new DragEvent(`dragleave`,{bubbles:!0}))},[]),pt=(0,Q.useRef)(0),mt=(0,Q.useRef)(void 0),gt=(0,Q.useCallback)((e,t)=>{let n=++pt.current;D(e),t?.silent||j(!0),a({type:`list_files`,path:e===``?void 0:e})||pt.current===n&&j(!1)},[a]),_t=(0,Q.useCallback)(e=>{let t=C.filter(t=>t!==e);et(t),(E===e||E.startsWith(`${e}/`))&>(``)},[C,et,E,gt]);(0,Q.useEffect)(()=>{e&&e.path===E&&j(!1)},[e,E]),(0,Q.useEffect)(()=>{if(S!==mt.current){let e=mt.current===void 0;mt.current=S,e?gt(``,{silent:!0}):D(``);return}let e=setInterval(()=>{document.visibilityState!==`hidden`&>(E,{silent:!0})},1e4);return()=>clearInterval(e)},[S,E,gt]),(0,Q.useEffect)(()=>{r&&r.path===E&>(E,{silent:!0})},[r,E,gt]);let vt=e=>gt(e);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;t&&typeof t.path==`string`&&(window.dispatchEvent(new CustomEvent(`pi:select-slot-tab`,{detail:{group:`rightpanel`,id:Vb}})),gt(t.path))};return window.addEventListener(`pi:open-folder`,e),()=>window.removeEventListener(`pi:open-folder`,e)},[gt]);let Z=()=>{e?.parent!==null&&e?.parent!==void 0&>(e.parent)},yt=(()=>{if(E===``||E===Pb)return[];let e=E.split(`/`).filter(e=>!!e&&e!==Pb);return E.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(`/`)}))})(),xt=E.startsWith(`/`)||E===Pb?yt:[{label:y(`rootDir`),path:``},...yt],St=E===``?S||y(`rootDir`):E,Ct=[];for(let e of d??[]){if(e.source===`host`||e.hidden||e.kind===`divider`)continue;let t=b.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 wt=(d??[]).some(e=>e.id===`host:right-files`&&e.hidden);return(0,$.jsxs)(`aside`,{className:`panel panel-right`,ref:M,children:[l&&u&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:y(`collapsePanel`),onClick:u,children:(0,$.jsx)(h,{})}),(0,$.jsx)(`div`,{ref:N,style:{display:`flex`,flexDirection:`column`,flex:se?`${P.files} 1 0`:`1 1 0`,minHeight:se?Rb:0},children:(0,$.jsx)(Nb,{storageKey:`rightpanel`,epoch:_??0,send:v??Ub,tabs:(e=>{let t=(d??[]).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===Vb?`host:right-files`:e)??1e9;return[...e].sort((e,t)=>r(e.id)-r(t.id))})([...wt?[]:[{id:Vb,label:y(`openFiles`),element:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`panel-crumbs files-toolbar`,children:[(0,$.jsx)(In,{className:`crumb ${E===Pb?`active`:``}`,tip:y(`computer`),onClick:()=>gt(Pb),children:(0,$.jsx)(Ie,{})}),w!==``&&(0,$.jsx)(In,{className:`crumb ${E===w||E.startsWith(`${w}/`)?`active`:``}`,tip:y(`homeDir`),onClick:()=>gt(w),children:(0,$.jsx)(tt,{})}),T!==``&&(0,$.jsx)(In,{className:`crumb ${E===T||E.startsWith(`${T}/`)?`active`:``}`,tip:y(`desktopDir`),onClick:()=>gt(T),children:(0,$.jsx)(re,{})}),(0,$.jsx)(In,{className:`crumb ${I?`active`:``}`,tip:y(I?`filesHideHidden`:`filesShowHidden`),"aria-pressed":I,onClick:()=>L(e=>!e),children:I?(0,$.jsx)(Ne,{}):(0,$.jsx)(bt,{})}),(0,$.jsx)(In,{className:`crumb ${B?`active`:``}`,tip:y(`filesFilterPlaceholder`),"aria-pressed":B,onClick:()=>{B&&z(``),ee(e=>!e)},children:(0,$.jsx)(ft,{})}),(0,$.jsx)(Rn,{text:y(`filesHelp`)}),C.length>0&&(0,$.jsxs)(`div`,{className:`root-picker`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`crumb root-picker-trigger`,"aria-haspopup":`menu`,"aria-expanded":Qe,title:y(`workspaceRoots`),onClick:()=>$e(e=>!e),children:[(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`root-picker-label`,children:y(`workspaceRoots`)}),(0,$.jsx)(`span`,{className:`set-count`,children:C.length+1}),`▾`]}),Qe&&(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:E===``?`root-picker-item active`:`root-picker-item`,title:S,onClick:()=>{$e(!1),gt(``)},children:[y(`rootDir`),(0,$.jsx)(`span`,{className:`root-picker-path`,children:S})]})}),C.map(e=>(0,$.jsxs)(`div`,{className:`root-picker-row`,children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:E===e?`root-picker-item active`:`root-picker-item`,title:e,onClick:()=>{$e(!1),gt(e)},children:(0,$.jsx)(`span`,{className:`root-picker-path`,children:e})}),(0,$.jsx)(`button`,{type:`button`,className:`root-picker-remove`,title:y(`removeWorkspaceRoot`),"aria-label":y(`removeWorkspaceRoot`),onClick:()=>_t(e),children:(0,$.jsx)(Be,{})})]},e)),(0,$.jsx)(`div`,{className:`root-picker-hint`,children:y(`workspaceRootsHint`)})]})]})]}),(0,$.jsx)(`div`,{className:`panel-crumbs files-pathrow`,style:{flexWrap:`nowrap`},children:B?(0,$.jsxs)(`span`,{className:`crumb file-filter-wrap`,style:{flex:1,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,$.jsx)(ft,{"aria-hidden":`true`}),(0,$.jsx)(`input`,{className:`file-filter-input`,autoFocus:!0,value:R,onChange:e=>z(e.target.value),placeholder:y(`filesFilterPlaceholder`),"aria-label":y(`filesFilterPlaceholder`),onKeyDown:e=>{e.key===`Escape`&&(z(``),ee(!1))},style:{flex:1,minWidth:0,background:`transparent`,border:`none`,outline:`none`,color:`inherit`}}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,style:{padding:2},onClick:()=>{R===``?ee(!1):z(``)},"aria-label":y(`close`),title:y(`close`),children:(0,$.jsx)(Be,{"aria-hidden":`true`})})]}):(0,$.jsx)($.Fragment,{children:(0,$.jsx)(`span`,{className:`file-path-text`,title:St,style:{flex:1,minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:xt.map((e,t)=>e===null?(0,$.jsxs)(`span`,{className:`crumb-seg`,style:{margin:`0 2px`},children:[`…`,(0,$.jsx)(h,{"aria-hidden":`true`})]},`ellipsis`):(0,$.jsxs)(`span`,{className:`crumb-seg`,children:[t>0&&(0,$.jsx)(h,{"aria-hidden":`true`}),(0,$.jsx)(`button`,{type:`button`,className:`crumb ${e.path===E?`active`:``}`,onClick:()=>gt(e.path),title:e.path||St,children:e.label})]},e.path||`root`))})})}),(0,$.jsxs)(`div`,{ref:K,className:`panel-body`,onScroll:e=>{G.current=e.currentTarget.scrollTop},onContextMenu:e=>at(e,{id:E,kind:`list`,label:E===``?y(`rootDir`):E===Pb?y(`computer`):E}),onDragOver:e=>{ot(e)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,dt(),lt(ut(e.target)))},onDragLeave:e=>{e.relatedTarget&&e.currentTarget.contains(e.relatedTarget)||ct()},onDrop:e=>{if(ct(),!ot(e))return;e.preventDefault(),e.stopPropagation(),dt();let t=Array.from(e.dataTransfer?.files??[]);if(t.length===0){c(`warning`,y(`foldersNotSupported`));return}Se(ut(e.target),t)},onDragEnd:ct,children:[(0,$.jsx)(`input`,{ref:Te,type:`file`,multiple:!0,hidden:!0,onChange:rt}),J.length>0&&(0,$.jsx)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`4px 8px`},children:J.map(e=>{let t=e.phase===`reading`?y(`fileUploadReading`,{name:e.name,percent:e.percent}):e.phase===`waiting`?y(`fileUploadWaiting`,{name:e.name}):e.phase===`success`?y(`fileUploadConfirmed`):e.phase===`unknown`?y(`fileUploadOutcomeUnknown`):y(`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":`${y(`fileUploadDismiss`)}: ${e.name}`,title:y(`fileUploadDismiss`),onClick:()=>ye(t=>t.filter(t=>t.id!==e.id)),style:{flex:`none`,padding:2},children:(0,$.jsx)(Be,{"aria-hidden":`true`})})]}),e.phase===`reading`&&(0,$.jsx)(`progress`,{max:100,value:e.percent,"aria-label":y(`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)})}),Y&&(0,$.jsx)(Sb,{request:Y,onClose:()=>we(null),onComplete:Ze}),Fe&&(0,$.jsxs)(`div`,{className:`file-item dir`,children:[Fe.kind===`dir`?(0,$.jsx)(st,{className:`file-icon`}):(0,$.jsx)(ht,{className:`file-icon`}),Ke(Re,ze,X,()=>Le(null))]}),A&&(0,$.jsx)(`div`,{className:`panel-empty`,children:y(`loading`)}),!A&&e&&e.path===E&&(0,$.jsxs)($.Fragment,{children:[ie===``&&e.parent!=null&&(0,$.jsxs)(`button`,{type:`button`,className:`file-item dir`,onClick:Z,children:[(0,$.jsx)(st,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:`..`})]}),wb(e.entries,I).filter(e=>ie===``&&(R.trim()===``||e.name.toLowerCase().includes(R.trim().toLowerCase()))).map(e=>e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir${Oe?.cut&&Oe.src===e.path?` cut`:``}`,"data-type":`dir`,"data-path":e.path,onClick:t=>{Ae!==e.path&&(t.target.closest(`.file-attach`)||vt(e.path))},onContextMenu:t=>at(t,{id:e.path,kind:`dir`,label:e.name}),children:[Ae===e.path?Ke(Me,Pe,We,()=>je(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:t=>{t.stopPropagation(),vt(e.path)},children:[(0,$.jsx)(st,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":y(`linkFolderTip`),"aria-label":y(`linkFolderTip`),onClick:t=>{t.stopPropagation(),o(e.path,e.name,`reference`,!0)},children:(0,$.jsx)(At,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${ue===`name:${e.path}`?` copied`:``}`,"data-tip":y(`copyName`),"aria-label":y(`copyName`),onClick:t=>{t.stopPropagation(),q(e.name,`name:${e.path}`)},children:ue===`name:${e.path}`?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${ue===`path:${e.path}`?` copied`:``}`,"data-tip":y(`copyPath`),"aria-label":y(`copyPath`),onClick:t=>{t.stopPropagation(),q(me(e.path),`path:${e.path}`)},children:ue===`path:${e.path}`?(0,$.jsx)(n,{}):(0,$.jsx)(ae,{})})]},e.path):(0,$.jsxs)(`div`,{className:`file-item file${Oe?.cut&&Oe.src===e.path?` cut`:``}`,"data-type":`file`,"data-path":e.path,onClick:t=>{Ae!==e.path&&(t.target.closest(`.file-attach`)||s(e.path,e.name))},onContextMenu:t=>at(t,{id:e.path,kind:`file`,label:e.name}),children:[Ae===e.path?Ke(Me,Pe,We,()=>je(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-name`,title:`${e.path} — ${y(`previewFile`)}`,onClick:t=>{t.stopPropagation(),s(e.path,e.name)},children:[(0,$.jsx)(ht,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name-text`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach download`,"data-tip":y(`downloadFile`),onClick:t=>{t.stopPropagation(),Ve(e.path,e.name)},children:(0,$.jsx)(he,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":y(`referenceTip`),"aria-label":y(`referenceTip`),onClick:t=>{t.stopPropagation(),o(e.path,e.name,`reference`)},children:(0,$.jsx)(At,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${ue===`name:${e.path}`?` copied`:``}`,"data-tip":y(`copyName`),"aria-label":y(`copyName`),onClick:t=>{t.stopPropagation(),q(e.name,`name:${e.path}`)},children:ue===`name:${e.path}`?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${ue===`path:${e.path}`?` copied`:``}`,"data-tip":y(`copyPath`),"aria-label":y(`copyPath`),onClick:t=>{t.stopPropagation(),q(me(e.path),`path:${e.path}`)},children:ue===`path:${e.path}`?(0,$.jsx)(n,{}):(0,$.jsx)(ae,{})})]},e.path)),ie!==``&&(U.length>0?(0,$.jsx)(Kb,{nodes:U,depth:0,collapsed:te,onToggle:oe,onOpenDir:vt,onOpenFile:s}):(0,$.jsx)(`div`,{className:`panel-empty`,children:y(`searchNoResults`)})),ie===``&&e.truncated&&(0,$.jsx)(`div`,{className:`panel-empty files-truncated`,children:y(`filesTruncated`)})]}),!A&&!e&&(0,$.jsx)(`div`,{className:`panel-empty`,children:y(`noFiles`)})]})]})}],...Ct])})}),se&&(0,$.jsx)(`div`,{className:`rp-sash`,onPointerDown:ce,onDoubleClick:()=>F({...Lb}),title:y(`dragToResize`)}),se&&(0,$.jsx)(`div`,{className:`panel-widgets`,style:{flexGrow:P.widgets,minHeight:zb},children:i.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:y(`widgetExpand`),onClick:()=>k(e.key),children:[(0,$.jsx)(`span`,{children:e.key}),(0,$.jsx)(m,{})]}),(0,$.jsx)(`pre`,{className:`widget-lines`,children:e.lines.join(`
|
|
71
|
+
`)})]},e.key))}),O&&(()=>{let e=i.find(e=>e.key===O);return e?(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>k(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:y(`close`),onClick:()=>k(null),children:(0,$.jsx)(Be,{})})]}),(0,$.jsx)(`pre`,{className:`widget-expand-lines`,children:e.lines.join(`
|
|
72
|
+
`)})]})}):null})()]})});function Yb(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 Xb(e){let t=e.details??{};if(t.mode===`quote`){let e=$u(t.quote);return e?{path:``,mode:`quote`,quote:e}:null}let n=[];if(Yb(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 Zb(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 Qb(e){let t=new Set,n=[];for(let r of e){let e=Zb(r);t.has(e)||(t.add(e),n.push(r))}return n}function $b(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=[];Yb(i,r.content);let a=r.details?.quotes;for(let e of Array.isArray(a)?a:[]){let t=$u(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=Xb(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=Xb(e[t]);n&&i.push(n)}let s=Qb(i);s.length>0&&t.set(r.id,s)}return t}function ex(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 tx=(0,Q.memo)(function({message:e,onExpand:t,summary:n}){let r=W(),i=Tg(),a=bg(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=Vg(t);if(e&&e.text.trim()){let t=Lh(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)Hg(t)?l++:Ug(t)?u++:Gg(t)?d++:Wg(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:()=>kg(e.id)}),(0,$.jsx)(`span`,{className:`msg-collapsed-role role-${e.role}`,children:e.role===`custom`&&e.customType===`file`?r(`attachment`):a_(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:nx(e.timestamp)}):null,(0,$.jsx)(`span`,{className:`msg-collapsed-action`,children:r(`expandMsg`)})]})});function nx(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}var rx=`[goal-review]`;function ix(e){for(let t of e.content??[]){let e=Vg(t);if(e&&e.text.trim())return e.text}return``}function ax(e){if(e.role!==`assistant`)return;let t=ix(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 ox(e){if(e.role===`user`&&ix(e).includes(rx))return{kind:`prompt`};let t=ax(e);if(t)return{kind:`verdict`,verdict:t}}var sx=`--flow-inline-stream`;function cx(){if(typeof window>`u`||typeof document>`u`)return!1;let e=getComputedStyle(document.documentElement).getPropertyValue(sx).trim();return e===`1`||e===`true`}function lx(){let[e,t]=(0,Q.useState)(cx);return(0,Q.useEffect)(()=>{let e=()=>t(cx());return e(),window.addEventListener(Jt,e),()=>window.removeEventListener(Jt,e)},[]),e}var ux=(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 dx(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 fx(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 px(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)??mx(n.role,n.customType)}return r}function mx(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 hx=[`text`,`thinking`,`argumentsText`,`output`,`command`];function gx(e){let t=0;for(let n of e.content){n.type===`image`&&(t+=1);for(let e of hx){let r=n[e];typeof r==`string`&&(t+=r.length)}}return t}function _x(e,t,n,r){let i=n.get(e);return i&&i.len===t?i.h:r}function vx(e){let t=[];for(let n of e.content)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
|
|
73
|
+
`)}function yx(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=vx(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(`
|
|
74
|
+
`)}function bx(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function xx(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=bx(yx(n,r).toLowerCase(),a);e>0&&i.set(n.id,e)}return i}function Sx(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 Cx(e,t,n,r,i){let a=xx(n,r,t,i),o=new Map;for(let n of Sx(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 wx(e,t){return e.findIndex(e=>e.msgId===t.msgId&&e.k===t.k)}function Tx(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 Ex(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 Dx(e,t){let n=t.startContainer.parentElement;for(let r of Ex(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 Ox({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}),S=(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||(Tx(`msg-search`,[]),Tx(`msg-search-active`,[])),()=>{Tx(`msg-search`,[]),Tx(`msg-search-active`,[])}),[o]),(0,Q.useLayoutEffect)(()=>{let s=()=>{h(0),p(null),g(0),b.current=[],Tx(`msg-search`,[]),Tx(`msg-search-active`,[]),x.current={key:null},S.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=Cx(c,v,t,n,r);b.current=e;let o=e.length;if(h(o),o===0){p(null),g(0),Tx(`msg-search`,[]),Tx(`msg-search-active`,[]),x.current={key:null},S.current=v;return}let s=y.current,u;if(s){if(u=wx(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!==S.current;if(x.current={key:{msgId:d.msgId,k:d.k},kind:d.kind},S.current=v,Tx(`msg-search`,e.filter(e=>e.kind===`dom`).map(e=>e.range)),d.kind===`folded`){Tx(`msg-search-active`,[]),m&&i(d.msgId);return}Tx(`msg-search-active`,[d.range]),m&&(a?.(),Dx(c,d.range))}),()=>{l=!0,cancelAnimationFrame(u)}},[o,v,t,e,f,n,r,i,a]);let C=(0,Q.useCallback)(e=>{let t=b.current,n=t.length;if(n===0)return;let r=y.current,i=t[((r?wx(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=wx(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(),C(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:()=>C(-1),children:(0,$.jsx)(w,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:c(`searchNext`),disabled:m===0,onClick:()=>C(1),children:(0,$.jsx)(L,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:c(`searchClose`),onClick:s,children:(0,$.jsx)(Be,{})})]})}function kx(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 Ax(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 jx(e){let{wasStreaming:t,isStreaming:n,escaped:r,hasJumpTarget:i}=e;return i?!1:!t&&n?!r:!1}function Mx(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 Nx(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 Px(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,_]),R=(0,Q.useRef)(d);R.current=d;let z=(0,Q.useRef)(f);z.current=f;let B=(0,Q.useCallback)(e=>{let t=_.current;t&&Nx({scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,hasEarlier:R.current,isMovingUp:e})&&z.current()},[_]),ee=(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(),B(!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,B,_]),V=(0,Q.useCallback)(e=>{e.touches.length>0&&(j.current=e.touches[0].clientY)},[]),te=(0,Q.useCallback)(e=>{if(e.touches.length>0){let t=e.touches[0].clientY-j.current;if(t>8)F(),B(!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,B,_]),ne=(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 re=(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=kx({dSt:t,dSh:n,escaped:w.current,graceActive:i,stuck:S.current});o.reassert&&!a&&I();let{shouldEscape:s,shouldReassert:c}=Ax({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;B(l),b(e=>e===S.current?e:S.current),p(),m()},[p,m,I,F,B,_]),ie=(0,Q.useRef)(!!n);(0,Q.useEffect)(()=>{let e=ie.current;if(ie.current=!!n,jx({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 H=c.length>0?c[c.length-1].id:null,ae=(0,Q.useRef)(`${o??``}:${s??``}`),U=(0,Q.useRef)(H);(0,Q.useEffect)(()=>{let e=`${o??``}:${s??``}`,t=e!==ae.current,n=_.current,r=!n||n.scrollHeight-n.scrollTop-n.clientHeight<36,i=!!(H&&f_(H)),{shouldScroll:a}=Mx({convChanged:t,lastQuestionId:H,prevLastQuestionId:U.current,escaped:w.current,nearBottom:r,hasJumpTarget:!!(l||u)});ae.current=e,U.current=H,(a||i)&&L()},[o,s,H,l,u,L]);let oe=(0,Q.useRef)(h??0);(0,Q.useEffect)(()=>{let e=h??0;e>oe.current&&(oe.current=e,L())},[h,L]),(0,Q.useLayoutEffect)(()=>{_.current&&S.current&&!w.current&&I()},[t,n,r,i,I,_]);let se=a?a.steering.join(`\0`)+``+a.followUp.join(`\0`):``,ce=a?a.steering.length+a.followUp.length:0,W=(0,Q.useRef)(ce);return(0,Q.useLayoutEffect)(()=>{let e=ce>W.current;if(W.current=ce,e){L();return}_.current&&S.current&&!w.current&&I()},[se,ce,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:ee,handleTouchStart:V,handleTouchMove:te,handlePointerDown:ne,onScroll:re}}var Fx=[{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 Ix(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 Lx(e){return e.trim().replace(/^\//,``).toLowerCase()}function Rx(e){return/^[a-z][a-z0-9_-]*$/.test(e)}function zx(e,t){let n=new Set([`help`,`copy`,...t.map(e=>e.name.toLowerCase())]);return e.filter(e=>{let t=Lx(e.command??``);return!Rx(t)||n.has(t)?!1:(n.add(t),!0)})}function Bx(e,t,n=new Date){let r=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!r)return e;let i=t.find(e=>Lx(e.command??``)===r[1].toLowerCase());if(!i)return e;let a=r[2]??``;return Ix(i.prompt.includes(`{{input}}`)?i.prompt.replaceAll(`{{input}}`,()=>a):[i.prompt,a].filter(Boolean).join(`
|
|
75
|
+
|
|
76
|
+
`),n)}var Vx=[{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`}],Hx=`pi-web-ui:prompt-templates`;function Ux(){try{let e=localStorage.getItem(Hx);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 Wx(e){return Vx.some(t=>t.id===e)}function Gx(e){return typeof e.title==`string`}var Kx=(0,Q.createContext)(null);function qx(){let e=(0,Q.useContext)(Kx);if(!e)throw Error(`useTemplates must be used within TemplateProvider`);return e}function Jx({children:e,currentModelId:t}){let n=W(),r=He(`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(g(`/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}},[]),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,_]=(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(g(`/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=Ux();if(e.length&&await u({action:`migrate`,templates:e}))try{localStorage.removeItem(Hx)}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):(Gx(n)&&!Wx(n.id)||Gx(n))&&e.set(n.id,n);let r=Vx.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=>Gx(e)&&!Wx(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)(()=>f(!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),m({...e})):(_(!0),m({id:Ht(),icon:`📌`,title:``,desc:``,prompt:``}))},[]),E=(0,Q.useCallback)(()=>{f(!1),m(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=>{f(!1),w(e.prompt)},[w]),k=(0,Q.useCallback)(e=>{f(!1),T(e,!0)},[T]),A=(0,Q.useCallback)(()=>{f(!1),T(void 0,!0)},[T]),j=(0,Q.useCallback)(async e=>{await u({action:`upsert`,template:e})&&(m(null),b&&(f(!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})&&(m(null),b&&(f(!0),x(!1)))},[b]),N=(0,Q.useCallback)(async e=>{await u({action:`remove`,id:e.id})&&(m(null),b&&(f(!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=p?i.some(e=>e.id===p.id&&!e.hidden&&Gx(e)):!1;return(0,$.jsxs)(Kx.Provider,{value:P,children:[e,o&&(0,$.jsxs)(`div`,{className:`template-error`,role:`alert`,children:[n(`tpl.storageError`),`: `,o]}),d&&(0,$.jsx)(Zx,{templates:S,resetConfirm:v,onFill:O,onEditTpl:k,onNew:A,onResetToggle:D,onClose:E}),p&&(0,$.jsx)($x,{editing:p,isNew:h,hasOverride:F,storageError:o,templates:S,onDraft:m,onSave:j,onRestore:()=>N(p),onRemove:()=>M(p),onFill:()=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:p.prompt})),E()},onSend:()=>{let e=Ix(p.prompt.trim());e&&Z({type:`prompt`,text:e,queue:!1})&&(t&&qc(t),E())},onClose:E})]})}function Yx(){let e=W(),{templates:t,fill:n,openEdit:r,toggleReset:i,resetConfirm:a}=qx();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)(Xx,{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)(C,{})}),(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)(me,{}),e(a?`tpl.resetConfirm`:`tpl.reset`)]})})]})}function Xx({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)(J,{})})]})}function Zx({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:i,onResetToggle:a,onClose:o}){let s=W();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal template-picker`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-picker-top`,children:[(0,$.jsxs)(`div`,{className:`template-picker-head`,children:[(0,$.jsx)(`span`,{className:`template-picker-title`,children:s(`tpl.pickerTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:s(`close`),onClick:o,children:(0,$.jsx)(Be,{})})]}),(0,$.jsx)(`div`,{className:`template-picker-hint`,children:s(`tpl.pickerHint`)})]}),(0,$.jsx)(`div`,{className:`template-picker-scroll`,children:(0,$.jsxs)(`div`,{className:`template-picker-grid`,children:[e.map(e=>(0,$.jsx)(Xx,{tpl:e,title:s(`tpl.clickCard`),onFill:()=>n(e),onEdit:()=>r(e),editTitle:s(`tpl.editTpl`)},e.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:i,title:s(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(C,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:s(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:s(`tpl.addDesc`)})]})]})]})}),(0,$.jsx)(`div`,{className:`template-picker-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:a,children:[(0,$.jsx)(me,{}),s(t?`tpl.resetConfirm`:`tpl.reset`)]})})]})})}var Qx=[`📌`,`🚀`,`⚡`,`📝`,`🔍`,`🛠️`,`🎯`,`💡`,`🤖`,`🌐`,`📦`,`🎨`,`🐛`,`🧪`,`✨`];function $x({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=Lx(n.command??``);if(i&&!Rx(i)){a({...n,error:f(`tpl.commandInvalid`)});return}if(i&&t.some(e=>e.id!==n.id&&Lx(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:Qx.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)(Be,{})})]}),(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:Fx.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)(_t,{}),` `,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)(_t,{}),` `,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)(O,{}),` `,f(`tpl.sendNow`)]})]})]})]})})}var eS=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 tS(e,t){return!e||e.length===0?null:(0,$.jsx)(`span`,{className:`slot-toolbar`,children:e.map((e,n)=>(0,$.jsx)(eS,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:nS(e,n,t)},`${e.id}#${n}`))})}function nS(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 rS(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)(eS,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:nS(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 iS=`#ffffff`,aS=`#1e1e1e`,oS=`.msg-actions, .msg-text-copy, .chead-copy, .stream-cursor, .msg-editor, .msg-collapse-btn, .msg-export-check, .toolcall-kill, .toolcall-open`,sS=16384;function cS(e,t=800,n=2){let r=Math.max(e,t,1);return r*n<=sS?n:+(r<=sS)}function lS(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=dS(t.trim())}else if(r.includes(`,`)){let e=r.split(`,`).map(e=>e.trim());e.length===4&&(a=dS(e.pop())),i=e}else i=r.split(/\s+/).filter(Boolean),i.length===4&&(a=dS(i.pop()));if(i.length!==3)return null;let o=uS(i[0]),s=uS(i[1]),c=uS(i[2]);return[o,s,c,a].some(e=>Number.isNaN(e))?null:{r:o,g:s,b:c,a}}function uS(e){return e.endsWith(`%`)?Math.round(fS(Number.parseFloat(e),0,100)*2.55):Math.round(fS(Number.parseFloat(e),0,255))}function dS(e){return e.endsWith(`%`)?fS(Number.parseFloat(e)/100,0,1):fS(Number.parseFloat(e),0,1)}function fS(e,t,n){return Math.min(n,Math.max(t,e))}function pS(e){let t=fS(Math.round(e.r),0,255),n=fS(Math.round(e.g),0,255),r=fS(Math.round(e.b),0,255);return e.a<.996?`rgba(${t}, ${n}, ${r}, ${Math.round(fS(e.a,0,1)*1e3)/1e3})`:`rgb(${t}, ${n}, ${r})`}function mS(e,t){let n=fS(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 hS(e,t){let n=lS(t)??{r:255,g:255,b:255,a:1},r=lS(e);return!r||r.a<=.004?pS({...n,a:1}):pS(mS(r,{...n,a:1}))}function gS(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 _S(e){return gS(e)>.45}function vS(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 yS(){return getComputedStyle(document.documentElement).colorScheme.split(/\s+/).includes(`light`)?iS:aS}function bS(e){let t=yS(),n=t;try{n=hS(vS(`var(--bg)`),t)}catch{n=t}try{let e=hS(vS(`var(--card-bg, var(--msgs-bg, var(--bg)))`),n),t=lS(e);if(t&&gS(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=hS(e,n),r=lS(e);if(r&&r.a>.04)return t}r=r.parentElement}return n}function xS(e){return e instanceof HTMLElement||e instanceof SVGElement?e.style:null}function SS(e,t){let n=lS(e);return n?n.a<=.004?`transparent`:n.a>=.996?pS({...n,a:1}):pS(mS(n,{...lS(t)??{r:255,g:255,b:255,a:1},a:1})):null}function CS(e,t,n){let r=getComputedStyle(e),i=xS(t),a=n;if(i){let e=SS(r.backgroundColor,n);e===`transparent`?i.backgroundColor=`transparent`:e&&(i.backgroundColor=e,a=e);let t=SS(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=SS(r[e],a);t&&t!==`transparent`&&(i[e]=t)}let o=SS(r.fill,a);o&&o!==`transparent`&&r.fill!==`none`&&(i.fill=o);let s=SS(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++)CS(o[e],s[e],a)}function wS(e){e.querySelectorAll(oS).forEach(e=>e.remove())}function TS(e,t={}){t.includeThinking||e.querySelectorAll(`.thinking`).forEach(e=>e.remove()),t.includeTools||e.querySelectorAll(`.toolcall`).forEach(e=>e.remove())}function ES(e,t,n={}){let r=e.cloneNode(!0);return CS(e,r,t),TS(r,n),wS(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 DS(e,t={}){let{toBlob:n}=await _d(async()=>{let{toBlob:e}=await import(`./es-DWMIuDU2.js`);return{toBlob:e}},[],import.meta.url),r=t.backgroundColor??bS(e),i=lS(r),a=await n(e,{pixelRatio:t.pixelRatio??2,backgroundColor:r,cacheBust:!1,style:{colorScheme:i&&!_S(i)?`dark`:`light`}});if(!a)throw Error(`toBlob returned null`);return a}function OS(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function kS(e){return document.querySelector(`.msg[data-msg-id="${OS(e)}"]`)??document.querySelector(`[data-msg-id="${OS(e)}"]`)}function AS(){let e=W(),t=Tg(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`pi-web-ui`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),b=(0,Q.useRef)(`#ffffff`);if((0,Q.useEffect)(()=>{t.open&&(d(!1),h(!1),_(``))},[t.open]),Vt(()=>{Eg()},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=kS(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=bS(s??void 0);b.current=c;let l=document.createDocumentFragment();for(let e of i)l.appendChild(ES(e,c,{includeThinking:t.includeThinking,includeTools:t.includeTools}));y.current.replaceChildren(l);let u=v.current;if(u){u.style.backgroundColor=c;let e=lS(c);if(u.style.colorScheme=e&&!_S(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=cS(n.scrollHeight,n.scrollWidth);if(t===0){_(e(`exportTooLong`));return}let r=await DS(n,{backgroundColor:b.current,pixelRatio:t});await navigator.clipboard.write([new ClipboardItem({"image/png":r})]),h(!0),window.setTimeout(()=>h(!1),1500)}catch(t){let n=t instanceof Error?t.message:String(t);_(`${e(`copyFailed`)}: ${n}`)}finally{d(!1)}}};return(0,$.jsxs)(`aside`,{className:`saveimg-dock`,role:`dialog`,"aria-label":e(`saveAsImage`),children:[(0,$.jsxs)(`div`,{className:`saveimg-head`,children:[(0,$.jsx)(`span`,{className:`saveimg-title`,children:e(`saveAsImage`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),"aria-label":e(`close`),onClick:()=>Eg(),children:(0,$.jsx)(Be,{})})]}),(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=>Og({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=>Og({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)(kl,{className:`saveimg-spin`}):m?(0,$.jsx)(Ge,{}):(0,$.jsx)(x,{}),(0,$.jsx)(`span`,{children:e(u||f?`savingImage`:m?`copied`:`copyImageBtn`)})]})]})]}),g?(0,$.jsx)(`div`,{className:`saveimg-error`,children:g}):null]})]})}var jS=`.msg-text, .attachcard-content, .toolcall-output pre, .bashblock-output, .quote-content`,MS=`button, input, textarea, [contenteditable], .msg-meta, .msg-actions, .chead, .toolcall-output-label`;function NS(e){return e.nodeType===1?e:e.parentElement}function PS(e,t,n){if(!t||t.isCollapsed||t.rangeCount!==1)return null;let r=t.getRangeAt(0),i=NS(r.startContainer),a=NS(r.endContainer);if(!i||!a||!e.contains(i)||!e.contains(a)||!i.closest(jS)||!a.closest(jS)||i.closest(MS)||a.closest(MS))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(MS))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 FS({rootRef:e,sessionId:t,enabled:n=!0,translateEnabled:r=!0,onSelect:i}){let a=W(),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{s(null);let a=e.current;if(!a||!n)return;let o=!1,c=0,l=()=>{cancelAnimationFrame(c),s(null)},u=()=>{cancelAnimationFrame(c),c=requestAnimationFrame(()=>{let e=window.getSelection(),n=PS(a,e,t);if(!n||!e){s(null);return}let o=e.getRangeAt(0).getBoundingClientRect();if(!o.width&&!o.height){s(null);return}i?.(),s({quote:n,left:Math.max(8,Math.min(o.right-(r?240:176),window.innerWidth-(r?248:184))),top:Math.max(8,Math.min(o.top>=44?o.top-40:o.bottom+8,window.innerHeight-42))})})},d=e=>{e.target?.closest?.(`.quote-selection-toolbar, .quick-ask-popover`)||(o=e.button===0&&a.contains(e.target),l())},f=e=>{o=!1,e.button===0&&u()},p=()=>{o||u()},m=e=>{e.key===`Escape`&&l()};return document.addEventListener(`mousedown`,d),document.addEventListener(`mouseup`,f),document.addEventListener(`selectionchange`,p),document.addEventListener(`keydown`,m),window.addEventListener(`scroll`,l,!0),window.addEventListener(`resize`,l),window.addEventListener(`blur`,l),()=>{cancelAnimationFrame(c),document.removeEventListener(`mousedown`,d),document.removeEventListener(`mouseup`,f),document.removeEventListener(`selectionchange`,p),document.removeEventListener(`keydown`,m),window.removeEventListener(`scroll`,l,!0),window.removeEventListener(`resize`,l),window.removeEventListener(`blur`,l)}},[e,t,n,r,i]),!n||!o||o.quote.sessionId!==t?null:(0,cr.createPortal)((0,$.jsxs)(`div`,{className:`quote-selection-toolbar`,role:`group`,style:{left:o.left,top:o.top},onMouseDown:e=>e.preventDefault(),children:[(0,$.jsxs)(`button`,{type:`button`,className:`quote-selection-button`,onClick:()=>{dn({attachments:[{path:``,name:a(`quoteText`),mode:`quote`,quote:o.quote,key:Ht()}]})&&(s(null),window.getSelection()?.removeAllRanges(),sn())},children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),` `,a(`quoteSelection`)]}),(0,$.jsx)(`button`,{type:`button`,className:`quote-selection-button selection-explain-trigger`,onClick:e=>{let t=e.currentTarget.parentElement.getBoundingClientRect();jl({selection:o.quote.text,action:`explain`,anchor:{left:t.left,right:t.right,top:t.top,bottom:t.bottom}}),s(null),window.getSelection()?.removeAllRanges()},children:a(`explainSelection`)}),r&&(0,$.jsx)(`button`,{type:`button`,className:`quote-selection-button selection-translate-trigger`,onClick:e=>{let t=e.currentTarget.parentElement.getBoundingClientRect();jl({selection:o.quote.text,action:`translate`,anchor:{left:t.left,right:t.right,top:t.top,bottom:t.bottom}}),s(null),window.getSelection()?.removeAllRanges()},children:a(`quickAskTranslate`)})]}),document.body)}var IS=new Map,LS=new Set,RS=new Map,zS=15,BS=5,VS=100,HS=30,US=1200,WS=2400,GS=1600;function KS({kind:e,text:t,index:n,id:r,onRemoveQueued:i,onRecallQueued:a}){let o=W(),s=id(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)(ld,{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?pn({src:e.url.startsWith(`/`)?ne(e.url):e.url,alt:e.name}):n&&e.path&&Hf({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)(rp,{text:s.text,hardBreaks:!0}):null]})})]})}function qS({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 JS(e){return e.content.some(e=>e.type===`toolCall`)}function YS(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 XS(e){return Array.isArray(e.content)?e.content.some(e=>{let t=Vg(e);return t&&t.text.trim().length>0}):!1}function ZS(e){return e.role&&e.role!==`assistant`||e.customType||!Array.isArray(e.content)||e.content.length===0||XS(e)?!1:e.content.some(e=>e.type===`toolCall`||e.type===`thinking`)}function QS(e){return e.customType?!1:e.role===`assistant`||!e.role}function $S(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=ox(a),s=QS(a),c=ZS(a),l=!c&&!!i&&s&&!o&&t===e.length-1&&!XS(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 eC(e,t=!1){return t?Math.max(48,Math.ceil(e.length/4)*30):Math.max(48,e.length*52)}var tC=(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 nC({state:e,liveOutputs:t,toolStatuses:n,onEdit:r,onKillBash:i,onRetry:a,onRemoveQueued:o,onRecallQueued:s,thinkingWrap:c,quickAskTranslateEnabled:l=!0,toolsWrap:u,toolImages:d,keepRecent:f,reversePagination:p=!1,minimalNewChat:m=!1,jumpTarget:h,onJumpDone:g,urlJumpMessageId:_,onUrlJumpDone:v,preview:y=!1,userPromptNonce:b,messageLabels:x,readOnly:S=!1,uiMessageActions:C,uiContextMessage:w,uiContextToolCall:T,uiToolCardFooter:E,uiChatEmpty:D,onUiAction:O}){let k=W(),A=Tg(),j=(0,Q.useRef)(null),M=(0,Q.useRef)(!0),N=(0,Q.useRef)(!1),[P,F]=(0,Q.useState)(()=>new Set),[I,L]=(0,Q.useState)(!1),R=(0,Q.useMemo)(()=>e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,[e.messages,e.streamingMessage]),z=(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]),B=(0,Q.useMemo)(()=>$b(e.messages),[e.messages]),ee=(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]),[V,te]=(0,Q.useState)(null),ne=(0,Q.useMemo)(()=>{for(let e=R.length-1;e>=0;e--)if(R[e].role!==`system`)return R[e].id;return null},[R]),re=Math.min(VS,Math.max(BS,Math.floor(Number(f)||zS))),ie=(0,Q.useMemo)(()=>{let t=new Set;for(let n of e.messages)n.role!==`toolResult`&&ox(n)&&!P.has(n.id)&&t.add(n.id);return t},[e.messages,P]),H=lx(),ae=(0,Q.useMemo)(()=>({mergeTurns:!0}),[]),[U,oe]=(0,Q.useState)(()=>{if(p||e.messages.length<=HS)return new Set;let t=px(e.messages,new Map,Math.max(GS,re*120)),n=new Set;for(let r of e.messages)t.has(r.id)||n.add(r.id);for(let r of $S(e.messages,ae))r.type===`tool_cluster`&&r.messages.every(e=>!t.has(e.id))&&n.add(r.id);return n}),[se,ce]=(0,Q.useState)(()=>new Set),le=(0,Q.useRef)(new Map),G=(0,Q.useRef)(new Map),K=(0,Q.useRef)(new Map),ue=(0,Q.useRef)(0),de=(0,Q.useRef)(0),fe=(0,Q.useRef)(0),pe=(0,Q.useRef)(null),q=Math.max(H?240:60,re*2),me=H?120:30,he=Math.min(q,10),[ge,_e]=(0,Q.useState)(()=>he),ve=`${e.conversationId??``}:${e.sessionFile??``}`,[J,be]=(0,Q.useState)(y),xe=J&&!y;J!==y&&be(y);let Se=(0,Q.useRef)(ve),Ce=(0,Q.useRef)(R.length),Y=(0,Q.useRef)(R[0]?.id),we=(0,Q.useRef)(null),Te=(0,Q.useRef)(null),Ee=(0,Q.useRef)(!1),[De,Oe]=(0,Q.useState)(!1),ke=(0,Q.useRef)(!1),Ae=(0,Q.useCallback)(e=>{ke.current=e,Oe(e)},[]),je=(0,Q.useRef)(0),Me=(0,Q.useRef)(null),Ne=(0,Q.useCallback)(()=>{let e=j.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},[]),Pe=(0,Q.useCallback)(()=>{je.current&&=(cancelAnimationFrame(je.current),0),Me.current=null},[]),Fe=(0,Q.useCallback)(()=>{let e=j.current,t=Ne();Te.current={sh:e?e.scrollHeight:0,st:e?e.scrollTop:0,id:t?.id??null,top:t?.top??0,msgLen:R.length,firstId:R[0]?.id}},[Ne,R]),Ie=(0,Q.useCallback)(e=>{let t=j.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)}},[]),Le=(0,Q.useCallback)(()=>{let e=Te.current,t=j.current;if(!t||!e)return;Pe(),Ae(!0),Ie(e);let n=Ne();Me.current={id:n?.id??null,top:n?.top??0,sh:t.scrollHeight,st:t.scrollTop};let r=0,i=0,a=()=>{je.current=0;let e=j.current,t=Me.current;if(!e||!t){Ae(!1);return}if(Math.abs(e.scrollTop-t.st)>2){let t=Ne();Me.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),Me.current={...t,sh:e.scrollHeight,st:e.scrollTop};else{n=e.scrollHeight-t.sh;let r=Ne();n!==0&&(e.scrollTop+=n),Me.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){Me.current=null,Ae(!1);return}je.current=requestAnimationFrame(a)};je.current=requestAnimationFrame(a)},[Pe,Ne,Ie,Ae]);(Se.current!==ve||xe)&&(Se.current=ve,we.current=null,_e(xe?Math.max(he,Math.min(ge,Ce.current)):he),Ce.current=R.length,Y.current=R[0]?.id,Te.current=null,Pe(),ke.current&&Ae(!1),Ee.current=!1),(0,Q.useLayoutEffect)(()=>{let e=R.length-Ce.current;Ce.current=R.length;let t=R[0]?.id,n=t!==Y.current;Y.current=t,!(e<=0)&&(_e(t=>t+e),n&&(Ee.current=!1))},[R.length]),(0,Q.useLayoutEffect)(()=>{let e=Te.current;if(!e)return;let t=R[0]?.id!==e.firstId,n=R.length===e.msgLen&&!t;if(t||n){if(Ee.current&&n){Le(),Fe();return}Te.current=null,Le()}},[ge]);let Re=!!p&&!A.open&&!I;(0,Q.useEffect)(()=>{if(!Re||ge>=q)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{(0,Q.startTransition)(()=>_e(e=>e<q?q:e))})});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[Re,ge,q,ve]);let ze=Re?Math.min(R.length,ge):R.length;(0,Q.useEffect)(()=>{Ee.current=!1},[e.historyStart,e.historyTotal]);let Be=Math.max(0,e.historyStart??0),Ve=(0,Q.useRef)(Be);Ve.current=Be;let He=qv({isPagingActive:Re,totalMessages:R.length,visibleCount:ge,historyStart:Be}),Ue=!y&&!A.open&&!I&&He>0,We=Re&&ze<R.length?R.slice(-ze):R,Ge=(0,Q.useCallback)(t=>{if(y||S||Ee.current)return;Ee.current=!0,Pe(),Fe();let n=R[0]?.id,r=Ve.current;Z(t.all?{type:`load_earlier_messages`,all:!0,conversationId:e.conversationId??void 0,beforeId:n,before:r}:{type:`load_earlier_messages`,count:t.count??me,conversationId:e.conversationId??void 0,beforeId:n,before:r}),setTimeout(()=>{Ee.current=!1},3e3)},[y,S,R,me,Pe,Fe,e.conversationId]),X=(0,Q.useCallback)(e=>{if(y)return;let t=e??me;if(Pe(),Re&&R.length-ge>=t){Fe(),_e(e=>Math.min(R.length,e+t));return}Re&&R.length>ge&&(Fe(),_e(R.length)),Ve.current>0&&Ge({count:t})},[Re,R,ge,Ge,me,Pe,Fe]),Ke=(0,Q.useRef)(Ue);Ke.current=Ue;let qe=(0,Q.useRef)(X);qe.current=X,(0,Q.useEffect)(()=>{let t=e.conversationId;if(!t||we.current===t||!Ue||y)return;let n=setTimeout(()=>{we.current!==t&&(we.current=t,Ke.current&&X())},150);return()=>clearTimeout(n)},[e.conversationId,Ue,y,X]);let Je=!y&&(I||A.open);(0,Q.useEffect)(()=>{Je&&Ve.current>0&&Ge({all:!0})},[Je,Ge]);let Ye=(0,Q.useMemo)(()=>$S(We,ae),[We,ae]),Xe=!p&&e.messages.length>HS&&!I,Ze=(0,Q.useRef)(Xe);Ze.current=Xe;let Qe=(0,Q.useMemo)(()=>Xe?px(R,le.current,Math.max(GS,re*120)):LS,[Xe,R,re]),$e=(0,Q.useMemo)(()=>{let e=new Set(Qe);for(let t of Ye)t.type===`tool_cluster`&&t.messages.some(e=>Qe.has(e.id))&&e.add(t.id);return e},[Qe,Ye]),et=(0,Q.useRef)($e);et.current=$e;let tt=(0,Q.useMemo)(()=>{if(!Xe)return RS;let t=new Map;for(let n of e.messages)t.set(n.id,gx(n));for(let e of Ye)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},[Xe,e.messages,Ye]),nt=(0,Q.useRef)(U),rt=U,it=(0,Q.useRef)(ve);if(it.current!==ve||xe){it.current=ve;{let t=new Set(e.messages.map(e=>e.id));for(let n of $S(e.messages,ae))n.type===`tool_cluster`&&t.add(n.id);for(let e of K.current.keys())t.has(e)||K.current.delete(e)}if(!p&&e.messages.length>HS){let t=px(e.messages,le.current,Math.max(GS,re*120)),n=xe?new Set(K.current.keys()):null,r=new Set;for(let i of e.messages)!t.has(i.id)&&!n?.has(i.id)&&r.add(i.id);for(let i of $S(e.messages,ae))i.type===`tool_cluster`&&!n?.has(i.id)&&i.messages.every(e=>!t.has(e.id)&&!n?.has(e.id))&&r.add(i.id);rt=r,oe(r),nt.current=r}else if(U.size>0){let e=new Set;rt=e,oe(e),nt.current=e}}nt.current=rt;let at=(0,Q.useRef)(tt);at.current=tt;let ot=YS((0,Q.useRef)({convKey:ve,pending:null,finalizedMap:new Map}).current,ve,e.messages,e.streamingMessage,(e,t)=>{let n=le.current.get(e);n!==void 0&&!le.current.has(t)&&le.current.set(t,n)}),st=(0,Q.useCallback)((e,t,n)=>{n!==void 0&&(G.current.set(e,{h:t,len:n}),le.current.set(e,t))},[]),ct=(0,Q.useCallback)((e,t)=>{st(e,t,at.current.get(e))},[st]),lt=(0,Q.useCallback)((t=!1)=>{let n=j.current;if(!n)return;if(!Ze.current){oe(e=>e.size?new Set:e);return}if(!t&&Math.abs(n.scrollTop-de.current)<200&&e.messages.length===fe.current)return;de.current=n.scrollTop,fe.current=e.messages.length;let r=n.getBoundingClientRect(),i={top:r.top-US,bottom:r.bottom+US},a={top:r.top-WS,bottom:r.bottom+WS},o=[];for(let[e,t]of K.current){let n=t.getBoundingClientRect();o.push({id:e,top:n.top,bottom:n.bottom}),nt.current.has(e)||st(e,n.bottom-n.top,at.current.get(e))}let s=dx(o,i,et.current,nt.current,a);for(let e of s.hide){let t=K.current.get(e);t&&st(e,t.offsetHeight,at.current.get(e))}oe(e=>fx(e,s))},[st,e.messages.length]),ut=(0,Q.useCallback)(()=>{pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{pe.current=null,lt(!0)},120),!ue.current&&(ue.current=requestAnimationFrame(()=>{ue.current=0,lt(!1)}))},[lt]);(0,Q.useEffect)(()=>{ut()},[ut,e.conversationId,e.sessionFile,e.messages.length]);let dt=(0,Q.useRef)(I);(0,Q.useLayoutEffect)(()=>{dt.current&&!I&<(!0),dt.current=I},[I,lt]);let ft=(0,Q.useCallback)(e=>{e&&K.current.set(e.dataset.lazyId??``,e)},[]);(0,Q.useEffect)(()=>{let t=new Set(e.messages.map(e=>e.id));for(let e of Ye)e.type===`tool_cluster`&&t.add(e.id);for(let e of K.current.keys())t.has(e)||(K.current.delete(e),le.current.delete(e),G.current.delete(e));oe(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,Ye,P]),(0,Q.useEffect)(()=>()=>{cancelAnimationFrame(ue.current),Pe(),pe.current&&clearTimeout(pe.current)},[]);let pt=(0,Q.useMemo)(()=>{let t=[];for(let n of e.messages){if(n.role!==`user`)continue;let e=n.content.map(e=>Vg(e)?.text??``).filter(Boolean).join(` `),r=Lh(e),i=r?r.userMessage??`skill:${r.name}`:e.trim();i&&t.push({id:n.id,text:i})}return t},[e.messages]),mt=(0,Q.useMemo)(()=>{let e=new Map;return pt.forEach((t,n)=>e.set(t.id,n)),e},[pt]),[ht,gt]=(0,Q.useState)(-1),_t=(0,Q.useRef)(-1),vt=(0,Q.useRef)(0),yt=(0,Q.useRef)(pt);(0,Q.useEffect)(()=>{yt.current=pt},[pt]);let bt=(0,Q.useCallback)(()=>{let e=j.current,t=yt.current;if(!e||t.length===0)return;if(M.current&&!N.current){let e=t.length-1;e!==_t.current&&(_t.current=e,gt(e));return}let n=e.getBoundingClientRect().top,r=-1;for(let i=0;i<t.length;i++){let a=K.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!==_t.current&&(_t.current=r,gt(r))},[]),xt=(0,Q.useCallback)(()=>{vt.current||=requestAnimationFrame(()=>{vt.current=0,bt()})},[bt]);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(vt.current),[]),(0,Q.useEffect)(()=>{bt()},[pt,bt]);let St=(0,Q.useCallback)(e=>{F(t=>t.has(e)?t:new Set(t).add(e))},[]);(0,Q.useLayoutEffect)(()=>{Sg(e.messages.filter(bg).map(e=>({id:e.id,role:e.role,content:e.content})))},[e.messages]),(0,Q.useEffect)(()=>{if(A.open){for(let e of A.selectedIds)St(e);ce(e=>{let t=!1,n=new Set(e);for(let e of A.selectedIds)n.has(e)||(n.add(e),t=!0);return t?n:e})}},[A.open,A.selectedIds,St]),(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(),L(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let Ct=(0,Q.useCallback)(e=>{F(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),wt=(0,Q.useCallback)(e=>{if(Re){let t=R.findIndex(t=>t.id===e);t!==-1&&t<R.length-ge&&(0,cr.flushSync)(()=>{_e(R.length-t+5)})}(0,cr.flushSync)(()=>{St(e),ce(t=>t.has(e)?t:new Set(t).add(e))});let t=yt.current.findIndex(t=>t.id===e);_t.current=t,gt(t),requestAnimationFrame(()=>{let t=j.current?.querySelector(`[data-msg-id="${e}"]`);t&&(j.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!==j.current?.lastElementChild&&(N.current=!0))})},[St]),Tt=(0,Q.useCallback)(t=>{let n=ee.get(t);n&&r&&(wt(n),te({id:n,session:e.sessionFile}))},[ee,r,wt,e.sessionFile]),[Et,Dt]=(0,Q.useState)(null),Ot=(0,Q.useRef)(null),kt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let t=Ot.current;if(!t||t.convId!==e.conversationId){Ot.current={convId:e.conversationId,ids:new Set(e.messages.filter(e=>e.role===`compactionSummary`).map(e=>e.id))},kt.current=null,Dt(null);return}for(let n of e.messages)if(n.role===`compactionSummary`&&!t.ids.has(n.id)){t.ids.add(n.id),Dt(n.id);break}},[e.messages,e.conversationId]),(0,Q.useEffect)(()=>{Et&&kt.current!==Et&&(kt.current=Et,wt(Et))},[Et,wt]);let At=(0,Q.useMemo)(()=>h?e.messages.find(e=>e.role===h.role&&e.timestamp===h.timestamp)?.id??null:null,[e.messages,h]);(0,Q.useEffect)(()=>{if(h){if(At){wt(At),g?.();return}e.sessionFile===h.path&&e.messages.length>0&&g?.()}},[At,wt,g,h,e.sessionFile,e.messages.length]),(0,Q.useEffect)(()=>{if(!_)return;let t=Ul(e.messages,_);if(t){wt(t),v?.();return}e.messages.length>0&&v?.()},[_,e.messages,wt,v]);let{railRef:jt,stickBottom:Mt,scrollToBottom:Nt,pauseForSelection:Pt,handleWheel:Ft,handleTouchStart:It,handleTouchMove:Lt,handlePointerDown:Rt,onScroll:zt}=Px({scrollRef:j,stickRef:M,escapedRef:N,messages:R,isStreaming:e.isStreaming,liveOutputs:t,toolStatuses:n,queue:e.queue,conversationId:e.conversationId,sessionFile:e.sessionFile,questions:pt,jumpTarget:h,urlJumpMessageId:_,hasEarlier:Ue,loadEarlier:X,scheduleActiveFromScroll:xt,scheduleSweep:ut,userPromptNonce:b}),[Bt,Vt]=(0,Q.useState)(0),Ht=pt.length>0;(0,Q.useLayoutEffect)(()=>{let e=jt.current;if(!e)return;let t=()=>Vt(e.clientHeight);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[Ht,jt]),(0,Q.useEffect)(()=>(window.addEventListener(`resize`,ut),()=>window.removeEventListener(`resize`,ut)),[ut]);let{indices:Ut,gap:Wt,many:Gt}=(0,Q.useMemo)(()=>ex(pt.length,Bt,ht),[pt.length,Bt,ht]);return(0,$.jsxs)(`div`,{className:`messages-wrap${A.open?` messages-exporting`:``}`,children:[(0,$.jsx)(FS,{rootRef:j,sessionId:e.sessionId,enabled:!A.open,translateEnabled:l,onSelect:Pt}),(0,$.jsxs)(`div`,{className:`messages${I||De||Mt&&!N.current?``:` anchor-live`}`,ref:j,onScroll:zt,onWheel:Ft,onTouchStart:It,onTouchMove:Lt,onPointerDown:Rt,children:[e.messages.length===0&&!e.streamingMessage&&!m&&(0,$.jsxs)(`div`,{className:`empty-state`,children:[(0,$.jsx)(Yx,{}),!S&&D&&D.length>0&&(0,$.jsx)(`div`,{className:`chat-empty-slots`,children:tS(D,O)})]}),Ye.map(o=>{if(o.type===`tool_cluster`){let s=e.streamingMessage?.id,l=(s?o.messages.some(e=>e.id===s):!1)||e.isStreaming&&o.messages.some(e=>e.id===ne),f=o.messages.some(e=>se.has(e.id)),p=o.messages.some(e=>$e.has(e.id)),m=rt.has(o.id),h=!H&&!o.messages.every(ZS),g=!Xe||l||f||p||!m,_=o.messages.filter(ZS).length>=4;return(0,$.jsx)(tC,{id:o.id,show:g,placeholderHeight:_x(o.id,tt.get(o.id)??-1,G.current,eC(o.messages,H)),attachEl:ft,onMeasured:ct,variant:H?`flow`:h?`contents`:`trail`,children:o.messages.map(o=>{let s=(e.streamingMessage?o.id===e.streamingMessage.id:e.isStreaming&&o.id===ne)&&(o.role===`assistant`||!o.role),l=ot.get(o.id)??o.id,f=_?s?u:!1:u;return(0,$.jsx)(Qg,{uiMessageActions:C,uiContextMessage:w,uiContextToolCall:T,uiToolCardFooter:E,onUiAction:S?void 0:O,message:o,toolResults:z,liveOutputs:JS(o)?t:IS,toolStatuses:n,streaming:s,onKillBash:S?void 0:i,onRetry:!S&&o.id===ne?a:void 0,toolsWrap:f,toolImages:d,thinkingWrap:c,isLast:o.id===ne,onEdit:S?void 0:r,readOnly:S,messageLabel:x?.get(o.id),onRollbackEdit:Tt,canRollbackEdit:!S&&!!r&&ee.has(o.id),questionAttachments:B.get(o.id),editRequest:V&&V.session===e.sessionFile&&V.id===o.id?V:void 0,searchActive:I},l)})},`cluster-${ot.get(o.messages[0].id)??o.messages[0].id}`)}let s=o.message,l=ox(s);if(l&&!P.has(s.id))return(0,$.jsx)(tx,{message:s,onExpand:St,summary:l.kind===`prompt`?k(`goalBarReviewing`):l.verdict===`pass`?k(`goalBarPassed`):k(`goalBarFailed`)},s.id);let f=s.role===`user`?mt.get(s.id):void 0,p=!Xe||$e.has(s.id)||se.has(s.id)||!rt.has(s.id),m=(e.streamingMessage?s.id===e.streamingMessage.id:e.isStreaming&&s.id===ne)&&(s.role===`assistant`||!s.role),h=ot.get(s.id)??s.id;return(0,$.jsx)(ux,{id:s.id,show:p,height:_x(s.id,tt.get(s.id)??-1,G.current,mx(s.role,s.customType)),containerRef:j,onMeasured:ct,lazyRef:ft,children:(0,$.jsx)(Qg,{uiMessageActions:C,uiContextMessage:w,uiContextToolCall:T,uiToolCardFooter:E,onUiAction:S?void 0:O,message:s,qnIndex:f,qnActive:f===void 0?void 0:f===ht,onJump:wt,toolResults:z,liveOutputs:JS(s)?t:IS,toolStatuses:n,streaming:m,onKillBash:S?void 0:i,onRetry:!S&&s.id===ne?a:void 0,toolsWrap:u,toolImages:d,thinkingWrap:c,isLast:s.id===ne,onEdit:S?void 0:r,readOnly:S,messageLabel:x?.get(s.id),onRollbackEdit:Tt,canRollbackEdit:!S&&!!r&&ee.has(s.id),editRequest:V&&V.session===e.sessionFile&&V.id===s.id?V:void 0,questionAttachments:B.get(s.id),onCollapse:l?Ct:void 0,searchActive:I,autoExpand:s.id===Et},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?k(`retryingApi`,{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):k(`retryingApiSoon`,{error:e.retry.errorMessage})})]}),e.compaction&&(0,$.jsx)(qS,{compaction:e.compaction}),e.isStreaming&&R.length===0&&(0,$.jsx)(`div`,{className:`streaming-wait`,children:k(`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)(KS,{kind:`steer`,text:r,index:t,id:i,onRemoveQueued:S?void 0:o,onRecallQueued:S?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)(KS,{kind:`followUp`,text:r,index:t,id:i,onRemoveQueued:S?void 0:o,onRecallQueued:S?void 0:s},i||`q-fu-${t}`)}),!S&&e.actionSuggestions&&e.actionSuggestions.length>0&&(0,$.jsx)(`div`,{className:`action-suggestions`,"aria-label":k(`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:k(`actionSuggestionsTip`,{prompt:t.prompt}),disabled:e.isStreaming,onClick:()=>{Nt(),Z({type:`prompt`,text:t.prompt})},children:[(0,$.jsx)(`span`,{className:`action-suggestion-label`,children:t.label}),(0,$.jsx)(`span`,{className:`action-suggestion-icon`,"aria-hidden":`true`,children:`↵`})]},t.id))})})]}),!Mt&&(0,$.jsxs)(`button`,{type:`button`,className:`scroll-bottom`,title:k(`backToBottom`),"aria-label":k(`backToBottom`),onClick:Nt,children:[(0,$.jsx)(ye,{}),(0,$.jsx)(`span`,{className:`scroll-bottom-label`,children:k(`backToBottom`)})]}),(0,$.jsx)(Ox,{containerRef:j,messages:R,collapsedIds:ie,toolResults:z,onExpand:St,onProgrammaticScroll:()=>{Pt()},open:I,onClose:()=>L(!1)}),pt.length>0&&(0,$.jsxs)(`div`,{className:`qn-rail ${Gt?`many`:``}`,ref:jt,"aria-label":k(`questionNavTitle`),style:{"--rail-gap":`${Wt}px`},children:[Ut.map(e=>{let t=pt[e];return(0,$.jsx)(`button`,{type:`button`,className:`qn-bar ${e===ht?`active`:``}`,"aria-label":`${e+1}. ${t.text}`,onClick:()=>wt(t.id),children:(0,$.jsxs)(`span`,{className:`qn-bar-text`,children:[e+1,`. `,t.text]})},t.id)}),Gt&&(0,$.jsx)(`div`,{className:`qn-list`,children:pt.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`qn-list-item ${t===ht?`active`:``}`,"aria-label":`${t+1}. ${e.text}`,onClick:()=>wt(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)(AS,{})]})}function rC(e,t){return t?e.trim()?`${e.replace(/\s+$/,``)}\n${t}`:t:e}function iC(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 aC(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 oC(e,t){return t?e?{key:t,clear:e!==t}:{key:t,clear:!1}:{key:e,clear:!1}}function sC(e,t){if(t.length===0)return e;if(e.length===0)return[...t];let n=new Set(e.map(aC).filter(e=>e!==null)),r=[...e];for(let e of t){let t=aC(e);if(t!==null){if(n.has(t))continue;n.add(t)}r.push(e)}return r}function cC(e,t,n,r,i=!1){return!e||!e.trim()?!1:!!(t||i)}function lC(e,t){if(!t||!t.trim())return!1;let n=e.trim();return!(!n||n===t.trim())}function uC(e,t,n){switch(n){case`cancel`:return null;case`append`:return rC(e,t);case`overwrite`:return t}}function dC(e){let t=Number.parseFloat(getComputedStyle(e).lineHeight)||0;return t>0?Math.max(2,t/2):2}var fC=``;function pC(e,t,n=1){return{first:e<=n,last:Math.abs(t-e)<=n}}function mC(e,t){return{first:!e.slice(0,t).includes(`
|
|
77
|
+
`),last:!e.slice(t).includes(`
|
|
78
|
+
`)}}var hC=null;function gC(){if(hC?.isConnected)return hC;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),hC=e,e}function _C(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 vC(e,t){e.textContent=t;let n=document.createElement(`span`);return n.textContent=fC,e.appendChild(n),n.offsetTop}function yC(e){let t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};let r=mC(t,n);if(!r.first&&!r.last||typeof document>`u`||typeof getComputedStyle!=`function`)return r;let i=gC();if(_C(e,i)<=0)return r;let a=vC(i,t.slice(0,n)),o=vC(i,t),s=i.offsetHeight>0;return i.textContent=``,!s&&t!==``?r:pC(a,o,dC(e))}function bC(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 xC=`pi-web-ui:prompt-history`,SC=`pi-web-ui:prompt-history-settings`,CC={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function wC(e){let t=CC;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 TC(){try{let e=localStorage.getItem(SC);return e?wC(JSON.parse(e)):{...CC}}catch{return{...CC}}}function EC(e){let t=wC(e);try{localStorage.setItem(SC,JSON.stringify(t))}catch{}try{let e=kC();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)),AC(e)}catch{}}function DC(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 OC(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 kC(){try{let e=localStorage.getItem(xC);return e?DC(JSON.parse(e)):[]}catch{return[]}}function AC(e){let t=e;for(;t;)try{localStorage.setItem(xC,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 jC(e){let t=e.trim();if(!t)return;let n=TC();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));let r=kC(),i=OC(r,t,n.maxEntries);i!==r&&AC(i)}function MC(){try{localStorage.removeItem(xC)}catch{}}var NC=`skill:`,PC=/[\s\-_./:]/;function FC(e,t){let n=e.toLowerCase();return t===`skill`&&n.startsWith(`skill:`)?[n,n.slice(6)]:[n]}function IC(e,t){let n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r===-1)return-1;if(r>0&&PC.test(t[r-1]))return r;n=r+1}return-1}function LC(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=IC(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||PC.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||PC.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 RC(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=FC(i.name,i.source),o=null;for(let e of a){let t=LC(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 zC=new Set([`p`,`page`,`pages`,`web`,`网页`,`页面`]);function BC(e,t,n,r=10){if(!Array.isArray(t))return[];let i=String(n??``).toLowerCase(),a=i===``||zC.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.tabId??n.origin,name:t,mode:`page`}]}),o.length>=Math.max(0,r))break}return o}function VC(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 HC(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 UC(e,t,n,r=15,i){if(!Array.isArray(t)||r<=0)return[];let a=String(n??``).toLowerCase(),o=a.startsWith(NC),s=o?a.slice(NC.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(NC.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 WC(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 GC(e){return e===void 0||!(e===`@`||/[A-Za-z0-9_]/.test(e))}function KC(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||!GC(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 qC(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 JC(){return typeof window>`u`||typeof navigator>`u`||typeof window.matchMedia!=`function`?!1:qC({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}var YC=`pi-web-send-key`;function XC(e,t){return e===`enter`||e===`mod-enter`?e:t?`mod-enter`:`enter`}function ZC(e){return e.key===`Enter`?XC(e.pref,!!e.isTouch)===`enter`?e.shiftKey?`newline`:`send`:(e.ctrlKey||e.metaKey)&&!e.shiftKey?`send`:`newline`:`ignore`}function QC(){try{let e=localStorage.getItem(YC);return e===`enter`||e===`mod-enter`?e:null}catch{return null}}function $C(e){try{localStorage.setItem(YC,e)}catch{}ew=e;for(let e of tw)e()}var ew=null,tw=new Set;function nw(e){return tw.add(e),()=>{tw.delete(e)}}function rw(){return ew===null&&(ew=QC()),ew}function iw(){return(0,Q.useSyncExternalStore)(nw,rw)}function aw(e=JC()){return XC(iw(),e)}function ow(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}var sw=`pi-web-ui:project-title`,cw={projectName:!0};function lw(e){if(!e||typeof e!=`object`)return{...cw};let t=e;return{projectName:typeof t.projectName==`boolean`?t.projectName:cw.projectName}}function uw(e){return e?e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``:``}function dw(){try{let e=localStorage.getItem(sw);return e?lw(JSON.parse(e)):{...cw}}catch{return{...cw}}}function fw(e){let t=lw(e);try{localStorage.setItem(sw,JSON.stringify(t))}catch{}pw=t;for(let e of mw)e()}var pw=null,mw=new Set;function hw(e){return mw.add(e),()=>{mw.delete(e)}}function gw(){return pw||=dw(),pw.projectName}function _w(){return(0,Q.useSyncExternalStore)(hw,gw)}function vw(e,t=0,n=Date.now()){return!!(e.isComposing||e.keyCode===229||t>0&&n-t<50)}function yw(){let e=(0,Q.useRef)(0);return{onCompositionEnd:()=>{e.current=Date.now()},isImeKey:t=>vw(t,e.current)}}var bw=1;function xw(){return++bw}var Sw=(0,Q.memo)(function({state:e,models:t,modelsLoading:n,onManageModels:r,providerKeys:i={},providers:a,defaultModel:o,compact:s=!1,only:c,onSelectModel:l,onSelectThinking:u,direction:d=`up`}){let f=W(),p=e?.model,m=p?p.id.startsWith(`${p.provider}/`)?p.id:`${p.provider}/${p.id}`:null,[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),[x,S]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!h){S(null);return}if(t.length===0)return;let e=requestAnimationFrame(()=>{let e=b.current;e&&S(e.offsetWidth)});return()=>cancelAnimationFrame(e)},[h,t.length]);let[C,w]=(0,Q.useState)(!1),T=(p?.id??``).toLowerCase(),E=T.includes(`claude`)||T.includes(`gemini`)||T.includes(`sonnet`)||p?.provider===`anthropic`||p?.provider===`google`,D=T.includes(`r1`)||T.includes(`reasoner`)||T.includes(`qwq`),O=e?.availableThinkingLevels&&e.availableThinkingLevels.length>0?new Set(e.availableThinkingLevels):null,A=ho.map(e=>({value:e,label:yo(e,f(`thinking.${e}`),void 0,E),supported:!O||O.has(e)})),[j,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)(null),F=()=>{let e=parseInt(j.trim(),10);if(!Number.isFinite(e)||e<=0)return;P(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)}u?u(n):Z({type:`set_thinking`,level:n}),v(!1)},I=e=>N&&e!==`off`?`${f(`thinkingCustomized`)} (${N.toLocaleString()} tokens)`:A.find(t=>t.value===e)?.label??e,L=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{h||(L.current=!1)},[h]),(0,Q.useEffect)(()=>{w(!1)},[t]),(0,Q.useEffect)(()=>{h&&(y.current?.querySelector(`.dd-item.active`))?.scrollIntoView({block:`nearest`})},[h,m,t.length]);let R=(0,$.jsx)(Zc,{models:t,modelsLoading:n,providerKeys:i,providers:a,defaultModel:o,currentModelId:m,active:h,onEnsureModels:()=>{L.current||t.length>0||n||(L.current=!0,w(!0),Z({type:`list_models`})||w(!1))},loading:C,onRefresh:()=>{w(!0),Z({type:`list_models`})},onManageModels:r?()=>{g(!1),r()}:void 0,onPickModel:(e,t)=>{if(l){l(e),g(!1);return}t&&!t.active&&Z({type:`activate_provider_key`,provider:e.provider,keyName:t.name}),m!==e.id&&p?.id!==e.id&&Z({type:`set_model`,modelId:e.id}),g(!1)},onToggleDefault:(e,t)=>{Z(t?{type:`clear_default_model`}:{type:`set_default_model`,modelId:e.id})},isRowActive:(e,t)=>(m===e.id||p?.id===e.id||`${e.provider}/${e.id}`===m)&&(!t||t.active),listRef:y}),z=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:f(`thinkingLevel`)}),D&&(0,$.jsxs)(`div`,{className:`dd-item-notice`,style:{padding:`4px 10px`,fontSize:`11px`,opacity:.7},children:[`🧠 `,f(`thinkingFixedNotice`)]}),A.filter(e=>e.supported).map(t=>(0,$.jsx)(Ut,{active:e?.thinkingLevel===t.value&&!N,onClick:()=>{if(P(null),u){u(t.value),v(!1);return}e?.thinkingLevel!==t.value&&Z({type:`set_thinking`,level:t.value}),v(!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:f(`thinkingCustomBudgetTitle`)})}),(0,$.jsxs)(`div`,{className:`dd-custom-token-group`,children:[(0,$.jsx)(`input`,{type:`number`,className:`dd-custom-token-input`,placeholder:f(`thinkingCustomBudgetPlaceholder`),value:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Enter`&&F()}}),(0,$.jsx)(`button`,{type:`button`,className:`dd-custom-token-btn`,onClick:F,children:f(`thinkingCustomBudgetBtn`)})]})]})]}),B=(0,$.jsx)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(k,{}),(0,$.jsx)(`span`,{className:`chip-model`,children:p?p.name:f(`selectModel`)}),!s&&p?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:f(`vision`),children:`🖼`}),!s&&p&&(0,$.jsx)(`span`,{className:`chip-sub`,children:p.provider})]}),open:h,onOpenChange:g,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:b,menuStyle:x==null?void 0:{width:x},direction:d,children:R}),ee=(0,$.jsx)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Re,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:f(`thinkingChip`,{level:e?I(e.thinkingLevel):`—`})})]}),tip:f(`thinkingLevel`),open:_,onOpenChange:v,align:`left`,portal:!0,direction:d,children:z});if(c===`model`)return B;if(c===`thinking`)return ee;let V=e?.thinkingLevel&&e.thinkingLevel!==`off`;return(0,$.jsxs)(`div`,{className:`model-thinking-capsule`,children:[(0,$.jsx)(Wt,{className:`capsule-dropdown capsule-model-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(k,{}),(0,$.jsx)(`span`,{className:`capsule-model-name`,children:p?p.name:f(`selectModel`)}),!s&&p?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:f(`vision`),children:`🖼`})]}),triggerClassName:`capsule-segment capsule-model`,open:h,onOpenChange:g,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:b,menuStyle:x==null?void 0:{width:x},direction:d,children:R}),(0,$.jsx)(`div`,{className:`capsule-divider`}),(0,$.jsx)(Wt,{className:`capsule-dropdown capsule-thinking-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-pulse-dot ${V?`on`:``}`}),(0,$.jsx)(`span`,{className:`capsule-thinking-text`,children:e?I(e.thinkingLevel):`—`})]}),triggerClassName:`capsule-segment capsule-thinking`,open:_,onOpenChange:v,align:`left`,portal:!0,direction:d,children:z})]})});function Cw({onNotice:e}){let t=W(),{locale:n}=c(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),{panelRef:f,style:p}=dr({open:s,anchor:u,side:`top`,align:`left`,onClose:()=>l(!1)});(0,Q.useEffect)(()=>{let e=new AbortController;return fetch(g(`/api/system-screenshot`),{signal:e.signal}).then(async t=>{if(t.ok){let n=await t.json();e.signal.aborted||i(n.available===!0)}}).catch(()=>{}),()=>e.abort()},[]);let m=async i=>{if(!r||d.current)return;d.current=!0,l(!1),o(!0);let a=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``),s=document.title;i&&(document.title=`${s} [${a}]`);try{let e=await fetch(g(`/api/system-screenshot`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:a,locale:X(n)?`zh`:`en`,hideWindow:i})}),r=await e.json();if(!e.ok)throw r.error===`window-not-focused`?Error(t(`screenshotFocus`)):r.error===`busy`?Error(t(`screenshotBusy`)):r.error===`local-only`||r.error===`unsupported`?Error(t(`screenshotUnavailable`)):Error(t(`screenshotFailed`));if(r.cancelled)return;if(!r.dataUrl?.startsWith(`data:image/png;base64,`)||!pn({src:r.dataUrl,alt:`${t(`screenshotName`)}.png`}))throw Error(t(`screenshotFailed`))}catch(n){e(`error`,n instanceof Error?n.message:t(`screenshotFailed`))}finally{i&&document.title.endsWith(`[${a}]`)&&(document.title=s),d.current=!1,o(!1)}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:u,type:`button`,className:`btn attach-img`,title:t(r?a?`screenshotBusy`:`screenshotCapture`:`screenshotUnavailable`),"aria-label":t(`screenshotCapture`),"aria-busy":a,"aria-haspopup":`menu`,"aria-expanded":s,disabled:!r||a,onClick:()=>l(e=>!e),children:(0,$.jsx)(j,{})}),s&&(0,cr.createPortal)((0,$.jsxs)(`div`,{ref:f,className:`ctx-menu`,style:p,role:`menu`,"aria-label":t(`screenshotCapture`),children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-item`,onClick:()=>void m(!1),children:t(`screenshotKeepWindow`)}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-item`,onClick:()=>void m(!0),children:t(`screenshotHideWindow`)})]}),document.body)]})}var ww=[`standard`,`ptc`,`minimal`,`cordis`],Tw={standard:`preset.standard`,minimal:`preset.minimal`,code:`preset.code`,reader:`preset.reader`,ask:`preset.ask`},Ew={standard:`preset.standardDesc`,minimal:`preset.minimalDesc`,code:`preset.codeDesc`,reader:`preset.readerDesc`,ask:`preset.askDesc`};function Dw(e){return Tw[e]??null}function Ow(e){return Ew[e]??null}function kw(e,t,n){let r=X(t),i=Dw(e.id),a=Ow(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 Aw(e){return[...e].sort((e,t)=>{let n=Number.isSafeInteger(e.order)?e.order:ww.indexOf(e.id),r=Number.isSafeInteger(t.order)?t.order:ww.indexOf(t.id),i=n>=0?n:1e3,a=r>=0?r:1e3;return i===a?e.id.localeCompare(t.id):i-a})}var jw=(0,Q.memo)(function({preset:e,presets:t,defaultPreset:n,blank:r,conversationId:i,compact:a=!1}){let o=W(),{locale:s}=c(),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(e?.id??n);if((0,Q.useEffect)(()=>{p(e?.id??n)},[i,e?.id,n]),t.length===0)return null;let m=e?.locked||!r,h=Aw(t),g=h.find(t=>t.id===e?.id),_=h.find(e=>e.id===f)??g,v=e=>kw(e,s,o),y=g?v(g):void 0,b=t=>{p(t),d(!1),r&&t!==e?.id&&Z({type:`dsh_preset_select`,preset:t})};if(a){let t=y?.description??g?.id??o(`dshPreset`);return(0,$.jsx)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(yt,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:m?`${t}(${o(`dshPresetLocked`)})`:t,children:[y?.name??g?.id??e?.name??o(`dshPreset`),m&&(0,$.jsx)(l,{style:{marginLeft:3}})]})]}),open:u&&!m,onOpenChange:d,direction:`up`,align:`left`,children:h.map(t=>{let r=v(t);return(0,$.jsxs)(Ut,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>b(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)(yt,{}),o(`dshPreset`)]}),(0,$.jsx)(Wt,{trigger:(0,$.jsxs)(`span`,{title:y?.description??g?.id??``,children:[y?.name??g?.id??e?.name??`…`,m&&(0,$.jsxs)(`span`,{className:`dsh-preset-lock`,title:o(`dshPresetBlankOnly`),children:[(0,$.jsx)(l,{}),` `,o(`dshPresetLocked`)]})]}),open:u&&!m,onOpenChange:d,children:h.map(t=>{let r=v(t);return(0,$.jsxs)(Ut,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>b(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)})}),!m&&(0,$.jsx)(`span`,{className:`dsh-preset-hint`,title:o(`dshPresetBlankOnly`),children:o(`dshPresetBlankOnly`)}),_?.id===`minimal`&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:o(`dshPresetMinimalNote`)}),(0,$.jsxs)(`button`,{type:`button`,className:`chip`,title:o(`dshPresetNewChat`),onClick:()=>{Z({type:`new_chat`,preset:_?.id??f}),sn()},children:[(0,$.jsx)(C,{}),` `,o(`dshPresetNewChat`)]})]})}),Mw=[`read-only`,`workspace-write-never`,`danger-full-access`],Nw=[`read-only`,`workspace-write-never`,`danger-full-access`];function Pw(e){return e===`read-only`?`dshPermReadOnly`:e===`danger-full-access`?`dshPermFullAccess`:`dshPermWorkspaceWrite`}function Fw(e){return e===`read-only`?`dshPermReadOnlyDesc`:e===`danger-full-access`?`dshPermFullAccessDesc`:`dshPermWorkspaceWriteDesc`}var Iw=(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=Mw.filter(e=>t.some(t=>t.value===e));if(u.length===0)return null;let d=e??n,f=!!e&&!u.includes(e),p=e=>{if(e===`danger-full-access`&&e!==d&&!c){l(!0);return}l(!1),s(!1),e!==d&&Z({type:`dsh_permission_set`,preset:e})};if(i){let t=a(f?`dshPermCustom`:Pw(d)),r=f?e??t:a(Fw(d));return(0,$.jsxs)(Wt,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(H,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r,children:[t,d===`danger-full-access`&&(0,$.jsx)(ct,{style:{marginLeft:3}})]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},direction:`up`,align:`left`,children:[u.map(e=>(0,$.jsxs)(Ut,{active:e===d,title:a(Fw(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(Pw(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(Fw(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)(H,{}),a(`dshPerm`)]}),(0,$.jsx)(Wt,{trigger:(0,$.jsxs)(`span`,{title:f?e:a(Fw(d)),children:[a(f?`dshPermCustom`:Pw(d)),d===`danger-full-access`&&(0,$.jsxs)(`span`,{className:`dd-preset-tag warn`,children:[(0,$.jsx)(ct,{}),` `,a(`dshPermFullAccessTag`)]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},children:u.map(e=>(0,$.jsxs)(Ut,{active:e===d,title:a(Fw(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(Pw(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(Fw(e))})]},e))}),c&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:a(`dshPermConfirmFull`)})]})}),Lw=JC(),Rw=40,zw=320,Bw=`pi-web-ui:composer-height`;function Vw(){return typeof window>`u`?zw:Math.max(160,Math.min(zw,Math.floor(window.innerHeight*.42)))}var Hw=(0,Q.memo)(function({groupDevices:e,groupReady:t,groupPrimaryBotName:n,groupConversationError:r,groupConversations:a=[],onGroupSend:o,onAbort:s,streaming:l,planMode:u,messages:d,slashCommands:f,modelState:m,models:h,modelsLoading:g,attachments:_,onRemoveAttachment:v,onAnnotateImage:y,onAddImageFiles:b,onAddLocalFiles:x,onAddPathAttachment:S,fileSearch:C,onSearchFiles:w,onNotice:T,onSent:E,onManageModels:D,providerKeys:O,providers:k,defaultModel:A,quickPhrases:j,quickPhrasesEnabled:M,recallDrafts:N,composerLeading:P,composerActions:F,onUiAction:I,dshPermCurrent:L,dshPermOptions:z,dshPermDefault:B,dshPreset:ee,dshPresets:V,dshPresetDefault:te,dshBlank:ne,conversationId:re,sessionDraft:ie,sessionId:H,preserveDraftAcrossConversations:ae=!1}){let U=W(),oe=He(`ready`),se=e?!!t:oe,le=De(),G=at(),K=!!(u&&G.planMode),{locale:ue}=c(),de=aw(Lw),fe=de===`mod-enter`,pe=uw(He(`cwd`)||``)||`pi`,{openPicker:q,templates:me}=qx(),he=zx(me,f),ge=[...f,...he.map(e=>({name:Lx(e.command??``),description:e.desc||e.title,source:`prompt`}))],_e=e=>!X(ue)&&e.descriptionEn?e.descriptionEn:e.description??``,ve=e=>!X(ue)&&e.argumentHintEn?e.argumentHintEn:e.argumentHint??``,[J,ye]=(0,Q.useState)(``),[be,xe]=(0,Q.useState)(()=>{try{let e=Number(localStorage.getItem(Bw));if(Number.isFinite(e)&&e>44)return Math.min(e,zw)}catch{}return null}),Se=(0,Q.useRef)(null),[Ce,Y]=(0,Q.useState)(null),[we,Te]=(0,Q.useState)(0),Ee=(0,Q.useRef)(0),Oe=(0,Q.useRef)(new Map),ke=(0,Q.useRef)(``),[Ae,je]=(0,Q.useState)(!1),[Me,Ne]=(0,Q.useState)(void 0),Pe=(0,Q.useRef)(null),Fe=(0,Q.useRef)(null),Ie=(0,Q.useRef)(null),Le=(0,Q.useRef)(-1),Re=(0,Q.useRef)(``),[ze,Be]=(0,Q.useState)(!1),Ve=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!N||N.length===0)return;let e=N.filter(e=>e.text&&e.seq>Ve.current);e.length!==0&&(Ve.current=e[e.length-1].seq,Y(null),ye(t=>{let n=e.reduce((e,t)=>rC(e,t.text),t);return ke.current=n,n}),Le.current=-1,Re.current=``,requestAnimationFrame(()=>{let e=Pe.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}))},[N]),(0,Q.useEffect)(()=>{if(!e)return fn(e=>{Y(null),ye(t=>{let n=rC(t,e);return ke.current=n,n}),Le.current=-1,Re.current=``,requestAnimationFrame(()=>{let e=Pe.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})}),()=>fn(null)},[]),(0,Q.useEffect)(()=>(tn(()=>{Lw||requestAnimationFrame(()=>{Pe.current?.focus()})}),()=>tn(null)),[]);let Ue=(0,Q.useRef)(``);Ue.current=J,(0,Q.useEffect)(()=>{if(!e)return nn(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(Ue.current))return}let t=Pe.current;if(!t){ye(t=>{let n=t+(t&&!t.endsWith(` `)?` `:``)+e;return ke.current=n,n});return}let n=t.selectionStart??Ue.current.length,r=t.selectionEnd??Ue.current.length,i=Ue.current,a=(n>0&&!/[\s([{]$/.test(i.slice(0,n))?` `:``)+e,o=i.slice(0,n)+a+i.slice(r);ke.current=o,ye(o);let s=n+a.length;requestAnimationFrame(()=>{t.focus(),t.selectionStart=t.selectionEnd=s})}),()=>nn(null)},[]),(0,Q.useEffect)(()=>{if(!e)return cn(e=>{ye(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(),ke.current=a,a})}),()=>cn(null)},[]);let We=2e4,Ge=H?`${re??``}${H}`:null,Ke=Ge&&H?`pi-web-ui:composer-draft:${H}`:null,Je=(0,Q.useRef)(``),Ye=(0,Q.useRef)(0),Xe=(0,Q.useRef)(!1),Ze=(0,Q.useRef)(0),Qe=(0,Q.useRef)(null),$e=(0,Q.useRef)(null),et=(0,Q.useRef)(null),tt=(0,Q.useRef)(ae);tt.current=ae;let nt=yw(),it=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,We),ts:n.ts}}catch{return null}},ot=(t,n,r,i)=>{let a=r.slice(0,We);try{a.trim()?localStorage.setItem(n,JSON.stringify({text:a,ts:i})):localStorage.removeItem(n)}catch{}e||Z({type:`draft_update`,sessionId:t,text:a,ts:i})},st=()=>{Qe.current&&=(clearTimeout(Qe.current),null),Xe.current&&Ge&&Ke&&H&&Dt&&ot(H,Ke,Je.current,Ye.current)},ct=(0,Q.useRef)(new Set),lt=(0,Q.useRef)([]),ut=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(lt.current=[],ut.current=Ue.current,e&&H?.startsWith(`device-group:`))return Ic(H.slice(13),e=>{if(lt.current.find(t=>t.member.id===e.id)){Pe.current?.focus();return}let t=Pe.current,n=Lc(Ue.current,t?.selectionStart??Ue.current.length,e);lt.current=Ac(Ue.current,n.text,lt.current),lt.current.push({start:n.cursor-e.name.length-2,end:n.cursor-1,member:e}),ut.current=n.text,Je.current=n.text,Ue.current=n.text,ke.current=n.text,ye(n.text),requestAnimationFrame(()=>{Pe.current?.focus(),Pe.current?.setSelectionRange(n.cursor,n.cursor)})})},[H,!!e]);let dt=t=>{if(e){lt.current=Ac(ut.current,t,lt.current),ut.current=t;let n=new Set(Ec(t,e));for(let e of ct.current)n.has(e)||ct.current.delete(e)}if(Je.current=t,Xe.current=!0,Ye.current=Date.now(),Ke){let e=t.slice(0,We);try{e.trim()?localStorage.setItem(Ke,JSON.stringify({text:e,ts:Ye.current})):localStorage.removeItem(Ke)}catch{}}if(Ge&&H&&Dt){Qe.current&&clearTimeout(Qe.current);let e=H,t=Ke,n=Ye.current,r=Ge;Qe.current=setTimeout(()=>{Qe.current=null,r===$e.current&&t&&ot(e,t,Je.current,n)},2e3)}},ft=(e,t)=>{Le.current=-1,ye(e),ht(e,t),dt(e)};(0,Q.useEffect)(()=>{let e=Ge,t=H,n=Ke;return()=>{Qe.current&&=(clearTimeout(Qe.current),null);let r=Je.current;if(Xe.current&&r.trim()){e&&t&&n&&ot(t,n,r,Ye.current);let i=an(),a=i>0&&Ye.current>i;et.current={text:r,userEditedAfterSwitch:a}}else et.current=null}},[Ge]),(0,Q.useEffect)(()=>{$e.current=Ge;let e=et.current;et.current=null;let t=e?.text??null,n=e?.userEditedAfterSwitch??!1,r=Ke?it(Ke):null,i=!!(ie&&ie.text?.trim()&&ie.ts>0||r&&r.text?.trim());cC(t,n,d.length,i,tt.current)&&t!==null&&Ke&&H?(Xe.current=!0,Ze.current=Date.now(),Je.current=t,Ye.current=Ze.current,ye(t),i||ot(H,Ke,t,Ye.current)):(Xe.current=!1,Ze.current=0,Je.current=``,Ye.current=0,ye(``)),Y(null),Le.current=-1},[Ge]);let pt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=d.length===0,t=pt.current!==null&&pt.current!==Ge,n=pt.current===null&&e;pt.current=Ge,se&&!Lw&&(t||n)&&requestAnimationFrame(()=>{Pe.current?.focus()})},[Ge,d.length,se]),(0,Q.useEffect)(()=>{if(!Ge||!Ke||Xe.current||Je.current!==``)return;let e=iC(ie&&ie.text?{text:ie.text.slice(0,We),ts:ie.ts}:null,it(Ke),Ze.current);e&&(Ze.current=e.ts,Je.current=e.text,Ye.current=e.ts,ye(e.text),ht(e.text,null))});let mt={builtin:U(`slashBuiltin`),extension:U(`slashExtension`),prompt:U(`slashPrompt`),skill:U(`slashSkill`),plugin:U(`slashPlugin`)},ht=(t,n)=>{ke.current=t;let r=t.match(/^\/([^\s]*)$/);if(r&&se&&!e){let e=r[1].toLowerCase(),t=RC(ge,e);Y(t.length>0?{kind:`slash`,items:t}:null),Te(0);return}if(n===null||!se){Y(null);return}let i=KC(t,n);if(!i){Y(null);return}if(e){let t=xc(e,a,i.query,X(ue));Y(t.length?{kind:`at`,start:i.start,end:n,items:t}:null),Te(0);return}let o=[];try{o=Tn()}catch{o=[]}let s=++Ee.current,c=t,l=i.start,u=i.query,d=l+1+u.length,p=o.map(e=>({id:e.id,label:e.label,run:()=>{let t;try{t=On(e.id)?.search}catch{t=void 0}return typeof t==`function`?t(u):Promise.resolve([])}}));p.push({id:`host:canvases`,label:U(`canvasTab`),run:async()=>tu(await nu(()=>Z({type:`canvas_list`})),u,U(`canvasTab`))}),u&&typeof w==`function`&&p.push({id:`host:files`,label:U(`openFiles`),run:()=>gt(u)});let m=[];if(G.pageRef&&(Lr(),m=BC(U(`browserControl`),Ir(),u),p.push({id:`host:pages`,label:U(`browserControl`),run:()=>Promise.resolve(m)})),p.length===0){Y(null);return}let h=UC(U(`slashSkill`),f,u,15,_e),g=WC({pages:m,skills:h},u,30),_=!1;g.length>0&&(_=!0,Y({kind:`at`,start:l,end:d,items:g}),Te(0)),Promise.allSettled(p.map(e=>Promise.race([e.run(),new Promise((e,t)=>setTimeout(()=>t(Error(`at-mention timeout`)),2e3))]))).then(e=>{if(Ee.current!==s||ke.current!==c)return;let t=[],n=[],r=[],i=[];e.forEach((e,a)=>{e.status===`fulfilled`&&(p[a].id===`host:pages`&&Array.isArray(e.value)?n.push(...e.value):p[a].id===`host:canvases`&&Array.isArray(e.value)?t.push(...e.value):p[a].id===`host:files`?r.push(...VC(p[a].label,e.value)):i.push(...HC(p[a].id,p[a].label,e.value)))});let a=WC({canvases:t,pages:n,skills:h,files:r,plugins:i},u,30);Y(a.length>0?{kind:`at`,start:l,end:d,items:a}:null),!_&&a.length>0&&Te(0)})},gt=e=>{if(typeof w!=`function`)return Promise.resolve([]);let t=xw();return new Promise(n=>{Oe.current.set(t,n);try{w(t,e)}catch{Oe.current.delete(t),n([]);return}setTimeout(()=>{Oe.current.get(t)===n&&(Oe.current.delete(t),n([]))},3e3)})};(0,Q.useEffect)(()=>{if(!C||!C.ok)return;let e=Oe.current.get(C.reqId);e&&(Oe.current.delete(C.reqId),e(C.results??[]))},[C]);let _t=e=>ht(e,null);(0,Q.useEffect)(()=>{(Ie.current?.querySelector(`.slash-item.active`))?.scrollIntoView({block:`nearest`})},[we,Ce]);let vt=e=>{let t=Ce?.kind===`slash`?Ce.items:[],n=e??t[we%Math.max(t.length,1)];if(!n){Y(null);return}let r=J.match(/^\/([^\s]*)([\s\S]*)$/),i=r?r[2]:``,a=`/${n.name} ${i}`;ke.current=a,ye(a),dt(a),Y(null),Pe.current?.focus()},yt=(t,n)=>{let r=Ce?.kind===`at`?Ce:null,i=r?.items??[],o=t??i[we%Math.max(i.length,1)],s=n??r?.start;if(!o||s===void 0){Y(null);return}let c=Pe.current,l=c?c.selectionStart??J.length:J.length,u=r?.end!==void 0&&r.end>=s?r.end:l,d=o.attachments??[],f=o.providerId===`host:group-conversations`?a.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&&ct.current.add(o.hint);let h=d.length>0&&!m.startsWith(`@`)?`@${m} `:`${m} `,g=`${J.slice(0,s)}${h}${J.slice(u)}`;ke.current=g,ye(g),dt(g),p&<.current.push({start:s,end:s+m.length,member:p,conversationId:f?.id}),Y(null);for(let e of d)try{S?.({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=Pe.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=s+h.length)})},bt=()=>Ce?.kind===`slash`?Ce.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===we?` active`:``}`,onMouseEnter:()=>Te(t),onClick:()=>St(e),children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:mt[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,xt=()=>Ce?.kind===`at`?Ce.items.map((t,n)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${n===we?` active`:``}`,onMouseEnter:()=>Te(n),onClick:()=>St(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,St=e=>{Ce&&(Ce.kind===`slash`?vt(e):yt(e,Ce.start))},Ct=async()=>{let e=[...d].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(`
|
|
79
|
+
`);if(!e){T(`warning`,U(`slashCopyEmpty`));return}await Gd(e)?T(`info`,U(`slashCopied`)):T(`error`,U(`slashCopyFailed`))},wt=t=>{if(e)return;if(!t||t.length===0){T(`warning`,U(`foldersNotSupported`));return}let n=Array.from(t).filter(e=>Bh(e.type)),r=Array.from(t).filter(e=>!Bh(e.type)),i=Et();n.length>0&&i?T(`warning`,i):n.length>0&&b(n),r.length>0&&x(r)},Tt=e=>{let t=bC(e.clipboardData?.items,e.clipboardData?.files);t.length!==0&&(e.preventDefault(),wt(t))},Et=()=>{let e=m?.model;if(!e?.id)return null;let t=h.find(t=>t.id===e.id);return t&&t.vision===!1?U(`modelNoVision`,{name:t.name}):null},Dt=se,kt=se&&!!H,At=(0,Q.useRef)(J);(0,Q.useEffect)(()=>{At.current=J},[J]),(0,Q.useEffect)(()=>{!e&&/^\/[^\s]*$/.test(At.current)&&_t(At.current)},[f]);let[jt,Mt]=(0,Q.useState)(null),Nt=e=>{let t=jt;if(Mt(null),t===null)return;let n=uC(At.current,t,e);n!==null&&(Y(null),ke.current=n,ye(n)),requestAnimationFrame(()=>Pe.current?.focus())};(0,Q.useEffect)(()=>{if(e)return;let t=e=>{let t=e.detail;if(typeof t==`string`){if(lC(At.current,t)){Mt(t);return}Y(null),ke.current=t,ye(t),Pe.current?.focus()}};return window.addEventListener(`pi-web:fill`,t),()=>window.removeEventListener(`pi-web:fill`,t)},[]),(0,Q.useEffect)(()=>{if(!Ae&&jt===null)return;let e=e=>{e.key===`Escape`&&(jt===null?je(!1):(Mt(null),requestAnimationFrame(()=>Pe.current?.focus())))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ae,jt]);let Pt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Pe.current,t=Pt.current;if(!e||!t)return;let n=e.closest(`main`)?.querySelector(`.messages`),r=t.getBoundingClientRect().height,i=n?.scrollTop??0,a=Vw();e.style.maxHeight=`${a}px`;let o=be!=null&&be>44,s;e.style.height=`auto`;let c=e.scrollHeight;s=Math.min(o?be:Math.max(c,Rw),a),e.style.height=`${s}px`,e.style.overflowY=c>s?`auto`:`hidden`,n&&(n.scrollTop=i+(t.getBoundingClientRect().height-r))},[J,be]);let Ft=(0,Q.useRef)(null),Lt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=Ft.current,t=Lt.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`)}},[_.length,M,j.length]);let Rt=()=>_.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}:{}}:{}}),zt=()=>{if(Ke)try{localStorage.removeItem(Ke)}catch{}Qe.current&&=(clearTimeout(Qe.current),null),Xe.current=!1,Ze.current=Date.now(),Je.current=``,Ye.current=0},Bt=(0,Q.useRef)(!1),Vt=(t=!1)=>{let n=J.trim(),r=_.length>0;if(n||r){if(!Dt){T(`error`,U(`netDisconnected`));return}if(!kt){T(`warning`,U(`sessionInitializingNotice`));return}if(e){if(!o||Bt.current)return;let t;try{t=kc(lt.current)}catch(e){T(`error`,e.message);return}Bt.current=!0;let r=jc(J,lt.current);o(r.text.trim(),[...new Set([...r.targets,...Ec(n,e).filter(e=>ct.current.has(e))])],t,{planOnly:ze}).then(e=>{e&&Je.current.trim()===n&&(ye(``),ct.current.clear(),lt.current=[],ut.current=``,zt(),E())}).catch(e=>T(`error`,String(e))).finally(()=>{Bt.current=!1});return}if(!G.conversationRef&&_.some(e=>e.mode===`conversation`)){T(`warning`,X(ue)?`当前底层智能体不支持跨对话引用(缺少 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=Pe.current?.closest(`.inputbox`)?.getBoundingClientRect();Ne(e?.width),je(!0),ye(``),zt(),Pe.current?.focus();return}if(n===`/copy`){ye(``),zt(),Pe.current?.focus(),Ct();return}if(Z({type:`prompt`,text:Bx(n,he),queue:t,attachments:Rt()})){n&&jC(n),Le.current=-1,Re.current=``,ye(``),zt(),E();let e=m?.model;e&&qc(`${e.provider}/${e.id}`),Pe.current?.focus()}else T(`error`,U(`netDisconnected`))}},Ht=(t,n=!1)=>{if(e)return;let r=t.trim();if(r){if(!Dt){T(`error`,U(`netDisconnected`));return}if(!kt){T(`warning`,U(`sessionInitializingNotice`));return}if(Z({type:`prompt`,text:r,queue:n,attachments:Rt()})){r&&jC(r),Le.current=-1,Re.current=``,st(),E();let e=m?.model;e&&qc(`${e.provider}/${e.id}`),Lw||Pe.current?.focus()}else T(`error`,U(`netDisconnected`))}},Ut=t=>{if(!nt.isImeKey(t.nativeEvent)){if(Ce&&Ce.items.length>0){let e=Ce.items.length;switch(t.key){case`ArrowDown`:t.preventDefault(),Te(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),Te(t=>(t-1+e)%e);return;case`Tab`:case`Enter`:t.preventDefault(),St();return;case`Escape`:t.preventDefault(),Y(null);return}}if(e&&(t.key===`Backspace`||t.key===`Delete`)&&!t.nativeEvent.isComposing){let e=Pe.current;if(e){let n=Mc(J,e.selectionStart,e.selectionEnd,t.key,lt.current);if(n){t.preventDefault();let r=J.slice(0,n.start)+J.slice(n.end);dt(r),ye(r),Ue.current=r,requestAnimationFrame(()=>e.setSelectionRange(n.start,n.start));return}}}if(t.key===`Backspace`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=Pe.current;if(e&&e.selectionStart===e.selectionEnd&&e.selectionStart>0){let n=e.selectionStart,r=ow(J.slice(0,n),n,_);if(r&&r.tokenStart>=0&&r.tokenStart<n){t.preventDefault();let e=r.tokenStart,i=J.slice(0,e)+J.slice(n);ke.current=i,ye(i),requestAnimationFrame(()=>{Pe.current&&(Pe.current.selectionStart=Pe.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=Pe.current;if(!e)return;let n=t.key===`ArrowUp`,r=yC(e);if(n&&!r.first||!n&&!r.last||!n&&Le.current===-1)return;let i=kC();if(i.length===0)return;if(t.preventDefault(),n){if(Le.current===-1){Re.current=J;let e=i.length-1;Le.current=e;let t=i[e];ye(t),_t(t),requestAnimationFrame(()=>{let e=Pe.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else if(Le.current>0){let e=Le.current-1;Le.current=e;let t=i[e];ye(t),_t(t),requestAnimationFrame(()=>{let e=Pe.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}}else{let e=Le.current+1;if(e<i.length){Le.current=e;let t=i[e];ye(t),_t(t),requestAnimationFrame(()=>{let e=Pe.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else{Le.current=-1;let e=Re.current;ye(e),_t(e),requestAnimationFrame(()=>{let t=Pe.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}}return}if(t.key===`Escape`&&Le.current!==-1){t.preventDefault();let e=Re.current;Le.current=-1,ye(e),_t(e),requestAnimationFrame(()=>{let t=Pe.current;t&&(t.selectionStart=t.selectionEnd=e.length)});return}if(ZC({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,isTouch:Lw,pref:de})===`send`){t.preventDefault(),Vt();return}}},Wt=kt&&(J.trim()!==``||_.length>0),Gt=(0,Q.useMemo)(()=>ka((F??[]).filter(e=>e.source!==`host`&&!e.hidden)),[F]),Kt=(0,Q.useMemo)(()=>(P??[]).filter(e=>e.source!==`host`&&!e.hidden),[P]),qt=F!==void 0,Jt=(0,Q.useMemo)(()=>ka((F??[]).filter(e=>!e.hidden)),[F]),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=>I?.(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)(i,{}):e.icon===`camera`?(0,$.jsx)(qe,{}):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:()=>I?.(e),children:t},e.id)},Xt=G.steer!==!1&&!le,Zt=()=>(0,$.jsx)(`div`,{className:`inputbox-actions`,children:l?Wt?(0,$.jsxs)(`div`,{className:`split-send${Xt?``:` single`}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`split-queue`,title:U(`supplementTip`),"aria-label":U(`queueFollowTag`),onClick:()=>Vt(!0),children:(0,$.jsx)(ce,{})}),Xt&&(0,$.jsx)(`button`,{type:`button`,className:`split-steer`,title:U(fe?`steerTipMod`:`steerTip`),"aria-label":U(`queueSteerTag`),onClick:()=>Vt(),children:(0,$.jsx)(Ot,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`btn stop`,title:U(`stopAgent`),onClick:()=>s?s():Z({type:`abort`}),children:(0,$.jsx)(rt,{})}):(0,$.jsx)(`button`,{type:`button`,className:`btn send`,title:U(Dt?kt?fe?`sendTipMod`:`sendTip`:`sessionInitializingNotice`:`netDisconnected`),disabled:!Wt,onClick:()=>Vt(),children:(0,$.jsx)(Ot,{})})}),Qt={"host:composer-upload":(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:U(`uploadFile`),disabled:!Dt,onClick:()=>Fe.current?.click(),children:(0,$.jsx)(It,{})}),"host:composer-screenshot":(0,$.jsx)(Cw,{onNotice:T}),"host:composer-templates":(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:U(`tpl.openPicker`),onClick:q,children:(0,$.jsx)(p,{})}),"host:composer-model":(0,$.jsx)(Sw,{only:`model`,state:m,models:h,modelsLoading:g,onManageModels:D,providerKeys:O,providers:k,defaultModel:A,compact:!0}),"host:composer-thinking":(0,$.jsx)(Sw,{only:`thinking`,state:m,models:h,modelsLoading:g,onManageModels:D,providerKeys:O,compact:!0}),"host:composer-dsh-perm":z&&z.length>0&&B!==void 0?(0,$.jsx)(Iw,{compact:!0,current:L??null,options:z,defaultPreset:B,conversationId:re??``}):null,"host:composer-dsh-preset":V&&V.length>0&&te!==void 0?(0,$.jsx)(jw,{compact:!0,preset:ee??null,presets:V,defaultPreset:te,blank:ne??!1,conversationId:re??``}):null,"host:composer-send":Zt()},$t=e=>e.source===`host`?(0,$.jsx)(Q.Fragment,{children:Qt[e.id]??null},e.id):Yt(e);return(0,$.jsxs)(`div`,{ref:Pt,className:`inputbar`,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault(),e.stopPropagation(),wt(e.dataTransfer?.files??null)},children:[_.length>0&&(0,$.jsxs)(`div`,{className:`attach-row`,ref:Ft,children:[_.map(e=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(ld,{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}`:t&&e.path?Yf(e.path):void 0,a=()=>{i?pn({src:i,alt:e.name,onSaveAnnotation:y?t=>y(e,t):void 0}):n&&e.path&&Hf({path:e.path,name:e.name})},o=e.imageData?U(`attachImage`,{name:e.name}):e.fileData?U(`attachFile`,{name:e.name}):e.isDir?U(`folderRef`,{path:e.path}):e.mode===`page`?U(`attachPage`,{name:e.name}):e.mode===`canvas`?`${U(`canvasTab`)} · ${e.name}`:e.mode===`conversation`?U(`attachConversation`,{name:e.name}):e.mode===`reference`?U(`refOnly`,{path:e.path}):e.mode===`lines`&&e.lines?U(`attachLines`,{path:e.path,start:e.lines.start,end:e.lines.end}):U(`attachContent`,{path:e.path});return(0,$.jsxs)(`span`,{className:`attach-chip ${e.imageData?`image`:e.fileData?`file`:e.mode}${r?` previewable`:``}`,title:o+(r?` (${U(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`,{crossOrigin:R(i),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:U(`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:U(`attachHint`)})]}),Ce&&Ce.items.length>0&&(0,$.jsxs)(`div`,{className:`slash-menu`,role:`listbox`,ref:Ie,"aria-label":Ce.kind===`slash`?U(`slashCommands`):U(`atMentions`),"data-menu-kind":Ce.kind,children:[(0,$.jsxs)(`div`,{className:`slash-menu-hint`,children:[(0,$.jsx)(`span`,{children:Ce.kind===`slash`?U(`slashMenuHint`):U(`atMenuHint`)}),(0,$.jsx)(`span`,{className:`slash-menu-close`,onClick:()=>Y(null),children:`Esc`})]}),Ce.kind===`slash`?bt():xt(),e&&Ce.kind===`at`&&r&&(0,$.jsx)(`div`,{className:`slash-desc`,role:`status`,children:r})]}),jt!==null&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>Nt(`cancel`),children:(0,$.jsxs)(`div`,{className:`slash-help`,role:`dialog`,"aria-modal":`true`,"aria-label":U(`tpl.confirmFillTitle`),style:{maxWidth:420},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`div`,{className:`slash-help-head`,children:(0,$.jsx)(`span`,{children:U(`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:U(`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:()=>Nt(`cancel`),children:U(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Nt(`append`),children:U(`tpl.confirmFillAppend`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>Nt(`overwrite`),children:U(`tpl.confirmFillOverwrite`)})]})]})]})}),Ae&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>je(!1),children:(0,$.jsxs)(`div`,{className:`slash-help`,style:Me?{width:Me}:void 0,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`slash-help-head`,children:[(0,$.jsxs)(`span`,{children:[`⚡ `,U(`slashHelpTitle`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>je(!1),children:U(`close`)})]}),(0,$.jsx)(`div`,{className:`slash-help-body`,children:ge.length===0?(0,$.jsx)(`div`,{className:`slash-help-empty`,children:U(`slashLoading`)}):ge.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:mt[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))})]})}),M&&j.length>0&&(0,$.jsx)(`div`,{className:`quick-row`,"aria-label":U(`quickPhrases`),ref:Lt,children:j.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`quick-chip`,title:`${U(`quickPhrasesTip`,{text:e})}(${U(`quickPhrasesSendTip`)})`,disabled:!Dt,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${be!=null&&be>44?` is-manual`:``}`,"aria-label":U(be!=null&&be>44?`composerResizeFixed`:`composerResize`),role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":Math.round(be??Rw),"aria-valuemin":Rw,"aria-valuemax":zw,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId);let t=Pe.current?.getBoundingClientRect().height;Se.current={startY:e.clientY,startH:typeof t==`number`&&Number.isFinite(t)?t:be??Rw,next:null}},onPointerMove:e=>{let t=Se.current;if(!t)return;let n=Vw(),r=Math.min(n,Math.max(Rw,t.startH+(t.startY-e.clientY)));t.next=r,xe(r<=44?null:r)},onPointerUp:()=>{let e=Se.current?.next;if(Se.current=null,e!=null)try{if(e<=44)xe(null),localStorage.removeItem(Bw);else{let t=Math.round(e);xe(t),localStorage.setItem(Bw,String(t))}}catch{}},onPointerCancel:()=>{Se.current=null},onDoubleClick:()=>{xe(null);try{localStorage.removeItem(Bw)}catch{}},children:(0,$.jsx)(`span`,{className:`composer-resize-tip`,children:U(be!=null&&be>44?`composerResizeFixed`:`composerResize`)})}),(0,$.jsx)(`input`,{ref:Fe,type:`file`,multiple:!0,hidden:!0,onChange:e=>{wt(e.target.files),e.target.value=``}}),(0,$.jsx)(`textarea`,{ref:Pe,value:J,rows:1,placeholder:e?n?X(ue)?`直接发送给 ${n},或 @ 其他 Bot`:`Message ${n}, or @ another Bot`:X(ue)?`输入 @,选择 Bot 开始新对话或继续之前的对话`:`Type @ to start or continue a Bot conversation`:Dt?l?U(le?`placeholderStreamingQueued`:`placeholderStreaming`):K?U(`placeholderPlanMode`):U(fe?`placeholderIdleMod`:`placeholderIdle`,{name:pe}):U(`placeholderConnecting`),disabled:!Dt,onChange:e=>{ft(e.target.value,e.target.selectionStart??e.target.value.length)},onSelect:e=>{if(Ce?.kind===`at`){let t=e.target.selectionStart;(t<Ce.start||t>Ce.end)&&Y(null)}},onCompositionEnd:nt.onCompositionEnd,onBlur:st,onKeyDown:Ut,onPaste:Tt}),K&&(0,$.jsxs)(`button`,{type:`button`,style:{display:`inline-flex`,alignItems:`center`,gap:4,fontSize:11,color:`var(--accent, #38bdf8)`,background:`var(--accent-soft, rgba(56, 189, 248, 0.1))`,padding:`2px 8px`,borderRadius:12,position:`absolute`,right:12,top:8,cursor:`pointer`,border:`1px solid var(--border, rgba(255, 255, 255, 0.1))`,zIndex:2},onClick:()=>Z({type:`set_plan_mode`,enabled:!1}),title:U(`planModeTip`),children:[`📋 `,U(`planModeBadge`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),e&&ze&&(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:()=>Be(!1),title:X(ue)?`群计划模式(只规划,不实施写操作)`:`Group plan mode (planning only)`,children:[`📋 `,X(ue)?`群计划模式`:`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:X(ue)?`选择或 @ 群成员 Bot`:`Mention a Bot (@)`,onClick:()=>{let e=Pe.current,t=e?e.selectionStart:J.length,n=J.slice(0,t)+`@`+J.slice(t);ft(n,t+1),e?.focus()},children:`@`}),(0,$.jsxs)(`button`,{type:`button`,className:`btn group-plan-toggle ${ze?`active`:``}`,title:X(ue)?`群任务计划模式(只规划不实施)`:`Group task plan mode (plan only)`,onClick:()=>Be(e=>!e),children:[(0,$.jsx)(`span`,{className:`group-plan-icon`,children:`📋`}),(0,$.jsx)(`span`,{className:`group-plan-label`,children:X(ue)?`只规划`:`Plan Only`})]})]}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Zt()})]}):qt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Kt.map(Yt),Jt.start.map($t)]}),Jt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:Jt.center.map($t)}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Jt.end.map($t)})]}):(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:U(`uploadFile`),disabled:!Dt,onClick:()=>Fe.current?.click(),children:(0,$.jsx)(It,{})}),Gt.start.map(Yt),(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:U(`tpl.openPicker`),onClick:q,children:(0,$.jsx)(p,{})}),(0,$.jsx)(Sw,{state:m,models:h,modelsLoading:g,onManageModels:D,providerKeys:O,providers:k,defaultModel:A,compact:!0}),z&&z.length>0&&B!==void 0&&(0,$.jsx)(Iw,{compact:!0,current:L??null,options:z,defaultPreset:B,conversationId:re??``}),V&&V.length>0&&te!==void 0&&(0,$.jsx)(jw,{compact:!0,preset:ee??null,presets:V,defaultPreset:te,blank:ne??!1,conversationId:re??``})]}),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),Zt()]})]})})]})]})}),Uw=(0,Q.memo)(function({goal:e,models:t,modelsLoading:n,activeConversationId:r,uiGoalbarActions:i,onUiAction:a}){let o=W(),{locale:u}=c(),d=!X(u)&&e.statusEn?e.statusEn:e.status||``,f=!X(u)&&e.wizard?.statusEn?e.wizard.statusEn:e.wizard?.status||``,p=De(),m=at(),h=!e.conversationId||e.conversationId===r,g=e.goal!==null&&h,_=h?e.roles?.executor:void 0,v=_?.convId,y=_?.activity?!X(u)&&_.activityEn?_.activityEn:_.activity:_?.streaming?`…`:void 0,b=e.locked&&e.maxRounds>0?e.maxRounds:0,x=b>0?X(u)?o(`goalBarRound`,{n:`${e.round}/${b}`}):`Round ${e.round}/${b}`:`${o(`goalBarRound`,{n:e.round})}${e.locked?` · ${o(`goalBarUnlimitedShort`)}`:``}`,S=(e.usage?.inputTokens??0)+(e.usage?.outputTokens??0),C=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),[R,z]=(0,Q.useState)(!1),[B,ee]=(0,Q.useState)(!1),[V,te]=(0,Q.useState)(!1),[ne,re]=(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&&!V&&!n&&(te(!0),Z({type:`list_models`}))},[I,t.length,V,n]),(0,Q.useEffect)(()=>{t.length>0&&te(!1)},[t.length]);let ie=()=>O?t.find(e=>e.id===O)?.name??O:o(`goalBarUseMainModel`),H=()=>P?t.find(e=>e.id===P)?.name??P:o(`goalBarUseMainModel`),ae=()=>{let e=E.trim();e&&(Z({type:`set_goal`,goal:e,...O?{reviewModel:O}:{},maxRounds:A,locked:M,...P?{execModel:P}:{}}),D(``),re(!1))},U=()=>{let e=E.trim();Z({type:`set_plan_mode`,enabled:!0}),e&&(Z({type:`prompt`,text:e}),D(``))},oe=()=>{let e=E.trim();e&&(Z({type:`start_goal_wizard`,text:e,...O?{wizardModel:O}:{},maxRounds:A,locked:M}),D(``),re(!1))},se=i===void 0?[`host:goal-pill`,`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`,`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`,`host:goal-openrole`,`host:goal-clear`].map(e=>({id:e,source:`host`})):i.filter(e=>!e.hidden),ce=e=>{let t=new Set(e);return se.filter(e=>t.has(e.id)||e.source!==`host`)},le=(e,t)=>{let n=se.find(t=>t.id===e);return n?.labelExplicit?n.label:t},G={"host:goal-pill":(0,$.jsxs)(`button`,{type:`button`,className:`goalbar-hint`,title:o(`goalBarPlaceholder`),onClick:()=>re(!1),children:[(0,$.jsx)(Ue,{}),` `,(0,$.jsx)(`span`,{children:le(`host:goal-pill`,o(`goalBarTitle`))})]}),"host:goal-set":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn`,disabled:!E.trim(),onClick:ae,children:le(`host:goal-set`,o(`goalBarSet`))}),"host:goal-wizard":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action wizard`,disabled:!E.trim(),title:o(`goalWizardTip`),onClick:oe,children:le(`host:goal-wizard`,o(`goalWizardBtn`))}),"host:goal-plan":m.planMode?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-btn action plan`,disabled:!E.trim(),title:o(`planActionTip`),onClick:U,children:le(`host:goal-plan`,o(`planActionBtn`))}):null,"host:goal-lock":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(M?`goalBarLocked`:`goalBarUnlocked`),onClick:()=>N(e=>(Z({type:`set_goal_prefs`,locked:!e}),!e)),children:M?(0,$.jsx)(l,{}):(0,$.jsx)(Ze,{})}),"host:goal-collapse":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarClear`),onClick:()=>re(!0),children:(0,$.jsx)(w,{})}),"host:goal-model":p?(0,$.jsx)(`p`,{className:`goalbar-dsh-note`,children:o(`dshNoReviewModel`)}):(0,$.jsx)(Wt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarReviewModel`)}: ${ie()}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${le(`host:goal-model`,o(`goalBarReviewModel`))}:`}),(0,$.jsx)(`b`,{children:ie()})]}),open:I,onOpenChange:L,direction:`up`,children:(0,$.jsx)(Zc,{models:t,modelsLoading:n,currentModelId:O||null,active:I,onEnsureModels:()=>{t.length===0&&!n&&!V&&(te(!0),Z({type:`list_models`}))},loading:V,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{k(e.id),L(!1),Z({type:`set_goal_prefs`,reviewModel:e.id})},isRowActive:e=>Jc(e,O),extraTopRow:(0,$.jsx)(Ut,{active:O===``,onClick:()=>{k(``),L(!1),Z({type:`set_goal_prefs`,reviewModel:``})},children:o(`goalBarUseMainModel`)})})}),"host:goal-rounds":(0,$.jsxs)(`label`,{className:`goalbar-round`,title:o(`goalBarMaxRoundsTip`),children:[(0,$.jsx)(`span`,{children:le(`host:goal-rounds`,o(`goalBarMaxRounds`))}),(0,$.jsx)(`input`,{type:`number`,min:0,step:1,value:A,placeholder:o(`goalBarUnlimitedShort`),onChange:e=>{let t=parseInt(e.target.value,10);if(Number.isNaN(t)||t<0){j(0);return}j(t)},onBlur:()=>Z({type:`set_goal_prefs`,maxRounds:A}),onKeyDown:e=>{e.key===`Enter`&&(Z({type:`set_goal_prefs`,maxRounds:A}),e.target.blur())}})]}),"host:goal-execmodel":p?null:(0,$.jsx)(Wt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${o(`goalBarExecModel`)}: ${H()} · ${o(`goalBarExecModelTip`)}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${le(`host:goal-execmodel`,o(`goalBarExecModel`))}:`}),(0,$.jsx)(`b`,{children:H()})]}),open:R,onOpenChange:z,direction:`up`,children:(0,$.jsx)(Zc,{models:t,modelsLoading:n,currentModelId:P||null,active:R,onEnsureModels:()=>{t.length===0&&!n&&!V&&(te(!0),Z({type:`list_models`}))},loading:V,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{F(e.id),z(!1),Z({type:`set_goal_prefs`,execModel:e.id})},isRowActive:e=>Jc(e,P),extraTopRow:(0,$.jsx)(Ut,{active:P===``,onClick:()=>{F(``),z(!1),Z({type:`set_goal_prefs`,execModel:``})},children:o(`goalBarUseMainModel`)})})})},K=(e.wizard?.active??!1)&&h;if(K)return(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${K?`wizard`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`🔍`})}),(0,$.jsxs)(`span`,{className:`goalbar-text`,title:e.wizard?.draft??``,children:[o(`goalWizardRunning`),`: `,e.wizard?.draft]}),(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[o(`goalBarRound`,{n:(e.wizard?.step??0)+1}),` / `,e.wizard?.maxSteps??6]}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:f||o(`goalBarReviewing`)}),rS(ce([`host:goal-clear`]),{...G,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x`,title:o(`goalBarClear`),onClick:()=>{Z({type:`clear_goal`}),re(!0)},children:(0,$.jsx)(Be,{})})},a)]})});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`?o(`goalBarExecuting`):o(`goalBarReviewing`),` `,x]}):(0,$.jsx)(`span`,{className:`goalbar-chip ${e.verdict===`pass`?`pass`:e.verdict===`fail`?`fail`:e.verdict===`blocked`?`blocked`:``}`,children:e.verdict===`pass`?o(`goalBarPassed`):e.verdict===`fail`?o(`goalBarFailed`):e.verdict===`blocked`?o(`goalBarBlocked`):`${o(`goalBarRound`,{n:e.round||1})} · ${e.locked?o(`goalBarLocked`):o(`goalBarUnlocked`)}`}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:d}),y&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:_?.convId,children:[`· `,y]}),S>0&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:`${e.usage?.inputTokens??0} in / ${e.usage?.outputTokens??0} out`,children:[`· `,C(S),` tokens`]}),T&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)}),rS(ce([`host:goal-openrole`,`host:goal-clear`]),{...G,"host:goal-openrole":v?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:o(`goalBarOpenExecTip`),onClick:()=>Z({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:le(`host:goal-clear`,e.reviewing?o(`goalBarStop`):o(`goalBarClear`)),onClick:()=>{e.goal&&D(e.goal),Z({type:`clear_goal`}),re(!1)},children:e.reviewing?(0,$.jsx)(rt,{}):(0,$.jsx)(Be,{})})},a)]})});if(ne){let e=rS(ce([`host:goal-pill`]),G,a);return e?(0,$.jsx)(`div`,{className:`goalbar-collapsed`,children:e}):null}return(0,$.jsxs)(`div`,{className:`goalbar`,children:[(0,$.jsxs)(`div`,{className:`goalbar-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(Ue,{})}),(0,$.jsx)(`input`,{className:`goalbar-input`,autoFocus:!0,value:E,placeholder:o(`goalBarPlaceholder`),title:o(`goalBarPlaceholder`),onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ae()}}),rS(ce([`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`]),G,a)]}),(0,$.jsxs)(`div`,{className:`goalbar-opts`,children:[ce([`host:goal-model`,`host:goal-execmodel`,`host:goal-rounds`]).filter(e=>e.source===`host`).map(e=>(0,$.jsx)(Q.Fragment,{children:G[e.id]},e.id)),e.history&&e.history.length>0&&(0,$.jsxs)(Wt,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:o(`goalHistory`),children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:`${o(`goalHistory`)}:`}),(0,$.jsx)(`b`,{children:e.history.length})]}),open:B,onOpenChange:ee,direction:`up`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:o(`goalHistory`)}),e.history.map((e,t)=>(0,$.jsx)(Ut,{onClick:()=>{D(e.goal),ee(!1)},children:(0,$.jsxs)(`span`,{className:`dd-model-cell`,title:e.goal,children:[(0,$.jsxs)(`span`,{className:`dd-model-name`,children:[e.verdict===`pass`?`✅ `:e.verdict===`fail`?`❌ `:`⚠️ `,e.goal.length>42?`${e.goal.slice(0,42)}…`:e.goal]}),(0,$.jsx)(`span`,{className:`dd-model-meta`,children:(0,$.jsxs)(`span`,{className:`dd-model-id`,children:[o(`goalBarRound`,{n:e.rounds}),` · `,new Date(e.finishedAt).toLocaleString()]})})]})},`${e.finishedAt}-${t}`))]}),(0,$.jsx)(`span`,{className:`goalbar-lock-hint`,children:o(M?`goalBarLocked`:`goalBarUnlocked`)}),T&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:o(`goalBarStaleBackend`)})]})]})});function Ww(e){return e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e}function Gw(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 Kw(e){return!!(e&&!e.error&&e.expectedRevision&&e.added.length+e.modified.length+e.deleted.length>0)}function qw({mode:e,currentCwd:t,currentSandbox:r,sandboxDiff:i,projects:a,send:o,onClose:s}){let c=W(),l=r?.sourcePath||(!r&&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=r?.sourcePath?`${r.sourcePath}-exp`:`~/projects/${(r?.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(!r)return;let e={requestId:Ht(),path:r.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`&&r?.path){let e={requestId:Ht(),path:r.path};T(e),o({type:`diff_sandbox`,...e})}},[e,r?.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:r?.path,targetPath:t,switchToTarget:S}),s())},A=e=>{e.preventDefault(),r?.path&&j&&Kw(i)&&i.expectedRevision&&(T(null),o({type:`apply_sandbox_to_source`,path:r.path,expectedRevision:i.expectedRevision}),s())},j=e===`apply`&&Gw(i,r,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)(Be,{})}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:(0,$.jsx)(Or,{})}),(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)(oe,{"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)(We,{"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)(st,{"aria-hidden":!0,style:{marginRight:4,verticalAlign:`-1px`}}),Ww(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)(Pt,{"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()?`${Ww(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)(Or,{"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:r?.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)(St,{"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:r?.name||``,source:r?.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||!Kw(i),children:[(0,$.jsx)(n,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),c(`sandboxApplySubmit`,{count:M})]})]})]})]})})}function Jw(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(.5),c=(0,Q.useRef)(0),l=(0,Q.useRef)(0),u=(0,Q.useRef)(0),d=(0,Q.useRef)(0),f=typeof window<`u`&&Zt(),p=typeof window<`u`?window.piDesktop?.browser:void 0;if((0,Q.useEffect)(()=>{if(!p||!f)return;p.getState().then(e=>{e&&typeof e==`object`&&t(e)});let e=p.onState(e=>{e&&typeof e==`object`&&t(e)});return()=>{e?.()}},[p,f]),!f||!p||e?.mode!==`split`)return null;let m=t=>{if(t.button!==0)return;t.preventDefault(),t.currentTarget.setPointerCapture(t.pointerId);let n=window.innerWidth,i=Number(e?.splitRatio)||.5,o=n>0&&i>0?Math.round(n/i):window.screen.width;c.current=t.clientX,l.current=n,u.current=o,r(!0),a(null),s(i),document.body.classList.add(`desktop-is-resizing`)},h=e=>{if(!n)return;let t=e.clientX-c.current,r=l.current+t,i=u.current;if(i<=0)return;let o=r/i;if(o>.92||r>i-60)a(`agent`),s(1);else if(o<.08||r<60)a(`browser`),s(0);else{a(null);let e=Math.max(.2,Math.min(.8,o));s(e),cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{p.setSplitRatio?.(e)})}},g=e=>{if(!n)return;r(!1),document.body.classList.remove(`desktop-is-resizing`);try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}let t=e.clientX-c.current,i=l.current+t,o=u.current,s=o>0?i/o:.5;if(s>.92||i>o-60)p.setMode(`agent`);else if(s<.08||i<60)p.setMode(`browser`);else{let e=Math.max(.2,Math.min(.8,s));p.setSplitRatio?.(e)}a(null)};return(0,$.jsxs)(`div`,{className:`desktop-split-resizer ${n?`dragging`:``} ${i?`snap-${i}`:``}`,onPointerDown:m,onPointerMove:h,onPointerUp:g,onPointerCancel:g,title:`按住拖动调整分栏比例,拖至边缘可隐藏`,children:[(0,$.jsx)(`div`,{className:`desktop-split-resizer-line`}),n&&(0,$.jsx)(`div`,{className:`desktop-split-resizer-badge`,children:i===`agent`?`释放隐藏浏览器`:i===`browser`?`释放隐藏智能体`:`${Math.round(o*100)}% | ${Math.round((1-o)*100)}%`})]})}function Yw(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 Xw({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)(jt,{}),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)(ue,{})})]}),(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)(ke,{}),(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)(_t,{}),a(`worktreeActionRemove`)]})]})]},t.path)})})]})}var Zw=[{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 Qw({chat:e,bottombarItems:t,onUiAction:n,onOpenSettings:r,onViewChange:i,onCreateCli:a,onOpenGlobalSearch:o,onOpenBgTasks:s}){let c=He(`workspaceRoots`),l=e.state,[u,d]=(0,Q.useState)(!1);if(!l)return null;let f=t?t.map(e=>({id:e.id,entry:e,fallbackAlign:`start`})):Zw.map(({id:e,align:t})=>({id:e,entry:null,fallbackAlign:t})),p=[],m=[],h=[];for(let{id:t,entry:c,fallbackAlign:l}of f){if(c?.hidden)continue;let f=c??{id:t,slot:`bottombar`,source:`host`,label:t.slice(5),kind:`action`,order:100,align:l,hidden:!1,userOverrides:[],arrangedBy:[]},g=(0,$.jsx)(Us,{entry:f,bar:`bottom`,chat:e,view:void 0,onViewChange:i,onCreateCli:a,onOpenSettings:r,onOpenGlobalSearch:o,onOpenBgTasks:s,onOpenProjectPicker:()=>d(!0),isProjectPickerOpen:u,onUiAction:n});if(!g)continue;let _=f.align??l;_===`end`?h.push({key:t,node:g}):_===`center`?m.push({key:t,node:g}):p.push({key:t,node:g})}let g=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:g(p)}),m.length>0&&(0,$.jsx)(`div`,{className:`statusbar-center`,children:g(m)}),(0,$.jsx)(`div`,{className:`statusbar-right`,children:g(h)}),u&&(0,$.jsx)(uo,{open:!0,currentCwd:l.cwd,pathCompletions:e.pathCompletions,workspaceRoots:c,onClose:()=>d(!1),onSelectDirectory:e=>{e&&e!==l.cwd&&Z({type:`set_cwd`,path:e}),d(!1)},mode:`folder`})]})}var $w=[{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}],eT=`__tray`,tT=[`start`,`center`,`end`];function nT(e,t){return e(t===`start`?`uiLayoutAlignTop`:t===`end`?`uiLayoutAlignBottom`:`uiLayoutAlignMiddle`)}function rT(e,t=new Set){let n={},r=[],i=new Set;for(let a of $w){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 iT(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 aT(e){return(e??[]).filter(e=>!e.hidden)}function oT(e,t){let n=aT(e);return t===void 0?n:n.filter(e=>(e.align??`start`)===t)}function sT(e){return[...new Set(e)]}function cT(e,t,n){let r=e??{},i=iT(t,n.id);if(!i)return r;let a={...r};i.hidden&&(a.hidden=(r.hidden??[]).filter(e=>e!==n.id),a.shown=sT([...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=aT(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=sT([...(r.order??[]).filter(e=>!p.has(e)&&e!==n.id),...u,...f]),a}function lT(e,t){let n=e??{};return{...n,hidden:sT([...n.hidden??[],t]),shown:(n.shown??[]).filter(e=>e!==t)}}function uT({side:e,items:t,chat:n,view:r,onViewChange:i,onCreateCli:a,onOpenPanel:o,onOpenSettings:s,onOpenBgTasks:l,onOpenGlobalSearch:u,onUiAction:d,uiContextTopbar:f,onOpenProjectPicker:p,onThemeToggle:m,onSoundToggle:g,zenMode:_,onToggleZenMode:v,dropdownProps:y,plugins:b,onOpenPluginMenu:x,isPluginMenuOpen:S}){let{t:C}=c(),[w,T]=(0,Q.useState)(!1),E=(0,Q.useRef)(null),D=n.settings?.uiLayout?.sideDockFloat===!0,O=D?` side-dock-float`:``,k=t.filter(e=>!e.hidden);if(k.length===0)return null;if(D&&w)return(0,$.jsx)(`div`,{ref:E,className:`side-dock side-dock-${e} side-dock-collapsed${O}`,children:(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-toggle-btn`,"data-tip":`${C(`sideDockExpand`)} (${k.length})`,onClick:()=>T(!1),"aria-label":C(`sideDockExpand`),children:e===`left`?(0,$.jsx)(h,{}):(0,$.jsx)(te,{})})});let A=ka(k),j=t=>(0,$.jsx)(Us,{entry:t,bar:e,chat:n,view:r,plugins:b,onViewChange:i,onCreateCli:a,onOpenPanel:o,onOpenSettings:s,onOpenGlobalSearch:u,onOpenBgTasks:l,onOpenProjectPicker:p,onOpenPluginMenu:x,isPluginMenuOpen:S,onUiAction:d,uiContextEntries:f,zenMode:_,onToggleZenMode:v,dropdownProps:y},t.id);return(0,$.jsxs)(`div`,{ref:E,className:`side-dock side-dock-${e}${O}`,children:[D&&(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-collapse-btn`,"data-tip":C(`sideDockCollapse`),onClick:()=>T(!0),"aria-label":C(`sideDockCollapse`),children:e===`left`?(0,$.jsx)(te,{}):(0,$.jsx)(h,{})}),tT.map(e=>(0,$.jsx)(`div`,{className:`side-dock-slot side-dock-slot-${e}`,children:A[e].length>0&&(0,$.jsx)(`div`,{className:`side-dock-seg`,children:A[e].map(j)})},e))]})}function dT(e){let t=e.trim().toLowerCase();return/^(yes|allow|approve|confirm|ok|是|允许|同意|确认|放行)/i.test(t)}function fT(e){let t=e.trim().toLowerCase();return/^(no|deny|reject|cancel|block|否|拒绝|取消|阻止)/i.test(t)}function pT(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(`
|
|
80
|
+
`),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(`
|
|
81
|
+
`).trim(),n=r.slice(i,a+1).map(e=>e.startsWith(`$ `)?e.slice(2):e.startsWith(` `)?e.trimStart():e).join(`
|
|
82
|
+
`).trim(),o=r.slice(a+1).join(`
|
|
83
|
+
`).trim();if(n.length>0)return{hasRisk:t,intro:e,command:n,outro:o}}return{hasRisk:t,intro:e,command:null,outro:``}}function mT({command:e,hasRisk:t}){let r=W(),{copied:i,copy:a}=Kd({duration:2e3}),[o,s]=(0,Q.useState)(!1),c=(0,Q.useMemo)(()=>e.split(`
|
|
84
|
+
`),[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)(ct,{}),(0,$.jsx)(`span`,{children:r(`cmdInspectorRisk`)})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-head`,children:[(0,$.jsxs)(`div`,{className:`dialog-cmd-tag`,children:[(0,$.jsx)(Ce,{}),(0,$.jsx)(`span`,{children:r(`cmdInspectorTitle`)}),(0,$.jsx)(`span`,{className:`dialog-cmd-badge`,children:r(`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:r(o?`cmdInspectorCollapse`:`cmdInspectorExpand`),children:[o?(0,$.jsx)(w,{}):(0,$.jsx)(L,{}),(0,$.jsx)(`span`,{children:r(o?`cmdInspectorCollapse`:`cmdInspectorExpand`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>{a(e)},title:r(`copy`),children:[i?(0,$.jsx)(n,{}):(0,$.jsx)(x,{}),(0,$.jsx)(`span`,{children:r(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 hT({text:e,structuredCode:t}){let n=(0,Q.useMemo)(()=>t?{hasRisk:t.hasRisk??!1,intro:e,command:t.content,outro:``}:pT(e),[e,t]);return n.command?(0,$.jsxs)(`div`,{className:`dialog-prompt dialog-body`,children:[n.intro&&(0,$.jsx)(rp,{text:n.intro,rawHtml:!0,disableMath:!0}),(0,$.jsx)(mT,{command:n.command,hasRisk:n.hasRisk}),n.outro&&(0,$.jsx)(rp,{text:n.outro,rawHtml:!0,disableMath:!0})]}):(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(rp,{text:e,rawHtml:!0,disableMath:!0})})}function gT({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=>{Z({type:`dialog_response`,id:e.id,value:t})};(0,Q.useEffect)(()=>{r(``),a(0),s(!1),l(``)},[e.id]),Vt(()=>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(`
|
|
85
|
+
`)[0].trim():``,h=d.some(fT),g=d.find(fT)??d[d.length-1]??`No`,_=()=>{let e=c.trim();e&&(dn({text:`${t(`rejectFeedbackPrefix`)}${e}\n`}),sn()),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(dT);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(fT);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)(hT,{text:p,structuredCode:e.code}),e.kind===`confirm`&&(0,$.jsxs)($.Fragment,{children:[p&&(p.includes(`
|
|
86
|
+
`)||p.length>50||!f||e.code)&&(0,$.jsx)(hT,{text:p,structuredCode:e.code}),f&&(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(rp,{text:f,rawHtml:!0,disableMath:!0})})]}),e.kind===`input`&&(0,$.jsxs)($.Fragment,{children:[p&&(0,$.jsx)(hT,{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=dT(e),r=fT(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)(rp,{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)(pe,{}),(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 _T(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 vT(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 yT(e,t,n,r=[],i){let a=r.map(e=>({...e,global:!0,audience:`user`,createdAt:e.createdAt??0})),o=e=>bT(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 bT(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 xT(e){return JSON.stringify([e.owner??``,e.conversationId??``,e.id])}function ST(e,t){return!!t&&(e.conversationId===t||e.rootConversationId===t)}var CT=150;function wT({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),CT)},[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=Ln(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,cr.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 TT=`pi_web_qdraft_`,ET=864e5,DT=new Map;function OT(e){return`${TT}${e}`}function kT(e){if(!e)return null;try{if(typeof window<`u`&&window.sessionStorage){let t=window.sessionStorage.getItem(OT(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>ET?(jT(e),null):n}}}catch{}let t=DT.get(e);return t?t.updatedAt&&Date.now()-t.updatedAt>ET?(DT.delete(e),null):t:null}function AT(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){jT(e);return}let a={selections:{...t.selections},customs:{...t.customs},step:t.step,updatedAt:Date.now()};DT.set(e,a);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.setItem(OT(e),JSON.stringify(a))}catch{}}function jT(e){if(e){DT.delete(e);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.removeItem(OT(e))}catch{}}}function MT({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)(()=>kT(o)?.selections??{}),[u,d]=(0,Q.useState)(()=>kT(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=yw(),[_,v]=(0,Q.useState)(()=>kT(o)?.step??0),[y,b]=(0,Q.useState)(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1),[x,S]=(0,Q.useState)(Date.now),C=(0,Q.useRef)(!1),[T,E]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{C.current=!1;let t=kT(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),S(Date.now())},[e.id,e.deadline,e.createdAt,t]),(0,Q.useEffect)(()=>{C.current||AT(o,{selections:c,customs:u,step:_})},[e.id,c,u,_]),(0,Q.useEffect)(()=>{if(!e.deadline&&!e.createdAt)return;S(Date.now());let t=setInterval(()=>{let t=Date.now();S(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=>{C.current=!0,jT(o),F_({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...e.global?{global:!0}:{},...n?.trim()?{cancelReason:n.trim()}:{},...t?{owner:t}:{}})},[e.id,t]);Vt(()=>{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)),A=k.length;(0,Q.useEffect)(()=>{if(e.questions.length===0||A>0)return;let n=setTimeout(()=>{F_({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,A,t]);let j=Math.min(_,Math.max(0,A-1)),M=k[j];if(!M)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 N=(()=>{if(!M)return[];if(M.optionsMap&&M.dependsOn){let e=c[M.dependsOn.questionId]??[];for(let t of e)if(M.optionsMap[t])return M.optionsMap[t]}return M.options??[]})(),P=n=>{C.current=!0,jT(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}:{}}});F_({type:`question_answer`,id:e.id,answers:r,...e.global?{global:!0}:{},...t?{owner:t}:{}})||E(!0)},F=(e,t)=>{l(n=>{let r=n[e]??[];return{...n,[e]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}})},I=(t,n,r)=>{if(r){F(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&&P(a)},R=()=>{j>=A-1?P(c):v(j+1)},z=t=>{let n=e.questions.find(e=>e.id===t);return N.length===0&&(n?.options?.length??0)===0||(c[t]?.length??0)>0||(u[t]??``).trim()!==``},B=N.filter(e=>(c[M.id]??[]).includes(e.label)&&e.preview).map(e=>e.preview),ee=(M.header||M.question).replace(/\s+/g,` `).trim(),V=(u[M.id]??``).trim(),te=Object.values(u).map(e=>e?.trim()).filter(Boolean).join(`;
|
|
87
|
+
`),ne=V.length>0||te.length>0,re=V||te;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<N.length){e.preventDefault(),I(M.id,N[t].label,!!M.multiSelect);return}}if(e.key===`ArrowLeft`&&j>0){e.preventDefault(),v(j-1);return}if(e.key===`ArrowRight`&&j<A-1&&z(M.id)){e.preventDefault(),v(j+1);return}e.key===`Enter`&&z(M.id)&&(e.preventDefault(),R())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[f,N,M.id,M.multiSelect,j,A,z,R,I]),(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}),A>1&&(0,$.jsx)(`span`,{className:`question-progress`,children:a(`questionStep`,{cur:j+1,total:A})}),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`)}):vT(e.createdAt??0,x)?(0,$.jsxs)(`span`,{className:`question-timer question-queue-wait`,children:[`⏱ `,vT(e.createdAt??0,x)]}):null,f&&(0,$.jsx)(`span`,{className:`question-collapsed-preview`,title:ee,children:ee}),(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)(w,{}):(0,$.jsx)(L,{})}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:a(r?`questionQueueDefer`:ne?`modelQuestionRejectWithNoteTip`:`cancel`),onClick:e=>{e.stopPropagation(),r?r():D(ne?re:void 0)},children:`✕`})]})]}),!f&&(0,$.jsxs)($.Fragment,{children:[A>1&&(0,$.jsx)(`div`,{className:`question-step-pills`,role:`tablist`,children:k.map((e,t)=>{let n=t===j,r=z(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:M.header??`${a(`modelQuestion`)} ${j+1}`}),(0,$.jsx)(`div`,{className:`question-head`,children:(0,$.jsx)(rp,{text:M.question,rawHtml:!0})}),M.detail&&(0,$.jsx)(`div`,{className:`set-hint`,children:(0,$.jsx)(rp,{text:M.detail,rawHtml:!0})}),N.length>0&&(0,$.jsx)(`div`,{className:`set-list`,children:N.map((e,t)=>{let n=(c[M.id]??[]).includes(e.label),r=e.recommended??(t===0&&N.length>1),i=t<9?t+1:void 0;return(0,$.jsx)(NT,{label:e.label,description:e.description,mark:M.multiSelect?n?`☑ `:`☐ `:n?`● `:`○ `,active:n,keyNumber:i,recommended:r,onPick:()=>I(M.id,e.label,!!M.multiSelect)},e.label)})}),B.length>0&&(0,$.jsxs)(`div`,{className:`question-preview`,children:[(0,$.jsx)(`div`,{className:`question-preview-label`,children:a(`optionPreview`)}),B.map((e,t)=>(0,$.jsx)(`div`,{className:`question-preview-body`,children:(0,$.jsx)(rp,{text:e,rawHtml:!0})},t))]}),(0,$.jsx)(`input`,{className:`set-prompt-input question-custom`,placeholder:a(`modelQuestionCustom`),value:u[M.id]??``,onChange:e=>d(t=>({...t,[M.id]:e.target.value})),onCompositionEnd:g.onCompositionEnd,onKeyDown:e=>{g.isImeKey(e.nativeEvent)||e.key===`Enter`&&(e.preventDefault(),z(M.id)&&R())}})]},M.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&&j===A-1&&!M.multiSelect&&N.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${ne?` reject-note`:``}`,onClick:()=>D(ne?re:void 0),title:a(ne?`modelQuestionRejectWithNoteTip`:`cancel`),children:a(ne?`modelQuestionRejectWithNote`:`cancel`)}),(0,$.jsxs)(`div`,{className:`dialog-nav-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-prev`,disabled:j===0,onClick:()=>v(j-1),children:a(`previous`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-submit`,disabled:!z(M.id),onClick:R,children:j===A-1?a(`modelQuestionSubmit`):a(`next`)})]})]})]})]})}function NT({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)(rp,{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)(rp,{text:t,rawHtml:!0})}),(0,$.jsx)(wT,{anchorRef:s,enabled:Fn(),className:`question-desc-tip`,children:(0,$.jsx)(rp,{text:t,rawHtml:!0})})]})]})}function PT({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=Zl(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)}),vT(a(e),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,vT(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 FT({questions:e,activeConversationId:t,mode:n}){let r=W(),i=e=>{let t=_T(e);t&&Z(t)};return(0,$.jsx)(PT,{items:e.filter(e=>e.audience===`user`),itemKey:xT,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:!ST(e,t))),children:(e,t)=>(0,$.jsx)(MT,{question:e,owner:e.owner,onDefer:t,onNavigate:e.rootConversationId||e.conversationId?()=>i(e):void 0},xT(e))})}function IT({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}=rv(r,{isolated:!!(e.info.isolated||e.module.isolated||e.module.shadow)}),o;try{o=e.module.mount(i,kv(e.info.id,e=>Z(e)))}catch(t){console.error(`[plugin:${e.info.id}] mount failed:`,t),i.textContent=n(`pluginMountFailed`,{name:e.info.name})}return()=>{if(typeof o==`function`)try{o()}catch(t){console.error(`[plugin:${e.info.id}] cleanup failed:`,t)}a()}},[e]),(0,$.jsx)(`div`,{className:`plugin-view`,ref:t})}function LT({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),yv(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 RT({onAction:e}){let t=Ua(),n=Jm(!!t),r=(0,Q.useMemo)(()=>t?Xa(t.entries):[],[t]),{items:i,selectParents:a}=(0,Q.useMemo)(()=>Ya(r),[r]),o=(0,Q.useMemo)(()=>Za(i),[i]),s=(0,Q.useMemo)(()=>typeof window>`u`?!1:o.length>14&&window.innerWidth>=640,[o.length]),c=(0,Q.useMemo)(()=>t?Ka(t.slot,t.target):void 0,[t,t?.slot,t?.target.kind]),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(-1),[h,g]=(0,Q.useState)(-1),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(0),x=(0,Q.useRef)(-1),S=e=>{x.current=e,m(e)},C=(0,Q.useMemo)(()=>h>=0?Xa(i[h]?.children??[]):[],[i,h]),w=(0,Q.useMemo)(()=>Za(C),[C]),T=e=>{let n=i[e];if(t&&n&&!Ja(n,c)){if(n.children?.length){g(e);return}E(n,t)||Ba()}},E=(t,n,r)=>t.source===`host`&&n.onHostAction?n.onHostAction(t,n.target)===!0:(e(t,n.target,r),!1),D=(0,Q.useRef)(T);if((0,Q.useLayoutEffect)(()=>{D.current=T}),(0,Q.useEffect)(()=>{if(!t){x.current=-1,m(-1),g(-1);return}let e=$a(i,-1,1,c);x.current=e,m(e),g(-1),l.current?.focus()},[t,i,c]),(0,Q.useLayoutEffect)(()=>{if(!t){f(null);return}let e=l.current;if(!e)return;let n=e.getBoundingClientRect();f(Ga(t.x,t.y,n.width,n.height,window.innerWidth,window.innerHeight))},[t,i]),(0,Q.useLayoutEffect)(()=>{let e=u.current,t=l.current;if(h<0||!e||!t){v(!1),b(0);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=window.innerWidth-r.right,a=r.left;v(i<n.width+8&&a>i);let o=n.bottom-(window.innerHeight-8);b(o>0?-Math.min(o,Math.max(0,n.top-8)):0)},[h,i]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>l.current&&e instanceof Node&&l.current.contains(e),n=t=>{e(t.target)||Ba()},r=t=>{e(t.target)||Ba()},i=()=>Ba();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=$a(i,x.current,e,c);x.current=t,m(t)},n=t=>{switch(t.key){case`Escape`:t.preventDefault(),Ba();return;case`Tab`:Ba();return;case`ArrowDown`:t.preventDefault(),e(1);return;case`ArrowUp`:t.preventDefault(),e(-1);return;case`ArrowRight`:i[x.current]?.children?.length&&(t.preventDefault(),g(x.current));return;case`ArrowLeft`:h>=0&&(t.preventDefault(),g(-1));return;case`Enter`:case` `:t.preventDefault(),D.current(x.current);return;default:return}};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[t,i,h,c]),(0,Q.useEffect)(()=>{p<0||l.current?.querySelector(`[data-ctx-active="true"]`)?.scrollIntoView?.({block:`nearest`})},[p]),!t)return null;let O=e=>{let n=a.get(e.id);if(n){if(Ja(n.parent,c))return;t&&!E(n.parent,t,n.value)&&Ba();return}Ja(e,c)||E(e,t)||Ba()},k=(e,t,n)=>{let r=Ja(e,c),i=!!e.children?.length,a=to(e.icon),o=n&&p===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?h===t:void 0,"data-ctx-active":o?`true`:void 0,onMouseEnter:n?()=>{S(t),i&&!r&&g(t)}:void 0,onClick:()=>n?T(t):O(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&&h===t?(0,$.jsx)(`div`,{ref:u,className:`ctx-menu-sub${_?` left`:``}`,role:`menu`,"aria-label":e.label,style:y?{marginTop:y}:void 0,children:w.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):k(e.entry,e.index,!1))}):null]},`${e.id}#${t}`)};return(0,cr.createPortal)((0,$.jsx)(`div`,{ref:l,className:`ctx-menu${s?` is-multi-col`:``}`,role:`menu`,"aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:d?.x??t.x,top:d?.y??t.y,zIndex:n,visibility:d?`visible`:`hidden`},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},children:o.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):k(e.entry,e.index,!0))}),document.body)}var zT=0,BT=[],VT=new Map,HT=new Set;function UT(){for(let e of HT)try{e()}catch{}}function WT(e){let t=VT.get(e);t!==void 0&&(clearTimeout(t),VT.delete(e))}function GT(e){let t=e.id||`banner-${Date.now()}-${++zT}`,n={...e,id:t,type:e.type||`info`,persistent:!!e.persistent,timeoutMs:e.timeoutMs??5e3,dismissible:e.dismissible!==!1};if(WT(t),!n.persistent&&n.timeoutMs&&n.timeoutMs>0){let e=setTimeout(()=>{KT(t)},n.timeoutMs);VT.set(t,e)}let r=BT.findIndex(e=>e.id===t);if(r>=0){let e=[...BT];e[r]=n,BT=e}else BT=[...BT,n];return UT(),t}function KT(e,t){WT(e);let n=BT.find(t=>t.id===e);if(n){if(BT=BT.filter(t=>t.id!==e),!t?.silent)try{n.onClose?.()}catch{}UT()}}function qT(e,t){let n=BT.filter(e);if(n.length!==0){for(let e of n)if(WT(e.id),!t?.silent)try{e.onClose?.()}catch{}BT=BT.filter(t=>!e(t)),UT()}}function JT(){return BT}function YT(e){return HT.add(e),()=>{HT.delete(e)}}function XT(){return(0,Q.useSyncExternalStore)(YT,JT,JT)}function ZT({type:e}){switch(e){case`question`:return(0,$.jsx)(ut,{className:`banner-icon banner-icon-question`});case`warning`:return(0,$.jsx)(ct,{className:`banner-icon banner-icon-warning`});case`error`:return(0,$.jsx)(Pe,{className:`banner-icon banner-icon-error`});case`success`:return(0,$.jsx)(Ge,{className:`banner-icon banner-icon-success`});default:return(0,$.jsx)(xe,{className:`banner-icon banner-icon-info`})}}var QT=(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)(ZT,{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(),KT(e.id)},"aria-label":`Close banner`,title:t(`close`),children:(0,$.jsx)(Be,{})})]})}),$T=(0,Q.memo)(function(){let e=XT();return e.length===0?null:(0,$.jsx)(`aside`,{className:`banner-container`,"aria-label":`Notifications`,children:e.map(e=>(0,$.jsx)(QT,{banner:e},e.id))})});function eE(e){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1),l=(0,Q.useCallback)(e=>{let r=t.current;if(!r)return;let{width:i,height:o}=r.getBoundingClientRect(),s={x:Math.max(8,Math.min(e.x,window.innerWidth-i-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-o-8))};n.current=s,a(e=>e?.x===s.x&&e.y===s.y?e:s)},[]);(0,Q.useLayoutEffect)(()=>{if(!e){r.current=null,s(!1);return}let i=t.current;if(!i)return;let a=()=>{n.current&&l(n.current)};a();let o=new ResizeObserver(a);return o.observe(i),window.addEventListener(`resize`,a),()=>{o.disconnect(),window.removeEventListener(`resize`,a)}},[e,l]);let u=e=>{let n=e.target instanceof Element?e.target.closest(`button, select, input, textarea, a, [role='button'], [contenteditable='true']`):null;if(e.button!==0||!e.isPrimary||n&&n!==e.currentTarget)return!1;let i=t.current;if(!i)return!1;let a=i.getBoundingClientRect();return r.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY},origin:{x:a.left,y:a.top},moved:!1},c.current=!1,n!==e.currentTarget&&e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),!0},d=e=>{let t=r.current;if(!t||t.pointerId!==e.pointerId)return;let n=e.clientX-t.start.x,i=e.clientY-t.start.y;!t.moved&&Math.hypot(n,i)<3||(t.moved=!0,c.current=!0,s(!0),l({x:t.origin.x+n,y:t.origin.y+i}))},f=e=>{r.current?.pointerId===e.pointerId&&(r.current=null,s(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return{panelRef:t,style:i?{left:i.x,top:i.y,right:`auto`,bottom:`auto`}:void 0,dragging:o,onPointerDown:u,onPointerMove:d,onPointerUp:f,onPointerCancel:f,onLostPointerCapture:f,onClickCapture:e=>{c.current&&e.detail!==0&&(e.preventDefault(),e.stopPropagation()),c.current=!1}}}var tE=class extends Error{code;constructor(e){super(e),this.code=e}};function nE(e){let t=0,n=0,r=0;for(let i of e){n+=i.content.length;for(let e of i.attachments||[]){t++,n+=e.content.length+e.name.length+(e.path?.length||0)+128;let i=e.image?.data;i&&(r+=i.length*3/4-(i.endsWith(`==`)?2:+!!i.endsWith(`=`)))}}return t>8?`quickAskTooManyReferences`:r>6291456?`quickAskImagesTooLarge`:n>65536?`quickAskContextTooLarge`:null}async function rE(e,t){let n=new AbortController,r=()=>n.abort(t.signal.reason);t.signal.aborted?r():t.signal.addEventListener(`abort`,r,{once:!0});let i=setTimeout(()=>n.abort(Error(`Loading reference timed out`)),45e3);try{let r=await fetch(g(`/api/quick-ask/context`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({source:e,scope:t.scope,clientId:t.clientId}),signal:n.signal}),i=await r.json();if(!r.ok)throw r.status===415||/unsupported|binary file/i.test(i.error||``)?new tE(`quickAskUnsupportedFile`):Error(i.error||`HTTP ${r.status}`);let a=i.attachment;if(!a||typeof a.id!=`string`||typeof a.name!=`string`||typeof a.content!=`string`||![`file`,`directory`,`conversation`].includes(a.kind))throw Error(`Invalid reference response`);return a}finally{clearTimeout(i),t.signal.removeEventListener(`abort`,r)}}async function iE(e,t){if(e.size>2097152)throw new tE(`quickAskFileTooLarge`);t.signal.throwIfAborted();let n=new Uint8Array(await e.arrayBuffer());t.signal.throwIfAborted();let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.subarray(e,e+8192));return rE({kind:`upload`,name:e.name,data:btoa(r),mimeType:e.type},t)}async function aE(e,t){t.signal.throwIfAborted();let n=e[0]?.webkitRelativePath.split(`/`)[0]||`folder`,r=e.slice(0,64),i=r.map(e=>e.webkitRelativePath||e.name).join(`
|
|
88
|
+
`).slice(0,16e3);if(e.length>r.length&&(i+=`\n[Listing truncated: ${e.length-r.length} more files]`),t.scope===`content`){let e=r.filter(e=>e.type.startsWith(`text/`)||/\.(?:txt|md|mdx|json|jsonc|ya?ml|toml|xml|csv|ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|c|cpp|h|css|html|sh|sql|log|ini|conf)$/i.test(e.name));for(let n of e.slice(0,8)){let e=await iE(n,t);if(i+=`\n\n--- ${n.webkitRelativePath||n.name} ---\n${e.content}`,i.length>3e4){i=i.slice(0,3e4)+`
|
|
89
|
+
[Content truncated]`;break}}e.length>8&&(i+=`
|
|
90
|
+
[Additional text files omitted]`)}return{id:`upload-directory:${n}`,kind:`directory`,name:`${n}/`,content:i}}function oE({attachments:e,onRemove:t}){let n=W(),[r,i]=(0,Q.useState)(!1);return e.length?(0,$.jsxs)(`div`,{className:`quick-ask-references${r?` is-expanded`:``}`,"aria-label":n(`quickAskReferences`),children:[(0,$.jsx)(`div`,{className:`quick-ask-reference-tags`,children:(r?e:e.slice(0,2)).map(e=>{let r=e.kind===`conversation`?V:e.kind===`directory`?st:Y;return(0,$.jsxs)(`span`,{className:`quick-ask-reference-tag`,title:e.path||e.name,children:[(0,$.jsx)(r,{size:10,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:e.name}),t&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`${n(`quickAskRemoveReference`)}: ${e.name}`,onClick:()=>t(e.id),children:(0,$.jsx)(Be,{size:10})})]},e.id)})}),e.length>2&&(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-reference-count`,"aria-expanded":r,"aria-label":n(r?`quickAskCollapseReferences`:`quickAskExpandReferences`),onClick:()=>i(!r),children:r?`−`:`+${e.length-2}`})]}):null}function sE({currentConversation:e,disabled:t,onReference:n,onFiles:r,onFolder:i}){let a=W(),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=dr({open:o,anchor:c,side:`top`,align:`left`,onClose:()=>s(!1)});return(0,Q.useEffect)(()=>{u.current?.setAttribute(`webkitdirectory`,``)},[]),(0,Q.useLayoutEffect)(()=>{o||(d.current=!1),o&&f.pos&&!d.current&&(d.current=!0,f.panelRef.current?.querySelector(`button:not(:disabled)`)?.focus({preventScroll:!0}))},[o,f.pos,f.panelRef]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:c,type:`button`,className:`quick-ask-attach`,title:a(`quickAskAttach`),"aria-label":a(`quickAskAttach`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`quick-ask-attachment-menu`,disabled:t,onClick:()=>s(!o),children:(0,$.jsx)(It,{size:14})}),(0,$.jsx)(`input`,{ref:l,type:`file`,multiple:!0,hidden:!0,"aria-label":a(`quickAskAttachFiles`),onChange:e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&r(t)}}),(0,$.jsx)(`input`,{ref:u,type:`file`,multiple:!0,hidden:!0,"aria-label":a(`quickAskAttachFolder`),onChange:e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&i(t)}}),o&&(0,cr.createPortal)((0,$.jsxs)(`div`,{ref:f.panelRef,style:f.style,id:`quick-ask-attachment-menu`,className:`quick-ask-menu quick-ask-attachment-menu`,role:`dialog`,"aria-label":a(`quickAskAttach`),children:[(0,$.jsxs)(`button`,{type:`button`,disabled:!e,onClick:()=>{let t=e;s(!1),t&&n(t)},children:[(0,$.jsx)(V,{size:13}),a(`quickAskAttachCurrent`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{s(!1),l.current?.click()},children:[(0,$.jsx)(Y,{size:13}),a(`quickAskAttachFiles`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{s(!1),u.current?.click()},children:[(0,$.jsx)(st,{size:13}),a(`quickAskAttachFolder`)]})]}),document.body)]})}function cE({settings:e,fallbackModel:t,currentConversation:n,clientId:r}){let i=W(),{locale:a}=c(),[o,s]=(0,Q.useState)(!1),u=eE(o),d=eE(!o&&e?.quickAskEnabled!==!1),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),[S,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(``),[F,I]=(0,Q.useState)(`ask`),[L,R]=(0,Q.useState)(e?.quickAskTranslateTarget||`auto`),[z,B]=(0,Q.useState)([]),ee=(0,Q.useRef)([]),te=(0,Q.useRef)(0),ne=(0,Q.useRef)(new Set),[re,ie]=(0,Q.useState)(0),[H,ae]=(0,Q.useState)(null),U=(0,Q.useRef)(null),oe=(0,Q.useRef)(null),se=(0,Q.useRef)(null),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(null),G=d.panelRef,K=(0,Q.useRef)(null),ue=(0,Q.useRef)(null),de=(0,Q.useRef)(null),fe=(0,Q.useRef)(!0),pe=(0,Q.useRef)(0),q=(0,Q.useRef)(o),me=()=>{de.current&&(pe.current=de.current.scrollTop),x(!1),s(!1)};Vt(me,o);let he=dr({open:o&&b,anchor:ue,onClose:()=>x(!1)}),ge=()=>{se.current?.(),se.current=null,U.current?.abort(),U.current=null,E(!1)},_e=()=>{te.current++;for(let e of ne.current)e.abort();ne.current.clear(),ee.current=[],B([]),ie(0),ae(null)},ve=()=>{ge(),_e(),I(`ask`),oe.current=null,p([]),h(``),y(!0),x(!1),w(``),O(null),A(!1),M(!1),P(``),fe.current=!0,pe.current=0,le.current?.focus({preventScroll:!0})},J=async e=>{ge();let n=new AbortController;U.current=n,oe.current=e,p(e),E(!0),O(null),A(!1),M(!1),fe.current=!0;let r=``,a=()=>U.current===n&&!n.signal.aborted,o=()=>{ce.current!==null&&cancelAnimationFrame(ce.current),ce.current=null,a()&&r&&p([...e,{role:`assistant`,content:r}])};se.current=o;try{await Il(await fetch(g(`/api/quick-ask`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},body:JSON.stringify({messages:e,fallbackModel:t}),signal:n.signal}),e=>{a()&&(e.type===`start`&&P(e.model),e.type===`delta`&&(r+=e.text,ce.current===null&&(ce.current=requestAnimationFrame(o))),e.type===`done`&&(r=e.text,P(e.model),o(),q.current||M(!0)))})}catch(e){if(a()){let t=e instanceof Error?e.message:String(e);O(e instanceof TypeError||/failed to fetch|networkerror|load failed/i.test(t)?i(`quickAskNetworkError`):t===`Model returned no answer`?i(`quickAskEmptyAnswer`):t)}}finally{U.current===n&&(o(),se.current=null,U.current=null,E(!1))}},ye=(e=S.trim())=>{if(!e||U.current||ne.current.size)return;let t=Ll(f,e,ee.current),n=nE(t);if(n){ae(i(n));return}I(`ask`),y(!0),J(t),w(``)},be=async e=>{let t=te.current,n=new AbortController;ne.current.add(n),s(!0),M(!1),x(!1),ie(e=>e+1),ae(null);try{let r=await e(n.signal);if(t!==te.current||n.signal.aborted)return;let i=[...ee.current];for(let e of r){let t=i.findIndex(t=>t.id===e.id);t<0?i.push(e):i[t]=e}if(i.length>8)throw new tE(`quickAskTooManyReferences`);ee.current=i,B(i),y(!0)}catch(e){t===te.current&&!n.signal.aborted&&ae(e instanceof tE?i(e.code):e instanceof Error?e.message:String(e))}finally{ne.current.delete(n),t===te.current&&ie(e=>Math.max(0,e-1))}},xe=t=>{let n=t.kind===`conversation`?e?.quickAskConversationScope||`recent`:t.kind===`directory`?e?.quickAskFolderScope||`listing`:void 0;return be(async e=>[await rE(t,{scope:n,clientId:r,signal:e})])},Se=e=>be(async t=>{if(e.length>8)throw new tE(`quickAskTooManyReferences`);let n=[];for(let i of e)n.push(await iE(i,{signal:t,clientId:r}));return n}),Ce=t=>{let n=e?.quickAskFolderScope||`listing`;return be(async e=>[await aE(t,{scope:n,clientId:r,signal:e})])},Y=(t,n,r=e?.quickAskTranslateTarget||`auto`)=>{if(n!==`translate`||e?.quickAskTranslateEnabled!==!1){if(!t.trim()){ae(i(`quickAskEmptySelection`));return}_e(),s(!0),I(n),R(r),h(t),y(!1),x(!1),w(``),P(``),pe.current=0,J([{role:`user`,content:n===`translate`?Fl(e,t,a,r):Ml(e?.quickAskExplainPrompt,t)}])}};(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;s(!0),M(!1),t.reference?xe(t.reference):t.selection!==void 0&&Y(t.selection,t.action||`explain`)};return window.addEventListener(Al,e),()=>window.removeEventListener(Al,e)},[e?.quickAskExplainPrompt,e?.quickAskTranslatePrompt,e?.quickAskTranslateTarget,e?.quickAskTranslateStyle,e?.quickAskTranslateEnabled,e?.quickAskConversationScope,e?.quickAskFolderScope,t,r,a,i]),(0,Q.useEffect)(()=>()=>{te.current++;for(let e of ne.current)e.abort();ne.current.clear();let e=U.current;U.current=null,se.current=null,e?.abort(),ce.current!==null&&cancelAnimationFrame(ce.current),ce.current=null},[]),(0,Q.useLayoutEffect)(()=>{q.current=o,o?(M(!1),(le.current||K.current)?.focus({preventScroll:!0}),de.current&&(de.current.scrollTop=pe.current)):document.activeElement===document.body&&G.current?.focus({preventScroll:!0})},[o]),(0,Q.useLayoutEffect)(()=>{o&&v&&le.current?.focus({preventScroll:!0})},[o,v]),(0,Q.useLayoutEffect)(()=>{b&&he.panelRef.current?.querySelector(`button`)?.focus({preventScroll:!0})},[b,he.panelRef]),(0,Q.useLayoutEffect)(()=>{o&&fe.current&&de.current&&(de.current.scrollTop=de.current.scrollHeight)},[o,f,T,D,k]);let we=N||e?.quickAskModel||t||i(`quickAskFollowModel`),Te=f.findLast(e=>e.role===`assistant`),Ee=f.at(-1)?.role===`assistant`,De=v||f.length===0;return(0,cr.createPortal)((0,$.jsxs)($.Fragment,{children:[!o&&e?.quickAskEnabled!==!1&&(0,$.jsxs)(`button`,{ref:G,type:`button`,className:`quick-ask-launcher${T?` is-loading`:``}${j?` has-answer`:``}${d.dragging?` is-dragging`:``}`,style:d.style,title:i(j?`quickAskReady`:T?`quickAskLoading`:`quickAskOpen`),"aria-label":i(`quickAskOpen`),onPointerDown:d.onPointerDown,onPointerMove:d.onPointerMove,onPointerUp:d.onPointerUp,onPointerCancel:d.onPointerCancel,onLostPointerCapture:d.onLostPointerCapture,onClickCapture:d.onClickCapture,onClick:()=>s(!0),children:[(0,$.jsx)(V,{size:20}),(T||j)&&(0,$.jsx)(`span`,{className:`quick-ask-launcher-dot`,"aria-hidden":`true`}),j&&(0,$.jsx)(`span`,{className:`quick-ask-launcher-status`,role:`status`,children:i(`quickAskReady`)})]}),o&&(0,$.jsxs)(`div`,{ref:u.panelRef,style:u.style,className:`quick-ask-popover${u.dragging?` is-dragging`:``}`,role:`dialog`,"aria-modal":`false`,"aria-label":i(`quickAskTitle`),children:[(0,$.jsxs)(`div`,{className:`quick-ask-header`,onPointerDown:e=>{u.onPointerDown(e)&&x(!1)},onPointerMove:u.onPointerMove,onPointerUp:u.onPointerUp,onPointerCancel:u.onPointerCancel,onLostPointerCapture:u.onLostPointerCapture,children:[F===`translate`?(0,$.jsx)(Ct,{className:`quick-ask-symbol`,size:14,"aria-hidden":`true`}):(0,$.jsx)(Re,{className:`quick-ask-symbol`,size:14,"aria-hidden":`true`}),(0,$.jsx)(`strong`,{className:`quick-ask-heading`,children:i(F===`translate`?`quickAskTranslation`:`quickAskTitle`)}),F===`translate`&&(0,$.jsx)(`select`,{className:`quick-ask-target`,value:L,"aria-label":i(`quickAskTargetLanguage`),disabled:e?.quickAskTranslateEnabled===!1,onChange:e=>Y(m,`translate`,e.target.value),children:Object.entries(Pl).map(([e,t])=>(0,$.jsx)(`option`,{value:e,children:e===`auto`?i(`quickAskTargetAuto`):t},e))}),(0,$.jsxs)(`div`,{className:`quick-ask-header-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-icon`,title:i(`quickAskNewTopic`),"aria-label":i(`quickAskNewTopic`),onClick:ve,children:(0,$.jsx)(C,{size:15,"aria-hidden":`true`})}),(0,$.jsx)(`button`,{ref:ue,type:`button`,className:`btn-icon`,title:i(`quickAskMore`),"aria-label":i(`quickAskMore`),"aria-expanded":b,"aria-haspopup":`dialog`,"aria-controls":`quick-ask-menu`,onClick:()=>x(!b),children:(0,$.jsx)(_,{size:15})}),(0,$.jsx)(`button`,{ref:K,type:`button`,className:`btn-icon`,title:i(`quickAskClose`),"aria-label":i(`quickAskClose`),onClick:me,children:(0,$.jsx)(Be,{size:14})})]})]}),(0,$.jsx)(oE,{attachments:z,onRemove:e=>{let t=ee.current.filter(t=>t.id!==e);ee.current=t,B(t)}}),(0,$.jsxs)(`div`,{ref:de,id:`quick-ask-answer`,className:`quick-ask-body`,"aria-busy":T,onScroll:()=>{let e=de.current;e&&(fe.current=e.scrollHeight-e.scrollTop-e.clientHeight<36,pe.current=e.scrollTop)},children:[f.length===0&&z.length>0&&(0,$.jsx)(`p`,{className:`quick-ask-reference-empty`,children:i(`quickAskReferenceEmpty`)}),f.length===0&&z.length===0&&(0,$.jsxs)(`div`,{className:`quick-ask-empty`,children:[(0,$.jsx)(`strong`,{children:i(`quickAskEmptyTitle`)}),(0,$.jsx)(`p`,{children:i(`quickAskEmpty`)})]}),f.map((e,t)=>(0,$.jsx)(`div`,{className:`quick-ask-message quick-ask-${e.role}`,children:e.role===`assistant`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`quick-ask-answer${T&&t===f.length-1?` is-streaming`:``}`,children:(0,$.jsx)(rp,{text:e.content})}),(!T||t<f.length-1)&&(0,$.jsx)(qd,{text:e.content})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(oE,{attachments:e.attachments||[]}),(0,$.jsx)(`div`,{className:t===0&&m?`quick-ask-selection`:void 0,children:t===0&&m?m:e.content})]})},t)),re>0&&(0,$.jsx)(`p`,{role:`status`,className:`quick-ask-reference-status`,children:i(`quickAskReferenceLoading`)}),H&&(0,$.jsxs)(`p`,{role:`alert`,className:`quick-ask-reference-error`,children:[i(`quickAskReferenceError`),`: `,H]}),T&&(0,$.jsxs)(`p`,{role:`status`,className:`quick-ask-stream-status`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`}),i(`quickAskLoading`)]}),D&&(0,$.jsxs)(`div`,{role:`alert`,className:`quick-ask-error`,children:[(0,$.jsx)(`strong`,{children:i(`quickAskError`)}),(0,$.jsx)(`p`,{children:D})]}),k&&(0,$.jsx)(`p`,{role:`status`,className:`quick-ask-stopped`,children:i(`quickAskStopped`)}),(D||k)&&oe.current&&(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>void J(oe.current),children:i(`quickAskRetry`)}),!T&&!D&&!k&&Ee&&(0,$.jsxs)(`div`,{className:`quick-ask-suggestions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>ye(i(`quickAskExample`)),children:i(`quickAskExample`)}),(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>ye(i(`quickAskSummarize`)),children:i(`quickAskSummarize`)})]})]}),(0,$.jsxs)(`div`,{className:`quick-ask-actions`,children:[(0,$.jsx)(sE,{currentConversation:n,disabled:re>0,onReference:e=>void xe(e),onFiles:e=>void Se(e),onFolder:e=>void Ce(e)}),f.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`quick-ask-ask`,"aria-expanded":De,"aria-controls":`quick-ask-composer`,onClick:()=>y(!De),children:[(0,$.jsx)(V,{size:12,"aria-hidden":`true`}),i(De?`quickAskHideInput`:`quickAskAsk`)]}),T&&(0,$.jsxs)(`button`,{type:`button`,className:`quick-ask-stop`,title:i(`quickAskStop`),"aria-label":i(`quickAskStop`),onClick:()=>{ge(),A(!0)},children:[(0,$.jsx)(rt,{size:10,"aria-hidden":`true`}),i(`quickAskStop`)]})]})]}),De&&(0,$.jsx)(`form`,{id:`quick-ask-composer`,className:`quick-ask-composer`,onSubmit:e=>{e.preventDefault(),ye()},children:(0,$.jsxs)(`div`,{className:`quick-ask-input-wrap`,children:[(0,$.jsx)(`textarea`,{ref:le,value:S,onChange:e=>w(e.target.value),placeholder:i(Ee?`quickAskFollowUp`:`quickAskPlaceholder`),"aria-label":i(`quickAskInputLabel`),rows:S.includes(`
|
|
91
|
+
`)?2:1,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==229&&(e.preventDefault(),ye())}}),(0,$.jsx)(`button`,{type:`submit`,className:`quick-ask-send`,disabled:T||re>0||!S.trim(),title:i(`quickAskSend`),"aria-label":i(`quickAskSend`),children:(0,$.jsx)(Ot,{size:14})})]})})]}),o&&b&&(0,$.jsxs)(`div`,{ref:he.panelRef,id:`quick-ask-menu`,className:`quick-ask-menu`,style:he.style,role:`dialog`,"aria-label":i(`quickAskMore`),children:[Te&&(0,$.jsxs)(`div`,{className:`quick-ask-menu-row`,children:[(0,$.jsx)(`span`,{children:i(`copy`)}),(0,$.jsx)(qd,{text:Te.content})]}),(0,$.jsxs)(`div`,{className:`quick-ask-model`,title:we,children:[(0,$.jsx)(Re,{size:11,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:we})]}),(0,$.jsxs)(`div`,{className:`quick-ask-scope`,children:[(0,$.jsx)(l,{size:10,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:i(`quickAskScope`)})]})]})]}),document.body)}function lE({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)(()=>rT(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`?lT(n,e):cT(n,f.current,{id:e,slot:t.slot,...t.align===void 0?{}:{align:t.align},index:t.index});m.current=r,Z({type:`set_settings`,uiLayout:r})};(0,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.preventDefault();let t=h(e.clientX,e.clientY);d.current=t,c(t)},t=()=>g();return window.addEventListener(`pointermove`,e,{passive:!1}),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t)}},[a]),Vt(()=>{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:So(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)(Be,{})})]}),(0,$.jsxs)(`div`,{className:`icon-editor-body`,children:[$w.map(e=>{let t=l.zones[e.slot]??[],n=aT(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?tT.map(n=>y(e.slot,n,e.vertical?nT(i,n):n,oT(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(eT,void 0,null,l.tray)]})]})]})]})}function uE(e,t){let n=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let r=oC(n.current,e);n.current=r.key,r.clear&&t()},[e,t])}var dE=new Map,fE=-1;function pE(e){let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}function mE(e){let t=e.replace(/\\/g,`/`).split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(n).toLowerCase():``}function hE(e,t){fE!==t&&(fE=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=pE(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));dE=n}function gE(e){return dE.get(mE(e))?.[0]??null}async function _E(e){let t=await Tv(e.plugin,fE);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 vE=(0,Q.memo)(function({open:e=!0,currentModelId:t,models:n,modelsLoading:r=!1,providerKeys:i={},providers:a,defaultModel:o,onManageModels:s,onSelect:c,onClose:l,title:u}){let d=W();return(0,Q.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),l())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,l]),e?(0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:1200,display:`flex`,alignItems:`center`,justifyContent:`center`},onClick:e=>{e.target===e.currentTarget&&l()},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:u||d(`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:l,title:`关闭`,children:(0,$.jsx)(Be,{})})})]}),(0,$.jsx)(Zc,{models:n,modelsLoading:r,providerKeys:i,providers:a,defaultModel:o,currentModelId:t,active:e,onEnsureModels:()=>{n.length===0&&!r&&Z({type:`list_models`})},onRefresh:()=>Z({type:`list_models`}),onManageModels:s,onPickModel:e=>{c(e.id,e),l()},isRowActive:e=>Jc(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}),yE=null,bE=new Set;function xE(){for(let e of bE)e()}function SE(e){yE=e,xE()}function CE(){yE=null,xE()}function wE(e){yE&&(Z({type:`rollback_session`,messageId:yE.messageId,conversationId:yE.conversationId,restoreWorkspace:e}),yE=null,xE())}function TE(){return(0,Q.useSyncExternalStore)(e=>(bE.add(e),()=>bE.delete(e)),()=>yE)}function EE(){let e=W(),t=TE(),[r,i]=(0,Q.useState)(!0),a=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{t&&i(!0)},[t]),Vt(()=>{t&&CE()},!!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(),wE(r))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,r]),t?(0,cr.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:CE,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)(ct,{}),e(`rollbackSession`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`cancel`),onClick:CE,children:(0,$.jsx)(Be,{})})]}),(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:r,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:CE,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:()=>wE(r),children:[(0,$.jsx)(n,{}),e(`confirm`)]})]})]})]})}),document.body):null}function DE({approvals:e,activeConversationId:t,mode:n=`all`}){let r=W();return(0,$.jsx)(PT,{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&&Z(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)(OE,{approval:e,onDefer:t},`${e.owner??`local`}:${e.id}`)})}function OE({approval:e,onDefer:t}){let r=W(),{locale:i}=c(),a=Jm(!!e),[o,s]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(Date.now);if((0,Q.useEffect)(()=>{if(!e?.createdAt)return;f(Date.now());let t=setInterval(()=>f(Date.now()),1e3);return()=>clearInterval(t)},[e?.id,e?.createdAt]),(0,Q.useEffect)(()=>{if(e){let t=e.params;s(typeof t==`object`&&t?JSON.stringify(t,null,2):t==null?`{}`:String(t)),u(null)}},[e?.id]),!e)return null;let p=t=>{Z({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`approve`,...t&&t!==`once`?{scope:t}:{}})},m=()=>{Z({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,cr.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:a},children:(0,$.jsxs)(`div`,{className:`tool-info-modal approval-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":r(`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)(ct,{}),r(`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:[`⚡ `,r(`codemodeNestedApprovalBadge`)]}),e.conversationTitle&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:e.conversationTitle}),e.createdAt&&vT(e.createdAt,d)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,style:{marginLeft:`auto`},children:[`⏱ `,vT(e.createdAt,d)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,children:r(`pendingQueueDefer`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:r(`toolApprovalDeny`),onClick:m,children:(0,$.jsx)(Be,{})})]}),(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:r(`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:[r(`toolApprovalRiskAlert`),`:`]}),(0,$.jsx)(`div`,{children:X(i)?e.reason||e.reasonEn:e.reasonEn||e.reason}),e.category&&(0,$.jsxs)(`div`,{style:{marginTop:6,fontSize:12,opacity:.85},children:[r(`toolApprovalCategory`),`:`,X(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:[r(`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:X(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:r(`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:[r(`approvalCommandPreview`),`:`]}),(0,$.jsxs)(`div`,{className:`approval-cmd-preview-box`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:cd(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:r(`toolApprovalParams`)}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim, #9aa1b4)`},children:r(`toolApprovalEditPlaceholder`)})]}),(0,$.jsx)(`textarea`,{rows:8,value:o,onChange:e=>{s(e.target.value),l&&u(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:l?`1px solid var(--red, #ef4444)`:`1px solid var(--border-subtle, rgba(255,255,255,0.1))`,boxSizing:`border-box`,resize:`vertical`}}),l&&(0,$.jsx)(`div`,{style:{color:`var(--red, #ef4444)`,fontSize:12,marginTop:4},children:l})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,justifyContent:`flex-end`,gap:10},children:[e.category&&(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:r(`toolApprovalAllowCategoryHint`),onClick:()=>p(`category`),children:[(0,$.jsx)(Nt,{}),r(`toolApprovalAllowCategory`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:r(`toolApprovalAllowConversationHint`),onClick:()=>p(`all`),children:[(0,$.jsx)(Ge,{}),r(`toolApprovalAllowConversation`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,style:{color:`var(--red, #ef4444)`},onClick:m,children:[(0,$.jsx)(Be,{}),r(`toolApprovalDeny`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>p(),style:{fontWeight:500},children:[(0,$.jsx)(n,{}),r(`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(o):o,u(null),Z({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`edit`,editedParams:n})}catch(e){u(X(i)?`JSON 格式错误:${e.message}`:`JSON parse error: ${e.message}`)}},children:[(0,$.jsx)(ie,{}),r(`toolApprovalEditAndRun`)]})]})]})]})}),document.body)}var kE={pending:`in_progress`,in_progress:`done`,done:`failed`,failed:`pending`};function AE({plan:e}){let t=W(),r=X(Et()),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Kd({duration:2e3}),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(``);if(!e||!e.steps||e.steps.length===0)return null;let m=e.steps,h=m.filter(e=>e.status===`done`).length,g=m.length,_=Math.round(h/g*100),v=m.find(t=>t.id===e.activeStepId)??m.find(e=>e.status===`in_progress`),y=()=>{window.confirm(r?`确定要清空当前任务计划看板吗?`:`Are you sure you want to clear the plan board?`)&&Z({type:`plan_update`,steps:[]})},b=()=>{Z({type:`set_plan_mode`,enabled:!1}),Z({type:`prompt`,text:t(`planImplementRequest`)})},S=()=>{let e=m.map((e,t)=>`${t+1}. ${e.title}${e.description?` (${e.description})`:``}`).join(`
|
|
92
|
+
`);Z({type:`plan_clean_handoff`,steps:m,prompt:`${t(`planCleanHandoffPrompt`)}\n\n${e}`})},T=async()=>{let e=[`# ${t(`planBoardTitle`)} (${h}/${g})`,``,...m.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(`
|
|
93
|
+
`))},E=e=>{l(e.id),d(e.title),p(e.description||``)},D=()=>{l(null),d(``),p(``)},O=e=>{let t=u.trim();if(!t)return;let n={title:t};n.description=f.trim()?f.trim():void 0,Z({type:`plan_step_update`,stepId:e,patch:n}),l(null)},k=e=>{Z({type:`plan_step_delete`,stepId:e})},A=e=>{let t=m.find(t=>t.id===e);t&&Z({type:`plan_step_update`,stepId:e,patch:{status:kE[t.status]}})},j=()=>{let e={id:`step-${Date.now()}`,title:t(`planBoardAddStep`),status:`pending`};Z({type:`plan_step_add`,step:e}),E(e)},N=(e,n)=>{let i=(()=>{switch(e){case`done`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ge,{}),t(`planBoardCompleted`)]});case`in_progress`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Pt,{}),t(`planBoardInProgress`)]});case`failed`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Pe,{}),t(`planBoardFailed`)]});default:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(M,{}),t(`planBoardPending`)]})}})();return(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),A(n)},title:r?`点击切换状态 (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)(ce,{className:`plan-board-icon`}),(0,$.jsx)(`span`,{className:`plan-board-title`,children:t(`planBoardTitle`)}),(0,$.jsxs)(`span`,{className:`plan-board-count ${_===100?`plan-board-count-done`:``}`.trim(),children:[h,`/`,g]}),!i&&v&&(0,$.jsx)(`span`,{className:`plan-board-active`,title:v.title,children:v.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(),b()},children:t(`planImplementBtn`)}),i&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-clean-handoff`,title:t(`planCleanHandoffTip`),onClick:e=>{e.stopPropagation(),S()},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)(n,{style:{color:`var(--green, #22c55e)`}}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`clear`),onClick:e=>{e.stopPropagation(),y()},children:(0,$.jsx)(_t,{})})]}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(i?`collapseSection`:`expandSection`),children:i?(0,$.jsx)(w,{}):(0,$.jsx)(L,{})})]}),i&&(0,$.jsx)(`div`,{className:`plan-board-head-divider`,children:(0,$.jsx)(`div`,{className:`plan-board-head-divider-fill`,style:{width:`${_}%`,backgroundColor:_===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:`${_}%`,backgroundColor:_===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:[m.map((r,i)=>{let a=r.id===e.activeStepId||r.status===`in_progress`;return c===r.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:u,onChange:e=>d(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(),O(r.id)):e.key===`Escape`&&D()}}),(0,$.jsx)(`textarea`,{rows:2,value:f,onChange:e=>p(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(),O(r.id)):e.key===`Escape`&&D()}}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:6,marginTop:2},children:[(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-iconbtn`,onClick:D,title:t(`cancel`),style:{padding:`3px 8px`,fontSize:12},children:[(0,$.jsx)(Be,{}),` `,t(`cancel`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-implement`,onClick:()=>O(r.id),title:t(`confirm`),style:{padding:`3px 10px`,fontSize:12},children:[(0,$.jsx)(n,{}),` `,t(`confirm`)]})]})]},r.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:r.status===`done`?`var(--text-dim, #9aa1b4)`:`var(--text, #f1f5f9)`,textDecoration:r.status===`done`?`line-through`:`none`,minWidth:0,overflowWrap:`anywhere`,wordBreak:`break-word`},children:r.title})]}),r.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:r.description})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,flexShrink:0,marginTop:2},children:[N(r.status,r.id),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardEditStep`),onClick:()=>E(r),children:(0,$.jsx)(J,{size:12})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardDeleteStep`),onClick:()=>k(r.id),children:(0,$.jsx)(_t,{size:12})})]})]},r.id||i)}),(0,$.jsxs)(`button`,{type:`button`,className:`plan-board-add-btn`,onClick:j,children:[(0,$.jsx)(C,{}),` `,t(`planBoardAddStep`)]})]})]})}var jE=3,ME=200;function NE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function PE(e){return typeof e==`string`&&e.trim()||void 0}function FE(e,t){let n=[];for(let r of e){let e=LE(r,t);if(n.includes(e)||n.push(e),n.length>=4){n.push(`…`);break}}return n.join(` | `)||`any`}function IE(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 LE(e,t=0){if(t>6||!NE(e))return`any`;if(PE(e.$ref))return`ref`;let n=PE(e.type);if(n===`array`){let n=e.items;return`array<${n===void 0?`any`:LE(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 FE(r,t+1)}return NE(e.properties)?`object`:NE(e.additionalProperties)?`record<${LE(e.additionalProperties,t+1)}>`:`any`}function RE(e){let t=[],n=e.enum;if(Array.isArray(n)&&n.length>0){let e=IE(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 zE(e,t={}){let n=t.maxDepth??jE,r=t.maxRows??ME,i=e;if(!NE(i))return[];let a=i.properties;if(!NE(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=NE(l)?l:{},u=t?`${t}.${s}`:s,d={name:u,type:LE(e,i),required:a.has(s),depth:i},f=PE(e.description);f&&(d.description=f);let p=RE(e);if(p&&(d.hint=p),o.push(d),i+1<n&&NE(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 BE(){let e=W(),t=Kp();return Vt(()=>{Hp()},!!t),t?(0,cr.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:Hp,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)(xe,{}),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:Hp,children:(0,$.jsx)(Be,{})})]}),(0,$.jsx)(`div`,{className:`tool-info-body`,children:(0,$.jsx)(VE,{info:t})})]})}),document.body):null}function VE({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?[]:zE(e.parameters),r=e.parameters===void 0?``:UE(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)(HE,{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)(qd,{text:r})]}),(0,$.jsx)(`pre`,{children:r})]})]}),(0,$.jsx)(`div`,{className:`tool-info-foot`,children:t(`toolInfoFootnote`)})]})}function HE({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 UE(e){try{return JSON.stringify(e,null,2)??``}catch{return``}}function WE(e,t,n){let r={action:`spawn`};if(e)try{let t=JSON.parse(e);t&&typeof t==`object`&&(typeof t.action==`string`&&(r.action=t.action.trim().toLowerCase()),typeof t.prompt==`string`&&(r.prompt=t.prompt),typeof t.type==`string`&&(r.type=t.type),typeof t.template==`string`&&(r.template=t.template),typeof t.model==`string`&&(r.model=t.model),typeof t.thinking==`string`&&(r.thinking=t.thinking),typeof t.isolation==`string`&&(r.isolation=t.isolation),typeof t.cwd==`string`&&(r.cwd=t.cwd),typeof t.runId==`string`&&(r.runId=t.runId),typeof t.message==`string`&&(r.message=t.message),typeof t.summary==`string`&&(r.summary=t.summary),(typeof t.notifyOnDone==`boolean`||t.notifyOnDone===`manual`)&&(r.notifyOnDone=t.notifyOnDone))}catch{}if(t&&typeof t==`object`){let e=t;if(typeof e.convId==`string`&&(r.convId=e.convId),typeof e.executionId==`string`&&(r.executionId=e.executionId),typeof e.type==`string`&&!r.type&&(r.type=e.type),typeof e.model==`string`&&!r.model&&(r.model=e.model),typeof e.thinkingLevel==`string`&&!r.thinking&&(r.thinking=e.thinkingLevel),typeof e.state==`string`&&(r.state=e.state),typeof e.streaming==`boolean`&&(r.streaming=e.streaming),typeof e.messageCount==`number`&&(r.messageCount=e.messageCount),typeof e.prompt==`string`&&!r.prompt&&(r.prompt=e.prompt),typeof e.output==`string`&&(r.output=e.output),e.worktree&&typeof e.worktree==`object`){let t=e.worktree;r.worktree={branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,uncommittedCount:typeof t.uncommittedCount==`number`?t.uncommittedCount:void 0,aheadCount:typeof t.aheadCount==`number`?t.aheadCount:void 0,isDirty:typeof t.isDirty==`boolean`?t.isDirty:void 0,error:typeof t.error==`string`?t.error:void 0}}Array.isArray(e.requests)&&(r.consultRequests=e.requests)}if(!r.convId){if(r.runId&&/^sa-[0-9a-f]{8}/.test(r.runId))r.convId=r.runId;else if(n){let e=/sa-[0-9a-f]{8}/.exec(n);e&&(r.convId=e[0])}}return r}function GE(e,t=!0){switch((e||``).toLowerCase()){case`review`:return{icon:`⚖️`,label:t?`审查者 (Review)`:`Reviewer`,desc:t?`只读审查代码与架构`:`Read-only audit`};case`implement`:return{icon:`🛠️`,label:t?`实施者 (Implement)`:`Implementer`,desc:t?`编写与重构代码`:`Code modification`};case`explore`:return{icon:`🔍`,label:t?`探索者 (Explore)`:`Explorer`,desc:t?`调查依赖与路径`:`Codebase discovery`};case`test`:return{icon:`🧪`,label:t?`测试者 (Test)`:`Tester`,desc:t?`执行验证套件`:`Test verification`};default:return{icon:`👥`,label:t?`通用助手 (General)`:`General`,desc:t?`通用协同智能体`:`General agent`}}}function KE({args:e,details:t,output:r,duration:i,statusClass:a,isError:o}){let s=X(Et()),c=(0,Q.useMemo)(()=>WE(e,t,r),[e,t,r]),l=Kd({duration:1200}),u=Kd({duration:1200}),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!0),h=c.action===`spawn`,[g,_]=(0,Q.useState)(h?`spawn`:`result`),v=GE(c.type,s),y=c.output||r||``,b=c.convId||(c.runId&&/^sa-[0-9a-f]{8}/.test(c.runId)?c.runId:void 0);return(0,$.jsxs)(`div`,{className:`subagent-inspector-container`,children:[(0,$.jsx)(`style`,{children:`
|
|
94
|
+
.subagent-inspector-container {
|
|
95
|
+
display: flex;
|
|
96
|
+
flex-direction: column;
|
|
97
|
+
gap: 12px;
|
|
98
|
+
padding: 16px;
|
|
99
|
+
width: 100%;
|
|
100
|
+
box-sizing: border-box;
|
|
101
|
+
background: var(--bg);
|
|
102
|
+
color: var(--text);
|
|
103
|
+
font-family: var(--sans);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/* 顶部形态切换条 */
|
|
107
|
+
.subagent-mode-switcher {
|
|
108
|
+
display: flex;
|
|
109
|
+
align-items: center;
|
|
110
|
+
justify-content: space-between;
|
|
111
|
+
background: var(--bg-elev);
|
|
112
|
+
border: 1px solid var(--border);
|
|
113
|
+
border-radius: 8px;
|
|
114
|
+
padding: 6px 12px;
|
|
115
|
+
gap: 12px;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
.subagent-mode-tabs {
|
|
119
|
+
display: flex;
|
|
120
|
+
background: var(--bg-elev2);
|
|
121
|
+
border: 1px solid var(--border-soft);
|
|
122
|
+
border-radius: 6px;
|
|
123
|
+
padding: 2px;
|
|
124
|
+
gap: 2px;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
.subagent-mode-btn {
|
|
128
|
+
background: transparent;
|
|
129
|
+
border: none;
|
|
130
|
+
color: var(--text-dim);
|
|
131
|
+
font-size: 12px;
|
|
132
|
+
font-weight: 500;
|
|
133
|
+
padding: 4px 10px;
|
|
134
|
+
border-radius: 4px;
|
|
135
|
+
cursor: pointer;
|
|
136
|
+
transition: all 0.15s ease;
|
|
137
|
+
white-space: nowrap;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
.subagent-mode-btn:hover {
|
|
141
|
+
color: var(--text);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
.subagent-mode-btn.active {
|
|
145
|
+
background: var(--bg-elev);
|
|
146
|
+
color: var(--accent);
|
|
147
|
+
font-weight: 600;
|
|
148
|
+
box-shadow: 0 1px 3px rgba(0,0,0,0.15);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
.subagent-conv-badge {
|
|
152
|
+
font-family: var(--mono);
|
|
153
|
+
font-size: 11.5px;
|
|
154
|
+
color: var(--text-dim);
|
|
155
|
+
display: flex;
|
|
156
|
+
align-items: center;
|
|
157
|
+
gap: 6px;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
.subagent-conv-badge strong {
|
|
161
|
+
color: var(--accent);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/* HUD 核心指标网格 */
|
|
165
|
+
.subagent-hud-grid {
|
|
166
|
+
display: grid;
|
|
167
|
+
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
|
168
|
+
gap: 10px;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
.subagent-hud-card {
|
|
172
|
+
background: var(--bg-elev);
|
|
173
|
+
border: 1px solid var(--border-soft);
|
|
174
|
+
border-radius: 6px;
|
|
175
|
+
padding: 10px 12px;
|
|
176
|
+
display: flex;
|
|
177
|
+
flex-direction: column;
|
|
178
|
+
gap: 4px;
|
|
179
|
+
position: relative;
|
|
180
|
+
overflow: hidden;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
.subagent-hud-card::before {
|
|
184
|
+
content: "";
|
|
185
|
+
position: absolute;
|
|
186
|
+
top: 0;
|
|
187
|
+
left: 0;
|
|
188
|
+
bottom: 0;
|
|
189
|
+
width: 3px;
|
|
190
|
+
background: var(--border);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
.subagent-hud-card.accent::before { background: var(--accent); }
|
|
194
|
+
.subagent-hud-card.green::before { background: var(--green); }
|
|
195
|
+
.subagent-hud-card.blue::before { background: var(--blue); }
|
|
196
|
+
.subagent-hud-card.amber::before { background: var(--amber); }
|
|
197
|
+
|
|
198
|
+
.subagent-hud-label {
|
|
199
|
+
font-size: 10.5px;
|
|
200
|
+
color: var(--text-faint);
|
|
201
|
+
text-transform: uppercase;
|
|
202
|
+
letter-spacing: 0.5px;
|
|
203
|
+
font-weight: 600;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
.subagent-hud-val {
|
|
207
|
+
font-size: 13px;
|
|
208
|
+
font-weight: 600;
|
|
209
|
+
color: var(--text);
|
|
210
|
+
display: flex;
|
|
211
|
+
align-items: center;
|
|
212
|
+
gap: 6px;
|
|
213
|
+
white-space: nowrap;
|
|
214
|
+
overflow: hidden;
|
|
215
|
+
text-overflow: ellipsis;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
.subagent-hud-sub {
|
|
219
|
+
font-size: 11px;
|
|
220
|
+
color: var(--text-dim);
|
|
221
|
+
font-family: var(--mono);
|
|
222
|
+
white-space: nowrap;
|
|
223
|
+
overflow: hidden;
|
|
224
|
+
text-overflow: ellipsis;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/* 结构化卡片共通 */
|
|
228
|
+
.subagent-section-card {
|
|
229
|
+
background: var(--bg-elev);
|
|
230
|
+
border: 1px solid var(--border);
|
|
231
|
+
border-radius: 8px;
|
|
232
|
+
overflow: hidden;
|
|
233
|
+
display: flex;
|
|
234
|
+
flex-direction: column;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
.subagent-section-header {
|
|
238
|
+
background: var(--bg-elev2);
|
|
239
|
+
border-bottom: 1px solid var(--border-soft);
|
|
240
|
+
padding: 8px 12px;
|
|
241
|
+
display: flex;
|
|
242
|
+
align-items: center;
|
|
243
|
+
justify-content: space-between;
|
|
244
|
+
gap: 8px;
|
|
245
|
+
font-size: 12.5px;
|
|
246
|
+
font-weight: 600;
|
|
247
|
+
color: var(--text);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
.subagent-section-header.clickable {
|
|
251
|
+
cursor: pointer;
|
|
252
|
+
user-select: none;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
.subagent-section-header.clickable:hover {
|
|
256
|
+
background: var(--bg-elev);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
.subagent-section-title {
|
|
260
|
+
display: flex;
|
|
261
|
+
align-items: center;
|
|
262
|
+
gap: 6px;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
.subagent-section-body {
|
|
266
|
+
padding: 12px;
|
|
267
|
+
display: flex;
|
|
268
|
+
flex-direction: column;
|
|
269
|
+
gap: 8px;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
.subagent-prompt-box {
|
|
273
|
+
font-size: 13px;
|
|
274
|
+
line-height: 1.6;
|
|
275
|
+
color: var(--text);
|
|
276
|
+
background: var(--bg);
|
|
277
|
+
border: 1px solid var(--border-soft);
|
|
278
|
+
border-radius: 6px;
|
|
279
|
+
padding: 10px 12px;
|
|
280
|
+
white-space: pre-wrap;
|
|
281
|
+
word-break: break-word;
|
|
282
|
+
max-height: 320px;
|
|
283
|
+
overflow-y: auto;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
.subagent-output-box {
|
|
287
|
+
font-size: 12.5px;
|
|
288
|
+
line-height: 1.6;
|
|
289
|
+
color: var(--text);
|
|
290
|
+
background: var(--bg);
|
|
291
|
+
border: 1px solid var(--border-soft);
|
|
292
|
+
border-radius: 6px;
|
|
293
|
+
padding: 12px;
|
|
294
|
+
white-space: pre-wrap;
|
|
295
|
+
word-break: break-word;
|
|
296
|
+
font-family: var(--mono);
|
|
297
|
+
max-height: 380px;
|
|
298
|
+
overflow-y: auto;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/* 环境与参数清单表格 */
|
|
302
|
+
.subagent-spec-table {
|
|
303
|
+
width: 100%;
|
|
304
|
+
border-collapse: collapse;
|
|
305
|
+
font-size: 12px;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
.subagent-spec-table tr {
|
|
309
|
+
border-bottom: 1px solid var(--border-soft);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
.subagent-spec-table tr:last-child {
|
|
313
|
+
border-bottom: none;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
.subagent-spec-table td {
|
|
317
|
+
padding: 6px 8px;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
.subagent-spec-table td.label {
|
|
321
|
+
width: 120px;
|
|
322
|
+
color: var(--text-faint);
|
|
323
|
+
font-weight: 500;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
.subagent-spec-table td.val {
|
|
327
|
+
color: var(--text);
|
|
328
|
+
font-family: var(--mono);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/* 底部快捷操作条 */
|
|
332
|
+
.subagent-action-dock {
|
|
333
|
+
display: flex;
|
|
334
|
+
align-items: center;
|
|
335
|
+
justify-content: space-between;
|
|
336
|
+
gap: 12px;
|
|
337
|
+
background: var(--bg-elev);
|
|
338
|
+
border: 1px solid var(--border);
|
|
339
|
+
border-radius: 8px;
|
|
340
|
+
padding: 10px 14px;
|
|
341
|
+
flex-wrap: wrap;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
.subagent-dock-tip {
|
|
345
|
+
font-size: 12px;
|
|
346
|
+
color: var(--text-dim);
|
|
347
|
+
display: flex;
|
|
348
|
+
align-items: center;
|
|
349
|
+
gap: 6px;
|
|
350
|
+
flex: 1;
|
|
351
|
+
min-width: 220px;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
.subagent-dock-btns {
|
|
355
|
+
display: flex;
|
|
356
|
+
align-items: center;
|
|
357
|
+
gap: 8px;
|
|
358
|
+
flex-wrap: wrap;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
.subagent-btn {
|
|
362
|
+
background: var(--bg-elev2);
|
|
363
|
+
border: 1px solid var(--border);
|
|
364
|
+
color: var(--text);
|
|
365
|
+
font-size: 12px;
|
|
366
|
+
font-weight: 500;
|
|
367
|
+
padding: 5px 10px;
|
|
368
|
+
border-radius: 6px;
|
|
369
|
+
cursor: pointer;
|
|
370
|
+
display: inline-flex;
|
|
371
|
+
align-items: center;
|
|
372
|
+
gap: 6px;
|
|
373
|
+
transition: all 0.15s;
|
|
374
|
+
white-space: nowrap;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
.subagent-btn:hover {
|
|
378
|
+
border-color: var(--text-faint);
|
|
379
|
+
color: var(--text);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
.subagent-btn.primary {
|
|
383
|
+
background: var(--accent);
|
|
384
|
+
border-color: var(--accent);
|
|
385
|
+
color: var(--accent-contrast);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
.subagent-btn.primary:hover {
|
|
389
|
+
opacity: 0.92;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
.subagent-btn.copied {
|
|
393
|
+
color: var(--green);
|
|
394
|
+
border-color: var(--green);
|
|
395
|
+
}
|
|
396
|
+
`}),(0,$.jsxs)(`div`,{className:`subagent-mode-switcher`,children:[(0,$.jsxs)(`div`,{className:`subagent-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`subagent-mode-btn${g===`spawn`?` active`:``}`,onClick:()=>_(`spawn`),children:[`🚀 `,s?`任务使命与指派 (Prompt)`:`Mission & Prompt`]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-mode-btn${g===`result`?` active`:``}`,onClick:()=>_(`result`),children:[`📋 `,s?`交付成果与产出 (Result)`:`Deliverables & Output`]})]}),(0,$.jsxs)(`div`,{className:`subagent-conv-badge`,children:[(0,$.jsxs)(`span`,{children:[s?`子代理`:`Subagent`,`:`]}),(0,$.jsx)(`strong`,{children:b||(s?`未绑定`:`unbound`)})]})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-grid`,children:[(0,$.jsxs)(`div`,{className:`subagent-hud-card accent`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:s?`角色与类型`:`Role & Type`}),(0,$.jsxs)(`span`,{className:`subagent-hud-val`,children:[(0,$.jsx)(`span`,{children:v.icon}),(0,$.jsx)(`span`,{children:c.type||`general`})]}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:c.template?`模板: ${c.template}`:v.desc})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card green`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:s?`执行模型`:`Model & Thinking`}),(0,$.jsx)(`span`,{className:`subagent-hud-val`,children:c.model||(s?`跟随宿主`:`inherit host`)}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:c.thinking?`${s?`思考`:`thinking`}: ${c.thinking}`:s?`标准思考档位`:`default`})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card blue`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:s?`隔离工作区`:`Isolation`}),(0,$.jsxs)(`span`,{className:`subagent-hud-val`,children:[(0,$.jsx)(ke,{}),(0,$.jsx)(`span`,{children:c.worktree?.branch?c.worktree.branch.replace(/^agent\//,``):c.isolation===`worktree`?s?`独立分支隔离`:`worktree`:s?`共享主工作区`:`shared workspace`})]}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:c.worktree?.uncommittedCount===void 0?c.isolation===`worktree`?s?`Git Worktree 物理隔离`:`Dedicated worktree`:s?`无分支隔离`:`No git branch`:`${s?`变更文件`:`files`}: ${c.worktree.uncommittedCount}`})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card amber`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:s?`运行指标`:`Metrics`}),(0,$.jsx)(`span`,{className:`subagent-hud-val`,children:a===`run`?s?`⟳ 执行中...`:`Running...`:i||(s?`已完成`:`Completed`)}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:c.messageCount===void 0?`action: ${c.action}`:`${s?`交互`:`turns`}: ${c.messageCount} ${s?`轮`:``}`})]})]}),g===`spawn`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header`,children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(Re,{style:{color:`var(--accent)`}}),(0,$.jsx)(`span`,{children:s?`🎯 指派任务使命 (Mission Prompt)`:`Mission Prompt`})]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn${l.copied?` copied`:``}`,onClick:()=>void l.copy(c.prompt||``),children:[l.copied?(0,$.jsx)(n,{}):(0,$.jsx)(x,{}),(0,$.jsx)(`span`,{children:l.copied?s?`已复制`:`Copied`:s?`复制指令`:`Copy`})]})]}),(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-prompt-box`,children:c.prompt||(s?`(无明确 prompt,或通过 steer/消息派发)`:`(No explicit prompt)`)})})]}),(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header clickable`,onClick:()=>f(e=>!e),children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(Nt,{style:{color:`var(--blue)`}}),(0,$.jsx)(`span`,{children:s?`🛡️ 运行环境与调度配置`:`Runtime Environment & Config`})]}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim)`},children:d?s?`收起 ▲`:`Collapse ▲`:s?`展开 ▼`:`Expand ▼`})]}),d&&(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`table`,{className:`subagent-spec-table`,children:(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:s?`工作目录`:`CWD`}),(0,$.jsx)(`td`,{className:`val`,children:c.cwd||`(继承主项目路径)`})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:s?`隔离策略`:`Isolation`}),(0,$.jsx)(`td`,{className:`val`,children:c.isolation===`worktree`?s?`🌿 Git Worktree 独立分支隔离`:`Git Worktree isolation`:s?`共享主工作区`:`Shared workspace`})]}),c.worktree?.path&&(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:s?`工作树路径`:`Worktree Path`}),(0,$.jsx)(`td`,{className:`val`,children:c.worktree.path})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:s?`自动唤醒`:`Notify Strategy`}),(0,$.jsx)(`td`,{className:`val`,children:c.notifyOnDone===!1?s?`已禁用自动通知 (静默)`:`Disabled`:s?`终态自动通知唤醒父级 (notifyOnDone: true)`:`Auto-notify on complete`})]})]})})})]})]}),g===`result`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header`,children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(Ce,{style:{color:`var(--green)`}}),(0,$.jsx)(`span`,{children:s?`📋 任务执行交付报告 (Deliverables)`:`Deliverables`})]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn${u.copied?` copied`:``}`,onClick:()=>void u.copy(y),children:[u.copied?(0,$.jsx)(n,{}):(0,$.jsx)(x,{}),(0,$.jsx)(`span`,{children:u.copied?s?`已复制`:`Copied`:s?`复制产出`:`Copy`})]})]}),(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-output-box`,children:y||(a===`run`?s?`⟳ 子代理正在后台执行并流式生成结果中...`:`Running and generating output...`:s?`(暂无产出文本)`:`(No output yet)`)})})]}),c.prompt&&(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header clickable`,onClick:()=>m(e=>!e),children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(Re,{style:{color:`var(--text-dim)`}}),(0,$.jsx)(`span`,{children:s?`🎯 关联指派 Prompt`:`Associated Prompt`})]}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim)`},children:p?s?`收起 ▲`:`Collapse ▲`:s?`展开 ▼`:`Expand ▼`})]}),p&&(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-prompt-box`,style:{maxHeight:180},children:c.prompt})})]})]}),(0,$.jsxs)(`div`,{className:`subagent-action-dock`,children:[(0,$.jsxs)(`div`,{className:`subagent-dock-tip`,children:[(0,$.jsx)(`span`,{children:`💡`}),(0,$.jsx)(`span`,{children:b?s?`可直接切换至子代理会话查看完整上下文交互与各轮工具调用。`:`Switch to this subagent conversation to view full chat history.`:s?`子代理未绑定有效会话 ID。`:`Subagent ID not resolved.`})]}),(0,$.jsx)(`div`,{className:`subagent-dock-btns`,children:b&&(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn primary`,onClick:()=>{b&&(Af(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:b})))},children:[(0,$.jsx)(lt,{}),(0,$.jsx)(`span`,{children:s?`切换到该子会话 ➔`:`Switch to Conversation ➔`})]})})]})]})}function qE({state:e}){let t=W(),n=e.startTimestamp??(e.resultTimestamp!==void 0&&e.durationMs!==void 0?e.resultTimestamp-e.durationMs:void 0),r=e.endTimestamp??e.resultTimestamp,i=e.durationMs,a=``;if(n!==void 0&&r!==void 0&&i!==void 0)try{a=t(`toolTimeRange`,{start:Dp(n),end:Dp(r),duration:Tp(i)})}catch{a=``}else r===void 0?n!==void 0&&(a=Dp(n)):a=Dp(r);return a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`inspector-time`,title:a,children:a}),(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`})]}):null}var JE={bash:(0,$.jsx)(Ce,{}),skill:(0,$.jsx)(p,{}),read:(0,$.jsx)(Y,{}),write:(0,$.jsx)(ie,{}),edit:(0,$.jsx)(J,{}),grep:(0,$.jsx)(ft,{}),find:(0,$.jsx)(de,{}),codemode:(0,$.jsx)(Re,{}),eval:(0,$.jsx)(a,{}),lsp:(0,$.jsx)(a,{}),tool_search:(0,$.jsx)(ft,{}),conversation:(0,$.jsx)(lt,{}),delegate_task:(0,$.jsx)(Nt,{}),present_files:(0,$.jsx)(oe,{}),browser_search:(0,$.jsx)(ft,{}),browser_use:(0,$.jsx)(Ct,{}),ask_user_question:(0,$.jsx)(ut,{}),conversation_read:(0,$.jsx)(Ye,{})};function YE(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 XE(){let e=Ff();return!e||typeof document>`u`?null:(0,$.jsx)(ZE,{state:e})}function ZE({state:e}){let t=Jm();return(0,cr.createPortal)((0,$.jsx)(`div`,{className:`overlay-layer`,style:{zIndex:t},children:(0,$.jsx)(QE,{state:e})}),document.body)}function QE({state:e}){let[t,n]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),Af())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let r=()=>n(e=>!e);if(e.isThinking)return(0,$.jsx)($E,{state:e,isMaximized:t,onToggleMaximize:r});let i=e.name||``;return i===`edit`||i===`write`||i===`patch`?(0,$.jsx)(nD,{state:e,isMaximized:t,onToggleMaximize:r}):i===`bash`?(0,$.jsx)(eD,{state:e,isMaximized:t,onToggleMaximize:r}):i===`read`||i===`ls`||i===`grep`||i===`find`||i===`tool_search`?(0,$.jsx)(tD,{state:e,isMaximized:t,onToggleMaximize:r}):(0,$.jsx)(rD,{state:e,isMaximized:t,onToggleMaximize:r})}function $E({state:e,isMaximized:t,onToggleMaximize:r}){let i=W(),{copy:a,copied:o}=Kd({duration:1200}),s=e.thinking||e.output||``,c=s.length,l=s?s.split(`
|
|
397
|
+
`).length:0,u=(0,Q.useRef)(null),d=(0,Q.useRef)(!0);return(0,Q.useEffect)(()=>{d.current=!0},[e.toolCallId]),(0,Q.useEffect)(()=>{if(!e.streaming)return;let t=u.current;t&&d.current&&(t.scrollTop=t.scrollHeight)},[s,e.streaming]),(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Af()},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:r,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(k,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,children:i(`toolInspectorThinkingSection`).replace(/^💭\s*/,``)}),(0,$.jsx)(`span`,{className:`file-diff-lang`,children:i(`toolInspectorStats`,{chars:c,lines:l})}),(0,$.jsx)(`span`,{className:`file-diff-status-pill ${e.streaming?`run`:`ok`}`,children:e.streaming?i(`toolInspectorThinkingStatusRunning`):i(`toolInspectorThinkingStatusDone`)})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${o?` copied`:``}`,title:i(o?`toolInspectorCopied`:`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),a(s)},children:o?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),r()},children:t?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${i(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Af()},children:(0,$.jsx)(Be,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,ref:u,onWheel:e=>{if(e.deltaY<0)d.current=!1;else if(e.deltaY>0&&u.current){let e=u.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(d.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(d.current=!0)},children:(0,$.jsx)(`div`,{className:`thinking-inspector-content`,children:s?(0,$.jsxs)(`div`,{className:`markdown thinking-markdown`,children:[(0,$.jsx)(rp,{text:s}),e.streaming&&(0,$.jsx)(`span`,{className:`stream-cursor`})]}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:i(`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?i(`toolInspectorThinkingFooterRunning`):i(`toolInspectorThinkingFooterLines`,{lines:l})})]}),(0,$.jsx)(`div`,{className:`file-diff-footer-meta`,children:(0,$.jsx)(qE,{state:e})})]})]})})}function eD({state:e,isMaximized:t,onToggleMaximize:r}){let i=W(),o=X(Et()),[s,c]=(0,Q.useState)(`preview`),l=Kd({duration:1200}),u=Kd({duration:1200}),{args:d=``,output:f=``,details:p,isError:h=!1,status:g,duration:_,exitHint:v}=e,y=(e.hints||_s(d)).command||(d&&!d.startsWith(`{`)?d:``),b=(0,Q.useMemo)(()=>{if(!p||typeof p!=`object`)return``;try{return JSON.stringify(p,null,2)}catch{return``}},[p]),S=YE(e,i,o),C=f?f.split(`
|
|
398
|
+
`).length:0,w=p&&typeof p==`object`?Object.keys(p).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Af()},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:r,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(Ce,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:y||`bash`,children:y?`$ ${y}`:`bash`}),v&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:v}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${S.badgeClass}`,children:[S.statusIcon,` `,S.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[S.isRunning&&e.onKillBash&&(0,$.jsxs)(`button`,{type:`button`,className:`file-diff-action-btn kill-btn`,title:o?`结束此 bash 命令 (Stop)`:`Stop bash command`,onClick:t=>{t.stopPropagation(),e.onKillBash?.()},children:[(0,$.jsx)(rt,{}),(0,$.jsx)(`span`,{className:`kill-btn-label`,children:o?`结束`:`Stop`})]}),(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(),c(`preview`)},children:o?`终端输出`:`Terminal`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`raw`)},children:i(`diffViewRaw`)})]}),y&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${l.copied?` copied`:``}`,title:l.copied?i(`toolInspectorCopied`):i(`toolInspectorCopyArgs`),onClick:e=>{e.stopPropagation(),l.copy(y)},children:l.copied?(0,$.jsx)(n,{}):(0,$.jsx)(a,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${u.copied?` copied`:``}`,title:u.copied?i(`toolInspectorCopied`):i(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),u.copy(f)},children:u.copied?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),r()},children:t?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${i(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Af()},children:(0,$.jsx)(Be,{})})]})]}),(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:[`⚡ `,i(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:d||`(无入参参数 / No arguments)`})]}),b&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,i(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[w,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:b})]})]}):(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(ha({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:o?`结束此 bash 命令`:`Stop bash command`,icon:`■`,kind:`action`,order:-1,when:S.isRunning?void 0:[`disabled`]})),y&&r.push(ha({id:`host:copy-command`,slot:`contextmenu.toolcall`,label:o?`复制执行命令`:`Copy command`,icon:`copy`,kind:`action`,order:1})),f&&r.push(ha({id:`host:copy-output`,slot:`contextmenu.toolcall`,label:o?`复制终端输出`:`Copy output`,icon:`copy`,kind:`action`,order:2})),r.push(ha({id:`host:tool-info`,slot:`contextmenu.toolcall`,label:o?`工具详细信息`:`Tool Details`,icon:`info`,kind:`action`,order:3})),za({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`){l.copy(y);return}if(t.id===`host:copy-output`){u.copy(f);return}if(t.id===`host:tool-info`){Vp(`bash`);return}}})},children:[y&&(0,$.jsx)(bh,{command:y}),(0,$.jsx)(`pre`,{className:`bash-output-pre`,children:f||(e.statusClass===`run`?i(`toolInspectorRunningOutput`):i(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${S.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${S.isRunning?` spin`:``}`,children:S.statusIcon}),(0,$.jsxs)(`span`,{className:`file-diff-status-text`,children:[S.footerText,` · `,i(`toolInspectorOutputStats`,{lines:C,chars:f.length})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(qE,{state:e}),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(),c(s===`raw`?`preview`:`raw`)},children:s===`raw`?o?`返回终端输出`:`Back to terminal`:o?`查看完整日志与详情`:`View raw & details`})]})]})]})})}function tD({state:e,isMaximized:t,onToggleMaximize:r}){let i=W(),a=X(Et()),[o,s]=(0,Q.useState)(`preview`),c=Kd({duration:1200}),{name:l=`read`,args:u=``,output:d=``,details:f,isError:p=!1,status:h,duration:g,images:_}=e,v=e.hints||_s(u),y=v.path||``,b=v.query||``,S=b?y?`${b} (${y})`:b:y||l,C=(0,Q.useMemo)(()=>{if(_&&_.length>0)return!0;if(y){let e=y.split(`.`).pop()?.toLowerCase();return e&&[`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`,`bmp`].includes(e)}return!1},[_,y]),w=(0,Q.useMemo)(()=>{if(!u)return 1;try{let e=JSON.parse(u);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(u);if(e){let t=parseInt(e[1],10);if(t>0)return t}}return 1},[u]),T=(0,Q.useMemo)(()=>{if(!f||typeof f!=`object`)return``;try{return JSON.stringify(f,null,2)}catch{return``}},[f]),E=YE(e,i,a),D=d?d.split(`
|
|
399
|
+
`).length:0,O=f&&typeof f==`object`?Object.keys(f).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Af()},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:r,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:JE[l]??(0,$.jsx)(Y,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:S,children:S}),b&&(0,$.jsx)(`span`,{className:`file-diff-pattern`,title:a?`搜索表达式: ${b}`:`Pattern: ${b}`,children:l===`grep`?`REGEX`:`QUERY`}),y&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:y.split(`.`).pop()?.toUpperCase()||`FILE`}),w>1&&(0,$.jsxs)(`span`,{className:`file-diff-lang`,title:a?`起始偏移量: 第 ${w} 行`:`Start offset: line ${w}`,children:[`L`,w,`~L`,w+D-1]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${E.badgeClass}`,children:[E.statusIcon,` `,E.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${o===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`preview`)},children:a?`内容查看`:`Content`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:i(`diffViewRaw`)})]}),y&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!y)return;let t=y.split(`/`).pop()||y;Hf({path:y,name:t})},children:(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${c.copied?` copied`:``}`,title:c.copied?i(`toolInspectorCopied`):i(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),c.copy(d)},children:c.copied?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),r()},children:t?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${i(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Af()},children:(0,$.jsx)(Be,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:o===`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:[`⚡ `,i(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:u||`(无入参参数 / No arguments)`})]}),T&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,i(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[O,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:T})]})]}):(0,$.jsxs)(`div`,{className:`read-inspector-viewport`,children:[l===`tool_search`&&(0,$.jsx)(xh,{details:f}),C&&_&&_.length>0?(0,$.jsxs)(`div`,{className:`read-image-viewport`,children:[_.map((e,t)=>{let n=e.startsWith(`/`)?ne(e):e;return(0,$.jsx)(`div`,{className:`read-image-container`,children:(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,title:i(`toolImageZoom`),onClick:()=>pn({src:n,alt:y||`Image ${t+1}`}),children:(0,$.jsx)(`img`,{crossOrigin:R(n),src:n,alt:y||`Image ${t+1}`,className:`read-image-item`})})},t)}),d&&(0,$.jsx)(`div`,{className:`read-image-caption`,children:d})]}):d?(0,$.jsx)(ah,{content:d,startLine:w}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:e.statusClass===`run`?i(`toolInspectorRunningOutput`):i(`toolInspectorEmptyOutput`)})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${E.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${E.isRunning?` spin`:``}`,children:E.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:E.isRunning?E.footerText:i(`toolInspectorStats`,{chars:d.length,lines:D})})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(qE,{state:e}),O>0&&(0,$.jsxs)(`span`,{children:[`details: `,O,` keys`]}),O>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(o===`raw`?`preview`:`raw`)},children:o===`raw`?a?`返回内容`:`Back to content`:a?`查看完整参数`:`View raw`})]})]})]})})}function nD({state:e,isMaximized:t,onToggleMaximize:r}){let i=W(),a=X(Et()),[o,s]=(0,Q.useState)(`unified`),{copied:c,copy:l}=Kd({duration:1200}),{name:u=`edit`,args:d=``,details:f,output:p=``,isError:h=!1,status:g,duration:_}=e,v=u===`edit`||u===`patch`,y=(0,Q.useMemo)(()=>rh(u,d,f,p),[u,d,f,p]),b=f&&typeof f==`object`?Object.keys(f).length:0,S=(0,Q.useMemo)(()=>{if(!f||typeof f!=`object`)return``;try{return JSON.stringify(f,null,2)}catch{return``}},[f]),C=YE(e,i,a);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Af()},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:r,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(Y,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:y?.filePath||u,children:y?.filePath||u}),y?.language&&y.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:y.language}),y?.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:i(`diffNewFile`)}):y?.stats.additions!==void 0&&(y.stats.additions>0||y.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[y.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,y.stats.additions]}),y.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,y.stats.deletions]})]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${C.badgeClass}`,children:[C.statusIcon,` `,C.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${o===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`unified`)},children:i(`diffViewUnified`)}),!y?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`split`)},children:i(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:i(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${c?` copied`:``}`,title:y?.isWrite?i(`diffCopyContent`):i(`diffCopyPatch`),"aria-label":y?.isWrite?i(`diffCopyContent`):i(`diffCopyPatch`),onClick:e=>{e.stopPropagation(),y?.isWrite&&y.content?l(y.content):d&&l(d)},children:c?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),y?.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(`diffOpenFile`),"aria-label":i(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!y?.filePath)return;let t=y.filePath.split(`/`).pop()||y.filePath;Hf({path:y.filePath,name:t})},children:(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(t?`diffRestoreScreen`:`diffFullscreen`),"aria-label":i(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),r()},children:t?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${i(`close`)} (ESC)`,"aria-label":i(`close`),onClick:e=>{e.stopPropagation(),Af()},children:(0,$.jsx)(Be,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:o===`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:[`⚡ `,i(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:d||`(无入参参数 / 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:[`⚙ `,i(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[b,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:S})]})]}):y?.isWrite?(0,$.jsx)(ah,{content:y.content||``}):o===`split`?(0,$.jsx)(ch,{hunks:y?.hunks||[],isStreaming:y?.isStreamingPartial,fallbackText:d}):(0,$.jsx)(oh,{hunks:y?.hunks||[],isStreaming:y?.isStreamingPartial,fallbackText:d})}),(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:p||(v?a?`补丁已应用`:`Patch applied`:a?`文件已写入`:`File written`)})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(qE,{state:e}),b>0&&(0,$.jsxs)(`span`,{children:[`details: `,b,` keys`]}),b>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(o===`raw`?`unified`:`raw`)},children:o===`raw`?a?`返回差异对比`:`Back to diff`:a?`查看完整日志`:`View raw logs`})]})]})]})})}function rD({state:e,isMaximized:t,onToggleMaximize:r}){let i=W(),a=X(Et()),[o,s]=(0,Q.useState)(`preview`),c=Kd({duration:1200}),{name:l=`tool`,args:u=``,details:d,output:f=``,isError:p=!1,status:h,duration:g,images:_}=e,v=gs({name:l,argumentsText:u,hints:e.hints||_s(u)}),y=v?`${l}(${v.text})`:l?`${l}()`:i(`toolInspectorTitle`),b=(0,Q.useMemo)(()=>{if(!d||typeof d!=`object`)return``;try{return JSON.stringify(d,null,2)}catch{return``}},[d]),S=YE(e,i,a),C=d&&typeof d==`object`?Object.keys(d).length:0,w=l===`present_files`,T=(0,Q.useMemo)(()=>w&&u?Qp(u):null,[w,u]),E=l===`delegate_task`,D=(0,Q.useMemo)(()=>E&&u?xs(u):{},[E,u]),O=l===`codemode`,k=(0,Q.useMemo)(()=>O&&u?Os(u):null,[O,u]),A=l===`ask_user_question`,j=(0,Q.useMemo)(()=>A&&u?Ms(u):null,[A,u]),M=l===`conversation`,N=!!(w&&T||E&&Object.keys(D).length>0||O&&k?.code||A&&j||M);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&Af()},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:r,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:JE[l]??(0,$.jsx)(oe,{})}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:y,children:y}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${S.badgeClass}`,children:[S.statusIcon,` `,S.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${o===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`preview`)},children:a?`视图`:`View`}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:i(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${c.copied?` copied`:``}`,title:c.copied?i(`toolInspectorCopied`):i(`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),c.copy(`[Arguments]\n${u}\n\n[Output]\n${f}`)},children:c.copied?(0,$.jsx)(n,{}):(0,$.jsx)(x,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:i(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),r()},children:t?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${i(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),Af()},children:(0,$.jsx)(Be,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:o===`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:[`⚡ `,i(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:u||`(无入参参数 / No arguments)`})]}),b&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,i(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[C,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:b})]})]}):(0,$.jsxs)(`div`,{className:`generic-inspector-viewport`,children:[w&&T&&(0,$.jsx)(Pm,{args:T,details:d,toolCallId:e.toolCallId??``,resultTimestamp:e.resultTimestamp}),E&&(0,$.jsx)(Sh,{args:D}),O&&k?.code&&(0,$.jsx)(Ch,{code:k.code,options:k.options,details:d,output:f}),A&&j&&(0,$.jsx)(zm,{questions:j.questions,details:d,output:f,isError:p,waiting:e.statusClass===`run`}),M&&(0,$.jsx)(KE,{name:l,args:u,details:d,output:f,duration:g,statusClass:e.statusClass,isError:p}),_&&_.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:[i(`toolInspectorImages`),` (`,_.length,`)`]})}),(0,$.jsx)(`div`,{className:`tool-inspector-images`,children:_.map((e,t)=>{let n=e.startsWith(`/`)?ne(e):e;return(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,title:i(`toolImageZoom`),onClick:()=>pn({src:n,alt:`output image ${t+1}`}),children:(0,$.jsx)(`img`,{crossOrigin:R(n),src:n,alt:`output image ${t+1}`,loading:`lazy`})},t)})})]}),!N&&(0,$.jsx)(`pre`,{className:`generic-output-pre`,children:f||(e.statusClass===`run`?i(`toolInspectorRunningOutput`):i(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${S.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${S.isRunning?` spin`:``}`,children:S.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:S.isRunning?S.footerText:f?i(`toolInspectorOutputStats`,{lines:f.split(`
|
|
400
|
+
`).length,chars:f.length}):S.footerText})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(qE,{state:e}),C>0&&(0,$.jsxs)(`span`,{children:[`details: `,C,` keys`]}),C>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(o===`raw`?`preview`:`raw`)},children:o===`raw`?a?`返回视图`:`Back to view`:a?`查看完整参数与详情`:`View raw & details`})]})]})]})})}function iD({entry:e,pluginView:t,onUiAction:n,onClose:r}){let i=W(),a=e.label||e.id,o=e.kind===`view`;return(0,$.jsx)(Do,{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)(IT,{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 aD({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 oD({file:e,plugin:t,declaration:n,epoch:r,send:i,onClose:a,onFallback:s}){let c=W(),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),m=(0,Q.useRef)(s);m.current=s;let h=n.label??t.name;(0,Q.useEffect)(()=>{let r=l.current;if(!r)return;let a=!1,s;return d(null),p(!1),(async()=>{try{let c=await _E({plugin:t,declaration:n});if(a)return;if(!c)throw Error(`插件没有提供可用的文件查看器`);let l=`/plugins-api/${encodeURIComponent(t.id)}`,u={...kv(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`,yy());let i=r.toString();return o(g(`${l}${n}${i?`?${i}`:``}`))}};s=c.handler.mount(r,e,u),a||p(!0)}catch(e){a||(console.error(`[plugin:${t.id}] file handler failed:`,e),m.current())}})(),()=>{if(a=!0,typeof s==`function`)try{s()}catch(e){console.error(`[plugin:${t.id}] file handler cleanup failed:`,e)}r.textContent=``}},[e,t,n,r,i]);let _=(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)(Do,{className:`plugin-file-preview`,title:_,icon:t.icon,allowFullscreen:!0,onClose:a,children:(0,$.jsxs)(`div`,{className:`modal-body plugin-file-preview-body`,children:[u?(0,$.jsx)(`div`,{className:`plugin-file-preview-error`,children:u}):null,!u&&!f?(0,$.jsx)(`div`,{className:`plugin-file-preview-loading`,children:c(`loading`)}):null,(0,$.jsx)(`div`,{ref:l,className:`plugin-file-preview-host`})]})})}var sD=.4,cD=1.05;function lD(e){return Math.min(300,e*.86)}function uD(e,t,n){return n||(t<=144?null:e<=72?`left`:t-e<=72?`right`:null)}function dD(e,t){let n=Math.abs(e),r=Math.abs(t);return n<12&&r<12?`none`:n>r*1.2?`horizontal`:`vertical`}function fD(e,t){return e===`left`?t:-t}function pD(e,t){return Math.max(-e,Math.min(0,-e+t))}function mD(e,t,n){let r=n?e+t:t;return Math.max(0,Math.min(1,r/e))}function hD(e){let{wasOpen:t,pull:n,width:r,durationMs:i}=e;return i<=320&&Math.abs(n)>=48?n>0:mD(r*cD,n,t)>=sD}var gD=new Set([`auto`,`scroll`,`overlay`]);function _D(e,t){let n=e instanceof Element?e:null;for(;n;){if(n instanceof HTMLElement&&n.scrollWidth>n.clientWidth+4&&gD.has(getComputedStyle(n).overflowX))return!0;if(n===t)break;n=n.parentElement}return!1}function vD(){let e=e=>{e.stopPropagation(),e.preventDefault()};window.addEventListener(`click`,e,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,e,{capture:!0}),400)}function yD(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=uD(r.clientX,window.innerWidth,n);i&&!_D(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=dD(d,v);if(t===`none`)return;if(t===`vertical`){s=null;return}c=`horizontal`,p=n===r,m=lD(window.innerWidth),h=m*cD;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=fD(r,d);let b=pD(h,f);y.style.transform=`translateX(${r===`left`?b:-b}px)`,_&&(_.style.opacity=String(mD(h,f,p))),t.preventDefault()},x=()=>{let e=s,t=c===`horizontal`&&e!==null&&g!==null,i=f,a=Date.now()-d,o=t?hD({wasOpen:p,pull:i,width:m,durationMs:a}):!1;v(),t&&e&&o!==(n===e)&&(vD(),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 bD={revision:0},xD=new Set;function SD(e){bD={...e,revision:bD.revision+1};for(let e of xD)e()}var CD={zh:[`继续`,`上传发布`,`上传github`,`处理pr`,`处理issue`,`还有更好的方式吗`,`关闭回复issue`],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`]},wD=`pi-web-ui:wide-chat`,TD={wide:!1};function ED(e){if(!e||typeof e!=`object`)return{...TD};let t=e;return{wide:typeof t.wide==`boolean`?t.wide:TD.wide}}function DD(){try{let e=localStorage.getItem(wD);return e?ED(JSON.parse(e)):{...TD}}catch{return{...TD}}}function OD(e){let t=ED(e);try{localStorage.setItem(wD,JSON.stringify(t))}catch{}kD=t;for(let e of AD)e()}var kD=null,AD=new Set;function jD(e){return AD.add(e),()=>{AD.delete(e)}}function MD(){return kD||=DD(),kD.wide}function ND(){return(0,Q.useSyncExternalStore)(jD,MD)}var PD=`pi-web-ui:hide-model-row`,FD={hide:!1};function ID(e){if(!e||typeof e!=`object`)return{...FD};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:FD.hide}}function LD(){try{let e=localStorage.getItem(PD);return e?ID(JSON.parse(e)):{...FD}}catch{return{...FD}}}function RD(e){let t=ID(e);try{localStorage.setItem(PD,JSON.stringify(t))}catch{}zD=t;for(let e of BD)e()}var zD=null,BD=new Set;function VD(e){return BD.add(e),()=>{BD.delete(e)}}function HD(){return zD||=LD(),zD.hide}function UD(){return(0,Q.useSyncExternalStore)(VD,HD)}function WD(e,t,n,r,i){return{x:Math.max(0,Math.min(r,(e-n.left)*r/Math.max(1,n.width))),y:Math.max(0,Math.min(i,(t-n.top)*i/Math.max(1,n.height)))}}function GD(e,t){let n=t.points[0];if(!n)return;let r=t.points[t.points.length-1];if(e.save(),e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.width,e.lineCap=`round`,e.lineJoin=`round`,t.tool===`text`){e.font=`600 ${Math.max(16,t.width*6)}px system-ui, sans-serif`,e.textBaseline=`top`;for(let[r,i]of(t.text||``).split(`
|
|
401
|
+
`).entries())e.fillText(i,n.x,n.y+r*Math.max(20,t.width*7.5))}else if(t.tool===`rectangle`)e.strokeRect(n.x,n.y,r.x-n.x,r.y-n.y);else if(t.tool===`pen`&&t.points.length===1)e.beginPath(),e.arc(n.x,n.y,t.width/2,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(n.x,n.y);for(let n of t.points.slice(1))e.lineTo(n.x,n.y);if(e.stroke(),t.tool===`arrow`){let i=Math.atan2(r.y-n.y,r.x-n.x),a=Math.max(12,t.width*4);e.beginPath(),e.moveTo(r.x-a*Math.cos(i-Math.PI/6),r.y-a*Math.sin(i-Math.PI/6)),e.lineTo(r.x,r.y),e.lineTo(r.x-a*Math.cos(i+Math.PI/6),r.y-a*Math.sin(i+Math.PI/6)),e.stroke()}}e.restore()}function KD({src:e,onSave:t,onCancel:n,saveLabel:r}){let i=W(),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(`pen`),[g,_]=(0,Q.useState)(`#ef4444`),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(``),D=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>{D.current=!0,S(!1),p([]),E(``);let t=new Image;return t.crossOrigin=`anonymous`,t.onload=()=>{if(!D.current||!a.current)return;o.current=t;let e=Math.min(1,4096/Math.max(t.naturalWidth,t.naturalHeight));a.current.width=Math.max(1,Math.round(t.naturalWidth*e)),a.current.height=Math.max(1,Math.round(t.naturalHeight*e)),S(!0),d(e=>e+1)},t.onerror=()=>{D.current&&E(i(`imagePreviewFailed`))},t.src=e,()=>{D.current=!1,t.onload=null,t.onerror=null,c.current=null,o.current=null}},[e,i]),(0,Q.useEffect)(()=>{let e=a.current,t=e?.getContext(`2d`);if(e&&t&&o.current){t.clearRect(0,0,e.width,e.height),t.drawImage(o.current,0,0,e.width,e.height);for(let e of f)GD(t,e);c.current&&GD(t,c.current)}},[f,u,x]);let O=e=>WD(e.clientX,e.clientY,e.currentTarget.getBoundingClientRect(),e.currentTarget.width,e.currentTarget.height),k=(e,t)=>{if(l.current===e.pointerId){if(t&&c.current){let t=c.current;t.tool!==`pen`&&(t.points=[t.points[0],O(e)]),p(e=>[...e,t])}c.current=null,l.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),d(e=>e+1)}};return(0,$.jsxs)(`div`,{className:`image-annotation-editor`,children:[(0,$.jsxs)(`div`,{className:`image-annotation-toolbar`,role:`toolbar`,"aria-label":i(`imageAnnotate`),children:[[[`pen`,ie,`imageAnnotatePen`],[`arrow`,s,`imageAnnotateArrow`],[`rectangle`,rt,`imageAnnotateRectangle`],[`text`,Oe,`imageAnnotateText`]].map(([e,t,n])=>(0,$.jsxs)(`button`,{type:`button`,className:`btn ${m===e?`active`:``}`,"aria-pressed":m===e,disabled:C,onClick:()=>h(e),children:[(0,$.jsx)(t,{}),i(n)]},e)),(0,$.jsx)(`input`,{type:`color`,"aria-label":i(`imageAnnotateColor`),value:g,disabled:C,onChange:e=>_(e.target.value)}),m===`text`&&(0,$.jsx)(`input`,{type:`text`,className:`image-annotation-text`,"aria-label":i(`imageAnnotateText`),placeholder:i(`imageAnnotateTextHint`),value:y,maxLength:280,disabled:C,onChange:e=>b(e.target.value)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:!f.length||C,onClick:()=>p(e=>e.slice(0,-1)),children:[(0,$.jsx)(v,{}),i(`imageAnnotateUndo`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:C,onClick:n,children:i(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:!x||!f.length||C,onClick:async()=>{if(a.current&&!C){w(!0),E(``);try{await t(a.current.toDataURL(`image/png`))}catch{D.current&&E(i(`imageAnnotateSaveFailed`))}finally{D.current&&w(!1)}}},children:r??i(`imageAnnotateSave`)})]}),(0,$.jsx)(`p`,{className:`img-lightbox-hint`,children:i(m===`text`?`imageAnnotateTextHint`:`imageAnnotateHint`)}),T&&(0,$.jsx)(`p`,{role:`alert`,children:T}),(0,$.jsx)(`div`,{className:`image-annotation-stage`,children:(0,$.jsx)(`canvas`,{ref:a,className:`image-annotation-canvas`,"aria-label":i(`imageAnnotateCanvas`),onPointerDown:e=>{if(!x||C||l.current!==null||e.pointerType===`mouse`&&e.button!==0)return;let t=O(e),n={tool:m,color:g,width:Math.max(3,e.currentTarget.width/300),points:[t]};if(m===`text`){y.trim()&&p(e=>[...e,{...n,text:y.trim()}]);return}e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),l.current=e.pointerId,c.current=n,d(e=>e+1)},onPointerMove:e=>{if(!c.current||l.current!==e.pointerId)return;e.preventDefault();let t=O(e);c.current.points=m===`pen`?[...c.current.points,t]:[c.current.points[0],t],d(e=>e+1)},onPointerUp:e=>k(e,!0),onPointerCancel:e=>k(e,!1),onLostPointerCapture:e=>k(e,!1)})})]})}var qD=null,JD={busy:!1,error:``},YD=new Set;function XD(e,t=``){if(JD.busy!==e||JD.error!==t){JD={busy:e,error:t};for(let e of YD)e()}}function ZD(){return JD}function QD(e){return YD.add(e),()=>{YD.delete(e)}}function $D(e){qD=e}function eO(){if(!JD.busy){XD(!0);try{if(!qD)throw Error(`OCR installation is unavailable. Reconnect and retry.`);qD()}catch(e){XD(!1,e instanceof Error?e.message:String(e))}}}var tO={"image/png":`png`,"image/jpeg":`jpg`,"image/gif":`gif`,"image/webp":`webp`,"image/avif":`avif`,"image/bmp":`bmp`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/x-icon":`ico`},nO=/\.(?:png|jpe?g|gif|webp|avif|bmp|svg|tiff?|ico|heic|heif)$/i;function rO(e,t){let n=(e?.split(/[\\/]/).pop()||`image`).replace(/[\u0000-\u001f<>:"|?*]/g,`_`).trim(),r=tO[t];return r?n.toLowerCase().endsWith(`.${r}`)||r===`jpg`&&/\.jpeg$/i.test(n)?n:`${n.replace(nO,``).slice(0,180)||`image`}.${r}`:n||`image`}async function iO(e,t,n){let r=await fetch(e,{credentials:`same-origin`,signal:n});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.blob();if(n?.throwIfAborted(),!i.size)throw Error(`Empty image`);let a=i.type;if(!a.startsWith(`image/`)){let e=new Uint8Array(await i.slice(0,12).arrayBuffer()),t=String.fromCharCode(...e);a=e[0]===137&&t.slice(1,4)===`PNG`?`image/png`:e[0]===255&&e[1]===216&&e[2]===255?`image/jpeg`:t.startsWith(`GIF8`)?`image/gif`:t.startsWith(`RIFF`)&&t.slice(8)===`WEBP`?`image/webp`:`image/unknown`}return n?.throwIfAborted(),new File([i],rO(t,a),{type:a})}async function aO(e,t){let n=await iO(e,void 0,t);if(n.type===`image/png`)return n;let r=URL.createObjectURL(n);try{let e=new Image;e.src=r,await e.decode(),t?.throwIfAborted();let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let i=n.getContext(`2d`);if(!i)throw Error(`Image conversion is unavailable`);i.drawImage(e,0,0);let a=await new Promise((e,t)=>{n.toBlob(n=>n?e(n):t(Error(`Image conversion failed`)),`image/png`)});return t?.throwIfAborted(),a}finally{URL.revokeObjectURL(r)}}async function oO(e,t){if(!navigator.clipboard?.write||typeof ClipboardItem>`u`)throw new DOMException(`Image clipboard is unavailable`,`NotSupportedError`);let n=aO(e,t);n.catch(()=>{}),await navigator.clipboard.write([new ClipboardItem({"image/png":n})])}async function sO(e,t,n){let r=await iO(e,t,n),i=await _m(r,r.name);if(i.ok)return!0;if(i.cancelled)return!1;throw Error(i.error)}function cO({tip:e,label:t,disabled:n,onClick:r,className:i,buttonRef:a,children:o}){return(0,$.jsx)(`button`,{ref:a,type:`button`,className:i?`img-lightbox-btn ${i}`:`img-lightbox-btn`,"data-tip":e,"aria-label":t??e,disabled:n,onClick:r,children:o})}function lO({src:e,alt:t,onClose:r,onSaveAnnotation:i,actions:a,composerSessionId:o}){let s=W(),c=Jm(),l=X(Et()),u=o,d=(0,Q.useRef)(u);d.current=u;let[f,p]=(0,Q.useState)(null),h=f?.original===e?f.src:e,g=h===e?t:rO(t,`image/png`),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=!!i||w?.sessionId===u&&w?.src===h,D=(0,Q.useRef)(null),O=(0,Q.useRef)(null),[k,A]=(0,Q.useState)(null),j=k?.src===h?k:{width:0,height:0},[M,N]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(!1),L=(0,Q.useRef)(!1);L.current=P;let z=(0,Q.useSyncExternalStore)(Mn,gn),B=(0,Q.useSyncExternalStore)(QD,ZD),[ee,V]=(0,Q.useState)(``),te=z.find(e=>e.id===ee)??z[0],ne=!te&&B.busy,re=!te&&B.error,[H,ae]=(0,Q.useState)(!1),[U,oe]=(0,Q.useState)(0),[se,ce]=(0,Q.useState)(null),[G,K]=(0,Q.useState)(``),[ue,de]=(0,Q.useState)(null),fe=ue===h,[pe,q]=(0,Q.useState)(!1),ge=(0,Q.useRef)(null),_e=(0,Q.useRef)(null),ve=(0,Q.useRef)(null),J=(0,Q.useRef)(r);J.current=r;let ye=(0,Q.useRef)({src:h,onSaveAnnotation:i});ye.current={src:h,onSaveAnnotation:i};let xe=(0,Q.useRef)(pe);xe.current=pe;let{copied:Se,copy:Ce,reset:we}=Kd();(0,Q.useEffect)(()=>(ge.current?.abort(),ge.current=null,ae(!1),oe(0),ce(null),K(``),we(),()=>{ge.current?.abort(),ge.current=null}),[h,te,we]),(0,Q.useEffect)(()=>p(null),[e]),(0,Q.useEffect)(()=>(D.current?.abort(),D.current=null,v(null),b(``),C(``),q(!1),N(null),F(!1),()=>{D.current?.abort(),D.current=null}),[h]),(0,Q.useEffect)(()=>{let e=document.activeElement;ve.current?.focus({focusVisible:!1});let t=e=>{if(!document.querySelector(`.approval-modal, .perm-modal-backdrop`)){if(e.key===`Escape`){if(e.stopImmediatePropagation(),xe.current){e.preventDefault(),q(!1);return}if(L.current){e.preventDefault(),F(!1);return}e.preventDefault(),J.current()}else if(e.key===`Tab`){let t=_e.current?.querySelectorAll(`button:not(:disabled), select:not(:disabled), textarea:not(:disabled), input:not(:disabled)`);if(!t?.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||!_e.current?.contains(document.activeElement))?(e.preventDefault(),r.focus()):!e.shiftKey&&(document.activeElement===r||!_e.current?.contains(document.activeElement))&&(e.preventDefault(),n.focus())}else if((e.key===`f`||e.key===`F`)&&!e.metaKey&&!e.ctrlKey&&!e.altKey){let t=e.target instanceof HTMLElement?e.target:null;if(e.repeat||t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))return;e.preventDefault(),F(!L.current)}}};return window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`keydown`,t,!0),e instanceof HTMLElement&&e.isConnected&&e.focus()}},[]);let Te=async()=>{if(!te||ge.current||fe)return;let e=new AbortController;ge.current=e,ae(!0),K(``),ce(null),oe(0),we();try{let t=await te.recognize({src:h,signal:e.signal,onProgress:t=>{ge.current===e&&Number.isFinite(t)&&oe(Math.max(0,Math.min(1,t)))}});ge.current===e&&!e.signal.aborted&&ce(String(t.text??``).trim())}catch(t){ge.current===e&&!e.signal.aborted&&K(t instanceof Error?t.message:s(`imageOcrFailed`))}finally{ge.current===e&&(ge.current=null,ae(!1))}},Ee=async e=>{if(D.current||fe||pe)return;let t=new AbortController;D.current=t,v(e),b(``),C(``);try{if(e===`copy`)await oO(h,t.signal);else if(e===`download`){if(!await sO(h,g,t.signal))return}else{if(!u)throw Error(s(`imageAttachFailed`));let e=await Vh(await iO(h,g,t.signal));if(t.signal.throwIfAborted(),!e||e.size>2097152||d.current!==u||!dn({attachments:[{path:``,name:rO(e.name,e.mimeType),imageData:e.data,mimeType:e.mimeType,size:e.size,key:crypto.randomUUID()}]}))throw Error(s(`imageAttachFailed`));D.current===t&&T({sessionId:u,src:h})}D.current===t&&C(s(e===`attach`?`imageAttached`:e===`copy`?`imageCopied`:`imageDownloaded`))}catch(n){if(D.current===t&&!t.signal.aborted){let t=n instanceof Error?n.message:String(n),r=s(e===`attach`?`imageAttachFailed`:`copyFailed`);b(n instanceof Error&&n.name===`NotSupportedError`?s(`imageCopyUnavailable`):e===`download`?s(`downloadFailed`,{error:t}):t===r?r:`${r}: ${t}`)}}finally{D.current===t&&(D.current=null,v(null))}},De=e=>{let t=M??Math.min((O.current?.clientWidth||j.width)/j.width,(O.current?.clientHeight||j.height)/j.height);N(Math.max(.1,Math.min(4,t*e)))},Oe=!!_||pe||fe;return(0,cr.createPortal)((0,$.jsx)(`div`,{ref:_e,className:`img-lightbox`,"data-fullscreen":P?`true`:void 0,style:{zIndex:c},role:`dialog`,"aria-modal":`true`,"aria-label":t||s(`toolImageZoom`),onClick:e=>{e.target===e.currentTarget&&r()},children:(0,$.jsxs)(`div`,{className:`img-lightbox-panel`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-toolbar`,children:[(0,$.jsx)(`span`,{className:`img-lightbox-name`,title:g,children:g}),(0,$.jsxs)(`div`,{className:`img-lightbox-actions`,children:[(0,$.jsx)(cO,{tip:s(E?`imageAttached`:`imageAttach`),disabled:Oe||!u||E,onClick:()=>void Ee(`attach`),children:E?(0,$.jsx)(n,{}):(0,$.jsx)(It,{})}),(0,$.jsx)(cO,{tip:s(`imageCopy`),disabled:Oe,onClick:()=>void Ee(`copy`),children:(0,$.jsx)(x,{})}),(0,$.jsx)(cO,{tip:s(`downloadFile`),disabled:Oe,onClick:()=>void Ee(`download`),children:(0,$.jsx)(he,{})}),a?.filter(e=>e.id!==`download`).map(e=>(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-btn img-lightbox-btn-text`,disabled:!!_||pe,onClick:()=>{try{let t=e.onSelect();e.closeOnSelect&&r(),Promise.resolve(t).catch(e=>{_e.current&&K(e instanceof Error?e.message:String(e))})}catch(e){K(e instanceof Error?e.message:String(e))}},children:e.label},e.id)),z.length>1&&(0,$.jsx)(`select`,{className:`img-lightbox-select`,"aria-label":s(`imageOcrProvider`),value:te?.id??``,disabled:H,onChange:e=>V(e.target.value),children:z.map(e=>(0,$.jsx)(`option`,{value:e.id,children:l?e.label:e.labelEn||e.label},e.id))}),(0,$.jsx)(cO,{tip:s(`imageAnnotate`),disabled:H||Oe,onClick:()=>{F(!0),q(!0)},children:(0,$.jsx)(ie,{})}),h!==e&&(0,$.jsx)(cO,{tip:s(`imageRestoreOriginal`),disabled:H||Oe,onClick:()=>p(null),children:(0,$.jsx)(me,{})}),(0,$.jsx)(cO,{tip:s(te?`imageOcr`:`imageOcrInstall`),label:s(ne?`imageOcrInstalling`:`imageOcr`),disabled:H||ne||Oe,onClick:()=>te?void Te():eO(),children:(0,$.jsx)(Y,{})}),(0,$.jsx)(cO,{tip:s(P?`exitFullscreen`:`fullscreen`),onClick:()=>F(!P),children:P?(0,$.jsx)(I,{}):(0,$.jsx)(m,{})}),(0,$.jsx)(cO,{tip:s(`close`),className:`img-lightbox-close`,buttonRef:ve,onClick:r,children:(0,$.jsx)(Be,{})})]})]}),(_||S||y)&&(0,$.jsx)(`div`,{className:`img-lightbox-notice${y?` img-lightbox-notice-error`:``}`,role:y?`alert`:`status`,children:y||(_?s(`running`):S)}),pe?(0,$.jsx)(KD,{src:h,saveLabel:s(i?`imageAnnotateSave`:`imageAnnotApply`),onCancel:()=>q(!1),onSave:async t=>{i&&await i(t),_e.current?.isConnected&&ye.current.src===h&&ye.current.onSaveAnnotation===i&&(i?r():(p({original:e,src:t}),q(!1)))}},h):(0,$.jsxs)(`div`,{className:`img-lightbox-content`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-viewer`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-image${M===null?``:` img-lightbox-image-zoomed`}`,"data-pending":j.width>0||fe?void 0:`true`,children:[(0,$.jsx)(`img`,{crossOrigin:R(h),ref:O,src:h,alt:t??`image preview`,style:M===null||!j.width?void 0:{width:j.width*M,height:j.height*M},onLoad:e=>{A({src:h,width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight}),de(null)},onDoubleClick:()=>F(!P),onError:()=>de(h)},h),fe&&(0,$.jsx)(`p`,{role:`alert`,children:s(`imagePreviewFailed`)})]}),(0,$.jsxs)(`div`,{className:`img-lightbox-view-controls`,children:[j.width>0&&(0,$.jsxs)(`span`,{className:`img-lightbox-dims`,children:[j.width,` × `,j.height]}),(0,$.jsx)(cO,{tip:s(`imageZoomOut`),disabled:!j.width||M!==null&&M<=.1,onClick:()=>De(1/1.25),children:(0,$.jsx)(wt,{})}),(0,$.jsx)(cO,{tip:s(`imageActualSize`),disabled:!j.width,onClick:()=>N(1),children:(0,$.jsx)(le,{})}),M!==null&&(0,$.jsxs)(`span`,{className:`img-lightbox-zoom`,children:[Math.round(M*100),`%`]}),(0,$.jsx)(cO,{tip:s(`imageZoomIn`),disabled:!j.width||M!==null&&M>=4,onClick:()=>De(1.25),children:(0,$.jsx)(be,{})}),(0,$.jsx)(cO,{tip:s(`imageFit`),disabled:M===null,onClick:()=>N(null),children:(0,$.jsx)(Ke,{})})]})]}),(H||se!==null||G||ne||re)&&(0,$.jsxs)(`section`,{className:`img-lightbox-ocr`,"aria-label":s(`imageOcrResult`),children:[(0,$.jsxs)(`div`,{className:`img-lightbox-ocr-head`,children:[(0,$.jsx)(`strong`,{children:s(`imageOcrResult`)}),H?(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{ge.current?.abort(),ge.current=null,ae(!1)},children:s(`cancel`)}):se?(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:async()=>{await Ce(se)||K(s(`copyFailed`))},children:[Se?(0,$.jsx)(n,{}):(0,$.jsx)(x,{}),s(Se?`copied`:`copyText`)]}):null]}),H&&(0,$.jsxs)(`div`,{role:`status`,children:[(0,$.jsxs)(`p`,{children:[s(`imageOcrWorking`),` `,Math.round(U*100),`%`]}),(0,$.jsx)(`progress`,{max:1,value:U}),(0,$.jsx)(`p`,{className:`img-lightbox-hint`,children:s(`imageOcrDownload`)})]}),ne&&(0,$.jsx)(`p`,{role:`status`,children:s(`imageOcrInstalling`)}),re&&(0,$.jsx)(`p`,{role:`alert`,children:re}),G&&(0,$.jsx)(`p`,{role:`alert`,children:G}),se!==null&&(se?(0,$.jsx)(`textarea`,{"aria-label":s(`imageOcrResult`),value:se,readOnly:!0,spellCheck:!1}):(0,$.jsx)(`p`,{role:`status`,children:s(`imageOcrEmpty`)}))]})]})]})}),document.body)}var uO=`pi-web-ui:favicon-settings`,dO=[{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`}],fO=`#8b5cf6`,pO={color:`default`,customHex:``,instanceName:``};function mO(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 hO(e){if(!e||typeof e!=`object`)return{...pO};let t=e;return{color:typeof t.color==`string`&&t.color.trim()?t.color.trim():pO.color,customHex:typeof t.customHex==`string`?t.customHex.trim():``,instanceName:typeof t.instanceName==`string`?t.instanceName.trim():``}}function gO(e,t=dO){if(!e||t.length===0)return fO;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 _O(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 vO(e){let t=_O(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 yO={};function bO(e){yO={...yO,...e},EO();for(let e of kO)e()}async function xO(){if(typeof window<`u`&&typeof fetch<`u`)try{let e=await fetch(g(`/api/health`));if(!e.ok)return;let t=await e.json();t&&(t.instanceName||t.faviconColor)&&bO({instanceName:t.instanceName,faviconColor:t.faviconColor})}catch{}}function SO(e,t=typeof window<`u`?window.location.host:``,n=yO.faviconColor){if(e.color===`custom`&&e.customHex){let t=mO(e.customHex);if(t)return t}if(e.color===`auto`)return gO(t||`localhost`);let r=dO.find(t=>t.id===e.color);if(r)return r.hex;let i=mO(e.color);if(i)return i;if(e.color==="default"&&n){let e=dO.find(e=>e.id===n.toLowerCase());if(e)return e.hex;let t=mO(n);if(t)return t}return fO}function CO(e,t=yO.instanceName){return e.instanceName&&e.instanceName.trim()?e.instanceName.trim():t&&t.trim()?t.trim():``}function wO(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=vO(e);t.href=`data:image/svg+xml;utf8,${encodeURIComponent(n)}`}function TO(){try{let e=localStorage.getItem(uO);return e?hO(JSON.parse(e)):{...pO}}catch{return{...pO}}}function EO(){wO(SO(OO??TO(),typeof window<`u`?window.location.host:``))}function DO(e){let t=hO(e);try{localStorage.setItem(uO,JSON.stringify(t))}catch{}OO=t,EO();for(let e of kO)e()}var OO=null,kO=new Set;function AO(e){return kO.add(e),()=>{kO.delete(e)}}function jO(){return OO||=TO(),OO}function MO(){return(0,Q.useSyncExternalStore)(AO,jO)}function NO(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 PO=`pi-web-ui:wallpaper`,FO=`has-wallpaper`,IO={url:``,dim:78,blur:0},LO=2e3,RO=28e5;function zO(e){if(typeof e!=`string`)return``;let t=e.trim();if(!t)return``;let n=t.toLowerCase().startsWith(`data:image/`)?RO:LO;return t.length>n?``:/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)?t:``}var BO=(e,t,n,r)=>typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function VO(e){if(!e||typeof e!=`object`)return{...IO};let t=e;return{url:zO(t.url),dim:BO(t.dim,0,95,IO.dim),blur:BO(t.blur,0,24,IO.blur)}}function HO(){try{let e=localStorage.getItem(PO);return e?VO(JSON.parse(e)):{...IO}}catch{return{...IO}}}function UO(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\r\n]/g,``)}async function WO(e){let t=await Vh(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function GO(){let e=qO??HO(),t=document.documentElement;e.url?(t.style.setProperty(`--bg-image`,`url("${UO(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(FO,e.url!==``||n!==``&&n!==`none`)}function KO(e){let t=VO(e);qO=t;try{localStorage.setItem(PO,JSON.stringify(t))}catch{}for(let e of JO)e();GO()}var qO=null,JO=new Set;function YO(e){return JO.add(e),()=>{JO.delete(e)}}function XO(){return qO||=HO(),qO}function ZO(){return(0,Q.useSyncExternalStore)(YO,XO)}function QO(){let e=ZO();(0,Q.useEffect)(()=>{GO()},[e]),(0,Q.useEffect)(()=>{let e=()=>GO();return window.addEventListener(Jt,e),GO(),()=>window.removeEventListener(Jt,e)},[])}var $O=(0,Q.lazy)(()=>_d(()=>import(`./TerminalPanel-vdSIOPjD.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([6,1,7,3,8,9,10,11,12]),import.meta.url)),ek=(0,Q.lazy)(()=>_d(()=>import(`./NativeCliPanel-B108d697.js`).then(e=>({default:e.NativeCliPanel})),__vite__mapDeps([13,1,7,3,8,14,9,10,11,12]),import.meta.url)),tk=(0,Q.lazy)(()=>_d(()=>import(`./SCMPanel-DluNcd2-.js`).then(e=>({default:e.ScmPanel})),__vite__mapDeps([15,1,7,3,8]),import.meta.url)),nk=(0,Q.lazy)(()=>_d(()=>import(`./DeviceCenter-By1zVTSY.js`).then(e=>({default:e.DeviceCenter})),__vite__mapDeps([16,1,7,3,17,18]),import.meta.url)),rk=(0,Q.lazy)(()=>_d(()=>import(`./DeviceGroups-DPrQxW6B.js`).then(e=>({default:e.DeviceGroupCreateDialog})),__vite__mapDeps([19,1,7,3,20,21]),import.meta.url)),ik=(0,Q.lazy)(()=>_d(()=>import(`./CanvasStudio-DU6O3N4u.js`).then(e=>({default:e.CanvasStudio})),__vite__mapDeps([22,1,7,3,8,14,23,24]),import.meta.url)),ak=(0,Q.lazy)(()=>_d(()=>import(`./PiSetupModal-D0HitBfd.js`).then(e=>({default:e.PiSetupModal})),__vite__mapDeps([25,1,7,3,26,10,27]),import.meta.url)),ok=(0,Q.lazy)(()=>_d(()=>import(`./ModelConfigModal-D2Ro-jUZ.js`).then(e=>({default:e.ModelConfigModal})),__vite__mapDeps([28,1,7,3,27]),import.meta.url)),sk=(0,Q.lazy)(()=>_d(()=>import(`./SettingsModal-Dm_haPme.js`).then(e=>({default:e.SettingsModal})),__vite__mapDeps([29,1,7,3,20,8,26,10,30,14,31,17,32]),import.meta.url)),ck=(0,Q.lazy)(()=>_d(()=>import(`./BgTasksModal-SAH2XCkY.js`).then(e=>({default:e.BgTasksModal})),__vite__mapDeps([33,1,7,3]),import.meta.url)),lk=(0,Q.lazy)(()=>_d(()=>import(`./TuiOverlayModal-Cy1jYYIw.js`).then(e=>({default:e.TuiOverlayModal})),__vite__mapDeps([34,1,7,3,10,11,12]),import.meta.url)),uk=(0,Q.lazy)(()=>_d(()=>import(`./GlobalSearchModal-CiT6wBmR.js`).then(e=>({default:e.GlobalSearchModal})),__vite__mapDeps([35,1,7,3,14,30,8,26,10]),import.meta.url)),dk=(0,Q.lazy)(()=>_d(()=>import(`./FilePreview-CC76Z6an.js`).then(e=>({default:e.FilePreview})),__vite__mapDeps([36,1,7,3]),import.meta.url)),fk=(0,Q.lazy)(()=>_d(()=>import(`./GroupConversation-HeiyW_O_.js`).then(e=>({default:e.GroupConversation})),__vite__mapDeps([37,1,7,3,8,18,21,23]),import.meta.url));function pk({notice:e,onDismiss:t}){let n=W(),{locale:r}=c(),i=!X(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),Jv(e.level));return()=>clearTimeout(n)},[a,e.id,e.level,t]);let s=e.level===`error`?Pe:e.level===`warning`?ct:xe;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)(Be,{})})]})}var mk=[],hk=180,gk=520,_k=240,vk=e=>`pi-web-ui:${e}-panel-width`;function yk(e){try{let t=Number(localStorage.getItem(vk(e)));return Number.isFinite(t)&&t>=hk&&t<=gk?t:_k}catch{return _k}}var bk=e=>`pi-web-ui:${e}-panel-collapsed`;function xk(e){try{return localStorage.getItem(bk(e))===`1`}catch{return!1}}function Sk({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(gk,Math.max(hk,Math.round(a+r))),n(o)},c=()=>{window.removeEventListener(`pointermove`,s),window.removeEventListener(`pointerup`,c),document.body.classList.remove(`panel-resizing`);try{localStorage.setItem(vk(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(_k)})}function Ck({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)(h,{}):(0,$.jsx)(te,{})})}var wk=`pi-web-ui:plugin-path-grants`,Tk=e=>e?`${wk}:${e}`:wk;function Ek(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function Dk(e){try{let t=Tk(e);if(localStorage.getItem(t)!==null)return Ek(localStorage.getItem(t));if(!e)return[];let n=Ek(localStorage.getItem(wk));return localStorage.setItem(t,JSON.stringify(n)),n}catch{return[]}}function Ok(e,t){try{let n=[...new Set([...Dk(t),e])];localStorage.setItem(Tk(t),JSON.stringify(n))}catch{}}function kk(){let e=W(),{locale:t}=c(),{chat:r,send:i,dismissNotice:a,pushNotice:o,terminal:s}=Ry(),l=r.state?.sharedConversation?.readOnly===!0,d=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail,n=typeof t?.text==`string`?t.text.trim():``;if(!n)return;let r=t?.level===`warning`||t?.level===`error`?t.level:`info`;o(r,n)};return window.addEventListener(`pi-web-ui:toast`,e),()=>window.removeEventListener(`pi-web-ui:toast`,e)},[o]),(0,Q.useEffect)(()=>{r.ready&&r.settings&&(d.current||r.settings.quickPhrasesSeeded||(d.current=!0,r.settings.quickPhrases.length===0&&i({type:`set_settings`,quickPhrases:CD[t]??CD.en,quickPhrasesSeeded:!0})))},[r.ready,r.settings,i,t]);let f=r.state?.cwd??``,p=_w(),m=CO(MO());(0,Q.useEffect)(()=>{xO()},[]),(0,Q.useEffect)(()=>{let t=p?uw(f):``,n=t?`${t} — pi-web-ui`:e(`docTitle`);document.title=m?`[${m}] ${n}`:n},[f,p,m,e]);let[h,_]=(0,Q.useState)([]);(0,Q.useEffect)(()=>(en(e=>_(t=>sC(t,e))),()=>en(null)),[]);let[v,b]=(0,Q.useState)(null),[x,C]=(0,Q.useState)(0),w=v?v[x]??v[0]??null:null,[T,E]=(0,Q.useState)(null),D=(0,Q.useRef)(!1),O=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{D.current=v!==null,O.current=T},[v,T]);let k=(0,Q.useCallback)((e,t)=>{let n=gE(t);if(n){b(null),E({file:{path:e,name:t},plugin:n.plugin,declaration:n.declaration});return}E(null),b([{path:e,name:t}]),C(0)},[]),j=(0,Q.useCallback)((e,t=0)=>{let n=(Array.isArray(e)?e:[]).filter(e=>e&&typeof e.path==`string`&&e.path);if(n.length===0)return;let r=Math.min(Math.max(0,t|0),n.length-1),i=n[r]??n[0],a=i?gE(i.name):null;if(a&&i){b(null),E({file:{path:i.path,name:i.name},plugin:a.plugin,declaration:a.declaration});return}E(null),b(n.map(e=>({path:e.path,name:e.name}))),C(r)},[]);(0,Q.useEffect)(()=>(Bf({open:e=>k(e.path,e.name),openList:(e,t)=>j(e,t??0),isOpen:()=>D.current||O.current!==null}),()=>Bf(null)),[k]);let[M,N]=(0,Q.useState)(null),P=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{P.current=M!==null},[M]),(0,Q.useEffect)(()=>(Nn({open:e=>N(e),close:()=>N(null),isOpen:()=>P.current}),()=>Nn(null)),[]);let[F,I]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=()=>I(!1);return window.addEventListener(`drop`,e,!0),()=>window.removeEventListener(`drop`,e,!0)},[]);let[L,R]=(0,Q.useState)(()=>new URLSearchParams(window.location.search).get(`view`)===`devices`?`devices`:`chat`),[z,B]=(0,Q.useState)(null),[ee,V]=(0,Q.useState)(!1),[te,ne]=(0,Q.useState)(null),[re,ie]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>(on(()=>{ne(null),R(`chat`)}),()=>on(null)),[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(t&&typeof t==`object`){if(t.create===!0){ie(!0);return}SD({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?(ne(t.roomId),R(`chat`)):(ne(null),R(`devices`))}};return window.addEventListener(`pi-web-ui:device-group-open`,e),()=>window.removeEventListener(`pi-web-ui:device-group-open`,e)},[]);let H=(e=>!r.tabs||e===`chat`||e===`devices`||e===`worktrees`||r.tabs.includes(e))(L.startsWith(`plugin:`)?`plugins`:L)&&L!==`native-cli`&&(!l||L===`chat`||L===`devices`)?L:`chat`,ae=!!r.state?.nativeCli&&!te&&!l,[U,oe]=(0,Q.useState)({});(0,Q.useEffect)(()=>{if(ae&&r.state?.nativeCli&&r.state.conversationId){let e=r.state.conversationId,t=r.state.nativeCli,n=r.state.cwd;oe(r=>{let i=r[e];return i&&i.nativeCli===t&&i.cwd===n?r:{...r,[e]:{nativeCli:t,cwd:n}}})}},[ae,r.state?.nativeCli,r.state?.conversationId,r.state?.cwd]),(0,Q.useEffect)(()=>{let e=new Set(r.conversations.map(e=>e.id));oe(t=>{let n=!1,r={};for(let[i,a]of Object.entries(t))e.has(i)?r[i]=a:n=!0;return n?r:t})},[r.conversations]);let se=(0,Q.useRef)(!1);se.current=H===`chat`&&ae;let ce=(0,Q.useCallback)(()=>i({type:`refresh_worktrees`}),[i]);Yw(r.state?.worktree?.mainPath,ce);let le=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=le.current;if(e&&r.state?.cwd){if(H!==`worktrees`){le.current=null;return}r.state.cwd===e.target||r.state.worktree?.currentPath===e.target?(le.current=null,R(`chat`),sn()):r.state.cwd!==e.source&&(le.current=null)}},[r.state?.cwd,r.state?.worktree?.currentPath,H]);let G=(0,Q.useMemo)(()=>r.plugins.filter(e=>!r.settings?.disabledPlugins?.includes(e.id)),[r.plugins,r.settings?.disabledPlugins]),[K,de]=(0,Q.useMemo)(()=>{let n=[];return[Ea(ma(r.plugins),{locale:t,t:t=>e(t),disabledPlugins:r.settings?.disabledPlugins??[],layout:r.settings?.uiLayout,diagnostics:n}),n]},[r.plugins,r.settings?.disabledPlugins,r.settings?.uiLayout,t,e]),pe=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let e=de.map(e=>`${e.level}:${e.pluginId??``}:${e.entryId??``}:${e.message}`).join(`
|
|
402
|
+
`);if(e!==pe.current){pe.current=e;for(let e of de){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}`)}}},[de]);let me=(0,Q.useMemo)(()=>K[`topbar.primary`].filter(e=>!e.hidden),[K]),he=(0,Q.useMemo)(()=>[...K[`topbar.primary`].filter(e=>e.hidden),...K[`topbar.overflow`]],[K]),ge=(0,Q.useMemo)(()=>K[`leftpanel.sessions`].filter(e=>!e.hidden),[K]),_e=(0,Q.useMemo)(()=>K[`leftpanel.projects.actions`].filter(e=>!e.hidden),[K]),ve=(0,Q.useMemo)(()=>K[`leftpanel.project`].filter(e=>!e.hidden),[K]),J=(0,Q.useMemo)(()=>K[`leftpanel.running.actions`].filter(e=>!e.hidden),[K]),ye=(0,Q.useMemo)(()=>K[`leftpanel.history.actions`].filter(e=>!e.hidden),[K]),be=K[`leftpanel.sections`],xe=(0,Q.useMemo)(()=>K[`leftpanel.running`].filter(e=>!e.hidden),[K]),Se=(0,Q.useMemo)(()=>K[`leftpanel.history`].filter(e=>!e.hidden),[K]),Ce=(0,Q.useMemo)(()=>K[`terminal.toolbar`].filter(e=>!e.hidden),[K]),Y=(0,Q.useMemo)(()=>K[`scm.toolbar`].filter(e=>!e.hidden),[K]),we=(0,Q.useMemo)(()=>K[`goalbar.actions`].filter(e=>!e.hidden),[K]),Te=(0,Q.useMemo)(()=>K[`chat.header`].filter(e=>!e.hidden),[K]),Ee=(0,Q.useMemo)(()=>K[`chat.empty`].filter(e=>!e.hidden),[K]),De=(0,Q.useMemo)(()=>K[`file.preview.toolbar`].filter(e=>!e.hidden),[K]),Oe=(0,Q.useMemo)(()=>Object.fromEntries((r.dshPresets?.presets??[]).map(n=>[n.id,kw(n,t,e).name])),[r.dshPresets,t]),ke=(0,Q.useMemo)(()=>K[`notice.actions`].filter(e=>!e.hidden),[K]),Ae=(0,Q.useMemo)(()=>K[`sidebar.left`]??[],[K]),je=(0,Q.useMemo)(()=>K[`sidebar.right`]??[],[K]),Me=(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&&SE({messageId:r.id});return}let a=(t.action??``).trim();if(t.kind===`view`||(!a||a===`view`)&&t.source!==`host`){R(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):``;xn(s,a,t.id,{...n===void 0?{}:{value:n},...r===void 0?{}:{target:r},loadBundle:async e=>{let t=Ye.current.plugins.find(t=>t.id===e);return t?Dv(t,Ye.current.pluginsEpoch):!1}}).then(t=>{t||o(`info`,e(`pluginUiNoHandler`))})},[e,o]),Ne=(0,Q.useCallback)(e=>{let t=r.plugins.find(t=>t.id===e.source.slice(7));return t?(0,$.jsx)(Db,{plugin:t,epoch:r.pluginsEpoch,send:i,className:`lp-plugin-page`}):null},[r.plugins,r.pluginsEpoch,i]),Pe=(0,Q.useCallback)((t,n)=>{n.action&&xn(t.pluginId,n.action,n.id,{target:{id:n.id,kind:`plugin-running`,label:n.title},loadBundle:async e=>{let t=Ye.current.plugins.find(t=>t.id===e);return t?Dv(t,Ye.current.pluginsEpoch):!1}}).then(t=>{t||o(`info`,e(`pluginUiNoHandler`))})},[e,o]),[Fe,Ie]=(0,Q.useState)([]);(0,Q.useEffect)(()=>bv(Ie),[]);let[Le,Re]=(0,Q.useState)([]);(0,Q.useEffect)(()=>vv(Re),[]);let[ze,Ve]=(0,Q.useState)(null),[Ue,We]=(0,Q.useState)(null),[Ge,Ke]=(0,Q.useState)(null),qe=ze?K[`modal.dialog`].find(e=>e.id===ze&&!e.hidden):void 0,Je=(0,Q.useMemo)(()=>{if(!qe||qe.kind!==`view`)return``;let e=qe.view??``;return e.startsWith(`plugin:`)?e.slice(7):qe.source.startsWith(`plugin:`)?qe.source.slice(7):``},[qe]);(0,Q.useEffect)(()=>{if(!qe||!Je||Fe.some(e=>e.info.id===Je))return;let e=Ye.current.plugins.find(e=>e.id===Je);e&&Dv(e,Ye.current.pluginsEpoch)},[qe,Je,Fe,r.pluginsEpoch]),(0,Q.useEffect)(()=>{mf(i),hf(G,r.pluginsEpoch),Sf(G,r.pluginsEpoch),hE(G,r.pluginsEpoch),Ov(G,r.pluginsEpoch)},[G,r.pluginsEpoch,i]);let Ye=(0,Q.useRef)(r),Xe=(0,Q.useRef)(null);Ye.current=r,(0,Q.useEffect)(()=>{$D(()=>{let t=Ye.current;if(!t.ready)throw Error(e(`imageOcrInstallFailed`));let n=t.plugins.find(e=>e.id===`image-ocr`);if(n?.error)throw Error(n.error);Xe.current=null;let r=t.settings?.disabledPlugins??[],a=r.includes(`image-ocr`);if(a&&i({type:`set_settings`,disabledPlugins:r.filter(e=>e!==`image-ocr`)}),n)a||i({type:`plugins_reload`});else{let e=Object.values(t.pluginJobs).find(e=>e.pluginId===`image-ocr`&&e.phase!==`done`),n=e?.jobId??Ht();Xe.current=n,e||i({type:`plugin_job`,jobId:n,action:`install`,id:`image-ocr`,source:`xing-shuyin/pi-web-ui/plugins/image-ocr`})}});let t=Mn(()=>{gn().length&&XD(!1)}),n=vv(t=>{t.includes(`image-ocr`)&&XD(!1,e(`imageOcrInstallFailed`))});return()=>{$D(null),t(),n()}},[i,e]),(0,Q.useEffect)(()=>{if(!r.ready){XD(!1);return}let t=Xe.current?r.pluginJobs[Xe.current]:void 0;t&&XD(t.phase!==`done`,t.phase===`done`&&!t.ok?t.error||e(`imageOcrInstallFailed`):``)},[r.pluginJobs,r.ready,e]);let Ze=(0,Q.useRef)(R);Ze.current=R;let Qe=(0,Q.useRef)(K);Qe.current=K,(0,Q.useEffect)(()=>(yn(jn({send:i,isReady:()=>!!Ye.current.state,setView:e=>Ze.current(e),getCwd:()=>Ye.current.state?.cwd??``,getWorkspaceRoots:()=>Ye.current.state?.workspaceRoots??[],listSessions:()=>{let e=Ye.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:()=>Ye.current.state?.conversationId??null,getConversationOwner:()=>Ye.current.state?.sharedConversation?.owner??null,isConversationBlank:()=>(Ye.current.state?.messages.length??0)===0,listModels:()=>Ye.current.models.map(e=>({id:e.id,provider:e.provider,name:e.name,vision:e.vision,reasoning:e.reasoning})),getCurrentModelId:()=>{let e=Ye.current.state?.model;return e?`${e.provider}/${e.id}`:null},listProjects:()=>Ye.current.projects.map(e=>e.path),grantedPaths:Dk,grantPath:Ok,confirm:e=>new Promise(t=>{if(Lt.current){t(!1);return}let n={path:e.path,resolve:t};Lt.current=n,It(n)}),openModal:e=>{let t=String(e??``).trim();if(!t)return!1;let n=Qe.current[`modal.dialog`].find(e=>e.id===t);return!n||n.hidden?!1:(Ve(t),!0)},closeModal:()=>Ve(null),setFooterStatus:(e,t)=>Go(e,t?{...t}:null),pickDirectory:e=>new Promise(t=>{We({initialPath:e?.initialPath,resolve:t})}),pickModel:e=>new Promise(t=>{Ke({currentModelId:e?.currentModelId,resolve:t})}),dialogConfirm:e=>new Promise(t=>{if(Bt.current){t(!1);return}let n={kind:`confirm`,title:e.title,resolve:t};Bt.current=n,zt(n)}),select:e=>new Promise(t=>{if(Bt.current){t({ok:!1,error:`busy`});return}let n={kind:`select`,title:e.title,options:e.options,...e.multi?{multi:!0}:{},resolve:t};Bt.current=n,Wt([]),zt(n)}),input:e=>new Promise(t=>{if(Bt.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};Bt.current=n,qt(e.initial??``),zt(n)}),notifyAction:e=>new Promise(t=>{try{let n=Xt.current;Xt.current=null,Yt(null);try{n?.resolve(null)}catch{}let r={text:e.text,actions:e.actions,resolve:t};Xt.current=r,Yt(r)}catch{t(null)}}),loadPluginBundle:e=>{let t=Ye.current.plugins.find(t=>t.id===e);return t?Dv(t,Ye.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=Ye.current.state?.cwd??``,p=String(t.path??``).replace(/\\/g,`/`),m=/^[A-Za-z]:$/.test(p)?`${p}/`:p.startsWith(`/`)||/^[A-Za-z]:\//.test(p)||!f?p:`${f.replace(/\\/g,`/`).replace(/\/+$/,``)}/${p}`,h=!d&&m&&(f||m.startsWith(`/`)||/^[A-Za-z]:\//.test(m))?{kind:u?`directory`:`file`,path:m,cwd:f||void 0}:void 0,g=(Qe.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-quick-ask`:return Ye.current.settings?.quickAskReferenceMenus!==!1&&h?t:{...t,hidden:!0};case`host:file-compress`:case`host:file-compress-download`:return d?{...t,hidden:!0}:t;case`host:file-extract`:return l&&_b(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}});Xa(g).length!==0&&za({x:t.x,y:t.y,slot:`contextmenu.file`,target:c,entries:g,onHostAction:(n,r)=>{if(n.id===`host:file-quick-ask`){h&&jl({reference:h});return}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=Ye.current.state?.cwd??``,n=t?`${t.replace(/\\/g,`/`).replace(/\/+$/,``)}/${r.id}`:r.id;navigator.clipboard?.writeText(n),o(`info`,e(`copied`));break}}}})}})),()=>yn(null)),[i]);let[$e,et]=(0,Q.useState)(()=>yk(`left`)),[tt,nt]=(0,Q.useState)(()=>yk(`right`)),rt=(0,Q.useCallback)(e=>et(e),[]),at=(0,Q.useCallback)(e=>nt(e),[]),[ot,st]=(0,Q.useState)(()=>xk(`left`)),[ct,lt]=(0,Q.useState)(()=>xk(`right`)),ut=(0,Q.useCallback)(()=>{st(e=>{try{localStorage.setItem(bk(`left`),e?`0`:`1`)}catch{}return!e})},[]),dt=(0,Q.useCallback)(()=>{lt(e=>{try{localStorage.setItem(bk(`right`),e?`0`:`1`)}catch{}return!e})},[]),[ft,pt]=(0,Q.useState)(null),mt=yl(),ht=(0,Q.useRef)(null),[gt,vt]=(0,Q.useState)(()=>window.matchMedia(`(max-width: 768px)`).matches);(0,Q.useEffect)(()=>{let e=window.matchMedia(`(max-width: 768px)`),t=e=>vt(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),yD({enabled:gt&&H===`chat`,open:ft,onOpenChange:pt,container:ht,backdropSelector:`.drawer-backdrop.persistent`});let[Z,yt]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_web_setup_dismissed`)===`1`}catch{return!1}}),bt=()=>{yt(!0);try{localStorage.setItem(`pi_web_setup_dismissed`,`1`)}catch{}},[xt,Ct]=(0,Q.useState)(!1),[wt,Tt]=(0,Q.useState)(!1),[Et,Dt]=(0,Q.useState)(),[Ot,kt]=(0,Q.useState)(null),At=(0,Q.useCallback)(()=>kt(`create`),[]),jt=r.transition?.kind,Mt=r.transition?.target,Nt=r.transition?.progress,Pt=(0,Q.useMemo)(()=>jt&&Mt!==void 0?{kind:jt,target:Mt,progress:Nt??0}:null,[jt,Mt,Nt]),[Ft,It]=(0,Q.useState)(null),Lt=(0,Q.useRef)(null),[Rt,zt]=(0,Q.useState)(null),Bt=(0,Q.useRef)(null),[Ut,Wt]=(0,Q.useState)([]),[Kt,qt]=(0,Q.useState)(``),[Jt,Yt]=(0,Q.useState)(null),Xt=(0,Q.useRef)(null),[Qt,tn]=(0,Q.useState)(()=>new Set),nn=(e,t)=>{i({type:`plugin_path_response`,id:e,ok:t}),tn(t=>new Set(t).add(e))},an=r.pathRequests.find(e=>!Qt.has(e.id))??null,[cn,un]=(0,Q.useState)(()=>new Set),fn=(e,t,n=!1)=>{i({type:`plugin_permission_response`,id:e,ok:t,...n?{remember:!0}:{}}),un(t=>new Set(t).add(e))},pn=r.permRequests.find(e=>!cn.has(e.id))??null,mn=Jm(!!(pn||an||Ft)),hn=ND(),vn=UD(),bn=!ae&&!!r.settings?.minimalNewChat&&(r.state?.messages?.length??0)===0&&!r.state?.streamingMessage,[Sn,Cn]=(0,Q.useState)(!1),[Tn,On]=(0,Q.useState)(!1),[kn,Pn]=(0,Q.useState)(!1),[Fn,In]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!Fn)return;let e=setTimeout(()=>In(null),15e3);return()=>clearTimeout(e)},[Fn]);let[Ln,Rn]=(0,Q.useState)(null),zn=(0,Q.useRef)(null),Bn=(0,Q.useRef)(null),Vn=r.state?.sessionId??``,Hn=(0,Q.useRef)(Vn);Hn.current=Vn;let Un=(0,Q.useRef)(r.ready);Un.current=r.ready,(0,Q.useEffect)(()=>{let e=()=>{if(q())return;let e=zl(window.location.hash);if(e){if(e.messageId?Rn({sessionId:e.sessionId,messageId:e.messageId}):Rn(null),!Un.current||!Hn.current){zn.current=e.sessionId;return}Hn.current===e.sessionId||Hn.current&&e.sessionId&&(Hn.current.includes(e.sessionId)||e.sessionId.includes(Hn.current))||(Bn.current=e.sessionId,R(`chat`),i({type:`switch_session`,path:``,sessionId:e.sessionId}))}};e(),window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e);let t=_u(t=>{window.history.replaceState(null,``,t),ne(null),R(`chat`),e()});return()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e),t()}},[i]);let Wn=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!y()||!r.ready)return;let e=e=>{let t=S()??e?.detail;if(!t||t.eventId&&t.eventId===Wn.current)return;let n=A(t,yy());if(!n){o(`warning`,`The notification no longer identifies an open conversation.`);return}Wn.current=t.eventId,zn.current=null,Bn.current=null,Rn(null),ne(null),R(`chat`);let r=new URL(window.location.href);r.searchParams.delete(`token`),r.searchParams.delete(`view`),r.hash=``,window.history.replaceState(null,``,r.href),i(n)};return window.addEventListener(fe,e),e(),()=>window.removeEventListener(fe,e)},[r.ready,o,i]),(0,Q.useEffect)(()=>{let e=Bn.current;if(e&&r.notices.some(t=>t.text.includes(e)&&(t.text.includes(`未找到会话`)||t.text.includes(`Session not found`)))&&(Bn.current=null,Rn(null),Vn)){let e=Bl({sessionId:Vn});window.location.hash!==e&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${e}`)}},[r.notices,Vn]),(0,Q.useEffect)(()=>{if(!r.ready||!Vn)return;if(zn.current){let e=zn.current;zn.current=null;let t=e===Vn||e&&Vn&&(e.includes(Vn)||Vn.includes(e));if(ne(null),R(`chat`),!t){Bn.current=e,i({type:`switch_session`,path:``,sessionId:e});return}}if(Bn.current){if(Vn===Bn.current||Vn&&Bn.current&&(Vn.includes(Bn.current)||Bn.current.includes(Vn)))Bn.current=null;else return}let e=zl(window.location.hash),t=e?.sessionId===Vn?e.messageId:void 0,n=Bl({sessionId:Vn,...t?{messageId:t}:{}});window.location.hash!==n&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${n}`)},[r.ready,Vn,i]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail,a=n?.title||e(`pluginCommandFallback`),o=n?.command;if(!o||!r.ready)return;let c={name:a,command:o,cwd:"${pwd}"},l=r.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=Ht(),s.create({id:u,conversationId:r.activeConversationId||r.state?.conversationId||``,title:a,cwd:r.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:c})),s.select(u),R(`terminal`)};window.addEventListener(`pi-web-ui:plugin-run-command`,t),window.addEventListener(`pi-web-ui:run-command`,t);let n=e=>{let t=e.detail;typeof t==`string`&&t&&(R(e=>e===`chat`?e:`chat`),i({type:`switch_conversation`,id:t}),sn())};return window.addEventListener(`pi-web-ui:switch-conversation`,n),()=>{window.removeEventListener(`pi-web-ui:plugin-run-command`,t),window.removeEventListener(`pi-web-ui:run-command`,t),window.removeEventListener(`pi-web-ui:switch-conversation`,n)}},[r,s,i]),(0,Q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),On(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let[Gn,Kn]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_zen_mode`)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{Gn?localStorage.setItem(`pi_zen_mode`,`1`):localStorage.removeItem(`pi_zen_mode`)}catch{}},[Gn]);let qn=(0,Q.useCallback)(()=>{Kn(e=>{let t=!e;return t&&H!==`chat`&&R(`chat`),t})},[H]);Vt(()=>Gn?(Kn(!1),!0):!1,Gn),Vt(()=>ft?(pt(null),!0):!1,ft!==null),(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(),qn())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[qn]);let[Jn,Yn]=(0,Q.useState)(su),[Xn,Zn]=(0,Q.useState)(Xh),{themes:Qn,theme:$n,switchTheme:er,reloadThemes:tr}=Gt();QO(),(0,Q.useEffect)(()=>{try{typeof wn==`function`&&wn($n??``)}catch{}},[$n]),(0,Q.useEffect)(()=>{try{typeof Dn==`function`&&Dn(t)}catch{}},[t]),(0,Q.useEffect)(()=>{try{typeof _n==`function`&&_n(H)}catch{}},[H]),(0,Q.useEffect)(()=>{try{let e=r.state?.model,t=e?`${e.provider}/${e.id}`:null;typeof An==`function`&&An(t)}catch{}},[r.state?.model?.provider,r.state?.model?.id]),(0,Q.useEffect)(()=>{if(!Rt)return;let e=e=>{if(e.key!==`Escape`)return;let t=Bt.current;Bt.current=null,zt(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)},[Rt]),(0,Q.useEffect)(()=>{if(!Jt)return;let e=setTimeout(()=>{let e=Xt.current;Xt.current=null,Yt(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[Jt]);let nr=(0,Q.useRef)(null),rr=(0,Q.useRef)(null),ir=(0,Q.useRef)(r.state?.messages);ir.current=r.state?.messages;let ar=(0,Q.useRef)(new Set),or=(0,Q.useRef)(new Set),sr=(0,Q.useRef)(new Set),lr=(0,Q.useRef)(0),ur=(0,Q.useRef)(!1),dr=(0,Q.useRef)(r.terminals);(0,Q.useEffect)(()=>{cu(Jn)},[Jn]),(0,Q.useEffect)(()=>{Zh(Xn)},[Xn]),(0,Q.useEffect)(()=>{let e=dr.current;dr.current=r.terminals;for(let t of r.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})))}},[r.terminals,i]),(0,Q.useEffect)(()=>{let t=r.state?.conversationId??null,n=NO(nr.current,t,r.state?.isStreaming??!1,r.conversations,rr.current,!!r.state?.completionPending||!!r.state?.queue?.steering.length||!!r.state?.queue?.followUp.length);nr.current=n.nextMap,rr.current=t;for(let[e,t]of n.nextMap.entries())t&&vl(e);if(n.startCue&&(hu(`start`,Jn),Wu(e(`notifyStartTitle`),e(`notifyStartBody`),`start`,Vn)),n.finishedConvs.length>0){let t=typeof document<`u`&&document.hasFocus?document.hasFocus():!0,i=[];for(let e of n.finishedConvs)if(!e.isActive||!t){let t=r.conversations.find(t=>t.id===e.id);i.push({id:e.id,sessionId:t?.sessionId,sessionFile:t?.sessionFile})}i.length>0&&_l(i),n.finishedConvs.some(e=>!e.isSubagent&&Jn.done)?hu(`done`,Jn):n.finishedConvs.some(e=>e.isSubagent)&&hu(`subagentDone`,Jn);let a=n.finishedConvs.find(e=>e.isActive);if(a&&(Wu(e(`notifyDoneTitle`),e(`notifyDoneBody`),a.isSubagent?`subagentDone`:`done`,Vn),Xn.enabled)){if(Xn.readReplies){if(!Xn.streamReplies){let t=tg(ir.current);t?dg(t,Xn):Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceDone`),Xn)}}else Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceDone`),Xn)}for(let t of n.finishedConvs.filter(e=>!e.isActive)){let n=t.title?`${t.title}:${e(`notifyDoneBody`)}`:e(`notifyDoneBody`),i=r.conversations.find(e=>e.id===t.id)?.sessionId;Wu(e(`notifyDoneTitle`),n,t.isSubagent?`subagentDone`:`done`,i)}!a&&Xn.enabled&&Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceDone`),Xn)}},[r.state?.conversationId,Vn,r.state?.isStreaming,r.state?.completionPending,r.state?.queue,r.conversations,Jn,Xn,e]),(0,Q.useEffect)(()=>{let e=r.state?.conversationId??null;e&&(vl(e),r.state?.sessionId&&vl(r.state.sessionId),r.state?.sessionFile&&vl(r.state.sessionFile))},[r.state?.conversationId,r.state?.sessionId,r.state?.sessionFile]),(0,Q.useEffect)(()=>{let e=()=>{let e=r.state?.conversationId;e&&(vl(e),r.state?.sessionId&&vl(r.state.sessionId),r.state?.sessionFile&&vl(r.state.sessionFile))};return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[r.state?.conversationId,r.state?.sessionId,r.state?.sessionFile]);let fr=(0,Q.useRef)(null),pr=(0,Q.useRef)(null),mr=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let e=r.state?.isStreaming??!1,t=r.state?.conversationId;if(!(Xn.enabled&&Xn.readReplies&&Xn.streamReplies)||!e){if(fr.current){let e=ir.current,t=Array.isArray(e)&&e.length>0?e[e.length-1]:null;if(t&&t.role===`assistant`&&pr.current){let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
403
|
+
`);pr.current.flush(e)}fr.current.finish(),fr.current=null,pr.current=null,mr.current=0}return}let n=r.state?.messages,i=Array.isArray(n)&&n.length>0?n[n.length-1]:null;if(!i||i.role!==`assistant`)return;let a=Date.now();if(a-mr.current<150)return;if(mr.current=a,!fr.current){let e=mg(Xn,t);fr.current=e,pr.current=new eg(t=>{e.push(t)})}let o=(i.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
404
|
+
`);pr.current?.feed(o)},[r.state?.messages,r.state?.isStreaming,r.state?.conversationId,Xn]),(0,Q.useEffect)(()=>{let t=r.dialog?.id??null;if(t!==null&&!ar.current.has(t)){if(ar.current.add(t),ar.current.size>64){let e=ar.current.values().next().value;e!==void 0&&ar.current.delete(e)}hu(`question`,Jn),Wu(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`),Xn.enabled&&Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceQuestion`),Xn)}},[r.dialog,Jn,Xn,e]),(0,Q.useEffect)(()=>{let t=r.question?.id??null,n=r.remoteQuestion?`${r.remoteQuestion.owner}:${r.remoteQuestion.id}`:null,i=new Set;t!==null&&!or.current.has(t)&&(or.current.add(t),i.add(Vn)),n!==null&&!or.current.has(n)&&(or.current.add(n),i.add(void 0));for(let e of r.conversations){if(!e.hasQuestion)continue;let n=e.questionId?`q:${e.questionId}`:`conv-q:${e.id}`;or.current.has(n)||(or.current.add(n),e.questionId&&or.current.add(e.questionId),t!==e.questionId&&i.add(e.sessionId))}if(or.current.size>64){let e=or.current.values().next().value;e!==void 0&&or.current.delete(e)}if(i.size>0){hu(`question`,Jn);for(let t of i)Wu(e(`notifyQuestionTitle`),e(`notifyQuestionBody`),`question`,t);Xn.enabled&&Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceQuestion`),Xn)}},[r.question,r.remoteQuestion,r.conversations,Vn,Jn,Xn,e]),(0,Q.useEffect)(()=>{let t=r.approval,n=t?.id??null;if(n!==null&&!sr.current.has(n)){if(sr.current.add(n),sr.current.size>64){let e=sr.current.values().next().value;e!==void 0&&sr.current.delete(e)}hu(`approval`,Jn);let r=typeof t?.toolName==`string`?t.toolName:``;Wu(e(`notifyApprovalTitle`),r?e(`notifyApprovalBodyTool`,{tool:r}):e(`notifyApprovalBody`),`approval`),Xn.enabled&&Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceApproval`),Xn)}},[r.approval,Jn,Xn,e]),(0,Q.useEffect)(()=>{let t=[...r.notices].reverse().find(e=>e.level===`error`);t&&t.id!==lr.current&&(lr.current=t.id,hu(`error`,Jn),Wu(e(`notifyErrorTitle`),e(`notifyErrorBody`),`error`),Xn.enabled&&Xn.announce&&!ju(Ru())&&dg(e(`ttsAnnounceError`),Xn))},[r.notices,Jn,Xn,e]);let hr=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{let e=r.state?.messages??[];for(let t of e){if(t.toolName!==`live_preview`||hr.current.has(t.id))continue;hr.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(g(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)}},[r.state?.messages,o]);let gr=(t,n,r,i=!1,a,s=!1)=>{if(se.current){dn({attachments:[{path:t,name:n,mode:r,isDir:i,...a?{lines:a}:{}}]})||o(`warning`,e(`nativeCliDisconnected`));return}let c=`${t}|${r}|${a?`${a.start}-${a.end}`:``}`;_(e=>e.some(e=>`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`===c)?e:[...e,{path:t,name:n,mode:r,isDir:i,...a?{lines:a}:{}}]);let l=r===`page`||r===`canvas`?n:t;!s&&l&&!se.current&&$t(`@${l} `)},_r=e=>{let t=``;_(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&&rn(`@${t}`)},vr=(0,Q.useCallback)(e=>(!e.type.startsWith(`list_`)&&!e.type.startsWith(`get_`)&&pt(null),i(e)),[i]),yr=(0,Q.useRef)(new Set),br=r.activeConversationId||r.state?.conversationId||``;(0,Q.useEffect)(()=>{let t=r.conversations.filter(e=>e.hasQuestion),n=new Set(t.map(e=>e.id)),i=new Set(t.map(e=>e.questionId).filter(Boolean));for(let e of yr.current)i.has(e)||yr.current.delete(e);for(let n of t){let t=`question-${n.id}`;if(n.id===br){KT(t,{silent:!0});continue}n.questionId&&yr.current.has(n.questionId)||GT({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&&yr.current.add(n.questionId)},onClick:()=>{vr({type:`switch_conversation`,id:n.id}),KT(t,{silent:!0})}})}qT(e=>{let t=e.data?.conversationId;return t?!n.has(t)||t===br:!1},{silent:!0})},[r.conversations,br,vr,e]);let xr=He(`chatUploadMaxMb`),[Sr,Cr]=(0,Q.useState)({}),wr=(0,Q.useRef)(0),Tr=(0,Q.useRef)(0),Er=(0,Q.useRef)(0),Dr=(0,Q.useCallback)(t=>{let n=Date.now();r.state?.model&&!r.state.model.vision&&n-Er.current>1e4&&(Er.current=n,o(`warning`,e(`imageNotSupported`)));let i=`paste-${++Tr.current}`;_(e=>[...e,{path:``,key:i,name:t.name,imageData:t.data,mimeType:t.mimeType}])},[r.state?.model,o,e]),kr=(0,Q.useCallback)(async t=>{for(let n of t){if(n.size>xr*1024*1024){o(`warning`,e(`fileTooLarge`,{name:n.name,size:xr}));continue}let t=String(++wr.current);Cr(e=>({...e,[t]:{name:n.name}}));try{let t=await Vh(n);t?Dr(t):o(`error`,e(`imageLoadFailed`,{name:n.name}))}catch{o(`error`,e(`imageLoadFailed`,{name:n.name}))}finally{Cr(e=>{let n={...e};return delete n[t],n})}}},[Dr,o,e,xr]),Ar=xr*1024*1024,jr=(0,Q.useRef)(0),Mr=(0,Q.useCallback)(async t=>{if(t.size>Ar){o(`warning`,e(`fileTooLarge`,{name:t.name,size:Ar/1024/1024}));return}let n=String(++wr.current);Cr(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&&Cr(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{Cr(e=>{let t={...e};return delete t[n],t})}let i=`upload-${++jr.current}`;_(e=>[...e,{path:``,key:i,name:t.name,fileData:r,size:t.size,mimeType:t.type||void 0}])},[Ar,o,e]),Nr=(0,Q.useCallback)(async e=>{for(let t of e)Bh(t.type)?await kr([t]):await Mr(t)},[kr,Mr]),Pr=(0,Q.useCallback)(async t=>{let n=ln();if(!n){o(`warning`,e(`nativeCliDisconnected`));return}for(let r of t){if(r.size>Ar){o(`warning`,e(`fileTooLarge`,{name:r.name,size:xr}));continue}try{let t=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result).replace(/^data:[^;]*;base64,/,``)),n.onerror=()=>t(n.error),n.onabort=()=>t(Error(`read aborted`)),n.readAsDataURL(r)});n.compose({attachments:[{path:``,name:r.name,fileData:t,size:r.size,mimeType:r.type||void 0}]})||o(`error`,e(`fileLoadFailed`,{name:r.name}))}catch{o(`error`,e(`fileLoadFailed`,{name:r.name}))}}},[Ar,xr,o,e]);(0,Q.useEffect)(()=>{let t=r.nativeCliPasteResult;t&&!t.ok&&o(`error`,e(`nativeCliPasteFailed`,{error:t.error??``}))},[r.nativeCliPasteResult,o,e]);let Fr=(0,Q.useCallback)((e,t,n)=>{i({type:`edit_message`,messageId:e,text:t,attachments:n})},[i]),Ir=(0,Q.useCallback)((e,t,n,r)=>{i({type:`queue_remove`,kind:e,text:t,index:n,id:r})},[i]),[Lr,Rr]=(0,Q.useState)([]),zr=(0,Q.useRef)(0),Br=(0,Q.useCallback)((e,t,n,r)=>{i({type:`queue_remove`,kind:e,text:t,index:n,id:r}),zr.current+=1;let a=id(t),o={text:a.text,seq:zr.current};if(a.quotes.length&&_(e=>sC(e,a.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:Ht()})))),a.attachments?.length){let e=a.attachments.filter(e=>e.type!==`vision-bridge`).map(e=>({path:e.path||e.url||``,name:e.name,mode:e.type===`page`?`page`:e.type===`canvas`?`canvas`:e.type===`conversation`?`conversation`:e.lines?`lines`:`reference`,lines:e.lines,key:Ht()}));e.length&&_(t=>sC(t,e))}Rr(e=>[...e.slice(-9),o])},[i]),Vr=(0,Q.useCallback)(()=>Ct(!0),[]),Hr=(0,Q.useCallback)(()=>_([]),[]),[Ur,Wr]=(0,Q.useState)(0),Gr=(0,Q.useCallback)(()=>{Hr(),Wr(e=>e+1)},[Hr]),Kr=(0,Q.useCallback)(()=>{let e=r.state?.queue?.steering??[],t=r.state?.queue?.followUp??[],n=[...e,...t];for(let e of n){zr.current+=1;let t=id(e);if(t.quotes?.length&&_(e=>sC(e,t.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:Ht()})))),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:Ht()}));e.length&&_(t=>sC(t,e))}Rr(e=>[...e.slice(-9),{text:t.text,seq:zr.current}])}i({type:`abort`})},[r.state?.queue?.steering,r.state?.queue?.followUp,i]);uE(r.state?.sessionId??``,Hr);let qr=(0,Q.useCallback)(_r,[]),Jr=(0,Q.useCallback)(async(e,t)=>{if(!t.startsWith(`data:image/png;base64,`))throw Error(`Invalid annotated image`);let n=await(await fetch(t)).blob(),r=`${e.name.replace(/\.[^.]+$/,``).replace(/-annotated$/,``)}-annotated`,i=await Vh(new File([n],`${r}.png`,{type:`image/png`}));if(!i||i.size>2097152)throw Error(`Annotated image exceeds the attachment limit`);let a={path:``,name:`${r}.${i.mimeType===`image/jpeg`?`jpg`:i.mimeType===`image/webp`?`webp`:`png`}`,key:e.key||Ht(),imageData:i.data,mimeType:i.mimeType,size:i.size};_(t=>t.map(t=>t===e?a:t))},[]),Yr=kr,Xr=Nr,Zr=(0,Q.useCallback)((e,t)=>i({type:`search_files`,reqId:e,query:t}),[i]),Qr=(0,Q.useCallback)(e=>gr(e.path,e.name,e.mode??`reference`,e.isDir??!1,e.lines,e.silent??!1),[]),$r=r.state?.model,ei=r.state?.thinkingLevel,ti=r.state?.availableThinkingLevels,ni=(0,Q.useMemo)(()=>$r?{model:$r,thinkingLevel:ei??`off`,availableThinkingLevels:ti??[]}:null,[$r,ei,ti]),ri=r.terminals.filter(e=>!e.nativeCli&&((e.ownerKind??`client`)===`client`||e.conversationId===(r.activeConversationId||r.state?.conversationId||``))).length,ii=(0,Q.useCallback)(()=>!r.ready||ri!==0?!1:(s.create({id:Ht(),conversationId:r.activeConversationId||r.state?.conversationId||``,title:e(`terminalTitle`,{n:1}),cwd:r.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null}),!0),[r.ready,r.state?.cwd,ri,e,s]);(0,Q.useEffect)(()=>{if(ur.current){if(H!==`terminal`||ri!==0){ur.current=!1;return}ii()&&(ur.current=!1)}},[ri,ii,H]);let ai=(0,Q.useCallback)((e,t)=>{if(l&&e!==`chat`&&e!==`devices`){o(`info`,`This conversation is open in read-only mode.`);return}if(e===`native-cli`){B(f);return}t?.skipAutoCreate?ur.current=!1:(ur.current=e===`terminal`&&ri===0,ur.current&&ii()&&(ur.current=!1)),R(e),pt(null)},[ri,ii,f,l,o]),oi=(0,Q.useCallback)(e=>{l||(B(e??f),pt(null))},[f,l]);return(0,$.jsxs)(`div`,{className:`app${Gn?` zen-mode`:``}`,"data-pi-anchor":`app`,onDragOver:e=>{Array.from(e.dataTransfer?.types??[]).includes(`Files`)&&(e.preventDefault(),I(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||I(!1)},onDrop:t=>{if(I(!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}if(se.current){Pr(n);return}let r=n.filter(e=>Bh(e.type)),i=n.filter(e=>!Bh(e.type));r.length>0&&kr(r),i.length>0&&Nr(i)},children:[(0,$.jsx)(Ys,{}),Gn&&(0,$.jsxs)(`button`,{type:`button`,className:`zen-exit-pill`,onClick:qn,title:e(`zenModeExitTip`),"aria-label":e(`zenModeExit`),children:[(0,$.jsx)(it,{}),(0,$.jsx)(`span`,{children:e(`zenModeExit`)})]}),F&&(0,$.jsx)(`div`,{className:`app-drop-overlay`,"aria-hidden":!0,children:(0,$.jsxs)(`span`,{children:[`📎 `,e(`dropHereToAttach`)]})}),(0,$.jsx)(Js,{chat:r,terminal:s,view:H,plugins:G,uiPrimary:me,uiOverflow:he,uiContextTopbar:K[`contextmenu.topbar`],onCreateCli:oi,onUiAction:Me,zenMode:Gn,onToggleZenMode:qn,onViewChange:ai,onOpenPanel:pt,onOpenSettings:()=>{Dt(void 0),Tt(!0)},onManagePlugins:()=>{Dt(`plugins`),Tt(!0)},onOpenBgTasks:()=>Cn(!0),onOpenGlobalSearch:()=>On(!0),onOpenIconEdit:()=>Pn(!0),onOpenSandboxModal:()=>kt(`create`),themes:Qn,theme:$n,onThemeChange:er,reloadThemes:tr}),z!==null&&(0,$.jsx)(Is,{cwd:z,disabled:ee,onClose:()=>{ee||B(null)},onCreate:async t=>{if(ee||z===null)return;V(!0);let n=await En(i,t,z);V(!1),n?B(null):o(`error`,e(`nativeCliCreateFailed`))}}),kn&&(0,$.jsx)(lE,{slots:K,layout:r.settings?.uiLayout,exclude:oa,onClose:()=>Pn(!1)}),r.protocolMismatch&&(0,$.jsxs)(`div`,{className:`protocol-banner`,children:[`⚠ `,e(`protocolMismatch`)]}),(0,$.jsxs)(`div`,{className:`notices`,children:[r.notices.map(e=>(0,$.jsx)(pk,{notice:e,onDismiss:a},e.id)),Jt&&(0,$.jsxs)(`div`,{className:`notice notice-info`,role:`status`,children:[(0,$.jsx)(`span`,{className:`notice-text`,children:Jt.text}),Jt.actions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let t=Xt.current;Xt.current=null,Yt(null);try{t?.resolve(e.id)}catch{}},children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:e(`close`),onClick:()=>{let e=Xt.current;Xt.current=null,Yt(null);try{e?.resolve(null)}catch{}},children:(0,$.jsx)(Be,{})})]}),ke.length>0&&(0,$.jsx)(`div`,{className:`notice-actions`,role:`toolbar`,children:ke.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=>Me(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:()=>Me(e),children:[e.icon?`${e.icon} `:``,e.badge??e.label]},e.id))})]}),(0,$.jsxs)(Jx,{currentModelId:$r?`${$r.provider}/${$r.id}`:null,children:[(0,$.jsx)(RT,{onAction:(e,t,n)=>Me(e,n,t)}),(0,$.jsxs)(`div`,{ref:ht,className:`layout`,style:{"--left-w":`${$e}px`,"--right-w":`${tt}px`},children:[gt?(0,$.jsx)(`div`,{className:`drawer-backdrop persistent${ft?` on`:``}`,onClick:()=>pt(null)}):ft&&(0,$.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>pt(null)}),(0,$.jsx)(uT,{side:`left`,onCreateCli:oi,items:Ae,chat:r,view:H,plugins:G,dropdownProps:{theme:$n,themes:Qn,onThemeChange:er,reloadThemes:tr},onViewChange:ai,onOpenPanel:pt,onOpenSettings:e=>{Dt(e),Tt(!0)},onOpenBgTasks:()=>Cn(!0),onOpenGlobalSearch:()=>On(!0),onUiAction:Me,uiContextTopbar:K[`contextmenu.topbar`],onThemeToggle:()=>er($n===`light`?null:`light`),onSoundToggle:()=>Yn({...Jn,enabled:!Jn.enabled}),zenMode:Gn,onToggleZenMode:qn}),(0,$.jsxs)(`div`,{className:`view-pane ${H===`chat`?``:`hidden`}`,children:[!gt&&ot&&(0,$.jsx)(Ck,{side:`left`,onClick:ut}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-left ${ft===`left`?`open`:``}${gt?``:ot?` hidden`:``}`,children:(0,$.jsx)(gb,{quickAskReferenceMenus:r.settings?.quickAskReferenceMenus!==!1,collapsible:!gt,onToggleCollapse:ut,panelSend:vr,onCreateCli:oi,active:!gt||ft===`left`,unreadConvKeys:mt,sessionFile:te?null:r.state?.sessionFile??null,conversations:r.conversations,elsewhere:r.elsewhere,sessions:r.sessions,projects:r.projects,projectSessions:r.projectSessions,projectSessionsHasMore:r.projectSessionsHasMore,engine:r.engine,pathCompletions:r.pathCompletions,activeConversationId:te?``:r.activeConversationId,sharedConversationOwner:r.state?.sharedConversation?.owner,activeGroupId:te,uiContextSession:K[`contextmenu.session`],uiLeftSessions:ge,uiContextProject:K[`contextmenu.project`],uiProjectsActions:_e,uiLeftProject:ve,uiRunningActions:J,uiHistoryActions:ye,uiSections:be,renderPluginSectionBody:Ne,uiLeftRunning:xe,uiLeftHistory:Se,uiPluginRunning:r.pluginPanelGroups,onPluginRunningAction:Pe,onUiAction:Me,presetNames:Oe,transition:Pt,onOpenSandboxModal:At})}),!gt&&!ot&&(0,$.jsx)(Sk,{side:`left`,width:$e,onResize:rt}),(0,$.jsxs)(`main`,{className:`${hn?`main wide-chat`:`main`}${vn?` hide-model-row`:``}${r.transition&&!r.transition.previewMessages?.length?` main-transitioning`:``}${bn?` main-minimal-empty`:``}`,children:[Object.entries(U).map(([e,t])=>{let n=ae&&r.state?.conversationId===e,a=n&&H===`chat`&&!r.transition;return(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(`div`,{className:`native-cli-main ${n?``:`hidden`}`,children:(0,$.jsx)(ek,{chat:r,terminal:s,send:i,conversationId:e,nativeCli:n&&r.state?.nativeCli?r.state.nativeCli:t.nativeCli,active:a,cwd:t.cwd,onAddFiles:Pr,pushNotice:o})})},e)}),ae&&r.state?.nativeCli&&!U[r.state.conversationId]&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(`div`,{className:`native-cli-main`,children:(0,$.jsx)(ek,{chat:r,terminal:s,send:i,conversationId:r.state.conversationId,nativeCli:r.state.nativeCli,active:H===`chat`&&!r.transition,cwd:r.state.cwd,onAddFiles:Pr,pushNotice:o})})}),!ae&&(0,$.jsx)(`div`,{className:`native-cli-chat-content`,children:te?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(fk,{roomId:te,active:H===`chat`,onBack:()=>ne(null)},te)}):(0,$.jsxs)($.Fragment,{children:[r.transition&&(0,$.jsxs)(`div`,{className:`workspace-transition-bar phase-${r.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,r.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:!X(t)&&r.transition.textEn?r.transition.textEn:r.transition.text}),(0,$.jsxs)(`span`,{className:`workspace-transition-pct`,children:[r.transition.progress,`%`]})]})]}),Te.length>0&&(0,$.jsx)(`div`,{className:`chat-header`,role:`toolbar`,children:tS(Te,Me)}),r.state?(0,$.jsxs)($.Fragment,{children:[!l&&r.state.sandbox&&(0,$.jsxs)(`div`,{className:`sandbox-banner`,role:`region`,"aria-label":r.state.sandbox.name,children:[(0,$.jsxs)(`div`,{className:`sandbox-banner-info`,children:[(0,$.jsxs)(`span`,{className:`sandbox-banner-title`,children:[(0,$.jsx)(Or,{className:`sandbox-banner-icon`,"aria-hidden":!0}),e(`sandboxBannerTitle`,{name:r.state.sandbox.name}),(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${r.state.sandbox.ephemeral?`ephemeral`:`permanent`}`,children:r.state.sandbox.ephemeral?e(`sandboxBadgeEphemeral`):e(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`sandbox-banner-desc`,children:r.state.sandbox.sourcePath?e(`sandboxBannerSourceDesc`,{source:r.state.sandbox.sourcePath}):e(`sandboxBannerBlankDesc`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-banner-actions`,children:[r.state.sandbox.ephemeral&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPersistTip`),onClick:()=>i({type:`persist_sandbox`,path:r.state?.sandbox?.path}),children:[(0,$.jsx)(u,{"aria-hidden":!0}),` `,e(`sandboxActionPersist`)]}),r.state.sandbox.sourcePath&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn primary`,title:e(`sandboxActionApplySourceTip`),onClick:()=>kt(`apply`),children:[(0,$.jsx)(n,{"aria-hidden":!0}),` `,e(`sandboxActionApplySource`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionPromoteTip`),onClick:()=>kt(`promote`),children:[(0,$.jsx)(St,{"aria-hidden":!0}),` `,e(`sandboxActionPromote`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:e(`sandboxActionResetTip`),onClick:()=>{let t=r.state?.sandbox;t&&window.confirm(e(`sandboxActionResetConfirm`,{name:t.name}))&&i({type:`reset_sandbox`,path:t.path})},children:[(0,$.jsx)(ue,{"aria-hidden":!0}),` `,e(`sandboxActionReset`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn danger`,title:e(`sandboxActionDestroyTip`),onClick:()=>{let t=r.state?.sandbox;t&&window.confirm(e(`sandboxActionDestroyConfirm`,{name:t.name}))&&i({type:`destroy_sandbox`,path:t.path})},children:[(0,$.jsx)(_t,{"aria-hidden":!0}),` `,e(`sandboxActionDestroy`)]})]})]}),r.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:br}),children:[`💾 `,e(`saveEphemeral`)]})]}),(0,$.jsx)(nC,{quickAskTranslateEnabled:r.settings?.quickAskTranslateEnabled!==!1,uiMessageActions:K[`message.actions`],uiContextMessage:K[`contextmenu.message`],uiContextToolCall:K[`contextmenu.toolcall`],uiToolCardFooter:K[`tool.card.footer`],uiChatEmpty:Ee,onUiAction:Me,preview:!!r.transition?.previewMessages?.length,state:r.transition?.previewMessages?.length?{...r.state,conversationId:r.transition.previewConversationId??r.transition.target,sessionFile:r.transition.previewSessionFile,historyStart:0,historyTotal:r.transition.previewMessages.length,messages:r.transition.previewMessages,streamingMessage:null,isStreaming:!1,pendingQuestion:null,pendingApproval:null}:r.state,liveOutputs:r.liveOutputs,toolStatuses:r.toolStatuses,onEdit:Fr,onKillBash:()=>{let e=r.state?.conversationId;e&&!r.transition&&i({type:`abort_bash`,conversationId:e})},onRetry:()=>{if(i({type:`retry_last`})){let e=r.state?.model;e&&qc(`${e.provider}/${e.id}`)}},onRemoveQueued:Ir,onRecallQueued:Br,thinkingWrap:r.settings?.thinkingWrap??!0,toolsWrap:r.settings?.toolsWrap??!0,toolImages:r.settings?.toolImagesEnabled??!0,keepRecent:r.settings?.keepRecentMessages,reversePagination:r.settings?.reversePagination??!1,minimalNewChat:r.settings?.minimalNewChat??!1,jumpTarget:Fn,onJumpDone:()=>In(null),urlJumpMessageId:Ln&&Ln.sessionId===r.state.sessionId?Ln.messageId:null,onUrlJumpDone:()=>Rn(null),userPromptNonce:Ur},r.transition?.previewMessages?.length?r.transition.previewConversationId??r.transition.target:r.state.conversationId??`boot`)]}):(0,$.jsx)(`div`,{className:`boot-wait`,children:r.ready?e(`loadingSession`):e(`connectingServer`)}),r.settings?.goalModeEnabled!==!1&&(0,$.jsx)(`div`,{className:`goalbar-slot`,children:(0,$.jsx)(Uw,{goal:r.goal,models:r.models,modelsLoading:r.modelsLoading,activeConversationId:r.activeConversationId,uiGoalbarActions:we,onUiAction:Me})}),r.dialog&&(0,$.jsx)(gT,{dialog:r.dialog}),Rt&&(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":Rt.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:e(`pluginRequest`)}),Rt.title&&(0,$.jsx)(`span`,{className:`dialog-title`,children:Rt.title}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{let e=Bt.current;Bt.current=null,zt(null);try{e?.kind===`confirm`?e.resolve(!1):e?.resolve({ok:!1})}catch{}},children:`✕`})]}),Rt.kind===`select`&&(0,$.jsxs)(`div`,{className:`dialog-options`,children:[(Rt.options??[]).map((e,t)=>{let n=Rt.multi?Ut.includes(t):!1;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${n?`sel`:``}`,title:e.description,onClick:()=>{if(Rt.multi){Wt(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);return}let n=Bt.current;Bt.current=null,zt(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)}),(Rt.options??[]).length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:e(`noOptions`)}),Rt.multi&&(0,$.jsx)(`div`,{className:`dialog-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=Bt.current,t=(e?.options??[]).filter((e,t)=>Ut.includes(t)).map(e=>e.label);Bt.current=null,zt(null);try{e?.resolve({ok:!0,selected:t})}catch{}},children:e(`ok`)})})]}),Rt.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=Bt.current;Bt.current=null,zt(null);try{e?.resolve(!1)}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=Bt.current;Bt.current=null,zt(null);try{e?.resolve(!0)}catch{}},children:e(`ok`)})]})}),Rt.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-body`,children:[(0,$.jsx)(`input`,{className:`dialog-input`,value:Kt,placeholder:Rt.placeholder||e(`inputPlaceholder`),autoFocus:!0,onChange:e=>qt(e.target.value),onKeyDown:e=>{if(e.key===`Enter`&&!e.nativeEvent.isComposing){let e=Bt.current;Bt.current=null,zt(null);try{e?.resolve({ok:!0,value:Kt})}catch{}}}}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=Bt.current;Bt.current=null,zt(null);try{e?.resolve({ok:!1})}catch{}},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=Bt.current;Bt.current=null,zt(null);try{e?.resolve({ok:!0,value:Kt})}catch{}},children:e(`ok`)})]})]})]}),(0,$.jsx)(FT,{questions:yT(r.questionQueue,r.question,r.remoteQuestion,r.globalQuestions,r.state?.sharedConversation?.owner),activeConversationId:br,mode:r.settings?.questionPresentation??`queue`}),(0,$.jsx)(DE,{approvals:bT(r.approvals,r.globalApprovals,r.state?.sharedConversation?.owner),activeConversationId:br,mode:r.settings?.toolApprovalPresentation??`all`}),(0,$.jsx)(AE,{plan:r.activeConversationId&&r.state?.conversationId!==r.activeConversationId?null:r.state?.plan}),Object.entries(Sr).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)),l?(0,$.jsx)(`div`,{className:`sound-hint`,role:`status`,children:`Read-only conversation. Questions and approvals remain available above.`}):(0,$.jsx)(Hw,{composerLeading:K[`composer.leading`],composerActions:K[`composer.actions`],onUiAction:Me,streaming:r.state?.isStreaming??!1,onAbort:Kr,planMode:r.state?.planMode??!1,messages:r.state?.messages??mk,slashCommands:r.slashCommands,modelState:ni,models:r.models,modelsLoading:r.modelsLoading,providerKeys:r.providerKeys,providers:r.providers,defaultModel:r.defaultModel??void 0,attachments:h,onRemoveAttachment:qr,onAnnotateImage:Jr,onAddImageFiles:Yr,onAddLocalFiles:Xr,onAddPathAttachment:Qr,fileSearch:r.fileSearch,onSearchFiles:Zr,onNotice:o,onManageModels:Vr,onSent:Gr,quickPhrases:r.settings?.quickPhrases??[],quickPhrasesEnabled:!Gn&&(r.settings?.quickPhrasesEnabled??!0)&&(!r.settings?.minimalNewChat||(r.state?.messages?.length??0)>0||!!r.state?.streamingMessage),recallDrafts:Lr,dshPermCurrent:r.state?.permission??null,dshPermOptions:r.dshPermission?.options??void 0,dshPermDefault:r.dshPermission?.defaultPreset,dshPreset:r.state?.agentPreset??null,dshPresets:r.dshPresets?.presets??void 0,dshPresetDefault:r.dshPresets?.defaultPreset,dshBlank:(r.state?.messages?.length??0)===0,conversationId:r.activeConversationId||r.state?.conversationId||``,sessionDraft:r.state?.draft??null,sessionId:r.state?.sessionId??``,preserveDraftAcrossConversations:r.settings?.preserveDraftAcrossConversations??!1})]})})]}),!gt&&!ct&&(0,$.jsx)(Sk,{side:`right`,width:tt,onResize:at}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-right ${ft===`right`?`open`:``}${gt?``:ct?` hidden`:``}`,children:(0,$.jsx)(Jb,{quickAskReferenceMenus:r.settings?.quickAskReferenceMenus!==!1,collapsible:!gt,onToggleCollapse:dt,panelSend:vr,files:r.files,fileSearch:r.fileSearch,fileChanged:r.fileChanged,widgets:r.widgets,onAttach:(e,t,n,r)=>{pt(null),gr(e,t,n,r)},onPreview:(e,t)=>{pt(null),k(e,t)},onNotice:(e,t)=>o(e,t),uiRightPanelTabs:K[`rightpanel.tabs`],uiContextFile:K[`contextmenu.file`],plugins:G,pluginsEpoch:r.pluginsEpoch,send:i})}),!gt&&ct&&(0,$.jsx)(Ck,{side:`right`,onClick:dt})]}),(0,$.jsx)(`div`,{className:`view-pane ${H===`terminal`?``:`hidden`}`,children:(0,$.jsx)(aD,{active:H===`terminal`,children:(0,$.jsx)($O,{chat:r,terminal:s,uiTerminalToolbar:Ce,onUiAction:Me})})}),(0,$.jsx)(`div`,{className:`view-pane ${H===`git`?``:`hidden`}`,children:(0,$.jsx)(aD,{active:H===`git`,children:(0,$.jsx)(tk,{chat:r,terminal:s,active:H===`git`,onSwitchToTerminal:()=>R(`terminal`),uiScmToolbar:Y,onUiAction:Me})})}),(0,$.jsx)(`div`,{className:`view-pane ${H===`canvas`?``:`hidden`}`,children:(0,$.jsx)(aD,{active:H===`canvas`,children:(0,$.jsx)(ik,{send:i,active:H===`canvas`,models:r.models,defaultModel:r.defaultModel,installedSkills:r.settings?.skills,projects:r.projects,workspaceRoots:r.state?.workspaceRoots??[],pathCompletions:r.pathCompletions,currentCwd:r.state?.cwd||`.`})})}),H===`worktrees`&&(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsx)(Xw,{worktree:r.state?.worktree,onRefresh:ce,onSwitch:e=>{le.current={source:r.state?.cwd??``,target:e},i({type:`switch_worktree`,path:e})},onRemove:e=>i({type:`remove_worktree`,path:e}),onBack:()=>{R(`chat`),sn()}})}),(0,$.jsx)(`div`,{className:`view-pane ${H===`devices`?``:`hidden`}`,children:(0,$.jsx)(aD,{active:H===`devices`,children:(0,$.jsx)(nk,{pathCompletions:r.pathCompletions,plugins:r.plugins,pluginsEpoch:r.pluginsEpoch})})}),Fe.map(e=>{let t=`plugin:${e.info.id}`;return(0,$.jsx)(`div`,{className:`view-pane ${H===t?``:`hidden`}`,children:(0,$.jsx)(IT,{entry:e})},e.info.id)}),H.startsWith(`plugin:`)&&!Fe.some(e=>`plugin:${e.info.id}`===H)&&(0,$.jsx)(LT,{pluginId:H.slice(7),info:r.plugins.find(e=>`plugin:${e.id}`===H),epoch:r.pluginsEpoch,failed:Le.includes(H.slice(7))}),(0,$.jsx)(uT,{side:`right`,onCreateCli:oi,items:je,chat:r,view:H,plugins:G,dropdownProps:{theme:$n,themes:Qn,onThemeChange:er,reloadThemes:tr},onViewChange:ai,onOpenPanel:pt,onOpenSettings:e=>{Dt(e),Tt(!0)},onOpenBgTasks:()=>Cn(!0),onOpenGlobalSearch:()=>On(!0),onUiAction:Me,uiContextTopbar:K[`contextmenu.topbar`],onThemeToggle:()=>er($n===`light`?null:`light`),onSoundToggle:()=>Yn({...Jn,enabled:!Jn.enabled}),zenMode:Gn,onToggleZenMode:qn})]})]}),(0,$.jsx)(Qw,{onCreateCli:oi,chat:r,bottombarItems:K.bottombar,onUiAction:Me,onOpenSettings:()=>{Dt(void 0),Tt(!0)},onViewChange:ai,onOpenGlobalSearch:()=>On(!0),onOpenBgTasks:()=>Cn(!0)}),w&&v&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(dk,{file:w,files:v,activeIndex:x,onSelectFile:C,composerSessionId:r.state?.sessionId,content:r.fileContent,onAddLines:(e,t,n,r)=>gr(e,t,`lines`,!1,{start:n,end:r}),onAttach:(e,t,n)=>gr(e,t,n),onClose:()=>b(null),uiFilePreviewToolbar:De,onUiAction:Me})}),T&&(0,$.jsx)(oD,{file:T.file,plugin:T.plugin,declaration:T.declaration,epoch:r.pluginsEpoch,send:i,onClose:()=>E(null),onFallback:()=>{E(null),b([T.file]),C(0)}}),M&&(0,$.jsx)(lO,{...M,composerSessionId:r.state?.sessionId,onClose:()=>N(null)}),r.ready&&r.state&&r.state.piConfigured===!1&&!ae&&!Z&&!xt&&!Zt()&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(ak,{piConfigured:r.state.piConfigured,piAgentInstalled:r.state.piAgentInstalled,providers:r.providers,providerOAuthFlows:r.providerOAuthFlows,providerOAuthResults:r.providerOAuthResults,installResult:r.installResult,onClose:bt})}),xt&&!l&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(ok,{providers:r.modelsConfig,providerStatus:r.providers,providerKeys:r.providerKeys,providerOAuthFlows:r.providerOAuthFlows,providerOAuthResults:r.providerOAuthResults,fetchModelsResult:r.fetchModelsResult,testModelConnectionResult:r.testModelConnectionResult,enrichModelsResult:r.enrichModelsResult,enrichModelsProgress:r.enrichModelsProgress,refreshBuiltinResult:r.refreshBuiltinResult,refreshProviderResult:r.refreshProviderResult,appendBuiltinResult:r.appendBuiltinResult,cloneProviderResult:r.cloneProviderResult,defaultModel:r.defaultModel,onClose:()=>Ct(!1)})}),wt&&!l&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(sk,{chat:r,terminal:s,initialSection:Et,onSwitchToTerminal:()=>R(`terminal`),onClose:()=>Tt(!1),onOpenIconEdit:()=>Pn(!0),onOpenManageModels:()=>{Tt(!1),Ct(!0)},sound:Jn,onSoundChange:Yn,tts:Xn,onTtsChange:Zn})}),Sn&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(ck,{servers:r.bgServers,projectScripts:r.projectScripts,plugins:r.plugins,epoch:r.pluginsEpoch,send:i,onUiAction:Me,autoCleanupMin:r.settings?.bgAutoCleanupMin??0,onClose:()=>Cn(!1)})}),(0,$.jsx)(BE,{}),(0,$.jsx)(XE,{}),(0,$.jsx)(EE,{}),r.tuiOverlay&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(lk,{overlay:r.tuiOverlay})}),qe&&(0,$.jsx)(iD,{entry:qe,pluginView:Je?Fe.find(e=>e.info.id===Je):void 0,onUiAction:(e,t)=>{Me(e,t),Ve(null)},onClose:()=>Ve(null)}),(0,$.jsx)(aD,{active:Tn,children:(0,$.jsx)(uk,{open:Tn,projects:r.projects,fileSearch:r.fileSearch,sessionSearch:r.sessionSearch,onClose:()=>On(!1),onSwitchSession:(e,t)=>{i({type:`switch_session`,path:e});let n=t&&t[0];In(n?{path:e,role:n.role,timestamp:n.timestamp}:null)},onSwitchProject:e=>{i({type:`set_cwd`,path:e})},onPreviewFile:(e,t)=>{k(e,t)},onOpenFolder:e=>{On(!1),lt(e=>{if(e)try{localStorage.setItem(bk(`right`),`0`)}catch{}return!1}),pt(null),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(`pi:open-folder`,{detail:{path:e}}))},0)}})}),Ue&&(0,$.jsx)(lo,{currentCwd:Ue.initialPath||r.state?.cwd||``,pathCompletions:r.pathCompletions,workspaceRoots:r.state?.workspaceRoots??[],onClose:()=>{Ue.resolve({ok:!1,canceled:!0}),We(null)},onSelectDirectory:e=>{Ue.resolve({ok:!0,path:e}),We(null)},onCreateProject:e=>{i({type:`make_dir`,path:e}),Ue.resolve({ok:!0,path:e}),We(null)},mode:`project`,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:e(`projectPickerTitle`)}),Ge&&(0,$.jsx)(vE,{currentModelId:Ge.currentModelId,models:r.models,modelsLoading:r.modelsLoading,providerKeys:r.providerKeys,providers:r.providers,onManageModels:()=>Ct(!0),defaultModel:r.defaultModel,onClose:()=>{Ge.resolve({ok:!1,canceled:!0}),Ke(null)},onSelect:(e,t)=>{Ge.resolve({ok:!0,modelId:e,name:t?.name,provider:t?.provider}),Ke(null)}}),re&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(rk,{onClose:()=>ie(!1)})}),(pn||an||Ft)&&(0,cr.createPortal)((0,$.jsxs)(`div`,{className:`modal-backdrop perm-modal-backdrop`,style:{zIndex:mn},children:[pn&&(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:()=>fn(pn.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[pn.family===`net`?e(`pluginPermBodyNet`).replace(`{plugin}`,pn.pluginId).replace(`{hosts}`,(pn.hosts??[]).join(`, `)):e(`pluginPermBodyLlm`).replace(`{plugin}`,pn.pluginId).replace(`{models}`,(pn.models??[]).length>0?` ${(pn.models??[]).join(`, `)}`:``),pn.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:pn.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>fn(pn.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>fn(pn.id,!0),children:e(`pluginPermOnce`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>fn(pn.id,!0,!0),children:e(`pluginPermAlways`)})]})]})]}),an&&(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:()=>nn(an.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginGrantRequestBody`).replace(`{plugin}`,an.pluginId).replace(`{path}`,an.path),an.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:an.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>nn(an.id,!1),children:e(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>nn(an.id,!0),children:e(`pluginGrantAllow`)})]})]})]}),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(`pluginSessionGrantTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:e(`cancel`),onClick:()=>{Lt.current=null,Ft.resolve(!1),It(null)},children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[e(`pluginSessionGrantBody`).replace(`{path}`,Ft.path),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{Lt.current=null,Ft.resolve(!1),It(null)},children:e(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{Lt.current=null,Ft.resolve(!0),It(null)},children:e(`ok`)})]})]})]})]}),document.body),!wt&&Object.values(r.pluginJobs??{}).some(e=>e.phase!==`done`)&&(0,$.jsxs)(`div`,{className:`active-plugin-jobs-bar`,onClick:()=>{Dt(`plugins`),Tt(!0)},title:e(`pluginJobRunning`),children:[(0,$.jsx)(ue,{className:`spin`}),(0,$.jsxs)(`span`,{className:`active-plugin-jobs-title`,children:[e(`pluginJobRunning`),`:`,` `,Object.values(r.pluginJobs??{}).filter(e=>e.phase!==`done`).map(e=>e.pluginId).join(`, `)]}),(()=>{let e=Object.values(r.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})()]}),Ot&&(0,$.jsx)(qw,{mode:Ot,currentCwd:r.state?.cwd,currentSandbox:r.state?.sandbox,sandboxDiff:r.sandboxDiff,projects:r.projects,send:i,onClose:()=>kt(null)}),(0,$.jsx)(cE,{settings:r.settings,clientId:yy(),currentConversation:r.activeConversationId||r.state?.conversationId?{kind:`conversation`,conversationId:r.activeConversationId||r.state.conversationId}:void 0,fallbackModel:r.state?.model?`${r.state.model.provider}/${r.state.model.id}`:void 0}),(0,$.jsx)(Jw,{}),(0,$.jsx)($T,{})]})}function Ak(){typeof document<`u`&&(jk(Mk()),Pk())}function jk(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty(`--msgs-gutter`,`${Math.round(e*100)/100}px`)}function Mk(){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 Nk(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 Pk(){let e=()=>{let e=document.querySelector(`.messages`);return e?(jk(Nk(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 Fk(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 Ik(e,t){let n=!1;return r=>{if(!Fk(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 Lk(e){let t=Ik(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 Rk=y()?()=>!1:Lk(`20261112T05452`),zk=class extends Q.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){Rk(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}};if(Ft(),y()){let e=()=>{wu().catch(e=>console.warn(`Push event settings failed:`,e))};e(),window.addEventListener(`pi-web-ui:sound-settings`,e)}function Bk(){qt(Kt()),(0,lr.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(zk,{children:(0,$.jsx)(Te,{children:(0,$.jsx)(kk,{})})})}))}EO(),Yt(),Ak(),sr?or(window).then(Bk):Bk(),!y()&&!sr&&`serviceWorker`in navigator&&window.addEventListener(`load`,()=>{let e=F();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(e=>{console.warn(`Service worker registration failed:`,e)})});export{dg as $,Oi as $t,aw as A,ac as At,yy as B,oa as Bt,kw as C,Cc as Ct,fw as D,_c as Dt,xw as E,Oc as Et,bC as F,Do as Ft,Lv as G,ma as Gt,Rv as H,Ea as Ht,nC as I,go as It,Q_ as J,Ri as Jt,Tv as K,Xi as Kt,rS as L,_o as Lt,kC as M,rs as Mt,TC as N,ns as Nt,_w as O,hc as Ot,EC as P,Oo as Pt,Qh as Q,_i as Qt,tS as R,vo as Rt,Pw as S,Bc as St,Sw as T,Dc as Tt,Mv as U,ja as Ut,Av as V,aa as Vt,jv as W,Aa as Wt,K_ as X,xi as Xt,nv as Y,yi as Yt,Qg as Z,vi as Zt,tT as _,Tu as _t,fO as a,gm as at,Nw as b,nu as bt,DO as c,qd as ct,OD as d,vu as dt,ki as en,Kh as et,RD as f,Lu as ft,IT as g,Eu as gt,CD as h,Ou as ht,ZO as i,Am as it,MC as j,as as jt,$C as k,ic as kt,MO as l,Kd as lt,ND as m,zu as mt,zO as n,vr as nn,Jm as nt,dO as o,_m as ot,UD as p,Su as pt,ev as q,Yi as qt,KO as r,dr as rn,wm as rt,mO as s,rp as st,WO as t,Ti as tn,qh as tt,lO as u,Ku as ut,nT as v,Cu as vt,Aw as w,wc as wt,Fw as x,nl as xt,Hw as y,hu as yt,Db as z,ho as zt};
|