pop-agent 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/server/asr/bridge.js +135 -188
  2. package/dist/server/asr/routes.js +20 -11
  3. package/dist/server/computer/helper-client.js +3 -2
  4. package/dist/server/snapshot/state.js +3 -0
  5. package/package.json +2 -8
  6. package/web/dist/assets/{architecture-WOLXFQ4H-DwHKr8GA.js → architecture-WOLXFQ4H-DOSQge0o.js} +1 -1
  7. package/web/dist/assets/{blockDiagram-RJAE7QA3-CA2AOM6-.js → blockDiagram-RJAE7QA3-DJFf5WSV.js} +1 -1
  8. package/web/dist/assets/channel-Dys6KAxG.js +1 -0
  9. package/web/dist/assets/{chunk-55XCU76K-DlITu1ZH.js → chunk-55XCU76K-BymFzRwu.js} +1 -1
  10. package/web/dist/assets/{chunk-7S6XSTFO-DzX1XF3_.js → chunk-7S6XSTFO-0TGPJxiv.js} +1 -1
  11. package/web/dist/assets/{chunk-AQDTSKZB-BdEDejS-.js → chunk-AQDTSKZB-C3NroFBT.js} +1 -1
  12. package/web/dist/assets/{chunk-DSNLSHJZ-Chj2PD0m.js → chunk-DSNLSHJZ-C_LIPn61.js} +1 -1
  13. package/web/dist/assets/{chunk-HNE4Q36P-V3jylrEv.js → chunk-HNE4Q36P-riaksE6p.js} +1 -1
  14. package/web/dist/assets/{chunk-VQ5W62QI-BiWZxVe5.js → chunk-VQ5W62QI-D1v-PJLW.js} +1 -1
  15. package/web/dist/assets/{chunk-WQQL4CDK-BtyaHLI7.js → chunk-WQQL4CDK-Dv8ocEd6.js} +1 -1
  16. package/web/dist/assets/{chunk-ZAUX2LTX-DS3wpSTy.js → chunk-ZAUX2LTX-DP4s36LS.js} +1 -1
  17. package/web/dist/assets/{chunk-ZCHMQSOR-at82jgqF.js → chunk-ZCHMQSOR-CgvPm9f1.js} +1 -1
  18. package/web/dist/assets/{classDiagram-v2-4MYWR3UA-CTgR1e3M.js → classDiagram-v2-4MYWR3UA-BbG5SHcI.js} +1 -1
  19. package/web/dist/assets/{cynefin-EF2NZ3EQ-Pg-c-yVE.js → cynefin-EF2NZ3EQ-DImLnJIk.js} +1 -1
  20. package/web/dist/assets/{dagre-NK4GIZVX-B0Ivt5Pn.js → dagre-NK4GIZVX-DKVcPJLn.js} +1 -1
  21. package/web/dist/assets/{diagram-I5XIIV2D-jE6SNlbX.js → diagram-I5XIIV2D-Cgadlzhg.js} +1 -1
  22. package/web/dist/assets/{diagram-RJA3I4VV-DQJNgW0u.js → diagram-RJA3I4VV-_sRGhjHY.js} +1 -1
  23. package/web/dist/assets/{elk-QONTBCTQ-KOJVoDyP.js → elk-QONTBCTQ-m1jnHGpZ.js} +1 -1
  24. package/web/dist/assets/{erDiagram-KYQIGQAA-DNUqfe2J.js → erDiagram-KYQIGQAA-BJA55Q8F.js} +1 -1
  25. package/web/dist/assets/{eventmodeling-K75KTNOO-DnxXCUaf.js → eventmodeling-K75KTNOO-B0sNQJ7K.js} +1 -1
  26. package/web/dist/assets/{flowDiagram-IUGLLWBU-CRLc8ozS.js → flowDiagram-IUGLLWBU-DQTCQwSE.js} +1 -1
  27. package/web/dist/assets/{ganttDiagram-R7GPNTJY-DDLhSPGT.js → ganttDiagram-R7GPNTJY-DwG27iiU.js} +1 -1
  28. package/web/dist/assets/{gitGraph-VSP46ZUC-BjfoZeXP.js → gitGraph-VSP46ZUC-XxCjGklF.js} +1 -1
  29. package/web/dist/assets/{gitGraphDiagram-PDYL7XHY-6uZGw3lU.js → gitGraphDiagram-PDYL7XHY-juq_nFAa.js} +1 -1
  30. package/web/dist/assets/{index-CQ1VhLwx.js → index-D-YnULfY.js} +27 -27
  31. package/web/dist/assets/{info-OHQRW6UA-BMDHcIvy.js → info-OHQRW6UA-BGvjB5Yf.js} +1 -1
  32. package/web/dist/assets/{infoDiagram-MVDRKAX5-C2d1Uwhn.js → infoDiagram-MVDRKAX5-BPn-AsQi.js} +1 -1
  33. package/web/dist/assets/{journeyDiagram-BOSHW7O7-BAE_nPCd.js → journeyDiagram-BOSHW7O7-BXvjbozA.js} +1 -1
  34. package/web/dist/assets/{kanban-definition-FNSA4HC5-C2Z3ejvx.js → kanban-definition-FNSA4HC5-CxyIdAwF.js} +1 -1
  35. package/web/dist/assets/{line-DHlXL-f4.js → line-IQmg25td.js} +1 -1
  36. package/web/dist/assets/{mermaid-parser.core-CxD9DMnU.js → mermaid-parser.core-DZwBblMg.js} +3 -3
  37. package/web/dist/assets/{mermaid.core-CdVzG6_M.js → mermaid.core-CQFwDpsY.js} +4 -4
  38. package/web/dist/assets/{packet-JDAUHWVQ-Cx23kBS5.js → packet-JDAUHWVQ-DgkYilva.js} +1 -1
  39. package/web/dist/assets/{pie-XZMESJXO-BDdtcaza.js → pie-XZMESJXO-B3VKO2xO.js} +1 -1
  40. package/web/dist/assets/{pieDiagram-GNMPY74T-DRqt_o8d.js → pieDiagram-GNMPY74T-BveSF0g-.js} +1 -1
  41. package/web/dist/assets/{quadrantDiagram-D57K4MC3-Cq3-_E3T.js → quadrantDiagram-D57K4MC3-BQWlPpUC.js} +1 -1
  42. package/web/dist/assets/{radar-ABXABTNO-yJ_gp7Uq.js → radar-ABXABTNO-CN_6P1P3.js} +1 -1
  43. package/web/dist/assets/{railroad-I3PHUGI6-BFVVDyfL.js → railroad-I3PHUGI6-B9PNW16c.js} +1 -1
  44. package/web/dist/assets/{railroad-abnf-LNEFI6M7-BhhpD6rl.js → railroad-abnf-LNEFI6M7-CTmCJfja.js} +1 -1
  45. package/web/dist/assets/{railroad-ebnf-DWYD2UWJ-os_iV6TA.js → railroad-ebnf-DWYD2UWJ-CoEhN_zz.js} +1 -1
  46. package/web/dist/assets/{railroad-peg-JR7BVNR7-kex9mDBE.js → railroad-peg-JR7BVNR7-BQYjO9-Q.js} +1 -1
  47. package/web/dist/assets/{requirementDiagram-EQYSW5RA-BnDM54-F.js → requirementDiagram-EQYSW5RA-DWCQ25jk.js} +1 -1
  48. package/web/dist/assets/{sankeyDiagram-SY24JHO5-CMQmL2Tu.js → sankeyDiagram-SY24JHO5-DsBwLv8a.js} +1 -1
  49. package/web/dist/assets/{sequenceDiagram-BLEHNHQU-Dqhxl46T.js → sequenceDiagram-BLEHNHQU-CXrCzr9_.js} +1 -1
  50. package/web/dist/assets/{stateDiagram-v2-A6IESKWZ-D1u1qdD7.js → stateDiagram-v2-A6IESKWZ-C8wl0PRO.js} +1 -1
  51. package/web/dist/assets/{timeline-definition-JXYKGLGB-DEjsSeWV.js → timeline-definition-JXYKGLGB-syLevD3_.js} +1 -1
  52. package/web/dist/assets/{treeView-D4JQ5SDB-BXYISxgj.js → treeView-D4JQ5SDB-D5Dhd9U9.js} +1 -1
  53. package/web/dist/assets/{treemap-SAJKECNS-B6BJK2c0.js → treemap-SAJKECNS-MiXU26tY.js} +1 -1
  54. package/web/dist/assets/{wardley-7MLQ67FV-DsjBYeKs.js → wardley-7MLQ67FV-DFAjR6qV.js} +1 -1
  55. package/web/dist/assets/{xychartDiagram-4URNHDU4-CBbRqTE2.js → xychartDiagram-4URNHDU4-DZzoyQQ0.js} +1 -1
  56. package/web/dist/index.html +1 -1
  57. package/dist/server/asr/install.js +0 -188
  58. package/dist/server/asr/paths.js +0 -101
  59. package/helper/asr/Info.plist +0 -24
  60. package/helper/asr/build.sh +0 -59
  61. package/helper/asr/main.swift +0 -279
  62. package/helper/asr/release/ASRBridge.zip +0 -0
  63. package/web/dist/assets/channel-PVcvMEH-.js +0 -1
@@ -1,26 +1,26 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-CdVzG6_M.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/chunk-DUW6YSOI-Dgx8z5s3.js","assets/src-BWF7jMDv.js","assets/rolldown-runtime-COiEfhsA.js","assets/chunk-DSNLSHJZ-Chj2PD0m.js","assets/chunk-ZAUX2LTX-DS3wpSTy.js","assets/chunk-AQDTSKZB-BdEDejS-.js","assets/chunk-7S6XSTFO-DzX1XF3_.js","assets/math-Dh0H2mym.js","assets/chunk-J5ZVWO5B-oDCd-gWO.js","assets/chunk-WQQL4CDK-BtyaHLI7.js","assets/line-DHlXL-f4.js","assets/path-fybaL0A-.js","assets/array-BifhSqXX.js","assets/chunk-HNE4Q36P-V3jylrEv.js"])))=>i.map(i=>d[i]);
2
- import{i as e,n as t,r as n,t as r}from"./react-TO3cgmuO.js";import{a as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,s as g,u as _}from"./highlight-DMv0JmTA.js";import{n as v,r as y,t as b}from"./markdown-Bcx45PNe.js";import{n as x,t as S}from"./xterm-C3-Bm0Yw.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)}})();var C=e(),w=t(),T=`https://github.com/duzhenxun/pop-agent`,E=`npm -g install pop-agent@latest`;function D(e){let t=A(e);return t.length===0?e:t[t.length-1]??e}function O(e){let t=A(e);return t.length<=1?``:t.slice(0,-1).join(`/`)}function k(e,t){let n=A(e);return n.length<=t?e:`…/${n.slice(-t).join(`/`)}`}function A(e){return e.split(/[\\/]+/).filter(e=>e!==``)}function j(e){let t=e.trim();if(t===``)return``;let n=/^[A-Za-z]:/.test(t)||!t.startsWith(`/`)&&t.includes(`\\`),r=n?`\\`:`/`,i=t.replace(n?/[\\/]+/g:/\/+/g,r);return i===r||/^[A-Za-z]:[\\/]$/.test(i)||/^[\\/]{2}$/.test(i)?i:i.replace(n?/[\\/]+$/:/\/+$/,``)}function M(){return typeof navigator<`u`&&/windows/i.test(navigator.userAgent)}var N=2,P=6,F=10,I=500,L=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function R(e,t,n=!0){let r=(0,C.useRef)(null),i=(0,C.useRef)(n);i.current=n;let a=(0,C.useRef)(!0),[o,s]=(0,C.useState)(!0),c=(0,C.useRef)(t),l=(0,C.useRef)(-1),u=(0,C.useRef)(null),d=(0,C.useRef)(0),f=(0,C.useRef)(0),p=(0,C.useRef)(0),m=(0,C.useRef)(null),h=(0,C.useRef)(0),[g,_]=(0,C.useState)(0),v=(0,C.useCallback)(e=>{let t=u.current,n=Math.max(0,e.scrollHeight-h.current-e.clientHeight),r=t===null?0:Math.max(0,t-n),i=r===0?0:Math.ceil(r/16)*16;return i!==h.current&&(h.current=i,_(i),!0)},[]),y=(0,C.useCallback)(()=>{u.current=null,d.current=0,f.current&&=(cancelAnimationFrame(f.current),0),h.current!==0&&(h.current=0,_(0))},[]),b=(0,C.useCallback)(()=>{let e=r.current;if(!e||!a.current||!i.current)return;let t=u.current;if(t!==null){if(e.scrollHeight-h.current-(t+e.clientHeight)<=0){if(v(e))return;e.scrollTo({top:t}),l.current=e.scrollTop;return}y()}let n=Math.max(0,e.scrollHeight-h.current-e.clientHeight);e.scrollTo({top:n}),l.current=e.scrollTop},[v,y]),x=(0,C.useCallback)(()=>{p.current||=requestAnimationFrame(()=>{p.current=0,b()})},[b]),S=(0,C.useCallback)(()=>{f.current=0;let e=r.current,t=u.current;!e||t===null||Math.abs(e.scrollTop-t)<=N||d.current>=P?d.current=0:(d.current+=1,!v(e)&&(e.scrollTo({top:t}),l.current=e.scrollTop,f.current=requestAnimationFrame(S)))},[v]),w=(0,C.useCallback)(e=>{if(r.current=e,m.current?.(),m.current=null,!e)return;let t=0,n=!1,i=()=>{t=performance.now()+I},o=()=>{n=!0,i()},c=()=>{n=!1,i()},u=e=>{L.has(e.key)&&i()};e.addEventListener(`wheel`,i,{passive:!0}),e.addEventListener(`touchstart`,i,{passive:!0}),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`keydown`,u),e.addEventListener(`pointerdown`,o,{passive:!0}),window.addEventListener(`pointerup`,c),window.addEventListener(`pointercancel`,c);let h=()=>{let e=r.current;if(!e)return;let i=e.scrollHeight-e.scrollTop-e.clientHeight,o=!n&&performance.now()>t||Math.abs(e.scrollTop-l.current)<=N;if(a.current&&o){l.current=e.scrollTop,i>1&&x();return}let c=i<=80;c||(l.current=-1,y()),c!==a.current&&(a.current=c,s(c))};e.addEventListener(`scroll`,h,{passive:!0});let g=null,_=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>b());_?.observe(e);let v=()=>{let t=e.firstElementChild;t!==g&&(g&&_?.unobserve(g),g=t,g&&_?.observe(g))},S=typeof MutationObserver>`u`?null:new MutationObserver(v);S?.observe(e,{childList:!0}),v(),b(),m.current=()=>{cancelAnimationFrame(p.current),p.current=0,f.current&&cancelAnimationFrame(f.current),f.current=0,d.current=0,e.removeEventListener(`scroll`,h),e.removeEventListener(`wheel`,i),e.removeEventListener(`touchstart`,i),e.removeEventListener(`touchmove`,i),e.removeEventListener(`keydown`,u),e.removeEventListener(`pointerdown`,o),window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),S?.disconnect(),_?.disconnect()}},[b,x]);return(0,C.useEffect)(()=>{c.current!==t&&(c.current=t,a.current=!0,s(!0),y(),b())},[t,b,y]),(0,C.useEffect)(()=>{b()},[e,b]),(0,C.useEffect)(()=>{b()},[g,b]),(0,C.useEffect)(()=>()=>m.current?.(),[]),{ref:w,stuck:o,toBottom:(0,C.useCallback)(()=>{let e=r.current;e&&(a.current=!0,u.current=null,s(!0),e.scrollTo({top:e.scrollHeight,behavior:`auto`}),l.current=e.scrollTop)},[y]),anchorTo:(0,C.useCallback)(e=>{let t=r.current;if(!t||!e)return;let n=e.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop;u.current=Math.max(0,n-F),a.current=!0,s(!0),v(t)||b(),d.current=0,f.current&&cancelAnimationFrame(f.current),f.current=requestAnimationFrame(S)},[v,b,S]),pad:g}}function z(e,t){return e.conversation===t.conversation?t.messageId!==null&&e.messageId!==t.messageId?{seen:t,target:t.messageId}:t.queuedId!==null&&e.queuedId!==t.queuedId?{seen:t,target:t.queuedId}:{seen:t,target:null}:{seen:t,target:null}}var B={enabled:!0,start:!1,steer:!0,done:!0,error:!0,approval:!0,volume:70},V={start:{title:`回复开始`,titleEn:`Reply starts`,hint:`智能体开始新一轮时`,hintEn:`when the agent starts a new turn`},done:{title:`回复结束`,titleEn:`Reply finishes`,hint:`智能体完成一轮回答时`,hintEn:`when the agent finishes a turn`},steer:{title:`插队`,titleEn:`Steering`,hint:`你的追问插进正在跑的这一轮时`,hintEn:`when your follow-up cuts into the running turn`},error:{title:`出错`,titleEn:`Error`,hint:`出现错误提示时`,hintEn:`when an error notice appears`},approval:{title:`等待审批`,titleEn:`Waiting for approval`,hint:`AI 请求执行工具、等待批准时`,hintEn:`when the AI asks to run a tool and waits for approval`}},H=`pop-agent.voice.sound`;function U(){try{let e=localStorage.getItem(H);if(!e)return{...B};let t=JSON.parse(e),n={...B,...t};for(let e of[`enabled`,`start`,`steer`,`done`,`error`,`approval`])typeof n[e]!=`boolean`&&(n[e]=B[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?B.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...B}}}function W(e){try{localStorage.setItem(H,JSON.stringify(e))}catch{}}var ee=null,G=!1;function K(){try{let e=window.AudioContext??window.webkitAudioContext;return e?(ee=new e,ee):null}catch{return null}}function te(e){return e.state===`running`}function ne(){return ae()}function re(e){return te(e)}function ie(e){return Math.max(0,Math.min(1,e.volume/100))}function ae(){try{ee&&ee.state===`closed`&&(ee=null);let e=ee??K();return e?(te(e)||e.resume().catch(()=>{}),e):null}catch{return null}}function oe(){if(G||typeof window>`u`)return;G=!0;let e=()=>{ae()};for(let t of[`pointerdown`,`keydown`,`touchstart`,`click`])window.addEventListener(t,e,{capture:!0,passive:!0});document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}oe();var se={start:[{type:`triangle`,freq:660,start:0,dur:.08,peak:.22}],steer:[{type:`triangle`,freq:740,start:0,dur:.07,peak:.2},{type:`triangle`,freq:988,start:.09,dur:.1,peak:.22}],done:[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],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 ce(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 le(e,t,n){for(let r of se[t])ce(e,r,n)}var ue=1500;function de(e){return Date.now()-e<=ue}function fe(e,t=U()){if(!t.enabled||!t[e])return;let n=ae();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));if(te(n)){le(n,e,r);return}let i=Date.now();n.resume().then(()=>{Date.now()-i>ue||te(n)&&le(n,e,r)}).catch(()=>{})}var pe=`pop-agent.language`,me=`pop-agent:language`,he=`en`,ge=[{id:`zh`,label:`中文`},{id:`en`,label:`English`}];function _e(){let e=typeof navigator>`u`?void 0:navigator,t=e?.languages?.[0]??e?.language;return typeof t==`string`&&t.trim()!==``?t.trim():null}function ve(){let e=_e();return e===null?he:/^zh/i.test(e)?`zh`:`en`}function ye(){try{let e=localStorage.getItem(pe);return e===`zh`||e===`en`?e:ve()}catch{return ve()}}function be(e){try{localStorage.setItem(pe,e)}catch{}xe(e),window.dispatchEvent(new CustomEvent(me,{detail:e}))}function xe(e){try{document.documentElement.lang=e===`en`?`en`:`zh-CN`}catch{}}var Se=`modulepreload`,Ce=function(e){return`/`+e},we={},Te=function(e){return e.pathname.endsWith(`.css`)},Ee=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},De=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,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?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Ce(t,n);let r=s(t),i=Te(r);return Ee(we,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:Se,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).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)})},Oe=null,ke=null;function Ae(){return Oe?Promise.resolve():(ke||=De(()=>import(`./i18n-en-H5OrSHR5.js`).then(e=>{Oe=e.EN}),[]).catch(e=>{ke=null,console.warn(`[i18n] 英文词条加载失败,界面回落中文`,e)}),ke)}function je(){let[e,t]=(0,C.useState)(()=>ye());return(0,C.useEffect)(()=>{let e=e=>{e===`en`?Ae().then(()=>t(`en`)):t(e)},n=t=>{let n=t.detail;(n===`zh`||n===`en`)&&e(n)},r=t=>{t.key===`pop-agent.language`&&e(t.newValue===`en`?`en`:`zh`)};return window.addEventListener(`pop-agent:language`,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(`pop-agent:language`,n),window.removeEventListener(`storage`,r)}},[]),(0,C.useEffect)(()=>xe(e),[e]),{language:e,setLanguage:(0,C.useCallback)(e=>{e===`en`?Ae().then(()=>be(e)):be(e)},[])}}function Me(e,t,n){return e===`en`?n||(Oe?Oe[t]??t:(Ae(),t)):t}function q(e,t){return Me(ye(),e,t)}function J(){let{language:e}=je();return(0,C.useCallback)((t,n)=>Me(e,t,n),[e])}var Ne,Y=!1;function Pe(){if(Y||typeof document>`u`)return;Y=!0;let e=()=>{try{let e=Fe();if(!e)return;(!Ne||Ne.state===`closed`)&&(Ne=new e),Ne.state===`suspended`&&Ne.resume().catch(()=>void 0)}catch{}};for(let t of[`pointerdown`,`keydown`,`touchstart`])document.addEventListener(t,e,{capture:!0,passive:!0})}function Fe(){if(typeof window<`u`)return window.AudioContext??window.webkitAudioContext}function Ie(){return!!Fe()&&typeof fetch==`function`}function Le(e,t=1800){let n=[],r=new TextEncoder,i=``,a=0;for(let o of e.match(/[^。!?.!?\n]+[。!?.!?\n]*|[。!?.!?\n]+/gu)??[]){let e=r.encode(o).length;i&&a+e>t&&(n.push(i),i=``,a=0);for(let e of o){let o=r.encode(e).length;i&&a+o>t&&(n.push(i),i=``,a=0),i+=e,a+=o}}return i&&n.push(i),n}var Re={edge:`Edge`,kokoro:`Kokoro`,qwen3:`Qwen3`};async function ze(e,t){let n=await fetch(`/api/tts/voices?provider=${t}`,{signal:e});if(!n.ok)throw Error(q(`无法加载 ${Re[t]} 音色,请稍后重试`,`Unable to load ${Re[t]} voices; try again later`));return(await n.json()).voices}Pe();function Be(e,t,n,r){let i=new AbortController,a=!1,o,s,c=()=>{a=!0,i.abort(),o&&=(o.onended=null,o.stop(),o.disconnect(),void 0),s?.()};return(async()=>{let c=Fe();if(!c)throw Error(q(`当前浏览器不支持音频播放`,`This browser does not support audio playback`));(!Ne||Ne.state===`closed`)&&(Ne=new c);let l=Ne;if(await l.resume(),a)return;if(l.state!==`running`)throw Error(q(`浏览器拦截了播放,请在页面上点击后重新朗读`,`Playback was blocked; click on the page and try again`));let u=Le(e),d=0,f=()=>{for(;;){for(;d<u.length;){let e=u[d++];if(e&&e.trim()!==``)return e}let e=r?.();if(e===void 0||e.trim()===``)return;u=Le(e),d=0}},p=async e=>{let n=t.provider===`edge`?45e3:18e4,r=window.setTimeout(()=>i.abort(),n);try{let n=await fetch(`/api/tts/speak`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t,text:e}),signal:i.signal});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??q(`${t.provider} 语音请求失败(${n.status})`,`${t.provider} speech request failed (${n.status})`))}let r=await n.arrayBuffer();if(a)throw Error(`canceled`);return await l.decodeAudioData(r)}finally{window.clearTimeout(r)}},m=f(),h=m===void 0?void 0:await p(m);for(let e=!0;h&&!a;e=!1){let t=l.createBufferSource();o=t,t.buffer=h,t.connect(l.destination);let r=new Promise(e=>{s=e,t.onended=()=>{t.disconnect(),o===t&&(o=void 0),e()}});t.start(),e&&n.onStart?.();let i=f(),a=i===void 0?Promise.resolve(void 0):p(i);[,h]=await Promise.all([r,a])}a||n.onEnd?.()})().catch(e=>{if(a)return;let r=i.signal.aborted;c(),n.onIssue?.(r?t.provider===`edge`?q(`Edge 语音请求超时,请检查网络后重试`,`Edge speech timed out; check your connection and try again`):q(`本地模型首次加载或合成超时,请稍后重试`,`Local model loading or synthesis timed out; try again later`):e instanceof Error?e.message:q(`语音播放失败,请重试`,`Speech playback failed; try again`))}),c}function Ve(){Ne&&Ne.state===`running`&&Ne.suspend()}function He(){Ne&&Ne.state===`suspended`&&Ne.resume()}var Ue={provider:`browser`,edgeVoice:`zh-CN-XiaoxiaoNeural`,kokoroVoice:`zf_xiaoxiao`,qwen3Voice:`serena`,enabled:!0,readReplies:!1,rate:1,voiceURI:``,allowOnline:!0},We=400;function Ge(){return q(`语音播报正常,任务已完成`,`Speech is working — the task is done`)}var Ke=`pop-agent.voice.tts`;function qe(){try{let e=localStorage.getItem(Ke);if(!e)return{...Ue};let t=JSON.parse(e),n={...Ue,...t};for(let e of[`enabled`,`readReplies`,`allowOnline`])typeof n[e]!=`boolean`&&(n[e]=Ue[e]);n.rate=typeof n.rate==`number`&&Number.isFinite(n.rate)?Math.round(Math.max(.5,Math.min(2,n.rate))*10)/10:Ue.rate,typeof n.voiceURI!=`string`&&(n.voiceURI=Ue.voiceURI),[`browser`,`edge`,`kokoro`,`qwen3`].includes(n.provider)||(n.provider=`browser`);for(let e of[`edgeVoice`,`kokoroVoice`,`qwen3Voice`])(typeof n[e]!=`string`||!n[e])&&(n[e]=Ue[e]);return n}catch{return{...Ue}}}var Je=`pop-agent:tts-settings`;function Ye(e){try{localStorage.setItem(Ke,JSON.stringify(e))}catch{}try{window.dispatchEvent(new CustomEvent(Je,{detail:e}))}catch{}}function Xe(e){let t=t=>e(t.detail),n=t=>{t.key===Ke&&e(qe())};return window.addEventListener(Je,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Je,t),window.removeEventListener(`storage`,n)}}function Ze(){return typeof window<`u`&&`speechSynthesis`in window&&`SpeechSynthesisUtterance`in window}function Qe(e=qe()){return e.provider&&e.provider!==`browser`?Ie():Ze()}function $e(e={}){if(!Ze())return[];let t=e.onlyOnline===!0,n=e.includeOnline!==!1;return window.speechSynthesis.getVoices().filter(e=>t?!e.localService:n||e.localService).map(e=>({voiceURI:e.voiceURI,name:e.name,lang:e.lang,localService:e.localService})).sort((e,t)=>e.lang.localeCompare(t.lang)||e.name.localeCompare(t.name))}function et(e){return Ze()?(window.speechSynthesis.addEventListener(`voiceschanged`,e),()=>window.speechSynthesis.removeEventListener(`voiceschanged`,e)):()=>{}}function tt(e,t,n,r={}){let i=r.allowOnline===!0,a=i?[...t]:t.filter(e=>e.localService);if(e!==``){let t=a.find(t=>t.voiceURI===e);if(t)return t}let o=n.split(`-`)[0]?.toLowerCase()??``,s=(e,t)=>e.lang.toLowerCase().startsWith(t),c=e=>{let t=a.filter(e=>e.localService!==i),n=a.filter(e=>e.localService===i);return t.find(t=>s(t,e))??n.find(t=>s(t,e))??null};if(o!==``){let e=c(o);if(e)return e}return c(`zh`)}function nt(e,t=We){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(),n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}function rt(e){switch(e){case`not-allowed`:return q(`浏览器拦了这次朗读:先在页面上点一下(任意按钮)再试`,`The browser blocked this playback: click anywhere on the page, then try again`);case`voice-unavailable`:return q(`选中的音色在系统里不可用,换个「语音」或选「自动」`,`The selected voice is not available on this system — pick another voice or use Auto`);case`audio-busy`:return q(`音频输出被别的应用占着,关掉它再试`,`Another app is holding the audio output — close it and try again`);case`audio-hardware`:return q(`没有可用的音频输出设备`,`No audio output device is available`);case`network`:return q(`这个音色要联网(在线音色)才能念,换一个本机音色`,`This voice is an online voice and needs a network connection — pick a local voice`);case`synthesis-unavailable`:return q(`系统语音服务不可用(macOS:系统设置 → 辅助功能 → 朗读内容)`,`The system speech service is unavailable (macOS: System Settings → Accessibility → Spoken Content)`);case`synthesis-failed`:return q(`系统语音服务合成失败,试试点「停止」再试听一次`,`The system speech service failed to synthesize — click Stop, then preview again`);case`text-too-long`:return q(`这段话太长,合成器拒了`,`This text is too long — the synthesizer refused it`);case`invalid-argument`:return q(`音色参数无效(换一个「语音」再试)`,`The voice setting is invalid (pick another voice and try again)`);default:return q(`语音合成失败:${e}`,`Speech synthesis failed: ${e}`)}}var it=!1,at=0,ot,st,ct=200,lt=2,ut=700,dt=2;function ft(e){return e===null?1500:e?900:2500}var pt=new Set([`canceled`,`interrupted`,`synthesis-unavailable`,`synthesis-failed`]),mt=new Set;function ht(e){try{return!e.speaking&&!e.pending?!1:(e.cancel(),!0)}catch{return!1}}function gt(e,t=ct){if(!Ze()){window.setTimeout(e,t);return}let n=window.speechSynthesis,r;try{ht(n),n.resume(),r=new SpeechSynthesisUtterance(` `)}catch{window.setTimeout(e,t);return}mt.add(r),r.volume=0,r.lang=``;let i=!1,a=a=>{if(!i){i=!0,window.clearTimeout(o),mt.delete(r);try{a!==`end`&&ht(n),n.resume()}catch{}window.setTimeout(e,t)}},o=window.setTimeout(()=>a(`timeout`),ut);r.onend=()=>a(`end`),r.onerror=()=>a(`error`);try{n.speak(r)}catch{a(`error`)}}function _t(e){return q(`语音服务没起来(${e}):已自动唤醒并重试 ${lt} 次仍然没出声。点「试听」再试一次;还是不行就重启浏览器(macOS 也可在终端执行 killall speechsynthesisd)`,`The speech service did not start (${e}): woke it up and retried ${lt} times with no sound. Click Preview to try again; if that fails, restart the browser (on macOS you can also run killall speechsynthesisd)`)}var vt=``;function yt(){return vt}function bt(e,t=qe(),n={}){if(!e.trim())return;if(vt=e,wt&&(Et(!1),Ze()&&window.speechSynthesis.resume()),t.provider===`browser`||!t.provider){st&&Ct(),xt(e,t,n);return}Ct();let r=t.provider,i=r===`kokoro`?t.kokoroVoice||`zf_xiaoxiao`:r===`qwen3`?t.qwen3Voice||`serena`:t.edgeVoice||`zh-CN-XiaoxiaoNeural`;ot=n.onCancel;let a=()=>{st=void 0,ot=void 0};st=Be(e,{provider:r,voice:i,rate:t.rate},{onStart:n.onStart,onEnd:()=>{a(),n.onEnd?.()},onIssue:e=>{a(),n.onIssue?.(e,{wakeable:!1})}},n.nextText?()=>{let e=n.nextText?.();return e!==void 0&&(vt=e),e}:void 0)}function xt(e,t,n){let r=e.trim();if(r===``)return;if(!Ze()){n.onIssue?.(q(`当前浏览器不支持语音合成`,`This browser does not support speech synthesis`),{wakeable:!1});return}let i=window.speechSynthesis;ot&&ht(i),ot?.(),ot=n.onCancel,it=!1;let a=++at,o=()=>it||a!==at,s=0,c=!1,l=0,u=(e,a=`first`)=>{if(o())return;let d=0;try{let f=a===`retry`?null:tt(t.voiceURI,e,navigator.language??`zh-CN`,{allowOnline:t.allowOnline}),p=new SpeechSynthesisUtterance(r);mt.add(p),p.rate=t.rate,p.volume=1,f?(p.voice=i.getVoices().find(e=>e.voiceURI===f.voiceURI)??null,p.lang=f.lang):p.lang=``;let m=!1,h=!1;if(c){console.warn(`[tts] 这一句已经出过声,不再重排`,{stage:a,queued:l});return}if(l>=dt){console.warn(`[tts] 已经排过两句,不再重排(重排只会让同一句多念一遍)`,{stage:a,queued:l}),n.onIssue?.(_t(`canceled`),{code:`canceled`,wakeable:!0});return}l+=1;let g=()=>{d&&window.clearTimeout(d),d=0},_=()=>{g(),mt.delete(p)};p.onstart=()=>{c=!0,!o()&&(h=!0,m=!0,g(),n.onStart?.())},p.onend=()=>{o()||(m=!0,_(),n.onEnd?.())},p.onerror=r=>{let l=String(r.error??`unknown`);if(o()){m=!0,_();return}let d=l===`canceled`||l===`interrupted`;if(d&&h)m=!0,_();else if(d){if(m=!0,_(),c)return;if(console.warn(`[tts] 还没开始就被打断`,{code:l,stage:a,voice:f?.name??`(交给浏览器默认)`,wakes:s}),s<lt){s+=1,gt(()=>{o()||u(e,a)},ct*s);return}n.onIssue?.(_t(l),{code:l,wakeable:!0})}else a===`first`&&f&&l!==`not-allowed`&&!c?(m=!0,_(),console.warn(`[tts] 音色不可用,改用默认音色重试`,{code:l,voice:f.name}),window.setTimeout(()=>{o()||u(e,`retry`)},ct)):(m=!0,_(),console.warn(`[tts] 合成失败`,l,{voice:f?.name??`(交给浏览器默认)`,voices:e.length,allVoices:i.getVoices().length,rate:t.rate}),n.onIssue?.(rt(l),{code:l,wakeable:pt.has(l)}))},d=window.setTimeout(()=>{m||o()||c||i.speaking||(m=!0,_(),ht(i),i.resume(),a===`first`&&f?(console.warn(`[tts] 音色没有开始,改用默认音色重试`,{voice:f.name}),window.setTimeout(()=>{o()||u(e,`retry`)},ct)):(console.warn(`[tts] 语音服务没有响应`,{voice:f?.name??`(交给浏览器默认)`,voices:e.length,allVoices:i.getVoices().length}),n.onIssue?.(q(`系统语音服务没有响应(换个「语音」,或检查系统的语音合成设置)`,`The system speech service is not responding (pick another voice, or check the system speech settings)`),{wakeable:!0})))},ft(a===`first`&&f?f.localService:null));let v=e=>{m||o()||(!i.speaking&&!i.pending?(i.resume(),i.speak(p)):e>=6?(m=!0,g(),ht(i),i.resume(),console.warn(`[tts] 上一句没退干净,队列清不掉`,{stage:a}),n.onIssue?.(q(`语音服务卡住了(上一句没退干净):点「停止」再试听一次`,`The speech service is stuck (the previous line never cleared): click Stop, then preview again`),{wakeable:!0})):window.setTimeout(()=>v(e+1),120))};if(i.speaking||i.pending){ht(i),i.resume(),v(0);return}i.resume(),i.speak(p)}catch(e){d&&window.clearTimeout(d),n.onIssue?.(q(`语音合成出错:${e instanceof Error?e.message:String(e)}`,`Speech synthesis error: ${e instanceof Error?e.message:String(e)}`),{wakeable:!1})}},d=$e({includeOnline:t.allowOnline});if(d.length>0){u(d);return}let f=!1,p=()=>{f||(f=!0,m(),u($e({includeOnline:t.allowOnline})))},m=et(()=>{$e({includeOnline:t.allowOnline}).length>0&&p()});window.setTimeout(p,1200)}function St(e=2500){let t={available:Ze(),voices:0,online:0,started:!1,ended:!1,error:null,ms:0};if(!t.available)return Promise.resolve(t);let n=window.speechSynthesis.getVoices();t.voices=n.length,t.online=n.filter(e=>!e.localService).length;let r=Date.now();return new Promise(n=>{let i=!1,a=null,o=e=>{i||(i=!0,window.clearTimeout(s),a&&mt.delete(a),ht(window.speechSynthesis),n({...t,...e,ms:Date.now()-r}))},s=window.setTimeout(()=>o({}),e);try{a=new SpeechSynthesisUtterance(q(`测试`,`test`)),mt.add(a),a.volume=1,a.onstart=()=>o({started:!0}),a.onend=()=>o({started:!0,ended:!0}),a.onerror=e=>o({error:String(e.error??`unknown`)}),window.speechSynthesis.resume(),window.speechSynthesis.speak(a)}catch(e){o({error:e instanceof Error?e.message:String(e)})}})}function Ct(){wt&&(Et(!1),Ze()&&window.speechSynthesis.resume()),it=!0,at++,st?.(),st=void 0;let e=ot;ot=void 0,e?.(),Ze()&&ht(window.speechSynthesis)}var wt=!1,Tt=new Set;function Et(e){if(wt!==e){wt=e;for(let e of Tt)e()}}function Dt(){return st?!0:Ze()&&(window.speechSynthesis.speaking||window.speechSynthesis.pending)}function Ot(){!wt&&Dt()&&(Et(!0),st?Ve():window.speechSynthesis.pause())}function kt(){wt&&(Et(!1),st?He():Ze()&&window.speechSynthesis.resume())}function At(){return wt}function jt(e){return Tt.add(e),()=>Tt.delete(e)}var X=90,Mt=4,Nt=/[。!?;!?;…]|\n/;function Pt(e){let t=[],n=e;for(;n.length>X;){let e=n.slice(0,X),r=Math.max(e.lastIndexOf(`,`),e.lastIndexOf(`,`),e.lastIndexOf(`、`));if(r<Mt)break;t.push(n.slice(0,r+1)),n=n.slice(r+1)}return{pieces:t,rest:n}}function Ft(e){let t=[],n=e;for(;;){let e=n.search(Nt);if(e===-1)break;let r=n.slice(0,e+1);if(r.trim().length>=Mt){let i=Pt(r);if(i.pieces.length===0){t.push(r),n=n.slice(e+1);continue}t.push(...i.pieces),n=i.rest+n.slice(e+1);continue}let i=n.slice(e+1).search(Nt);if(i===-1)break;let a=n.slice(0,e+1+i+1),o=Pt(a);o.pieces.length===0?(t.push(a),n=n.slice(a.length)):(t.push(...o.pieces),n=o.rest)}let r=Pt(n);return t.push(...r.pieces),{units:t,rest:r.rest}}function It(){let e=0,t=``,n=!1,r=0,i=e=>{let t=nt(e,1/0).trim();return t===``||!/[\p{L}\p{N}]/u.test(t)?``:t},a=e=>{let{units:n,rest:a}=Ft(e);t=a;let o=[];for(let e of n){let t=i(e);t!==``&&o.push(t)}return r+=o.length,o};return{get spoken(){return r},push(r){if(r.length<=e)return[];let i=r.slice(e);e=r.length;let o=t+i;t=``;let s=[];for(;;){if(n){let e=o.indexOf("```");if(e===-1)return s;n=!1,o=o.slice(e+3);continue}let e=o.indexOf("```");if(e===-1)return s.push(...a(o)),s;s.push(...a(o.slice(0,e))),n=!0,o=o.slice(e+3)}},flush(){let e=n?``:t;t=``,n=!1;let a=i(e);return a===``?[]:(r+=1,[a])},reset(){e=0,t=``,n=!1,r=0}}}var Lt=`/api/client-log`,Rt=120,zt=1e4,Bt=0,Vt=0;function Ht(e){return{textLen:e.length,textHead:e.slice(0,24)}}function Ut(e,t){let n=Date.now();if(n-Bt>zt&&(Bt=n,Vt=0),!(Vt>=Rt)){Vt+=1;try{fetch(Lt,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{event:e,detail:t}:{event:e}),keepalive:!0}).catch(()=>void 0)}catch{}}}var Wt=!1,Gt=new Set,Kt=new Set,qt=new Set;function Jt(){for(let e of Gt)e()}function Yt(e){Wt!==e&&(Wt=e,Jt())}function Xt(){return Wt}function Zt(e){return Gt.add(e),()=>Gt.delete(e)}function Qt(){return(0,C.useSyncExternalStore)(Zt,Xt,Xt)}var $t=new Set;function en(){for(let e of $t)e()}function tn(e){return $t.add(e),()=>$t.delete(e)}function nn(){for(let e of Kt)e();en()}function rn(e){return Kt.add(e),()=>Kt.delete(e)}function an(){for(let e of qt)e()}function on(e){return qt.add(e),()=>qt.delete(e)}function sn(e){return e===`queue`?`stop`:e===`steer`?`none`:`interrupt`}function cn(e){let t=sn(e);t===`stop`?nn():(en(),t===`interrupt`&&an())}var ln=!1,un=new Set;function dn(){for(let e of un)e()}jt(()=>{let e=At();e!==ln&&(ln=e,dn())});function fn(e){return un.add(e),()=>un.delete(e)}function pn(){return(0,C.useSyncExternalStore)(fn,mn,mn)}function mn(){return ln}function hn(e){if(e===ln)return;e?Ot():kt();let t=At();t!==ln&&(ln=t,dn())}function gn(e){return un.add(e),()=>un.delete(e)}function _n(){if(typeof window>`u`)return null;let e=window,t=e.SpeechRecognition??e.webkitSpeechRecognition??null;return typeof t==`function`?t:null}function vn(){return!_n()||typeof window>`u`?!1:window.isSecureContext===!0}function yn(e){let t=_n();if(!t||typeof window>`u`||window.isSecureContext!==!0)return e.onError(`unsupported`),null;let n=new t;n.lang=e.lang,n.continuous=!0,n.interimResults=!0,n.maxAlternatives=1,n.onresult=t=>{let n=``;for(let e=0;e<t.results.length;e+=1){let r=t.results[e];n+=r?.[0]?.transcript??``}e.onText(n.trim())},n.onerror=t=>{let n=t.error??`other`;n===`not-allowed`||n===`service-not-allowed`?e.onError(`denied`):n===`no-speech`?e.onError(`no-speech`):n===`network`?e.onError(`network`):n!==`aborted`&&e.onError(`other`)},n.onend=()=>e.onEnd();try{n.start()}catch{return e.onError(`other`),null}return{stop:()=>{try{n.stop()}catch{}},abort:()=>{try{n.abort()}catch{}}}}function bn(e){return!Number.isFinite(e.blockedForMs)||e.blockedForMs<=0||!Number.isFinite(e.fallbackMs)||e.fallbackMs<=0?!1:e.blockedForMs>=e.fallbackMs}var xn=16e3,Sn=300,Cn=12,wn=36,Tn=2,En=700,Dn=1500;function On(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n]??0;t+=r*r}let n=Math.sqrt(t/Math.max(1,e.length));return n>0?20*Math.log10(n):-100}function kn(e,t){let n=t/xn,r=Math.max(0,Math.floor(e.length/n)),i=new Int16Array(r);for(let t=0;t<r;t+=1){let r=Math.floor(t*n),a=Math.min(e.length,Math.floor((t+1)*n)),o=0;for(let t=r;t<a;t+=1)o+=e[t]??0;let s=a>r?o/(a-r):0;i[t]=Math.round(Math.max(-1,Math.min(1,s))*32767)}return i}var An=null;function jn(){return(!An||An.state===`closed`)&&(An=new AudioContext),An.resume().catch(()=>void 0),An}function Mn(e){let t=!1,n=``,r=Math.max(0,Math.min(30,e.nearTalkDb??Cn)),i=r>0,a=jn(),o=null,s=null,c=[],l=Promise.resolve(),u=0,d=[],f=0,p=0,m=0,h=0,g=0,_=0,v=null,y=async(e,t)=>await fetch(e,{method:`POST`,headers:t?{"content-type":`application/octet-stream`}:void 0,body:t}),b=()=>(l=l.then(async()=>{for(;c.length>0&&!t;){let t=c.shift();try{let r=await y(`/api/asr/chunk`,t.buffer);if(!r.ok)continue;let i=await r.json(),a=typeof i.text==`string`?i.text:``;a!==n&&(n=a,e.onText(a))}catch{}}}),l),x=async()=>{s?.disconnect(),s=null;for(let e of o?.getTracks()??[])e.stop();o=null;let e=c;return c=[],e},S=()=>t;return(async()=>{let n={},l=Date.now(),x=!1;for(;;){let t=!1;try{let e=await y(`/api/asr/start`);if(n=await e.json().catch(()=>({})),e.ok)break;t=n.state===`starting`||n.state===`authorizing`}catch(t){e.onError(`local`,t instanceof Error?t.message:`连不上本地识别服务`,`error`),e.onEnd();return}if(!t||S())return;if(Date.now()-l>8e3){e.onError(`local`,n.message??`本地识别启动超时`,n.state),e.onEnd();return}if(x||(x=!0,e.onWaiting?.(n.state??`starting`)),await new Promise(e=>setTimeout(e,400)),S())return}if(t)return;try{o=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!i}})}catch{e.onError(`denied`),e.onEnd();return}if(t){for(let e of o.getTracks())e.stop();return}a.state!==`running`&&await a.resume().catch(()=>void 0),e.onContext?.(a.state);let C=a.createMediaStreamSource(o);s=a.createScriptProcessor(4096,1,1),s.onaudioprocess=n=>{if(t)return;let o=n.inputBuffer.getChannelData(0),s=Date.now(),l=!0,y=!1;if(i&&!e.bypassGate?.()){let e=On(o);d.push(e),d.length>wn&&d.shift(),g=e>Math.min(...d)+r?g+1:0,l=g>=Tn,y=s<_,f+=1,!l&&!y?(p+=1,h===0&&(h=s),bn({blockedForMs:s-h,fallbackMs:Dn})&&(l=!0,h=0,m+=1)):h=0,l&&(_=s+En)}let x=o;(e.shouldMuteAudio?.()||!l&&!y)&&(v??=new Float32Array(o.length),x=v);let S=kn(x,a.sampleRate||xn);S.length!==0&&(c.push(S),s-u>=Sn&&(u=s,b()))},C.connect(s),s.connect(a.destination)})(),{stop:()=>{t||(t=!0,x())},abort:()=>{t=!0,c=[],x()},flush:async()=>{e.onGating?.({marginDb:r,frames:f,blocked:p,fallbacks:m});let t=await x();for(let e of t)c.push(e);await b();try{let t=await(await y(`/api/asr/end`)).json().catch(()=>({})),r=typeof t.text==`string`?t.text:n;r!==n&&(n=r,e.onText(r))}catch{}return n}}}function Nn(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0||e<=0?0:e>=t?1:e/t}function Pn(e,t){return Math.abs(t-e)>=.08||e>0&&t===0}var Fn=1e4;function In(e,t){if(typeof e!=`number`||!Number.isFinite(e))return t;let n=Math.round(e*1e3);return Math.min(Fn,Math.max(600,n))}function Ln(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?0:Math.min(120,Math.max(3,Math.round(e)))}var Rn=[`,`,`,`,`、`,`;`,`;`,`:`,`:`,`—`,`-`,`…`,`“`,`「`,`「`,`(`,`(`];function zn(e){let t=e.trim();if(t===``)return!1;let n=t.slice(-1);return Rn.includes(n)}var Bn={min:600,max:1e4},Vn={min:0,max:30},Hn={min:0,max:120},Un={autoSend:!0,continuous:!1,submitMode:`queue`,engine:`auto`,nearTalkDb:12,silenceMs:2e3,readingResumeMs:4e3,idleStopSec:0,showReadingDock:!0};function Wn(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function Gn(e,t,n){return Math.min(n,Math.max(t,e))}function Kn(e,t=Un){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{autoSend:typeof n.autoSend==`boolean`?n.autoSend:t.autoSend,continuous:typeof n.continuous==`boolean`?n.continuous:t.continuous,submitMode:n.submitMode===`steer`?`steer`:n.submitMode===`queue`?`queue`:t.submitMode,engine:n.engine===`local`||n.engine===`browser`||n.engine===`auto`?n.engine:t.engine,nearTalkDb:Math.round(Gn(Wn(n.nearTalkDb,t.nearTalkDb),Vn.min,Vn.max)),silenceMs:Math.round(Gn(Wn(n.silenceMs,t.silenceMs),Bn.min,Bn.max)),readingResumeMs:Math.round(Gn(Wn(n.readingResumeMs,t.readingResumeMs),Bn.min,Bn.max)),showReadingDock:typeof n.showReadingDock==`boolean`?n.showReadingDock:t.showReadingDock,idleStopSec:Math.round(Gn(Wn(n.idleStopSec,t.idleStopSec),Hn.min,Hn.max))}}var qn=`/api/voice-settings`;async function Jn(){try{let e=await fetch(qn,{headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json();return{settings:Kn(t.settings),stored:t.stored===!0}}catch{return null}}function Yn(e){try{fetch(qn,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),keepalive:!0}).catch(()=>void 0)}catch{}}function Xn(e,t){return e.autoSend===t.autoSend&&e.continuous===t.continuous&&e.submitMode===t.submitMode&&e.engine===t.engine&&e.nearTalkDb===t.nearTalkDb&&e.silenceMs===t.silenceMs&&e.readingResumeMs===t.readingResumeMs&&e.idleStopSec===t.idleStopSec&&e.showReadingDock===t.showReadingDock}function Zn(e){return!e.continuous||e.manualPause||e.status!==`idle`||e.hidden?!1:e.errorStreak<e.maxErrorStreak}var Qn=[],$n=new Set,er=0;function tr(){for(let e of $n)e()}function nr(e){Qn=e,tr()}function Z(e){er+=1;let t={id:er,text:e.text,actions:e.actions??[],ttl:e.ttl??8e3};return nr([...Qn,t].slice(-3)),t.id}function rr(e){nr(Qn.filter(t=>t.id!==e))}function ir(e){return $n.add(e),()=>{$n.delete(e)}}function ar(){return Qn}function or(){return(0,C.useSyncExternalStore)(ir,ar,ar)}var sr=`pop-agent:pref`,cr=`pop-agent.chat.thinkingOpen`,lr=`pop-agent.split.chatSide`,ur=`pop-agent.chat.toolOpen`,dr=`pop-agent.chat.processAutoCollapse`,fr=`pop-agent.chat.processAutoFoldRunning`,pr=`pop-agent.chat.selectionToolbar`,mr=`pop-agent.preview.wrap`,hr=`pop-agent.preview.fontSize`,gr=`pop-agent.sidechat.zoom`,_r=`pop-agent.web.zoom`,vr=`pop-agent.web.phone`,yr=`pop-agent.web.phoneSize`,br=`pop-agent.terminal.fontSize`,xr=[`models`,`cron`,`skills`,`push`,`voice`,`plugins`,`mcp`,`agents`],Sr=[...xr,`settings`],Cr=[`models`,`cron`,`skills`],wr=e=>Cr.includes(e),Tr=`pop-agent.appbar.`,Er=e=>`${Tr}${e}`,Dr=[`label`,`icon`],Or=e=>`pop-agent.appbar.show-${e}`,kr={label:`显示文案`,icon:`显示图标`},Ar={label:`Show labels`,icon:`Show icons`},jr={models:`模型`,skills:`技能`,push:`推送`,voice:`语音`,plugins:`插件`,mcp:`MCP`,agents:`子代理`,cron:`定时任务`,settings:`设置`},Mr={models:`Models`,skills:`Skills`,push:`Push`,voice:`Voice`,plugins:`Plugins`,mcp:`MCP`,agents:`Subagents`,cron:`Cron`,settings:`Settings`},Nr=`pop-agent.appbar.tempchat`,Pr=[`model`,`thinking`,`templates`,`think`,`quick`],Fr=new Set([`model`,`thinking`,`templates`,`think`]),Ir=e=>Fr.has(e),Lr=e=>`pop-agent.composer.${e}`,Rr={model:`模型`,thinking:`思考强度`,templates:`提示词`,think:`想想`,quick:`快捷指令(显示在输入框上方)`},zr={model:`Model`,thinking:`Thinking effort`,templates:`Prompts`,think:`Think`,quick:`Quick commands (above the input)`},Br=[`settings`,`engine`,`approval`,`history`,`prompt`,`queued`,`running`,`context`,`terminal`,`top`],Vr=[`settings`,`engine`,`approval`],Hr=e=>Vr.includes(e),Ur=`pop-agent.statusbar.`,Wr=e=>`${Ur}${e}`,Gr={settings:`设置`,approval:`审批模式`,engine:`引擎`,queued:`排队`,running:`工作中`,context:`上下文用量`,history:`完整历史`,prompt:`系统提示词`,terminal:`终端`,top:`顶部`},Kr={settings:`Settings`,approval:`Approval mode`,engine:`Engine`,queued:`Queued`,running:`Running`,context:`Context`,history:`Full history`,prompt:`System prompt`,terminal:`Terminal`,top:`Top bar`},qr=`pop-agent.sidebar.sessionsPerProject`,Jr=`pop-agent.chat.imageMaxWidth`;function Yr(e){try{return localStorage.getItem(e)}catch{return null}}function Xr(e,t){try{localStorage.setItem(e,t)}catch{}}function Zr(e,t){try{let n=localStorage.getItem(e);return n===`1`||n!==`0`&&t}catch{return t}}function Qr(e,t){try{localStorage.setItem(e,t?`1`:`0`)}catch{}window.dispatchEvent(new CustomEvent(sr,{detail:{key:e,value:t}}))}function $r(e,t){let n=n=>{let r=n.detail;r?.key===e&&t(r.value)},r=n=>{n.key===e&&t(Zr(e,!1))};return window.addEventListener(sr,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(sr,n),window.removeEventListener(`storage`,r)}}var ei=`pop-agent:pref-number`;function ti(e,t,n,r){if(e==null||e===``)return t;let i=typeof e==`number`?e:Number(e);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.round(i))):t}function ni(e,t,n,r){let i=Yr(e);return i===null||i.trim()===``?t:ti(i,t,n,r)}function ri(e,t){Xr(e,String(t));try{window.dispatchEvent(new CustomEvent(ei,{detail:{key:e,value:t}}))}catch{}}function ii(e,t){let n=n=>{let r=n.detail;r?.key===e&&t(r.value)},r=n=>{if(n.key!==e)return;let r=n.newValue===null?``:n.newValue,i=Number(r);Number.isFinite(i)&&t(i)};return window.addEventListener(ei,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(ei,n),window.removeEventListener(`storage`,r)}}var ai=`pop-agent.voice.input`,oi=2e3,si=200,ci={autoSend:!0,submitMode:`queue`,engine:`auto`,continuous:!1,idleStopSec:0,nearTalkDb:12,silenceMs:oi,readingResumeMs:4e3,showReadingDock:!0};function li(e){let t=typeof e==`number`&&Number.isFinite(e)?e:ci.nearTalkDb;return Math.max(0,Math.min(30,Math.round(t)))}var ui=new Set;function di(){let e=Yr(ai);if(!e)return{...ci};try{let t=JSON.parse(e);return{autoSend:t.autoSend!==!1,continuous:t.continuous===!0,idleStopSec:Ln(t.idleStopSec),submitMode:t.submitMode===`steer`?`steer`:`queue`,engine:t.engine===`browser`||t.engine===`local`?t.engine:`auto`,nearTalkDb:li(t.nearTalkDb),silenceMs:In(t.silenceMs===void 0?void 0:t.silenceMs/1e3,oi),readingResumeMs:In(t.readingResumeMs===void 0?void 0:t.readingResumeMs/1e3,4e3),showReadingDock:t.showReadingDock!==!1}}catch{return{...ci}}}var fi=di(),pi=!1;function mi(){pi=!1}function hi(e,t){return e===`browser`?`browser`:e===`local`?`local`:t?`browser`:`local`}function gi(){typeof window<`u`&&typeof fetch==`function`&&fetch(`/api/asr/status`).then(async e=>e.ok?await e.json():null).catch(()=>null).then(e=>{e?.state===`missing`&&(pi=!0)}).catch(()=>void 0)}gi();var _i=0;(async()=>{let e=_i,t=await Jn();if(t===null||_i!==e)return;if(!t.stored){Yn(fi);return}let n=Kn(t.settings);if(!Xn(n,fi)){fi=n,Xr(ai,JSON.stringify(fi)),Ut(`settings:from-server`,{silenceMs:fi.silenceMs,nearTalkDb:fi.nearTalkDb});for(let e of ui)e()}})();function vi(){return fi}function yi(e){_i+=1;let t=fi;fi={autoSend:e.autoSend,continuous:e.continuous===!0,idleStopSec:Ln(e.idleStopSec),submitMode:e.submitMode===`steer`?`steer`:`queue`,engine:e.engine===`browser`||e.engine===`local`?e.engine:`auto`,nearTalkDb:li(e.nearTalkDb),silenceMs:In(e.silenceMs/1e3,oi),readingResumeMs:In(e.readingResumeMs/1e3,4e3),showReadingDock:e.showReadingDock!==!1},Xr(ai,JSON.stringify(fi)),Yn(fi);for(let e of ui)e();t.nearTalkDb!==fi.nearTalkDb&&Ci===`listening`&&Ai===`local`&&(Ut(`restart:gate`,{from:t.nearTalkDb,to:fi.nearTalkDb}),Da())}function bi(){return(0,C.useSyncExternalStore)(e=>(ui.add(e),()=>ui.delete(e)),vi,vi)}var xi=null,Si=null,Ci=`idle`,wi=!1,Ti=!1,Ei=``,Di=``,Oi=0,ki=null,Ai=`browser`,ji=!1,Mi=0,Ni=0,Pi=!1,Fi=!1,Ii=!1,Li=0,Ri=null,zi=800,Bi=2,Vi=!1,Hi=null,Ui=null,Wi=0,Gi=0,Ki=8,qi=2e3,Ji=new Set;function Yi(e){if(Ci!==e){Ut(`status`,{from:Ci,to:e,engine:Ai}),Ci=e,e!==`listening`&&Xi(0);for(let e of Ji)e()}}function Xi(e){if(Pn(Ni,e)){Ni=e;for(let e of Ji)e()}}function Zi(e){return Ji.add(e),()=>Ji.delete(e)}function Qi(){return Ci}function $i(){return(0,C.useSyncExternalStore)(Zi,Qi,Qi)}function ea(){return Ni}function ta(){return(0,C.useSyncExternalStore)(Zi,ea,ea)}function na(){return Ci===`listening`}function ra(e){xi=e}function ia(){return xi!==null&&(xi.conversationId??null)===Si}function aa(){Ut(`abandon:conversation-switched`,{owner:Si,current:xi?.conversationId??null}),Ii=!0,ga(),va(),Yi(`idle`),xi?.onEnd()}function oa(e,t){let n=e.trimEnd(),r=t.trimStart();return n?r?/[\u3400-\u9fff\u3000-\u303f\uff00-\uffef]$/.test(n)||/^[\u3400-\u9fff]/.test(r)?`${n}${r}`:`${n} ${r}`:n:r}function sa(e,t){if(e===`local`)return t??q(`本地识别还没就绪`,`Local recognition isn't ready yet`);switch(e){case`unsupported`:return q(`这台浏览器用不了语音输入:Firefox 没有这个能力;手机通过局域网 http 打开时也没有麦克风(需要 localhost 或 HTTPS)`,`Voice input is unavailable here: Firefox has no support, and a phone opening this over plain LAN http has no microphone (localhost or HTTPS is required)`);case`denied`:return q(`麦克风被拒绝了:点地址栏左边的权限图标,允许麦克风后再点一次`,`Microphone permission was denied: allow it from the icon next to the address bar, then try again`);case`network`:return q(`Chrome 的语音识别要把声音传到 Google 的服务器,这个网络连不上(实测 speech.googleapis.com 超时)。要么让代理覆盖浏览器,要么改用离线识别(目前还没装)`,`Chrome's speech recognition uploads audio to Google, which is unreachable on this network (speech.googleapis.com times out). Either route the browser through a proxy, or switch to offline recognition (not installed yet)`);default:return q(`语音输入出错了,再点一次试试`,`Voice input failed — try tapping again`)}}function ca(){Hi!==null&&(window.clearInterval(Hi),Hi=null),Ui!==null&&(window.clearTimeout(Ui),Ui=null)}function la(){Hi===null&&(Hi=window.setInterval(()=>{if(!(Ci===`listening`&&fi.autoSend&&oa(Ei,Di).trim()!==``)){Xi(0);return}let e=Date.now()-Oi;if(Pi&&e>=ha()&&!ji&&(Pi=!1,mn()&&(Ut(`read:resume`,{idleMs:e}),hn(!1))),fi.idleStopSec>0&&e>=fi.idleStopSec*1e3){Ut(`idle:stop`,{idleMs:e,idleStopSec:fi.idleStopSec}),Ta();return}if(zn(oa(Ei,Di))){Fi||(Fi=!0,Ut(`countdown:hold`,{reason:`unfinished`,...Ht(oa(Ei,Di))})),Xi(1);return}let t=Nn(e,fi.silenceMs);t>=1?(Xi(1),ua()):Xi(t)},si))}function ua(){if(Ui!==null||ji){Date.now()-Mi>=2e3&&(Mi=Date.now(),Ut(`countdown:blocked`,{counting:Ui!==null,flushing:ji,status:Ci}));return}Ut(`countdown:start`,{engine:Ai,...Ht(oa(Ei,Di))}),Yi(`sending`);let e=ki?.flush;if(!e){da();return}ji=!0;let t=Date.now();Ut(`flush:start`,{engine:Ai}),e().catch(e=>(Ut(`flush:error`,{ms:Date.now()-t,error:String(e).slice(0,120)}),``)).finally(()=>{ji=!1,Ut(`flush:done`,{ms:Date.now()-t,...Ht(Di),status:Ci}),Ci===`sending`&&da()})}function da(){ia()?(Ut(`submit`,{engine:Ai,...Ht(oa(Ei,Di))}),va(),Yi(`idle`),xi?.onEnd(),xi?.submitVoice(),_a()):aa()}var fa=10;function pa(e){if(!Xt())return!1;let t=yt().replace(/\s+/g,``),n=e.replace(/\s+/g,``);if(!t||!n||n.length<fa)return!1;let r=t.includes(n);return r&&Ut(`echo:drop`,{heardLen:n.length,spokenLen:t.length}),r}function ma(){if(!Xt()||mn())return;let e=yt().replace(/\s+/g,``),t=oa(Ei,Di).replace(/\s+/g,``);e&&t&&(e.includes(t)||t.includes(e.slice(0,Math.min(12,e.length))))||(Ut(`read:pause`,{}),Pi=!0,hn(!0))}function ha(){return fi.readingResumeMs}function ga(){Ri!==null&&(window.clearTimeout(Ri),Ri=null)}function _a(){Ri===null&&fi.continuous&&(Ri=window.setTimeout(()=>{Ri=null,Zn({continuous:fi.continuous,manualPause:Ii,status:Ci,hidden:document.visibilityState===`hidden`,errorStreak:Li,maxErrorStreak:Bi})?(Ut(`continuous:resume`,{engine:fi.engine}),wa()):Ut(`continuous:skip`,{manualPause:Ii,status:Ci,hidden:document.visibilityState===`hidden`,errorStreak:Li})},zi))}function va(){let e=ki;ki=null,wi=!0,Ti=!0,e?.stop(),Ei=``,Di=``,ca()}function ya(){Oi=Date.now(),ki=yn({lang:ye()===`en`?`en-US`:`zh-CN`,onText:e=>{if(!ia()){aa();return}Oi=Date.now();let t=e!==Di;Di=e,t&&(Li=0),Ut(`text:legacy`,{changed:t,...Ht(oa(Ei,e))}),t&&(Fi=!1,ma()),xi?.onText(oa(Ei,e)),t&&Ci===`sending`&&(Ui!==null&&window.clearTimeout(Ui),Ui=null,Yi(`listening`))},onError:e=>{e!==`no-speech`&&(Li+=1,Ut(`error`,{engine:`browser`,kind:e,errorStreak:Li}),Z({text:sa(e)}),xa())},onEnd:()=>{if(Ti){Ti=!1;return}if(wi||Ci===`sending`)return;let e=Date.now();Wi=e-Gi<qi?Wi+1:1,Gi=e,Wi>Ki?(Z({text:q(`语音输入总是被立刻中断(麦克风可能被别的程序占着),先停下来,待会儿再试`,`Voice input keeps ending immediately (the microphone may be in use) — stopping for now`)}),xa()):(Ei=oa(Ei,Di),Di=``,ya())}})}function ba(){ki=Mn({nearTalkDb:fi.nearTalkDb,onText:e=>{if(!ia()){aa();return}if(pa(e))return;Oi=Date.now();let t=e!==Di;Di=e,xi?.onText(e),t&&(Li=0),Ut(`text:local`,{changed:t,...Ht(e)}),t&&(Fi=!1,ma()),t&&Ci===`sending`&&!ji&&(Ut(`countdown:cancel`,{reason:`new-text`}),Ui!==null&&window.clearTimeout(Ui),Ui=null,Yi(`listening`))},onError:(e,t,n)=>{e!==`no-speech`&&(Li+=1,Ut(`error`,{engine:`local`,kind:e,detail:t?.slice(0,120),state:n,errorStreak:Li}),xa(),fi.engine===`auto`&&(n===`missing`||n===`error`)?(pi=!0,n===`error`&&!Vi&&(Vi=!0,Z({text:q(`本地识别不可用(${t??`原因未知`}),已改用 Chrome 识别`,`Local recognition is unavailable (${t??`unknown`}), falling back to Chrome`)})),Ca()):Z({text:sa(e,t)}))},onContext:e=>Ut(`audio-context`,{state:e}),onGating:e=>Ut(`gate`,e),bypassGate:()=>Xt(),onWaiting:e=>Ut(`asr:waiting`,{state:e}),onEnd:()=>{}})}function xa(){ga();let e=ki;ki=null,Ti=!0,e?.abort(),Ei=``,Di=``,ji=!1,ca(),Yi(`idle`),Si=null,xi?.onEnd()}function Sa(){wi=!1,Ti=!1,Wi=0,Gi=0,Ei=``,Di=``,Si=xi?.conversationId??null,Xt()&&(Pi=!0,hn(!0)),xi?.onStart(),Yi(`listening`),la(),Ai===`local`?ba():ya()}function Ca(){vn()?(Ai=`browser`,Sa()):Z({text:sa(`unsupported`)})}function wa(){Ci===`idle`&&(Ii=!1,Li=0,Ut(`start`,{engineSetting:fi.engine,autoSend:fi.autoSend,submitMode:fi.submitMode,silenceMs:fi.silenceMs,continuous:fi.continuous,secure:typeof window<`u`?window.isSecureContext:void 0}),hi(fi.engine,pi)===`browser`?Ca():(Ai=`local`,Sa()))}function Ta(){Ci!==`idle`&&(Ut(`stop`,{status:Ci,flushing:ji,engine:Ai}),Ii=!0,ga(),!ji&&(Ci===`listening`&&ki?.flush?(ji=!0,ki.flush().catch(()=>``).finally(()=>{ji=!1,va(),Yi(`idle`),xi?.onEnd()})):(va(),Yi(`idle`),xi?.onEnd())))}function Ea(){Ci===`idle`?wa():Ta()}function Da(e){if(Ci!==`listening`)return;let t=ki;ki=null,Ti=!0,t?.abort(),Ei=``,Di=``,Si=xi?.conversationId??null,xi?.onStart(e),Oi=Date.now(),Ai===`local`?ba():ya()}var Oa={done:{zh:`/assets/done.zh-Dq-Os4NS.mp3`,en:`/assets/done.en-s1tZOg6A.mp3`},stopped:{zh:`/assets/stopped.zh-D2CUs-KZ.mp3`,en:`/assets/stopped.en-CFPMi6oy.mp3`},steer:{zh:`/assets/steer.zh-BCINYQs7.mp3`,en:`/assets/steer.en-1RIP4K_0.mp3`},error:{zh:`/assets/error.zh-DdFp64-u.mp3`,en:`/assets/error.en-BGPHdZVi.mp3`},approval:{zh:`/assets/approval.zh-DWqP6Pcu.mp3`,en:`/assets/approval.en-BFhMPNWP.mp3`}},ka={done:`done`,stopped:`done`,steer:`steer`,error:`error`,approval:`approval`};function Aa(e,t){return Oa[e][t]}var ja=new Map;function Ma(e,t){let n=ja.get(t);if(n)return n;let r=fetch(t).then(e=>e.ok?e.arrayBuffer():Promise.reject(Error(String(e.status)))).then(t=>e.decodeAudioData(t)).catch(e=>(ja.delete(t),console.warn(`[voice-clips] 状态语音解码失败`,t,e),null));return ja.set(t,r),r}function Na(e,t={}){let n=U();if(!n.enabled&&t.force!==!0)return;let r=t.language??ye(),i=t.volume??ie(n),a=ne();if(!a){fe(ka[e],n);return}let o=Date.now();Ma(a,Aa(e,r)).then(t=>{if(!t){fe(ka[e],n);return}if(!de(o))return;let r=()=>{let e=a.createBufferSource(),n=a.createGain();e.buffer=t,n.gain.value=i,e.connect(n),n.connect(a.destination),e.start()};re(a)?r():a.resume().then(()=>{de(o)&&(re(a)?r():fe(ka[e],n))}).catch(()=>fe(ka[e],n))}).catch(()=>fe(ka[e],n))}function Pa(){let e=ne();if(e)for(let t of Object.keys(Oa))for(let n of[`zh`,`en`])Ma(e,Aa(t,n))}function Fa(){return{prevStatus:new Map,turnStartMark:new Map,awaitingEnd:new Map,announcedTurns:new Set,startedTurns:new Set,seenErrors:new Set,lastApprovalId:null,knownConversations:new Set,seenSteers:new Set}}function Ia(e){return e.kind===`start`||!e.voiceEnabled?`beep`:e.kind===`done`&&e.readReplies&&e.hasReply?`reply`:`clip`}function La(){return{lastText:null,lastAt:0}}var Ra=`\0sound`,za=`\0stopped`;function Ba(e,t,n,r=`done`){let i=t??(r===`stopped`?za:Ra);return e.lastText===i&&n-e.lastAt<1500?!1:(e.lastText=i,e.lastAt=n,!0)}function Va(e){if(!e)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n&&n.role===`assistant`)return n}return null}function Ha(e,t){return!t||t.endedAt===void 0?!1:!e||t.id!==e.id||t.endedAt!==e.endedAt}var Ua=200;function Wa(e,t){let n=[],r=t.active.conversationId,i=t.active.messages,a=e=>{let n=t.runningByConversation[e]?.status;return n===void 0?t.running.conversationId===e&&t.running.status!==`idle`?t.running.status:`idle`:n},o=e=>t.runningByConversation[e]?.turnStartedAt??(t.running.conversationId===e?t.running.turnStartedAt??null:null),s=(e,t)=>t?.stopped===!0?{kind:`stopped`,conversationId:e,message:t}:{kind:`done`,conversationId:e,message:t},c=(t,n,i)=>{if(!(t!==r||Ha(n,i)))return!1;let a=t===r&&i?`${t}:msg:${i.id}:${i.endedAt??``}`:`${t}:turn:${n?.turnStartedAt??`?`}`;return!e.announcedTurns.has(a)&&(e.announcedTurns.add(a),Ga(e.announcedTurns),!0)};if(e.awaitingEnd.size>0)for(let[t,a]of e.awaitingEnd){if(t!==r){e.awaitingEnd.delete(t);continue}let o=Va(i);o?.endedAt!==void 0&&(e.awaitingEnd.delete(t),c(t,a,o)&&n.push(s(t,o)))}let l=new Set([...e.prevStatus.keys(),...Object.keys(t.runningByConversation)]);r!==null&&l.add(r);for(let t of l){let l=e.prevStatus.get(t)??`idle`,u=a(t);if(e.prevStatus.set(t,u),l!==u){if(u===`streaming`&&l!==`streaming`){let a=t===r?Va(i):null,s=o(t);e.turnStartMark.set(t,a?{id:a.id,endedAt:a.endedAt,turnStartedAt:s}:null),e.awaitingEnd.delete(t);let c=`${t}:turn:${s??`?`}`;if(s!==null&&e.startedTurns.has(c))continue;e.startedTurns.add(c),Ga(e.startedTurns),n.push({kind:`start`,conversationId:t})}else if(l===`streaming`&&u!==`streaming`){let a=e.turnStartMark.get(t)??null;e.turnStartMark.delete(t);let o=t===r?Va(i):null;if(t===r&&o&&o.endedAt===void 0){e.awaitingEnd.set(t,a);continue}c(t,a,o)&&n.push(s(t,o))}}}if(r!==null){let t=i.filter(e=>e.role===`user`&&e.steer===!0);if(e.knownConversations.has(r)){for(let i of t){let t=`${r}:${i.id}`;e.seenSteers.has(t)||(e.seenSteers.add(t),n.push({kind:`steer`,conversationId:r}))}Ga(e.seenSteers)}else{e.knownConversations.add(r),Ga(e.knownConversations);for(let n of t)e.seenSteers.add(`${r}:${n.id}`)}}let u=t.pendingApproval?.requestId??null;u!==null&&u!==e.lastApprovalId?(e.lastApprovalId=u,n.push({kind:`approval`})):u===null&&(e.lastApprovalId=null);let d=(t.notices??[]).filter(e=>e.level===`error`),f=d.find(t=>!e.seenErrors.has(t.id));for(let t of d)e.seenErrors.add(t.id);return Ga(e.seenErrors),f&&n.push({kind:`error`}),n}function Ga(e){if(e.size<=Ua)return;let t=[...e].slice(-200);e.clear();for(let n of t)e.add(n)}function Ka(e,t,n=0){bt(e,t,n>=1?{}:{onIssue:(r,i)=>{i.wakeable&&window.setTimeout(()=>Ka(e,t,n+1),qa)}})}var qa=1200;function Ja(e){return e.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
3
- `)}function Ya(e){return nt(Ja(e))}var Xa=e=>e.kind===`done`;function Za(e,t){let n=t===null?e:[...e.filter(e=>e.conversationId===t),...e];for(let e of n){if(!e.message)continue;let t=Ya(e.message);if(t!==``)return t}return``}function Qa(e){let t=(0,C.useRef)(Fa()),n=(0,C.useRef)(La()),r=(0,C.useRef)(!1),i=(0,C.useRef)({key:``,reader:It(),queue:[],busy:!1,token:0,spoke:!1,spokeConversation:``,conversationId:``,turnStartedAt:0}),a=(0,C.useRef)({conversationId:``,turnStartedAt:0,on:!1}),o=(0,C.useRef)(null),s=()=>{if(!(mn()||na()))return i.current.queue.shift()},c=e=>{let t=i.current;if(mn()||na()||(o.current=e,t.busy))return;let n=t.queue.shift();if(n===void 0)return;t.busy=!0,Yt(!0);let r=++t.token,a=()=>{r===t.token&&(t.busy=!1,t.queue.length===0&&Yt(!1),c(e))};bt(n,e,{onEnd:a,nextText:s,onIssue:e=>{Ut(`read:issue`,{message:e.slice(0,80)}),a()},onCancel:()=>{r===t.token&&(t.busy=!1,t.queue.length=0,Yt(!1))}})},l=(e,t)=>{e.length!==0&&(na()||(Ut(`read:enqueue`,{units:e.length,provider:t.provider,firstLen:e[0]?.length??0}),i.current.queue.push(...e),c(t)))},u=()=>{let e=i.current;e.token+=1,e.busy=!1,e.queue.length=0,e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset(),Yt(!1),Ct()},d=()=>{a.current={conversationId:i.current.conversationId,turnStartedAt:i.current.turnStartedAt,on:!0},u()};(0,C.useEffect)(()=>rn(d),[]);let f=()=>{let e=i.current;Ut(`read:interrupt`,{queued:e.queue.length,spoken:e.reader.spoken}),e.token+=1,e.busy=!1,e.queue.length=0,Yt(!1),Ct()};(0,C.useEffect)(()=>on(f),[]),(0,C.useEffect)(()=>gn(()=>{if(mn())return;let e=o.current;e&&c(e)}),[]);let p=(e,t)=>{let n=i.current;if(!t.enabled||!t.readReplies){r.current||(r.current=!0,Ut(`read:off`,{enabled:t.enabled,readReplies:t.readReplies}));return}let o=e.active.conversationId;if(o===null)return;let s=e.active.messages,c=null;for(let e=s.length-1;e>=0;--e){let t=s[e];if(t&&t.role===`assistant`){c=t;break}}if(!c||c.endedAt!==void 0)return;let u=e.runningByConversation[o],d=e.running.conversationId===o?e.running:null;if((u?.status??d?.status??`idle`)===`idle`)return;let f=c.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
4
- `);if(f===``)return;let p=u?.turnStartedAt??d?.turnStartedAt??0;if(a.current.on&&a.current.conversationId===o){if(a.current.turnStartedAt===p)return;a.current={conversationId:``,turnStartedAt:0,on:!1}}let m=`${o}:${c.id}:${p}`;m!==n.key&&(n.token+=1,n.busy=!1,n.queue.length=0,n.reader.reset(),n.spoke=!1,n.spokeConversation=``,n.key=m,n.conversationId=o,n.turnStartedAt=p,Ct());let h=n.reader.push(f);h.length>0&&(n.spoke=!0,n.spokeConversation=o),l(h,t)};(0,C.useEffect)(()=>{if(!e)return;let r=qe();p(e,r);let o=Wa(t.current,e);if(o.length===0)return;let s=U(),c=[];for(let e of o)e.kind===`done`||e.kind===`stopped`?c.push(e):(e.kind!==`steer`||s.steer)&&(Ia({kind:e.kind,voiceEnabled:r.enabled,readReplies:r.readReplies,hasReply:!1})===`clip`&&e.kind!==`start`?Na(e.kind):fe(e.kind));if(c.length===0)return;let d=c.find(t=>t.conversationId===e.active.conversationId)??c[0],f=d.kind===`done`&&r.enabled&&r.readReplies?Za(c.filter(Xa),e.active.conversationId):``,m=Ia({kind:d.kind,voiceEnabled:r.enabled,readReplies:r.readReplies,hasReply:f!==``}),h=d.kind===`stopped`?`stopped`:`done`;if(h===`stopped`&&a.current.conversationId===d.conversationId&&(a.current={conversationId:``,turnStartedAt:0,on:!1}),h===`stopped`&&u(),Ba(n.current,m===`reply`?f:null,Date.now(),h)){if(m===`reply`){let e=i.current;if(a.current.on&&a.current.conversationId===d.conversationId)e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset();else if(e.spoke&&e.spokeConversation===d.conversationId){let t=d.message?e.reader.push(Ja(d.message)):[];l([...t,...e.reader.flush()],r),e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset()}else Ka(f,r)}else m===`clip`?Na(h):fe(`done`)}},[e]),(0,C.useEffect)(()=>{let e=window.setTimeout(Pa,2e3);return()=>window.clearTimeout(e)},[])}var $a=200,eo=`pop-agent.unseen-finish`,to=(e,t)=>e.visible&&e.activeId===t;function no(e,t,n){let r=null,i=()=>(r??={...e},r);for(let e of t)n.running.includes(e)||to(n,e)||(i()[e]=n.now);for(let t of n.running)(r?.[t]!==void 0||e[t]!==void 0)&&delete i()[t];return n.activeId!==null&&to(n,n.activeId)&&(r?.[n.activeId]!==void 0||e[n.activeId]!==void 0)&&delete i()[n.activeId],r??e}function ro(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>t[n]===e[n])}function io(e){let t=Object.entries(e).filter(([,e])=>Number.isFinite(e)&&e>0);return t.length<=$a?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,$a)))}function ao(e){if(!e)return{};try{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))e!==``&&typeof r==`number`&&Number.isFinite(r)&&r>0&&(n[e]=r);return io(n)}catch{return{}}}function oo(){try{return typeof localStorage>`u`?{}:ao(localStorage.getItem(eo))}catch{return{}}}var so=oo(),co=new Set;function lo(){for(let e of co)e()}function uo(e){try{localStorage.setItem(eo,JSON.stringify(e))}catch{}}function fo(e){let t=io(e);ro(so,t)||(so=t,uo(t),lo())}function po(){return so}function mo(e){return co.add(e),()=>{co.delete(e)}}function ho(e){if(so[e]===void 0)return;let{[e]:t,...n}=so;fo(n)}function go(e){if(!e.some(e=>so[e]!==void 0))return;let t={...so};for(let n of e)delete t[n];fo(t)}function _o(e,t){fo(no(so,e,t))}typeof window<`u`&&window.addEventListener(`storage`,e=>{if(e.key!==eo)return;let t=ao(e.newValue);ro(so,t)||(so=t,lo())});function vo(){if(typeof document>`u`)return;let e=document.querySelector(`.composer-input`);if(!e)return;e.focus();let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}}var yo={snapshot:null,connection:`connecting`,lastError:null,draft:``,settingsOpen:!1,pendingActive:null,creating:!1,pendingNewChat:!1,newSession:null,preview:null},bo=new Set;function xo(){return yo}function So(e){Fo({draft:e})}var Co=`\0new-session`,wo=new Map,To=40,Eo=null;function Do(e){return e??Co}function Oo(){if(Eo!==null)return Eo;let e=xo();return Eo=e.newSession?Co:Do(e.pendingActive??e.snapshot?.active.conversationId??null),Eo}function ko(e,t){if(wo.set(e,t),!(wo.size<=To)){for(let t of wo.keys())if(t!==e){wo.delete(t);break}}}function Ao(e){let t=Oo(),n=Do(e);if(t===n)return;yo.draft===``?wo.delete(t):ko(t,yo.draft),Eo=n;let r=wo.get(n)??``;r!==yo.draft&&Fo({draft:r})}function jo(e){wo.delete(Do(e)),Eo===Do(e)&&(Eo=null)}function Mo(e){vo(),Ao(null);let t=xo().snapshot?.files?.root??null;Fo({newSession:{workspace:e===void 0?t:e,ephemeral:!1}})}function No(e){let t=xo().newSession;t&&Fo({newSession:{...t,workspace:e}})}function Po(e){let t=xo().newSession;t&&Fo({newSession:{...t,ephemeral:e}})}function Fo(e){yo={...yo,...e};for(let e of bo)e()}function Io(e){return bo.add(e),()=>{bo.delete(e)}}function Lo(){return(0,C.useSyncExternalStore)(Io,xo,xo)}function Ro(e){let t=(0,C.useRef)(e);t.current=e;let n=(0,C.useRef)(null),r=()=>{let e=t.current(xo());return n.current!==null&&Object.is(n.current.value,e)?n.current.value:(n.current={value:e},e)};return(0,C.useSyncExternalStore)(Io,r,r)}var zo=[];function Bo(e){zo=e}function Vo(){return zo}function Ho(){return(0,C.useSyncExternalStore)(mo,po,po)}function Uo(){return typeof document>`u`||document.visibilityState===`visible`}function Wo(e){let t=new Set;for(let[n,r]of Object.entries(e.runningByConversation??{}))r.status!==`idle`&&t.add(n);let n=e.running;return n.status!==`idle`&&n.conversationId&&t.add(n.conversationId),[...t]}function Go(){let e=Ro(e=>e.snapshot),[t,n]=(0,C.useState)(Uo),r=(0,C.useRef)([]);(0,C.useEffect)(()=>{let e=()=>n(Uo());return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),(0,C.useEffect)(()=>{if(!e)return;let n=Wo(e);_o(r.current,{running:n,activeId:e.active.conversationId,visible:t,now:Date.now()}),r.current=n},[e,t])}var Ko=n(),Q=r();function qo(){let e=document.querySelector(`.workspace .composer-wrap`);if(!e)return null;let t=getComputedStyle(e),n=e.getBoundingClientRect(),r=Number.parseFloat(t.paddingLeft)||0,i=Number.parseFloat(t.paddingRight)||0,a=n.width-r-i;return a>0?{left:n.left+r,width:a}:null}function Jo(e){(0,C.useEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=qo();e?(t.classList.add(`toast-host-in-column`),t.style.left=`${Math.round(e.left)}px`,t.style.width=`${Math.round(e.width)}px`,t.style.maxWidth=`none`):(t.classList.remove(`toast-host-in-column`),t.style.removeProperty(`left`),t.style.removeProperty(`width`),t.style.removeProperty(`max-width`))};n();let r=document.querySelector(`.workspace .composer-wrap`),i=new ResizeObserver(n);return r&&i.observe(r),window.addEventListener(`resize`,n),()=>{i.disconnect(),window.removeEventListener(`resize`,n)}},[e])}function Yo({item:e}){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(0),i=(0,C.useRef)(Date.now());return(0,C.useEffect)(()=>{if(t){r.current+=Date.now()-i.current;return}i.current=Date.now();let n=window.setTimeout(()=>rr(e.id),Math.max(1200,e.ttl-r.current));return()=>window.clearTimeout(n)},[t,e.id,e.ttl]),(0,Q.jsxs)(`div`,{className:`toast`,role:`status`,"aria-live":`polite`,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[(0,Q.jsx)(`span`,{className:`toast-text`,title:e.text,children:e.text}),e.actions.map(t=>(0,Q.jsx)(`button`,{type:`button`,className:`toast-action`,onClick:()=>{t.onClick(),rr(e.id)},children:t.label},t.label)),(0,Q.jsx)(`button`,{type:`button`,className:`toast-close`,title:`关掉`,onClick:()=>rr(e.id),children:`×`})]})}function Xo({children:e}){let t=(0,C.useRef)(null);return Jo(t),(0,Q.jsx)(`div`,{className:`toast-host`,ref:t,children:e})}function Zo(){let e=or();return e.length===0?null:(0,Ko.createPortal)((0,Q.jsx)(Xo,{children:e.map(e=>(0,Q.jsx)(Yo,{item:e},e.id))}),document.body)}var Qo=null,$o=new Set;function es(){for(let e of $o)e()}function ts(e){return $o.add(e),()=>{$o.delete(e)}}function ns(e,t=``){e&&(Qo={src:e,alt:t},es())}function rs(){Qo&&(Qo=null,es())}function is(){return(0,C.useSyncExternalStore)(ts,()=>Qo)}var as=.25,os=1.25;function ss(e){return!Number.isFinite(e)||e<=0?1:Math.min(8,Math.max(as,e))}function cs(e,t){let n=ss(e);return ss(t===`in`?n*os:n/os)}function ls(e,t,n=.94){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return 1;let r=Math.min(t.width*n/e.width,t.height*n/e.height);return!Number.isFinite(r)||r<=0||r>1?1:r}var us=`\\/:*?"<>|`,ds=100;function fs(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e<32||e===127||us.includes(n)?`_`:n}return t}function ps(e){let t=e.trim();if(t===``)return``;if(/^https?:\/\//i.test(t))try{t=new URL(t).pathname}catch{return``}t=t.split(`?`)[0]?.split(`#`)[0]??``;try{t=decodeURIComponent(t)}catch{}let n=fs(t.split(/[\\/]/).at(-1)??``).trim();return n.length>ds?n.slice(0,ds):n}function ms(e,t=``){let n=[t,/[?&]path=([^&#]*)/.exec(e)?.[1]??``,e].map(ps).filter(e=>e!==``);return n.find(e=>/\.[A-Za-z0-9]{1,8}$/.test(e))??n[0]??`image`}function hs(){let e=is(),t=J(),n=e!==null,[r,i]=(0,C.useState)(1),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(1),[l,u]=(0,C.useState)(!1),d=e?.src??``;(0,C.useEffect)(()=>{i(1),o(null),c(1),u(!1)},[d]),(0,C.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`?rs():e.metaKey||e.ctrlKey||e.altKey||(e.key===`+`||e.key===`=`?i(e=>cs(e,`in`)):e.key===`-`||e.key===`_`?i(e=>cs(e,`out`)):e.key===`0`&&i(1))};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[n]);let f=(0,C.useCallback)(e=>{let t=e.currentTarget,n=t.naturalWidth,r=t.naturalHeight;n<=0||r<=0||(o({width:n,height:r}),c(ls({width:n,height:r},{width:window.innerWidth,height:window.innerHeight})))},[]),p=(0,C.useCallback)(async()=>{if(!d||l)return;let t=ms(d,e?.alt??``);u(!0);try{let e=await fetch(d,{credentials:`same-origin`});if(!e.ok)throw Error(String(e.status));let n=await e.blob(),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(r),1e4)}catch{window.open(d,`_blank`,`noopener,noreferrer`)}finally{u(!1)}},[l,e?.alt,d]);if(!e)return null;let m=r!==1&&a!==null?{width:Math.round(a.width*s*r),height:`auto`,maxWidth:`none`,maxHeight:`none`}:void 0,h=Math.round(s*r*100);return(0,Ko.createPortal)((0,Q.jsxs)(`div`,{className:`image-viewer-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`图片预览`,`Image preview`),onClick:()=>rs(),children:[(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-close`,title:t(`关闭(Esc)`,`Close (Esc)`),"aria-label":t(`关闭`,`Close`),onClick:()=>rs(),children:`×`}),(0,Q.jsx)(`div`,{className:`image-viewer-stage`,onClick:e=>{e.target===e.currentTarget&&rs()},children:(0,Q.jsx)(`img`,{className:`image-viewer-img`,src:d,alt:e.alt,style:m,onLoad:f})}),(0,Q.jsxs)(`div`,{className:`image-viewer-tools`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool`,title:t(`缩小(-)`,`Zoom out (-)`),"aria-label":t(`缩小`,`Zoom out`),disabled:r<=as,onClick:()=>i(e=>cs(e,`out`)),children:`−`}),(0,Q.jsxs)(`button`,{type:`button`,className:`image-viewer-zoom`,title:t(`点一下回到适应窗口(0)`,`Click to reset to fit (0)`),onClick:()=>i(1),children:[h,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool`,title:t(`放大(+)`,`Zoom in (+)`),"aria-label":t(`放大`,`Zoom in`),disabled:r>=8,onClick:()=>i(e=>cs(e,`in`)),children:`+`}),(0,Q.jsx)(`span`,{className:`image-viewer-divider`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool image-viewer-download`,title:t(`下载这张图`,`Download this image`),disabled:l,onClick:()=>void p(),children:t(`下载`,`Download`)})]})]}),document.body)}var gs=260,_s=`pop-agent.sidebar.width`,vs=`pop-agent.sidebar.collapsed`;function ys(e,t=2**53-1){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,240),Math.max(240,t))):gs}function bs(e){return!Number.isFinite(e)||e<=0?2**53-1:Math.max(240,Math.round(e-240))}function xs(e){return e===null?gs:ys(Number(e))}function Ss(e){return e.stored===`1`||e.stored!==`0`&&e.tablet}function Cs(e){return e(`(pointer: coarse) and (min-width: 601px) and (max-width: 1366px)`)}var ws=[{id:`newChat`,label:`新会话`,labelEn:`New session`,hint:`换掉左边这条主对话,会落盘`,hintEn:`Replaces the main chat on the left; it is saved`,defaultCombo:`Mod+Alt+N`},{id:`newProject`,label:`新项目`,labelEn:`New project`,hint:`打开目录选择器;macOS 上 ⌘M 会被系统「最小化」抢走,所以默认避开 ⌘M`,hintEn:`Opens the directory picker; ⌘M is taken by Window ▸ Minimize on macOS, so it is avoided`,defaultCombo:`Mod+Alt+X`},{id:`tempChat`,label:`临时会话`,labelEn:`Temp session`,hint:`在右侧另开一条不落盘的聊天`,hintEn:`Opens an unsaved chat on the right`,defaultCombo:`Mod+Alt+H`},{id:`settings`,label:`设置`,labelEn:`Settings`,defaultCombo:`Mod+Comma`},{id:`toggleRight`,label:`收起 / 展开右侧栏`,labelEn:`Toggle right panel`,hint:`同一个键开 / 关:关着就打开,开着就收起`,hintEn:`Opens and closes with the same key`,defaultCombo:`Mod+Alt+O`},{id:`toggleLeft`,label:`收起 / 展开左侧栏`,labelEn:`Toggle left sidebar`,defaultCombo:`Mod+Alt+L`},{id:`projects`,label:`项目`,labelEn:`Projects`,hint:`侧栏里「项目」那一栏的开关;侧栏收着时会先展开`,hintEn:`Toggles the Projects section in the sidebar; expands the sidebar if it was collapsed`,defaultCombo:`Mod+Alt+P`},{id:`files`,label:`文件`,labelEn:`Files`,hint:`同一个键开 / 关:右侧面板里的「文件」页开着就收起`,hintEn:`Opens and closes with the same key; expands the sidebar if it was collapsed`,defaultCombo:`Mod+Alt+F`},{id:`canvas`,label:`画布`,labelEn:`Canvas`,hint:`同一个键开 / 关:没开就打开画布标签,已经开着就收起来`,hintEn:`Opens and closes the canvas tab with the same key`,defaultCombo:`Mod+Alt+C`},{id:`terminal`,label:`切换终端`,labelEn:`Toggle terminal`,hint:"Ctrl+` —— 显示 / 隐藏对话框下面的终端(隐藏时进程不断);mac ⌘` 会被系统「切换窗口」先吃掉,所以用 ⌃",hintEn:"Ctrl+` — shows / hides the terminal under the chat (shells keep running while hidden); on macOS ⌘` is taken by “cycle windows”, hence ⌃",defaultCombo:`Ctrl+Backquote`},{id:`contentSearch`,label:`搜索文件内容`,labelEn:`Search file contents`,hint:`全文搜索浮层(改键后文件管理里那句提示也会跟着变)`,hintEn:`Full-text search overlay; the hint in the file manager follows this binding`,defaultCombo:`Mod+Shift+F`},{id:`toggleMic`,label:`开始 / 停止语音输入`,labelEn:`Start / stop voice input`,hint:`按一下开、一直听着,再按一下关;也可以按住不放说一句短的,松手就停(设置里能录右⌘ / 右⌥,也能录成只按这一颗)`,hintEn:`Tap to keep listening, tap again to stop; or hold and release to say one short thing (right ⌘ / right ⌥ work, alone or with a key)`,defaultCombo:`Mod+Alt+M`},{id:`pauseSpeech`,label:`暂停 / 继续朗读`,labelEn:`Pause / resume reading`,hint:`冻住正在念的这句,再按一次从原地接着念(不会跳过后面的内容);朗读中浮条上也有这颗按钮`,hintEn:`Freezes the current sentence; press again to continue from the same spot (nothing later gets skipped). Also a button on the floating bar`,defaultCombo:`Mod+Shift+P`},{id:`stopSpeech`,label:`停止朗读`,labelEn:`Stop reading aloud`,hint:`停掉正在念的这句;这一轮剩下的文字也不再自动念(朗读中底部也会出现一颗按钮)`,hintEn:`Stops the current sentence; the rest of this turn stays silent (a button also appears while reading)`,defaultCombo:`Mod+Alt+S`},{id:`cheatSheet`,label:`快捷键速查表`,labelEn:`Shortcut cheat sheet`,hint:`浮层列出当前所有绑定(就是这份表);再按一次关掉`,hintEn:`Shows every binding as an overlay; press again to close`,defaultCombo:`Mod+Slash`}],Ts=`pop-agent.shortcuts`,Es=`pop-agent:shortcuts`,Ds=new Set([`Enter`,`Space`,`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Comma`,`Period`,`Slash`,`Backquote`,`Minus`,`Equal`,`BracketLeft`,`BracketRight`,`Semicolon`,`Quote`,`Backslash`]),Os=new Set([`Meta`,`Control`,`Shift`,`Alt`,`AltGraph`,`CapsLock`,`Dead`]),ks=new Set([`Mod+T`,`Mod+Shift+T`,`Mod+W`,`Mod+Shift+W`,`Mod+N`,`Mod+Shift+N`,`Mod+R`,`Mod+Shift+R`,`Mod+Q`,`Mod+L`,`Mod+P`,`Mod+Shift+J`,`Mod+Shift+I`,`Mod+Alt+I`]);function As(e){let t=e.code??``,n=/^Key([A-Z])$/.exec(t);if(n?.[1])return n[1];let r=/^Digit([0-9])$/.exec(t);if(r?.[1])return r[1];let i=/^F([1-9]|1[0-2])$/.exec(t);return i?.[0]?i[0]:Ds.has(t)?t:/^[a-zA-Z0-9]$/.test(e.key)?e.key.toUpperCase():e.key===` `||e.key===`Spacebar`?`Space`:Os.has(e.key)?null:Ds.has(e.key)?e.key:null}function js(e){return As(e)}var Ms={Mod:{mod:!0,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1},RightMod:{mod:!0,ctrl:!1,shift:!1,alt:!1,modRight:!0,altRight:!1},Alt:{mod:!1,ctrl:!1,shift:!1,alt:!0,modRight:!1,altRight:!1},RightAlt:{mod:!1,ctrl:!1,shift:!1,alt:!0,modRight:!1,altRight:!0},Ctrl:{mod:!1,ctrl:!0,shift:!1,alt:!1,modRight:!1,altRight:!1}},Ns=/^F([1-9]|1[0-2])$/;function Ps(e){if(!e)return null;let t=e.split(`+`);if(t.length===1){let e=t[0]??``,n=Ms[e];return n?{...n,key:``}:Ns.test(e)?{mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:e}:null}let n=t[t.length-1]??``;if(n===``)return null;let r={mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:n};for(let e of t.slice(0,-1))if(e===`Mod`)r.mod=!0;else if(e===`RightMod`)r.mod=!0,r.modRight=!0;else if(e===`RightAlt`)r.alt=!0,r.altRight=!0;else if(e===`Ctrl`)r.ctrl=!0;else if(e===`Shift`)r.shift=!0;else if(e===`Alt`)r.alt=!0;else return null;return!r.mod&&!r.ctrl&&!r.alt?null:/^[A-Z0-9]$/.test(n)||/^F([1-9]|1[0-2])$/.test(n)||Ds.has(n)?r:null}function Fs(e){let t=[];return e.mod&&t.push(e.modRight?`RightMod`:`Mod`),e.ctrl&&t.push(`Ctrl`),e.shift&&t.push(`Shift`),e.alt&&t.push(e.altRight?`RightAlt`:`Alt`),e.key!==``&&t.push(e.key),t.join(`+`)}function Is(e,t){return!(!e||!t||e.key!==t.key||e.mod!==t.mod||e.ctrl!==t.ctrl||e.shift!==t.shift||e.alt!==t.alt||e.modRight&&!t.modRight||e.altRight&&!t.altRight)}function Ls(e){let t=Ps(e);return t?Fs(t):null}var Rs={mod:!1,alt:!1};function zs(e,t=oc()){let n=e.type!==`keyup`;e.code===(t?`MetaRight`:`ControlRight`)?Rs.mod=n:e.code===`AltRight`&&(Rs.alt=n)}function Bs(){Rs.mod=!1,Rs.alt=!1}function Vs(e,t,n=Rs){let r=As(e);if(!r)return null;let i=t?!!e.metaKey:!!e.ctrlKey,a=t?!!e.ctrlKey:!1,o=!!e.altKey;return!i&&!a&&!o?Ns.test(r)?{mod:!1,modRight:!1,ctrl:!1,shift:!!e.shiftKey,alt:!1,altRight:!1,key:r}:null:t&&a&&!i&&/^[A-Z0-9]$/.test(r)?null:{mod:i,modRight:i&&n.mod,ctrl:a,shift:!!e.shiftKey,alt:o,altRight:o&&n.alt,key:r}}function Hs(e,t=oc()){let n=Vs(e,t);return n?Fs(n):null}function Us(e,t=oc()){let n=Ps(e);return n?!t&&n.ctrl?{...n,ctrl:!1,mod:!0,modRight:!1}:n:null}function Ws(e,t,n=oc()){let r=Vs(t,n);if(!r)return null;for(let t of ws)if(Is(Us(e[t.id],n),r))return t.id;return null}function Gs(e){let t=Ps(e);return t?ks.has(Fs({...t,modRight:!1,altRight:!1})):!1}function Ks(e,t=oc()){let n=e.code??``,r={mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:``},i=t?`Meta`:`Control`;return n===`${i}Left`?{...r,mod:!0}:n===`${i}Right`?{...r,mod:!0,modRight:!0}:n===`AltLeft`?{...r,alt:!0}:n===`AltRight`?{...r,alt:!0,altRight:!0}:t&&(n===`ControlLeft`||n===`ControlRight`)?{...r,ctrl:!0}:null}function qs(e,t=oc()){return Ks(e,t)!==null}function Js(e,t=oc()){let n=Ks(e,t);return n?Fs(n):null}function Ys(e,t,n=oc()){let r=Ks(t,n);if(!r)return null;for(let t of ws)if(Is(Us(e[t.id],n),r))return t.id;return null}function Xs(){let e={};for(let t of ws)e[t.id]=Ls(t.defaultCombo);return Zs(e)}function Zs(e){let t=[],n={};for(let r of ws){let i=Ls(e[r.id]),a=Ps(i),o=a!==null&&t.some(e=>Is(e,a)||Is(a,e));!i||!a||o?n[r.id]=null:(t.push(a),n[r.id]=i)}return n}var Qs={toggleRight:[`openRight`,`closeRight`]};function $s(e){let t=null;try{t=e?JSON.parse(e):null}catch{t=null}let n=t&&typeof t==`object`?t:{},r={};for(let e of ws){if(!(e.id in n)){let t=Qs[e.id]?.find(e=>typeof n[e]==`string`);if(t){r[e.id]=Ls(n[t]);continue}r[e.id]=Ls(e.defaultCombo);continue}let t=n[e.id],i=t===null?null:Ls(typeof t==`string`?t:null);r[e.id]=t===null?null:i??Ls(e.defaultCombo)}return Zs(r)}function ec(){if(typeof localStorage>`u`)return Xs();try{return $s(localStorage.getItem(Ts))}catch{return Xs()}}function tc(e){let t=Zs(e);try{localStorage.setItem(Ts,JSON.stringify(t))}catch{}window.dispatchEvent(new CustomEvent(Es,{detail:t}))}function nc(e){let t=()=>e(),n=t=>{t.key===`pop-agent.shortcuts`&&e()};return window.addEventListener(Es,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Es,t),window.removeEventListener(`storage`,n)}}function rc(e,t,n=350){return t?`stop`:e>=n?`startHold`:`start`}function ic(e,t,n,r=oc()){let i=Us(t,r);if(!i)return null;for(let t of ws){if(t.id===n)continue;let a=Us(e[t.id],r);if(Is(a,i)||Is(i,a))return t.id}return null}function ac(e){let t=ws.find(t=>t.id===e);return{zh:t?.label??e,en:t?.labelEn??e}}function oc(){if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)}var sc={Enter:[`⏎`,`Enter`],Space:[`Space`,`Space`],ArrowUp:[`↑`,`↑`],ArrowDown:[`↓`,`↓`],ArrowLeft:[`←`,`←`],ArrowRight:[`→`,`→`],Comma:[`,`,`,`],Period:[`.`,`.`],Slash:[`/`,`/`],Backquote:["`","`"],Minus:[`-`,`-`],Equal:[`=`,`=`],BracketLeft:[`[`,`[`],BracketRight:[`]`,`]`],Semicolon:[`;`,`;`],Quote:[`'`,`'`],Backslash:[`\\`,`\\`]};function cc(e,t=oc()){let n=Ps(e);if(!n)return``;let r=[];if(t?(n.ctrl&&r.push(`⌃`),n.mod&&r.push(n.modRight?`右⌘`:`⌘`),n.shift&&r.push(`⇧`),n.alt&&r.push(n.altRight?`右⌥`:`⌥`)):(n.mod?r.push(n.modRight?`RightCtrl`:`Ctrl`):n.ctrl&&r.push(`Ctrl`),n.shift&&r.push(`Shift`),n.alt&&r.push(n.altRight?`RightAlt`:`Alt`)),n.key!==``){let e=sc[n.key];r.push(e?e[+!t]:n.key)}return t?r.join(``):r.join(`+`)}var lc=null;function uc(e){return lc=e,()=>{lc===e&&(lc=null)}}function dc(){return lc?(lc(),!0):!1}var fc=!1,pc=new Set;function mc(){for(let e of pc)e()}function hc(e){return pc.add(e),()=>{pc.delete(e)}}function gc(){fc||(fc=!0,mc())}function _c(){fc&&(fc=!1,mc())}function vc(){fc?_c():gc()}function yc(){return(0,C.useSyncExternalStore)(hc,()=>fc)}function bc(e,t=oc()){return ws.map(n=>{let r=Ls(e[n.id]);return{id:n.id,label:n.label,labelEn:n.labelEn,combo:r?cc(r,t):null}})}function xc(){let[e,t]=(0,C.useState)(()=>ec());return(0,C.useEffect)(()=>nc(()=>t(ec())),[]),[e,(0,C.useCallback)(e=>tc(e),[])]}var Sc=`pop-agent.preview.tabs.v1`;function Cc(e){return e.kind===`file`&&e.path&&e.root!==void 0?{kind:`file`,path:e.path,root:e.root}:e.kind===`web`?{kind:`web`,url:e.url??``}:e.kind===`files`?{kind:`files`}:null}function wc(e){let t=[];return e.slice(0,10).forEach((e,n)=>{e.kind===`file`?t.push({id:`file:${e.root}:${e.path}`,kind:`file`,path:e.path,root:e.root}):e.kind===`web`?t.push({id:`web:restored:${n}`,kind:`web`,url:e.url}):t.push({id:`files:restored:${n}`,kind:`files`})}),t}function Tc(e){if(e===null)return null;try{let t=JSON.parse(e);if(!Array.isArray(t?.tabs))return null;let n=t.tabs.filter(Ec);return n.length===0?null:{tabs:n.slice(0,10),active:typeof t.active==`string`?t.active:null,open:t.open===!0}}catch{return null}}function Ec(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.kind===`file`?typeof t.path==`string`&&t.path!==``&&typeof t.root==`string`:t.kind===`web`?typeof t.url==`string`:t.kind===`files`}function Dc(e,t,n){let r=[],i=null;for(let n of e){if(r.length>=10)break;let e=Cc(n);e!==null&&(r.push(e),n.id===t&&(i=n.id))}return JSON.stringify({tabs:r,active:i,open:n})}function Oc(e){let t=new URLSearchParams(e).get(`session`);return t!==null&&t.trim()!==``?t.trim():null}function kc(e,t){let n=new URL(e);return t===null?n.searchParams.delete(`session`):n.searchParams.set(`session`,t),`${n.pathname}${n.search}${n.hash}`}var Ac=`pop-agent-cache`,jc=1,Mc=`transcripts`,Nc=40,Pc=3145728,Fc=null;function Ic(){return Fc??=new Promise(e=>{if(typeof indexedDB>`u`)e(null);else try{let t=indexedDB.open(Ac,jc);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(Mc)||e.createObjectStore(Mc,{keyPath:`id`}).createIndex(`savedAt`,`savedAt`)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}catch{e(null)}}),Fc}function Lc(e){let t=0;for(let n of e){t+=120;for(let e of n.blocks)e.kind===`text`||e.kind===`thinking`?t+=e.text.length*2:t+=240}return t}async function Rc(e){let t=await Ic();return t?new Promise(n=>{try{let r=t.transaction(Mc,`readonly`).objectStore(Mc).get(e);r.onsuccess=()=>{let e=r.result;n(e&&Array.isArray(e.messages)&&e.messages.length>0?e.messages:null)},r.onerror=()=>n(null)}catch{n(null)}}):null}async function zc(e,t){if(t.length===0)return;if(Lc(t)>Pc){await Bc(e);return}let n=await Ic();if(!n)return;let r={id:e,savedAt:Date.now(),messages:t};return new Promise(e=>{try{let t=n.transaction(Mc,`readwrite`),i=t.objectStore(Mc);i.put(r);let a=0;i.index(`savedAt`).openCursor(null,`prev`).onsuccess=e=>{let t=e.target.result;t&&(a+=1,a>Nc&&t.delete(),t.continue())},t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()}catch{e()}})}async function Bc(e){let t=await Ic();if(t)return new Promise(n=>{try{let r=t.transaction(Mc,`readwrite`);r.objectStore(Mc).delete(e),r.oncomplete=()=>n(),r.onerror=()=>n(),r.onabort=()=>n()}catch{n()}})}function Vc(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Hc(e,t){if(Object.is(e,t))return t;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return t;let n=!1,r=t.map((t,r)=>{let i=Hc(e[r],t);return i!==e[r]&&(n=!0),i});return n?r:e}if(Vc(e)&&Vc(t)){let n=Object.keys(t);if(n.length!==Object.keys(e).length)return t;let r=!1,i={};for(let a of n){if(!Object.hasOwn(e,a))return t;let n=Hc(e[a],t[a]);i[a]=n,n!==e[a]&&(r=!0)}return r?i:e}return t}function Uc(e,t){return e==null?t:Hc(e,t)}function Wc(e,t){let n=[...e.blocks],r=n[n.length-1];return r&&r.kind===`text`?n[n.length-1]={kind:`text`,text:r.text+t}:n.push({kind:`text`,text:t}),{...e,blocks:n}}function Gc(){return`/login`}function Kc(){try{if(location.pathname===Gc())return;location.replace(Gc())}catch{}}function qc(e){return e===401&&(Kc(),!0)}function Jc(){try{let e=location.hostname.toLowerCase();return e!==`localhost`&&e!==`127.0.0.1`&&e!==`::1`&&e!==`[::1]`}catch{return!1}}function Yc(){fetch(`/api/auth/logout`,{method:`POST`}).catch(()=>void 0).finally(()=>Kc())}async function Xc(){try{(await fetch(`/api/health`,{cache:`no-store`})).status===401&&Kc()}catch{}}function Zc(e,t){let n=e.indexOf(t);return n<0?1/0:n}function Qc(e,t){let n=[],r=[];for(let i of e)Zc(t,i.id)===1/0?r.push(i):n.push(i);n.sort((e,n)=>Zc(t,e.id)-Zc(t,n.id)||n.startedAt-e.startedAt),r.sort((e,t)=>t.startedAt-e.startedAt);let i=n.reduce((e,t)=>Math.max(e,t.startedAt),-1/0),a=r.filter(e=>e.startedAt>i),o=r.filter(e=>e.startedAt<=i);return[...a,...n,...o]}function $c(e,t,n){if(t===n||!e.includes(n))return e;let r=e.filter(e=>e!==t),i=r.indexOf(n);return i<0?e:(r.splice(i,0,t),r)}function el(e,t,n){let r=new Set(t),i=e.filter(e=>!r.has(e));return[...n,...i]}function tl(e,t){return[t,...e.filter(e=>e!==t)]}function nl(e,t){return e[0]===t?null:tl(e,t)}function rl(){let e=typeof globalThis>`u`?void 0:globalThis.crypto;if(e&&typeof e.randomUUID==`function`)try{return e.randomUUID()}catch{}let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}var il=!1;function al(e){let{wsPath:t,sseUrl:n,handlers:r}=e,i=!1,a=null,o=()=>{let e=new EventSource(n);a=e,e.onopen=()=>r.onOpen(),e.onmessage=e=>r.onMessage(String(e.data)),e.onerror=()=>r.onError?.()};return il?o():(()=>{let e=window.location.protocol===`https:`?`wss`:`ws`,n;try{n=new WebSocket(`${e}://${window.location.host}${t}`)}catch{il=!0,o();return}a={close:()=>n.close()};let s=!1;n.onopen=()=>{s=!0,r.onOpen()},n.onmessage=e=>{typeof e.data==`string`&&r.onMessage(e.data)},n.onerror=()=>r.onError?.(),n.onclose=()=>{i||(s?r.onClose():(il=!0,o()))}})(),{close:()=>{i=!0,a?.close()}}}var ol=8e3,sl=500,cl=`pop-agent-client`;function ll(){let e=sessionStorage.getItem(cl);return e||(e=rl(),sessionStorage.setItem(cl,e)),e}var ul=!1;function dl(){ul=!0;try{sessionStorage.removeItem(cl)}catch{}}var fl=null,pl=0,ml=null;function hl(){ml!==null&&(clearTimeout(ml),ml=null)}var $=0,gl=0,_l=null;function vl(){if(_l!==null)return;if(gl>=3){gl=0;return}let e=Math.min(sl*2**gl,ol);gl+=1,_l=setTimeout(()=>{_l=null,Cl({id:`req-${++$}`,type:`get_state`})},e)}function yl(){if(fl)return;hl(),Fo({connection:`connecting`});let e=`client=${encodeURIComponent(ll())}&slim=1`;fl=al({wsPath:`/ws?${e}`,sseUrl:`/api/events?${e}`,handlers:{onOpen:()=>{pl=0,Fo({connection:`open`,lastError:null}),bl(`get_state`)},onMessage:e=>{let t;try{t=JSON.parse(e)}catch{return}Su(t)},onError:()=>{Xc(),Fo({connection:`connecting`})},onClose:()=>{fl=null,Fo({connection:`closed`});let e=Math.min(sl*2**pl,ol);pl+=1,hl(),ml=setTimeout(()=>{ml=null,(typeof document>`u`||document.visibilityState!==`hidden`)&&yl()},e)}}})}function bl(e){let t=`req-${++$}`;return Cl({id:t,type:e}),t}function xl(){hl(),fl&&(fl.close(),fl=null,Fo({connection:`connecting`}))}function Sl(){typeof document<`u`&&document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?xl():yl()})}function Cl(e){return(async()=>{try{let t=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify(e)});if(!t.ok){if(qc(t.status))return;Fo({lastError:{text:t.status===502||t.status===503||t.status===504?q(`后端正在重启或还没起来(HTTP ${t.status}),稍等自动恢复`,`The backend is restarting or not up yet (HTTP ${t.status}) — it recovers on its own in a moment`):q(`请求失败:HTTP ${t.status}`,`Request failed: HTTP ${t.status}`),conversationId:null}}),vl();return}gl=0;let n=await t.json();for(let e of n.frames??[])try{Su(JSON.parse(e))}catch{}}catch{Fo({lastError:{text:q(`连接尚未就绪,稍后再试`,`The connection is not ready yet — try again in a moment`),conversationId:null}}),vl()}})()}function wl(e){Cl({id:`req-${++$}`,type:`cancel_queued`,payload:{queueId:e}})}function Tl(e){Cl({id:`req-${++$}`,type:`interrupt_subagent`,payload:{runId:e}})}function El(e){Cl({id:`req-${++$}`,type:`save_subagent_profile`,payload:{profile:e}})}function Dl(e){Cl({id:`req-${++$}`,type:`delete_subagent_profile`,payload:{profileId:e}})}function Ol(e){Cl({id:`req-${++$}`,type:`set_subagent_settings`,payload:e})}function kl(){Cl({id:`req-${++$}`,type:`get_state`})}function Al(e,t,n){Cl({id:`req-${++$}`,type:`send_message`,payload:{text:e,...t&&t.length>0?{attachments:t}:{},...n&&n!==`now`?{mode:n}:{}}})}function jl(e){Cl({id:`req-${++$}`,type:`interrupt`,payload:{conversationId:e}})}var Ml=null,Nl=null,Pl=!1,Fl=null,Il=null,Ll=null;function Rl(e,t,n,r,i){Ml={text:e,attachments:t,mode:n},zl(r,i)}function zl(e,t){vo(),Il={from:xo().snapshot?.active.conversationId??null};let n=Il;Fo({creating:!0,pendingNewChat:!0}),setTimeout(()=>{Fo({creating:!1}),Il===n&&n!==null&&(Il=null,Fo({pendingNewChat:!1,...xo().newSession?{newSession:null}:{}}))},8e3);let r={...e?{workspace:e}:{},...t?.ephemeral?{ephemeral:!0}:{}},i=`req-${++$}`;Nl=i,Pl=t?.ephemeral===!0,Cl(Object.keys(r).length>0?{id:i,type:`new_chat`,payload:r}:{id:i,type:`new_chat`})}function Bl(e){let t=`req-${++$}`;Ll={id:t,conversationId:e},Cl({id:t,type:`persist_conversation`,payload:{conversationId:e}})}function Vl(e){Cl({id:`req-${++$}`,type:`close_ephemeral`,payload:{conversationId:e}})}function Hl(e,t){vo(),Fo({creating:!0}),setTimeout(()=>Fo({creating:!1}),8e3);let n=`req-${++$}`;Fl=n,Cl({id:n,type:`fork_session`,payload:{conversationId:e,messageId:t}})}function Ul(e){if(typeof e!=`string`||e===``)return;let t=xo().snapshot?.settings.sessionPrefs;if(!t)return;let n=nl(t.order,e);n&&bu({sessionPrefs:{...t,order:n}})}var Wl=1200;function Gl(e,t){Cl({id:`req-${++$}`,type:`rename_session`,payload:{conversationId:e,title:t}})}function Kl(e){return(async()=>{try{let t=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify({id:`req-${++$}`,type:`suggest_title`,payload:{conversationId:e}})});if(!t.ok)return qc(t.status)||Fo({lastError:{text:q(`起名失败:HTTP ${t.status}`,`Could not generate a name: HTTP ${t.status}`),conversationId:e}}),!1;let n=await t.json(),r=!1;for(let t of n.frames??[]){let n=JSON.parse(t);n.type===`reply`&&(r=n.result?.ok===!0),n.type===`reply`&&n.result?.error?.message&&Fo({lastError:{text:n.result.error.message,conversationId:e}}),n.type===`notice`&&n.payload?.message&&!r&&Fo({lastError:{text:n.payload.message,conversationId:e}})}return r}catch(t){return Fo({lastError:{text:q(`起名失败:${t instanceof Error?t.message:String(t)}`,`Could not generate a name: ${t instanceof Error?t.message:String(t)}`),conversationId:e}}),!1}})()}function ql(e,t){Cl({id:`req-${++$}`,type:`move_session`,payload:{conversationId:e,workspace:t}})}function Jl(e,t){Cl({id:`req-${++$}`,type:`refresh_resources`,payload:t?.force?{conversationId:e,force:!0}:{conversationId:e}})}function Yl(e){if(Ao(e),en(),Fo({pendingActive:e,preview:null,newSession:null}),typeof window<`u`){let t=kc(window.location.href,e);window.history.replaceState(null,``,t)}Cl({id:`req-${++$}`,type:`switch_conversation`,payload:{conversationId:e}}),Rc(e).then(t=>{t&&xo().pendingActive===e&&Fo({preview:{conversationId:e,messages:t}})}),setTimeout(()=>{xo().pendingActive===e&&(Cl({id:`req-${++$}`,type:`switch_conversation`,payload:{conversationId:e}}),setTimeout(()=>{xo().pendingActive===e&&Fo({pendingActive:null})},Wl*3))},Wl)}var Xl=null,Zl=null;function Ql(e,t){Zl={conversationId:e,messages:t},!Xl&&(Xl=setTimeout(()=>{Xl=null;let e=Zl;Zl=null,e&&zc(e.conversationId,e.messages)},3e3))}function $l(e){Cl({id:`req-${++$}`,type:`set_thinking_level`,payload:{level:e}})}function eu(e,t){return Cl({id:`req-${++$}`,type:`refresh_actions`,...e||t?{payload:{...e?{conversationId:e}:{},...t?{count:t}:{}}}:{}})}function tu(e){Cl({id:`req-${++$}`,type:`set_engine`,payload:{engine:e}})}function nu(e,t){Cl({id:`req-${++$}`,type:`set_approval_mode`,payload:t?{mode:e,conversationId:t}:{mode:e}})}function ru(e,t,n){Cl({id:`req-${++$}`,type:`canvas_start_node`,payload:{conversationId:e,nodeId:t,...n===void 0?{}:{parent:n}}})}async function iu(e,t,n){try{let r=await fetch(`/api/rpc`,{signal:AbortSignal.timeout(8e3),method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify({id:`req-${++$}`,type:`canvas_suggest`,payload:{conversationId:e,nodeIds:t,...n===void 0?{}:{parent:n}}})});if(!r.ok)return qc(r.status),[];let i=await r.json();for(let e of i.frames??[]){let t=JSON.parse(e);if(t.type!==`reply`)continue;let n=t.result?.suggestions;if(Array.isArray(n))return n.filter(e=>typeof e==`string`)}return[]}catch{return[]}}function au(e,t,n,r){Cl({id:`req-${++$}`,type:`canvas_update_node`,payload:{conversationId:e,nodeId:t,...n,...r===void 0?{}:{parent:r}}})}function ou(e,t,n,r){Cl({id:`req-${++$}`,type:`canvas_set_status`,payload:{conversationId:e,nodeId:t,status:n,...r===void 0?{}:{parent:r}}})}function su(e,t,n){t.length!==0&&Cl({id:`req-${++$}`,type:`canvas_delete`,payload:{conversationId:e,ids:t,...n===void 0?{}:{parent:n}}})}function cu(e,t,n){t.length!==0&&Cl({id:`req-${++$}`,type:`canvas_move`,payload:{conversationId:e,moves:t,...n===void 0?{}:{parent:n}}})}function lu(e,t){Cl({id:`req-${++$}`,type:`set_model`,payload:t?{modelId:e,conversationId:t}:{modelId:e}})}function uu(){Cl({id:`req-${++$}`,type:`list_providers`})}async function du(e){try{let t=await fetch(`/api/templates/generate-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();return n.ok===!0&&typeof n.text==`string`?{ok:!0,text:n.text}:{ok:!1,message:n.message??`HTTP ${t.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function fu(e){try{let t=await fetch(`/api/cron/generate-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();return n.ok===!0&&typeof n.text==`string`?{ok:!0,text:n.text}:{ok:!1,message:n.message??`HTTP ${t.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function pu(e,t){try{let n=await fetch(`/api/providers/${encodeURIComponent(e)}/models/${encodeURIComponent(t)}/test`,{method:`POST`}),r=await n.json();return n.ok?{ok:r.ok===!0,status:r.status,latencyMs:r.latencyMs,message:r.message}:{ok:!1,message:r.error?.message??`HTTP ${n.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function mu(e,t){try{let n=await fetch(`/api/models/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e}),...t?{signal:t}:{}}),r=await n.json();return{ok:r.ok===!0,ttftMs:r.ttftMs??null,totalMs:r.totalMs,outputTokens:r.outputTokens,tps:r.tps??null,averageTps:r.averageTps??null,message:r.message??r.error?.message??(n.ok?void 0:`HTTP ${n.status}`)}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}function hu(e,t){Cl({id:`req-${++$}`,type:`update_model`,payload:{provider:e,model:t}})}function gu(e,t,n){Cl({id:`req-${++$}`,type:`set_enabled_models`,payload:{provider:e,enabled:t,...n?{modelId:n}:{}}})}function _u(e,t){Cl({id:`req-${++$}`,type:`remove_model`,payload:{provider:e,modelId:t}})}function vu(e){Cl({id:`req-${++$}`,type:`delete_provider`,provider:e})}function yu(e){Cl({id:`req-${++$}`,type:`upsert_provider`,payload:e})}function bu(e){Cl({id:`req-${++$}`,type:`set_settings`,payload:e})}function xu(e,t){Cl({id:`req-${++$}`,type:`approve`,payload:{requestId:e,decision:t}})}function Su(e){if(e.type===`reply`){if(Nl!==null&&e.id===Nl){let t=Ml,n=e.ok&&!Pl;Nl=null,Pl=!1,Ml=null,e.ok?(n&&Ul(e.result?.conversationId),t&&Al(t.text,t.attachments,t.mode)):t&&So(t.text),e.ok||(Il=null)}if(Fl!==null&&e.id===Fl&&(Fl=null,e.ok&&Ul(e.result?.conversationId)),Ll!==null&&e.id===Ll.id){let{conversationId:t}=Ll;Ll=null,e.ok&&Ul(t)}e.ok||(xo().pendingActive!==null&&Ao(xo().snapshot?.active.conversationId??null),Fo({lastError:{text:`${e.error.code}: ${e.error.message}`,conversationId:xo().snapshot?.active.conversationId??null},...xo().pendingActive?{pendingActive:null}:{},...xo().preview?{preview:null}:{},...xo().pendingNewChat?{pendingNewChat:!1}:{}}))}else if(e.event===`snapshot`){let t=xo().pendingActive,n=xo().preview,r=xo().snapshot,i=e.snapshot.piProjects??r?.piProjects??[],a=Uc(r,{...e.snapshot,piProjects:i}),o=Il!==null&&e.snapshot.active.conversationId!==Il.from,s=o&&xo().newSession!==null;o&&(Il=null);let c=ul&&t===null&&Il===null&&xo().newSession===null;ul&&=!1,(!t||t===e.snapshot.active.conversationId)&&(s||!xo().newSession)&&Ao(e.snapshot.active.conversationId??null),Fo({snapshot:a,lastError:null,creating:!1,...c?{newSession:{workspace:e.snapshot.files?.root??null,ephemeral:!1}}:{},...o?{pendingNewChat:!1}:{},...s?{newSession:null}:{},...t&&e.snapshot.active.conversationId===t?{pendingActive:null}:{},...n&&n.conversationId===e.snapshot.active.conversationId?{preview:null}:{}});let l=e.snapshot.active.conversationId;l&&Ql(l,e.snapshot.active.messages)}else e.event===`message_delta`&&Cu(e.conversationId,e.messageId,e.text)}function Cu(e,t,n){let r=xo().snapshot;if(!r||r.active.conversationId!==e)return;let i=r.active.messages.map(e=>e.id===t?Wc(e,n):e);Fo({snapshot:{...r,active:{...r.active,messages:i}}})}var wu={name:`pop-agent-text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`sentences`,spellCheck:!1,inputMode:`text`};function Tu(e){return e.replace(/\r\n/g,`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-CQFwDpsY.js","assets/chunk-Y2CYZVJY-DsF7k-Jl.js","assets/chunk-DUW6YSOI-Dgx8z5s3.js","assets/src-BWF7jMDv.js","assets/rolldown-runtime-COiEfhsA.js","assets/chunk-DSNLSHJZ-C_LIPn61.js","assets/chunk-ZAUX2LTX-DP4s36LS.js","assets/chunk-AQDTSKZB-C3NroFBT.js","assets/chunk-7S6XSTFO-0TGPJxiv.js","assets/math-Dh0H2mym.js","assets/chunk-J5ZVWO5B-oDCd-gWO.js","assets/chunk-WQQL4CDK-Dv8ocEd6.js","assets/line-IQmg25td.js","assets/path-fybaL0A-.js","assets/array-BifhSqXX.js","assets/chunk-HNE4Q36P-riaksE6p.js"])))=>i.map(i=>d[i]);
2
+ import{i as e,n as t,r as n,t as r}from"./react-TO3cgmuO.js";import{a as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,s as g,u as _}from"./highlight-DMv0JmTA.js";import{n as v,r as y,t as b}from"./markdown-Bcx45PNe.js";import{n as x,t as S}from"./xterm-C3-Bm0Yw.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)}})();var C=e(),w=t(),T=`https://github.com/duzhenxun/pop-agent`,E=`npm -g install pop-agent@latest`;function D(e){let t=A(e);return t.length===0?e:t[t.length-1]??e}function O(e){let t=A(e);return t.length<=1?``:t.slice(0,-1).join(`/`)}function k(e,t){let n=A(e);return n.length<=t?e:`…/${n.slice(-t).join(`/`)}`}function A(e){return e.split(/[\\/]+/).filter(e=>e!==``)}function j(e){let t=e.trim();if(t===``)return``;let n=/^[A-Za-z]:/.test(t)||!t.startsWith(`/`)&&t.includes(`\\`),r=n?`\\`:`/`,i=t.replace(n?/[\\/]+/g:/\/+/g,r);return i===r||/^[A-Za-z]:[\\/]$/.test(i)||/^[\\/]{2}$/.test(i)?i:i.replace(n?/[\\/]+$/:/\/+$/,``)}function M(){return typeof navigator<`u`&&/windows/i.test(navigator.userAgent)}var N=2,P=6,F=10,I=500,L=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function R(e,t,n=!0){let r=(0,C.useRef)(null),i=(0,C.useRef)(n);i.current=n;let a=(0,C.useRef)(!0),[o,s]=(0,C.useState)(!0),c=(0,C.useRef)(t),l=(0,C.useRef)(-1),u=(0,C.useRef)(null),d=(0,C.useRef)(0),f=(0,C.useRef)(0),p=(0,C.useRef)(0),m=(0,C.useRef)(null),h=(0,C.useRef)(0),[g,_]=(0,C.useState)(0),v=(0,C.useCallback)(e=>{let t=u.current,n=Math.max(0,e.scrollHeight-h.current-e.clientHeight),r=t===null?0:Math.max(0,t-n),i=r===0?0:Math.ceil(r/16)*16;return i!==h.current&&(h.current=i,_(i),!0)},[]),y=(0,C.useCallback)(()=>{u.current=null,d.current=0,f.current&&=(cancelAnimationFrame(f.current),0),h.current!==0&&(h.current=0,_(0))},[]),b=(0,C.useCallback)(()=>{let e=r.current;if(!e||!a.current||!i.current)return;let t=u.current;if(t!==null){if(e.scrollHeight-h.current-(t+e.clientHeight)<=0){if(v(e))return;e.scrollTo({top:t}),l.current=e.scrollTop;return}y()}let n=Math.max(0,e.scrollHeight-h.current-e.clientHeight);e.scrollTo({top:n}),l.current=e.scrollTop},[v,y]),x=(0,C.useCallback)(()=>{p.current||=requestAnimationFrame(()=>{p.current=0,b()})},[b]),S=(0,C.useCallback)(()=>{f.current=0;let e=r.current,t=u.current;!e||t===null||Math.abs(e.scrollTop-t)<=N||d.current>=P?d.current=0:(d.current+=1,!v(e)&&(e.scrollTo({top:t}),l.current=e.scrollTop,f.current=requestAnimationFrame(S)))},[v]),w=(0,C.useCallback)(e=>{if(r.current=e,m.current?.(),m.current=null,!e)return;let t=0,n=!1,i=()=>{t=performance.now()+I},o=()=>{n=!0,i()},c=()=>{n=!1,i()},u=e=>{L.has(e.key)&&i()};e.addEventListener(`wheel`,i,{passive:!0}),e.addEventListener(`touchstart`,i,{passive:!0}),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`keydown`,u),e.addEventListener(`pointerdown`,o,{passive:!0}),window.addEventListener(`pointerup`,c),window.addEventListener(`pointercancel`,c);let h=()=>{let e=r.current;if(!e)return;let i=e.scrollHeight-e.scrollTop-e.clientHeight,o=!n&&performance.now()>t||Math.abs(e.scrollTop-l.current)<=N;if(a.current&&o){l.current=e.scrollTop,i>1&&x();return}let c=i<=80;c||(l.current=-1,y()),c!==a.current&&(a.current=c,s(c))};e.addEventListener(`scroll`,h,{passive:!0});let g=null,_=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>b());_?.observe(e);let v=()=>{let t=e.firstElementChild;t!==g&&(g&&_?.unobserve(g),g=t,g&&_?.observe(g))},S=typeof MutationObserver>`u`?null:new MutationObserver(v);S?.observe(e,{childList:!0}),v(),b(),m.current=()=>{cancelAnimationFrame(p.current),p.current=0,f.current&&cancelAnimationFrame(f.current),f.current=0,d.current=0,e.removeEventListener(`scroll`,h),e.removeEventListener(`wheel`,i),e.removeEventListener(`touchstart`,i),e.removeEventListener(`touchmove`,i),e.removeEventListener(`keydown`,u),e.removeEventListener(`pointerdown`,o),window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),S?.disconnect(),_?.disconnect()}},[b,x]);return(0,C.useEffect)(()=>{c.current!==t&&(c.current=t,a.current=!0,s(!0),y(),b())},[t,b,y]),(0,C.useEffect)(()=>{b()},[e,b]),(0,C.useEffect)(()=>{b()},[g,b]),(0,C.useEffect)(()=>()=>m.current?.(),[]),{ref:w,stuck:o,toBottom:(0,C.useCallback)(()=>{let e=r.current;e&&(a.current=!0,u.current=null,s(!0),e.scrollTo({top:e.scrollHeight,behavior:`auto`}),l.current=e.scrollTop)},[y]),anchorTo:(0,C.useCallback)(e=>{let t=r.current;if(!t||!e)return;let n=e.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop;u.current=Math.max(0,n-F),a.current=!0,s(!0),v(t)||b(),d.current=0,f.current&&cancelAnimationFrame(f.current),f.current=requestAnimationFrame(S)},[v,b,S]),pad:g}}function z(e,t){return e.conversation===t.conversation?t.messageId!==null&&e.messageId!==t.messageId?{seen:t,target:t.messageId}:t.queuedId!==null&&e.queuedId!==t.queuedId?{seen:t,target:t.queuedId}:{seen:t,target:null}:{seen:t,target:null}}var B={enabled:!0,start:!1,steer:!0,done:!0,error:!0,approval:!0,volume:70},V={start:{title:`回复开始`,titleEn:`Reply starts`,hint:`智能体开始新一轮时`,hintEn:`when the agent starts a new turn`},done:{title:`回复结束`,titleEn:`Reply finishes`,hint:`智能体完成一轮回答时`,hintEn:`when the agent finishes a turn`},steer:{title:`插队`,titleEn:`Steering`,hint:`你的追问插进正在跑的这一轮时`,hintEn:`when your follow-up cuts into the running turn`},error:{title:`出错`,titleEn:`Error`,hint:`出现错误提示时`,hintEn:`when an error notice appears`},approval:{title:`等待审批`,titleEn:`Waiting for approval`,hint:`AI 请求执行工具、等待批准时`,hintEn:`when the AI asks to run a tool and waits for approval`}},H=`pop-agent.voice.sound`;function U(){try{let e=localStorage.getItem(H);if(!e)return{...B};let t=JSON.parse(e),n={...B,...t};for(let e of[`enabled`,`start`,`steer`,`done`,`error`,`approval`])typeof n[e]!=`boolean`&&(n[e]=B[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?B.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...B}}}function W(e){try{localStorage.setItem(H,JSON.stringify(e))}catch{}}var ee=null,G=!1;function K(){try{let e=window.AudioContext??window.webkitAudioContext;return e?(ee=new e,ee):null}catch{return null}}function te(e){return e.state===`running`}function ne(){return ae()}function re(e){return te(e)}function ie(e){return Math.max(0,Math.min(1,e.volume/100))}function ae(){try{ee&&ee.state===`closed`&&(ee=null);let e=ee??K();return e?(te(e)||e.resume().catch(()=>{}),e):null}catch{return null}}function oe(){if(G||typeof window>`u`)return;G=!0;let e=()=>{ae()};for(let t of[`pointerdown`,`keydown`,`touchstart`,`click`])window.addEventListener(t,e,{capture:!0,passive:!0});document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}oe();var se={start:[{type:`triangle`,freq:660,start:0,dur:.08,peak:.22}],steer:[{type:`triangle`,freq:740,start:0,dur:.07,peak:.2},{type:`triangle`,freq:988,start:.09,dur:.1,peak:.22}],done:[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],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 ce(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 le(e,t,n){for(let r of se[t])ce(e,r,n)}var ue=1500;function de(e){return Date.now()-e<=ue}function q(e,t=U()){if(!t.enabled||!t[e])return;let n=ae();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));if(te(n)){le(n,e,r);return}let i=Date.now();n.resume().then(()=>{Date.now()-i>ue||te(n)&&le(n,e,r)}).catch(()=>{})}var fe=`pop-agent.language`,pe=`pop-agent:language`,me=`en`,he=[{id:`zh`,label:`中文`},{id:`en`,label:`English`}];function ge(){let e=typeof navigator>`u`?void 0:navigator,t=e?.languages?.[0]??e?.language;return typeof t==`string`&&t.trim()!==``?t.trim():null}function _e(){let e=ge();return e===null?me:/^zh/i.test(e)?`zh`:`en`}function ve(){try{let e=localStorage.getItem(fe);return e===`zh`||e===`en`?e:_e()}catch{return _e()}}function ye(e){try{localStorage.setItem(fe,e)}catch{}be(e),window.dispatchEvent(new CustomEvent(pe,{detail:e}))}function be(e){try{document.documentElement.lang=e===`en`?`en`:`zh-CN`}catch{}}var xe=`modulepreload`,Se=function(e){return`/`+e},Ce={},we=function(e){return e.pathname.endsWith(`.css`)},Te=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},Ee=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,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?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Se(t,n);let r=s(t),i=we(r);return Te(Ce,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:xe,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).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)})},De=null,Oe=null;function ke(){return De?Promise.resolve():(Oe||=Ee(()=>import(`./i18n-en-H5OrSHR5.js`).then(e=>{De=e.EN}),[]).catch(e=>{Oe=null,console.warn(`[i18n] 英文词条加载失败,界面回落中文`,e)}),Oe)}function Ae(){let[e,t]=(0,C.useState)(()=>ve());return(0,C.useEffect)(()=>{let e=e=>{e===`en`?ke().then(()=>t(`en`)):t(e)},n=t=>{let n=t.detail;(n===`zh`||n===`en`)&&e(n)},r=t=>{t.key===`pop-agent.language`&&e(t.newValue===`en`?`en`:`zh`)};return window.addEventListener(`pop-agent:language`,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(`pop-agent:language`,n),window.removeEventListener(`storage`,r)}},[]),(0,C.useEffect)(()=>be(e),[e]),{language:e,setLanguage:(0,C.useCallback)(e=>{e===`en`?ke().then(()=>ye(e)):ye(e)},[])}}function je(e,t,n){return e===`en`?n||(De?De[t]??t:(ke(),t)):t}function J(e,t){return je(ve(),e,t)}function Y(){let{language:e}=Ae();return(0,C.useCallback)((t,n)=>je(e,t,n),[e])}var Me,Ne=!1;function X(){if(Ne||typeof document>`u`)return;Ne=!0;let e=()=>{try{let e=Pe();if(!e)return;(!Me||Me.state===`closed`)&&(Me=new e),Me.state===`suspended`&&Me.resume().catch(()=>void 0)}catch{}};for(let t of[`pointerdown`,`keydown`,`touchstart`])document.addEventListener(t,e,{capture:!0,passive:!0})}function Pe(){if(typeof window<`u`)return window.AudioContext??window.webkitAudioContext}function Fe(){return!!Pe()&&typeof fetch==`function`}function Ie(e,t=1800){let n=[],r=new TextEncoder,i=``,a=0;for(let o of e.match(/[^。!?.!?\n]+[。!?.!?\n]*|[。!?.!?\n]+/gu)??[]){let e=r.encode(o).length;i&&a+e>t&&(n.push(i),i=``,a=0);for(let e of o){let o=r.encode(e).length;i&&a+o>t&&(n.push(i),i=``,a=0),i+=e,a+=o}}return i&&n.push(i),n}var Le={edge:`Edge`,kokoro:`Kokoro`,qwen3:`Qwen3`};async function Re(e,t){let n=await fetch(`/api/tts/voices?provider=${t}`,{signal:e});if(!n.ok)throw Error(J(`无法加载 ${Le[t]} 音色,请稍后重试`,`Unable to load ${Le[t]} voices; try again later`));return(await n.json()).voices}X();function ze(e,t,n,r){let i=new AbortController,a=!1,o,s,c=()=>{a=!0,i.abort(),o&&=(o.onended=null,o.stop(),o.disconnect(),void 0),s?.()};return(async()=>{let c=Pe();if(!c)throw Error(J(`当前浏览器不支持音频播放`,`This browser does not support audio playback`));(!Me||Me.state===`closed`)&&(Me=new c);let l=Me;if(await l.resume(),a)return;if(l.state!==`running`)throw Error(J(`浏览器拦截了播放,请在页面上点击后重新朗读`,`Playback was blocked; click on the page and try again`));let u=Ie(e),d=0,f=()=>{for(;;){for(;d<u.length;){let e=u[d++];if(e&&e.trim()!==``)return e}let e=r?.();if(e===void 0||e.trim()===``)return;u=Ie(e),d=0}},p=async e=>{let n=t.provider===`edge`?45e3:18e4,r=window.setTimeout(()=>i.abort(),n);try{let n=await fetch(`/api/tts/speak`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...t,text:e}),signal:i.signal});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??J(`${t.provider} 语音请求失败(${n.status})`,`${t.provider} speech request failed (${n.status})`))}let r=await n.arrayBuffer();if(a)throw Error(`canceled`);return await l.decodeAudioData(r)}finally{window.clearTimeout(r)}},m=f(),h=m===void 0?void 0:await p(m);for(let e=!0;h&&!a;e=!1){let t=l.createBufferSource();o=t,t.buffer=h,t.connect(l.destination);let r=new Promise(e=>{s=e,t.onended=()=>{t.disconnect(),o===t&&(o=void 0),e()}});t.start(),e&&n.onStart?.();let i=f(),a=i===void 0?Promise.resolve(void 0):p(i);[,h]=await Promise.all([r,a])}a||n.onEnd?.()})().catch(e=>{if(a)return;let r=i.signal.aborted;c(),n.onIssue?.(r?t.provider===`edge`?J(`Edge 语音请求超时,请检查网络后重试`,`Edge speech timed out; check your connection and try again`):J(`本地模型首次加载或合成超时,请稍后重试`,`Local model loading or synthesis timed out; try again later`):e instanceof Error?e.message:J(`语音播放失败,请重试`,`Speech playback failed; try again`))}),c}function Be(){Me&&Me.state===`running`&&Me.suspend()}function Ve(){Me&&Me.state===`suspended`&&Me.resume()}var He={provider:`browser`,edgeVoice:`zh-CN-XiaoxiaoNeural`,kokoroVoice:`zf_xiaoxiao`,qwen3Voice:`serena`,enabled:!0,readReplies:!1,rate:1,voiceURI:``,allowOnline:!0},Ue=400;function We(){return J(`语音播报正常,任务已完成`,`Speech is working — the task is done`)}var Ge=`pop-agent.voice.tts`;function Ke(){try{let e=localStorage.getItem(Ge);if(!e)return{...He};let t=JSON.parse(e),n={...He,...t};for(let e of[`enabled`,`readReplies`,`allowOnline`])typeof n[e]!=`boolean`&&(n[e]=He[e]);n.rate=typeof n.rate==`number`&&Number.isFinite(n.rate)?Math.round(Math.max(.5,Math.min(2,n.rate))*10)/10:He.rate,typeof n.voiceURI!=`string`&&(n.voiceURI=He.voiceURI),[`browser`,`edge`,`kokoro`,`qwen3`].includes(n.provider)||(n.provider=`browser`);for(let e of[`edgeVoice`,`kokoroVoice`,`qwen3Voice`])(typeof n[e]!=`string`||!n[e])&&(n[e]=He[e]);return n}catch{return{...He}}}var qe=`pop-agent:tts-settings`;function Je(e){try{localStorage.setItem(Ge,JSON.stringify(e))}catch{}try{window.dispatchEvent(new CustomEvent(qe,{detail:e}))}catch{}}function Ye(e){let t=t=>e(t.detail),n=t=>{t.key===Ge&&e(Ke())};return window.addEventListener(qe,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(qe,t),window.removeEventListener(`storage`,n)}}function Xe(){return typeof window<`u`&&`speechSynthesis`in window&&`SpeechSynthesisUtterance`in window}function Ze(e=Ke()){return e.provider&&e.provider!==`browser`?Fe():Xe()}function Qe(e={}){if(!Xe())return[];let t=e.onlyOnline===!0,n=e.includeOnline!==!1;return window.speechSynthesis.getVoices().filter(e=>t?!e.localService:n||e.localService).map(e=>({voiceURI:e.voiceURI,name:e.name,lang:e.lang,localService:e.localService})).sort((e,t)=>e.lang.localeCompare(t.lang)||e.name.localeCompare(t.name))}function $e(e){return Xe()?(window.speechSynthesis.addEventListener(`voiceschanged`,e),()=>window.speechSynthesis.removeEventListener(`voiceschanged`,e)):()=>{}}function et(e,t,n,r={}){let i=r.allowOnline===!0,a=i?[...t]:t.filter(e=>e.localService);if(e!==``){let t=a.find(t=>t.voiceURI===e);if(t)return t}let o=n.split(`-`)[0]?.toLowerCase()??``,s=(e,t)=>e.lang.toLowerCase().startsWith(t),c=e=>{let t=a.filter(e=>e.localService!==i),n=a.filter(e=>e.localService===i);return t.find(t=>s(t,e))??n.find(t=>s(t,e))??null};if(o!==``){let e=c(o);if(e)return e}return c(`zh`)}function tt(e,t=Ue){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(),n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}function nt(e){switch(e){case`not-allowed`:return J(`浏览器拦了这次朗读:先在页面上点一下(任意按钮)再试`,`The browser blocked this playback: click anywhere on the page, then try again`);case`voice-unavailable`:return J(`选中的音色在系统里不可用,换个「语音」或选「自动」`,`The selected voice is not available on this system — pick another voice or use Auto`);case`audio-busy`:return J(`音频输出被别的应用占着,关掉它再试`,`Another app is holding the audio output — close it and try again`);case`audio-hardware`:return J(`没有可用的音频输出设备`,`No audio output device is available`);case`network`:return J(`这个音色要联网(在线音色)才能念,换一个本机音色`,`This voice is an online voice and needs a network connection — pick a local voice`);case`synthesis-unavailable`:return J(`系统语音服务不可用(macOS:系统设置 → 辅助功能 → 朗读内容)`,`The system speech service is unavailable (macOS: System Settings → Accessibility → Spoken Content)`);case`synthesis-failed`:return J(`系统语音服务合成失败,试试点「停止」再试听一次`,`The system speech service failed to synthesize — click Stop, then preview again`);case`text-too-long`:return J(`这段话太长,合成器拒了`,`This text is too long — the synthesizer refused it`);case`invalid-argument`:return J(`音色参数无效(换一个「语音」再试)`,`The voice setting is invalid (pick another voice and try again)`);default:return J(`语音合成失败:${e}`,`Speech synthesis failed: ${e}`)}}var rt=!1,it=0,at,ot,st=200,ct=2,lt=700,ut=2;function dt(e){return e===null?1500:e?900:2500}var ft=new Set([`canceled`,`interrupted`,`synthesis-unavailable`,`synthesis-failed`]),pt=new Set;function mt(e){try{return!e.speaking&&!e.pending?!1:(e.cancel(),!0)}catch{return!1}}function ht(e,t=st){if(!Xe()){window.setTimeout(e,t);return}let n=window.speechSynthesis,r;try{mt(n),n.resume(),r=new SpeechSynthesisUtterance(` `)}catch{window.setTimeout(e,t);return}pt.add(r),r.volume=0,r.lang=``;let i=!1,a=a=>{if(!i){i=!0,window.clearTimeout(o),pt.delete(r);try{a!==`end`&&mt(n),n.resume()}catch{}window.setTimeout(e,t)}},o=window.setTimeout(()=>a(`timeout`),lt);r.onend=()=>a(`end`),r.onerror=()=>a(`error`);try{n.speak(r)}catch{a(`error`)}}function gt(e){return J(`语音服务没起来(${e}):已自动唤醒并重试 ${ct} 次仍然没出声。点「试听」再试一次;还是不行就重启浏览器(macOS 也可在终端执行 killall speechsynthesisd)`,`The speech service did not start (${e}): woke it up and retried ${ct} times with no sound. Click Preview to try again; if that fails, restart the browser (on macOS you can also run killall speechsynthesisd)`)}var _t=``;function vt(){return _t}function yt(e,t=Ke(),n={}){if(!e.trim())return;if(_t=e,Ct&&(Tt(!1),Xe()&&window.speechSynthesis.resume()),t.provider===`browser`||!t.provider){ot&&St(),bt(e,t,n);return}St();let r=t.provider,i=r===`kokoro`?t.kokoroVoice||`zf_xiaoxiao`:r===`qwen3`?t.qwen3Voice||`serena`:t.edgeVoice||`zh-CN-XiaoxiaoNeural`;at=n.onCancel;let a=()=>{ot=void 0,at=void 0};ot=ze(e,{provider:r,voice:i,rate:t.rate},{onStart:n.onStart,onEnd:()=>{a(),n.onEnd?.()},onIssue:e=>{a(),n.onIssue?.(e,{wakeable:!1})}},n.nextText?()=>{let e=n.nextText?.();return e!==void 0&&(_t=e),e}:void 0)}function bt(e,t,n){let r=e.trim();if(r===``)return;if(!Xe()){n.onIssue?.(J(`当前浏览器不支持语音合成`,`This browser does not support speech synthesis`),{wakeable:!1});return}let i=window.speechSynthesis;at&&mt(i),at?.(),at=n.onCancel,rt=!1;let a=++it,o=()=>rt||a!==it,s=0,c=!1,l=0,u=(e,a=`first`)=>{if(o())return;let d=0;try{let f=a===`retry`?null:et(t.voiceURI,e,navigator.language??`zh-CN`,{allowOnline:t.allowOnline}),p=new SpeechSynthesisUtterance(r);pt.add(p),p.rate=t.rate,p.volume=1,f?(p.voice=i.getVoices().find(e=>e.voiceURI===f.voiceURI)??null,p.lang=f.lang):p.lang=``;let m=!1,h=!1;if(c){console.warn(`[tts] 这一句已经出过声,不再重排`,{stage:a,queued:l});return}if(l>=ut){console.warn(`[tts] 已经排过两句,不再重排(重排只会让同一句多念一遍)`,{stage:a,queued:l}),n.onIssue?.(gt(`canceled`),{code:`canceled`,wakeable:!0});return}l+=1;let g=()=>{d&&window.clearTimeout(d),d=0},_=()=>{g(),pt.delete(p)};p.onstart=()=>{c=!0,!o()&&(h=!0,m=!0,g(),n.onStart?.())},p.onend=()=>{o()||(m=!0,_(),n.onEnd?.())},p.onerror=r=>{let l=String(r.error??`unknown`);if(o()){m=!0,_();return}let d=l===`canceled`||l===`interrupted`;if(d&&h)m=!0,_();else if(d){if(m=!0,_(),c)return;if(console.warn(`[tts] 还没开始就被打断`,{code:l,stage:a,voice:f?.name??`(交给浏览器默认)`,wakes:s}),s<ct){s+=1,ht(()=>{o()||u(e,a)},st*s);return}n.onIssue?.(gt(l),{code:l,wakeable:!0})}else a===`first`&&f&&l!==`not-allowed`&&!c?(m=!0,_(),console.warn(`[tts] 音色不可用,改用默认音色重试`,{code:l,voice:f.name}),window.setTimeout(()=>{o()||u(e,`retry`)},st)):(m=!0,_(),console.warn(`[tts] 合成失败`,l,{voice:f?.name??`(交给浏览器默认)`,voices:e.length,allVoices:i.getVoices().length,rate:t.rate}),n.onIssue?.(nt(l),{code:l,wakeable:ft.has(l)}))},d=window.setTimeout(()=>{m||o()||c||i.speaking||(m=!0,_(),mt(i),i.resume(),a===`first`&&f?(console.warn(`[tts] 音色没有开始,改用默认音色重试`,{voice:f.name}),window.setTimeout(()=>{o()||u(e,`retry`)},st)):(console.warn(`[tts] 语音服务没有响应`,{voice:f?.name??`(交给浏览器默认)`,voices:e.length,allVoices:i.getVoices().length}),n.onIssue?.(J(`系统语音服务没有响应(换个「语音」,或检查系统的语音合成设置)`,`The system speech service is not responding (pick another voice, or check the system speech settings)`),{wakeable:!0})))},dt(a===`first`&&f?f.localService:null));let v=e=>{m||o()||(!i.speaking&&!i.pending?(i.resume(),i.speak(p)):e>=6?(m=!0,g(),mt(i),i.resume(),console.warn(`[tts] 上一句没退干净,队列清不掉`,{stage:a}),n.onIssue?.(J(`语音服务卡住了(上一句没退干净):点「停止」再试听一次`,`The speech service is stuck (the previous line never cleared): click Stop, then preview again`),{wakeable:!0})):window.setTimeout(()=>v(e+1),120))};if(i.speaking||i.pending){mt(i),i.resume(),v(0);return}i.resume(),i.speak(p)}catch(e){d&&window.clearTimeout(d),n.onIssue?.(J(`语音合成出错:${e instanceof Error?e.message:String(e)}`,`Speech synthesis error: ${e instanceof Error?e.message:String(e)}`),{wakeable:!1})}},d=Qe({includeOnline:t.allowOnline});if(d.length>0){u(d);return}let f=!1,p=()=>{f||(f=!0,m(),u(Qe({includeOnline:t.allowOnline})))},m=$e(()=>{Qe({includeOnline:t.allowOnline}).length>0&&p()});window.setTimeout(p,1200)}function xt(e=2500){let t={available:Xe(),voices:0,online:0,started:!1,ended:!1,error:null,ms:0};if(!t.available)return Promise.resolve(t);let n=window.speechSynthesis.getVoices();t.voices=n.length,t.online=n.filter(e=>!e.localService).length;let r=Date.now();return new Promise(n=>{let i=!1,a=null,o=e=>{i||(i=!0,window.clearTimeout(s),a&&pt.delete(a),mt(window.speechSynthesis),n({...t,...e,ms:Date.now()-r}))},s=window.setTimeout(()=>o({}),e);try{a=new SpeechSynthesisUtterance(J(`测试`,`test`)),pt.add(a),a.volume=1,a.onstart=()=>o({started:!0}),a.onend=()=>o({started:!0,ended:!0}),a.onerror=e=>o({error:String(e.error??`unknown`)}),window.speechSynthesis.resume(),window.speechSynthesis.speak(a)}catch(e){o({error:e instanceof Error?e.message:String(e)})}})}function St(){Ct&&(Tt(!1),Xe()&&window.speechSynthesis.resume()),rt=!0,it++,ot?.(),ot=void 0;let e=at;at=void 0,e?.(),Xe()&&mt(window.speechSynthesis)}var Ct=!1,wt=new Set;function Tt(e){if(Ct!==e){Ct=e;for(let e of wt)e()}}function Et(){return ot?!0:Xe()&&(window.speechSynthesis.speaking||window.speechSynthesis.pending)}function Dt(){!Ct&&Et()&&(Tt(!0),ot?Be():window.speechSynthesis.pause())}function Ot(){Ct&&(Tt(!1),ot?Ve():Xe()&&window.speechSynthesis.resume())}function kt(){return Ct}function At(e){return wt.add(e),()=>wt.delete(e)}var jt=90,Mt=4,Nt=/[。!?;!?;…]|\n/;function Pt(e){let t=[],n=e;for(;n.length>jt;){let e=n.slice(0,jt),r=Math.max(e.lastIndexOf(`,`),e.lastIndexOf(`,`),e.lastIndexOf(`、`));if(r<Mt)break;t.push(n.slice(0,r+1)),n=n.slice(r+1)}return{pieces:t,rest:n}}function Ft(e){let t=[],n=e;for(;;){let e=n.search(Nt);if(e===-1)break;let r=n.slice(0,e+1);if(r.trim().length>=Mt){let i=Pt(r);if(i.pieces.length===0){t.push(r),n=n.slice(e+1);continue}t.push(...i.pieces),n=i.rest+n.slice(e+1);continue}let i=n.slice(e+1).search(Nt);if(i===-1)break;let a=n.slice(0,e+1+i+1),o=Pt(a);o.pieces.length===0?(t.push(a),n=n.slice(a.length)):(t.push(...o.pieces),n=o.rest)}let r=Pt(n);return t.push(...r.pieces),{units:t,rest:r.rest}}function It(){let e=0,t=``,n=!1,r=0,i=e=>{let t=tt(e,1/0).trim();return t===``||!/[\p{L}\p{N}]/u.test(t)?``:t},a=e=>{let{units:n,rest:a}=Ft(e);t=a;let o=[];for(let e of n){let t=i(e);t!==``&&o.push(t)}return r+=o.length,o};return{get spoken(){return r},push(r){if(r.length<=e)return[];let i=r.slice(e);e=r.length;let o=t+i;t=``;let s=[];for(;;){if(n){let e=o.indexOf("```");if(e===-1)return s;n=!1,o=o.slice(e+3);continue}let e=o.indexOf("```");if(e===-1)return s.push(...a(o)),s;s.push(...a(o.slice(0,e))),n=!0,o=o.slice(e+3)}},flush(){let e=n?``:t;t=``,n=!1;let a=i(e);return a===``?[]:(r+=1,[a])},reset(){e=0,t=``,n=!1,r=0}}}var Lt=`/api/client-log`,Rt=120,zt=1e4,Bt=0,Vt=0;function Ht(e){return{textLen:e.length,textHead:e.slice(0,24)}}function Ut(e,t){let n=Date.now();if(n-Bt>zt&&(Bt=n,Vt=0),!(Vt>=Rt)){Vt+=1;try{fetch(Lt,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t?{event:e,detail:t}:{event:e}),keepalive:!0}).catch(()=>void 0)}catch{}}}var Wt=!1,Gt=new Set,Kt=new Set,qt=new Set;function Jt(){for(let e of Gt)e()}function Yt(e){Wt!==e&&(Wt=e,Jt())}function Xt(){return Wt}function Zt(e){return Gt.add(e),()=>Gt.delete(e)}function Qt(){return(0,C.useSyncExternalStore)(Zt,Xt,Xt)}var $t=new Set;function en(){for(let e of $t)e()}function tn(e){return $t.add(e),()=>$t.delete(e)}function nn(){for(let e of Kt)e();en()}function rn(e){return Kt.add(e),()=>Kt.delete(e)}function an(){for(let e of qt)e()}function on(e){return qt.add(e),()=>qt.delete(e)}function sn(e){return e===`queue`?`stop`:e===`steer`?`none`:`interrupt`}function cn(e){let t=sn(e);t===`stop`?nn():(en(),t===`interrupt`&&an())}var ln=!1,un=new Set;function dn(){for(let e of un)e()}At(()=>{let e=kt();e!==ln&&(ln=e,dn())});function fn(e){return un.add(e),()=>un.delete(e)}function pn(){return(0,C.useSyncExternalStore)(fn,mn,mn)}function mn(){return ln}function hn(e){if(e===ln)return;e?Dt():Ot();let t=kt();t!==ln&&(ln=t,dn())}function gn(e){return un.add(e),()=>un.delete(e)}function _n(){if(typeof window>`u`)return null;let e=window,t=e.SpeechRecognition??e.webkitSpeechRecognition??null;return typeof t==`function`?t:null}function vn(){return!_n()||typeof window>`u`?!1:window.isSecureContext===!0}function yn(e){let t=_n();if(!t||typeof window>`u`||window.isSecureContext!==!0)return e.onError(`unsupported`),null;let n=new t;n.lang=e.lang,n.continuous=!0,n.interimResults=!0,n.maxAlternatives=1,n.onresult=t=>{let n=``;for(let e=0;e<t.results.length;e+=1){let r=t.results[e];n+=r?.[0]?.transcript??``}e.onText(n.trim())},n.onerror=t=>{let n=t.error??`other`;n===`not-allowed`||n===`service-not-allowed`?e.onError(`denied`):n===`no-speech`?e.onError(`no-speech`):n===`network`?e.onError(`network`):n!==`aborted`&&e.onError(`other`)},n.onend=()=>e.onEnd();try{n.start()}catch{return e.onError(`other`),null}return{stop:()=>{try{n.stop()}catch{}},abort:()=>{try{n.abort()}catch{}}}}function bn(e){return!Number.isFinite(e.blockedForMs)||e.blockedForMs<=0||!Number.isFinite(e.fallbackMs)||e.fallbackMs<=0?!1:e.blockedForMs>=e.fallbackMs}var xn=16e3,Sn=300,Cn=12,wn=36,Tn=2,En=700,Dn=1500;function On(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n]??0;t+=r*r}let n=Math.sqrt(t/Math.max(1,e.length));return n>0?20*Math.log10(n):-100}function kn(e,t){let n=t/xn,r=Math.max(0,Math.floor(e.length/n)),i=new Int16Array(r);for(let t=0;t<r;t+=1){let r=Math.floor(t*n),a=Math.min(e.length,Math.floor((t+1)*n)),o=0;for(let t=r;t<a;t+=1)o+=e[t]??0;let s=a>r?o/(a-r):0;i[t]=Math.round(Math.max(-1,Math.min(1,s))*32767)}return i}var An=null;function jn(){return(!An||An.state===`closed`)&&(An=new AudioContext),An.resume().catch(()=>void 0),An}function Mn(e){let t=!1,n=``,r=Math.max(0,Math.min(30,e.nearTalkDb??Cn)),i=r>0,a=jn(),o=null,s=null,c=[],l=Promise.resolve(),u=0,d=[],f=0,p=0,m=0,h=0,g=0,_=0,v=null,y=async(e,t)=>await fetch(e,{method:`POST`,headers:t?{"content-type":`application/octet-stream`}:void 0,body:t}),b=()=>(l=l.then(async()=>{for(;c.length>0&&!t;){let t=c.shift();try{let r=await y(`/api/asr/chunk`,t.buffer);if(!r.ok)continue;let i=await r.json(),a=typeof i.text==`string`?i.text:``;a!==n&&(n=a,e.onText(a))}catch{}}}),l),x=async()=>{s?.disconnect(),s=null;for(let e of o?.getTracks()??[])e.stop();o=null;let e=c;return c=[],e},S=()=>t;return(async()=>{let n={},l=Date.now(),x=!1;for(;;){let t=!1;try{let e=await y(`/api/asr/start`);if(n=await e.json().catch(()=>({})),e.ok)break;t=n.state===`starting`||n.state===`authorizing`}catch(t){e.onError(`local`,t instanceof Error?t.message:`连不上本地识别服务`,`error`),e.onEnd();return}if(!t||S())return;if(Date.now()-l>8e3){e.onError(`local`,n.message??`本地识别启动超时`,n.state),e.onEnd();return}if(x||(x=!0,e.onWaiting?.(n.state??`starting`)),await new Promise(e=>setTimeout(e,400)),S())return}if(t)return;try{o=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!i}})}catch{e.onError(`denied`),e.onEnd();return}if(t){for(let e of o.getTracks())e.stop();return}a.state!==`running`&&await a.resume().catch(()=>void 0),e.onContext?.(a.state);let C=a.createMediaStreamSource(o);s=a.createScriptProcessor(4096,1,1),s.onaudioprocess=n=>{if(t)return;let o=n.inputBuffer.getChannelData(0),s=Date.now(),l=!0,y=!1;if(i&&!e.bypassGate?.()){let e=On(o);d.push(e),d.length>wn&&d.shift(),g=e>Math.min(...d)+r?g+1:0,l=g>=Tn,y=s<_,f+=1,!l&&!y?(p+=1,h===0&&(h=s),bn({blockedForMs:s-h,fallbackMs:Dn})&&(l=!0,h=0,m+=1)):h=0,l&&(_=s+En)}let x=o;(e.shouldMuteAudio?.()||!l&&!y)&&(v??=new Float32Array(o.length),x=v);let S=kn(x,a.sampleRate||xn);S.length!==0&&(c.push(S),s-u>=Sn&&(u=s,b()))},C.connect(s),s.connect(a.destination)})(),{stop:()=>{t||(t=!0,x())},abort:()=>{t=!0,c=[],x()},flush:async()=>{e.onGating?.({marginDb:r,frames:f,blocked:p,fallbacks:m});let t=await x();for(let e of t)c.push(e);await b();try{let t=await(await y(`/api/asr/end`)).json().catch(()=>({})),r=typeof t.text==`string`?t.text:n;r!==n&&(n=r,e.onText(r))}catch{}return n}}}function Nn(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0||e<=0?0:e>=t?1:e/t}function Pn(e,t){return Math.abs(t-e)>=.08||e>0&&t===0}var Fn=1e4;function In(e,t){if(typeof e!=`number`||!Number.isFinite(e))return t;let n=Math.round(e*1e3);return Math.min(Fn,Math.max(600,n))}function Ln(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?0:Math.min(120,Math.max(3,Math.round(e)))}var Rn=[`,`,`,`,`、`,`;`,`;`,`:`,`:`,`—`,`-`,`…`,`“`,`「`,`「`,`(`,`(`];function zn(e){let t=e.trim();if(t===``)return!1;let n=t.slice(-1);return Rn.includes(n)}var Bn={min:600,max:1e4},Vn={min:0,max:30},Hn={min:0,max:120},Un={autoSend:!0,continuous:!1,submitMode:`queue`,engine:`auto`,nearTalkDb:12,silenceMs:2e3,readingResumeMs:4e3,idleStopSec:0,showReadingDock:!0};function Wn(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function Gn(e,t,n){return Math.min(n,Math.max(t,e))}function Kn(e,t=Un){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{autoSend:typeof n.autoSend==`boolean`?n.autoSend:t.autoSend,continuous:typeof n.continuous==`boolean`?n.continuous:t.continuous,submitMode:n.submitMode===`steer`?`steer`:n.submitMode===`queue`?`queue`:t.submitMode,engine:n.engine===`local`||n.engine===`browser`||n.engine===`auto`?n.engine:t.engine,nearTalkDb:Math.round(Gn(Wn(n.nearTalkDb,t.nearTalkDb),Vn.min,Vn.max)),silenceMs:Math.round(Gn(Wn(n.silenceMs,t.silenceMs),Bn.min,Bn.max)),readingResumeMs:Math.round(Gn(Wn(n.readingResumeMs,t.readingResumeMs),Bn.min,Bn.max)),showReadingDock:typeof n.showReadingDock==`boolean`?n.showReadingDock:t.showReadingDock,idleStopSec:Math.round(Gn(Wn(n.idleStopSec,t.idleStopSec),Hn.min,Hn.max))}}var qn=`/api/voice-settings`;async function Jn(){try{let e=await fetch(qn,{headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json();return{settings:Kn(t.settings),stored:t.stored===!0}}catch{return null}}function Yn(e){try{fetch(qn,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e),keepalive:!0}).catch(()=>void 0)}catch{}}function Xn(e,t){return e.autoSend===t.autoSend&&e.continuous===t.continuous&&e.submitMode===t.submitMode&&e.engine===t.engine&&e.nearTalkDb===t.nearTalkDb&&e.silenceMs===t.silenceMs&&e.readingResumeMs===t.readingResumeMs&&e.idleStopSec===t.idleStopSec&&e.showReadingDock===t.showReadingDock}function Zn(e){return!e.continuous||e.manualPause||e.status!==`idle`||e.hidden?!1:e.errorStreak<e.maxErrorStreak}var Qn=[],$n=new Set,er=0;function tr(){for(let e of $n)e()}function nr(e){Qn=e,tr()}function Z(e){er+=1;let t={id:er,text:e.text,actions:e.actions??[],ttl:e.ttl??8e3};return nr([...Qn,t].slice(-3)),t.id}function rr(e){nr(Qn.filter(t=>t.id!==e))}function ir(e){return $n.add(e),()=>{$n.delete(e)}}function ar(){return Qn}function or(){return(0,C.useSyncExternalStore)(ir,ar,ar)}var sr=`pop-agent:pref`,cr=`pop-agent.chat.thinkingOpen`,lr=`pop-agent.split.chatSide`,ur=`pop-agent.chat.toolOpen`,dr=`pop-agent.chat.processAutoCollapse`,fr=`pop-agent.chat.processAutoFoldRunning`,pr=`pop-agent.chat.selectionToolbar`,mr=`pop-agent.preview.wrap`,hr=`pop-agent.preview.fontSize`,gr=`pop-agent.sidechat.zoom`,_r=`pop-agent.web.zoom`,vr=`pop-agent.web.phone`,yr=`pop-agent.web.phoneSize`,br=`pop-agent.terminal.fontSize`,xr=[`models`,`cron`,`skills`,`push`,`voice`,`plugins`,`mcp`,`agents`],Sr=[...xr,`settings`],Cr=[`models`,`cron`,`skills`],wr=e=>Cr.includes(e),Tr=`pop-agent.appbar.`,Er=e=>`${Tr}${e}`,Dr=[`label`,`icon`],Or=e=>`pop-agent.appbar.show-${e}`,kr={label:`显示文案`,icon:`显示图标`},Ar={label:`Show labels`,icon:`Show icons`},jr={models:`模型`,skills:`技能`,push:`推送`,voice:`语音`,plugins:`插件`,mcp:`MCP`,agents:`子代理`,cron:`定时任务`,settings:`设置`},Mr={models:`Models`,skills:`Skills`,push:`Push`,voice:`Voice`,plugins:`Plugins`,mcp:`MCP`,agents:`Subagents`,cron:`Cron`,settings:`Settings`},Nr=`pop-agent.appbar.tempchat`,Pr=[`model`,`thinking`,`templates`,`think`,`quick`],Fr=new Set([`model`,`thinking`,`templates`,`think`]),Ir=e=>Fr.has(e),Lr=e=>`pop-agent.composer.${e}`,Rr={model:`模型`,thinking:`思考强度`,templates:`提示词`,think:`想想`,quick:`快捷指令(显示在输入框上方)`},zr={model:`Model`,thinking:`Thinking effort`,templates:`Prompts`,think:`Think`,quick:`Quick commands (above the input)`},Br=[`settings`,`engine`,`approval`,`history`,`prompt`,`queued`,`running`,`context`,`terminal`,`top`],Vr=[`settings`,`engine`,`approval`],Hr=e=>Vr.includes(e),Ur=`pop-agent.statusbar.`,Wr=e=>`${Ur}${e}`,Gr={settings:`设置`,approval:`审批模式`,engine:`引擎`,queued:`排队`,running:`工作中`,context:`上下文用量`,history:`完整历史`,prompt:`系统提示词`,terminal:`终端`,top:`顶部`},Kr={settings:`Settings`,approval:`Approval mode`,engine:`Engine`,queued:`Queued`,running:`Running`,context:`Context`,history:`Full history`,prompt:`System prompt`,terminal:`Terminal`,top:`Top bar`},qr=`pop-agent.sidebar.sessionsPerProject`,Jr=`pop-agent.chat.imageMaxWidth`;function Yr(e){try{return localStorage.getItem(e)}catch{return null}}function Xr(e,t){try{localStorage.setItem(e,t)}catch{}}function Zr(e,t){try{let n=localStorage.getItem(e);return n===`1`||n!==`0`&&t}catch{return t}}function Qr(e,t){try{localStorage.setItem(e,t?`1`:`0`)}catch{}window.dispatchEvent(new CustomEvent(sr,{detail:{key:e,value:t}}))}function $r(e,t){let n=n=>{let r=n.detail;r?.key===e&&t(r.value)},r=n=>{n.key===e&&t(Zr(e,!1))};return window.addEventListener(sr,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(sr,n),window.removeEventListener(`storage`,r)}}var ei=`pop-agent:pref-number`;function ti(e,t,n,r){if(e==null||e===``)return t;let i=typeof e==`number`?e:Number(e);return Number.isFinite(i)?Math.min(r,Math.max(n,Math.round(i))):t}function ni(e,t,n,r){let i=Yr(e);return i===null||i.trim()===``?t:ti(i,t,n,r)}function ri(e,t){Xr(e,String(t));try{window.dispatchEvent(new CustomEvent(ei,{detail:{key:e,value:t}}))}catch{}}function ii(e,t){let n=n=>{let r=n.detail;r?.key===e&&t(r.value)},r=n=>{if(n.key!==e)return;let r=n.newValue===null?``:n.newValue,i=Number(r);Number.isFinite(i)&&t(i)};return window.addEventListener(ei,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(ei,n),window.removeEventListener(`storage`,r)}}var ai=`pop-agent.voice.input`,oi=2e3,si=200,ci={autoSend:!0,submitMode:`queue`,engine:`auto`,continuous:!1,idleStopSec:0,nearTalkDb:12,silenceMs:oi,readingResumeMs:4e3,showReadingDock:!0};function li(e){let t=typeof e==`number`&&Number.isFinite(e)?e:ci.nearTalkDb;return Math.max(0,Math.min(30,Math.round(t)))}var ui=new Set;function di(){let e=Yr(ai);if(!e)return{...ci};try{let t=JSON.parse(e);return{autoSend:t.autoSend!==!1,continuous:t.continuous===!0,idleStopSec:Ln(t.idleStopSec),submitMode:t.submitMode===`steer`?`steer`:`queue`,engine:t.engine===`browser`||t.engine===`local`?t.engine:`auto`,nearTalkDb:li(t.nearTalkDb),silenceMs:In(t.silenceMs===void 0?void 0:t.silenceMs/1e3,oi),readingResumeMs:In(t.readingResumeMs===void 0?void 0:t.readingResumeMs/1e3,4e3),showReadingDock:t.showReadingDock!==!1}}catch{return{...ci}}}var fi=di(),pi=!1;function mi(){pi=!1}function hi(e,t){return e===`browser`?`browser`:e===`local`?`local`:t?`browser`:`local`}function gi(){typeof window<`u`&&typeof fetch==`function`&&fetch(`/api/asr/status`).then(async e=>e.ok?await e.json():null).catch(()=>null).then(e=>{e?.state===`missing`&&(pi=!0)}).catch(()=>void 0)}gi();var _i=0;(async()=>{let e=_i,t=await Jn();if(t===null||_i!==e)return;if(!t.stored){Yn(fi);return}let n=Kn(t.settings);if(!Xn(n,fi)){fi=n,Xr(ai,JSON.stringify(fi)),Ut(`settings:from-server`,{silenceMs:fi.silenceMs,nearTalkDb:fi.nearTalkDb});for(let e of ui)e()}})();function vi(){return fi}function yi(e){_i+=1;let t=fi;fi={autoSend:e.autoSend,continuous:e.continuous===!0,idleStopSec:Ln(e.idleStopSec),submitMode:e.submitMode===`steer`?`steer`:`queue`,engine:e.engine===`browser`||e.engine===`local`?e.engine:`auto`,nearTalkDb:li(e.nearTalkDb),silenceMs:In(e.silenceMs/1e3,oi),readingResumeMs:In(e.readingResumeMs/1e3,4e3),showReadingDock:e.showReadingDock!==!1},Xr(ai,JSON.stringify(fi)),Yn(fi);for(let e of ui)e();t.nearTalkDb!==fi.nearTalkDb&&Ci===`listening`&&Ai===`local`&&(Ut(`restart:gate`,{from:t.nearTalkDb,to:fi.nearTalkDb}),Da())}function bi(){return(0,C.useSyncExternalStore)(e=>(ui.add(e),()=>ui.delete(e)),vi,vi)}var xi=null,Si=null,Ci=`idle`,wi=!1,Ti=!1,Ei=``,Di=``,Oi=0,ki=null,Ai=`browser`,ji=!1,Mi=0,Ni=0,Pi=!1,Fi=!1,Ii=!1,Li=0,Ri=null,zi=800,Bi=2,Vi=!1,Hi=null,Ui=null,Wi=0,Gi=0,Ki=8,qi=2e3,Ji=new Set;function Yi(e){if(Ci!==e){Ut(`status`,{from:Ci,to:e,engine:Ai}),Ci=e,e!==`listening`&&Xi(0);for(let e of Ji)e()}}function Xi(e){if(Pn(Ni,e)){Ni=e;for(let e of Ji)e()}}function Zi(e){return Ji.add(e),()=>Ji.delete(e)}function Qi(){return Ci}function $i(){return(0,C.useSyncExternalStore)(Zi,Qi,Qi)}function ea(){return Ni}function ta(){return(0,C.useSyncExternalStore)(Zi,ea,ea)}function na(){return Ci===`listening`}function ra(e){xi=e}function ia(){return xi!==null&&(xi.conversationId??null)===Si}function aa(){Ut(`abandon:conversation-switched`,{owner:Si,current:xi?.conversationId??null}),Ii=!0,ga(),va(),Yi(`idle`),xi?.onEnd()}function oa(e,t){let n=e.trimEnd(),r=t.trimStart();return n?r?/[\u3400-\u9fff\u3000-\u303f\uff00-\uffef]$/.test(n)||/^[\u3400-\u9fff]/.test(r)?`${n}${r}`:`${n} ${r}`:n:r}function sa(e,t){if(e===`local`)return t??J(`本地识别还没就绪`,`Local recognition isn't ready yet`);switch(e){case`unsupported`:return J(`这台浏览器用不了语音输入:Firefox 没有这个能力;手机通过局域网 http 打开时也没有麦克风(需要 localhost 或 HTTPS)`,`Voice input is unavailable here: Firefox has no support, and a phone opening this over plain LAN http has no microphone (localhost or HTTPS is required)`);case`denied`:return J(`麦克风被拒绝了:点地址栏左边的权限图标,允许麦克风后再点一次`,`Microphone permission was denied: allow it from the icon next to the address bar, then try again`);case`network`:return J(`Chrome 的语音识别要把声音传到 Google 的服务器,这个网络连不上(实测 speech.googleapis.com 超时)。要么让代理覆盖浏览器,要么改用离线识别(目前还没装)`,`Chrome's speech recognition uploads audio to Google, which is unreachable on this network (speech.googleapis.com times out). Either route the browser through a proxy, or switch to offline recognition (not installed yet)`);default:return J(`语音输入出错了,再点一次试试`,`Voice input failed — try tapping again`)}}function ca(){Hi!==null&&(window.clearInterval(Hi),Hi=null),Ui!==null&&(window.clearTimeout(Ui),Ui=null)}function la(){Hi===null&&(Hi=window.setInterval(()=>{if(!(Ci===`listening`&&fi.autoSend&&oa(Ei,Di).trim()!==``)){Xi(0);return}let e=Date.now()-Oi;if(Pi&&e>=ha()&&!ji&&(Pi=!1,mn()&&(Ut(`read:resume`,{idleMs:e}),hn(!1))),fi.idleStopSec>0&&e>=fi.idleStopSec*1e3){Ut(`idle:stop`,{idleMs:e,idleStopSec:fi.idleStopSec}),Ta();return}if(zn(oa(Ei,Di))){Fi||(Fi=!0,Ut(`countdown:hold`,{reason:`unfinished`,...Ht(oa(Ei,Di))})),Xi(1);return}let t=Nn(e,fi.silenceMs);t>=1?(Xi(1),ua()):Xi(t)},si))}function ua(){if(Ui!==null||ji){Date.now()-Mi>=2e3&&(Mi=Date.now(),Ut(`countdown:blocked`,{counting:Ui!==null,flushing:ji,status:Ci}));return}Ut(`countdown:start`,{engine:Ai,...Ht(oa(Ei,Di))}),Yi(`sending`);let e=ki?.flush;if(!e){da();return}ji=!0;let t=Date.now();Ut(`flush:start`,{engine:Ai}),e().catch(e=>(Ut(`flush:error`,{ms:Date.now()-t,error:String(e).slice(0,120)}),``)).finally(()=>{ji=!1,Ut(`flush:done`,{ms:Date.now()-t,...Ht(Di),status:Ci}),Ci===`sending`&&da()})}function da(){ia()?(Ut(`submit`,{engine:Ai,...Ht(oa(Ei,Di))}),va(),Yi(`idle`),xi?.onEnd(),xi?.submitVoice(),_a()):aa()}var fa=10;function pa(e){if(!Xt())return!1;let t=vt().replace(/\s+/g,``),n=e.replace(/\s+/g,``);if(!t||!n||n.length<fa)return!1;let r=t.includes(n);return r&&Ut(`echo:drop`,{heardLen:n.length,spokenLen:t.length}),r}function ma(){if(!Xt()||mn())return;let e=vt().replace(/\s+/g,``),t=oa(Ei,Di).replace(/\s+/g,``);e&&t&&(e.includes(t)||t.includes(e.slice(0,Math.min(12,e.length))))||(Ut(`read:pause`,{}),Pi=!0,hn(!0))}function ha(){return fi.readingResumeMs}function ga(){Ri!==null&&(window.clearTimeout(Ri),Ri=null)}function _a(){Ri===null&&fi.continuous&&(Ri=window.setTimeout(()=>{Ri=null,Zn({continuous:fi.continuous,manualPause:Ii,status:Ci,hidden:document.visibilityState===`hidden`,errorStreak:Li,maxErrorStreak:Bi})?(Ut(`continuous:resume`,{engine:fi.engine}),wa()):Ut(`continuous:skip`,{manualPause:Ii,status:Ci,hidden:document.visibilityState===`hidden`,errorStreak:Li})},zi))}function va(){let e=ki;ki=null,wi=!0,Ti=!0,e?.stop(),Ei=``,Di=``,ca()}function ya(){Oi=Date.now(),ki=yn({lang:ve()===`en`?`en-US`:`zh-CN`,onText:e=>{if(!ia()){aa();return}Oi=Date.now();let t=e!==Di;Di=e,t&&(Li=0),Ut(`text:legacy`,{changed:t,...Ht(oa(Ei,e))}),t&&(Fi=!1,ma()),xi?.onText(oa(Ei,e)),t&&Ci===`sending`&&(Ui!==null&&window.clearTimeout(Ui),Ui=null,Yi(`listening`))},onError:e=>{e!==`no-speech`&&(Li+=1,Ut(`error`,{engine:`browser`,kind:e,errorStreak:Li}),Z({text:sa(e)}),xa())},onEnd:()=>{if(Ti){Ti=!1;return}if(wi||Ci===`sending`)return;let e=Date.now();Wi=e-Gi<qi?Wi+1:1,Gi=e,Wi>Ki?(Z({text:J(`语音输入总是被立刻中断(麦克风可能被别的程序占着),先停下来,待会儿再试`,`Voice input keeps ending immediately (the microphone may be in use) — stopping for now`)}),xa()):(Ei=oa(Ei,Di),Di=``,ya())}})}function ba(){ki=Mn({nearTalkDb:fi.nearTalkDb,onText:e=>{if(!ia()){aa();return}if(pa(e))return;Oi=Date.now();let t=e!==Di;Di=e,xi?.onText(e),t&&(Li=0),Ut(`text:local`,{changed:t,...Ht(e)}),t&&(Fi=!1,ma()),t&&Ci===`sending`&&!ji&&(Ut(`countdown:cancel`,{reason:`new-text`}),Ui!==null&&window.clearTimeout(Ui),Ui=null,Yi(`listening`))},onError:(e,t,n)=>{e!==`no-speech`&&(Li+=1,Ut(`error`,{engine:`local`,kind:e,detail:t?.slice(0,120),state:n,errorStreak:Li}),xa(),fi.engine===`auto`&&(n===`missing`||n===`error`)?(pi=!0,n===`error`&&!Vi&&(Vi=!0,Z({text:J(`本地识别不可用(${t??`原因未知`}),已改用 Chrome 识别`,`Local recognition is unavailable (${t??`unknown`}), falling back to Chrome`)})),Ca()):Z({text:sa(e,t)}))},onContext:e=>Ut(`audio-context`,{state:e}),onGating:e=>Ut(`gate`,e),bypassGate:()=>Xt(),onWaiting:e=>Ut(`asr:waiting`,{state:e}),onEnd:()=>{}})}function xa(){ga();let e=ki;ki=null,Ti=!0,e?.abort(),Ei=``,Di=``,ji=!1,ca(),Yi(`idle`),Si=null,xi?.onEnd()}function Sa(){wi=!1,Ti=!1,Wi=0,Gi=0,Ei=``,Di=``,Si=xi?.conversationId??null,Xt()&&(Pi=!0,hn(!0)),xi?.onStart(),Yi(`listening`),la(),Ai===`local`?ba():ya()}function Ca(){vn()?(Ai=`browser`,Sa()):Z({text:sa(`unsupported`)})}function wa(){Ci===`idle`&&(Ii=!1,Li=0,Ut(`start`,{engineSetting:fi.engine,autoSend:fi.autoSend,submitMode:fi.submitMode,silenceMs:fi.silenceMs,continuous:fi.continuous,secure:typeof window<`u`?window.isSecureContext:void 0}),hi(fi.engine,pi)===`browser`?Ca():(Ai=`local`,Sa()))}function Ta(){Ci!==`idle`&&(Ut(`stop`,{status:Ci,flushing:ji,engine:Ai}),Ii=!0,ga(),!ji&&(Ci===`listening`&&ki?.flush?(ji=!0,ki.flush().catch(()=>``).finally(()=>{ji=!1,va(),Yi(`idle`),xi?.onEnd()})):(va(),Yi(`idle`),xi?.onEnd())))}function Ea(){Ci===`idle`?wa():Ta()}function Da(e){if(Ci!==`listening`)return;let t=ki;ki=null,Ti=!0,t?.abort(),Ei=``,Di=``,Si=xi?.conversationId??null,xi?.onStart(e),Oi=Date.now(),Ai===`local`?ba():ya()}var Oa={done:{zh:`/assets/done.zh-Dq-Os4NS.mp3`,en:`/assets/done.en-s1tZOg6A.mp3`},stopped:{zh:`/assets/stopped.zh-D2CUs-KZ.mp3`,en:`/assets/stopped.en-CFPMi6oy.mp3`},steer:{zh:`/assets/steer.zh-BCINYQs7.mp3`,en:`/assets/steer.en-1RIP4K_0.mp3`},error:{zh:`/assets/error.zh-DdFp64-u.mp3`,en:`/assets/error.en-BGPHdZVi.mp3`},approval:{zh:`/assets/approval.zh-DWqP6Pcu.mp3`,en:`/assets/approval.en-BFhMPNWP.mp3`}},ka={done:`done`,stopped:`done`,steer:`steer`,error:`error`,approval:`approval`};function Aa(e,t){return Oa[e][t]}var ja=new Map;function Ma(e,t){let n=ja.get(t);if(n)return n;let r=fetch(t).then(e=>e.ok?e.arrayBuffer():Promise.reject(Error(String(e.status)))).then(t=>e.decodeAudioData(t)).catch(e=>(ja.delete(t),console.warn(`[voice-clips] 状态语音解码失败`,t,e),null));return ja.set(t,r),r}function Na(e,t={}){let n=U();if(!n.enabled&&t.force!==!0)return;let r=t.language??ve(),i=t.volume??ie(n),a=ne();if(!a){q(ka[e],n);return}let o=Date.now();Ma(a,Aa(e,r)).then(t=>{if(!t){q(ka[e],n);return}if(!de(o))return;let r=()=>{let e=a.createBufferSource(),n=a.createGain();e.buffer=t,n.gain.value=i,e.connect(n),n.connect(a.destination),e.start()};re(a)?r():a.resume().then(()=>{de(o)&&(re(a)?r():q(ka[e],n))}).catch(()=>q(ka[e],n))}).catch(()=>q(ka[e],n))}function Pa(){let e=ne();if(e)for(let t of Object.keys(Oa))for(let n of[`zh`,`en`])Ma(e,Aa(t,n))}function Fa(){return{prevStatus:new Map,turnStartMark:new Map,awaitingEnd:new Map,announcedTurns:new Set,startedTurns:new Set,seenErrors:new Set,lastApprovalId:null,knownConversations:new Set,seenSteers:new Set}}function Ia(e){return e.kind===`start`||!e.voiceEnabled?`beep`:e.kind===`done`&&e.readReplies&&e.hasReply?`reply`:`clip`}function La(){return{lastText:null,lastAt:0}}var Ra=`\0sound`,za=`\0stopped`;function Ba(e,t,n,r=`done`){let i=t??(r===`stopped`?za:Ra);return e.lastText===i&&n-e.lastAt<1500?!1:(e.lastText=i,e.lastAt=n,!0)}function Va(e){if(!e)return null;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n&&n.role===`assistant`)return n}return null}function Ha(e,t){return!t||t.endedAt===void 0?!1:!e||t.id!==e.id||t.endedAt!==e.endedAt}var Ua=200;function Wa(e,t){let n=[],r=t.active.conversationId,i=t.active.messages,a=e=>{let n=t.runningByConversation[e]?.status;return n===void 0?t.running.conversationId===e&&t.running.status!==`idle`?t.running.status:`idle`:n},o=e=>t.runningByConversation[e]?.turnStartedAt??(t.running.conversationId===e?t.running.turnStartedAt??null:null),s=(e,t)=>t?.stopped===!0?{kind:`stopped`,conversationId:e,message:t}:{kind:`done`,conversationId:e,message:t},c=(t,n,i)=>{if(!(t!==r||Ha(n,i)))return!1;let a=t===r&&i?`${t}:msg:${i.id}:${i.endedAt??``}`:`${t}:turn:${n?.turnStartedAt??`?`}`;return!e.announcedTurns.has(a)&&(e.announcedTurns.add(a),Ga(e.announcedTurns),!0)};if(e.awaitingEnd.size>0)for(let[t,a]of e.awaitingEnd){if(t!==r){e.awaitingEnd.delete(t);continue}let o=Va(i);o?.endedAt!==void 0&&(e.awaitingEnd.delete(t),c(t,a,o)&&n.push(s(t,o)))}let l=new Set([...e.prevStatus.keys(),...Object.keys(t.runningByConversation)]);r!==null&&l.add(r);for(let t of l){let l=e.prevStatus.get(t)??`idle`,u=a(t);if(e.prevStatus.set(t,u),l!==u){if(u===`streaming`&&l!==`streaming`){let a=t===r?Va(i):null,s=o(t);e.turnStartMark.set(t,a?{id:a.id,endedAt:a.endedAt,turnStartedAt:s}:null),e.awaitingEnd.delete(t);let c=`${t}:turn:${s??`?`}`;if(s!==null&&e.startedTurns.has(c))continue;e.startedTurns.add(c),Ga(e.startedTurns),n.push({kind:`start`,conversationId:t})}else if(l===`streaming`&&u!==`streaming`){let a=e.turnStartMark.get(t)??null;e.turnStartMark.delete(t);let o=t===r?Va(i):null;if(t===r&&o&&o.endedAt===void 0){e.awaitingEnd.set(t,a);continue}c(t,a,o)&&n.push(s(t,o))}}}if(r!==null){let t=i.filter(e=>e.role===`user`&&e.steer===!0);if(e.knownConversations.has(r)){for(let i of t){let t=`${r}:${i.id}`;e.seenSteers.has(t)||(e.seenSteers.add(t),n.push({kind:`steer`,conversationId:r}))}Ga(e.seenSteers)}else{e.knownConversations.add(r),Ga(e.knownConversations);for(let n of t)e.seenSteers.add(`${r}:${n.id}`)}}let u=t.pendingApproval?.requestId??null;u!==null&&u!==e.lastApprovalId?(e.lastApprovalId=u,n.push({kind:`approval`})):u===null&&(e.lastApprovalId=null);let d=(t.notices??[]).filter(e=>e.level===`error`),f=d.find(t=>!e.seenErrors.has(t.id));for(let t of d)e.seenErrors.add(t.id);return Ga(e.seenErrors),f&&n.push({kind:`error`}),n}function Ga(e){if(e.size<=Ua)return;let t=[...e].slice(-200);e.clear();for(let n of t)e.add(n)}function Ka(e,t,n=0){yt(e,t,n>=1?{}:{onIssue:(r,i)=>{i.wakeable&&window.setTimeout(()=>Ka(e,t,n+1),qa)}})}var qa=1200;function Ja(e){return e.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
3
+ `)}function Ya(e){return tt(Ja(e))}var Xa=e=>e.kind===`done`;function Za(e,t){let n=t===null?e:[...e.filter(e=>e.conversationId===t),...e];for(let e of n){if(!e.message)continue;let t=Ya(e.message);if(t!==``)return t}return``}function Qa(e){let t=(0,C.useRef)(Fa()),n=(0,C.useRef)(La()),r=(0,C.useRef)(!1),i=(0,C.useRef)({key:``,reader:It(),queue:[],busy:!1,token:0,spoke:!1,spokeConversation:``,conversationId:``,turnStartedAt:0}),a=(0,C.useRef)({conversationId:``,turnStartedAt:0,on:!1}),o=(0,C.useRef)(null),s=()=>{if(!(mn()||na()))return i.current.queue.shift()},c=e=>{let t=i.current;if(mn()||na()||(o.current=e,t.busy))return;let n=t.queue.shift();if(n===void 0)return;t.busy=!0,Yt(!0);let r=++t.token,a=()=>{r===t.token&&(t.busy=!1,t.queue.length===0&&Yt(!1),c(e))};yt(n,e,{onEnd:a,nextText:s,onIssue:e=>{Ut(`read:issue`,{message:e.slice(0,80)}),a()},onCancel:()=>{r===t.token&&(t.busy=!1,t.queue.length=0,Yt(!1))}})},l=(e,t)=>{e.length!==0&&(na()||(Ut(`read:enqueue`,{units:e.length,provider:t.provider,firstLen:e[0]?.length??0}),i.current.queue.push(...e),c(t)))},u=()=>{let e=i.current;e.token+=1,e.busy=!1,e.queue.length=0,e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset(),Yt(!1),St()},d=()=>{a.current={conversationId:i.current.conversationId,turnStartedAt:i.current.turnStartedAt,on:!0},u()};(0,C.useEffect)(()=>rn(d),[]);let f=()=>{let e=i.current;Ut(`read:interrupt`,{queued:e.queue.length,spoken:e.reader.spoken}),e.token+=1,e.busy=!1,e.queue.length=0,Yt(!1),St()};(0,C.useEffect)(()=>on(f),[]),(0,C.useEffect)(()=>gn(()=>{if(mn())return;let e=o.current;e&&c(e)}),[]);let p=(e,t)=>{let n=i.current;if(!t.enabled||!t.readReplies){r.current||(r.current=!0,Ut(`read:off`,{enabled:t.enabled,readReplies:t.readReplies}));return}let o=e.active.conversationId;if(o===null)return;let s=e.active.messages,c=null;for(let e=s.length-1;e>=0;--e){let t=s[e];if(t&&t.role===`assistant`){c=t;break}}if(!c||c.endedAt!==void 0)return;let u=e.runningByConversation[o],d=e.running.conversationId===o?e.running:null;if((u?.status??d?.status??`idle`)===`idle`)return;let f=c.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
4
+ `);if(f===``)return;let p=u?.turnStartedAt??d?.turnStartedAt??0;if(a.current.on&&a.current.conversationId===o){if(a.current.turnStartedAt===p)return;a.current={conversationId:``,turnStartedAt:0,on:!1}}let m=`${o}:${c.id}:${p}`;m!==n.key&&(n.token+=1,n.busy=!1,n.queue.length=0,n.reader.reset(),n.spoke=!1,n.spokeConversation=``,n.key=m,n.conversationId=o,n.turnStartedAt=p,St());let h=n.reader.push(f);h.length>0&&(n.spoke=!0,n.spokeConversation=o),l(h,t)};(0,C.useEffect)(()=>{if(!e)return;let r=Ke();p(e,r);let o=Wa(t.current,e);if(o.length===0)return;let s=U(),c=[];for(let e of o)e.kind===`done`||e.kind===`stopped`?c.push(e):(e.kind!==`steer`||s.steer)&&(Ia({kind:e.kind,voiceEnabled:r.enabled,readReplies:r.readReplies,hasReply:!1})===`clip`&&e.kind!==`start`?Na(e.kind):q(e.kind));if(c.length===0)return;let d=c.find(t=>t.conversationId===e.active.conversationId)??c[0],f=d.kind===`done`&&r.enabled&&r.readReplies?Za(c.filter(Xa),e.active.conversationId):``,m=Ia({kind:d.kind,voiceEnabled:r.enabled,readReplies:r.readReplies,hasReply:f!==``}),h=d.kind===`stopped`?`stopped`:`done`;if(h===`stopped`&&a.current.conversationId===d.conversationId&&(a.current={conversationId:``,turnStartedAt:0,on:!1}),h===`stopped`&&u(),Ba(n.current,m===`reply`?f:null,Date.now(),h)){if(m===`reply`){let e=i.current;if(a.current.on&&a.current.conversationId===d.conversationId)e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset();else if(e.spoke&&e.spokeConversation===d.conversationId){let t=d.message?e.reader.push(Ja(d.message)):[];l([...t,...e.reader.flush()],r),e.spoke=!1,e.spokeConversation=``,e.key=``,e.reader.reset()}else Ka(f,r)}else m===`clip`?Na(h):q(`done`)}},[e]),(0,C.useEffect)(()=>{let e=window.setTimeout(Pa,2e3);return()=>window.clearTimeout(e)},[])}var $a=200,eo=`pop-agent.unseen-finish`,to=(e,t)=>e.visible&&e.activeId===t;function no(e,t,n){let r=null,i=()=>(r??={...e},r);for(let e of t)n.running.includes(e)||to(n,e)||(i()[e]=n.now);for(let t of n.running)(r?.[t]!==void 0||e[t]!==void 0)&&delete i()[t];return n.activeId!==null&&to(n,n.activeId)&&(r?.[n.activeId]!==void 0||e[n.activeId]!==void 0)&&delete i()[n.activeId],r??e}function ro(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>t[n]===e[n])}function io(e){let t=Object.entries(e).filter(([,e])=>Number.isFinite(e)&&e>0);return t.length<=$a?e:(t.sort((e,t)=>t[1]-e[1]),Object.fromEntries(t.slice(0,$a)))}function ao(e){if(!e)return{};try{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t))e!==``&&typeof r==`number`&&Number.isFinite(r)&&r>0&&(n[e]=r);return io(n)}catch{return{}}}function oo(){try{return typeof localStorage>`u`?{}:ao(localStorage.getItem(eo))}catch{return{}}}var so=oo(),co=new Set;function lo(){for(let e of co)e()}function uo(e){try{localStorage.setItem(eo,JSON.stringify(e))}catch{}}function fo(e){let t=io(e);ro(so,t)||(so=t,uo(t),lo())}function po(){return so}function mo(e){return co.add(e),()=>{co.delete(e)}}function ho(e){if(so[e]===void 0)return;let{[e]:t,...n}=so;fo(n)}function go(e){if(!e.some(e=>so[e]!==void 0))return;let t={...so};for(let n of e)delete t[n];fo(t)}function _o(e,t){fo(no(so,e,t))}typeof window<`u`&&window.addEventListener(`storage`,e=>{if(e.key!==eo)return;let t=ao(e.newValue);ro(so,t)||(so=t,lo())});function vo(){if(typeof document>`u`)return;let e=document.querySelector(`.composer-input`);if(!e)return;e.focus();let t=e.value.length;try{e.setSelectionRange(t,t)}catch{}}var yo={snapshot:null,connection:`connecting`,lastError:null,draft:``,settingsOpen:!1,pendingActive:null,creating:!1,pendingNewChat:!1,newSession:null,preview:null},bo=new Set;function xo(){return yo}function So(e){Fo({draft:e})}var Co=`\0new-session`,wo=new Map,To=40,Eo=null;function Do(e){return e??Co}function Oo(){if(Eo!==null)return Eo;let e=xo();return Eo=e.newSession?Co:Do(e.pendingActive??e.snapshot?.active.conversationId??null),Eo}function ko(e,t){if(wo.set(e,t),!(wo.size<=To)){for(let t of wo.keys())if(t!==e){wo.delete(t);break}}}function Ao(e){let t=Oo(),n=Do(e);if(t===n)return;yo.draft===``?wo.delete(t):ko(t,yo.draft),Eo=n;let r=wo.get(n)??``;r!==yo.draft&&Fo({draft:r})}function jo(e){wo.delete(Do(e)),Eo===Do(e)&&(Eo=null)}function Mo(e){vo(),Ao(null);let t=xo().snapshot?.files?.root??null;Fo({newSession:{workspace:e===void 0?t:e,ephemeral:!1}})}function No(e){let t=xo().newSession;t&&Fo({newSession:{...t,workspace:e}})}function Po(e){let t=xo().newSession;t&&Fo({newSession:{...t,ephemeral:e}})}function Fo(e){yo={...yo,...e};for(let e of bo)e()}function Io(e){return bo.add(e),()=>{bo.delete(e)}}function Lo(){return(0,C.useSyncExternalStore)(Io,xo,xo)}function Ro(e){let t=(0,C.useRef)(e);t.current=e;let n=(0,C.useRef)(null),r=()=>{let e=t.current(xo());return n.current!==null&&Object.is(n.current.value,e)?n.current.value:(n.current={value:e},e)};return(0,C.useSyncExternalStore)(Io,r,r)}var zo=[];function Bo(e){zo=e}function Vo(){return zo}function Ho(){return(0,C.useSyncExternalStore)(mo,po,po)}function Uo(){return typeof document>`u`||document.visibilityState===`visible`}function Wo(e){let t=new Set;for(let[n,r]of Object.entries(e.runningByConversation??{}))r.status!==`idle`&&t.add(n);let n=e.running;return n.status!==`idle`&&n.conversationId&&t.add(n.conversationId),[...t]}function Go(){let e=Ro(e=>e.snapshot),[t,n]=(0,C.useState)(Uo),r=(0,C.useRef)([]);(0,C.useEffect)(()=>{let e=()=>n(Uo());return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),(0,C.useEffect)(()=>{if(!e)return;let n=Wo(e);_o(r.current,{running:n,activeId:e.active.conversationId,visible:t,now:Date.now()}),r.current=n},[e,t])}var Ko=n(),Q=r();function qo(){let e=document.querySelector(`.workspace .composer-wrap`);if(!e)return null;let t=getComputedStyle(e),n=e.getBoundingClientRect(),r=Number.parseFloat(t.paddingLeft)||0,i=Number.parseFloat(t.paddingRight)||0,a=n.width-r-i;return a>0?{left:n.left+r,width:a}:null}function Jo(e){(0,C.useEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=qo();e?(t.classList.add(`toast-host-in-column`),t.style.left=`${Math.round(e.left)}px`,t.style.width=`${Math.round(e.width)}px`,t.style.maxWidth=`none`):(t.classList.remove(`toast-host-in-column`),t.style.removeProperty(`left`),t.style.removeProperty(`width`),t.style.removeProperty(`max-width`))};n();let r=document.querySelector(`.workspace .composer-wrap`),i=new ResizeObserver(n);return r&&i.observe(r),window.addEventListener(`resize`,n),()=>{i.disconnect(),window.removeEventListener(`resize`,n)}},[e])}function Yo({item:e}){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(0),i=(0,C.useRef)(Date.now());return(0,C.useEffect)(()=>{if(t){r.current+=Date.now()-i.current;return}i.current=Date.now();let n=window.setTimeout(()=>rr(e.id),Math.max(1200,e.ttl-r.current));return()=>window.clearTimeout(n)},[t,e.id,e.ttl]),(0,Q.jsxs)(`div`,{className:`toast`,role:`status`,"aria-live":`polite`,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[(0,Q.jsx)(`span`,{className:`toast-text`,title:e.text,children:e.text}),e.actions.map(t=>(0,Q.jsx)(`button`,{type:`button`,className:`toast-action`,onClick:()=>{t.onClick(),rr(e.id)},children:t.label},t.label)),(0,Q.jsx)(`button`,{type:`button`,className:`toast-close`,title:`关掉`,onClick:()=>rr(e.id),children:`×`})]})}function Xo({children:e}){let t=(0,C.useRef)(null);return Jo(t),(0,Q.jsx)(`div`,{className:`toast-host`,ref:t,children:e})}function Zo(){let e=or();return e.length===0?null:(0,Ko.createPortal)((0,Q.jsx)(Xo,{children:e.map(e=>(0,Q.jsx)(Yo,{item:e},e.id))}),document.body)}var Qo=null,$o=new Set;function es(){for(let e of $o)e()}function ts(e){return $o.add(e),()=>{$o.delete(e)}}function ns(e,t=``){e&&(Qo={src:e,alt:t},es())}function rs(){Qo&&(Qo=null,es())}function is(){return(0,C.useSyncExternalStore)(ts,()=>Qo)}var as=.25,os=1.25;function ss(e){return!Number.isFinite(e)||e<=0?1:Math.min(8,Math.max(as,e))}function cs(e,t){let n=ss(e);return ss(t===`in`?n*os:n/os)}function ls(e,t,n=.94){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return 1;let r=Math.min(t.width*n/e.width,t.height*n/e.height);return!Number.isFinite(r)||r<=0||r>1?1:r}var us=`\\/:*?"<>|`,ds=100;function fs(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e<32||e===127||us.includes(n)?`_`:n}return t}function ps(e){let t=e.trim();if(t===``)return``;if(/^https?:\/\//i.test(t))try{t=new URL(t).pathname}catch{return``}t=t.split(`?`)[0]?.split(`#`)[0]??``;try{t=decodeURIComponent(t)}catch{}let n=fs(t.split(/[\\/]/).at(-1)??``).trim();return n.length>ds?n.slice(0,ds):n}function ms(e,t=``){let n=[t,/[?&]path=([^&#]*)/.exec(e)?.[1]??``,e].map(ps).filter(e=>e!==``);return n.find(e=>/\.[A-Za-z0-9]{1,8}$/.test(e))??n[0]??`image`}function hs(){let e=is(),t=Y(),n=e!==null,[r,i]=(0,C.useState)(1),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(1),[l,u]=(0,C.useState)(!1),d=e?.src??``;(0,C.useEffect)(()=>{i(1),o(null),c(1),u(!1)},[d]),(0,C.useEffect)(()=>{if(!n)return;let e=e=>{e.key===`Escape`?rs():e.metaKey||e.ctrlKey||e.altKey||(e.key===`+`||e.key===`=`?i(e=>cs(e,`in`)):e.key===`-`||e.key===`_`?i(e=>cs(e,`out`)):e.key===`0`&&i(1))};window.addEventListener(`keydown`,e);let t=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{window.removeEventListener(`keydown`,e),document.body.style.overflow=t}},[n]);let f=(0,C.useCallback)(e=>{let t=e.currentTarget,n=t.naturalWidth,r=t.naturalHeight;n<=0||r<=0||(o({width:n,height:r}),c(ls({width:n,height:r},{width:window.innerWidth,height:window.innerHeight})))},[]),p=(0,C.useCallback)(async()=>{if(!d||l)return;let t=ms(d,e?.alt??``);u(!0);try{let e=await fetch(d,{credentials:`same-origin`});if(!e.ok)throw Error(String(e.status));let n=await e.blob(),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(r),1e4)}catch{window.open(d,`_blank`,`noopener,noreferrer`)}finally{u(!1)}},[l,e?.alt,d]);if(!e)return null;let m=r!==1&&a!==null?{width:Math.round(a.width*s*r),height:`auto`,maxWidth:`none`,maxHeight:`none`}:void 0,h=Math.round(s*r*100);return(0,Ko.createPortal)((0,Q.jsxs)(`div`,{className:`image-viewer-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`图片预览`,`Image preview`),onClick:()=>rs(),children:[(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-close`,title:t(`关闭(Esc)`,`Close (Esc)`),"aria-label":t(`关闭`,`Close`),onClick:()=>rs(),children:`×`}),(0,Q.jsx)(`div`,{className:`image-viewer-stage`,onClick:e=>{e.target===e.currentTarget&&rs()},children:(0,Q.jsx)(`img`,{className:`image-viewer-img`,src:d,alt:e.alt,style:m,onLoad:f})}),(0,Q.jsxs)(`div`,{className:`image-viewer-tools`,onClick:e=>e.stopPropagation(),children:[(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool`,title:t(`缩小(-)`,`Zoom out (-)`),"aria-label":t(`缩小`,`Zoom out`),disabled:r<=as,onClick:()=>i(e=>cs(e,`out`)),children:`−`}),(0,Q.jsxs)(`button`,{type:`button`,className:`image-viewer-zoom`,title:t(`点一下回到适应窗口(0)`,`Click to reset to fit (0)`),onClick:()=>i(1),children:[h,`%`]}),(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool`,title:t(`放大(+)`,`Zoom in (+)`),"aria-label":t(`放大`,`Zoom in`),disabled:r>=8,onClick:()=>i(e=>cs(e,`in`)),children:`+`}),(0,Q.jsx)(`span`,{className:`image-viewer-divider`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`image-viewer-tool image-viewer-download`,title:t(`下载这张图`,`Download this image`),disabled:l,onClick:()=>void p(),children:t(`下载`,`Download`)})]})]}),document.body)}var gs=260,_s=`pop-agent.sidebar.width`,vs=`pop-agent.sidebar.collapsed`;function ys(e,t=2**53-1){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,240),Math.max(240,t))):gs}function bs(e){return!Number.isFinite(e)||e<=0?2**53-1:Math.max(240,Math.round(e-240))}function xs(e){return e===null?gs:ys(Number(e))}function Ss(e){return e.stored===`1`||e.stored!==`0`&&e.tablet}function Cs(e){return e(`(pointer: coarse) and (min-width: 601px) and (max-width: 1366px)`)}var ws=[{id:`newChat`,label:`新会话`,labelEn:`New session`,hint:`换掉左边这条主对话,会落盘`,hintEn:`Replaces the main chat on the left; it is saved`,defaultCombo:`Mod+Alt+N`},{id:`newProject`,label:`新项目`,labelEn:`New project`,hint:`打开目录选择器;macOS 上 ⌘M 会被系统「最小化」抢走,所以默认避开 ⌘M`,hintEn:`Opens the directory picker; ⌘M is taken by Window ▸ Minimize on macOS, so it is avoided`,defaultCombo:`Mod+Alt+X`},{id:`tempChat`,label:`临时会话`,labelEn:`Temp session`,hint:`在右侧另开一条不落盘的聊天`,hintEn:`Opens an unsaved chat on the right`,defaultCombo:`Mod+Alt+H`},{id:`settings`,label:`设置`,labelEn:`Settings`,defaultCombo:`Mod+Comma`},{id:`toggleRight`,label:`收起 / 展开右侧栏`,labelEn:`Toggle right panel`,hint:`同一个键开 / 关:关着就打开,开着就收起`,hintEn:`Opens and closes with the same key`,defaultCombo:`Mod+Alt+O`},{id:`toggleLeft`,label:`收起 / 展开左侧栏`,labelEn:`Toggle left sidebar`,defaultCombo:`Mod+Alt+L`},{id:`projects`,label:`项目`,labelEn:`Projects`,hint:`侧栏里「项目」那一栏的开关;侧栏收着时会先展开`,hintEn:`Toggles the Projects section in the sidebar; expands the sidebar if it was collapsed`,defaultCombo:`Mod+Alt+P`},{id:`files`,label:`文件`,labelEn:`Files`,hint:`同一个键开 / 关:右侧面板里的「文件」页开着就收起`,hintEn:`Opens and closes with the same key; expands the sidebar if it was collapsed`,defaultCombo:`Mod+Alt+F`},{id:`canvas`,label:`画布`,labelEn:`Canvas`,hint:`同一个键开 / 关:没开就打开画布标签,已经开着就收起来`,hintEn:`Opens and closes the canvas tab with the same key`,defaultCombo:`Mod+Alt+C`},{id:`terminal`,label:`切换终端`,labelEn:`Toggle terminal`,hint:"Ctrl+` —— 显示 / 隐藏对话框下面的终端(隐藏时进程不断);mac ⌘` 会被系统「切换窗口」先吃掉,所以用 ⌃",hintEn:"Ctrl+` — shows / hides the terminal under the chat (shells keep running while hidden); on macOS ⌘` is taken by “cycle windows”, hence ⌃",defaultCombo:`Ctrl+Backquote`},{id:`contentSearch`,label:`搜索文件内容`,labelEn:`Search file contents`,hint:`全文搜索浮层(改键后文件管理里那句提示也会跟着变)`,hintEn:`Full-text search overlay; the hint in the file manager follows this binding`,defaultCombo:`Mod+Shift+F`},{id:`toggleMic`,label:`开始 / 停止语音输入`,labelEn:`Start / stop voice input`,hint:`按一下开、一直听着,再按一下关;也可以按住不放说一句短的,松手就停(设置里能录右⌘ / 右⌥,也能录成只按这一颗)`,hintEn:`Tap to keep listening, tap again to stop; or hold and release to say one short thing (right ⌘ / right ⌥ work, alone or with a key)`,defaultCombo:`Mod+Alt+M`},{id:`pauseSpeech`,label:`暂停 / 继续朗读`,labelEn:`Pause / resume reading`,hint:`冻住正在念的这句,再按一次从原地接着念(不会跳过后面的内容);朗读中浮条上也有这颗按钮`,hintEn:`Freezes the current sentence; press again to continue from the same spot (nothing later gets skipped). Also a button on the floating bar`,defaultCombo:`Mod+Shift+P`},{id:`stopSpeech`,label:`停止朗读`,labelEn:`Stop reading aloud`,hint:`停掉正在念的这句;这一轮剩下的文字也不再自动念(朗读中底部也会出现一颗按钮)`,hintEn:`Stops the current sentence; the rest of this turn stays silent (a button also appears while reading)`,defaultCombo:`Mod+Alt+S`},{id:`cheatSheet`,label:`快捷键速查表`,labelEn:`Shortcut cheat sheet`,hint:`浮层列出当前所有绑定(就是这份表);再按一次关掉`,hintEn:`Shows every binding as an overlay; press again to close`,defaultCombo:`Mod+Slash`}],Ts=`pop-agent.shortcuts`,Es=`pop-agent:shortcuts`,Ds=new Set([`Enter`,`Space`,`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Comma`,`Period`,`Slash`,`Backquote`,`Minus`,`Equal`,`BracketLeft`,`BracketRight`,`Semicolon`,`Quote`,`Backslash`]),Os=new Set([`Meta`,`Control`,`Shift`,`Alt`,`AltGraph`,`CapsLock`,`Dead`]),ks=new Set([`Mod+T`,`Mod+Shift+T`,`Mod+W`,`Mod+Shift+W`,`Mod+N`,`Mod+Shift+N`,`Mod+R`,`Mod+Shift+R`,`Mod+Q`,`Mod+L`,`Mod+P`,`Mod+Shift+J`,`Mod+Shift+I`,`Mod+Alt+I`]);function As(e){let t=e.code??``,n=/^Key([A-Z])$/.exec(t);if(n?.[1])return n[1];let r=/^Digit([0-9])$/.exec(t);if(r?.[1])return r[1];let i=/^F([1-9]|1[0-2])$/.exec(t);return i?.[0]?i[0]:Ds.has(t)?t:/^[a-zA-Z0-9]$/.test(e.key)?e.key.toUpperCase():e.key===` `||e.key===`Spacebar`?`Space`:Os.has(e.key)?null:Ds.has(e.key)?e.key:null}function js(e){return As(e)}var Ms={Mod:{mod:!0,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1},RightMod:{mod:!0,ctrl:!1,shift:!1,alt:!1,modRight:!0,altRight:!1},Alt:{mod:!1,ctrl:!1,shift:!1,alt:!0,modRight:!1,altRight:!1},RightAlt:{mod:!1,ctrl:!1,shift:!1,alt:!0,modRight:!1,altRight:!0},Ctrl:{mod:!1,ctrl:!0,shift:!1,alt:!1,modRight:!1,altRight:!1}},Ns=/^F([1-9]|1[0-2])$/;function Ps(e){if(!e)return null;let t=e.split(`+`);if(t.length===1){let e=t[0]??``,n=Ms[e];return n?{...n,key:``}:Ns.test(e)?{mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:e}:null}let n=t[t.length-1]??``;if(n===``)return null;let r={mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:n};for(let e of t.slice(0,-1))if(e===`Mod`)r.mod=!0;else if(e===`RightMod`)r.mod=!0,r.modRight=!0;else if(e===`RightAlt`)r.alt=!0,r.altRight=!0;else if(e===`Ctrl`)r.ctrl=!0;else if(e===`Shift`)r.shift=!0;else if(e===`Alt`)r.alt=!0;else return null;return!r.mod&&!r.ctrl&&!r.alt?null:/^[A-Z0-9]$/.test(n)||/^F([1-9]|1[0-2])$/.test(n)||Ds.has(n)?r:null}function Fs(e){let t=[];return e.mod&&t.push(e.modRight?`RightMod`:`Mod`),e.ctrl&&t.push(`Ctrl`),e.shift&&t.push(`Shift`),e.alt&&t.push(e.altRight?`RightAlt`:`Alt`),e.key!==``&&t.push(e.key),t.join(`+`)}function Is(e,t){return!(!e||!t||e.key!==t.key||e.mod!==t.mod||e.ctrl!==t.ctrl||e.shift!==t.shift||e.alt!==t.alt||e.modRight&&!t.modRight||e.altRight&&!t.altRight)}function Ls(e){let t=Ps(e);return t?Fs(t):null}var Rs={mod:!1,alt:!1};function zs(e,t=oc()){let n=e.type!==`keyup`;e.code===(t?`MetaRight`:`ControlRight`)?Rs.mod=n:e.code===`AltRight`&&(Rs.alt=n)}function Bs(){Rs.mod=!1,Rs.alt=!1}function Vs(e,t,n=Rs){let r=As(e);if(!r)return null;let i=t?!!e.metaKey:!!e.ctrlKey,a=t?!!e.ctrlKey:!1,o=!!e.altKey;return!i&&!a&&!o?Ns.test(r)?{mod:!1,modRight:!1,ctrl:!1,shift:!!e.shiftKey,alt:!1,altRight:!1,key:r}:null:t&&a&&!i&&/^[A-Z0-9]$/.test(r)?null:{mod:i,modRight:i&&n.mod,ctrl:a,shift:!!e.shiftKey,alt:o,altRight:o&&n.alt,key:r}}function Hs(e,t=oc()){let n=Vs(e,t);return n?Fs(n):null}function Us(e,t=oc()){let n=Ps(e);return n?!t&&n.ctrl?{...n,ctrl:!1,mod:!0,modRight:!1}:n:null}function Ws(e,t,n=oc()){let r=Vs(t,n);if(!r)return null;for(let t of ws)if(Is(Us(e[t.id],n),r))return t.id;return null}function Gs(e){let t=Ps(e);return t?ks.has(Fs({...t,modRight:!1,altRight:!1})):!1}function Ks(e,t=oc()){let n=e.code??``,r={mod:!1,ctrl:!1,shift:!1,alt:!1,modRight:!1,altRight:!1,key:``},i=t?`Meta`:`Control`;return n===`${i}Left`?{...r,mod:!0}:n===`${i}Right`?{...r,mod:!0,modRight:!0}:n===`AltLeft`?{...r,alt:!0}:n===`AltRight`?{...r,alt:!0,altRight:!0}:t&&(n===`ControlLeft`||n===`ControlRight`)?{...r,ctrl:!0}:null}function qs(e,t=oc()){return Ks(e,t)!==null}function Js(e,t=oc()){let n=Ks(e,t);return n?Fs(n):null}function Ys(e,t,n=oc()){let r=Ks(t,n);if(!r)return null;for(let t of ws)if(Is(Us(e[t.id],n),r))return t.id;return null}function Xs(){let e={};for(let t of ws)e[t.id]=Ls(t.defaultCombo);return Zs(e)}function Zs(e){let t=[],n={};for(let r of ws){let i=Ls(e[r.id]),a=Ps(i),o=a!==null&&t.some(e=>Is(e,a)||Is(a,e));!i||!a||o?n[r.id]=null:(t.push(a),n[r.id]=i)}return n}var Qs={toggleRight:[`openRight`,`closeRight`]};function $s(e){let t=null;try{t=e?JSON.parse(e):null}catch{t=null}let n=t&&typeof t==`object`?t:{},r={};for(let e of ws){if(!(e.id in n)){let t=Qs[e.id]?.find(e=>typeof n[e]==`string`);if(t){r[e.id]=Ls(n[t]);continue}r[e.id]=Ls(e.defaultCombo);continue}let t=n[e.id],i=t===null?null:Ls(typeof t==`string`?t:null);r[e.id]=t===null?null:i??Ls(e.defaultCombo)}return Zs(r)}function ec(){if(typeof localStorage>`u`)return Xs();try{return $s(localStorage.getItem(Ts))}catch{return Xs()}}function tc(e){let t=Zs(e);try{localStorage.setItem(Ts,JSON.stringify(t))}catch{}window.dispatchEvent(new CustomEvent(Es,{detail:t}))}function nc(e){let t=()=>e(),n=t=>{t.key===`pop-agent.shortcuts`&&e()};return window.addEventListener(Es,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Es,t),window.removeEventListener(`storage`,n)}}function rc(e,t,n=350){return t?`stop`:e>=n?`startHold`:`start`}function ic(e,t,n,r=oc()){let i=Us(t,r);if(!i)return null;for(let t of ws){if(t.id===n)continue;let a=Us(e[t.id],r);if(Is(a,i)||Is(i,a))return t.id}return null}function ac(e){let t=ws.find(t=>t.id===e);return{zh:t?.label??e,en:t?.labelEn??e}}function oc(){if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)}var sc={Enter:[`⏎`,`Enter`],Space:[`Space`,`Space`],ArrowUp:[`↑`,`↑`],ArrowDown:[`↓`,`↓`],ArrowLeft:[`←`,`←`],ArrowRight:[`→`,`→`],Comma:[`,`,`,`],Period:[`.`,`.`],Slash:[`/`,`/`],Backquote:["`","`"],Minus:[`-`,`-`],Equal:[`=`,`=`],BracketLeft:[`[`,`[`],BracketRight:[`]`,`]`],Semicolon:[`;`,`;`],Quote:[`'`,`'`],Backslash:[`\\`,`\\`]};function cc(e,t=oc()){let n=Ps(e);if(!n)return``;let r=[];if(t?(n.ctrl&&r.push(`⌃`),n.mod&&r.push(n.modRight?`右⌘`:`⌘`),n.shift&&r.push(`⇧`),n.alt&&r.push(n.altRight?`右⌥`:`⌥`)):(n.mod?r.push(n.modRight?`RightCtrl`:`Ctrl`):n.ctrl&&r.push(`Ctrl`),n.shift&&r.push(`Shift`),n.alt&&r.push(n.altRight?`RightAlt`:`Alt`)),n.key!==``){let e=sc[n.key];r.push(e?e[+!t]:n.key)}return t?r.join(``):r.join(`+`)}var lc=null;function uc(e){return lc=e,()=>{lc===e&&(lc=null)}}function dc(){return lc?(lc(),!0):!1}var fc=!1,pc=new Set;function mc(){for(let e of pc)e()}function hc(e){return pc.add(e),()=>{pc.delete(e)}}function gc(){fc||(fc=!0,mc())}function _c(){fc&&(fc=!1,mc())}function vc(){fc?_c():gc()}function yc(){return(0,C.useSyncExternalStore)(hc,()=>fc)}function bc(e,t=oc()){return ws.map(n=>{let r=Ls(e[n.id]);return{id:n.id,label:n.label,labelEn:n.labelEn,combo:r?cc(r,t):null}})}function xc(){let[e,t]=(0,C.useState)(()=>ec());return(0,C.useEffect)(()=>nc(()=>t(ec())),[]),[e,(0,C.useCallback)(e=>tc(e),[])]}var Sc=`pop-agent.preview.tabs.v1`;function Cc(e){return e.kind===`file`&&e.path&&e.root!==void 0?{kind:`file`,path:e.path,root:e.root}:e.kind===`web`?{kind:`web`,url:e.url??``}:e.kind===`files`?{kind:`files`}:null}function wc(e){let t=[];return e.slice(0,10).forEach((e,n)=>{e.kind===`file`?t.push({id:`file:${e.root}:${e.path}`,kind:`file`,path:e.path,root:e.root}):e.kind===`web`?t.push({id:`web:restored:${n}`,kind:`web`,url:e.url}):t.push({id:`files:restored:${n}`,kind:`files`})}),t}function Tc(e){if(e===null)return null;try{let t=JSON.parse(e);if(!Array.isArray(t?.tabs))return null;let n=t.tabs.filter(Ec);return n.length===0?null:{tabs:n.slice(0,10),active:typeof t.active==`string`?t.active:null,open:t.open===!0}}catch{return null}}function Ec(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.kind===`file`?typeof t.path==`string`&&t.path!==``&&typeof t.root==`string`:t.kind===`web`?typeof t.url==`string`:t.kind===`files`}function Dc(e,t,n){let r=[],i=null;for(let n of e){if(r.length>=10)break;let e=Cc(n);e!==null&&(r.push(e),n.id===t&&(i=n.id))}return JSON.stringify({tabs:r,active:i,open:n})}function Oc(e){let t=new URLSearchParams(e).get(`session`);return t!==null&&t.trim()!==``?t.trim():null}function kc(e,t){let n=new URL(e);return t===null?n.searchParams.delete(`session`):n.searchParams.set(`session`,t),`${n.pathname}${n.search}${n.hash}`}var Ac=`pop-agent-cache`,jc=1,Mc=`transcripts`,Nc=40,Pc=3145728,Fc=null;function Ic(){return Fc??=new Promise(e=>{if(typeof indexedDB>`u`)e(null);else try{let t=indexedDB.open(Ac,jc);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(Mc)||e.createObjectStore(Mc,{keyPath:`id`}).createIndex(`savedAt`,`savedAt`)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}catch{e(null)}}),Fc}function Lc(e){let t=0;for(let n of e){t+=120;for(let e of n.blocks)e.kind===`text`||e.kind===`thinking`?t+=e.text.length*2:t+=240}return t}async function Rc(e){let t=await Ic();return t?new Promise(n=>{try{let r=t.transaction(Mc,`readonly`).objectStore(Mc).get(e);r.onsuccess=()=>{let e=r.result;n(e&&Array.isArray(e.messages)&&e.messages.length>0?e.messages:null)},r.onerror=()=>n(null)}catch{n(null)}}):null}async function zc(e,t){if(t.length===0)return;if(Lc(t)>Pc){await Bc(e);return}let n=await Ic();if(!n)return;let r={id:e,savedAt:Date.now(),messages:t};return new Promise(e=>{try{let t=n.transaction(Mc,`readwrite`),i=t.objectStore(Mc);i.put(r);let a=0;i.index(`savedAt`).openCursor(null,`prev`).onsuccess=e=>{let t=e.target.result;t&&(a+=1,a>Nc&&t.delete(),t.continue())},t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()}catch{e()}})}async function Bc(e){let t=await Ic();if(t)return new Promise(n=>{try{let r=t.transaction(Mc,`readwrite`);r.objectStore(Mc).delete(e),r.oncomplete=()=>n(),r.onerror=()=>n(),r.onabort=()=>n()}catch{n()}})}function Vc(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Hc(e,t){if(Object.is(e,t))return t;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return t;let n=!1,r=t.map((t,r)=>{let i=Hc(e[r],t);return i!==e[r]&&(n=!0),i});return n?r:e}if(Vc(e)&&Vc(t)){let n=Object.keys(t);if(n.length!==Object.keys(e).length)return t;let r=!1,i={};for(let a of n){if(!Object.hasOwn(e,a))return t;let n=Hc(e[a],t[a]);i[a]=n,n!==e[a]&&(r=!0)}return r?i:e}return t}function Uc(e,t){return e==null?t:Hc(e,t)}function Wc(e,t){let n=[...e.blocks],r=n[n.length-1];return r&&r.kind===`text`?n[n.length-1]={kind:`text`,text:r.text+t}:n.push({kind:`text`,text:t}),{...e,blocks:n}}function Gc(){return`/login`}function Kc(){try{if(location.pathname===Gc())return;location.replace(Gc())}catch{}}function qc(e){return e===401&&(Kc(),!0)}function Jc(){try{let e=location.hostname.toLowerCase();return e!==`localhost`&&e!==`127.0.0.1`&&e!==`::1`&&e!==`[::1]`}catch{return!1}}function Yc(){fetch(`/api/auth/logout`,{method:`POST`}).catch(()=>void 0).finally(()=>Kc())}async function Xc(){try{(await fetch(`/api/health`,{cache:`no-store`})).status===401&&Kc()}catch{}}function Zc(e,t){let n=e.indexOf(t);return n<0?1/0:n}function Qc(e,t){let n=[],r=[];for(let i of e)Zc(t,i.id)===1/0?r.push(i):n.push(i);n.sort((e,n)=>Zc(t,e.id)-Zc(t,n.id)||n.startedAt-e.startedAt),r.sort((e,t)=>t.startedAt-e.startedAt);let i=n.reduce((e,t)=>Math.max(e,t.startedAt),-1/0),a=r.filter(e=>e.startedAt>i),o=r.filter(e=>e.startedAt<=i);return[...a,...n,...o]}function $c(e,t,n){if(t===n||!e.includes(n))return e;let r=e.filter(e=>e!==t),i=r.indexOf(n);return i<0?e:(r.splice(i,0,t),r)}function el(e,t,n){let r=new Set(t),i=e.filter(e=>!r.has(e));return[...n,...i]}function tl(e,t){return[t,...e.filter(e=>e!==t)]}function nl(e,t){return e[0]===t?null:tl(e,t)}function rl(){let e=typeof globalThis>`u`?void 0:globalThis.crypto;if(e&&typeof e.randomUUID==`function`)try{return e.randomUUID()}catch{}let t=new Uint8Array(16);if(e&&typeof e.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}var il=!1;function al(e){let{wsPath:t,sseUrl:n,handlers:r}=e,i=!1,a=null,o=()=>{let e=new EventSource(n);a=e,e.onopen=()=>r.onOpen(),e.onmessage=e=>r.onMessage(String(e.data)),e.onerror=()=>r.onError?.()};return il?o():(()=>{let e=window.location.protocol===`https:`?`wss`:`ws`,n;try{n=new WebSocket(`${e}://${window.location.host}${t}`)}catch{il=!0,o();return}a={close:()=>n.close()};let s=!1;n.onopen=()=>{s=!0,r.onOpen()},n.onmessage=e=>{typeof e.data==`string`&&r.onMessage(e.data)},n.onerror=()=>r.onError?.(),n.onclose=()=>{i||(s?r.onClose():(il=!0,o()))}})(),{close:()=>{i=!0,a?.close()}}}var ol=8e3,sl=500,cl=`pop-agent-client`;function ll(){let e=sessionStorage.getItem(cl);return e||(e=rl(),sessionStorage.setItem(cl,e)),e}var ul=!1;function dl(){ul=!0;try{sessionStorage.removeItem(cl)}catch{}}var fl=null,pl=0,ml=null;function hl(){ml!==null&&(clearTimeout(ml),ml=null)}var $=0,gl=0,_l=null;function vl(){if(_l!==null)return;if(gl>=3){gl=0;return}let e=Math.min(sl*2**gl,ol);gl+=1,_l=setTimeout(()=>{_l=null,Cl({id:`req-${++$}`,type:`get_state`})},e)}function yl(){if(fl)return;hl(),Fo({connection:`connecting`});let e=`client=${encodeURIComponent(ll())}&slim=1`;fl=al({wsPath:`/ws?${e}`,sseUrl:`/api/events?${e}`,handlers:{onOpen:()=>{pl=0,Fo({connection:`open`,lastError:null}),bl(`get_state`)},onMessage:e=>{let t;try{t=JSON.parse(e)}catch{return}Su(t)},onError:()=>{Xc(),Fo({connection:`connecting`})},onClose:()=>{fl=null,Fo({connection:`closed`});let e=Math.min(sl*2**pl,ol);pl+=1,hl(),ml=setTimeout(()=>{ml=null,(typeof document>`u`||document.visibilityState!==`hidden`)&&yl()},e)}}})}function bl(e){let t=`req-${++$}`;return Cl({id:t,type:e}),t}function xl(){hl(),fl&&(fl.close(),fl=null,Fo({connection:`connecting`}))}function Sl(){typeof document<`u`&&document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?xl():yl()})}function Cl(e){return(async()=>{try{let t=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify(e)});if(!t.ok){if(qc(t.status))return;Fo({lastError:{text:t.status===502||t.status===503||t.status===504?J(`后端正在重启或还没起来(HTTP ${t.status}),稍等自动恢复`,`The backend is restarting or not up yet (HTTP ${t.status}) — it recovers on its own in a moment`):J(`请求失败:HTTP ${t.status}`,`Request failed: HTTP ${t.status}`),conversationId:null}}),vl();return}gl=0;let n=await t.json();for(let e of n.frames??[])try{Su(JSON.parse(e))}catch{}}catch{Fo({lastError:{text:J(`连接尚未就绪,稍后再试`,`The connection is not ready yet — try again in a moment`),conversationId:null}}),vl()}})()}function wl(e){Cl({id:`req-${++$}`,type:`cancel_queued`,payload:{queueId:e}})}function Tl(e){Cl({id:`req-${++$}`,type:`interrupt_subagent`,payload:{runId:e}})}function El(e){Cl({id:`req-${++$}`,type:`save_subagent_profile`,payload:{profile:e}})}function Dl(e){Cl({id:`req-${++$}`,type:`delete_subagent_profile`,payload:{profileId:e}})}function Ol(e){Cl({id:`req-${++$}`,type:`set_subagent_settings`,payload:e})}function kl(){Cl({id:`req-${++$}`,type:`get_state`})}function Al(e,t,n){Cl({id:`req-${++$}`,type:`send_message`,payload:{text:e,...t&&t.length>0?{attachments:t}:{},...n&&n!==`now`?{mode:n}:{}}})}function jl(e){Cl({id:`req-${++$}`,type:`interrupt`,payload:{conversationId:e}})}var Ml=null,Nl=null,Pl=!1,Fl=null,Il=null,Ll=null;function Rl(e,t,n,r,i){Ml={text:e,attachments:t,mode:n},zl(r,i)}function zl(e,t){vo(),Il={from:xo().snapshot?.active.conversationId??null};let n=Il;Fo({creating:!0,pendingNewChat:!0}),setTimeout(()=>{Fo({creating:!1}),Il===n&&n!==null&&(Il=null,Fo({pendingNewChat:!1,...xo().newSession?{newSession:null}:{}}))},8e3);let r={...e?{workspace:e}:{},...t?.ephemeral?{ephemeral:!0}:{}},i=`req-${++$}`;Nl=i,Pl=t?.ephemeral===!0,Cl(Object.keys(r).length>0?{id:i,type:`new_chat`,payload:r}:{id:i,type:`new_chat`})}function Bl(e){let t=`req-${++$}`;Ll={id:t,conversationId:e},Cl({id:t,type:`persist_conversation`,payload:{conversationId:e}})}function Vl(e){Cl({id:`req-${++$}`,type:`close_ephemeral`,payload:{conversationId:e}})}function Hl(e,t){vo(),Fo({creating:!0}),setTimeout(()=>Fo({creating:!1}),8e3);let n=`req-${++$}`;Fl=n,Cl({id:n,type:`fork_session`,payload:{conversationId:e,messageId:t}})}function Ul(e){if(typeof e!=`string`||e===``)return;let t=xo().snapshot?.settings.sessionPrefs;if(!t)return;let n=nl(t.order,e);n&&bu({sessionPrefs:{...t,order:n}})}var Wl=1200;function Gl(e,t){Cl({id:`req-${++$}`,type:`rename_session`,payload:{conversationId:e,title:t}})}function Kl(e){return(async()=>{try{let t=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify({id:`req-${++$}`,type:`suggest_title`,payload:{conversationId:e}})});if(!t.ok)return qc(t.status)||Fo({lastError:{text:J(`起名失败:HTTP ${t.status}`,`Could not generate a name: HTTP ${t.status}`),conversationId:e}}),!1;let n=await t.json(),r=!1;for(let t of n.frames??[]){let n=JSON.parse(t);n.type===`reply`&&(r=n.result?.ok===!0),n.type===`reply`&&n.result?.error?.message&&Fo({lastError:{text:n.result.error.message,conversationId:e}}),n.type===`notice`&&n.payload?.message&&!r&&Fo({lastError:{text:n.payload.message,conversationId:e}})}return r}catch(t){return Fo({lastError:{text:J(`起名失败:${t instanceof Error?t.message:String(t)}`,`Could not generate a name: ${t instanceof Error?t.message:String(t)}`),conversationId:e}}),!1}})()}function ql(e,t){Cl({id:`req-${++$}`,type:`move_session`,payload:{conversationId:e,workspace:t}})}function Jl(e,t){Cl({id:`req-${++$}`,type:`refresh_resources`,payload:t?.force?{conversationId:e,force:!0}:{conversationId:e}})}function Yl(e){if(Ao(e),en(),Fo({pendingActive:e,preview:null,newSession:null}),typeof window<`u`){let t=kc(window.location.href,e);window.history.replaceState(null,``,t)}Cl({id:`req-${++$}`,type:`switch_conversation`,payload:{conversationId:e}}),Rc(e).then(t=>{t&&xo().pendingActive===e&&Fo({preview:{conversationId:e,messages:t}})}),setTimeout(()=>{xo().pendingActive===e&&(Cl({id:`req-${++$}`,type:`switch_conversation`,payload:{conversationId:e}}),setTimeout(()=>{xo().pendingActive===e&&Fo({pendingActive:null})},Wl*3))},Wl)}var Xl=null,Zl=null;function Ql(e,t){Zl={conversationId:e,messages:t},!Xl&&(Xl=setTimeout(()=>{Xl=null;let e=Zl;Zl=null,e&&zc(e.conversationId,e.messages)},3e3))}function $l(e){Cl({id:`req-${++$}`,type:`set_thinking_level`,payload:{level:e}})}function eu(e,t){return Cl({id:`req-${++$}`,type:`refresh_actions`,...e||t?{payload:{...e?{conversationId:e}:{},...t?{count:t}:{}}}:{}})}function tu(e){Cl({id:`req-${++$}`,type:`set_engine`,payload:{engine:e}})}function nu(e,t){Cl({id:`req-${++$}`,type:`set_approval_mode`,payload:t?{mode:e,conversationId:t}:{mode:e}})}function ru(e,t,n){Cl({id:`req-${++$}`,type:`canvas_start_node`,payload:{conversationId:e,nodeId:t,...n===void 0?{}:{parent:n}}})}async function iu(e,t,n){try{let r=await fetch(`/api/rpc`,{signal:AbortSignal.timeout(8e3),method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":ll()},body:JSON.stringify({id:`req-${++$}`,type:`canvas_suggest`,payload:{conversationId:e,nodeIds:t,...n===void 0?{}:{parent:n}}})});if(!r.ok)return qc(r.status),[];let i=await r.json();for(let e of i.frames??[]){let t=JSON.parse(e);if(t.type!==`reply`)continue;let n=t.result?.suggestions;if(Array.isArray(n))return n.filter(e=>typeof e==`string`)}return[]}catch{return[]}}function au(e,t,n,r){Cl({id:`req-${++$}`,type:`canvas_update_node`,payload:{conversationId:e,nodeId:t,...n,...r===void 0?{}:{parent:r}}})}function ou(e,t,n,r){Cl({id:`req-${++$}`,type:`canvas_set_status`,payload:{conversationId:e,nodeId:t,status:n,...r===void 0?{}:{parent:r}}})}function su(e,t,n){t.length!==0&&Cl({id:`req-${++$}`,type:`canvas_delete`,payload:{conversationId:e,ids:t,...n===void 0?{}:{parent:n}}})}function cu(e,t,n){t.length!==0&&Cl({id:`req-${++$}`,type:`canvas_move`,payload:{conversationId:e,moves:t,...n===void 0?{}:{parent:n}}})}function lu(e,t){Cl({id:`req-${++$}`,type:`set_model`,payload:t?{modelId:e,conversationId:t}:{modelId:e}})}function uu(){Cl({id:`req-${++$}`,type:`list_providers`})}async function du(e){try{let t=await fetch(`/api/templates/generate-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();return n.ok===!0&&typeof n.text==`string`?{ok:!0,text:n.text}:{ok:!1,message:n.message??`HTTP ${t.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function fu(e){try{let t=await fetch(`/api/cron/generate-prompt`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();return n.ok===!0&&typeof n.text==`string`?{ok:!0,text:n.text}:{ok:!1,message:n.message??`HTTP ${t.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function pu(e,t){try{let n=await fetch(`/api/providers/${encodeURIComponent(e)}/models/${encodeURIComponent(t)}/test`,{method:`POST`}),r=await n.json();return n.ok?{ok:r.ok===!0,status:r.status,latencyMs:r.latencyMs,message:r.message}:{ok:!1,message:r.error?.message??`HTTP ${n.status}`}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}async function mu(e,t){try{let n=await fetch(`/api/models/probe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({modelId:e}),...t?{signal:t}:{}}),r=await n.json();return{ok:r.ok===!0,ttftMs:r.ttftMs??null,totalMs:r.totalMs,outputTokens:r.outputTokens,tps:r.tps??null,averageTps:r.averageTps??null,message:r.message??r.error?.message??(n.ok?void 0:`HTTP ${n.status}`)}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}function hu(e,t){Cl({id:`req-${++$}`,type:`update_model`,payload:{provider:e,model:t}})}function gu(e,t,n){Cl({id:`req-${++$}`,type:`set_enabled_models`,payload:{provider:e,enabled:t,...n?{modelId:n}:{}}})}function _u(e,t){Cl({id:`req-${++$}`,type:`remove_model`,payload:{provider:e,modelId:t}})}function vu(e){Cl({id:`req-${++$}`,type:`delete_provider`,provider:e})}function yu(e){Cl({id:`req-${++$}`,type:`upsert_provider`,payload:e})}function bu(e){Cl({id:`req-${++$}`,type:`set_settings`,payload:e})}function xu(e,t){Cl({id:`req-${++$}`,type:`approve`,payload:{requestId:e,decision:t}})}function Su(e){if(e.type===`reply`){if(Nl!==null&&e.id===Nl){let t=Ml,n=e.ok&&!Pl;Nl=null,Pl=!1,Ml=null,e.ok?(n&&Ul(e.result?.conversationId),t&&Al(t.text,t.attachments,t.mode)):t&&So(t.text),e.ok||(Il=null)}if(Fl!==null&&e.id===Fl&&(Fl=null,e.ok&&Ul(e.result?.conversationId)),Ll!==null&&e.id===Ll.id){let{conversationId:t}=Ll;Ll=null,e.ok&&Ul(t)}e.ok||(xo().pendingActive!==null&&Ao(xo().snapshot?.active.conversationId??null),Fo({lastError:{text:`${e.error.code}: ${e.error.message}`,conversationId:xo().snapshot?.active.conversationId??null},...xo().pendingActive?{pendingActive:null}:{},...xo().preview?{preview:null}:{},...xo().pendingNewChat?{pendingNewChat:!1}:{}}))}else if(e.event===`snapshot`){let t=xo().pendingActive,n=xo().preview,r=xo().snapshot,i=e.snapshot.piProjects??r?.piProjects??[],a=Uc(r,{...e.snapshot,piProjects:i}),o=Il!==null&&e.snapshot.active.conversationId!==Il.from,s=o&&xo().newSession!==null;o&&(Il=null);let c=ul&&t===null&&Il===null&&xo().newSession===null;ul&&=!1,(!t||t===e.snapshot.active.conversationId)&&(s||!xo().newSession)&&Ao(e.snapshot.active.conversationId??null),Fo({snapshot:a,lastError:null,creating:!1,...c?{newSession:{workspace:e.snapshot.files?.root??null,ephemeral:!1}}:{},...o?{pendingNewChat:!1}:{},...s?{newSession:null}:{},...t&&e.snapshot.active.conversationId===t?{pendingActive:null}:{},...n&&n.conversationId===e.snapshot.active.conversationId?{preview:null}:{}});let l=e.snapshot.active.conversationId;l&&Ql(l,e.snapshot.active.messages)}else e.event===`message_delta`&&Cu(e.conversationId,e.messageId,e.text)}function Cu(e,t,n){let r=xo().snapshot;if(!r||r.active.conversationId!==e)return;let i=r.active.messages.map(e=>e.id===t?Wc(e,n):e);Fo({snapshot:{...r,active:{...r.active,messages:i}}})}var wu={name:`pop-agent-text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`sentences`,spellCheck:!1,inputMode:`text`};function Tu(e){return e.replace(/\r\n/g,`
5
5
  `).split(`
6
6
  `).map(e=>e.trim()===``?`>`:`> ${e}`).join(`
7
7
  `)}function Eu(e,t){let n=e.replace(/\s+$/,``);return n===``?`${t}\n\n`:`${n}\n\n${t}\n\n`}function Du(e,t){return Eu(e,t)}var Ou=80;function ku(e,t=400){if(typeof e!=`string`)return``;let n=e.replace(/\s+/g,` `).trim();return n.length>t?n.slice(0,t):n}function Au(e,t=Ou){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function ju(e){return Au(e.replace(/`/g,`'`),240)}function Mu(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.__aw!==`picker`)return null;if(t.type===`ready`)return{kind:`ready`,url:ku(t.url,2e3)};if(t.type===`blank`)return{kind:`blank`,url:ku(t.url,2e3)};if(t.type===`exit`)return{kind:`exit`};if(t.type!==`picked`&&t.type!==`note`)return null;let n=ju(ku(t.selector,400));if(n===``)return null;let r={url:ku(t.url,2e3),selector:n,tag:ku(t.tag,40),label:Au(ku(t.label,200)),text:Au(ku(t.text,200))};return t.type===`note`?{kind:`note`,note:{...r,comment:ku(t.comment,2e3)}}:{kind:`picked`,pick:r}}function Nu(e){let t=[],n=ju(e.selector);n!==``&&t.push(`位置:\`${n}\``);let r=e.tag.trim(),i=e.label.trim(),a=e.text.trim(),o=[];i!==``&&i!==a&&o.push(`「${i}」`),a!==``&&a!==i&&o.push(`「${a}」`);let s=`${r}${o.join(` `)}`;return s!==``&&t.push(`元素:${s}`),t}function Pu(e){return e.url.trim()}function Fu(e){return e.kind===`web`}var Iu=e=>`pop-agent.annotations.${e}`,Lu=[];function Ru(e){if(typeof e!=`object`||!e)return null;let t=e;if(typeof t.id!=`string`||t.id===``)return null;let n={id:t.id,comment:typeof t.comment==`string`?t.comment:``,createdAt:typeof t.createdAt==`number`&&Number.isFinite(t.createdAt)?t.createdAt:0,quoted:t.quoted===!0};if(t.kind===`web`){let e=typeof t.spot==`object`&&t.spot!==null?t.spot:null;return e===null||typeof e.selector!=`string`||e.selector.trim()===``?null:{...n,kind:`web`,number:typeof t.number==`number`&&Number.isFinite(t.number)?t.number:0,spot:{url:typeof e.url==`string`?e.url:``,selector:e.selector,tag:typeof e.tag==`string`?e.tag:``,label:typeof e.label==`string`?e.label:``,text:typeof e.text==`string`?e.text:``}}}if(t.kind!==void 0&&t.kind!==`message`||typeof t.messageId!=`string`||t.messageId===``)return null;let r=typeof t.anchor==`object`&&t.anchor!==null?t.anchor:null;return r===null||typeof r.exact!=`string`||r.exact===``?null:{...n,messageId:t.messageId,anchor:{exact:r.exact,prefix:typeof r.prefix==`string`?r.prefix:``,suffix:typeof r.suffix==`string`?r.suffix:``}}}function zu(e){if(e===null||e===``)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Ru(e);t!==null&&n.push(t)}return n.slice(-200)}function Bu(e,t){if(e===null||t===null)return[...Lu];try{return zu(e.getItem(Iu(t)))}catch{return[...Lu]}}function Vu(e,t,n){if(e!==null&&t!==null)try{if(n.length===0){e.removeItem(Iu(t));return}e.setItem(Iu(t),JSON.stringify(n.slice(-200)))}catch{}}function Hu(e,t,n){return e.findIndex(e=>!Fu(e)&&e.messageId===t&&e.anchor.exact===n.exact&&e.anchor.prefix===n.prefix&&e.anchor.suffix===n.suffix)}function Uu(e,t,n){return e.findIndex(e=>Fu(e)&&e.spot.url===t&&e.spot.selector===n)}function Wu(e,t){let n=Fu(t)?Uu(e,t.spot.url,t.spot.selector):Hu(e,t.messageId,t.anchor);if(n>=0){let r=e.slice(),i=e[n],a=t;return r[n]=Fu(i)&&Fu(a)?{...i,spot:a.spot,comment:a.comment}:{...i,comment:a.comment},r}return[...e,t].slice(-200)}function Gu(e,t){return e.filter(e=>e.id!==t)}function Ku(e,t,n){return e.map(e=>e.id===t?{...e,comment:n}:e)}function qu(e,t){return e.map(e=>e.id===t?{...e,quoted:!0}:e)}function Ju(e,t){let n=e.comment.trim(),r=Fu(e)&&e.number>0?e.number:t,i=Fu(e)?Yu(e,r):`标注 ${r}:\n${Tu(e.anchor.exact)}`;return n===``?i:`${i}\n\n${n}`}function Yu(e,t){let n=Xu(Pu(e.spot));return[n===``?`标注 ${t}(网页):`:`标注 ${t}(网页 ${n}):`,...Nu(e.spot)].join(`
8
- `)}function Xu(e){return e.length>120?`${e.slice(0,120)}…`:e}function Zu(e){let t=``;for(let[n,r]of e.entries())r.quoted!==!0&&(t=Du(t,Ju(r,n+1)));return t.replace(/\s+$/,``)}function Qu(e,t){let n=e.findIndex(e=>e.id===t);if(n<0)return 0;let r=e[n];return Fu(r)&&r.number>0?r.number:n+1}var $u=`pop-agent.web-marks.v1`,ed=40,td=[];function nd(e,t){return typeof e==`string`?e.slice(0,t):``}function rd(e){if(typeof e!=`object`||!e)return null;let t=e,n=nd(t.url,2e3).trim(),r=nd(t.selector,400).trim();if(n===``||r===``)return null;let i=typeof t.number==`number`&&Number.isFinite(t.number)&&t.number>0?t.number:0;return{number:Math.floor(i),url:n,selector:r,comment:nd(t.comment,2e3),createdAt:typeof t.createdAt==`number`&&Number.isFinite(t.createdAt)?t.createdAt:0}}function id(e){if(e===null||e===``)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=rd(e);t!==null&&n.push(t)}return ld(n)}function ad(e){if(e===null)return[...td];try{return id(e.getItem($u))}catch{return[...td]}}var od=`pop-agent:web-marks`;function sd(e){let t=t=>{t.key===$u&&e()};return window.addEventListener(od,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(od,e),window.removeEventListener(`storage`,t)}}function cd(e,t){if(e!==null){try{let n=ld(t);n.length===0?e.removeItem($u):e.setItem($u,JSON.stringify(n))}catch{}try{window.dispatchEvent(new Event(od))}catch{}}}function ld(e){let t=new Map;for(let n of e){let e=t.get(n.url);e===void 0?t.set(n.url,[n]):e.push(n)}return[...t.entries()].map(([e,t])=>({url:e,list:t.sort((e,t)=>e.number-t.number).slice(-200),last:t.reduce((e,t)=>Math.max(e,t.createdAt),0)})).sort((e,t)=>t.last-e.last).slice(0,ed).flatMap(e=>e.list)}function ud(e,t){return e.filter(e=>e.url===t).sort((e,t)=>e.number-t.number)}function dd(e,t){let n=0;for(let r of e)r.url===t&&r.number>n&&(n=r.number);return n+1}function fd(e,t,n=Date.now()){let r=e.find(e=>e.url===t.url&&e.selector===t.selector);if(r!==void 0)return e.map(e=>e===r?{...e,comment:t.comment,createdAt:n}:e);let i={number:dd(e,t.url),url:t.url,selector:t.selector,comment:t.comment,createdAt:n};return ld([...e,i])}function pd(e,t,n){return e.filter(e=>e.url!==t||e.selector!==n)}function md(e,t){return e.filter(e=>e.url!==t)}function hd({annotations:e,open:t,focusedId:n,onToggle:r,onRemove:i,onQuote:a,onJump:o,onComment:s,onClear:c}){let l=J(),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(``),m=(0,C.useRef)(null),[h,g]=(0,C.useState)(!1);if((0,C.useEffect)(()=>{u!==null&&m.current?.focus()},[u]),(0,C.useEffect)(()=>{t?u!==null&&!e.some(e=>e.id===u)&&d(null):d(null)},[t,e,u]),(0,C.useEffect)(()=>{e.length===0&&g(!1)},[e.length]),e.length===0)return null;let _=()=>g(!0),v=()=>{g(!1),c()},y=e=>{d(e.id),p(e.comment)},b=()=>{u!==null&&s(u,f.trim()),d(null)};return(0,Q.jsxs)(`div`,{className:`annot-summary`,children:[(0,Q.jsxs)(`div`,{className:`annot-head`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`annot-chip`,onClick:r,"aria-expanded":t,title:l(`这条对话里标过的几处文字(点开看每一条)`,`Spots you marked in this chat (click to see each)`),children:[(0,Q.jsx)(`span`,{className:`annot-chip-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,children:(0,Q.jsx)(`path`,{d:`M2.5 3.5h11v7.2h-6L4.2 13v-2.3H2.5z`,strokeLinejoin:`round`})})}),l(`${e.length} 条注释`,`${e.length} note(s)`),(0,Q.jsx)(`span`,{className:`annot-chip-caret${t?` annot-chip-caret-open`:``}`,"aria-hidden":`true`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-trash`,onClick:_,title:l(`批量清空这条对话里的全部注释`,`Discard all notes in this chat`),"aria-label":l(`批量清空`,`Discard all`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2.5 4h11M6.2 4V2.8h3.6V4M4 4l.7 9.2h6.6L12 4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),h?(0,Q.jsxs)(`div`,{className:`annot-confirm`,role:`alertdialog`,children:[(0,Q.jsx)(`div`,{className:`annot-confirm-title`,children:l(`丢弃所有待处理标注?`,`Discard all pending notes?`)}),(0,Q.jsx)(`div`,{className:`annot-confirm-sub`,children:l(`页面上的所有编辑都将被移除`,`All edits on the page will be removed`)}),(0,Q.jsxs)(`div`,{className:`annot-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`annot-confirm-cancel`,onClick:()=>g(!1),children:l(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-confirm-danger`,onClick:v,children:l(`放弃`,`Discard`)})]})]}):null]}),t?(0,Q.jsx)(`ul`,{className:`annot-list`,children:e.map(t=>{let r=Fu(t),s=r?t.spot.selector:t.anchor.exact.replace(/\s+/g,` `).trim(),c=u===t.id;return(0,Q.jsxs)(`li`,{id:`annot-row-${t.id}`,className:`annot-row${n===t.id?` annot-row-focus`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`annot-row-main`,disabled:r,onClick:()=>{r||o(t)},title:r?`${l(`网页上的一处`,`A spot on the page`)}: ${t.spot.url} ${t.spot.selector}`:l(`跳到正文里那一处`,`Jump to that spot in the chat`),children:[(0,Q.jsx)(`span`,{className:`annot-index`,children:Qu(e,t.id)}),r?(0,Q.jsx)(`span`,{className:`annot-web-mark`,children:`🌐`}):null,(0,Q.jsx)(`span`,{className:`annot-excerpt`,children:s})]}),c?(0,Q.jsxs)(`div`,{className:`annot-edit`,children:[(0,Q.jsx)(`input`,{ref:m,className:`annot-edit-input`,value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),b()),e.key===`Escape`&&(e.preventDefault(),d(null))},placeholder:l(`给这一处写句评论(可留空,回车保存)`,`Comment on this spot (optional, Enter to save)`),"aria-label":l(`这条标注的评论`,`Comment for this note`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action annot-action-ok`,onClick:b,title:l(`保存评论`,`Save comment`),children:`✓`})]}):t.comment===``?null:(0,Q.jsx)(`button`,{type:`button`,className:`annot-comment`,onClick:()=>y(t),title:l(`点一下改这句评论`,`Click to edit this comment`),children:t.comment}),(0,Q.jsxs)(`div`,{className:`annot-row-actions`,children:[c?null:(0,Q.jsx)(`button`,{type:`button`,className:`annot-action`,onClick:()=>y(t),title:l(t.comment===``?`给这一处写句评论`:`改这一处的评论`,t.comment===``?`Comment on this spot`:`Edit this comment`),children:t.comment===``?l(`+ 评论`,`+ Comment`):l(`改评论`,`Edit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action`,onClick:()=>a(t),title:l(`把这段(连同评论)变成引用接进输入框,再写自己的问题发出去`,`Quote this (with your comment) into the input, then send`),children:l(`放进输入框`,`Quote it`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action annot-action-remove`,onClick:()=>i(t.id),title:l(`删掉这条标注`,`Remove this annotation`),"aria-label":l(`删掉这条标注`,`Remove this annotation`),children:`✕`})]})]},t.id)})}):null]})}function gd(e){Bc(e),jo(e),Vl(e)}function _d({title:e,onConfirm:t,onCancel:n}){let r=J(),i=(0,C.useRef)(null);(0,C.useEffect)(()=>{i.current?.focus()},[]),(0,C.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let a=e||r(`未命名会话`,`Untitled session`);return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`close-ephemeral-title`,"aria-describedby":`close-ephemeral-desc`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,id:`close-ephemeral-title`,children:r(`关闭临时对话「${a}」?`,`Close the temporary chat “${a}”?`)}),(0,Q.jsxs)(`div`,{id:`close-ephemeral-desc`,children:[(0,Q.jsx)(`p`,{className:`modal-risk`,children:r(`它只活在内存里(没有会话文件),关闭后内容直接丢弃,无法恢复。`,`It lives in memory only (there is no session file). Closing it discards the content for good.`)}),(0,Q.jsx)(`p`,{children:r(`想留下去历史里找,请先点「保存为正式对话」。`,`To keep it in history, click “Save as a regular chat” first.`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:i,type:`button`,className:`btn`,onClick:n,children:r(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:t,children:r(`关闭对话`,`Close chat`)})]})]})})}function vd(e,t){let n=e[t];if(!n)return{from:t+1,to:t+1};let r=t+1;for(;r<e.length&&(e[r]?.depth??0)>n.depth;)r+=1;return{from:t+1,to:r}}function yd(e,t){if(!e[t])return e;let{to:n}=vd(e,t);return[...e.slice(0,t+1).map((e,n)=>n===t?{...e,expanded:!1}:e),...e.slice(n)]}function bd(e){let t=e.split(`/`).filter(e=>e!==``),n=[];for(let e=1;e<t.length;e+=1)n.push(t.slice(0,e).join(`/`));return n}function xd(e,t,n){return(e??t??``)===n?e:n===``?null:n}function Sd(e){for(let t of bd(e))if(t.split(`/`).some(e=>e.startsWith(`.`)))return t;return null}var Cd=/(^|__)(write|edit|multiedit|multi_edit|apply_patch|patch|create_file|write_file|edit_file|update_file|modify_file|str_replace\w*)$/i,wd=[`path`,`file_path`,`filePath`],Td=/"(?:path|file_path|filePath)"\s*:\s*"((?:[^"\\]|\\.)+)"/;function Ed(e){let t=e.split(`/`);return t[t.length-1]??e}function Dd(e){let t=Ed(e),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function Od(e,t){let n=e.trim();if(n===``)return{path:``,outside:!0};if(!n.startsWith(`/`))return{path:n.replace(/^\.\//,``),outside:!1};if(t===null||t===``)return{path:n,outside:!0};let r=t.endsWith(`/`)?t:`${t}/`;return n===t?{path:``,outside:!0}:n.startsWith(r)?{path:n.slice(r.length),outside:!1}:{path:n,outside:!0}}function kd(e,t,n=0){if(n>3||typeof e!=`object`||!e)return;if(Array.isArray(e)){for(let r of e)kd(r,t,n+1);return}let r=e;for(let e of wd){let n=r[e];typeof n==`string`&&n.trim()!==``&&t.push(n)}let i=r.files;Array.isArray(i)&&kd(i,t,n+1)}function Ad(e){let t=(e.argsFull??e.argsSummary??``).trim();if(t===``)return[];let n=[];try{return kd(JSON.parse(t),n),n}catch{let e=Td.exec(t)?.[1];if(e!==void 0)try{n.push(JSON.parse(`"${e}"`))}catch{n.push(e)}return n}}function jd(e,t){let n=[],r=new Set;for(let i of e.blocks)if(i.kind===`tool`&&i.status===`ok`&&Cd.test(i.name))for(let e of Ad(i)){let{path:i,outside:a}=Od(e,t);i===``||r.has(i)||(r.add(i),n.push({path:i,name:Ed(i),ext:Dd(i),outside:a}))}return n}function Md(e){let t=[];for(let n of e)for(let e of n.blocks)if(e.kind===`tool`)for(let n of Ad(e))t.push({path:n,name:Ed(n)});return t}function Nd(e,t){let n=e.trim().replace(/\\/g,`/`).replace(/^\.\//,``);if(n===``||n.startsWith(`/`))return null;let r=t.filter(e=>e.path.startsWith(`/`)),i=[...r].reverse().find(e=>e.path===n||e.path.endsWith(`/${n}`));return i?i.path:[...r].reverse().find(e=>e.name===n)?.path??null}function Pd(){return xo().snapshot?.settings.sessionPrefs??{pinned:[],archived:[],order:[]}}function Fd(e){bu({sessionPrefs:{...Pd(),...e}})}function Id(e){let t=Pd();Fd({pinned:t.pinned.includes(e)?t.pinned.filter(t=>t!==e):[e,...t.pinned]})}function Ld(e){let t=Pd();t.archived.includes(e)&&Fd({archived:t.archived.filter(t=>t!==e)})}function Rd(e,t,n,r){let i=Pd();i.archived.includes(e)||(Fd({archived:[...i.archived,e]}),Z({text:n(`已归档「${t||`未命名会话`}」`,`Archived "${t||`Untitled session`}"`),actions:[{label:n(`撤销`,`Undo`),onClick:()=>Ld(e)},...r?[{label:n(`查看`,`View`),onClick:r}]:[]]}))}async function zd(e){Bc(e);try{let t=await fetch(`/api/sessions/delete`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,purge:!0})});if(!t.ok){let e=await t.json().catch(()=>null);return t.status===404||e?.error?.code===`session.not_found`?{ok:!0}:{ok:!1,message:e?.error?.message??`HTTP ${t.status}`}}return{ok:!0,mode:(await t.json().catch(()=>null))?.mode}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}var Bd=`服务端还是旧版本:只改了名、没真删(重启服务后重试,或先把控制台里的服务端重构一下)`,Vd=`The server is an old build: the file was only renamed, not deleted (restart the server and try again)`;function Hd(e,t){(async()=>{let n=await zd(e);n.ok?(jo(e),n.mode===`file`&&Z({text:q(`「${t}」${Bd}`,`“${t}” ${Vd}`),ttl:12e3}),kl()):Z({text:q(`彻底删除「${t}」失败:${n.message}`,`Could not permanently delete “${t}”: ${n.message}`),ttl:12e3})})()}function Ud(e,t=q(`选中的会话`,`the selected sessions`)){e.length!==0&&(async()=>{let n=0,r=!1,i=[];for(let t of e){let e=await zd(t);e.ok?(n+=1,jo(t),e.mode===`file`&&(r=!0)):i.push(e.message)}kl(),r&&Z({text:q(`${n} 条${Bd}`,`${n} session(s): ${Vd}`),ttl:12e3}),i.length>0&&Z({text:q(`彻底删除${t}:成功 ${n} 条,失败 ${i.length} 条(${i[0]})`,`Permanently delete ${t}: ${n} succeeded, ${i.length} failed (${i[0]})`),ttl:12e3})})()}var Wd=400,Gd=14,Kd=6;function qd({anchor:e,point:t,pointerTail:n=!1,className:r,style:i,align:a,closeOnLeave:o,onClose:s,children:c}){let l=(0,C.useRef)(null),u=(0,C.useRef)(null),[d,f]=(0,C.useState)({left:0,top:0,width:0,height:0,visible:!1,arrow:null,below:!1});return(0,C.useLayoutEffect)(()=>{let r=l.current;if(!r||!t&&!e)return;let i=r.getBoundingClientRect(),o=e?e.getBoundingClientRect():null,s=!0,c=8,u=8;t?n?(c=t.x-Gd,u=t.y+Kd):(c=t.x,u=t.y):o&&a===`center`?(c=o.left+o.width/2-i.width/2,u=o.top-i.height-4,s=!1):o&&(c=o.right-i.width,u=o.bottom+4),c+i.width>window.innerWidth-8&&(c=window.innerWidth-i.width-8),c<8&&(c=8),!s&&o&&u<8?(u=o.bottom+4,s=!0):s&&u+i.height>window.innerHeight-8&&(u=t?t.y-i.height-(n?Kd:0):o.top-i.height-4,s=!1),u<8&&(u=8);let d=null;if(o){let e=o.left+o.width/2-c;d=Math.min(Math.max(14,e),Math.max(14,i.width-14)),s=u>=o.top+o.height/2}else if(t&&n){let e=Gd;d=Math.min(Math.max(e,t.x-c),Math.max(e,i.width-e)),s=u>=t.y}f({left:c,top:u,width:i.width,height:i.height,visible:!0,arrow:d,below:s})},[e,t,a,n]),(0,C.useEffect)(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]),(0,C.useEffect)(()=>{let t=performance.now(),n=t=>{let n=t.target;l.current?.contains(n)||e?.contains(n)||s()},r=e=>{e.key===`Escape`&&s()},i=e=>{if(performance.now()-t<200)return;let n=e.target;n instanceof Node&&l.current?.contains(n)||s()};return document.addEventListener(`mousedown`,n),document.addEventListener(`keydown`,r),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{document.removeEventListener(`mousedown`,n),document.removeEventListener(`keydown`,r),window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[e,s]),(0,Ko.createPortal)((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{ref:l,className:`${r??`proj-menu`} proj-menu-floating`,role:`menu`,style:{left:d.left,top:d.top,visibility:d.visible?`visible`:`hidden`,...i},onContextMenu:e=>e.preventDefault(),onMouseLeave:o?()=>{window.matchMedia(`(hover: hover)`).matches&&(u.current!==null&&clearTimeout(u.current),u.current=setTimeout(()=>{u.current=null,s()},Wd))}:void 0,onMouseEnter:o?()=>{u.current!==null&&(clearTimeout(u.current),u.current=null)}:void 0,children:c}),d.arrow===null?null:(0,Q.jsx)(`span`,{className:`proj-menu-arrow${d.below?` proj-menu-arrow-top`:``}`,style:{left:d.left+d.arrow-5,top:d.below?d.top-5:d.top+d.height-5},"aria-hidden":`true`})]}),document.body)}var Jd=5e3;function Yd(e=Jd){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(!1);return(0,C.useEffect)(()=>{if(!t)return;let i=setTimeout(()=>{r.current=!1,n(!1)},e);return()=>clearTimeout(i)},[t,e]),{armed:t,run:(0,C.useCallback)(e=>{r.current?(r.current=!1,n(!1),e()):(r.current=!0,n(!0))},[])}}function Xd({point:e,anchor:t,title:n,pinned:r,splitSide:i,fork:a,onClose:o,onRename:s,onAiRename:c,aiRenaming:l=!1,onPin:u,onOpenInNewTab:d,onArchive:f,onDelete:p}){let m=J(),h=e=>()=>{o(),e()},g=Yd();return(0,Q.jsxs)(qd,{point:e,anchor:t,className:`pi-menu`,closeOnLeave:!0,onClose:o,children:[i?(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`和右边那块交换位置`,`Swap places with the right part`),onClick:h(i.onMove),children:i.chatOnRight?`← ${m(`移至左侧`,`Move to the left`)}`:`→ ${m(`移至右侧面板`,`Move to the right panel`)}`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:h(u),children:[`📌 `,r?m(`取消置顶会话`,`Unpin session`):m(`置顶会话`,`Pin session`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:h(s),children:[`✏️ `,m(`重命名`,`Rename`)]}),c?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:l,title:m(`按这条会话的内容让 AI 起一个简洁的名字(会直接改会话名)`,`Let AI name this session from its content (renames it directly)`),onClick:h(c),children:[`💬 `,l?m(`AI 正在起名…`,`AI is naming…`):m(`AI 重命名`,`AI rename`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`在新标签页打开这条会话(?session=…)`,`Open this session in a new tab (?session=…)`),onClick:h(d),children:[`↗ `,m(`在新标签页打开`,`Open in new tab`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:a===void 0||!a.enabled,title:a===void 0?m(`打开这条会话后,从它的标题上分叉`,`Open this session, then fork from its title`):a.enabled?m(`从这条会话的最后一条消息派生一条新会话(原会话不动)`,`Branch a new session from its last message`):a.reason??m(`现在不能分叉`,`Cannot fork right now`),onClick:a?.enabled?h(a.onFork):void 0,children:[`🌿 `,m(`分叉`,`Fork`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`从列表里隐藏,可在「已归档」里找回`,`Hide it from the list; find it again under Archived`),onClick:h(f),children:[`🗄 `,m(`归档`,`Archive`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${g.armed?` proj-menu-item-armed`:``}`,title:g.armed?m(`再点一次就真删「${n}」的会话文件:不可恢复`,`Click again to permanently delete the session file for "${n}"`):m(`把「${n}」连同磁盘上的会话文件一起删掉(不可恢复);第一下只是确认`,`Delete "${n}" together with its session file on disk (cannot be undone); the first click only arms it`),onClick:()=>g.run(()=>{o(),p()}),"aria-label":g.armed?m(`再点一次确认彻底删除`,`Click again to delete permanently`):m(`彻底删除`,`Purge`),children:g.armed?m(`🧨 再点一次彻底删除`,`🧨 Click again to purge`):`🧨 ${m(`彻底删除`,`Purge`)}`})]})}var Zd=`pop-agent:open-panel`;function Qd(e){try{window.dispatchEvent(new CustomEvent(Zd,{detail:e}))}catch{}}function $d(e){let t=t=>e(t.detail);return window.addEventListener(Zd,t),()=>window.removeEventListener(Zd,t)}var ef=`pop-agent.speech.pet.enabled`,tf=`pop-agent.speech.pet.animal`,nf=[{emoji:`🐱`,zh:`猫`,en:`Cat`},{emoji:`🦊`,zh:`狐狸`,en:`Fox`},{emoji:`🐰`,zh:`兔子`,en:`Rabbit`},{emoji:`🐧`,zh:`企鹅`,en:`Penguin`}],rf=nf[0].emoji;function af(e){Qr(ef,e)}var of=`pop-agent:speech-pet-animal`;function sf(){let e=Yr(tf);return nf.some(t=>t.emoji===e)?e:rf}function cf(e){Xr(tf,e);try{window.dispatchEvent(new CustomEvent(of,{detail:e}))}catch{}}function lf(){let[e,t]=(0,C.useState)(()=>sf());return(0,C.useEffect)(()=>{let e=e=>t(e.detail),n=e=>{(e.key===null||e.key===`pop-agent.speech.pet.animal`)&&t(sf())};return window.addEventListener(of,e),window.addEventListener(`storage`,n),()=>{window.removeEventListener(of,e),window.removeEventListener(`storage`,n)}},[]),[e,cf]}function uf(e,t){let[n,r]=(0,C.useState)(()=>Zr(e,t));return(0,C.useEffect)(()=>$r(e,r),[e]),[n,t=>Qr(e,t)]}var df=`pop-agent.speech.pet.pos.v1`,ff=8,pf=4,mf=28,hf=[`left`,`right`,`top`,`bottom`];function gf(){let e=Yr(df);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.x!=`number`||typeof t.y!=`number`||!Number.isFinite(t.x)||!Number.isFinite(t.y))return null;let n=hf.includes(t.docked)?t.docked:null;return{x:t.x,y:t.y,docked:n}}catch{return null}}function _f(e,t,n){return{x:Math.min(Math.max(ff,e.x),Math.max(ff,n.width-t.width-ff)),y:Math.min(Math.max(ff,e.y),Math.max(ff,n.height-t.height-ff))}}var vf=()=>({width:window.innerWidth,height:window.innerHeight});function yf(e,t,n){let r=n.width-t.width,i=n.height-t.height,a={left:e.x,right:r-e.x,top:e.y,bottom:i-e.y},o=null,s=mf;for(let e of hf)a[e]<s&&(s=a[e],o=e);return o===null?{..._f(e,t,n),docked:null}:{x:o===`left`?0:o===`right`?r:Math.min(Math.max(ff,e.x),Math.max(ff,r)),y:o===`top`?0:o===`bottom`?i:Math.min(Math.max(ff,e.y),Math.max(ff,i)),docked:o}}function bf(){let e=J(),t=Qt(),n=pn(),[r]=uf(ef,!0),[i]=lf(),a=(0,C.useRef)(null),[o,s]=(0,C.useState)(gf),[c,l]=(0,C.useState)(!1),[u,d]=(0,C.useState)(null),f=(0,C.useRef)(!1),p=(0,C.useRef)(null),m=(0,C.useRef)(!1),h=(0,C.useRef)(null),g=()=>{let e=a.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}};(0,C.useEffect)(()=>{let e=()=>s(e=>{if(!e)return e;let t=g(),n=vf(),r=_f(e,t,n);return{x:e.docked===`left`?0:e.docked===`right`?n.width-t.width:r.x,y:e.docked===`top`?0:e.docked===`bottom`?n.height-t.height:r.y,docked:e.docked}});return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let _=e=>{let t=a.current?.getBoundingClientRect();if(t){if(f.current=!1,m.current=!1,e.pointerType!==`mouse`){let{clientX:t,clientY:n}=e;p.current=window.setTimeout(()=>{p.current=null,m.current=!0,d({x:t,y:n})},600)}h.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,offsetX:e.clientX-t.left,offsetY:e.clientY-t.top}}},v=e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if(!f.current){if(!(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>pf))return;f.current=!0,p.current!==null&&(clearTimeout(p.current),p.current=null),e.currentTarget.setPointerCapture(e.pointerId),l(!0),s(e=>e?.docked?{...e,docked:null}:e)}let n=_f({x:e.clientX-t.offsetX,y:e.clientY-t.offsetY},g(),vf());s({...n,docked:null})},y=e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId||(h.current=null,l(!1),p.current!==null&&(clearTimeout(p.current),p.current=null),!f.current))return;let n=yf({x:e.clientX-t.offsetX,y:e.clientY-t.offsetY},g(),vf());s(n),Xr(df,JSON.stringify(n))},b=()=>{f.current?f.current=!1:m.current?m.current=!1:t&&hn(!n)},x=()=>{s(null),Xr(df,``)},S=t?n?`paused`:`reading`:`idle`;return r?(0,Q.jsxs)(`div`,{ref:a,className:`speech-pet is-${S}${c?` is-dragging`:``}${o?.docked?` is-docked-${o.docked}`:``}`,style:o?{left:`${o.x}px`,top:`${o.y}px`,right:`auto`,bottom:`auto`}:void 0,onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y,onDoubleClick:x,onContextMenu:e=>{e.preventDefault(),d({x:e.clientX,y:e.clientY})},title:e(`点:暂停 / 继续 · 右键(触屏长按):停止 · 拖动:挪位置(贴边吸成半圆)· 双击:回默认位`,`Click: pause / resume · right-click (long-press): stop · drag to move (snaps to edges) · double-click: reset`),children:[(0,Q.jsxs)(`div`,{className:`speech-pet-stage`,children:[S===`reading`?(0,Q.jsxs)(`span`,{className:`speech-pet-ping`,"aria-hidden":`true`,children:[(0,Q.jsx)(`i`,{}),(0,Q.jsx)(`i`,{}),(0,Q.jsx)(`i`,{})]}):null,S===`paused`?(0,Q.jsx)(`span`,{className:`speech-pet-paused`,"aria-hidden":`true`,children:`⏸`}):null,(0,Q.jsx)(`button`,{type:`button`,className:`speech-pet-face`,onClick:b,"aria-pressed":n,"aria-label":n?e(`继续朗读`,`Resume reading`):e(`暂停朗读`,`Pause reading`),title:n?e(`点一下接着念(从停下的地方继续)`,`Click to resume from where it paused`):e(`点一下暂停(停在这一句,后面的不会跳过)`,`Click to pause here — the rest keeps its place`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:i})})]}),u?(0,Q.jsxs)(qd,{point:u,className:`pi-menu`,closeOnLeave:!0,onClose:()=>d(null),children:[(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),hn(!n)},children:n?`▶ ${e(`继续朗读`,`Resume reading`)}`:`⏸ ${e(`暂停朗读`,`Pause reading`)}`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:!t,onClick:()=>{d(null),nn()},children:[`⏹ `,e(`停止朗读`,`Stop reading`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),Qd(`voice`)},children:[`🔊 `,e(`设置语音功能`,`Voice settings`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),af(!1)},children:[`✕ `,e(`关闭宠物`,`Hide the pet`)]})]}):null]}):null}var xf=400,Sf=/iPhone|iPod|Android.*Mobile|Windows Phone|IEMobile|BlackBerry|Opera Mini|HarmonyOS|\bMobile\b/i;function Cf(e){return Sf.test(e)}function wf(e){return e.width<=xf||Cf(e.userAgent)}function Tf(){return typeof window>`u`?!1:wf({width:window.innerWidth,userAgent:navigator.userAgent})}function Ef(){document.documentElement.classList.toggle(`is-mobile-shell`,Tf())}function Df(){Ef();let e=()=>Ef();return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}}function Of({approval:e}){let t=J();return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`危险操作确认`,`Confirm a risky operation`),children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,children:t(`需要你确认`)}),(0,Q.jsx)(`p`,{className:`modal-risk`,children:e.riskNote}),(0,Q.jsxs)(`dl`,{className:`modal-facts`,children:[(0,Q.jsx)(`dt`,{children:t(`工具`)}),(0,Q.jsx)(`dd`,{children:e.toolName}),(0,Q.jsx)(`dt`,{children:t(`参数`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.argsSummary}),(0,Q.jsx)(`dt`,{children:t(`这类操作`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.scopeHint})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xu(e.requestId,`deny`),children:t(`拒绝`,`Deny`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xu(e.requestId,`once`),children:t(`允许一次`,`Allow once`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>xu(e.requestId,`always`),children:t(`总是允许这类`,`Always allow this kind`)})]})]})})}var kf=4e3;function Af({notices:e,activeConversationId:t=null}){let n=J(),[r,i]=(0,C.useState)(()=>new Set),[a,o]=(0,C.useState)(()=>Date.now());(0,C.useEffect)(()=>{let e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);let s=e.filter(e=>(e.conversationId===void 0||e.conversationId===t)&&!r.has(e.id)&&a-e.ts<kf).slice(-3);if(s.length===0)return null;let c=e=>i(t=>{let n=new Set(t);return n.add(e),n});return(0,Q.jsx)(`div`,{className:`notices`,children:s.map(e=>(0,Q.jsxs)(`div`,{className:`notice notice-${e.level}`,children:[(0,Q.jsx)(`span`,{className:`notice-text`,children:e.text}),(0,Q.jsx)(`button`,{type:`button`,className:`notice-close`,onClick:()=>c(e.id),title:n(`关闭这条提示`,`Dismiss this notice`),children:`×`})]},e.id))})}var jf=5,Mf=10485760;function Nf(e,t){let n=[],r=[],i=t;for(let t of e)i>=jf?r.push(q(`${t.name}:一条消息最多 ${jf} 个附件`,`${t.name}: at most ${jf} attachments per message`)):t.size===0?r.push(q(`${t.name}:空文件`,`${t.name}: empty file`)):t.size>10485760?r.push(q(`${t.name}:超过 ${Math.round(Mf/1024/1024)}MB`,`${t.name}: over ${Math.round(Mf/1024/1024)}MB`)):(n.push(t),i+=1);return{accepted:n,rejected:r}}function Pf(e){let t=e.filter(e=>e.kind===`image`).map(e=>`![${e.name}](/api/uploads/${e.id})`);return t.length>0?`\n\n${t.join(`
9
- `)}`:``}async function Ff(e){try{let t=await fetch(`/api/uploads`,{method:`POST`,headers:{"content-type":e.type||`application/octet-stream`,"x-file-name":encodeURIComponent(e.name)},body:await e.arrayBuffer()});return t.ok?{ok:!0,attachment:await t.json()}:{ok:!1,error:(await t.json().catch(()=>null))?.error?.message??q(`上传失败(HTTP ${t.status})`,`Upload failed (HTTP ${t.status})`)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}var If=8,Lf=14;function Rf(e){let t=e.gap??8,n=e.trigger.left+e.trigger.width/2-e.popover.width/2,r=Math.max(If,e.viewport.width-e.popover.width-If),i=Math.min(Math.max(If,n),r),a=e.trigger.left+e.trigger.width/2,o=Math.max(Lf,e.popover.width-Lf),s=Math.min(Math.max(Lf,a-i),o);return{left:i,bottom:e.viewport.height-e.trigger.top+t,arrow:s}}function zf(e){let t=e.gap??6,n=e.trigger.left+e.trigger.width/2-e.popover.width/2,r=Math.max(If,e.viewport.width-e.popover.width-If),i=Math.min(Math.max(If,n),r),a=e.trigger.left+e.trigger.width/2,o=Math.max(Lf,e.popover.width-Lf);return{left:i,top:e.trigger.top+e.trigger.height+t,arrow:Math.min(Math.max(Lf,a-i),o)}}function Bf(e,t,n){if(e.length===0)return!0;let r=`${t}/${n}`;return e.some(e=>e===`${t}/**`||e===r)}function Vf(e){let t=e.indexOf(`/`);return t>0?e.slice(0,t):``}function Hf(e,t){let n=Vf(t);return n===``||Bf(e,n,t.slice(n.length+1))}function Uf(e){let t=e.id.indexOf(`/`);return t>0?e.id.slice(0,t):`other`}function Wf(e,t=``){let n=t.trim().toLowerCase(),r=[],i=new Map;for(let t of e){if(n!==``&&!`${t.label} ${t.id}`.toLowerCase().includes(n))continue;let e=Uf(t),a=i.get(e);a||(a={provider:e,models:[]},i.set(e,a),r.push(a)),a.models.push(t)}return r}function Gf(e,t){return t.length===0?e:e.filter(e=>Hf(t,e.id))}function Kf({models:e,enabledAllowlist:t=[],current:n,disabled:r,defaultModel:i,onSetDefault:a,onSwitch:o}){let s=J(),[c,l]=(0,C.useState)(!1),[u,d]=(0,C.useState)(``),f=(0,C.useRef)(null),[p,m]=(0,C.useState)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(null),_=Tf();(0,C.useLayoutEffect)(()=>{if(!c||_){m(null);return}let e=()=>{let e=h.current?.getBoundingClientRect(),t=g.current?.getBoundingClientRect();e&&t&&m(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[c,_,u]),(0,C.useEffect)(()=>{if(!c)return;let e=e=>{f.current?.contains(e.target)||l(!1)},t=e=>{e.key===`Escape`&&l(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let v=Gf(e,t),y=Wf(v,u),b=e.find(e=>e.id===n)?.label??n??q(`模型未就绪`,`model not ready`),x=v.length===0;return(0,Q.jsxs)(`div`,{className:`model-picker`,ref:f,children:[(0,Q.jsxs)(`button`,{ref:h,type:`button`,className:`tool-chip model-trigger`,onClick:()=>{r||(d(``),l(e=>!e))},disabled:r,title:n??s(`选择模型`,`Choose a model`),children:[(0,Q.jsx)(`span`,{className:`model-trigger-label`,children:b}),(0,Q.jsx)(`span`,{className:`model-caret`,"aria-hidden":`true`,children:`▾`})]}),c?(0,Q.jsx)(`div`,{className:`model-sheet-backdrop`,onClick:()=>l(!1),"aria-hidden":`true`}):null,c?(0,Q.jsxs)(`div`,{ref:g,className:`model-menu`,role:`listbox`,"aria-label":s(`选择模型`),style:_?void 0:p?{left:p.left,bottom:p.bottom}:{visibility:`hidden`},children:[!_&&p?(0,Q.jsx)(`span`,{className:`model-menu-arrow`,style:{left:p.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`model-sheet-close`,onClick:()=>l(!1),title:s(`关闭`),children:[`✕ `,s(`关闭`,`Close`)]}),(0,Q.jsxs)(`div`,{className:`model-list`,children:[y.length===0?(0,Q.jsx)(`div`,{className:`model-empty`,children:x?s(`没有启用的模型:去「模型」面板里勾选要用的`,`No enabled models — pick some in the Models panel`):s(`没有匹配的模型`)}):null,y.map(e=>(0,Q.jsxs)(`div`,{className:`model-group`,children:[(0,Q.jsx)(`div`,{className:`model-group-title`,children:e.provider.toUpperCase()}),e.models.map(e=>{let t=e.id===i;return(0,Q.jsxs)(`div`,{className:`model-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`model-item${e.id===n?` model-item-on`:``}`,onClick:()=>{(o??lu)(e.id),l(!1)},title:e.id,children:[(0,Q.jsx)(`span`,{className:`model-check`,"aria-hidden":`true`,children:e.id===n?`✓`:``}),(0,Q.jsx)(`span`,{className:`model-label`,children:e.label})]}),a?(0,Q.jsx)(`button`,{type:`button`,className:`model-pin${t?` model-pin-on`:``}`,onClick:()=>a(t?null:e.id),title:t?s(`取消本项目的默认模型`,`Clear this project's default model`):s(`设为本项目的默认模型(新会话用它起步)`,`Set as this project's default (new conversations start with it)`),"aria-pressed":t,children:t?`📌`:`📍`}):null]},e.id)})]},e.provider))]})]}):null]})}function qf(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`3.6`,cy:`8`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`2.1`}),(0,Q.jsx)(`circle`,{cx:`12.6`,cy:`8`,r:`2.7`})]})}var Jf={off:`关`,minimal:`最低`,low:`低`,medium:`中`,high:`高`,xhigh:`很高`,max:`最高`},Yf={off:`Off`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`Very high`,max:`Max`};function Xf({level:e,levels:t}){let n=J(),[r,i]=(0,C.useState)(!1),[a,o]=(0,C.useState)(null),s=(0,C.useRef)(null),c=(0,C.useRef)(null),l=(0,C.useRef)(null),u=Tf(),d=e??t[0]??``,f=e=>n(Jf[e]??e,Yf[e]??e);return(0,C.useLayoutEffect)(()=>{if(!r||u){o(null);return}let e=()=>{let e=c.current?.getBoundingClientRect(),t=l.current?.getBoundingClientRect();e&&t&&o(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[r,u]),(0,C.useEffect)(()=>{if(!r)return;let e=e=>{s.current?.contains(e.target)||i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[r]),t.length===0?null:(0,Q.jsxs)(`div`,{className:`thinking-picker-box`,ref:s,children:[(0,Q.jsxs)(`button`,{ref:c,type:`button`,className:`tool-chip thinking-picker`,title:n(`思考强度(越高的档位越慢,推理也更细)`,`Thinking level (higher is slower but reasons more finely)`),"aria-haspopup":`listbox`,"aria-expanded":r,onClick:()=>i(e=>!e),children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(qf,{})}),(0,Q.jsx)(`span`,{className:`thinking-value`,children:f(d)}),(0,Q.jsx)(`span`,{className:`thinking-caret`,"aria-hidden":`true`,children:`▾`})]}),r?(0,Q.jsx)(`div`,{className:`model-sheet-backdrop`,onClick:()=>i(!1),"aria-hidden":`true`}):null,r?(0,Q.jsxs)(`div`,{ref:l,className:`model-menu thinking-menu`,role:`listbox`,"aria-label":n(`思考强度`,`Thinking level`),style:u?void 0:a?{left:a.left,bottom:a.bottom}:{visibility:`hidden`},children:[!u&&a?(0,Q.jsx)(`span`,{className:`model-menu-arrow`,style:{left:a.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`model-sheet-close`,onClick:()=>i(!1),title:n(`关闭`),children:[`✕ `,n(`关闭`,`Close`)]}),(0,Q.jsx)(`div`,{className:`model-list`,children:t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`model-item${e===d?` model-item-on`:``}`,onClick:()=>{$l(e),i(!1)},children:[(0,Q.jsx)(`span`,{className:`model-check`,"aria-hidden":`true`,children:e===d?`✓`:``}),(0,Q.jsx)(`span`,{className:`model-label`,children:f(e)})]},e))})]}):null]})}function Zf(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.4`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.9`,fill:`currentColor`})]})}function Qf({surface:e,part:t=`both`}){let n=J(),r=Ro(e=>e.snapshot),i=e?e.snapshot:r,a=i?.conversations.find(e=>e.id===i.active.conversationId)?.workspace??i?.files?.root??``,o=i?.settings.defaultModels??{};return(0,Q.jsxs)(Q.Fragment,{children:[t!==`thinking`&&i&&i.models.length>0&&i.engineCapabilities.modelSwitch?(0,Q.jsx)(Kf,{models:i.models,enabledAllowlist:i.enabledModels??[],current:i.model,defaultModel:o[a]??null,onSetDefault:t=>{if(!a)return;if(e){e.setProjectDefaultModel?.(a,t);return}let n={...o};t?n[a]=t:delete n[a],bu({defaultModels:n})},onSwitch:e?e.switchModel:e=>lu(e,i?.active.conversationId??null)}):t===`thinking`?null:(0,Q.jsxs)(`span`,{className:`tool-chip tool-static mono`,title:i?.model?n(`这个会话使用的模型`,`The model this conversation uses`):n(`还没打开会话,模型列表要等会话就绪`,`No conversation yet — the model list appears once one is open`),children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Zf,{})}),(0,Q.jsx)(`span`,{children:i?.model??n(`模型未就绪`,`Model not ready`)})]}),t===`model`?null:(0,Q.jsx)(Xf,{level:i?.thinkingLevel??null,levels:i?.thinkingLevels??[]})]})}var $f={isRepo:!1,branch:null,branches:[]};function ep(e){let[t,n]=(0,C.useState)($f),[r,i]=(0,C.useState)(0);(0,C.useEffect)(()=>{if(n($f),!e)return;let t=!1;return(async()=>{try{let r=await(await fetch(`/api/files/git?root=${encodeURIComponent(e)}`)).json();if(t)return;n({isRepo:r.isRepo===!0,branch:r.branch??null,branches:Array.isArray(r.branches)?r.branches:[],error:typeof r.error==`string`?r.error:void 0})}catch{}})(),()=>{t=!0}},[e,r]);let a=(0,C.useCallback)(()=>i(e=>e+1),[]),o=(0,C.useCallback)(async(t,r={})=>{if(!e)return{ok:!1,message:q(`还没有打开项目`,`No project is open`)};try{let i=await fetch(`/api/files/git/checkout`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({root:e,branch:t,force:r.force===!0})}),a=await i.json();return!i.ok||a.error?a.error?.code===`files.dirty_worktree`?{ok:!1,message:a.error.message??q(`工作区有未提交改动`,`The working tree has uncommitted changes`),dirty:{files:Array.isArray(a.error.files)?a.error.files.filter(e=>typeof e==`string`):[],total:typeof a.error.total==`number`?a.error.total:0}}:{ok:!1,message:a.error?.message??q(`切换到 ${t} 失败`,`Could not switch to ${t}`)}:(n({isRepo:a.isRepo===!0,branch:a.branch??t,branches:Array.isArray(a.branches)?a.branches:[],error:void 0}),{ok:!0})}catch{return{ok:!1,message:q(`切分支的请求没发出去(服务端没响应)`,`The switch request did not go through (no response from the server)`)}}},[e]);return{...t,refresh:a,checkout:o}}function tp({className:e}){return(0,Q.jsxs)(`svg`,{className:e,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`4.6`,cy:`3.6`,r:`1.7`}),(0,Q.jsx)(`circle`,{cx:`4.6`,cy:`12.4`,r:`1.7`}),(0,Q.jsx)(`circle`,{cx:`11.4`,cy:`6.4`,r:`1.7`}),(0,Q.jsx)(`path`,{d:`M4.6 5.3v5.4`}),(0,Q.jsx)(`path`,{d:`M11.4 8.1c0 2.2-3.1 1.9-5.1 2.9`})]})}var np={fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`},rp=`m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,ip=`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`;function ap({open:e,className:t}){return(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:t,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:e?rp:ip,...np})})}function op({className:e}){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:e,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M12 10v6`,...np}),(0,Q.jsx)(`path`,{d:`M9 13h6`,...np}),(0,Q.jsx)(`path`,{d:ip,...np})]})}function sp({anchor:e,git:t,align:n,onClose:r}){let i=J(),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),d=async(e,n=!1)=>{if(a||e===t.branch)return;o(e),c(null);let i=await t.checkout(e,{force:n});o(null),i.ok?r():i.dirty?u({name:e,files:i.dirty.files,total:i.dirty.total}):c(i.message)};return(0,Q.jsxs)(qd,{anchor:e,className:`proj-menu files-branch-menu`,align:n,onClose:r,children:[(0,Q.jsxs)(`div`,{className:`files-branch-menu-head`,children:[(0,Q.jsx)(`span`,{className:`files-branch-menu-title`,children:l?i(`确认切换分支`,`Confirm branch switch`):i(`切换分支`)}),(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-refresh`,title:i(`刷新分支列表(别的终端里刚建的分支)`),onClick:()=>{c(null),u(null),t.refresh()},children:`⟳`})]}),l?(0,Q.jsxs)(`div`,{className:`files-branch-confirm`,children:[(0,Q.jsxs)(`div`,{className:`files-branch-confirm-text`,children:[`⚠️ `,i(`工作区有`,`The working tree has`),` `,(0,Q.jsx)(`b`,{children:l.total}),` `,i(`个未提交改动。切到`,`uncommitted change(s). Switching to`),` `,(0,Q.jsx)(`b`,{children:l.name}),` `,i(`会把它们带过去 (git 不会丢弃,放不下的会拒绝切换)。`,`carries them over (git never discards them; it refuses the switch if they do not fit).`)]}),l.files.length>0?(0,Q.jsxs)(`ul`,{className:`files-branch-confirm-files`,children:[l.files.slice(0,5).map(e=>(0,Q.jsx)(`li`,{title:e,children:e},e)),l.total>5?(0,Q.jsxs)(`li`,{className:`files-branch-confirm-more`,children:[`… `,i(`还有`,`and`),` `,l.total-5,` `,i(`个`,`more`)]}):null]}):null,(0,Q.jsxs)(`div`,{className:`files-branch-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-btn files-branch-btn-primary`,disabled:a!==null,onClick:()=>void d(l.name,!0),children:a===l.name?i(`切换中…`):i(`仍然切换`,`Switch anyway`)}),(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-btn`,disabled:a!==null,onClick:()=>u(null),children:i(`取消`)})]})]}):t.branches.length===0?(0,Q.jsx)(`div`,{className:`files-branch-hint`,children:t.error??i(`这个仓库还没有别的分支`,`This repo has no other branches yet`)}):(0,Q.jsx)(`div`,{className:`files-branch-list`,children:t.branches.map(e=>{let n=e===t.branch;return(0,Q.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":n,className:`proj-menu-item files-branch-item${n?` files-branch-item-current`:``}`,title:n?i(`${e}(当前分支)`,`${e} (current branch)`):i(`切换到 ${e}`,`Switch to ${e}`),disabled:a!==null,onClick:()=>void d(e),children:[(0,Q.jsx)(`span`,{className:`files-branch-tick`,children:n?`✓`:``}),(0,Q.jsx)(`span`,{className:`files-branch-item-name`,children:e}),a===e?(0,Q.jsx)(`span`,{className:`files-branch-pending`,children:i(`切换中…`)}):null]},e)})}),s?(0,Q.jsx)(`div`,{className:`files-branch-error`,children:s}):null]})}function cp({projectRoot:e}){let t=J(),n=ep(e),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(!1),s=D(e)||e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`new-scope-chip new-scope-chip-static`,title:e,children:[(0,Q.jsx)(`span`,{className:`new-scope-icon new-scope-icon-folder`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:s})]}),n.isRepo&&n.branch?(0,Q.jsxs)(`button`,{type:`button`,ref:i,className:`new-scope-chip`,title:t(`当前分支:${n.branch}(点一下切换)`,`Current branch: ${n.branch} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":a,onClick:()=>{a||n.refresh(),o(e=>!e)},children:[(0,Q.jsx)(tp,{className:`new-scope-icon new-scope-branch-icon`}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:n.branch})]}):null,a&&r?(0,Q.jsx)(sp,{anchor:r,git:n,align:`center`,onClose:()=>o(!1)}):null]})}var lp=5;function up({conversationId:e,running:t}){let n=J(),r=Ro(e=>e.snapshot),i=r?.settings.thinkCount??5,a=Tf()?Math.min(3,i):i,[o,s]=(0,C.useState)(!1),c=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>{c.current!==null&&clearTimeout(c.current)},[]);let l=t||e===null||o,u=o?n(`正在想想…结果出来这颗按钮就亮回来`,`Thinking… the button lights up again once the suggestions arrive`):t?n(`这一轮还在跑,等结束再来一批`,`This turn is still running — ask again when it ends`):e===null?n(`先打开一个会话,再让模型想想下一步`,`Open a conversation first, then let the model suggest next steps`):n(`想想:让模型基于当前上下文再给几条下一步建议`,`Think: ask the model for a few next-step suggestions from the current context`),d=()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),s(!1)};return(0,Q.jsxs)(`button`,{type:`button`,className:`tool-chip action-think${o?` action-think-busy`:``}`,disabled:l,"aria-busy":o,title:u,onClick:()=>{if(l)return;s(!0);let t=r?.settings.thinkTimeoutSec??20;c.current!==null&&clearTimeout(c.current),c.current=setTimeout(d,(t+lp)*1e3),eu(e??void 0,a).finally(d)},children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:`💡`}),n(`想想`,`Think`)]})}function dp(e){return e.filter(e=>e.hidden!==!0)}function fp(e,t){return t===`en`?{name:e.nameEn||e.name,description:e.descriptionEn||e.description,text:e.textEn||e.text}:{name:e.name,description:e.description,text:e.text}}function pp(e,t){if(typeof e==`string`)return e;let n=e.text??``;return t===`en`&&e.textEn?e.textEn:n}function mp(e){return e.id.startsWith(`t-`)}function hp(e,t){return e.flatMap(e=>e.id===t?mp(e)?[{...e,hidden:!0}]:[]:[e])}function gp(e){(0,C.useEffect)(()=>{let t=t=>{t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e())};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[e])}function _p({templates:e,phrases:t,running:n=!1,onQuickPhrase:r,onEdit:i,onCreate:a,onClose:o}){let s=J(),{language:c}=je();gp(o);let[l,u]=(0,C.useState)(``),d=()=>{let e=l.trim();if(e===``)return;let n=c===`en`?{text:e,textEn:e}:{text:e};bu({quickPhrases:[...t,n]}),u(``)},f=e=>{bu({quickPhrases:t.filter((t,n)=>n!==e)})},p=t.filter(e=>(pp(e,c)??``).trim()!==``),m=e=>{let{text:t}=fp(e,c);So(`${t}${t.endsWith(`
8
+ `)}function Xu(e){return e.length>120?`${e.slice(0,120)}…`:e}function Zu(e){let t=``;for(let[n,r]of e.entries())r.quoted!==!0&&(t=Du(t,Ju(r,n+1)));return t.replace(/\s+$/,``)}function Qu(e,t){let n=e.findIndex(e=>e.id===t);if(n<0)return 0;let r=e[n];return Fu(r)&&r.number>0?r.number:n+1}var $u=`pop-agent.web-marks.v1`,ed=40,td=[];function nd(e,t){return typeof e==`string`?e.slice(0,t):``}function rd(e){if(typeof e!=`object`||!e)return null;let t=e,n=nd(t.url,2e3).trim(),r=nd(t.selector,400).trim();if(n===``||r===``)return null;let i=typeof t.number==`number`&&Number.isFinite(t.number)&&t.number>0?t.number:0;return{number:Math.floor(i),url:n,selector:r,comment:nd(t.comment,2e3),createdAt:typeof t.createdAt==`number`&&Number.isFinite(t.createdAt)?t.createdAt:0}}function id(e){if(e===null||e===``)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=rd(e);t!==null&&n.push(t)}return ld(n)}function ad(e){if(e===null)return[...td];try{return id(e.getItem($u))}catch{return[...td]}}var od=`pop-agent:web-marks`;function sd(e){let t=t=>{t.key===$u&&e()};return window.addEventListener(od,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(od,e),window.removeEventListener(`storage`,t)}}function cd(e,t){if(e!==null){try{let n=ld(t);n.length===0?e.removeItem($u):e.setItem($u,JSON.stringify(n))}catch{}try{window.dispatchEvent(new Event(od))}catch{}}}function ld(e){let t=new Map;for(let n of e){let e=t.get(n.url);e===void 0?t.set(n.url,[n]):e.push(n)}return[...t.entries()].map(([e,t])=>({url:e,list:t.sort((e,t)=>e.number-t.number).slice(-200),last:t.reduce((e,t)=>Math.max(e,t.createdAt),0)})).sort((e,t)=>t.last-e.last).slice(0,ed).flatMap(e=>e.list)}function ud(e,t){return e.filter(e=>e.url===t).sort((e,t)=>e.number-t.number)}function dd(e,t){let n=0;for(let r of e)r.url===t&&r.number>n&&(n=r.number);return n+1}function fd(e,t,n=Date.now()){let r=e.find(e=>e.url===t.url&&e.selector===t.selector);if(r!==void 0)return e.map(e=>e===r?{...e,comment:t.comment,createdAt:n}:e);let i={number:dd(e,t.url),url:t.url,selector:t.selector,comment:t.comment,createdAt:n};return ld([...e,i])}function pd(e,t,n){return e.filter(e=>e.url!==t||e.selector!==n)}function md(e,t){return e.filter(e=>e.url!==t)}function hd({annotations:e,open:t,focusedId:n,onToggle:r,onRemove:i,onQuote:a,onJump:o,onComment:s,onClear:c}){let l=Y(),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(``),m=(0,C.useRef)(null),[h,g]=(0,C.useState)(!1);if((0,C.useEffect)(()=>{u!==null&&m.current?.focus()},[u]),(0,C.useEffect)(()=>{t?u!==null&&!e.some(e=>e.id===u)&&d(null):d(null)},[t,e,u]),(0,C.useEffect)(()=>{e.length===0&&g(!1)},[e.length]),e.length===0)return null;let _=()=>g(!0),v=()=>{g(!1),c()},y=e=>{d(e.id),p(e.comment)},b=()=>{u!==null&&s(u,f.trim()),d(null)};return(0,Q.jsxs)(`div`,{className:`annot-summary`,children:[(0,Q.jsxs)(`div`,{className:`annot-head`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`annot-chip`,onClick:r,"aria-expanded":t,title:l(`这条对话里标过的几处文字(点开看每一条)`,`Spots you marked in this chat (click to see each)`),children:[(0,Q.jsx)(`span`,{className:`annot-chip-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,children:(0,Q.jsx)(`path`,{d:`M2.5 3.5h11v7.2h-6L4.2 13v-2.3H2.5z`,strokeLinejoin:`round`})})}),l(`${e.length} 条注释`,`${e.length} note(s)`),(0,Q.jsx)(`span`,{className:`annot-chip-caret${t?` annot-chip-caret-open`:``}`,"aria-hidden":`true`})]}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-trash`,onClick:_,title:l(`批量清空这条对话里的全部注释`,`Discard all notes in this chat`),"aria-label":l(`批量清空`,`Discard all`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2.5 4h11M6.2 4V2.8h3.6V4M4 4l.7 9.2h6.6L12 4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),h?(0,Q.jsxs)(`div`,{className:`annot-confirm`,role:`alertdialog`,children:[(0,Q.jsx)(`div`,{className:`annot-confirm-title`,children:l(`丢弃所有待处理标注?`,`Discard all pending notes?`)}),(0,Q.jsx)(`div`,{className:`annot-confirm-sub`,children:l(`页面上的所有编辑都将被移除`,`All edits on the page will be removed`)}),(0,Q.jsxs)(`div`,{className:`annot-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`annot-confirm-cancel`,onClick:()=>g(!1),children:l(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-confirm-danger`,onClick:v,children:l(`放弃`,`Discard`)})]})]}):null]}),t?(0,Q.jsx)(`ul`,{className:`annot-list`,children:e.map(t=>{let r=Fu(t),s=r?t.spot.selector:t.anchor.exact.replace(/\s+/g,` `).trim(),c=u===t.id;return(0,Q.jsxs)(`li`,{id:`annot-row-${t.id}`,className:`annot-row${n===t.id?` annot-row-focus`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`annot-row-main`,disabled:r,onClick:()=>{r||o(t)},title:r?`${l(`网页上的一处`,`A spot on the page`)}: ${t.spot.url} ${t.spot.selector}`:l(`跳到正文里那一处`,`Jump to that spot in the chat`),children:[(0,Q.jsx)(`span`,{className:`annot-index`,children:Qu(e,t.id)}),r?(0,Q.jsx)(`span`,{className:`annot-web-mark`,children:`🌐`}):null,(0,Q.jsx)(`span`,{className:`annot-excerpt`,children:s})]}),c?(0,Q.jsxs)(`div`,{className:`annot-edit`,children:[(0,Q.jsx)(`input`,{ref:m,className:`annot-edit-input`,value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),b()),e.key===`Escape`&&(e.preventDefault(),d(null))},placeholder:l(`给这一处写句评论(可留空,回车保存)`,`Comment on this spot (optional, Enter to save)`),"aria-label":l(`这条标注的评论`,`Comment for this note`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action annot-action-ok`,onClick:b,title:l(`保存评论`,`Save comment`),children:`✓`})]}):t.comment===``?null:(0,Q.jsx)(`button`,{type:`button`,className:`annot-comment`,onClick:()=>y(t),title:l(`点一下改这句评论`,`Click to edit this comment`),children:t.comment}),(0,Q.jsxs)(`div`,{className:`annot-row-actions`,children:[c?null:(0,Q.jsx)(`button`,{type:`button`,className:`annot-action`,onClick:()=>y(t),title:l(t.comment===``?`给这一处写句评论`:`改这一处的评论`,t.comment===``?`Comment on this spot`:`Edit this comment`),children:t.comment===``?l(`+ 评论`,`+ Comment`):l(`改评论`,`Edit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action`,onClick:()=>a(t),title:l(`把这段(连同评论)变成引用接进输入框,再写自己的问题发出去`,`Quote this (with your comment) into the input, then send`),children:l(`放进输入框`,`Quote it`)}),(0,Q.jsx)(`button`,{type:`button`,className:`annot-action annot-action-remove`,onClick:()=>i(t.id),title:l(`删掉这条标注`,`Remove this annotation`),"aria-label":l(`删掉这条标注`,`Remove this annotation`),children:`✕`})]})]},t.id)})}):null]})}function gd(e){Bc(e),jo(e),Vl(e)}function _d({title:e,onConfirm:t,onCancel:n}){let r=Y(),i=(0,C.useRef)(null);(0,C.useEffect)(()=>{i.current?.focus()},[]),(0,C.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let a=e||r(`未命名会话`,`Untitled session`);return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`close-ephemeral-title`,"aria-describedby":`close-ephemeral-desc`,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,id:`close-ephemeral-title`,children:r(`关闭临时对话「${a}」?`,`Close the temporary chat “${a}”?`)}),(0,Q.jsxs)(`div`,{id:`close-ephemeral-desc`,children:[(0,Q.jsx)(`p`,{className:`modal-risk`,children:r(`它只活在内存里(没有会话文件),关闭后内容直接丢弃,无法恢复。`,`It lives in memory only (there is no session file). Closing it discards the content for good.`)}),(0,Q.jsx)(`p`,{children:r(`想留下去历史里找,请先点「保存为正式对话」。`,`To keep it in history, click “Save as a regular chat” first.`)})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:i,type:`button`,className:`btn`,onClick:n,children:r(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:t,children:r(`关闭对话`,`Close chat`)})]})]})})}function vd(e,t){let n=e[t];if(!n)return{from:t+1,to:t+1};let r=t+1;for(;r<e.length&&(e[r]?.depth??0)>n.depth;)r+=1;return{from:t+1,to:r}}function yd(e,t){if(!e[t])return e;let{to:n}=vd(e,t);return[...e.slice(0,t+1).map((e,n)=>n===t?{...e,expanded:!1}:e),...e.slice(n)]}function bd(e){let t=e.split(`/`).filter(e=>e!==``),n=[];for(let e=1;e<t.length;e+=1)n.push(t.slice(0,e).join(`/`));return n}function xd(e,t,n){return(e??t??``)===n?e:n===``?null:n}function Sd(e){for(let t of bd(e))if(t.split(`/`).some(e=>e.startsWith(`.`)))return t;return null}var Cd=/(^|__)(write|edit|multiedit|multi_edit|apply_patch|patch|create_file|write_file|edit_file|update_file|modify_file|str_replace\w*)$/i,wd=[`path`,`file_path`,`filePath`],Td=/"(?:path|file_path|filePath)"\s*:\s*"((?:[^"\\]|\\.)+)"/;function Ed(e){let t=e.split(`/`);return t[t.length-1]??e}function Dd(e){let t=Ed(e),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function Od(e,t){let n=e.trim();if(n===``)return{path:``,outside:!0};if(!n.startsWith(`/`))return{path:n.replace(/^\.\//,``),outside:!1};if(t===null||t===``)return{path:n,outside:!0};let r=t.endsWith(`/`)?t:`${t}/`;return n===t?{path:``,outside:!0}:n.startsWith(r)?{path:n.slice(r.length),outside:!1}:{path:n,outside:!0}}function kd(e,t,n=0){if(n>3||typeof e!=`object`||!e)return;if(Array.isArray(e)){for(let r of e)kd(r,t,n+1);return}let r=e;for(let e of wd){let n=r[e];typeof n==`string`&&n.trim()!==``&&t.push(n)}let i=r.files;Array.isArray(i)&&kd(i,t,n+1)}function Ad(e){let t=(e.argsFull??e.argsSummary??``).trim();if(t===``)return[];let n=[];try{return kd(JSON.parse(t),n),n}catch{let e=Td.exec(t)?.[1];if(e!==void 0)try{n.push(JSON.parse(`"${e}"`))}catch{n.push(e)}return n}}function jd(e,t){let n=[],r=new Set;for(let i of e.blocks)if(i.kind===`tool`&&i.status===`ok`&&Cd.test(i.name))for(let e of Ad(i)){let{path:i,outside:a}=Od(e,t);i===``||r.has(i)||(r.add(i),n.push({path:i,name:Ed(i),ext:Dd(i),outside:a}))}return n}function Md(e){let t=[];for(let n of e)for(let e of n.blocks)if(e.kind===`tool`)for(let n of Ad(e))t.push({path:n,name:Ed(n)});return t}function Nd(e,t){let n=e.trim().replace(/\\/g,`/`).replace(/^\.\//,``);if(n===``||n.startsWith(`/`))return null;let r=t.filter(e=>e.path.startsWith(`/`)),i=[...r].reverse().find(e=>e.path===n||e.path.endsWith(`/${n}`));return i?i.path:[...r].reverse().find(e=>e.name===n)?.path??null}function Pd(){return xo().snapshot?.settings.sessionPrefs??{pinned:[],archived:[],order:[]}}function Fd(e){bu({sessionPrefs:{...Pd(),...e}})}function Id(e){let t=Pd();Fd({pinned:t.pinned.includes(e)?t.pinned.filter(t=>t!==e):[e,...t.pinned]})}function Ld(e){let t=Pd();t.archived.includes(e)&&Fd({archived:t.archived.filter(t=>t!==e)})}function Rd(e,t,n,r){let i=Pd();i.archived.includes(e)||(Fd({archived:[...i.archived,e]}),Z({text:n(`已归档「${t||`未命名会话`}」`,`Archived "${t||`Untitled session`}"`),actions:[{label:n(`撤销`,`Undo`),onClick:()=>Ld(e)},...r?[{label:n(`查看`,`View`),onClick:r}]:[]]}))}async function zd(e){Bc(e);try{let t=await fetch(`/api/sessions/delete`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,purge:!0})});if(!t.ok){let e=await t.json().catch(()=>null);return t.status===404||e?.error?.code===`session.not_found`?{ok:!0}:{ok:!1,message:e?.error?.message??`HTTP ${t.status}`}}return{ok:!0,mode:(await t.json().catch(()=>null))?.mode}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}var Bd=`服务端还是旧版本:只改了名、没真删(重启服务后重试,或先把控制台里的服务端重构一下)`,Vd=`The server is an old build: the file was only renamed, not deleted (restart the server and try again)`;function Hd(e,t){(async()=>{let n=await zd(e);n.ok?(jo(e),n.mode===`file`&&Z({text:J(`「${t}」${Bd}`,`“${t}” ${Vd}`),ttl:12e3}),kl()):Z({text:J(`彻底删除「${t}」失败:${n.message}`,`Could not permanently delete “${t}”: ${n.message}`),ttl:12e3})})()}function Ud(e,t=J(`选中的会话`,`the selected sessions`)){e.length!==0&&(async()=>{let n=0,r=!1,i=[];for(let t of e){let e=await zd(t);e.ok?(n+=1,jo(t),e.mode===`file`&&(r=!0)):i.push(e.message)}kl(),r&&Z({text:J(`${n} 条${Bd}`,`${n} session(s): ${Vd}`),ttl:12e3}),i.length>0&&Z({text:J(`彻底删除${t}:成功 ${n} 条,失败 ${i.length} 条(${i[0]})`,`Permanently delete ${t}: ${n} succeeded, ${i.length} failed (${i[0]})`),ttl:12e3})})()}var Wd=400,Gd=14,Kd=6;function qd({anchor:e,point:t,pointerTail:n=!1,className:r,style:i,align:a,closeOnLeave:o,onClose:s,children:c}){let l=(0,C.useRef)(null),u=(0,C.useRef)(null),[d,f]=(0,C.useState)({left:0,top:0,width:0,height:0,visible:!1,arrow:null,below:!1});return(0,C.useLayoutEffect)(()=>{let r=l.current;if(!r||!t&&!e)return;let i=r.getBoundingClientRect(),o=e?e.getBoundingClientRect():null,s=!0,c=8,u=8;t?n?(c=t.x-Gd,u=t.y+Kd):(c=t.x,u=t.y):o&&a===`center`?(c=o.left+o.width/2-i.width/2,u=o.top-i.height-4,s=!1):o&&(c=o.right-i.width,u=o.bottom+4),c+i.width>window.innerWidth-8&&(c=window.innerWidth-i.width-8),c<8&&(c=8),!s&&o&&u<8?(u=o.bottom+4,s=!0):s&&u+i.height>window.innerHeight-8&&(u=t?t.y-i.height-(n?Kd:0):o.top-i.height-4,s=!1),u<8&&(u=8);let d=null;if(o){let e=o.left+o.width/2-c;d=Math.min(Math.max(14,e),Math.max(14,i.width-14)),s=u>=o.top+o.height/2}else if(t&&n){let e=Gd;d=Math.min(Math.max(e,t.x-c),Math.max(e,i.width-e)),s=u>=t.y}f({left:c,top:u,width:i.width,height:i.height,visible:!0,arrow:d,below:s})},[e,t,a,n]),(0,C.useEffect)(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]),(0,C.useEffect)(()=>{let t=performance.now(),n=t=>{let n=t.target;l.current?.contains(n)||e?.contains(n)||s()},r=e=>{e.key===`Escape`&&s()},i=e=>{if(performance.now()-t<200)return;let n=e.target;n instanceof Node&&l.current?.contains(n)||s()};return document.addEventListener(`mousedown`,n),document.addEventListener(`keydown`,r),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{document.removeEventListener(`mousedown`,n),document.removeEventListener(`keydown`,r),window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[e,s]),(0,Ko.createPortal)((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{ref:l,className:`${r??`proj-menu`} proj-menu-floating`,role:`menu`,style:{left:d.left,top:d.top,visibility:d.visible?`visible`:`hidden`,...i},onContextMenu:e=>e.preventDefault(),onMouseLeave:o?()=>{window.matchMedia(`(hover: hover)`).matches&&(u.current!==null&&clearTimeout(u.current),u.current=setTimeout(()=>{u.current=null,s()},Wd))}:void 0,onMouseEnter:o?()=>{u.current!==null&&(clearTimeout(u.current),u.current=null)}:void 0,children:c}),d.arrow===null?null:(0,Q.jsx)(`span`,{className:`proj-menu-arrow${d.below?` proj-menu-arrow-top`:``}`,style:{left:d.left+d.arrow-5,top:d.below?d.top-5:d.top+d.height-5},"aria-hidden":`true`})]}),document.body)}var Jd=5e3;function Yd(e=Jd){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(!1);return(0,C.useEffect)(()=>{if(!t)return;let i=setTimeout(()=>{r.current=!1,n(!1)},e);return()=>clearTimeout(i)},[t,e]),{armed:t,run:(0,C.useCallback)(e=>{r.current?(r.current=!1,n(!1),e()):(r.current=!0,n(!0))},[])}}function Xd({point:e,anchor:t,title:n,pinned:r,splitSide:i,fork:a,onClose:o,onRename:s,onAiRename:c,aiRenaming:l=!1,onPin:u,onOpenInNewTab:d,onArchive:f,onDelete:p}){let m=Y(),h=e=>()=>{o(),e()},g=Yd();return(0,Q.jsxs)(qd,{point:e,anchor:t,className:`pi-menu`,closeOnLeave:!0,onClose:o,children:[i?(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`和右边那块交换位置`,`Swap places with the right part`),onClick:h(i.onMove),children:i.chatOnRight?`← ${m(`移至左侧`,`Move to the left`)}`:`→ ${m(`移至右侧面板`,`Move to the right panel`)}`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:h(u),children:[`📌 `,r?m(`取消置顶会话`,`Unpin session`):m(`置顶会话`,`Pin session`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:h(s),children:[`✏️ `,m(`重命名`,`Rename`)]}),c?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:l,title:m(`按这条会话的内容让 AI 起一个简洁的名字(会直接改会话名)`,`Let AI name this session from its content (renames it directly)`),onClick:h(c),children:[`💬 `,l?m(`AI 正在起名…`,`AI is naming…`):m(`AI 重命名`,`AI rename`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`在新标签页打开这条会话(?session=…)`,`Open this session in a new tab (?session=…)`),onClick:h(d),children:[`↗ `,m(`在新标签页打开`,`Open in new tab`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:a===void 0||!a.enabled,title:a===void 0?m(`打开这条会话后,从它的标题上分叉`,`Open this session, then fork from its title`):a.enabled?m(`从这条会话的最后一条消息派生一条新会话(原会话不动)`,`Branch a new session from its last message`):a.reason??m(`现在不能分叉`,`Cannot fork right now`),onClick:a?.enabled?h(a.onFork):void 0,children:[`🌿 `,m(`分叉`,`Fork`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:m(`从列表里隐藏,可在「已归档」里找回`,`Hide it from the list; find it again under Archived`),onClick:h(f),children:[`🗄 `,m(`归档`,`Archive`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${g.armed?` proj-menu-item-armed`:``}`,title:g.armed?m(`再点一次就真删「${n}」的会话文件:不可恢复`,`Click again to permanently delete the session file for "${n}"`):m(`把「${n}」连同磁盘上的会话文件一起删掉(不可恢复);第一下只是确认`,`Delete "${n}" together with its session file on disk (cannot be undone); the first click only arms it`),onClick:()=>g.run(()=>{o(),p()}),"aria-label":g.armed?m(`再点一次确认彻底删除`,`Click again to delete permanently`):m(`彻底删除`,`Purge`),children:g.armed?m(`🧨 再点一次彻底删除`,`🧨 Click again to purge`):`🧨 ${m(`彻底删除`,`Purge`)}`})]})}var Zd=`pop-agent:open-panel`;function Qd(e){try{window.dispatchEvent(new CustomEvent(Zd,{detail:e}))}catch{}}function $d(e){let t=t=>e(t.detail);return window.addEventListener(Zd,t),()=>window.removeEventListener(Zd,t)}var ef=`pop-agent.speech.pet.enabled`,tf=`pop-agent.speech.pet.animal`,nf=[{emoji:`🐱`,zh:`猫`,en:`Cat`},{emoji:`🦊`,zh:`狐狸`,en:`Fox`},{emoji:`🐰`,zh:`兔子`,en:`Rabbit`},{emoji:`🐧`,zh:`企鹅`,en:`Penguin`}],rf=nf[0].emoji;function af(e){Qr(ef,e)}var of=`pop-agent:speech-pet-animal`;function sf(){let e=Yr(tf);return nf.some(t=>t.emoji===e)?e:rf}function cf(e){Xr(tf,e);try{window.dispatchEvent(new CustomEvent(of,{detail:e}))}catch{}}function lf(){let[e,t]=(0,C.useState)(()=>sf());return(0,C.useEffect)(()=>{let e=e=>t(e.detail),n=e=>{(e.key===null||e.key===`pop-agent.speech.pet.animal`)&&t(sf())};return window.addEventListener(of,e),window.addEventListener(`storage`,n),()=>{window.removeEventListener(of,e),window.removeEventListener(`storage`,n)}},[]),[e,cf]}function uf(e,t){let[n,r]=(0,C.useState)(()=>Zr(e,t));return(0,C.useEffect)(()=>$r(e,r),[e]),[n,t=>Qr(e,t)]}var df=`pop-agent.speech.pet.pos.v1`,ff=8,pf=4,mf=28,hf=[`left`,`right`,`top`,`bottom`];function gf(){let e=Yr(df);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.x!=`number`||typeof t.y!=`number`||!Number.isFinite(t.x)||!Number.isFinite(t.y))return null;let n=hf.includes(t.docked)?t.docked:null;return{x:t.x,y:t.y,docked:n}}catch{return null}}function _f(e,t,n){return{x:Math.min(Math.max(ff,e.x),Math.max(ff,n.width-t.width-ff)),y:Math.min(Math.max(ff,e.y),Math.max(ff,n.height-t.height-ff))}}var vf=()=>({width:window.innerWidth,height:window.innerHeight});function yf(e,t,n){let r=n.width-t.width,i=n.height-t.height,a={left:e.x,right:r-e.x,top:e.y,bottom:i-e.y},o=null,s=mf;for(let e of hf)a[e]<s&&(s=a[e],o=e);return o===null?{..._f(e,t,n),docked:null}:{x:o===`left`?0:o===`right`?r:Math.min(Math.max(ff,e.x),Math.max(ff,r)),y:o===`top`?0:o===`bottom`?i:Math.min(Math.max(ff,e.y),Math.max(ff,i)),docked:o}}function bf(){let e=Y(),t=Qt(),n=pn(),[r]=uf(ef,!0),[i]=lf(),a=(0,C.useRef)(null),[o,s]=(0,C.useState)(gf),[c,l]=(0,C.useState)(!1),[u,d]=(0,C.useState)(null),f=(0,C.useRef)(!1),p=(0,C.useRef)(null),m=(0,C.useRef)(!1),h=(0,C.useRef)(null),g=()=>{let e=a.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}};(0,C.useEffect)(()=>{let e=()=>s(e=>{if(!e)return e;let t=g(),n=vf(),r=_f(e,t,n);return{x:e.docked===`left`?0:e.docked===`right`?n.width-t.width:r.x,y:e.docked===`top`?0:e.docked===`bottom`?n.height-t.height:r.y,docked:e.docked}});return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let _=e=>{let t=a.current?.getBoundingClientRect();if(t){if(f.current=!1,m.current=!1,e.pointerType!==`mouse`){let{clientX:t,clientY:n}=e;p.current=window.setTimeout(()=>{p.current=null,m.current=!0,d({x:t,y:n})},600)}h.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,offsetX:e.clientX-t.left,offsetY:e.clientY-t.top}}},v=e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if(!f.current){if(!(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>pf))return;f.current=!0,p.current!==null&&(clearTimeout(p.current),p.current=null),e.currentTarget.setPointerCapture(e.pointerId),l(!0),s(e=>e?.docked?{...e,docked:null}:e)}let n=_f({x:e.clientX-t.offsetX,y:e.clientY-t.offsetY},g(),vf());s({...n,docked:null})},y=e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId||(h.current=null,l(!1),p.current!==null&&(clearTimeout(p.current),p.current=null),!f.current))return;let n=yf({x:e.clientX-t.offsetX,y:e.clientY-t.offsetY},g(),vf());s(n),Xr(df,JSON.stringify(n))},b=()=>{f.current?f.current=!1:m.current?m.current=!1:t&&hn(!n)},x=()=>{s(null),Xr(df,``)},S=t?n?`paused`:`reading`:`idle`;return r?(0,Q.jsxs)(`div`,{ref:a,className:`speech-pet is-${S}${c?` is-dragging`:``}${o?.docked?` is-docked-${o.docked}`:``}`,style:o?{left:`${o.x}px`,top:`${o.y}px`,right:`auto`,bottom:`auto`}:void 0,onPointerDown:_,onPointerMove:v,onPointerUp:y,onPointerCancel:y,onDoubleClick:x,onContextMenu:e=>{e.preventDefault(),d({x:e.clientX,y:e.clientY})},title:e(`点:暂停 / 继续 · 右键(触屏长按):停止 · 拖动:挪位置(贴边吸成半圆)· 双击:回默认位`,`Click: pause / resume · right-click (long-press): stop · drag to move (snaps to edges) · double-click: reset`),children:[(0,Q.jsxs)(`div`,{className:`speech-pet-stage`,children:[S===`reading`?(0,Q.jsxs)(`span`,{className:`speech-pet-ping`,"aria-hidden":`true`,children:[(0,Q.jsx)(`i`,{}),(0,Q.jsx)(`i`,{}),(0,Q.jsx)(`i`,{})]}):null,S===`paused`?(0,Q.jsx)(`span`,{className:`speech-pet-paused`,"aria-hidden":`true`,children:`⏸`}):null,(0,Q.jsx)(`button`,{type:`button`,className:`speech-pet-face`,onClick:b,"aria-pressed":n,"aria-label":n?e(`继续朗读`,`Resume reading`):e(`暂停朗读`,`Pause reading`),title:n?e(`点一下接着念(从停下的地方继续)`,`Click to resume from where it paused`):e(`点一下暂停(停在这一句,后面的不会跳过)`,`Click to pause here — the rest keeps its place`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:i})})]}),u?(0,Q.jsxs)(qd,{point:u,className:`pi-menu`,closeOnLeave:!0,onClose:()=>d(null),children:[(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),hn(!n)},children:n?`▶ ${e(`继续朗读`,`Resume reading`)}`:`⏸ ${e(`暂停朗读`,`Pause reading`)}`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,disabled:!t,onClick:()=>{d(null),nn()},children:[`⏹ `,e(`停止朗读`,`Stop reading`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),Qd(`voice`)},children:[`🔊 `,e(`设置语音功能`,`Voice settings`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{d(null),af(!1)},children:[`✕ `,e(`关闭宠物`,`Hide the pet`)]})]}):null]}):null}var xf=400,Sf=/iPhone|iPod|Android.*Mobile|Windows Phone|IEMobile|BlackBerry|Opera Mini|HarmonyOS|\bMobile\b/i;function Cf(e){return Sf.test(e)}function wf(e){return e.width<=xf||Cf(e.userAgent)}function Tf(){return typeof window>`u`?!1:wf({width:window.innerWidth,userAgent:navigator.userAgent})}function Ef(){document.documentElement.classList.toggle(`is-mobile-shell`,Tf())}function Df(){Ef();let e=()=>Ef();return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}}function Of({approval:e}){let t=Y();return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":t(`危险操作确认`,`Confirm a risky operation`),children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,children:t(`需要你确认`)}),(0,Q.jsx)(`p`,{className:`modal-risk`,children:e.riskNote}),(0,Q.jsxs)(`dl`,{className:`modal-facts`,children:[(0,Q.jsx)(`dt`,{children:t(`工具`)}),(0,Q.jsx)(`dd`,{children:e.toolName}),(0,Q.jsx)(`dt`,{children:t(`参数`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.argsSummary}),(0,Q.jsx)(`dt`,{children:t(`这类操作`)}),(0,Q.jsx)(`dd`,{className:`mono`,children:e.scopeHint})]}),(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xu(e.requestId,`deny`),children:t(`拒绝`,`Deny`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>xu(e.requestId,`once`),children:t(`允许一次`,`Allow once`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>xu(e.requestId,`always`),children:t(`总是允许这类`,`Always allow this kind`)})]})]})})}var kf=4e3;function Af({notices:e,activeConversationId:t=null}){let n=Y(),[r,i]=(0,C.useState)(()=>new Set),[a,o]=(0,C.useState)(()=>Date.now());(0,C.useEffect)(()=>{let e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);let s=e.filter(e=>(e.conversationId===void 0||e.conversationId===t)&&!r.has(e.id)&&a-e.ts<kf).slice(-3);if(s.length===0)return null;let c=e=>i(t=>{let n=new Set(t);return n.add(e),n});return(0,Q.jsx)(`div`,{className:`notices`,children:s.map(e=>(0,Q.jsxs)(`div`,{className:`notice notice-${e.level}`,children:[(0,Q.jsx)(`span`,{className:`notice-text`,children:e.text}),(0,Q.jsx)(`button`,{type:`button`,className:`notice-close`,onClick:()=>c(e.id),title:n(`关闭这条提示`,`Dismiss this notice`),children:`×`})]},e.id))})}var jf=5,Mf=10485760;function Nf(e,t){let n=[],r=[],i=t;for(let t of e)i>=jf?r.push(J(`${t.name}:一条消息最多 ${jf} 个附件`,`${t.name}: at most ${jf} attachments per message`)):t.size===0?r.push(J(`${t.name}:空文件`,`${t.name}: empty file`)):t.size>10485760?r.push(J(`${t.name}:超过 ${Math.round(Mf/1024/1024)}MB`,`${t.name}: over ${Math.round(Mf/1024/1024)}MB`)):(n.push(t),i+=1);return{accepted:n,rejected:r}}function Pf(e){let t=e.filter(e=>e.kind===`image`).map(e=>`![${e.name}](/api/uploads/${e.id})`);return t.length>0?`\n\n${t.join(`
9
+ `)}`:``}async function Ff(e){try{let t=await fetch(`/api/uploads`,{method:`POST`,headers:{"content-type":e.type||`application/octet-stream`,"x-file-name":encodeURIComponent(e.name)},body:await e.arrayBuffer()});return t.ok?{ok:!0,attachment:await t.json()}:{ok:!1,error:(await t.json().catch(()=>null))?.error?.message??J(`上传失败(HTTP ${t.status})`,`Upload failed (HTTP ${t.status})`)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}var If=8,Lf=14;function Rf(e){let t=e.gap??8,n=e.trigger.left+e.trigger.width/2-e.popover.width/2,r=Math.max(If,e.viewport.width-e.popover.width-If),i=Math.min(Math.max(If,n),r),a=e.trigger.left+e.trigger.width/2,o=Math.max(Lf,e.popover.width-Lf),s=Math.min(Math.max(Lf,a-i),o);return{left:i,bottom:e.viewport.height-e.trigger.top+t,arrow:s}}function zf(e){let t=e.gap??6,n=e.trigger.left+e.trigger.width/2-e.popover.width/2,r=Math.max(If,e.viewport.width-e.popover.width-If),i=Math.min(Math.max(If,n),r),a=e.trigger.left+e.trigger.width/2,o=Math.max(Lf,e.popover.width-Lf);return{left:i,top:e.trigger.top+e.trigger.height+t,arrow:Math.min(Math.max(Lf,a-i),o)}}function Bf(e,t,n){if(e.length===0)return!0;let r=`${t}/${n}`;return e.some(e=>e===`${t}/**`||e===r)}function Vf(e){let t=e.indexOf(`/`);return t>0?e.slice(0,t):``}function Hf(e,t){let n=Vf(t);return n===``||Bf(e,n,t.slice(n.length+1))}function Uf(e){let t=e.id.indexOf(`/`);return t>0?e.id.slice(0,t):`other`}function Wf(e,t=``){let n=t.trim().toLowerCase(),r=[],i=new Map;for(let t of e){if(n!==``&&!`${t.label} ${t.id}`.toLowerCase().includes(n))continue;let e=Uf(t),a=i.get(e);a||(a={provider:e,models:[]},i.set(e,a),r.push(a)),a.models.push(t)}return r}function Gf(e,t){return t.length===0?e:e.filter(e=>Hf(t,e.id))}function Kf({models:e,enabledAllowlist:t=[],current:n,disabled:r,defaultModel:i,onSetDefault:a,onSwitch:o}){let s=Y(),[c,l]=(0,C.useState)(!1),[u,d]=(0,C.useState)(``),f=(0,C.useRef)(null),[p,m]=(0,C.useState)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(null),_=Tf();(0,C.useLayoutEffect)(()=>{if(!c||_){m(null);return}let e=()=>{let e=h.current?.getBoundingClientRect(),t=g.current?.getBoundingClientRect();e&&t&&m(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[c,_,u]),(0,C.useEffect)(()=>{if(!c)return;let e=e=>{f.current?.contains(e.target)||l(!1)},t=e=>{e.key===`Escape`&&l(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let v=Gf(e,t),y=Wf(v,u),b=e.find(e=>e.id===n)?.label??n??J(`模型未就绪`,`model not ready`),x=v.length===0;return(0,Q.jsxs)(`div`,{className:`model-picker`,ref:f,children:[(0,Q.jsxs)(`button`,{ref:h,type:`button`,className:`tool-chip model-trigger`,onClick:()=>{r||(d(``),l(e=>!e))},disabled:r,title:n??s(`选择模型`,`Choose a model`),children:[(0,Q.jsx)(`span`,{className:`model-trigger-label`,children:b}),(0,Q.jsx)(`span`,{className:`model-caret`,"aria-hidden":`true`,children:`▾`})]}),c?(0,Q.jsx)(`div`,{className:`model-sheet-backdrop`,onClick:()=>l(!1),"aria-hidden":`true`}):null,c?(0,Q.jsxs)(`div`,{ref:g,className:`model-menu`,role:`listbox`,"aria-label":s(`选择模型`),style:_?void 0:p?{left:p.left,bottom:p.bottom}:{visibility:`hidden`},children:[!_&&p?(0,Q.jsx)(`span`,{className:`model-menu-arrow`,style:{left:p.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`model-sheet-close`,onClick:()=>l(!1),title:s(`关闭`),children:[`✕ `,s(`关闭`,`Close`)]}),(0,Q.jsxs)(`div`,{className:`model-list`,children:[y.length===0?(0,Q.jsx)(`div`,{className:`model-empty`,children:x?s(`没有启用的模型:去「模型」面板里勾选要用的`,`No enabled models — pick some in the Models panel`):s(`没有匹配的模型`)}):null,y.map(e=>(0,Q.jsxs)(`div`,{className:`model-group`,children:[(0,Q.jsx)(`div`,{className:`model-group-title`,children:e.provider.toUpperCase()}),e.models.map(e=>{let t=e.id===i;return(0,Q.jsxs)(`div`,{className:`model-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`model-item${e.id===n?` model-item-on`:``}`,onClick:()=>{(o??lu)(e.id),l(!1)},title:e.id,children:[(0,Q.jsx)(`span`,{className:`model-check`,"aria-hidden":`true`,children:e.id===n?`✓`:``}),(0,Q.jsx)(`span`,{className:`model-label`,children:e.label})]}),a?(0,Q.jsx)(`button`,{type:`button`,className:`model-pin${t?` model-pin-on`:``}`,onClick:()=>a(t?null:e.id),title:t?s(`取消本项目的默认模型`,`Clear this project's default model`):s(`设为本项目的默认模型(新会话用它起步)`,`Set as this project's default (new conversations start with it)`),"aria-pressed":t,children:t?`📌`:`📍`}):null]},e.id)})]},e.provider))]})]}):null]})}function qf(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`currentColor`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`3.6`,cy:`8`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`2.1`}),(0,Q.jsx)(`circle`,{cx:`12.6`,cy:`8`,r:`2.7`})]})}var Jf={off:`关`,minimal:`最低`,low:`低`,medium:`中`,high:`高`,xhigh:`很高`,max:`最高`},Yf={off:`Off`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`Very high`,max:`Max`};function Xf({level:e,levels:t}){let n=Y(),[r,i]=(0,C.useState)(!1),[a,o]=(0,C.useState)(null),s=(0,C.useRef)(null),c=(0,C.useRef)(null),l=(0,C.useRef)(null),u=Tf(),d=e??t[0]??``,f=e=>n(Jf[e]??e,Yf[e]??e);return(0,C.useLayoutEffect)(()=>{if(!r||u){o(null);return}let e=()=>{let e=c.current?.getBoundingClientRect(),t=l.current?.getBoundingClientRect();e&&t&&o(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[r,u]),(0,C.useEffect)(()=>{if(!r)return;let e=e=>{s.current?.contains(e.target)||i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[r]),t.length===0?null:(0,Q.jsxs)(`div`,{className:`thinking-picker-box`,ref:s,children:[(0,Q.jsxs)(`button`,{ref:c,type:`button`,className:`tool-chip thinking-picker`,title:n(`思考强度(越高的档位越慢,推理也更细)`,`Thinking level (higher is slower but reasons more finely)`),"aria-haspopup":`listbox`,"aria-expanded":r,onClick:()=>i(e=>!e),children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(qf,{})}),(0,Q.jsx)(`span`,{className:`thinking-value`,children:f(d)}),(0,Q.jsx)(`span`,{className:`thinking-caret`,"aria-hidden":`true`,children:`▾`})]}),r?(0,Q.jsx)(`div`,{className:`model-sheet-backdrop`,onClick:()=>i(!1),"aria-hidden":`true`}):null,r?(0,Q.jsxs)(`div`,{ref:l,className:`model-menu thinking-menu`,role:`listbox`,"aria-label":n(`思考强度`,`Thinking level`),style:u?void 0:a?{left:a.left,bottom:a.bottom}:{visibility:`hidden`},children:[!u&&a?(0,Q.jsx)(`span`,{className:`model-menu-arrow`,style:{left:a.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`model-sheet-close`,onClick:()=>i(!1),title:n(`关闭`),children:[`✕ `,n(`关闭`,`Close`)]}),(0,Q.jsx)(`div`,{className:`model-list`,children:t.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`model-item${e===d?` model-item-on`:``}`,onClick:()=>{$l(e),i(!1)},children:[(0,Q.jsx)(`span`,{className:`model-check`,"aria-hidden":`true`,children:e===d?`✓`:``}),(0,Q.jsx)(`span`,{className:`model-label`,children:f(e)})]},e))})]}):null]})}function Zf(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.4`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.9`,fill:`currentColor`})]})}function Qf({surface:e,part:t=`both`}){let n=Y(),r=Ro(e=>e.snapshot),i=e?e.snapshot:r,a=i?.conversations.find(e=>e.id===i.active.conversationId)?.workspace??i?.files?.root??``,o=i?.settings.defaultModels??{};return(0,Q.jsxs)(Q.Fragment,{children:[t!==`thinking`&&i&&i.models.length>0&&i.engineCapabilities.modelSwitch?(0,Q.jsx)(Kf,{models:i.models,enabledAllowlist:i.enabledModels??[],current:i.model,defaultModel:o[a]??null,onSetDefault:t=>{if(!a)return;if(e){e.setProjectDefaultModel?.(a,t);return}let n={...o};t?n[a]=t:delete n[a],bu({defaultModels:n})},onSwitch:e?e.switchModel:e=>lu(e,i?.active.conversationId??null)}):t===`thinking`?null:(0,Q.jsxs)(`span`,{className:`tool-chip tool-static mono`,title:i?.model?n(`这个会话使用的模型`,`The model this conversation uses`):n(`还没打开会话,模型列表要等会话就绪`,`No conversation yet — the model list appears once one is open`),children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(Zf,{})}),(0,Q.jsx)(`span`,{children:i?.model??n(`模型未就绪`,`Model not ready`)})]}),t===`model`?null:(0,Q.jsx)(Xf,{level:i?.thinkingLevel??null,levels:i?.thinkingLevels??[]})]})}var $f={isRepo:!1,branch:null,branches:[]};function ep(e){let[t,n]=(0,C.useState)($f),[r,i]=(0,C.useState)(0);(0,C.useEffect)(()=>{if(n($f),!e)return;let t=!1;return(async()=>{try{let r=await(await fetch(`/api/files/git?root=${encodeURIComponent(e)}`)).json();if(t)return;n({isRepo:r.isRepo===!0,branch:r.branch??null,branches:Array.isArray(r.branches)?r.branches:[],error:typeof r.error==`string`?r.error:void 0})}catch{}})(),()=>{t=!0}},[e,r]);let a=(0,C.useCallback)(()=>i(e=>e+1),[]),o=(0,C.useCallback)(async(t,r={})=>{if(!e)return{ok:!1,message:J(`还没有打开项目`,`No project is open`)};try{let i=await fetch(`/api/files/git/checkout`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({root:e,branch:t,force:r.force===!0})}),a=await i.json();return!i.ok||a.error?a.error?.code===`files.dirty_worktree`?{ok:!1,message:a.error.message??J(`工作区有未提交改动`,`The working tree has uncommitted changes`),dirty:{files:Array.isArray(a.error.files)?a.error.files.filter(e=>typeof e==`string`):[],total:typeof a.error.total==`number`?a.error.total:0}}:{ok:!1,message:a.error?.message??J(`切换到 ${t} 失败`,`Could not switch to ${t}`)}:(n({isRepo:a.isRepo===!0,branch:a.branch??t,branches:Array.isArray(a.branches)?a.branches:[],error:void 0}),{ok:!0})}catch{return{ok:!1,message:J(`切分支的请求没发出去(服务端没响应)`,`The switch request did not go through (no response from the server)`)}}},[e]);return{...t,refresh:a,checkout:o}}function tp({className:e}){return(0,Q.jsxs)(`svg`,{className:e,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`4.6`,cy:`3.6`,r:`1.7`}),(0,Q.jsx)(`circle`,{cx:`4.6`,cy:`12.4`,r:`1.7`}),(0,Q.jsx)(`circle`,{cx:`11.4`,cy:`6.4`,r:`1.7`}),(0,Q.jsx)(`path`,{d:`M4.6 5.3v5.4`}),(0,Q.jsx)(`path`,{d:`M11.4 8.1c0 2.2-3.1 1.9-5.1 2.9`})]})}var np={fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`},rp=`m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,ip=`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`;function ap({open:e,className:t}){return(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:t,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:e?rp:ip,...np})})}function op({className:e}){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:e,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M12 10v6`,...np}),(0,Q.jsx)(`path`,{d:`M9 13h6`,...np}),(0,Q.jsx)(`path`,{d:ip,...np})]})}function sp({anchor:e,git:t,align:n,onClose:r}){let i=Y(),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),d=async(e,n=!1)=>{if(a||e===t.branch)return;o(e),c(null);let i=await t.checkout(e,{force:n});o(null),i.ok?r():i.dirty?u({name:e,files:i.dirty.files,total:i.dirty.total}):c(i.message)};return(0,Q.jsxs)(qd,{anchor:e,className:`proj-menu files-branch-menu`,align:n,onClose:r,children:[(0,Q.jsxs)(`div`,{className:`files-branch-menu-head`,children:[(0,Q.jsx)(`span`,{className:`files-branch-menu-title`,children:l?i(`确认切换分支`,`Confirm branch switch`):i(`切换分支`)}),(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-refresh`,title:i(`刷新分支列表(别的终端里刚建的分支)`),onClick:()=>{c(null),u(null),t.refresh()},children:`⟳`})]}),l?(0,Q.jsxs)(`div`,{className:`files-branch-confirm`,children:[(0,Q.jsxs)(`div`,{className:`files-branch-confirm-text`,children:[`⚠️ `,i(`工作区有`,`The working tree has`),` `,(0,Q.jsx)(`b`,{children:l.total}),` `,i(`个未提交改动。切到`,`uncommitted change(s). Switching to`),` `,(0,Q.jsx)(`b`,{children:l.name}),` `,i(`会把它们带过去 (git 不会丢弃,放不下的会拒绝切换)。`,`carries them over (git never discards them; it refuses the switch if they do not fit).`)]}),l.files.length>0?(0,Q.jsxs)(`ul`,{className:`files-branch-confirm-files`,children:[l.files.slice(0,5).map(e=>(0,Q.jsx)(`li`,{title:e,children:e},e)),l.total>5?(0,Q.jsxs)(`li`,{className:`files-branch-confirm-more`,children:[`… `,i(`还有`,`and`),` `,l.total-5,` `,i(`个`,`more`)]}):null]}):null,(0,Q.jsxs)(`div`,{className:`files-branch-confirm-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-btn files-branch-btn-primary`,disabled:a!==null,onClick:()=>void d(l.name,!0),children:a===l.name?i(`切换中…`):i(`仍然切换`,`Switch anyway`)}),(0,Q.jsx)(`button`,{type:`button`,className:`files-branch-btn`,disabled:a!==null,onClick:()=>u(null),children:i(`取消`)})]})]}):t.branches.length===0?(0,Q.jsx)(`div`,{className:`files-branch-hint`,children:t.error??i(`这个仓库还没有别的分支`,`This repo has no other branches yet`)}):(0,Q.jsx)(`div`,{className:`files-branch-list`,children:t.branches.map(e=>{let n=e===t.branch;return(0,Q.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":n,className:`proj-menu-item files-branch-item${n?` files-branch-item-current`:``}`,title:n?i(`${e}(当前分支)`,`${e} (current branch)`):i(`切换到 ${e}`,`Switch to ${e}`),disabled:a!==null,onClick:()=>void d(e),children:[(0,Q.jsx)(`span`,{className:`files-branch-tick`,children:n?`✓`:``}),(0,Q.jsx)(`span`,{className:`files-branch-item-name`,children:e}),a===e?(0,Q.jsx)(`span`,{className:`files-branch-pending`,children:i(`切换中…`)}):null]},e)})}),s?(0,Q.jsx)(`div`,{className:`files-branch-error`,children:s}):null]})}function cp({projectRoot:e}){let t=Y(),n=ep(e),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(!1),s=D(e)||e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`new-scope-chip new-scope-chip-static`,title:e,children:[(0,Q.jsx)(`span`,{className:`new-scope-icon new-scope-icon-folder`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:s})]}),n.isRepo&&n.branch?(0,Q.jsxs)(`button`,{type:`button`,ref:i,className:`new-scope-chip`,title:t(`当前分支:${n.branch}(点一下切换)`,`Current branch: ${n.branch} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":a,onClick:()=>{a||n.refresh(),o(e=>!e)},children:[(0,Q.jsx)(tp,{className:`new-scope-icon new-scope-branch-icon`}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:n.branch})]}):null,a&&r?(0,Q.jsx)(sp,{anchor:r,git:n,align:`center`,onClose:()=>o(!1)}):null]})}var lp=5;function up({conversationId:e,running:t}){let n=Y(),r=Ro(e=>e.snapshot),i=r?.settings.thinkCount??5,a=Tf()?Math.min(3,i):i,[o,s]=(0,C.useState)(!1),c=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>{c.current!==null&&clearTimeout(c.current)},[]);let l=t||e===null||o,u=o?n(`正在想想…结果出来这颗按钮就亮回来`,`Thinking… the button lights up again once the suggestions arrive`):t?n(`这一轮还在跑,等结束再来一批`,`This turn is still running — ask again when it ends`):e===null?n(`先打开一个会话,再让模型想想下一步`,`Open a conversation first, then let the model suggest next steps`):n(`想想:让模型基于当前上下文再给几条下一步建议`,`Think: ask the model for a few next-step suggestions from the current context`),d=()=>{c.current!==null&&(clearTimeout(c.current),c.current=null),s(!1)};return(0,Q.jsxs)(`button`,{type:`button`,className:`tool-chip action-think${o?` action-think-busy`:``}`,disabled:l,"aria-busy":o,title:u,onClick:()=>{if(l)return;s(!0);let t=r?.settings.thinkTimeoutSec??20;c.current!==null&&clearTimeout(c.current),c.current=setTimeout(d,(t+lp)*1e3),eu(e??void 0,a).finally(d)},children:[(0,Q.jsx)(`span`,{className:`tool-icon`,"aria-hidden":`true`,children:`💡`}),n(`想想`,`Think`)]})}function dp(e){return e.filter(e=>e.hidden!==!0)}function fp(e,t){return t===`en`?{name:e.nameEn||e.name,description:e.descriptionEn||e.description,text:e.textEn||e.text}:{name:e.name,description:e.description,text:e.text}}function pp(e,t){if(typeof e==`string`)return e;let n=e.text??``;return t===`en`&&e.textEn?e.textEn:n}function mp(e){return e.id.startsWith(`t-`)}function hp(e,t){return e.flatMap(e=>e.id===t?mp(e)?[{...e,hidden:!0}]:[]:[e])}function gp(e){(0,C.useEffect)(()=>{let t=t=>{t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),e())};return window.addEventListener(`keydown`,t,!0),()=>window.removeEventListener(`keydown`,t,!0)},[e])}function _p({templates:e,phrases:t,running:n=!1,onQuickPhrase:r,onEdit:i,onCreate:a,onClose:o}){let s=Y(),{language:c}=Ae();gp(o);let[l,u]=(0,C.useState)(``),d=()=>{let e=l.trim();if(e===``)return;let n=c===`en`?{text:e,textEn:e}:{text:e};bu({quickPhrases:[...t,n]}),u(``)},f=e=>{bu({quickPhrases:t.filter((t,n)=>n!==e)})},p=t.filter(e=>(pp(e,c)??``).trim()!==``),m=e=>{let{text:t}=fp(e,c);So(`${t}${t.endsWith(`
10
10
  `)?``:`
11
- `}`),o()};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":s(`提示词模板`,`Prompt templates`),onClick:e=>{e.target===e.currentTarget&&o()},children:(0,Q.jsxs)(`div`,{className:`modal tpl-modal`,children:[(0,Q.jsxs)(`div`,{className:`tpl-head`,children:[(0,Q.jsx)(`strong`,{className:`tpl-title`,children:s(`提示词模板`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,title:s(`关闭`,`Close`),children:`✕`})]}),(0,Q.jsx)(`div`,{className:`tpl-hint`,children:s(`点击卡片直接填入输入框,✏️ 可编辑或删除,也能新增自己的模板`)}),(0,Q.jsxs)(`div`,{className:`tpl-grid`,children:[dp(e).map(e=>{let t=fp(e,c);return(0,Q.jsxs)(`div`,{className:`tpl-card`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`tpl-card-main`,onClick:()=>m(e),title:t.description||t.name,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e.icon}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:t.name}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:t.description})]}),(0,Q.jsx)(`button`,{type:`button`,className:`tpl-edit`,onClick:()=>i(e),title:s(`编辑`,`Edit`),children:`✏️`})]},e.id)}),(0,Q.jsxs)(`button`,{type:`button`,className:`tpl-card tpl-card-new`,onClick:a,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:`+`}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:s(`新建模板`,`New template`)}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:s(`把常用工作流存成模板`,`Save a repeated workflow as a template`)})]})]}),(0,Q.jsxs)(`div`,{className:`tpl-head tpl-head-sub`,children:[(0,Q.jsx)(`strong`,{className:`tpl-title`,children:s(`快捷指令`,`Quick commands`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:s(`改完自动保存`,`Saved automatically`)})]}),p.length>0?(0,Q.jsx)(`div`,{className:`tpl-quick-chips`,children:t.map((e,t)=>{let i=pp(e,c);return i?(0,Q.jsxs)(`span`,{className:`quick-chip tpl-quick-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`tpl-quick-send`,disabled:n,title:s(`${i}(点击直接发送 · Shift+点击只填入)`,`${i} (click to send · Shift+click to fill in)`),onClick:e=>{r?.(i,e.shiftKey?`fill`:`send`),o()},children:i}),(0,Q.jsx)(`button`,{type:`button`,className:`tpl-quick-x`,title:s(`删除这条`,`Delete this one`),"aria-label":s(`删除这条`,`Delete this one`),onClick:()=>f(t),children:`×`})]},e.text+t):null})}):null,(0,Q.jsxs)(`div`,{className:`tpl-quick-add`,children:[(0,Q.jsx)(`input`,{className:`settings-input tpl-quick-input`,value:l,placeholder:s(`添加一条快捷指令…`,`Add a quick command…`),maxLength:200,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),d())}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:d,disabled:l.trim()===``,children:s(`添加`,`Add`)})]}),(0,Q.jsx)(`div`,{className:`tpl-hint`,children:s(`最多 30 条、每条 200 字;增删立刻生效。点名字直接发送,Shift+点击只填入输入框。`,`Up to 30 items, 200 characters each; changes apply immediately. Click to send, Shift+click to fill.`)}),(0,Q.jsx)(`div`,{className:`tpl-foot`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>bu({templates:null}),children:[`↺ `,s(`恢复默认模板`,`Restore the default templates`)]})})]})})}function vp({template:e,library:t,conversationId:n,onClose:r}){let i=J(),{language:a}=je();gp(r);let o=e?fp(e,a):null,[s,c]=(0,C.useState)(o?.name??``),[l,u]=(0,C.useState)(o?.description??``),[d,f]=(0,C.useState)(o?.text??``),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(null),y=async()=>{m(null),g(!0);let e=await du({name:s,description:l,text:d,conversationId:n??null});g(!1),e.ok?(v(d),f(e.text)):m(e.message)},b=()=>{_!==null&&f(_),v(null)},x=e=>{bu({templates:e})},S=()=>{if(s.trim()===``||d.trim()===``)return m(i(`标题和提示词都要填`,`Both the title and the prompt are required`)),null;let n={id:e?.id??`tpl-${Date.now().toString(36)}`,name:s.trim(),description:l.trim(),icon:e?.icon??`✳️`,text:d.trim()};return e?t.map(t=>t.id===e.id?n:t):[...t,n]};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`编辑提示词模板`,`Edit a prompt template`),onClick:e=>{e.target===e.currentTarget&&r()},children:(0,Q.jsxs)(`div`,{className:`modal tpl-editor`,children:[(0,Q.jsxs)(`div`,{className:`tpl-head`,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e?.icon??`✳️`}),e&&mp(e)?(0,Q.jsx)(`span`,{className:`tpl-badge`,children:i(`内置`,`Built-in`)}):null,(0,Q.jsx)(`strong`,{className:`tpl-title`,children:e?i(`编辑提示词模板`,`Edit a prompt template`):i(`新建提示词模板`,`New prompt template`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:r,title:i(`关闭`,`Close`),children:`✕`})]}),(0,Q.jsxs)(`label`,{className:`tpl-field`,children:[(0,Q.jsx)(`span`,{className:`tpl-label`,children:i(`标题`,`Title`)}),(0,Q.jsx)(`input`,{className:`tpl-input`,value:s,onChange:e=>c(e.target.value),placeholder:i(`例:仓库初始化`,`e.g. bootstrapping a repo`)})]}),(0,Q.jsxs)(`label`,{className:`tpl-field`,children:[(0,Q.jsx)(`span`,{className:`tpl-label`,children:i(`说明`,`Description`)}),(0,Q.jsx)(`input`,{className:`tpl-input`,value:l,onChange:e=>u(e.target.value),placeholder:i(`一句话:这个模板用来做什么`,`One line: what this template is for`)})]}),(0,Q.jsxs)(`div`,{className:`tpl-field tpl-field-grow`,children:[(0,Q.jsxs)(`div`,{className:`tpl-label-row`,children:[(0,Q.jsx)(`label`,{className:`tpl-label`,htmlFor:`tpl-prompt-text`,children:i(`提示词`,`Prompt`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),_===null?null:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:b,children:[`↶ `,i(`撤销`,`Undo`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:h,onClick:()=>void y(),title:i(`根据标题、说明和已有草稿,写一份标准提示词(会覆盖当前正文,可撤销)`,`Write a standard prompt from the title, description and draft (replaces the prompt; undo available)`),children:[`✨ `,h?i(`生成中…`,`Generating…`):i(`AI 生成`,`Generate with AI`)]})]}),(0,Q.jsx)(`textarea`,{id:`tpl-prompt-text`,className:`tpl-textarea`,value:d,onChange:e=>{f(e.target.value),v(null)},placeholder:i(`写清楚要 agent 做什么、输出什么、不做什么`,`Be explicit about what the agent should do, output, and not do`)})]}),p?(0,Q.jsx)(`div`,{className:`tpl-error`,children:p}):null,(0,Q.jsxs)(`div`,{className:`tpl-foot tpl-foot-editor`,children:[e?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,title:mp(e)?i(`内置模板只是隐藏,点「恢复默认模板」就能复原`,`A built-in template is only hidden; use “Restore the default templates” to bring it back`):i(`自建模板会被彻底删除`,`A template you created is deleted permanently`),onClick:()=>{x(hp(t,e.id)),r()},children:[`🗑 `,i(`移出模板库`,`Remove from library`),mp(e)?i(`(可恢复)`,` (recoverable)`):``]}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{let e=S();e&&(x(e),r())},children:i(`保存修改`,`Save changes`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:()=>{let e=S();e&&(x(e),So(`${d.trim()}\n`),r())},children:i(`填入输入框`,`Fill the input`)})]})]})})}function yp(e){return e.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
11
+ `}`),o()};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":s(`提示词模板`,`Prompt templates`),onClick:e=>{e.target===e.currentTarget&&o()},children:(0,Q.jsxs)(`div`,{className:`modal tpl-modal`,children:[(0,Q.jsxs)(`div`,{className:`tpl-head`,children:[(0,Q.jsx)(`strong`,{className:`tpl-title`,children:s(`提示词模板`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,title:s(`关闭`,`Close`),children:`✕`})]}),(0,Q.jsx)(`div`,{className:`tpl-hint`,children:s(`点击卡片直接填入输入框,✏️ 可编辑或删除,也能新增自己的模板`)}),(0,Q.jsxs)(`div`,{className:`tpl-grid`,children:[dp(e).map(e=>{let t=fp(e,c);return(0,Q.jsxs)(`div`,{className:`tpl-card`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`tpl-card-main`,onClick:()=>m(e),title:t.description||t.name,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e.icon}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:t.name}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:t.description})]}),(0,Q.jsx)(`button`,{type:`button`,className:`tpl-edit`,onClick:()=>i(e),title:s(`编辑`,`Edit`),children:`✏️`})]},e.id)}),(0,Q.jsxs)(`button`,{type:`button`,className:`tpl-card tpl-card-new`,onClick:a,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:`+`}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:s(`新建模板`,`New template`)}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:s(`把常用工作流存成模板`,`Save a repeated workflow as a template`)})]})]}),(0,Q.jsxs)(`div`,{className:`tpl-head tpl-head-sub`,children:[(0,Q.jsx)(`strong`,{className:`tpl-title`,children:s(`快捷指令`,`Quick commands`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:s(`改完自动保存`,`Saved automatically`)})]}),p.length>0?(0,Q.jsx)(`div`,{className:`tpl-quick-chips`,children:t.map((e,t)=>{let i=pp(e,c);return i?(0,Q.jsxs)(`span`,{className:`quick-chip tpl-quick-chip`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`tpl-quick-send`,disabled:n,title:s(`${i}(点击直接发送 · Shift+点击只填入)`,`${i} (click to send · Shift+click to fill in)`),onClick:e=>{r?.(i,e.shiftKey?`fill`:`send`),o()},children:i}),(0,Q.jsx)(`button`,{type:`button`,className:`tpl-quick-x`,title:s(`删除这条`,`Delete this one`),"aria-label":s(`删除这条`,`Delete this one`),onClick:()=>f(t),children:`×`})]},e.text+t):null})}):null,(0,Q.jsxs)(`div`,{className:`tpl-quick-add`,children:[(0,Q.jsx)(`input`,{className:`settings-input tpl-quick-input`,value:l,placeholder:s(`添加一条快捷指令…`,`Add a quick command…`),maxLength:200,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),d())}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:d,disabled:l.trim()===``,children:s(`添加`,`Add`)})]}),(0,Q.jsx)(`div`,{className:`tpl-hint`,children:s(`最多 30 条、每条 200 字;增删立刻生效。点名字直接发送,Shift+点击只填入输入框。`,`Up to 30 items, 200 characters each; changes apply immediately. Click to send, Shift+click to fill.`)}),(0,Q.jsx)(`div`,{className:`tpl-foot`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>bu({templates:null}),children:[`↺ `,s(`恢复默认模板`,`Restore the default templates`)]})})]})})}function vp({template:e,library:t,conversationId:n,onClose:r}){let i=Y(),{language:a}=Ae();gp(r);let o=e?fp(e,a):null,[s,c]=(0,C.useState)(o?.name??``),[l,u]=(0,C.useState)(o?.description??``),[d,f]=(0,C.useState)(o?.text??``),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(null),y=async()=>{m(null),g(!0);let e=await du({name:s,description:l,text:d,conversationId:n??null});g(!1),e.ok?(v(d),f(e.text)):m(e.message)},b=()=>{_!==null&&f(_),v(null)},x=e=>{bu({templates:e})},S=()=>{if(s.trim()===``||d.trim()===``)return m(i(`标题和提示词都要填`,`Both the title and the prompt are required`)),null;let n={id:e?.id??`tpl-${Date.now().toString(36)}`,name:s.trim(),description:l.trim(),icon:e?.icon??`✳️`,text:d.trim()};return e?t.map(t=>t.id===e.id?n:t):[...t,n]};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`编辑提示词模板`,`Edit a prompt template`),onClick:e=>{e.target===e.currentTarget&&r()},children:(0,Q.jsxs)(`div`,{className:`modal tpl-editor`,children:[(0,Q.jsxs)(`div`,{className:`tpl-head`,children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e?.icon??`✳️`}),e&&mp(e)?(0,Q.jsx)(`span`,{className:`tpl-badge`,children:i(`内置`,`Built-in`)}):null,(0,Q.jsx)(`strong`,{className:`tpl-title`,children:e?i(`编辑提示词模板`,`Edit a prompt template`):i(`新建提示词模板`,`New prompt template`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:r,title:i(`关闭`,`Close`),children:`✕`})]}),(0,Q.jsxs)(`label`,{className:`tpl-field`,children:[(0,Q.jsx)(`span`,{className:`tpl-label`,children:i(`标题`,`Title`)}),(0,Q.jsx)(`input`,{className:`tpl-input`,value:s,onChange:e=>c(e.target.value),placeholder:i(`例:仓库初始化`,`e.g. bootstrapping a repo`)})]}),(0,Q.jsxs)(`label`,{className:`tpl-field`,children:[(0,Q.jsx)(`span`,{className:`tpl-label`,children:i(`说明`,`Description`)}),(0,Q.jsx)(`input`,{className:`tpl-input`,value:l,onChange:e=>u(e.target.value),placeholder:i(`一句话:这个模板用来做什么`,`One line: what this template is for`)})]}),(0,Q.jsxs)(`div`,{className:`tpl-field tpl-field-grow`,children:[(0,Q.jsxs)(`div`,{className:`tpl-label-row`,children:[(0,Q.jsx)(`label`,{className:`tpl-label`,htmlFor:`tpl-prompt-text`,children:i(`提示词`,`Prompt`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),_===null?null:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:b,children:[`↶ `,i(`撤销`,`Undo`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:h,onClick:()=>void y(),title:i(`根据标题、说明和已有草稿,写一份标准提示词(会覆盖当前正文,可撤销)`,`Write a standard prompt from the title, description and draft (replaces the prompt; undo available)`),children:[`✨ `,h?i(`生成中…`,`Generating…`):i(`AI 生成`,`Generate with AI`)]})]}),(0,Q.jsx)(`textarea`,{id:`tpl-prompt-text`,className:`tpl-textarea`,value:d,onChange:e=>{f(e.target.value),v(null)},placeholder:i(`写清楚要 agent 做什么、输出什么、不做什么`,`Be explicit about what the agent should do, output, and not do`)})]}),p?(0,Q.jsx)(`div`,{className:`tpl-error`,children:p}):null,(0,Q.jsxs)(`div`,{className:`tpl-foot tpl-foot-editor`,children:[e?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,title:mp(e)?i(`内置模板只是隐藏,点「恢复默认模板」就能复原`,`A built-in template is only hidden; use “Restore the default templates” to bring it back`):i(`自建模板会被彻底删除`,`A template you created is deleted permanently`),onClick:()=>{x(hp(t,e.id)),r()},children:[`🗑 `,i(`移出模板库`,`Remove from library`),mp(e)?i(`(可恢复)`,` (recoverable)`):``]}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{let e=S();e&&(x(e),r())},children:i(`保存修改`,`Save changes`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:()=>{let e=S();e&&(x(e),So(`${d.trim()}\n`),r())},children:i(`填入输入框`,`Fill the input`)})]})]})})}function yp(e){return e.blocks.map(e=>e.kind===`text`?e.text:``).filter(e=>e.trim()!==``).join(`
12
12
 
13
13
  `)}function bp(e,t,n=!0){let r=e=>typeof n==`function`?n(e):n,[i,a]=(0,C.useState)(()=>Object.fromEntries(e.map(e=>[e,Zr(t(e),r(e))])));return(0,C.useEffect)(()=>{let n=e.map(e=>$r(t(e),t=>a(n=>n[e]===t?n:{...n,[e]:t})));return()=>{for(let e of n)e()}},[e,t]),[i,(e,n)=>Qr(t(e),n)]}async function xp(e){try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`),!0}catch{return!1}finally{t.remove()}}var Sp=[{name:`new`,kind:`app`,args:`[首条消息]`,argsEn:`[first message]`,description:`新建对话,可带上第一条消息`,descriptionEn:`Start a new conversation, optionally with the first message`},{name:`name`,kind:`app`,args:`<名称>`,argsEn:`<name>`,description:`重命名当前会话`,descriptionEn:`Rename the current conversation`},{name:`model`,kind:`app`,args:`<名称>`,argsEn:`<name>`,description:`切换模型(按 id 或显示名模糊匹配)`,descriptionEn:`Switch model (fuzzy match on id or display name)`},{name:`thinking`,kind:`app`,args:`<档位>`,argsEn:`<level>`,description:`设置思考强度(off / low / … / max)`,descriptionEn:`Set the thinking level (off / low / … / max)`},{name:`copy`,kind:`app`,description:`复制最后一条助手消息`,descriptionEn:`Copy the last assistant message`},{name:`session`,kind:`app`,description:`显示会话消息数 / token / 费用统计`,descriptionEn:`Show message counts, tokens and cost for this conversation`},{name:`resume`,kind:`app`,description:`刷新会话列表(别的终端里刚开的会话)`,descriptionEn:`Refresh the conversation list (sessions just opened elsewhere)`},{name:`skill`,kind:`agent`,args:`<技能名>`,argsEn:`<skill name>`,description:`用某个技能(下面会列出已安装的技能)`,descriptionEn:`Use a skill (installed skills are listed below)`},{name:`compact`,kind:`agent`,args:`[说明]`,argsEn:`[note]`,description:`压缩上下文(交给引擎处理)`,descriptionEn:`Compact the context (handled by the engine)`},{name:`plan`,kind:`agent`,args:`[on|off]`,description:`开关计划模式(交给引擎处理)`,descriptionEn:`Toggle plan mode (handled by the engine)`},{name:`cwd`,kind:`agent`,args:`<路径>`,argsEn:`<path>`,description:`切换工作目录(交给引擎处理)`,descriptionEn:`Switch the working directory (handled by the engine)`}];function Cp(e){let t=e.split(`
14
- `,1)[0]??``;if(!t.startsWith(`/`))return null;let n=t.slice(1);return/^skill:/i.test(n)?null:/^skill\s/i.test(n)?{mode:`skills`,term:n.replace(/^skill\s+/i,``).trim()}:n.includes(` `)?null:{mode:`commands`,term:n}}function wp(e){let t=e.trim().toLowerCase();if(t===``)return Sp;let n=Sp.filter(e=>e.name.startsWith(t)),r=Sp.filter(e=>!e.name.startsWith(t)&&e.name.includes(t));return[...n,...r]}function Tp(e,t){let n=t.trim().toLowerCase();return[...n===``?e:e.filter(e=>`${e.name} ${e.description}`.toLowerCase().includes(n))].sort((e,t)=>Number(t.enabled)-Number(e.enabled)||e.name.localeCompare(t.name))}function Ep(e){return e.args,`/${e.name} `}function Dp(e,t=!1){let n=t?e.argsEn??e.args:e.args;return n?`/${e.name} ${n}`:`/${e.name}`}function Op(e){let t=e.trim();if(!t.startsWith(`/`))return!1;let n=(t.slice(1).split(/\s+/)[0]??``).toLowerCase();return Sp.some(e=>e.name===n&&e.kind===`app`)}async function kp(e,t){let n=e.trim();if(!n.startsWith(`/`))return{handled:!1};let[r,...i]=n.slice(1).split(/\s+/),a=(r??``).toLowerCase(),o=i.join(` `).trim(),s=Sp.find(e=>e.name===a);if(!s||s.kind!==`app`)return{handled:!1};switch(a){case`new`:return zl(),o&&window.setTimeout(()=>So(o),80),{handled:!0};case`name`:{let e=t?.active.conversationId??null;return e?o?(Gl(e,o),Z({text:q(`已把会话改名为「${o}」`,`Renamed the session to “${o}”`)}),{handled:!0}):(Z({text:q(`用法:/name <名称>`,`Usage: /name <name>`)}),{handled:!0}):(Z({text:q(`先打开一个会话再改名`,`Open a session before renaming it`)}),{handled:!0})}case`model`:{let e=t?.models??[];if(e.length===0)return Z({text:q(`模型列表还没就绪,等一下再试`,`The model list is not ready yet — try again in a moment`)}),{handled:!0};if(!o)return Z({text:q(`用法:/model <模型名或 id>`,`Usage: /model <model name or id>`)}),{handled:!0};let n=o.toLowerCase(),r=e.find(e=>e.id.toLowerCase()===n)??e.find(e=>e.label.toLowerCase()===n)??e.find(e=>e.id.toLowerCase().includes(n)||e.label.toLowerCase().includes(n));return r?(lu(r.id,t?.active.conversationId??null),Z({text:q(`已切到 ${r.label}`,`Switched to ${r.label}`)}),{handled:!0}):(Z({text:q(`没找到模型「${o}」`,`No model named “${o}”`)}),{handled:!0})}case`thinking`:{let e=t?.thinkingLevels??[];return o?e.length>0&&!e.includes(o)?(Z({text:q(`这个模型没有「${o}」档:${e.join(` / `)}`,`This model has no “${o}” level: ${e.join(` / `)}`)}),{handled:!0}):($l(o),Z({text:q(`思考强度已设为 ${o}`,`Thinking level set to ${o}`)}),{handled:!0}):(Z({text:q(`用法:/thinking <${e.join(` | `)||`off | low | medium | high | xhigh | max`}>`,`Usage: /thinking <${e.join(` | `)||`off | low | medium | high | xhigh | max`}>`)}),{handled:!0})}case`copy`:{let e=[...Vo()].reverse().find(e=>e.role===`assistant`),t=(e?yp(e):``).trim();return t?(Z({text:await xp(t)?q(`已复制最后一条回复`,`Copied the last reply`):q(`复制失败(浏览器不给权限)`,`Copy failed (the browser denied permission)`)}),{handled:!0}):(Z({text:q(`没有可复制的助手消息`,`No assistant message to copy`)}),{handled:!0})}case`session`:{let e=t?.sessionStats??null;return e?(Z({text:q(`消息 ${e.userMessages}+${e.assistantMessages} · 工具 ${e.toolCalls} · 输入 ${e.inputTokens} / 输出 ${e.outputTokens} tokens`,`Messages ${e.userMessages}+${e.assistantMessages} · tools ${e.toolCalls} · in ${e.inputTokens} / out ${e.outputTokens} tokens`)}),{handled:!0}):(Z({text:q(`还没有会话统计(跑一轮之后才有)`,`No session stats yet (they appear after a turn)`)}),{handled:!0})}case`resume`:return kl(),Z({text:q(`已请求刷新会话列表`,`Requested a conversation list refresh`)}),{handled:!0};default:return{handled:!1}}}function Ap({commands:e,active:t,onPick:n,onHover:r,skills:i=null}){let a=J(),{language:o}=je(),s=(0,C.useRef)(null);return(0,C.useEffect)(()=>{(s.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]),(0,Q.jsxs)(`div`,{className:`slash-panel`,role:`listbox`,"aria-label":a(`斜杠命令`,`Slash commands`),children:[(0,Q.jsxs)(`div`,{className:`slash-head`,children:[(0,Q.jsx)(`span`,{children:i===null?a(`↑↓ 选择 · Enter/Tab 补全 · Esc 关闭`,`↑↓ to choose · Enter/Tab to complete · Esc to close`):a(`↑↓ 选择技能 · Enter/Tab 插入 · Esc 关闭`,`↑↓ to choose a skill · Enter/Tab to insert · Esc to close`)}),(0,Q.jsx)(`span`,{className:`slash-count`,children:i===null?(0,Q.jsxs)(Q.Fragment,{children:[e.length,` `,a(`条命令`,`commands`)]}):(0,Q.jsxs)(Q.Fragment,{children:[i.length,` `,a(`个技能`,`skills`)]})})]}),(0,Q.jsxs)(`div`,{className:`slash-list`,ref:s,children:[i===null?null:i.map((e,i)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:`slash-row${i===t?` slash-row-on`:``}`,onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n({name:`skill:${e.name}`,kind:`agent`,description:e.description})},children:[(0,Q.jsx)(`span`,{className:`slash-name mono`,children:`/skill:${e.name}`}),(0,Q.jsx)(`span`,{className:`slash-kind${e.enabled?``:` slash-kind-off`}`,children:e.enabled?a(`已启用`,`Enabled`):a(`已停用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`slash-desc`,children:e.description||e.name})]},e.id)),i===null&&e.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:a(`没有匹配的命令`,`No matching commands`)}):null,i!==null&&i.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:a(`没有匹配的技能`,`No matching skills`)}):null,(i===null?e:[]).map((e,i)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:`slash-row${i===t?` slash-row-on`:``}`,onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n(e)},children:[(0,Q.jsx)(`span`,{className:`slash-name mono`,children:Dp(e,o===`en`)}),(0,Q.jsx)(`span`,{className:`slash-kind${e.kind===`agent`?` slash-kind-agent`:``}`,children:e.kind===`agent`?a(`发给 Agent`,`Sent to agent`):a(`本地`,`Runs here`)}),(0,Q.jsx)(`span`,{className:`slash-desc`,children:a(e.description,e.descriptionEn)})]},e.name))]})]})}var jp=4,Mp=8;function Np(e,t,n){let r=Math.max(n,window.innerWidth-t.width-n),i=Math.max(n,window.innerHeight-t.height-n);return{x:Math.min(Math.max(n,e.x),r),y:Math.min(Math.max(n,e.y),i)}}function Pp(e){let t=Yr(e);if(!t)return null;try{let e=JSON.parse(t);return typeof e.x!=`number`||typeof e.y!=`number`||!Number.isFinite(e.x)||!Number.isFinite(e.y)?null:{x:e.x,y:e.y}}catch{return null}}function Fp(e){let t=e.edge??Mp,n=e.active??!0,r=(0,C.useRef)(null),[i,a]=(0,C.useState)(()=>Pp(e.storageKey)),[o,s]=(0,C.useState)(!1),c=(0,C.useRef)(null),l=()=>{let e=r.current?.getBoundingClientRect();e&&a(n=>{if(!n)return n;let r=Np(n,{width:e.width,height:e.height},t);return r.x===n.x&&r.y===n.y?n:r})};return(0,C.useEffect)(()=>{n&&l()},[n,i===null]),(0,C.useEffect)(()=>{if(n)return window.addEventListener(`resize`,l),()=>window.removeEventListener(`resize`,l)},[n]),{ref:r,pos:i,dragging:o,style:i?{left:`${i.x}px`,top:`${i.y}px`,right:`auto`,bottom:`auto`,transform:`none`}:void 0,onPointerDown:t=>{if(t.button!==0||e.ignoreSelector&&t.target.closest(e.ignoreSelector))return;let n=r.current?.getBoundingClientRect();n&&(t.currentTarget.setPointerCapture(t.pointerId),c.current={pointerId:t.pointerId,offsetX:t.clientX-n.left,offsetY:t.clientY-n.top,startX:t.clientX,startY:t.clientY,moved:!1},s(!0))},onPointerMove:e=>{let n=c.current;if(!n||n.pointerId!==e.pointerId)return;if(!n.moved){if(Math.hypot(e.clientX-n.startX,e.clientY-n.startY)<jp)return;n.moved=!0}let i=r.current?.getBoundingClientRect();a(Np({x:e.clientX-n.offsetX,y:e.clientY-n.offsetY},{width:i?.width??0,height:i?.height??0},t))},onPointerUp:t=>{let n=c.current;if(!n||n.pointerId!==t.pointerId||(c.current=null,s(!1),!n.moved))return!1;let i=r.current?.getBoundingClientRect();return i&&Xr(e.storageKey,JSON.stringify({x:Math.round(i.left),y:Math.round(i.top)})),!0},onPointerCancel:e=>{let t=c.current;t&&t.pointerId===e.pointerId&&(c.current=null,s(!1))},resetPosition:()=>{a(null),Xr(e.storageKey,``)}}}var Ip=`pop-agent.voice.badge.pos`;function Lp({inline:e=!1}={}){let t=J(),n=$i(),r=ta(),i=Fp({storageKey:Ip}),a=!e,o=n===`listening`,s=n===`sending`,c=s?t(`正在发送…`,`Sending…`):o?t(`正在听…说完停 2.2 秒会自动发送;点一下立刻停止并保留文字`,`Listening… it auto-sends after 2.2s of silence; tap to stop and keep the text`):t(`点一下开始语音输入(按住可拖到任意位置,右键回到默认位置)`,`Tap to start voice input (drag to move, right-click to reset)`),l=()=>{s||Ea()};return(0,Q.jsxs)(`button`,{type:`button`,ref:i.ref,className:`voice-mic${e?` is-inline`:``}${o?` is-listening`:``}${s?` is-sending`:``}${i.dragging?` is-dragging`:``}`,style:a?i.style:void 0,onPointerDown:a?i.onPointerDown:void 0,onPointerMove:a?i.onPointerMove:void 0,onPointerUp:e=>{a&&i.onPointerUp(e)||l()},onPointerCancel:a?i.onPointerCancel:void 0,onClick:e=>{e.detail===0&&l()},onContextMenu:e=>{a&&(e.preventDefault(),i.resetPosition())},"aria-pressed":o||s,"aria-label":c,title:c,children:[o&&r>.02?(0,Q.jsx)(`span`,{className:`voice-mic-ring`,style:{"--voice-progress":String(r)},"aria-hidden":`true`}):null,(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:o||s?`■`:`🎤`})]})}var Rp={go:{label:`GO`,tone:`go`},ts:{label:`TS`,tone:`ts`},tsx:{label:`TS`,tone:`ts`},mts:{label:`TS`,tone:`ts`},cts:{label:`TS`,tone:`ts`},js:{label:`JS`,tone:`js`},jsx:{label:`JS`,tone:`js`},mjs:{label:`JS`,tone:`js`},cjs:{label:`JS`,tone:`js`},vue:{label:`VUE`,tone:`js`},svelte:{label:`SV`,tone:`js`},json:{label:`{}`,tone:`json`},jsonc:{label:`{}`,tone:`json`},json5:{label:`{}`,tone:`json`},py:{label:`PY`,tone:`py`},pyi:{label:`PY`,tone:`py`},sh:{label:`SH`,tone:`sh`},bash:{label:`SH`,tone:`sh`},zsh:{label:`SH`,tone:`sh`},fish:{label:`SH`,tone:`sh`},ps1:{label:`PS`,tone:`sh`},md:{label:`MD`,tone:`md`},markdown:{label:`MD`,tone:`md`},mdx:{label:`MD`,tone:`md`},css:{label:`CSS`,tone:`style`},scss:{label:`CSS`,tone:`style`},sass:{label:`CSS`,tone:`style`},less:{label:`CSS`,tone:`style`},html:{label:`<>`,tone:`markup`},htm:{label:`<>`,tone:`markup`},xml:{label:`<>`,tone:`markup`},svg:{label:`<>`,tone:`markup`},yaml:{label:`YML`,tone:`data`},yml:{label:`YML`,tone:`data`},toml:{label:`TOML`,tone:`data`},ini:{label:`INI`,tone:`data`},env:{label:`ENV`,tone:`data`},conf:{label:`CFG`,tone:`data`},csv:{label:`CSV`,tone:`data`},sql:{label:`SQL`,tone:`sql`},rs:{label:`RS`,tone:`rs`},java:{label:`JAVA`,tone:`jvm`},kt:{label:`KT`,tone:`jvm`},kts:{label:`KT`,tone:`jvm`},gradle:{label:`GRD`,tone:`jvm`},c:{label:`C`,tone:`c`},h:{label:`C`,tone:`c`},cc:{label:`C++`,tone:`c`},cpp:{label:`C++`,tone:`c`},hpp:{label:`C++`,tone:`c`},cs:{label:`C#`,tone:`c`},txt:{label:`TXT`,tone:`text`},log:{label:`LOG`,tone:`text`},lock:{label:`LOCK`,tone:`text`}};function zp(e){let t=e.toLowerCase();if(t===`dockerfile`||t.startsWith(`dockerfile.`))return{label:`DOCK`,tone:`sh`};if(t===`makefile`||t===`gnumakefile`)return{label:`MK`,tone:`sh`};if(t===`.gitignore`||t===`.gitattributes`)return{label:`GIT`,tone:`text`};if(t===`go.mod`||t===`go.sum`)return{label:`GO`,tone:`go`};if(t===`package.json`||t===`tsconfig.json`)return{label:`{}`,tone:`json`};let n=t.lastIndexOf(`.`);return n<0?null:Rp[t.slice(n+1)]??null}var Bp={browse:{zh:`添加`,en:`Add`},recent:{zh:`最近用过`,en:`Recent`},result:null};function Vp({rows:e,active:t,loading:n=!1,error:r=null,onPick:i,onHover:a,onBrowse:o,onOpenFile:s}){let c=J(),l=(0,C.useRef)(null);(0,C.useEffect)(()=>{(l.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]);let u=null;return(0,Q.jsxs)(`div`,{className:`slash-panel mention-panel`,role:`listbox`,"aria-label":c(`@ 提及文件`,`Mention a file`),children:[(0,Q.jsxs)(`div`,{className:`slash-head`,children:[(0,Q.jsx)(`span`,{children:c(`↑↓ 选择 · Enter/Tab 插入 · Esc 关闭`,`↑↓ to choose · Enter/Tab to insert · Esc to close`)}),(0,Q.jsx)(`span`,{className:`slash-count`,children:n?c(`搜索中…`,`Searching…`):`${e.length} ${c(`项`,`items`)}`})]}),(0,Q.jsxs)(`div`,{className:`slash-list`,ref:l,children:[e.map((e,n)=>{let r=e.group===u?null:Bp[e.group];return u=e.group,(0,Q.jsxs)(`div`,{children:[r?(0,Q.jsx)(`div`,{className:`mention-group`,children:c(r.zh,r.en)}):null,(0,Q.jsx)(`button`,{type:`button`,"data-index":n,role:`option`,"aria-selected":n===t,className:`slash-row mention-row${n===t?` slash-row-on`:``}`,title:e.kind===`browse`?void 0:`@${e.path}`,onMouseEnter:()=>a(n),onMouseDown:t=>{t.preventDefault(),e.kind===`browse`?o(e.target):i(e)},children:e.kind===`browse`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:e.target===`file`?`📄`:`📁`}),(0,Q.jsx)(`span`,{className:`mention-name`,children:e.target===`file`?c(`文件和文件夹`,`Files and folders`):c(`文件夹`,`Folder`)}),(0,Q.jsx)(`span`,{className:`mention-path`,children:e.target===`file`?c(`从这台电脑选择`,`Pick from this computer`):c(`选择一个文件夹`,`Pick a folder`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Hp,{name:e.name,isDir:e.isDir}),(0,Q.jsx)(`span`,{className:`mention-name mono`,children:e.name}),(0,Q.jsx)(`span`,{className:`mention-path`,children:e.path}),s&&!e.isDir?(0,Q.jsx)(`span`,{className:`mention-open`,role:`button`,title:c(`在右侧面板打开这个文件`,`Open this file in the side panel`),"aria-label":c(`在右侧面板打开`,`Open in the side panel`),onMouseDown:t=>{t.preventDefault(),t.stopPropagation(),s(e.path)},children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M9.5 2.5H13.5V6.5`}),(0,Q.jsx)(`path`,{d:`M13.5 2.5 8 8`}),(0,Q.jsx)(`path`,{d:`M12.5 9.5V13.5H2.5V3.5H6.5`})]})}):null]})})]},e.kind===`browse`?`browse:${e.target}`:`${e.group}:${e.path}`)}),e.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:r??(n?c(`搜索中…`,`Searching…`):c(`没有匹配的文件`,`No matching files`))}):r?(0,Q.jsx)(`div`,{className:`slash-empty`,children:r}):null]})]})}function Hp({name:e,isDir:t}){if(t)return(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:`📁`});let n=zp(e);return n?(0,Q.jsx)(`span`,{className:`filetree-type filetype-${n.tone}`,"aria-hidden":`true`,children:n.label}):(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:`·`})}var Up=160,Wp=new Set([``,` `,` `,`
15
- `,`(`,`(`,`【`,`[`,`「`,`《`,`"`,`'`,"`",`:`,`:`]);function Gp(e,t){let n=Math.min(Math.max(t,0),e.length),r=-1;for(let t=n-1;t>=0;--t){let n=e[t]??``;if(n===`@`){r=t;break}if(/\s/.test(n))return null}if(r<0)return null;let i=r===0?``:e[r-1]??``;if(!Wp.has(i))return null;let a=e.slice(r+1,n);return a.length>Up?null:{start:r,end:n,term:a}}function Kp(e,t,n){return Jp(e,t.start,t.end,n)}function qp(e,t,n){let r=Math.min(Math.max(t,0),e.length);return Jp(e,r,r,n)}function Jp(e,t,n,r){let i=`@${r}`,a=e.slice(n),o=/^\s/.test(a),s=a===``||!o?` `:``;return{text:e.slice(0,t)+i+s+a,caret:t+i.length+(s===``&&o?1:s.length)}}function Yp(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function Xp(e,t){let n=j(e),r=j(t);if(n===``||r===``)return null;let i=/^[A-Za-z]:/.test(n),a=n.split(/[\\/]+/).filter(e=>e!==``),o=r.split(/[\\/]+/).filter(e=>e!==``);if(a.length===0||a.length>o.length)return null;for(let e=0;e<a.length;e+=1){let t=a[e]??``,n=o[e]??``;if(i?t.toLowerCase()!==n.toLowerCase():t!==n)return null}return o.slice(a.length).join(`/`)}function Zp(e,t){let n=e.trim();if(n===``||!Yp(n))return n;if(t){let e=Xp(t,n);if(e!==null)return e===``?`.`:e}return n}function Qp(e){let t=[];if(e.term.trim()===``){t.push({kind:`browse`,target:`file`,group:`browse`}),t.push({kind:`browse`,target:`dir`,group:`browse`});for(let n of e.recent.slice(0,40-t.length))t.push({kind:`file`,name:D(n.path),path:n.path,isDir:n.isDir,group:`recent`});return t}for(let n of e.results.slice(0,40))t.push({kind:`file`,name:D(n.path),path:n.path,isDir:n.isDir,group:`result`});return t}var $p=180,em=`pop-agent:mention-recent`,tm=24,nm=[];function rm(){if(typeof localStorage>`u`)return[];try{let e=JSON.parse(localStorage.getItem(em)??`[]`);return Array.isArray(e)?e.filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.root==`string`&&typeof t.path==`string`}).map(e=>({root:e.root,path:e.path,isDir:e.isDir===!0})):[]}catch{return[]}}function im(e,t){return+!e.toLowerCase().startsWith(t)}function am(e,t){let[n,r]=(0,C.useState)(nm),[i,a]=(0,C.useState)(!1),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(rm);(0,C.useEffect)(()=>{try{localStorage.setItem(em,JSON.stringify(c))}catch{}},[c]);let u=e??``,d=(0,C.useMemo)(()=>c.filter(e=>e.root===u).map(({path:e,isDir:t})=>({path:e,isDir:t})),[c,u]),f=(0,C.useCallback)(e=>{l(t=>{let n=t.filter(t=>t.root!==u||t.path!==e.path);return[{root:u,path:e.path,isDir:e.isDir},...n].slice(0,tm)})},[u]);return(0,C.useEffect)(()=>{let n=(t??``).trim();if(t===null||!e||n===``){r(nm),a(!1),s(null);return}let i=Math.max(n.lastIndexOf(`/`),n.lastIndexOf(`\\`)),o=i>=0?n.slice(i+1):n;if(o===``){r(nm),a(!1),s(null);return}let c=!1;a(!0);let l=setTimeout(()=>{(async()=>{try{let t=await fetch(`/api/files/search?q=${encodeURIComponent(o)}&root=${encodeURIComponent(e)}`),a=await t.json();if(c)return;if(!t.ok){r(nm),s(a.error?.message??`HTTP ${t.status}`);return}let l=a.entries??[],u=i<0?l:l.filter(e=>e.path.toLowerCase().includes(n.toLowerCase())),d=o.toLowerCase(),f=[...u].sort((e,t)=>im(e.name,d)-im(t.name,d));r(f.map(e=>({path:e.path,isDir:e.isDir===!0}))),s(null)}catch(e){if(c)return;r(nm),s(e instanceof Error?e.message:String(e))}finally{c||a(!1)}})()},$p);return()=>{c=!0,clearTimeout(l),a(!1)}},[e,t]),{results:n,recent:d,loading:i,error:o,remember:f}}function om(e){return e.sessions.reduce((e,t)=>Math.max(e,t.startedAt),0)}function sm(e){let t=new Map;return e.forEach((e,n)=>{t.has(e)||t.set(e,n)}),t}function cm(e,t){let n=sm(t.pinned),r=sm(t.order),i=e.filter(e=>n.has(e.cwd)).sort((e,t)=>(n.get(e.cwd)??0)-(n.get(t.cwd)??0)),a=e.filter(e=>!n.has(e.cwd)),o=a.filter(e=>r.has(e.cwd)).sort((e,t)=>(r.get(e.cwd)??0)-(r.get(t.cwd)??0)),s=a.filter(e=>!r.has(e.cwd)).sort((e,t)=>om(t)-om(e)||e.cwd.localeCompare(t.cwd));return[...i,...s,...o]}function lm(e){let{visible:t,pinned:n,from:r,target:i,after:a}=e;if(r===i||!t.includes(r))return null;let o=new Set(n);n.includes(i)?o.add(r):o.delete(r);let s=t.filter(e=>e!==r),c=s.indexOf(i);return c<0?null:(s.splice(c+ +!!a,0,r),{pinned:s.filter(e=>o.has(e)),order:s.filter(e=>!o.has(e))})}function um(e){let t=e.trim();for(let e of[`"`,`'`])t.length>=2&&t.startsWith(e)&&t.endsWith(e)&&(t=t.slice(1,-1).trim());return/^[A-Za-z]:$/.test(t)?`${t}\\`:t}async function dm(e){let t=await e.text();try{return{ok:!0,body:JSON.parse(t)}}catch{return{ok:!1,message:t.trimStart().startsWith(`<`)?q(`服务端上还没有这个接口(HTTP ${e.status})—— 服务可能在跑旧版本,重启一下就好`,`The server does not have this endpoint yet (HTTP ${e.status}) — it may be an older build, restart it`):q(`服务端返回的不是 JSON(HTTP ${e.status})`,`The server did not return JSON (HTTP ${e.status})`)}}}function fm({onClose:e,onPick:t}){let n=J(),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)([]),[d,f]=(0,C.useState)([]),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!0),[_,v]=(0,C.useState)(!1),y=async e=>{g(!0),m(null);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await dm(t);if(!n.ok){m(n.message);return}let r=n.body;if(!t.ok){m(r.error?.message??`HTTP ${t.status}`);return}i(r.path??``),o(r.path??``),c(r.parent??null),u(r.entries??[]),f(r.drives??[])}catch(e){m(e instanceof Error?e.message:String(e))}finally{g(!1)}};(0,C.useEffect)(()=>{y()},[]);let b=n=>{t?t(n):zl(n),e()},x=e=>void y(um(e)),S=async()=>{v(!0),m(null);try{let e=await fetch(`/api/fs/pick-dir`,{method:`POST`}),t=await dm(e);if(!t.ok){m(t.message);return}let r=t.body;if(!e.ok){m(r.error?.message??r.message??`HTTP ${e.status}`);return}if(r.unsupported){m(r.message??n(`这台机器上开不出目录选择框,请在下面直接浏览`,`No folder picker on this machine — browse below instead`));return}if(!r.path)return;b(r.path)}catch(e){m(e instanceof Error?e.message:String(e))}finally{v(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`新建项目`),children:(0,Q.jsxs)(`div`,{className:`modal new-project`,children:[(0,Q.jsxs)(`div`,{className:`new-project-head`,children:[(0,Q.jsx)(`strong`,{children:n(`🗂 本地目录`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:e,title:n(`关闭`),children:`✕`})]}),(0,Q.jsxs)(`div`,{className:`new-project-bar`,children:[(0,Q.jsx)(`input`,{className:`new-project-input mono`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&x(a)},placeholder:M()?n(`C:\\绝对路径`,`C:\\absolute\\path`):n(`/绝对路径`,`/absolute/path`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>x(a),disabled:h,children:n(`跳转`,`Go`)})]}),(0,Q.jsxs)(`div`,{className:`new-project-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void S(),disabled:_,title:n(`在服务端所在的电脑上打开系统自带的文件夹选择框`,`Open your computer's own folder picker (on the machine running the server)`),children:_?n(`📂 选择中…`,`📂 Choosing…`):n(`📂 浏览电脑…`,`📂 Browse computer…`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void y(s??void 0),disabled:!s||h,title:n(`回到上一级目录`,`Go to the parent folder`),children:n(`↑ 上级目录`,`↑ Up one level`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-send`,onClick:()=>b(r||um(a)),disabled:h||r===``&&a.trim()===``,children:n(`选择当前目录`,`Use this folder`)})]}),p?(0,Q.jsx)(`div`,{className:`side-error`,children:p}):null,_?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:n(`文件夹选择框已经在你电脑上打开,如果没看到,它可能被浏览器/别的窗口挡住了(Alt+Tab 找一下)`,`The folder picker is open on your computer — if you can't see it, it may be behind another window (Alt+Tab)`)}):null,d.length>1?(0,Q.jsx)(`div`,{className:`new-project-drives`,children:d.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${e.path===r?` is-current`:``}`,onClick:()=>void y(e.path),title:e.path,children:e.name},e.path))}):null,(0,Q.jsxs)(`div`,{className:`new-project-list`,children:[h?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:n(`读取中…`)}):null,!h&&l.length===0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[n(`这个目录下没有子目录`,`No subfolders here`),s?n(` —— 可以点上面的「↑ 上级目录」往外走`,` — use ↑ Up one level above`):null]}):null,l.map(e=>(0,Q.jsxs)(`div`,{className:`new-project-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`new-project-name`,onClick:()=>void y(e.path),title:e.path,children:[(0,Q.jsx)(`span`,{className:`new-project-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),e.name]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>b(e.path),children:n(`选择`,`Choose`)})]},e.path))]}),(0,Q.jsx)(`div`,{className:`new-project-foot`,children:(0,Q.jsx)(`span`,{className:`side-panel-hint`,children:n(`「选择」= 在这个目录下新建一个会话(项目随之出现),不会创建或修改任何文件。`,`Choose = start a new conversation in this folder (the project appears with it); no files are created or changed.`)})})]})})}function pm({workspace:e,ephemeral:t,onChange:n,onEphemeralChange:r}){let i=J(),a=Ro(e=>e.snapshot),o=a?.settings.projectPrefs??{order:[],pinned:[],aliases:{},hidden:[]},s=cm(a?.piProjects??[],o).map(e=>({cwd:e.cwd,label:o.aliases[e.cwd]||e.name||D(e.cwd)||e.cwd})),c=e===null?null:j(e),l=e=>c!==null&&j(e)===c,u=e!==null&&!s.some(e=>l(e.cwd))?[{cwd:e,label:D(e)||e,fresh:!0},...s.map(e=>({...e,fresh:!1}))]:s.map(e=>({...e,fresh:!1})),d=u.find(e=>l(e.cwd))??null,f=ep(e),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(null),[y,b]=(0,C.useState)(!1),[x,S]=(0,C.useState)(``),[w,T]=(0,C.useState)(-1),[E,O]=(0,C.useState)(!1),k=(0,C.useRef)(null),A=a?.engineCapabilities.ephemeralChat===!0,M=t&&A,N=e=>{n(e),g(!1),S(``),T(-1)},P=x.trim().toLowerCase(),F=P?u.filter(e=>e.label.toLowerCase().includes(P)||e.cwd.toLowerCase().includes(P)):u;return(0,C.useEffect)(()=>{w<0||(k.current?.querySelector(`[data-index="${w}"]`))?.scrollIntoView({block:`nearest`})},[w]),(0,Q.jsxs)(`div`,{className:`new-session-scope`,children:[M?null:(0,Q.jsxs)(`button`,{type:`button`,ref:m,className:`new-scope-chip${d?``:` new-scope-chip-muted`}`,title:e??i(`还没有项目:这条会话会跟在服务端的工作区里`,`No project yet: this session stays in the server workspace`),"aria-haspopup":`listbox`,"aria-expanded":h,onClick:()=>g(e=>!e),children:[(0,Q.jsx)(`span`,{className:`new-scope-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:d?.label??i(`选择项目`,`Choose a project`)}),(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,className:`new-scope-caret`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4.4 6.4 3.6 3.6 3.6-3.6`})})]}),t&&A?(0,Q.jsx)(`button`,{type:`button`,className:`new-scope-chip new-scope-chip-ephemeral`,title:i(`临时会话:只活在内存里,关闭即消失(点一下取消)· 工作目录:${e??`跟服务端工作区`}`,`Temporary session: in-memory only, gone on close (click to cancel) · working dir: ${e??`server workspace`}`),onClick:()=>r(!1),children:(0,Q.jsx)(`span`,{className:`new-scope-label`,children:M?i(`💬 临时会话(不保存)`,`💬 Temp session (not saved)`):i(`💬 不保存`,`💬 Not saved`)})}):null,f.isRepo&&f.branch&&!M?(0,Q.jsxs)(`button`,{type:`button`,ref:v,className:`new-scope-chip`,title:i(`当前分支:${f.branch}(点一下切换)`,`Current branch: ${f.branch} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":y,onClick:()=>b(e=>!e),children:[(0,Q.jsx)(tp,{className:`new-scope-icon new-scope-branch-icon`}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:f.branch})]}):null,h&&p?(0,Q.jsxs)(qd,{anchor:p,className:`proj-menu new-scope-menu`,align:`center`,style:{width:Math.min(320,Math.max(220,p.getBoundingClientRect().width+40))},onClose:()=>{g(!1),S(``),T(-1)},children:[(0,Q.jsx)(`input`,{className:`new-scope-search`,value:x,autoFocus:!0,placeholder:i(`搜索项目`,`Search projects`),"aria-label":i(`搜索项目`,`Search projects`),onChange:e=>{S(e.target.value),T(-1)},onKeyDown:e=>{if(e.key===`Escape`)g(!1),S(``),T(-1);else if(e.key===`ArrowDown`)e.preventDefault(),T(e=>F.length===0?-1:Math.min(F.length-1,e+1));else if(e.key===`ArrowUp`)e.preventDefault(),T(e=>Math.max(0,e-1));else if(e.key===`Enter`){let e=F[w>=0?w:0];e&&N(e.cwd)}e.stopPropagation()}}),(0,Q.jsxs)(`div`,{className:`new-scope-list`,ref:k,children:[F.map((e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":t,className:`proj-menu-item files-root-option${l(e.cwd)?` files-root-option-on`:``}${t===w?` new-scope-item-active`:``}`,title:e.fresh?i(`${e.cwd}(刚选的目录:发出第一条消息后才会成为项目)`,`${e.cwd} (just picked: becomes a project after the first message)`):e.cwd,onClick:()=>N(e.cwd),onMouseEnter:()=>T(t),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:l(e.cwd)?`✓`:``}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:e.label})]},e.cwd)),F.length===0?(0,Q.jsx)(`div`,{className:`new-scope-empty`,children:P?i(`没有匹配的项目`,`No matching project`):i(`还没有任何项目:点下面的「新建项目」选一个目录。`,`No projects yet — pick a folder with “New project” below.`)}):null]}),(0,Q.jsxs)(`div`,{className:`new-scope-foot`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option`,onClick:()=>{g(!1),S(``),T(-1),O(!0)},children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(op,{})}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:i(`新建项目`,`New project`)})]}),A?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${t?` files-root-option-on`:``}`,title:i(`建成临时会话:不写会话文件、不进历史,关闭即消失(目录仍用上面选的项目)`,`Create a temporary session: no session file, not in history, gone on close (still uses the project above)`),onClick:()=>{r(!t),g(!1),S(``),T(-1)},children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:t?`✓`:``}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon new-scope-menu-icon-emoji`,"aria-hidden":`true`,children:`💬`}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:i(`临时会话(不保存)`,`Temporary session (not saved)`)})]}):null]})]}):null,y&&_?(0,Q.jsx)(sp,{anchor:_,git:f,align:`center`,onClose:()=>b(!1)}):null,E?(0,Q.jsx)(fm,{onClose:()=>O(!1),onPick:e=>{n(e),O(!1)}}):null]})}var mm=240,hm=700;function gm(e){return e<1024?`${e}B`:e<1048576?`${Math.round(e/1024)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function _m({running:e,conversationId:t,surface:n,newSession:r=null,tempChat:i=!1,annotations:a=[],onAnnotationsSent:o,onOpenFile:s,annotationSummary:c=null}){let l=J(),{language:u}=je(),d=Lo(),f=n?n.draft:d.draft,p=n?n.setDraft:So,m=n?n.snapshot:d.snapshot,h=!n&&d.creating,[g,_]=(0,C.useState)([]),[v,y]=(0,C.useState)(!1),[b,x]=(0,C.useState)(null),S=(0,C.useRef)(t);S.current=t,(0,C.useEffect)(()=>{_([]),x(null),y(!1)},[t]),(0,C.useEffect)(()=>{na()&&Ta()},[t]);let w=(0,C.useRef)(null),T=(0,C.useRef)(null),E=(0,C.useRef)(null),D=(0,C.useCallback)(()=>{let e=w.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,mm)}px`)},[]);(0,C.useLayoutEffect)(()=>{D()},[f,D]),(0,C.useLayoutEffect)(()=>{let e=T.current,t=E.current;if(!e||!t)return;let n=()=>{let n=t.getBoundingClientRect();e.style.setProperty(`--composer-actions-w`,`${Math.ceil(n.width)}px`),e.style.setProperty(`--composer-actions-h`,`${Math.ceil(n.height)}px`),D()};n();let r=new ResizeObserver(n);return r.observe(t),()=>r.disconnect()},[D]);let O=(0,C.useRef)(0),k=(0,C.useRef)(!1);(0,C.useEffect)(()=>{let e=k.current&&!h;if(k.current=h,!e||!w.current)return;let t=document.activeElement;(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t!==w.current||w.current.focus()},[h]);let A=n?null:m?.conversations.find(e=>e.id===m.active.conversationId)?.workspace??m?.files?.root??null,[j]=bp(Pr,Lr,Ir),M=Cp(f),N=M?.mode===`commands`?wp(M.term):[],[P,F]=(0,C.useState)(null),I=async()=>{try{let e=(await(await fetch(`/api/skills`)).json()).skills??[];return F(e),e}catch{return F([]),[]}};(0,C.useEffect)(()=>{M?.mode===`skills`&&P===null&&I()},[M?.mode,P]);let L=M?.mode===`skills`?Tp(P??[],M.term):null,[R,z]=(0,C.useState)(0),B=L===null?N.length:L.length,[V,H]=(0,C.useState)(!1),U=M===null;(0,C.useEffect)(()=>{U&&H(!1)},[U]);let W=!V&&M!==null&&(B>0||L!==null);(0,C.useEffect)(()=>z(0),[M?.mode,M?.term]);let ee=e=>{p(Ep(e)),requestAnimationFrame(()=>w.current?.focus())},G=e=>{p(`/skill:${e} `),requestAnimationFrame(()=>w.current?.focus())},K=r?r.workspace:m?.files?.root??null,[te,ne]=(0,C.useState)(0),re=(0,C.useRef)(0),ie=(0,C.useRef)(f);ie.current=f,(0,C.useEffect)(()=>{let e=()=>{let e=w.current;if(!e||document.activeElement!==e)return;let t=e.selectionStart??0;re.current=t,ne(t)};return document.addEventListener(`selectionchange`,e),()=>document.removeEventListener(`selectionchange`,e)},[]);let ae=(0,C.useRef)(null),oe=(0,C.useRef)(null),se=(0,C.useRef)(e);se.current=e;let ce=(0,C.useRef)(m);ce.current=m;let le=(0,C.useRef)(!1);(0,C.useEffect)(()=>{if(!n)return ra({get conversationId(){return S.current??null},onStart:e=>{let t=w.current,n=e??ie.current,r=t?.selectionStart??n.length;ae.current={head:n.slice(0,r),tail:n.slice(r)}},onText:e=>{let t=ae.current;if(!t)return;let n=`${t.head}${e}${t.tail}`;p(n);let r=t.head.length+e.length;re.current=r;let i=w.current;i&&document.activeElement===i&&i.setSelectionRange(r,r)},onEnd:()=>{ae.current=null},submitVoice:()=>{let e=se.current,t=ce.current?.engineCapabilities?.steer!==!1,n=ie.current.trim().length;if(Ut(`submit:decide`,{running:e,steerCapable:t,submitMode:vi().submitMode,draftLen:n}),!e)oe.current?.(`now`);else{if(vi().submitMode===`steer`){if(t){oe.current?.(`steer`);return}le.current||(le.current=!0,Z({text:l(`当前引擎不支持插队(只有 Pi 引擎有),这句改成排队发送`,`This engine can't steer (only Pi can) — sending this one as queued instead`)}))}oe.current?.(`queue`)}}}),()=>{ra(null),na()&&Ta()}},[n,p,l]);let[ue,de]=(0,C.useState)(null),[fe,pe]=(0,C.useState)(0),[me,he]=(0,C.useState)(!1),ge=Gp(f,te),_e=ge&&ge.start!==ue?ge:null,ve=am(K,_e?_e.term:null),ye=_e===null?[]:Qp({term:_e.term,results:ve.results,recent:ve.recent}),be=Math.min(fe,Math.max(0,ye.length-1));(0,C.useEffect)(()=>pe(0),[_e?.term,_e?.start]);let xe=_e===null?null:_e.start;(0,C.useEffect)(()=>{if(!W&&xe===null)return;let e=()=>{xe!==null&&de(xe),U||H(!0)},t=e=>!(e instanceof Element)||e.closest(`.slash-panel`)?!1:!T.current?.contains(e),n=n=>{t(n.target)&&e()},r=t=>{t.key!==`Escape`||t.isComposing||(t.preventDefault(),e())};return document.addEventListener(`pointerdown`,n),document.addEventListener(`keydown`,r),()=>{document.removeEventListener(`pointerdown`,n),document.removeEventListener(`keydown`,r)}},[W,U,xe]);let Se=(e,t)=>{let n=Zp(e,K);if(n===``)return;let r=w.current,i=r?.value??ie.current,a=r?.selectionStart??re.current,o=Math.min(Math.max(a,0),i.length),s=Gp(i,o),c=s?Kp(i,s,n):qp(i,o,n);p(c.text),re.current=c.caret,ne(c.caret),de(null),ve.remember({path:n,isDir:t}),requestAnimationFrame(()=>{let e=w.current;e&&(e.focus(),e.setSelectionRange(c.caret,c.caret))})},Ce=async e=>{if(!me){he(!0);try{let t=await fetch(`/api/fs/pick-path`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({kind:e})}),n=await t.text(),r=null;try{r=JSON.parse(n)}catch{Z({text:n.trimStart().startsWith(`<`)?l(`服务端还没有这个接口(HTTP ${t.status})—— 服务可能在跑旧版本,重启一下就好`,`The server does not have this endpoint yet (HTTP ${t.status}) — it may be an older build, restart it`):l(`服务端返回的不是 JSON(HTTP ${t.status})`,`The server did not return JSON (HTTP ${t.status})`)});return}if(!r)return;if(!t.ok){Z({text:r.error?.message??r.message??`HTTP ${t.status}`});return}if(r.canceled)return;if(r.unsupported||!r.path){Z({text:r.message??l(`这台机器上开不出文件选择框:直接 @ 搜文件名也可以`,`No file picker on this machine — type @ to search file names`)});return}Se(r.path,e===`dir`)}catch(e){Z({text:e instanceof Error?e.message:String(e)})}finally{he(!1)}}},we=e=>{e.kind===`browse`?Ce(e.target):Se(e.path,e.isDir)},Te=(0,C.useMemo)(()=>{let e=[];for(let t of m?.active.messages??[]){if(t.role!==`user`)continue;let n=yp(t).trim();n!==``&&e.push(n)}return e.slice(-50)},[m?.active.messages]),[Ee,De]=(0,C.useState)(null),Oe=(0,C.useRef)(``);(0,C.useEffect)(()=>{De(null)},[t]);let ke=e=>{if(Te.length===0||Ee===null&&e===1)return!1;Ee===null&&(Oe.current=ie.current);let t=Ee===null?Te.length-1:Ee+e;t!==null&&t<0&&(t=0),t!==null&&t>=Te.length&&(t=null),De(t);let n=t===null?Oe.current:Te[t]??``;return p(n),re.current=n.length,ne(n.length),requestAnimationFrame(()=>{let e=w.current;e&&(e.focus(),e.setSelectionRange(n.length,n.length))}),!0},Ae=m?.settings.quickPhrases??[],Me=Ae.map(e=>pp(e,u)),q=j.quick&&!i?Me:[],Ne=m?.settings.templates??[],[Y,Pe]=(0,C.useState)(!1),[Fe,Ie]=(0,C.useState)(null),Le=async e=>{if(e.length===0)return;let{accepted:t,rejected:n}=Nf(e,g.length);if(n.length>0&&x(n.join(l(`;`,`; `))),t.length===0)return;let r=S.current;y(!0);let i=[];for(let e of t){let t=await Ff(e);if(S.current!==r)return;t.ok?i.push(t.attachment):x(t.error)}y(!1),i.length>0&&(_(e=>[...e,...i].slice(0,5)),x(null))},Re=e=>{let t=[...e.clipboardData.items].filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null);t.length!==0&&(e.preventDefault(),Le(t))},ze=async e=>{let t=/^\/skill:([^\s]+)/i.exec(e)?.[1]??``;if(t===``)return;let n=(P??await I()).find(e=>e.name.toLowerCase()===t.toLowerCase());n?n.enabled||Z({text:l(`技能「${t}」是停用状态:pi 不会加载它(去「技能」面板启用)`,`Skill "${t}" is disabled: pi will not load it (enable it in the Skills panel)`)}):Z({text:l(`没有叫「${t}」的技能:会当普通文本发出去。去「技能」面板核对名字`,`No skill named "${t}": the text goes out as plain text. Check the name in the Skills panel`)})},Be=(e,t,i=`now`)=>{cn(i),n?n.send(e,t,i):r?Rl(e,t,i,r.workspace??void 0,{ephemeral:r.ephemeral&&m?.engineCapabilities.ephemeralChat===!0}):Al(e,t,i)},Ve=Zu(a),He=a.filter(e=>e.quoted!==!0).length,Ue=f.trim()!==``||g.length>0||Ve!==``,We=(t=`now`)=>{Ta();let r=f.trim();if(!r&&g.length===0&&Ve===``){Ut(`submit:empty`,{mode:t});return}if(/^\/skill:/i.test(r)&&ze(r),(n?.hostCommands??!0)&&Op(r)){let e=g;kp(r,m).then(t=>{t.handled&&(ie.current.trim()===r&&p(``),_(t=>t===e?[]:t))});return}if(e&&t===`now`)return;let i=(r===``?Ve:Ve===``?r:`${r}\n\n${Ve}`)+Pf(g);Ut(`submit:send`,{mode:t,running:e,len:i.length,attachments:g.length}),Be(i,g.length>0?g:void 0,t),p(``),De(null),Oe.current=``,_([]),x(null),Ve!==``&&o?.()};return oe.current=We,(0,Q.jsxs)(`div`,{className:`composer-wrap`,children:[(0,Q.jsxs)(`div`,{className:`composer-topbar`,children:[(0,Q.jsxs)(`div`,{className:`composer-tools`,children:[r?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(pm,{workspace:r.workspace,ephemeral:r.ephemeral,onChange:r.onWorkspaceChange,onEphemeralChange:r.onEphemeralChange}),(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`})]}):A?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(cp,{projectRoot:A}),(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`})]}):null,j.model?(0,Q.jsx)(Qf,{surface:n,part:`model`}):null,j.thinking?(0,Q.jsx)(Qf,{surface:n,part:`thinking`}):null,j.think?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),(0,Q.jsx)(up,{conversationId:t,running:e})]}):null,j.templates&&!i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),(0,Q.jsxs)(`button`,{type:`button`,className:`tool-chip composer-template-btn`,onClick:()=>Pe(!0),title:l(`提示词模板库(含快捷指令)`,`Prompt templates (with quick commands)`),children:[`✏️ `,l(`提示词`,`Prompts`)]})]}):null]}),q.length>0?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`quick-row`,children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),q.map((t,n)=>(0,Q.jsx)(`button`,{type:`button`,className:`quick-chip`,disabled:e,title:l(`${t}(点击直接发送 · Shift+点击只填入)`,`${t} (click to send · Shift+click to fill in)`),onClick:n=>{if(n.shiftKey){p(t),w.current?.focus();return}if(e)return;let r=Date.now();r-O.current<hm||(O.current=r,Be(t))},children:t},`${t}-${n}`))]})}):null]}),g.length>0||v||b?(0,Q.jsxs)(`div`,{className:`attach-row`,children:[g.map(e=>(0,Q.jsxs)(`span`,{className:`attach-chip`,title:`${e.mime} · ${e.name}`,children:[e.kind===`image`?(0,Q.jsx)(`img`,{className:`attach-thumb`,src:`/api/uploads/${e.id}`,alt:e.name,title:l(`点击放大预览`,`Click to preview`),onClick:()=>ns(`/api/uploads/${e.id}`,e.name)}):(0,Q.jsx)(`span`,{className:`attach-kind`,children:`📄`}),(0,Q.jsx)(`span`,{className:`attach-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`attach-size`,children:gm(e.bytes)}),(0,Q.jsx)(`button`,{type:`button`,className:`attach-remove`,title:l(`移除`,`Remove`),onClick:()=>_(t=>t.filter(t=>t.id!==e.id)),children:`×`})]},e.id)),v?(0,Q.jsx)(`span`,{className:`attach-hint`,children:l(`上传中…`)}):null,b?(0,Q.jsx)(`span`,{className:`attach-error`,children:b}):null]}):null,W&&_e===null?(0,Q.jsx)(Ap,{commands:N,skills:L,active:R,onPick:e=>{e.name.startsWith(`skill:`)?G(e.name.slice(6)):ee(e)},onHover:z}):null,_e===null?null:(0,Q.jsx)(Vp,{rows:ye,active:be,loading:ve.loading,error:_e.term.trim()===``?null:ve.error,onPick:e=>Se(e.path,e.isDir),onHover:pe,onBrowse:e=>void Ce(e),onOpenFile:s?e=>s(e,K):void 0}),(0,Q.jsxs)(`div`,{className:`composer`,ref:T,children:[c,(0,Q.jsxs)(`div`,{className:`composer-row`,children:[n?null:(0,Q.jsx)(Lp,{inline:!0}),(0,Q.jsx)(`textarea`,{ref:w,className:`composer-input`,...wu,enterKeyHint:e?`enter`:`send`,value:f,placeholder:e?l(`正在跑…回车排队`,`Running… Enter to queue`):f.trim()===``&&Ve!==``?l(`回车发送 ${He} 条注释`,`Enter to send ${He} note(s)`):Tf()?l(`消息…`,`Message…`):l(`消息…输入 / 使用命令,输入 @ 查找文件`,`Message… type / for commands, @ to find a file`),onChange:e=>{let t=e.target.value,n=e.target.selectionStart??t.length;Ee!==null&&(De(null),Oe.current=t),p(t),re.current=n,ne(n),na()&&Da(t),ue!==null&&t[ue]!==`@`&&de(null)},onPaste:Re,onKeyDown:t=>{if(_e!==null&&!t.nativeEvent.isComposing){if(t.key===`ArrowDown`||t.key===`ArrowUp`){t.preventDefault();let e=t.key===`ArrowDown`?1:-1,n=Math.max(1,ye.length);pe(t=>(t+e+n)%n);return}if((t.key===`Tab`||t.key===`Enter`&&!t.shiftKey)&&ye.length>0){t.preventDefault();let e=ye[be];e&&we(e);return}if(t.key===`Escape`){t.preventDefault(),de(_e.start);return}}if(W&&!t.nativeEvent.isComposing){if(t.key===`ArrowDown`||t.key===`ArrowUp`){t.preventDefault();let e=t.key===`ArrowDown`?1:-1;z(t=>(t+e+Math.max(1,B))%Math.max(1,B));return}if(t.key===`Tab`||t.key===`Enter`&&!t.shiftKey){if(t.preventDefault(),L!==null){let e=L[R];e&&G(e.name);return}let e=N[R];e&&ee(e);return}if(t.key===`Escape`){t.preventDefault(),H(!0);return}}if(!t.nativeEvent.isComposing&&(t.key===`ArrowUp`||t.key===`ArrowDown`)&&t.currentTarget.selectionStart===t.currentTarget.selectionEnd){let e=t.currentTarget.value.slice(0,t.currentTarget.selectionStart??0),n=t.currentTarget.value.slice(t.currentTarget.selectionEnd??0);if((t.key===`ArrowUp`?!e.includes(`
14
+ `,1)[0]??``;if(!t.startsWith(`/`))return null;let n=t.slice(1);return/^skill:/i.test(n)?null:/^skill\s/i.test(n)?{mode:`skills`,term:n.replace(/^skill\s+/i,``).trim()}:n.includes(` `)?null:{mode:`commands`,term:n}}function wp(e){let t=e.trim().toLowerCase();if(t===``)return Sp;let n=Sp.filter(e=>e.name.startsWith(t)),r=Sp.filter(e=>!e.name.startsWith(t)&&e.name.includes(t));return[...n,...r]}function Tp(e,t){let n=t.trim().toLowerCase();return[...n===``?e:e.filter(e=>`${e.name} ${e.description}`.toLowerCase().includes(n))].sort((e,t)=>Number(t.enabled)-Number(e.enabled)||e.name.localeCompare(t.name))}function Ep(e){return e.args,`/${e.name} `}function Dp(e,t=!1){let n=t?e.argsEn??e.args:e.args;return n?`/${e.name} ${n}`:`/${e.name}`}function Op(e){let t=e.trim();if(!t.startsWith(`/`))return!1;let n=(t.slice(1).split(/\s+/)[0]??``).toLowerCase();return Sp.some(e=>e.name===n&&e.kind===`app`)}async function kp(e,t){let n=e.trim();if(!n.startsWith(`/`))return{handled:!1};let[r,...i]=n.slice(1).split(/\s+/),a=(r??``).toLowerCase(),o=i.join(` `).trim(),s=Sp.find(e=>e.name===a);if(!s||s.kind!==`app`)return{handled:!1};switch(a){case`new`:return zl(),o&&window.setTimeout(()=>So(o),80),{handled:!0};case`name`:{let e=t?.active.conversationId??null;return e?o?(Gl(e,o),Z({text:J(`已把会话改名为「${o}」`,`Renamed the session to “${o}”`)}),{handled:!0}):(Z({text:J(`用法:/name <名称>`,`Usage: /name <name>`)}),{handled:!0}):(Z({text:J(`先打开一个会话再改名`,`Open a session before renaming it`)}),{handled:!0})}case`model`:{let e=t?.models??[];if(e.length===0)return Z({text:J(`模型列表还没就绪,等一下再试`,`The model list is not ready yet — try again in a moment`)}),{handled:!0};if(!o)return Z({text:J(`用法:/model <模型名或 id>`,`Usage: /model <model name or id>`)}),{handled:!0};let n=o.toLowerCase(),r=e.find(e=>e.id.toLowerCase()===n)??e.find(e=>e.label.toLowerCase()===n)??e.find(e=>e.id.toLowerCase().includes(n)||e.label.toLowerCase().includes(n));return r?(lu(r.id,t?.active.conversationId??null),Z({text:J(`已切到 ${r.label}`,`Switched to ${r.label}`)}),{handled:!0}):(Z({text:J(`没找到模型「${o}」`,`No model named “${o}”`)}),{handled:!0})}case`thinking`:{let e=t?.thinkingLevels??[];return o?e.length>0&&!e.includes(o)?(Z({text:J(`这个模型没有「${o}」档:${e.join(` / `)}`,`This model has no “${o}” level: ${e.join(` / `)}`)}),{handled:!0}):($l(o),Z({text:J(`思考强度已设为 ${o}`,`Thinking level set to ${o}`)}),{handled:!0}):(Z({text:J(`用法:/thinking <${e.join(` | `)||`off | low | medium | high | xhigh | max`}>`,`Usage: /thinking <${e.join(` | `)||`off | low | medium | high | xhigh | max`}>`)}),{handled:!0})}case`copy`:{let e=[...Vo()].reverse().find(e=>e.role===`assistant`),t=(e?yp(e):``).trim();return t?(Z({text:await xp(t)?J(`已复制最后一条回复`,`Copied the last reply`):J(`复制失败(浏览器不给权限)`,`Copy failed (the browser denied permission)`)}),{handled:!0}):(Z({text:J(`没有可复制的助手消息`,`No assistant message to copy`)}),{handled:!0})}case`session`:{let e=t?.sessionStats??null;return e?(Z({text:J(`消息 ${e.userMessages}+${e.assistantMessages} · 工具 ${e.toolCalls} · 输入 ${e.inputTokens} / 输出 ${e.outputTokens} tokens`,`Messages ${e.userMessages}+${e.assistantMessages} · tools ${e.toolCalls} · in ${e.inputTokens} / out ${e.outputTokens} tokens`)}),{handled:!0}):(Z({text:J(`还没有会话统计(跑一轮之后才有)`,`No session stats yet (they appear after a turn)`)}),{handled:!0})}case`resume`:return kl(),Z({text:J(`已请求刷新会话列表`,`Requested a conversation list refresh`)}),{handled:!0};default:return{handled:!1}}}function Ap({commands:e,active:t,onPick:n,onHover:r,skills:i=null}){let a=Y(),{language:o}=Ae(),s=(0,C.useRef)(null);return(0,C.useEffect)(()=>{(s.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]),(0,Q.jsxs)(`div`,{className:`slash-panel`,role:`listbox`,"aria-label":a(`斜杠命令`,`Slash commands`),children:[(0,Q.jsxs)(`div`,{className:`slash-head`,children:[(0,Q.jsx)(`span`,{children:i===null?a(`↑↓ 选择 · Enter/Tab 补全 · Esc 关闭`,`↑↓ to choose · Enter/Tab to complete · Esc to close`):a(`↑↓ 选择技能 · Enter/Tab 插入 · Esc 关闭`,`↑↓ to choose a skill · Enter/Tab to insert · Esc to close`)}),(0,Q.jsx)(`span`,{className:`slash-count`,children:i===null?(0,Q.jsxs)(Q.Fragment,{children:[e.length,` `,a(`条命令`,`commands`)]}):(0,Q.jsxs)(Q.Fragment,{children:[i.length,` `,a(`个技能`,`skills`)]})})]}),(0,Q.jsxs)(`div`,{className:`slash-list`,ref:s,children:[i===null?null:i.map((e,i)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:`slash-row${i===t?` slash-row-on`:``}`,onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n({name:`skill:${e.name}`,kind:`agent`,description:e.description})},children:[(0,Q.jsx)(`span`,{className:`slash-name mono`,children:`/skill:${e.name}`}),(0,Q.jsx)(`span`,{className:`slash-kind${e.enabled?``:` slash-kind-off`}`,children:e.enabled?a(`已启用`,`Enabled`):a(`已停用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`slash-desc`,children:e.description||e.name})]},e.id)),i===null&&e.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:a(`没有匹配的命令`,`No matching commands`)}):null,i!==null&&i.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:a(`没有匹配的技能`,`No matching skills`)}):null,(i===null?e:[]).map((e,i)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":i,role:`option`,"aria-selected":i===t,className:`slash-row${i===t?` slash-row-on`:``}`,onMouseEnter:()=>r(i),onMouseDown:t=>{t.preventDefault(),n(e)},children:[(0,Q.jsx)(`span`,{className:`slash-name mono`,children:Dp(e,o===`en`)}),(0,Q.jsx)(`span`,{className:`slash-kind${e.kind===`agent`?` slash-kind-agent`:``}`,children:e.kind===`agent`?a(`发给 Agent`,`Sent to agent`):a(`本地`,`Runs here`)}),(0,Q.jsx)(`span`,{className:`slash-desc`,children:a(e.description,e.descriptionEn)})]},e.name))]})]})}var jp=4,Mp=8;function Np(e,t,n){let r=Math.max(n,window.innerWidth-t.width-n),i=Math.max(n,window.innerHeight-t.height-n);return{x:Math.min(Math.max(n,e.x),r),y:Math.min(Math.max(n,e.y),i)}}function Pp(e){let t=Yr(e);if(!t)return null;try{let e=JSON.parse(t);return typeof e.x!=`number`||typeof e.y!=`number`||!Number.isFinite(e.x)||!Number.isFinite(e.y)?null:{x:e.x,y:e.y}}catch{return null}}function Fp(e){let t=e.edge??Mp,n=e.active??!0,r=(0,C.useRef)(null),[i,a]=(0,C.useState)(()=>Pp(e.storageKey)),[o,s]=(0,C.useState)(!1),c=(0,C.useRef)(null),l=()=>{let e=r.current?.getBoundingClientRect();e&&a(n=>{if(!n)return n;let r=Np(n,{width:e.width,height:e.height},t);return r.x===n.x&&r.y===n.y?n:r})};return(0,C.useEffect)(()=>{n&&l()},[n,i===null]),(0,C.useEffect)(()=>{if(n)return window.addEventListener(`resize`,l),()=>window.removeEventListener(`resize`,l)},[n]),{ref:r,pos:i,dragging:o,style:i?{left:`${i.x}px`,top:`${i.y}px`,right:`auto`,bottom:`auto`,transform:`none`}:void 0,onPointerDown:t=>{if(t.button!==0||e.ignoreSelector&&t.target.closest(e.ignoreSelector))return;let n=r.current?.getBoundingClientRect();n&&(t.currentTarget.setPointerCapture(t.pointerId),c.current={pointerId:t.pointerId,offsetX:t.clientX-n.left,offsetY:t.clientY-n.top,startX:t.clientX,startY:t.clientY,moved:!1},s(!0))},onPointerMove:e=>{let n=c.current;if(!n||n.pointerId!==e.pointerId)return;if(!n.moved){if(Math.hypot(e.clientX-n.startX,e.clientY-n.startY)<jp)return;n.moved=!0}let i=r.current?.getBoundingClientRect();a(Np({x:e.clientX-n.offsetX,y:e.clientY-n.offsetY},{width:i?.width??0,height:i?.height??0},t))},onPointerUp:t=>{let n=c.current;if(!n||n.pointerId!==t.pointerId||(c.current=null,s(!1),!n.moved))return!1;let i=r.current?.getBoundingClientRect();return i&&Xr(e.storageKey,JSON.stringify({x:Math.round(i.left),y:Math.round(i.top)})),!0},onPointerCancel:e=>{let t=c.current;t&&t.pointerId===e.pointerId&&(c.current=null,s(!1))},resetPosition:()=>{a(null),Xr(e.storageKey,``)}}}var Ip=`pop-agent.voice.badge.pos`;function Lp({inline:e=!1}={}){let t=Y(),n=$i(),r=ta(),i=Fp({storageKey:Ip}),a=!e,o=n===`listening`,s=n===`sending`,c=s?t(`正在发送…`,`Sending…`):o?t(`正在听…说完停 2.2 秒会自动发送;点一下立刻停止并保留文字`,`Listening… it auto-sends after 2.2s of silence; tap to stop and keep the text`):t(`点一下开始语音输入(按住可拖到任意位置,右键回到默认位置)`,`Tap to start voice input (drag to move, right-click to reset)`),l=()=>{s||Ea()};return(0,Q.jsxs)(`button`,{type:`button`,ref:i.ref,className:`voice-mic${e?` is-inline`:``}${o?` is-listening`:``}${s?` is-sending`:``}${i.dragging?` is-dragging`:``}`,style:a?i.style:void 0,onPointerDown:a?i.onPointerDown:void 0,onPointerMove:a?i.onPointerMove:void 0,onPointerUp:e=>{a&&i.onPointerUp(e)||l()},onPointerCancel:a?i.onPointerCancel:void 0,onClick:e=>{e.detail===0&&l()},onContextMenu:e=>{a&&(e.preventDefault(),i.resetPosition())},"aria-pressed":o||s,"aria-label":c,title:c,children:[o&&r>.02?(0,Q.jsx)(`span`,{className:`voice-mic-ring`,style:{"--voice-progress":String(r)},"aria-hidden":`true`}):null,(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:o||s?`■`:`🎤`})]})}var Rp={go:{label:`GO`,tone:`go`},ts:{label:`TS`,tone:`ts`},tsx:{label:`TS`,tone:`ts`},mts:{label:`TS`,tone:`ts`},cts:{label:`TS`,tone:`ts`},js:{label:`JS`,tone:`js`},jsx:{label:`JS`,tone:`js`},mjs:{label:`JS`,tone:`js`},cjs:{label:`JS`,tone:`js`},vue:{label:`VUE`,tone:`js`},svelte:{label:`SV`,tone:`js`},json:{label:`{}`,tone:`json`},jsonc:{label:`{}`,tone:`json`},json5:{label:`{}`,tone:`json`},py:{label:`PY`,tone:`py`},pyi:{label:`PY`,tone:`py`},sh:{label:`SH`,tone:`sh`},bash:{label:`SH`,tone:`sh`},zsh:{label:`SH`,tone:`sh`},fish:{label:`SH`,tone:`sh`},ps1:{label:`PS`,tone:`sh`},md:{label:`MD`,tone:`md`},markdown:{label:`MD`,tone:`md`},mdx:{label:`MD`,tone:`md`},css:{label:`CSS`,tone:`style`},scss:{label:`CSS`,tone:`style`},sass:{label:`CSS`,tone:`style`},less:{label:`CSS`,tone:`style`},html:{label:`<>`,tone:`markup`},htm:{label:`<>`,tone:`markup`},xml:{label:`<>`,tone:`markup`},svg:{label:`<>`,tone:`markup`},yaml:{label:`YML`,tone:`data`},yml:{label:`YML`,tone:`data`},toml:{label:`TOML`,tone:`data`},ini:{label:`INI`,tone:`data`},env:{label:`ENV`,tone:`data`},conf:{label:`CFG`,tone:`data`},csv:{label:`CSV`,tone:`data`},sql:{label:`SQL`,tone:`sql`},rs:{label:`RS`,tone:`rs`},java:{label:`JAVA`,tone:`jvm`},kt:{label:`KT`,tone:`jvm`},kts:{label:`KT`,tone:`jvm`},gradle:{label:`GRD`,tone:`jvm`},c:{label:`C`,tone:`c`},h:{label:`C`,tone:`c`},cc:{label:`C++`,tone:`c`},cpp:{label:`C++`,tone:`c`},hpp:{label:`C++`,tone:`c`},cs:{label:`C#`,tone:`c`},txt:{label:`TXT`,tone:`text`},log:{label:`LOG`,tone:`text`},lock:{label:`LOCK`,tone:`text`}};function zp(e){let t=e.toLowerCase();if(t===`dockerfile`||t.startsWith(`dockerfile.`))return{label:`DOCK`,tone:`sh`};if(t===`makefile`||t===`gnumakefile`)return{label:`MK`,tone:`sh`};if(t===`.gitignore`||t===`.gitattributes`)return{label:`GIT`,tone:`text`};if(t===`go.mod`||t===`go.sum`)return{label:`GO`,tone:`go`};if(t===`package.json`||t===`tsconfig.json`)return{label:`{}`,tone:`json`};let n=t.lastIndexOf(`.`);return n<0?null:Rp[t.slice(n+1)]??null}var Bp={browse:{zh:`添加`,en:`Add`},recent:{zh:`最近用过`,en:`Recent`},result:null};function Vp({rows:e,active:t,loading:n=!1,error:r=null,onPick:i,onHover:a,onBrowse:o,onOpenFile:s}){let c=Y(),l=(0,C.useRef)(null);(0,C.useEffect)(()=>{(l.current?.querySelector(`[data-index="${t}"]`))?.scrollIntoView({block:`nearest`})},[t]);let u=null;return(0,Q.jsxs)(`div`,{className:`slash-panel mention-panel`,role:`listbox`,"aria-label":c(`@ 提及文件`,`Mention a file`),children:[(0,Q.jsxs)(`div`,{className:`slash-head`,children:[(0,Q.jsx)(`span`,{children:c(`↑↓ 选择 · Enter/Tab 插入 · Esc 关闭`,`↑↓ to choose · Enter/Tab to insert · Esc to close`)}),(0,Q.jsx)(`span`,{className:`slash-count`,children:n?c(`搜索中…`,`Searching…`):`${e.length} ${c(`项`,`items`)}`})]}),(0,Q.jsxs)(`div`,{className:`slash-list`,ref:l,children:[e.map((e,n)=>{let r=e.group===u?null:Bp[e.group];return u=e.group,(0,Q.jsxs)(`div`,{children:[r?(0,Q.jsx)(`div`,{className:`mention-group`,children:c(r.zh,r.en)}):null,(0,Q.jsx)(`button`,{type:`button`,"data-index":n,role:`option`,"aria-selected":n===t,className:`slash-row mention-row${n===t?` slash-row-on`:``}`,title:e.kind===`browse`?void 0:`@${e.path}`,onMouseEnter:()=>a(n),onMouseDown:t=>{t.preventDefault(),e.kind===`browse`?o(e.target):i(e)},children:e.kind===`browse`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:e.target===`file`?`📄`:`📁`}),(0,Q.jsx)(`span`,{className:`mention-name`,children:e.target===`file`?c(`文件和文件夹`,`Files and folders`):c(`文件夹`,`Folder`)}),(0,Q.jsx)(`span`,{className:`mention-path`,children:e.target===`file`?c(`从这台电脑选择`,`Pick from this computer`):c(`选择一个文件夹`,`Pick a folder`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Hp,{name:e.name,isDir:e.isDir}),(0,Q.jsx)(`span`,{className:`mention-name mono`,children:e.name}),(0,Q.jsx)(`span`,{className:`mention-path`,children:e.path}),s&&!e.isDir?(0,Q.jsx)(`span`,{className:`mention-open`,role:`button`,title:c(`在右侧面板打开这个文件`,`Open this file in the side panel`),"aria-label":c(`在右侧面板打开`,`Open in the side panel`),onMouseDown:t=>{t.preventDefault(),t.stopPropagation(),s(e.path)},children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M9.5 2.5H13.5V6.5`}),(0,Q.jsx)(`path`,{d:`M13.5 2.5 8 8`}),(0,Q.jsx)(`path`,{d:`M12.5 9.5V13.5H2.5V3.5H6.5`})]})}):null]})})]},e.kind===`browse`?`browse:${e.target}`:`${e.group}:${e.path}`)}),e.length===0?(0,Q.jsx)(`div`,{className:`slash-empty`,children:r??(n?c(`搜索中…`,`Searching…`):c(`没有匹配的文件`,`No matching files`))}):r?(0,Q.jsx)(`div`,{className:`slash-empty`,children:r}):null]})]})}function Hp({name:e,isDir:t}){if(t)return(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:`📁`});let n=zp(e);return n?(0,Q.jsx)(`span`,{className:`filetree-type filetype-${n.tone}`,"aria-hidden":`true`,children:n.label}):(0,Q.jsx)(`span`,{className:`mention-icon`,"aria-hidden":`true`,children:`·`})}var Up=160,Wp=new Set([``,` `,` `,`
15
+ `,`(`,`(`,`【`,`[`,`「`,`《`,`"`,`'`,"`",`:`,`:`]);function Gp(e,t){let n=Math.min(Math.max(t,0),e.length),r=-1;for(let t=n-1;t>=0;--t){let n=e[t]??``;if(n===`@`){r=t;break}if(/\s/.test(n))return null}if(r<0)return null;let i=r===0?``:e[r-1]??``;if(!Wp.has(i))return null;let a=e.slice(r+1,n);return a.length>Up?null:{start:r,end:n,term:a}}function Kp(e,t,n){return Jp(e,t.start,t.end,n)}function qp(e,t,n){let r=Math.min(Math.max(t,0),e.length);return Jp(e,r,r,n)}function Jp(e,t,n,r){let i=`@${r}`,a=e.slice(n),o=/^\s/.test(a),s=a===``||!o?` `:``;return{text:e.slice(0,t)+i+s+a,caret:t+i.length+(s===``&&o?1:s.length)}}function Yp(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`\\\\`)}function Xp(e,t){let n=j(e),r=j(t);if(n===``||r===``)return null;let i=/^[A-Za-z]:/.test(n),a=n.split(/[\\/]+/).filter(e=>e!==``),o=r.split(/[\\/]+/).filter(e=>e!==``);if(a.length===0||a.length>o.length)return null;for(let e=0;e<a.length;e+=1){let t=a[e]??``,n=o[e]??``;if(i?t.toLowerCase()!==n.toLowerCase():t!==n)return null}return o.slice(a.length).join(`/`)}function Zp(e,t){let n=e.trim();if(n===``||!Yp(n))return n;if(t){let e=Xp(t,n);if(e!==null)return e===``?`.`:e}return n}function Qp(e){let t=[];if(e.term.trim()===``){t.push({kind:`browse`,target:`file`,group:`browse`}),t.push({kind:`browse`,target:`dir`,group:`browse`});for(let n of e.recent.slice(0,40-t.length))t.push({kind:`file`,name:D(n.path),path:n.path,isDir:n.isDir,group:`recent`});return t}for(let n of e.results.slice(0,40))t.push({kind:`file`,name:D(n.path),path:n.path,isDir:n.isDir,group:`result`});return t}var $p=180,em=`pop-agent:mention-recent`,tm=24,nm=[];function rm(){if(typeof localStorage>`u`)return[];try{let e=JSON.parse(localStorage.getItem(em)??`[]`);return Array.isArray(e)?e.filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.root==`string`&&typeof t.path==`string`}).map(e=>({root:e.root,path:e.path,isDir:e.isDir===!0})):[]}catch{return[]}}function im(e,t){return+!e.toLowerCase().startsWith(t)}function am(e,t){let[n,r]=(0,C.useState)(nm),[i,a]=(0,C.useState)(!1),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(rm);(0,C.useEffect)(()=>{try{localStorage.setItem(em,JSON.stringify(c))}catch{}},[c]);let u=e??``,d=(0,C.useMemo)(()=>c.filter(e=>e.root===u).map(({path:e,isDir:t})=>({path:e,isDir:t})),[c,u]),f=(0,C.useCallback)(e=>{l(t=>{let n=t.filter(t=>t.root!==u||t.path!==e.path);return[{root:u,path:e.path,isDir:e.isDir},...n].slice(0,tm)})},[u]);return(0,C.useEffect)(()=>{let n=(t??``).trim();if(t===null||!e||n===``){r(nm),a(!1),s(null);return}let i=Math.max(n.lastIndexOf(`/`),n.lastIndexOf(`\\`)),o=i>=0?n.slice(i+1):n;if(o===``){r(nm),a(!1),s(null);return}let c=!1;a(!0);let l=setTimeout(()=>{(async()=>{try{let t=await fetch(`/api/files/search?q=${encodeURIComponent(o)}&root=${encodeURIComponent(e)}`),a=await t.json();if(c)return;if(!t.ok){r(nm),s(a.error?.message??`HTTP ${t.status}`);return}let l=a.entries??[],u=i<0?l:l.filter(e=>e.path.toLowerCase().includes(n.toLowerCase())),d=o.toLowerCase(),f=[...u].sort((e,t)=>im(e.name,d)-im(t.name,d));r(f.map(e=>({path:e.path,isDir:e.isDir===!0}))),s(null)}catch(e){if(c)return;r(nm),s(e instanceof Error?e.message:String(e))}finally{c||a(!1)}})()},$p);return()=>{c=!0,clearTimeout(l),a(!1)}},[e,t]),{results:n,recent:d,loading:i,error:o,remember:f}}function om(e){return e.sessions.reduce((e,t)=>Math.max(e,t.startedAt),0)}function sm(e){let t=new Map;return e.forEach((e,n)=>{t.has(e)||t.set(e,n)}),t}function cm(e,t){let n=sm(t.pinned),r=sm(t.order),i=e.filter(e=>n.has(e.cwd)).sort((e,t)=>(n.get(e.cwd)??0)-(n.get(t.cwd)??0)),a=e.filter(e=>!n.has(e.cwd)),o=a.filter(e=>r.has(e.cwd)).sort((e,t)=>(r.get(e.cwd)??0)-(r.get(t.cwd)??0)),s=a.filter(e=>!r.has(e.cwd)).sort((e,t)=>om(t)-om(e)||e.cwd.localeCompare(t.cwd));return[...i,...s,...o]}function lm(e){let{visible:t,pinned:n,from:r,target:i,after:a}=e;if(r===i||!t.includes(r))return null;let o=new Set(n);n.includes(i)?o.add(r):o.delete(r);let s=t.filter(e=>e!==r),c=s.indexOf(i);return c<0?null:(s.splice(c+ +!!a,0,r),{pinned:s.filter(e=>o.has(e)),order:s.filter(e=>!o.has(e))})}function um(e){let t=e.trim();for(let e of[`"`,`'`])t.length>=2&&t.startsWith(e)&&t.endsWith(e)&&(t=t.slice(1,-1).trim());return/^[A-Za-z]:$/.test(t)?`${t}\\`:t}async function dm(e){let t=await e.text();try{return{ok:!0,body:JSON.parse(t)}}catch{return{ok:!1,message:t.trimStart().startsWith(`<`)?J(`服务端上还没有这个接口(HTTP ${e.status})—— 服务可能在跑旧版本,重启一下就好`,`The server does not have this endpoint yet (HTTP ${e.status}) — it may be an older build, restart it`):J(`服务端返回的不是 JSON(HTTP ${e.status})`,`The server did not return JSON (HTTP ${e.status})`)}}}function fm({onClose:e,onPick:t}){let n=Y(),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)([]),[d,f]=(0,C.useState)([]),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!0),[_,v]=(0,C.useState)(!1),y=async e=>{g(!0),m(null);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await dm(t);if(!n.ok){m(n.message);return}let r=n.body;if(!t.ok){m(r.error?.message??`HTTP ${t.status}`);return}i(r.path??``),o(r.path??``),c(r.parent??null),u(r.entries??[]),f(r.drives??[])}catch(e){m(e instanceof Error?e.message:String(e))}finally{g(!1)}};(0,C.useEffect)(()=>{y()},[]);let b=n=>{t?t(n):zl(n),e()},x=e=>void y(um(e)),S=async()=>{v(!0),m(null);try{let e=await fetch(`/api/fs/pick-dir`,{method:`POST`}),t=await dm(e);if(!t.ok){m(t.message);return}let r=t.body;if(!e.ok){m(r.error?.message??r.message??`HTTP ${e.status}`);return}if(r.unsupported){m(r.message??n(`这台机器上开不出目录选择框,请在下面直接浏览`,`No folder picker on this machine — browse below instead`));return}if(!r.path)return;b(r.path)}catch(e){m(e instanceof Error?e.message:String(e))}finally{v(!1)}};return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`新建项目`),children:(0,Q.jsxs)(`div`,{className:`modal new-project`,children:[(0,Q.jsxs)(`div`,{className:`new-project-head`,children:[(0,Q.jsx)(`strong`,{children:n(`🗂 本地目录`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:e,title:n(`关闭`),children:`✕`})]}),(0,Q.jsxs)(`div`,{className:`new-project-bar`,children:[(0,Q.jsx)(`input`,{className:`new-project-input mono`,value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&x(a)},placeholder:M()?n(`C:\\绝对路径`,`C:\\absolute\\path`):n(`/绝对路径`,`/absolute/path`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>x(a),disabled:h,children:n(`跳转`,`Go`)})]}),(0,Q.jsxs)(`div`,{className:`new-project-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void S(),disabled:_,title:n(`在服务端所在的电脑上打开系统自带的文件夹选择框`,`Open your computer's own folder picker (on the machine running the server)`),children:_?n(`📂 选择中…`,`📂 Choosing…`):n(`📂 浏览电脑…`,`📂 Browse computer…`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void y(s??void 0),disabled:!s||h,title:n(`回到上一级目录`,`Go to the parent folder`),children:n(`↑ 上级目录`,`↑ Up one level`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-send`,onClick:()=>b(r||um(a)),disabled:h||r===``&&a.trim()===``,children:n(`选择当前目录`,`Use this folder`)})]}),p?(0,Q.jsx)(`div`,{className:`side-error`,children:p}):null,_?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:n(`文件夹选择框已经在你电脑上打开,如果没看到,它可能被浏览器/别的窗口挡住了(Alt+Tab 找一下)`,`The folder picker is open on your computer — if you can't see it, it may be behind another window (Alt+Tab)`)}):null,d.length>1?(0,Q.jsx)(`div`,{className:`new-project-drives`,children:d.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${e.path===r?` is-current`:``}`,onClick:()=>void y(e.path),title:e.path,children:e.name},e.path))}):null,(0,Q.jsxs)(`div`,{className:`new-project-list`,children:[h?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:n(`读取中…`)}):null,!h&&l.length===0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[n(`这个目录下没有子目录`,`No subfolders here`),s?n(` —— 可以点上面的「↑ 上级目录」往外走`,` — use ↑ Up one level above`):null]}):null,l.map(e=>(0,Q.jsxs)(`div`,{className:`new-project-row`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`new-project-name`,onClick:()=>void y(e.path),title:e.path,children:[(0,Q.jsx)(`span`,{className:`new-project-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),e.name]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>b(e.path),children:n(`选择`,`Choose`)})]},e.path))]}),(0,Q.jsx)(`div`,{className:`new-project-foot`,children:(0,Q.jsx)(`span`,{className:`side-panel-hint`,children:n(`「选择」= 在这个目录下新建一个会话(项目随之出现),不会创建或修改任何文件。`,`Choose = start a new conversation in this folder (the project appears with it); no files are created or changed.`)})})]})})}function pm({workspace:e,ephemeral:t,onChange:n,onEphemeralChange:r}){let i=Y(),a=Ro(e=>e.snapshot),o=a?.settings.projectPrefs??{order:[],pinned:[],aliases:{},hidden:[]},s=cm(a?.piProjects??[],o).map(e=>({cwd:e.cwd,label:o.aliases[e.cwd]||e.name||D(e.cwd)||e.cwd})),c=e===null?null:j(e),l=e=>c!==null&&j(e)===c,u=e!==null&&!s.some(e=>l(e.cwd))?[{cwd:e,label:D(e)||e,fresh:!0},...s.map(e=>({...e,fresh:!1}))]:s.map(e=>({...e,fresh:!1})),d=u.find(e=>l(e.cwd))??null,f=ep(e),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(null),[y,b]=(0,C.useState)(!1),[x,S]=(0,C.useState)(``),[w,T]=(0,C.useState)(-1),[E,O]=(0,C.useState)(!1),k=(0,C.useRef)(null),A=a?.engineCapabilities.ephemeralChat===!0,M=t&&A,N=e=>{n(e),g(!1),S(``),T(-1)},P=x.trim().toLowerCase(),F=P?u.filter(e=>e.label.toLowerCase().includes(P)||e.cwd.toLowerCase().includes(P)):u;return(0,C.useEffect)(()=>{w<0||(k.current?.querySelector(`[data-index="${w}"]`))?.scrollIntoView({block:`nearest`})},[w]),(0,Q.jsxs)(`div`,{className:`new-session-scope`,children:[M?null:(0,Q.jsxs)(`button`,{type:`button`,ref:m,className:`new-scope-chip${d?``:` new-scope-chip-muted`}`,title:e??i(`还没有项目:这条会话会跟在服务端的工作区里`,`No project yet: this session stays in the server workspace`),"aria-haspopup":`listbox`,"aria-expanded":h,onClick:()=>g(e=>!e),children:[(0,Q.jsx)(`span`,{className:`new-scope-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:d?.label??i(`选择项目`,`Choose a project`)}),(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,className:`new-scope-caret`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4.4 6.4 3.6 3.6 3.6-3.6`})})]}),t&&A?(0,Q.jsx)(`button`,{type:`button`,className:`new-scope-chip new-scope-chip-ephemeral`,title:i(`临时会话:只活在内存里,关闭即消失(点一下取消)· 工作目录:${e??`跟服务端工作区`}`,`Temporary session: in-memory only, gone on close (click to cancel) · working dir: ${e??`server workspace`}`),onClick:()=>r(!1),children:(0,Q.jsx)(`span`,{className:`new-scope-label`,children:M?i(`💬 临时会话(不保存)`,`💬 Temp session (not saved)`):i(`💬 不保存`,`💬 Not saved`)})}):null,f.isRepo&&f.branch&&!M?(0,Q.jsxs)(`button`,{type:`button`,ref:v,className:`new-scope-chip`,title:i(`当前分支:${f.branch}(点一下切换)`,`Current branch: ${f.branch} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":y,onClick:()=>b(e=>!e),children:[(0,Q.jsx)(tp,{className:`new-scope-icon new-scope-branch-icon`}),(0,Q.jsx)(`span`,{className:`new-scope-label`,children:f.branch})]}):null,h&&p?(0,Q.jsxs)(qd,{anchor:p,className:`proj-menu new-scope-menu`,align:`center`,style:{width:Math.min(320,Math.max(220,p.getBoundingClientRect().width+40))},onClose:()=>{g(!1),S(``),T(-1)},children:[(0,Q.jsx)(`input`,{className:`new-scope-search`,value:x,autoFocus:!0,placeholder:i(`搜索项目`,`Search projects`),"aria-label":i(`搜索项目`,`Search projects`),onChange:e=>{S(e.target.value),T(-1)},onKeyDown:e=>{if(e.key===`Escape`)g(!1),S(``),T(-1);else if(e.key===`ArrowDown`)e.preventDefault(),T(e=>F.length===0?-1:Math.min(F.length-1,e+1));else if(e.key===`ArrowUp`)e.preventDefault(),T(e=>Math.max(0,e-1));else if(e.key===`Enter`){let e=F[w>=0?w:0];e&&N(e.cwd)}e.stopPropagation()}}),(0,Q.jsxs)(`div`,{className:`new-scope-list`,ref:k,children:[F.map((e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-index":t,className:`proj-menu-item files-root-option${l(e.cwd)?` files-root-option-on`:``}${t===w?` new-scope-item-active`:``}`,title:e.fresh?i(`${e.cwd}(刚选的目录:发出第一条消息后才会成为项目)`,`${e.cwd} (just picked: becomes a project after the first message)`):e.cwd,onClick:()=>N(e.cwd),onMouseEnter:()=>T(t),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:l(e.cwd)?`✓`:``}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:!1})}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:e.label})]},e.cwd)),F.length===0?(0,Q.jsx)(`div`,{className:`new-scope-empty`,children:P?i(`没有匹配的项目`,`No matching project`):i(`还没有任何项目:点下面的「新建项目」选一个目录。`,`No projects yet — pick a folder with “New project” below.`)}):null]}),(0,Q.jsxs)(`div`,{className:`new-scope-foot`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option`,onClick:()=>{g(!1),S(``),T(-1),O(!0)},children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(op,{})}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:i(`新建项目`,`New project`)})]}),A?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${t?` files-root-option-on`:``}`,title:i(`建成临时会话:不写会话文件、不进历史,关闭即消失(目录仍用上面选的项目)`,`Create a temporary session: no session file, not in history, gone on close (still uses the project above)`),onClick:()=>{r(!t),g(!1),S(``),T(-1)},children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:t?`✓`:``}),(0,Q.jsx)(`span`,{className:`new-scope-menu-icon new-scope-menu-icon-emoji`,"aria-hidden":`true`,children:`💬`}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:i(`临时会话(不保存)`,`Temporary session (not saved)`)})]}):null]})]}):null,y&&_?(0,Q.jsx)(sp,{anchor:_,git:f,align:`center`,onClose:()=>b(!1)}):null,E?(0,Q.jsx)(fm,{onClose:()=>O(!1),onPick:e=>{n(e),O(!1)}}):null]})}var mm=240,hm=700;function gm(e){return e<1024?`${e}B`:e<1048576?`${Math.round(e/1024)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function _m({running:e,conversationId:t,surface:n,newSession:r=null,tempChat:i=!1,annotations:a=[],onAnnotationsSent:o,onOpenFile:s,annotationSummary:c=null}){let l=Y(),{language:u}=Ae(),d=Lo(),f=n?n.draft:d.draft,p=n?n.setDraft:So,m=n?n.snapshot:d.snapshot,h=!n&&d.creating,[g,_]=(0,C.useState)([]),[v,y]=(0,C.useState)(!1),[b,x]=(0,C.useState)(null),S=(0,C.useRef)(t);S.current=t,(0,C.useEffect)(()=>{_([]),x(null),y(!1)},[t]),(0,C.useEffect)(()=>{na()&&Ta()},[t]);let w=(0,C.useRef)(null),T=(0,C.useRef)(null),E=(0,C.useRef)(null),D=(0,C.useCallback)(()=>{let e=w.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,mm)}px`)},[]);(0,C.useLayoutEffect)(()=>{D()},[f,D]),(0,C.useLayoutEffect)(()=>{let e=T.current,t=E.current;if(!e||!t)return;let n=()=>{let n=t.getBoundingClientRect();e.style.setProperty(`--composer-actions-w`,`${Math.ceil(n.width)}px`),e.style.setProperty(`--composer-actions-h`,`${Math.ceil(n.height)}px`),D()};n();let r=new ResizeObserver(n);return r.observe(t),()=>r.disconnect()},[D]);let O=(0,C.useRef)(0),k=(0,C.useRef)(!1);(0,C.useEffect)(()=>{let e=k.current&&!h;if(k.current=h,!e||!w.current)return;let t=document.activeElement;(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t!==w.current||w.current.focus()},[h]);let A=n?null:m?.conversations.find(e=>e.id===m.active.conversationId)?.workspace??m?.files?.root??null,[j]=bp(Pr,Lr,Ir),M=Cp(f),N=M?.mode===`commands`?wp(M.term):[],[P,F]=(0,C.useState)(null),I=async()=>{try{let e=(await(await fetch(`/api/skills`)).json()).skills??[];return F(e),e}catch{return F([]),[]}};(0,C.useEffect)(()=>{M?.mode===`skills`&&P===null&&I()},[M?.mode,P]);let L=M?.mode===`skills`?Tp(P??[],M.term):null,[R,z]=(0,C.useState)(0),B=L===null?N.length:L.length,[V,H]=(0,C.useState)(!1),U=M===null;(0,C.useEffect)(()=>{U&&H(!1)},[U]);let W=!V&&M!==null&&(B>0||L!==null);(0,C.useEffect)(()=>z(0),[M?.mode,M?.term]);let ee=e=>{p(Ep(e)),requestAnimationFrame(()=>w.current?.focus())},G=e=>{p(`/skill:${e} `),requestAnimationFrame(()=>w.current?.focus())},K=r?r.workspace:m?.files?.root??null,[te,ne]=(0,C.useState)(0),re=(0,C.useRef)(0),ie=(0,C.useRef)(f);ie.current=f,(0,C.useEffect)(()=>{let e=()=>{let e=w.current;if(!e||document.activeElement!==e)return;let t=e.selectionStart??0;re.current=t,ne(t)};return document.addEventListener(`selectionchange`,e),()=>document.removeEventListener(`selectionchange`,e)},[]);let ae=(0,C.useRef)(null),oe=(0,C.useRef)(null),se=(0,C.useRef)(e);se.current=e;let ce=(0,C.useRef)(m);ce.current=m;let le=(0,C.useRef)(!1);(0,C.useEffect)(()=>{if(!n)return ra({get conversationId(){return S.current??null},onStart:e=>{let t=w.current,n=e??ie.current,r=t?.selectionStart??n.length;ae.current={head:n.slice(0,r),tail:n.slice(r)}},onText:e=>{let t=ae.current;if(!t)return;let n=`${t.head}${e}${t.tail}`;p(n);let r=t.head.length+e.length;re.current=r;let i=w.current;i&&document.activeElement===i&&i.setSelectionRange(r,r)},onEnd:()=>{ae.current=null},submitVoice:()=>{let e=se.current,t=ce.current?.engineCapabilities?.steer!==!1,n=ie.current.trim().length;if(Ut(`submit:decide`,{running:e,steerCapable:t,submitMode:vi().submitMode,draftLen:n}),!e)oe.current?.(`now`);else{if(vi().submitMode===`steer`){if(t){oe.current?.(`steer`);return}le.current||(le.current=!0,Z({text:l(`当前引擎不支持插队(只有 Pi 引擎有),这句改成排队发送`,`This engine can't steer (only Pi can) — sending this one as queued instead`)}))}oe.current?.(`queue`)}}}),()=>{ra(null),na()&&Ta()}},[n,p,l]);let[ue,de]=(0,C.useState)(null),[q,fe]=(0,C.useState)(0),[pe,me]=(0,C.useState)(!1),he=Gp(f,te),ge=he&&he.start!==ue?he:null,_e=am(K,ge?ge.term:null),ve=ge===null?[]:Qp({term:ge.term,results:_e.results,recent:_e.recent}),ye=Math.min(q,Math.max(0,ve.length-1));(0,C.useEffect)(()=>fe(0),[ge?.term,ge?.start]);let be=ge===null?null:ge.start;(0,C.useEffect)(()=>{if(!W&&be===null)return;let e=()=>{be!==null&&de(be),U||H(!0)},t=e=>!(e instanceof Element)||e.closest(`.slash-panel`)?!1:!T.current?.contains(e),n=n=>{t(n.target)&&e()},r=t=>{t.key!==`Escape`||t.isComposing||(t.preventDefault(),e())};return document.addEventListener(`pointerdown`,n),document.addEventListener(`keydown`,r),()=>{document.removeEventListener(`pointerdown`,n),document.removeEventListener(`keydown`,r)}},[W,U,be]);let xe=(e,t)=>{let n=Zp(e,K);if(n===``)return;let r=w.current,i=r?.value??ie.current,a=r?.selectionStart??re.current,o=Math.min(Math.max(a,0),i.length),s=Gp(i,o),c=s?Kp(i,s,n):qp(i,o,n);p(c.text),re.current=c.caret,ne(c.caret),de(null),_e.remember({path:n,isDir:t}),requestAnimationFrame(()=>{let e=w.current;e&&(e.focus(),e.setSelectionRange(c.caret,c.caret))})},Se=async e=>{if(!pe){me(!0);try{let t=await fetch(`/api/fs/pick-path`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({kind:e})}),n=await t.text(),r=null;try{r=JSON.parse(n)}catch{Z({text:n.trimStart().startsWith(`<`)?l(`服务端还没有这个接口(HTTP ${t.status})—— 服务可能在跑旧版本,重启一下就好`,`The server does not have this endpoint yet (HTTP ${t.status}) — it may be an older build, restart it`):l(`服务端返回的不是 JSON(HTTP ${t.status})`,`The server did not return JSON (HTTP ${t.status})`)});return}if(!r)return;if(!t.ok){Z({text:r.error?.message??r.message??`HTTP ${t.status}`});return}if(r.canceled)return;if(r.unsupported||!r.path){Z({text:r.message??l(`这台机器上开不出文件选择框:直接 @ 搜文件名也可以`,`No file picker on this machine — type @ to search file names`)});return}xe(r.path,e===`dir`)}catch(e){Z({text:e instanceof Error?e.message:String(e)})}finally{me(!1)}}},Ce=e=>{e.kind===`browse`?Se(e.target):xe(e.path,e.isDir)},we=(0,C.useMemo)(()=>{let e=[];for(let t of m?.active.messages??[]){if(t.role!==`user`)continue;let n=yp(t).trim();n!==``&&e.push(n)}return e.slice(-50)},[m?.active.messages]),[Te,Ee]=(0,C.useState)(null),De=(0,C.useRef)(``);(0,C.useEffect)(()=>{Ee(null)},[t]);let Oe=e=>{if(we.length===0||Te===null&&e===1)return!1;Te===null&&(De.current=ie.current);let t=Te===null?we.length-1:Te+e;t!==null&&t<0&&(t=0),t!==null&&t>=we.length&&(t=null),Ee(t);let n=t===null?De.current:we[t]??``;return p(n),re.current=n.length,ne(n.length),requestAnimationFrame(()=>{let e=w.current;e&&(e.focus(),e.setSelectionRange(n.length,n.length))}),!0},ke=m?.settings.quickPhrases??[],je=ke.map(e=>pp(e,u)),J=j.quick&&!i?je:[],Me=m?.settings.templates??[],[Ne,X]=(0,C.useState)(!1),[Pe,Fe]=(0,C.useState)(null),Ie=async e=>{if(e.length===0)return;let{accepted:t,rejected:n}=Nf(e,g.length);if(n.length>0&&x(n.join(l(`;`,`; `))),t.length===0)return;let r=S.current;y(!0);let i=[];for(let e of t){let t=await Ff(e);if(S.current!==r)return;t.ok?i.push(t.attachment):x(t.error)}y(!1),i.length>0&&(_(e=>[...e,...i].slice(0,5)),x(null))},Le=e=>{let t=[...e.clipboardData.items].filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null);t.length!==0&&(e.preventDefault(),Ie(t))},Re=async e=>{let t=/^\/skill:([^\s]+)/i.exec(e)?.[1]??``;if(t===``)return;let n=(P??await I()).find(e=>e.name.toLowerCase()===t.toLowerCase());n?n.enabled||Z({text:l(`技能「${t}」是停用状态:pi 不会加载它(去「技能」面板启用)`,`Skill "${t}" is disabled: pi will not load it (enable it in the Skills panel)`)}):Z({text:l(`没有叫「${t}」的技能:会当普通文本发出去。去「技能」面板核对名字`,`No skill named "${t}": the text goes out as plain text. Check the name in the Skills panel`)})},ze=(e,t,i=`now`)=>{cn(i),n?n.send(e,t,i):r?Rl(e,t,i,r.workspace??void 0,{ephemeral:r.ephemeral&&m?.engineCapabilities.ephemeralChat===!0}):Al(e,t,i)},Be=Zu(a),Ve=a.filter(e=>e.quoted!==!0).length,He=f.trim()!==``||g.length>0||Be!==``,Ue=(t=`now`)=>{Ta();let r=f.trim();if(!r&&g.length===0&&Be===``){Ut(`submit:empty`,{mode:t});return}if(/^\/skill:/i.test(r)&&Re(r),(n?.hostCommands??!0)&&Op(r)){let e=g;kp(r,m).then(t=>{t.handled&&(ie.current.trim()===r&&p(``),_(t=>t===e?[]:t))});return}if(e&&t===`now`)return;let i=(r===``?Be:Be===``?r:`${r}\n\n${Be}`)+Pf(g);Ut(`submit:send`,{mode:t,running:e,len:i.length,attachments:g.length}),ze(i,g.length>0?g:void 0,t),p(``),Ee(null),De.current=``,_([]),x(null),Be!==``&&o?.()};return oe.current=Ue,(0,Q.jsxs)(`div`,{className:`composer-wrap`,children:[(0,Q.jsxs)(`div`,{className:`composer-topbar`,children:[(0,Q.jsxs)(`div`,{className:`composer-tools`,children:[r?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(pm,{workspace:r.workspace,ephemeral:r.ephemeral,onChange:r.onWorkspaceChange,onEphemeralChange:r.onEphemeralChange}),(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`})]}):A?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(cp,{projectRoot:A}),(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`})]}):null,j.model?(0,Q.jsx)(Qf,{surface:n,part:`model`}):null,j.thinking?(0,Q.jsx)(Qf,{surface:n,part:`thinking`}):null,j.think?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),(0,Q.jsx)(up,{conversationId:t,running:e})]}):null,j.templates&&!i?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),(0,Q.jsxs)(`button`,{type:`button`,className:`tool-chip composer-template-btn`,onClick:()=>X(!0),title:l(`提示词模板库(含快捷指令)`,`Prompt templates (with quick commands)`),children:[`✏️ `,l(`提示词`,`Prompts`)]})]}):null]}),J.length>0?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`quick-row`,children:[(0,Q.jsx)(`span`,{className:`tool-sep`,"aria-hidden":`true`}),J.map((t,n)=>(0,Q.jsx)(`button`,{type:`button`,className:`quick-chip`,disabled:e,title:l(`${t}(点击直接发送 · Shift+点击只填入)`,`${t} (click to send · Shift+click to fill in)`),onClick:n=>{if(n.shiftKey){p(t),w.current?.focus();return}if(e)return;let r=Date.now();r-O.current<hm||(O.current=r,ze(t))},children:t},`${t}-${n}`))]})}):null]}),g.length>0||v||b?(0,Q.jsxs)(`div`,{className:`attach-row`,children:[g.map(e=>(0,Q.jsxs)(`span`,{className:`attach-chip`,title:`${e.mime} · ${e.name}`,children:[e.kind===`image`?(0,Q.jsx)(`img`,{className:`attach-thumb`,src:`/api/uploads/${e.id}`,alt:e.name,title:l(`点击放大预览`,`Click to preview`),onClick:()=>ns(`/api/uploads/${e.id}`,e.name)}):(0,Q.jsx)(`span`,{className:`attach-kind`,children:`📄`}),(0,Q.jsx)(`span`,{className:`attach-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`attach-size`,children:gm(e.bytes)}),(0,Q.jsx)(`button`,{type:`button`,className:`attach-remove`,title:l(`移除`,`Remove`),onClick:()=>_(t=>t.filter(t=>t.id!==e.id)),children:`×`})]},e.id)),v?(0,Q.jsx)(`span`,{className:`attach-hint`,children:l(`上传中…`)}):null,b?(0,Q.jsx)(`span`,{className:`attach-error`,children:b}):null]}):null,W&&ge===null?(0,Q.jsx)(Ap,{commands:N,skills:L,active:R,onPick:e=>{e.name.startsWith(`skill:`)?G(e.name.slice(6)):ee(e)},onHover:z}):null,ge===null?null:(0,Q.jsx)(Vp,{rows:ve,active:ye,loading:_e.loading,error:ge.term.trim()===``?null:_e.error,onPick:e=>xe(e.path,e.isDir),onHover:fe,onBrowse:e=>void Se(e),onOpenFile:s?e=>s(e,K):void 0}),(0,Q.jsxs)(`div`,{className:`composer`,ref:T,children:[c,(0,Q.jsxs)(`div`,{className:`composer-row`,children:[n?null:(0,Q.jsx)(Lp,{inline:!0}),(0,Q.jsx)(`textarea`,{ref:w,className:`composer-input`,...wu,enterKeyHint:e?`enter`:`send`,value:f,placeholder:e?l(`正在跑…回车排队`,`Running… Enter to queue`):f.trim()===``&&Be!==``?l(`回车发送 ${Ve} 条注释`,`Enter to send ${Ve} note(s)`):Tf()?l(`消息…`,`Message…`):l(`消息…输入 / 使用命令,输入 @ 查找文件`,`Message… type / for commands, @ to find a file`),onChange:e=>{let t=e.target.value,n=e.target.selectionStart??t.length;Te!==null&&(Ee(null),De.current=t),p(t),re.current=n,ne(n),na()&&Da(t),ue!==null&&t[ue]!==`@`&&de(null)},onPaste:Le,onKeyDown:t=>{if(ge!==null&&!t.nativeEvent.isComposing){if(t.key===`ArrowDown`||t.key===`ArrowUp`){t.preventDefault();let e=t.key===`ArrowDown`?1:-1,n=Math.max(1,ve.length);fe(t=>(t+e+n)%n);return}if((t.key===`Tab`||t.key===`Enter`&&!t.shiftKey)&&ve.length>0){t.preventDefault();let e=ve[ye];e&&Ce(e);return}if(t.key===`Escape`){t.preventDefault(),de(ge.start);return}}if(W&&!t.nativeEvent.isComposing){if(t.key===`ArrowDown`||t.key===`ArrowUp`){t.preventDefault();let e=t.key===`ArrowDown`?1:-1;z(t=>(t+e+Math.max(1,B))%Math.max(1,B));return}if(t.key===`Tab`||t.key===`Enter`&&!t.shiftKey){if(t.preventDefault(),L!==null){let e=L[R];e&&G(e.name);return}let e=N[R];e&&ee(e);return}if(t.key===`Escape`){t.preventDefault(),H(!0);return}}if(!t.nativeEvent.isComposing&&(t.key===`ArrowUp`||t.key===`ArrowDown`)&&t.currentTarget.selectionStart===t.currentTarget.selectionEnd){let e=t.currentTarget.value.slice(0,t.currentTarget.selectionStart??0),n=t.currentTarget.value.slice(t.currentTarget.selectionEnd??0);if((t.key===`ArrowUp`?!e.includes(`
16
16
  `):!n.includes(`
17
- `))&&ke(t.key===`ArrowUp`?-1:1)){t.preventDefault();return}}t.key!==`Enter`||t.shiftKey||t.nativeEvent.isComposing||(t.preventDefault(),We(e?`queue`:`now`))},rows:1})]}),(0,Q.jsx)(`div`,{className:`composer-actions`,ref:E,children:e&&Ue?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-send`,title:l(`等这一轮结束后再发(回车默认就是它)`,`Send after this turn ends (the Enter default)`),onClick:()=>We(`queue`),children:l(`排队`,`Queue`)}),m?.engineCapabilities?.steer===!1?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-queue`,title:l(`插进当前这一轮(打断它,按新指示继续)`,`Insert into the running turn (interrupt it, continue with new instructions)`),onClick:()=>We(`steer`),children:l(`插队`,`Steer`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-stop`,onClick:()=>t&&jl(t),children:l(`停止`,`Stop`)})]}):e?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-stop`,onClick:()=>t&&(n?n.interrupt(t):jl(t)),children:l(`停止`,`Stop`)}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-send`,onClick:()=>We(`now`),disabled:!Ue,title:f.trim()===``&&Ve!==``?l(`把这 ${He} 条注释发出去`,`Send these ${He} note(s)`):void 0,children:[`➤ `,l(`发送`,`Send`)]})})]}),Y?(0,Q.jsx)(_p,{templates:Ne,phrases:Ae,running:e,onQuickPhrase:(t,n)=>{if(n===`fill`){p(t),w.current?.focus();return}if(e)return;let r=Date.now();r-O.current<hm||(O.current=r,Be(t))},onEdit:e=>Ie({template:e}),onCreate:()=>Ie({template:null}),onClose:()=>Pe(!1)}):null,Fe?(0,Q.jsx)(vp,{template:Fe.template,library:Ne,conversationId:t,onClose:()=>Ie(null)}):null]})}function vm(e){return!Number.isFinite(e)||e<=0?`0`:e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}K`:`${(e/1e6).toFixed(2)}M`}var ym=250,bm=4e3;function xm(e){let t=0,n=0;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)>=11904?t+=1:n+=1;return t+Math.round(n/4)}function Sm(e,t=Date.now(),n=bm){let r=t-n,i=e.filter(e=>e.ts>=r);if(i.length<2)return 0;let a=i[0],o=i[i.length-1];if(!a||!o)return 0;let s=(o.ts-a.ts)/1e3;if(s*1e3<ym)return 0;let c=o.tokens-a.tokens;return c>0?c/s:0}function Cm(e){return!Number.isFinite(e)||e<=0?`—`:`${e>=100?Math.round(e):Math.round(e*10)/10} t/s`}function wm(e){let t=(0,C.useRef)([]),n=(0,C.useRef)(e),[,r]=(0,C.useState)(0);return n.current=e,(0,C.useEffect)(()=>{let e=()=>{let e=Date.now(),i=t.current;i.push({ts:e,tokens:xm(n.current)});let a=e-bm-ym;for(;i.length>2&&(i[0]?.ts??0)<a;)i.shift();r(e=>e+1)};e();let i=setInterval(e,ym);return()=>{clearInterval(i),t.current=[]}},[]),{tokens:t.current[t.current.length-1]?.tokens??0,rate:Sm(t.current)}}function Tm(e){let t=Number.isFinite(e)?Math.max(0,e):0;if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return t<1e4?`${(t/1e3).toFixed(1)}s`:`${Math.round(t/1e3)}s`;let n=Math.floor(t/6e4);if(n>=60)return`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`;let r=Math.round(t%6e4/1e3);return r>0?`${n}m${r}s`:`${n}m`}function Em(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t<3600?`${t}s`:Tm(t*1e3)}var Dm={},Om=null,km=0,Am=new Set;function jm(){km+=1;for(let e of Am)e()}function Mm(){Om||=fetch(`/api/skills`).then(e=>e.ok?e.json():null).then(e=>{let t=Array.isArray(e)?e:Array.isArray(e?.skills)?e.skills:null;if(!t)return;let n={};for(let e of t){let t=e;typeof t.id==`string`&&typeof t.name==`string`&&t.name!==``&&(n[t.id]=t.name)}Dm=n,jm()}).catch(()=>{})}function Nm(e){return Dm[e]??null}function Pm(e){return Mm(),Am.add(e),()=>{Am.delete(e)}}function Fm(){return km}function Im(){(0,C.useSyncExternalStore)((0,C.useCallback)(Pm,[]),Fm,Fm)}function Lm(e){return e.live&&e.endedAt===void 0}function Rm(e){let t=-1,n=-1,r=-1;e.forEach((e,i)=>{e.kind===`process`?(t<0&&(t=i),n=i):(e.kind===`error`||(e.text??``).trim()!==``)&&(r=i)});let i=t>=0;return{firstProcessAt:t,lastAnswerAt:r,lastProcessAt:n,hasAnswer:i&&r>n,insideFold:e=>i&&e<r}}function zm(e){return e.running?!0:!(e.index===e.lastAnswerAt&&e.lastAnswerAt>e.lastProcessAt)}function Bm(e){return e.manual===null?e.running?e.autoFoldRunning?`collapsed`:`all`:e.autoCollapse?`collapsed`:e.defaultOpen?`all`:`collapsed`:e.manual?`all`:`collapsed`}function Vm(e){return e.view!==`collapsed`||!e.hasProcess?!1:e.insideFold?!0:!e.running&&!e.hasAnswer}function Hm(e,t){return e&&!t}function Um(e){return`${e.code}\u0000${e.message}`}function Wm(e){let t=[],n=null,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a];if(o){if(o.kind===`thinking`||o.kind===`tool`){if(n||(n={kind:`process`,groups:[]},t.push(n)),o.kind===`thinking`){r+=1,n.groups.push({key:`think-${a}`,thinking:{text:o.text},tools:[]});continue}i+=1;let e=n.groups[n.groups.length-1];e?e.tools.push(o):n.groups.push({key:`lead-${a}`,thinking:null,tools:[o]})}else n=null,o.kind===`text`?t.push({kind:`text`,text:o.text,index:a}):t.push({kind:`error`,block:o,index:a})}}let a=new Map,o=new Map;for(let e=0;e<t.length;e+=1){let n=t[e];if(!n||n.kind!==`error`)continue;let r=Um(n.block);a.set(r,e),o.set(r,(o.get(r)??0)+(n.block.count??1))}if(a.size===0)return{segments:t,thinkingCount:r,toolCount:i};let s=[];for(let e=0;e<t.length;e+=1){let n=t[e];if(!n)continue;if(n.kind!==`error`){s.push(n);continue}let r=Um(n.block);a.get(r)===e&&s.push({kind:`error`,block:{...n.block,count:o.get(r)??1},index:e})}return{segments:s,thinkingCount:r,toolCount:i}}var Gm=`pop-agent:steer-expanded`,Km=200;function qm(e){if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=new Set,r=[];for(let e of t)typeof e!=`string`||e===``||n.has(e)||(n.add(e),r.push(e));return r}function Jm(e){return JSON.stringify([...e].slice(-200))}function Ym(e,t){let n=new Set(e);if(n.has(t))return n.delete(t),n;n.add(t);let r=n.size-Km;if(r>0)for(let e of n){if(r--<=0)break;n.delete(e)}return n}function Xm(e){return new Set(qm(e.getItem(Gm)))}function Zm(e,t){e.setItem(Gm,Jm(t))}function Qm(e){for(let t of e.split(`
18
- `)){let e=t.trim();if(e!==``)return e}return``}function $m(e){if(e.length<2)return e;let t=e;for(let n=0;n<e.length;n+=1){let e=!1,n=[...t];for(let t=1;t<n.length;t+=1){let r=n[t],i=n[t-1];if(!r||!i||r.role!==`user`||r.steer!==!0||i.role!==`assistant`)continue;let a=i.ts,o=i.endedAt??1/0;r.ts<a||r.ts>o||(n[t-1]=r,n[t]=i,e=!0)}if(t=n,!e)break}return t}function eh({actions:e,running:t}){let n=J(),[r,i]=(0,C.useState)(!1),a=e.map(e=>e.id).join(`|`);return(0,C.useEffect)(()=>{i(!1)},[a]),t||r||e.length===0?null:(0,Q.jsx)(`div`,{className:`action-row`,children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`action-btn`,disabled:t,title:n(`${e.label}\n发送:${e.prompt}\n(Shift+点击只填入输入框)`,`${e.label}\nSend: ${e.prompt}\n(Shift+click to fill the input only)`),onClick:n=>{n.shiftKey?So(e.prompt):t||r||(i(!0),an(),Al(e.prompt))},children:e.label},e.id))})}function th(e){return[`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`go`,`rs`,`java`,`kt`,`rb`,`php`,`sh`].includes(e)?`code`:[`css`,`scss`,`sass`,`less`,`html`,`vue`,`svelte`].includes(e)?`style`:`text`}function nh(e){return e===``?q(`文件`,`FILE`):e.length<=4?e.toUpperCase():e.slice(0,3).toUpperCase()}function rh({files:e,onOpen:t}){let n=J();return e.length===0?null:(0,Q.jsxs)(`div`,{className:`msg-files`,children:[(0,Q.jsx)(`span`,{className:`msg-files-label`,title:n(`这一轮工具写过的文件(按第一次出现的顺序)`,`Files the tools wrote this turn (in order of first appearance)`),children:n(`改动 ${e.length} 个文件`,`${e.length} file(s) changed`)}),e.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`msg-file${e.outside?` msg-file-off`:``}`,disabled:e.outside||!t,title:e.outside?n(`${e.path}(在工作区之外,右侧预览读不了)`,`${e.path} (outside the workspace — the preview cannot read it)`):n(`${e.path} · 点一下在右侧打开`,`${e.path} · click to open it on the right`),onClick:()=>t?.(e),children:[(0,Q.jsx)(`span`,{className:`msg-file-badge msg-file-badge-${th(e.ext)}`,children:nh(e.ext)}),(0,Q.jsx)(`span`,{className:`msg-file-name`,children:e.name})]},e.path))]})}var ih=1400;function ah({text:e,className:t=`msg-action`,title:n=`复制`}){let[r,i]=(0,C.useState)(!1),a=J(),o=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=async()=>{await xp(e)&&(i(!0),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>i(!1),ih))};return(0,Q.jsx)(`button`,{type:`button`,className:`${t}${r?` is-copied`:``}`,title:r?a(`已复制到剪贴板`,`Copied to clipboard`):a(n),"aria-live":`polite`,onClick:()=>void s(),children:r?`✓ ${a(`已复制`,`Copied`)}`:`⧉ ${a(`复制`,`Copy`)}`})}function oh({text:e}){let t=J(),[n,r]=(0,C.useState)(!1),i=(0,C.useRef)(null),a=Qt(),o=n||a;return(0,C.useEffect)(()=>()=>i.current?.(),[e]),(0,C.useEffect)(()=>tn(()=>{i.current&&i.current()}),[]),(0,Q.jsxs)(`button`,{type:`button`,className:`msg-foot-copy msg-foot-read-aloud`,onClick:()=>{if(i.current){i.current();return}if(a){nn(),Ct(),r(!1);return}let n=nt(e,1/0);if(!n){Z({text:t(`这条回复没有可朗读的文字`,`This reply has no text to read aloud`)});return}let o=!0,s=()=>{o&&(o=!1,i.current=null,r(!1))},c=()=>{o&&(nn(),Ct(),s())};i.current=c,r(!0),bt(n,qe(),{onCancel:s,onEnd:c,onIssue:e=>{c(),Z({text:e})}})},disabled:!Qe(),"aria-pressed":o,title:Qe()?o?t(`停止朗读`,`Stop reading`):t(`朗读这条回复`,`Read this reply aloud`):t(`当前浏览器不支持所选语音引擎`,`This browser does not support the selected speech engine`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M7 3 3.5 6H1.5v4h2L7 13Z`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`M10 5.5a3.5 3.5 0 0 1 0 5m2-7a6.5 6.5 0 0 1 0 9`,strokeLinecap:`round`})]}),(0,Q.jsx)(`span`,{children:o?t(`停止`,`Stop`):t(`朗读`,`Read aloud`)})]})}function sh(){let[e,t]=(0,C.useState)(()=>qe());return(0,C.useEffect)(()=>Xe(t),[]),e}function ch(e){if(!e.includes(`%`))return e;try{let t=decodeURIComponent(e);return t===e?e:t}catch{return e}}function lh(e){let t=e.trim();if(t===``)return null;if(/^https?:\/\//i.test(t)||t.startsWith(`/api/uploads/`)||t.startsWith(`/api/files/raw`))return t;let n=t.startsWith(`file://`)?t.slice(7).replace(/^\/(?=[A-Za-z]:[\\/])/,``):t;return/^(javascript|data|vbscript):/i.test(n)?null:`/api/files/raw?path=${encodeURIComponent(ch(n).replace(/^\.\//,``))}`}var uh=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`svg`,`ico`]),dh=`\\.(?:png|jpe?g|gif|webp|avif|bmp|svg|ico)`;function fh(e){let t=e.trim().replace(/^<+|>+$/g,``).replace(/^`+|`+$/g,``);if(t===``||/\s/.test(t))return!1;let n=/\.([A-Za-z0-9]{2,5})$/.exec(t);return n?uh.has(n[1].toLowerCase()):!1}function ph(e){let t=e.split(/[\\/]/).pop()??e;return t.trim()===``?e:t}function mh(e,t){return`![${((t??``).trim()||ph(e)).replace(/[[\]]/g,``)}](<${e.replace(/>/g,`%3E`)}>)`}var hh=RegExp(`(?:~/|[A-Za-z]:[\\\\/]|/)[^\\s"'\`<>|*?]+${dh}\\b`,`gi`),gh=/^[\s,。、;:!?,;!?…—·()【】「」『』“”‘’"'《》]$/;function _h(e){if(e===``)return e;let t=e.replace(/(?<!!)\[([^\]\n]*)\]\(([^)\s]+)\)/g,(e,t,n)=>fh(n)?mh(n,t):e);return t.replace(hh,(e,n)=>{let r=n>0?t[n-1]:``;return r!==``&&!gh.test(r)?e:mh(e)})}function vh(e){if(!e.includes(`.`))return e;let t=``,n=0;for(let r of e.matchAll(/(`+)([^`]+?)\1/g)){let i=r.index??0;t+=_h(e.slice(n,i));let a=r[2]??``;t+=fh(a)?mh(a):r[0],n=i+r[0].length}return t+_h(e.slice(n))}function yh(e){if(!new RegExp(dh,`i`).test(e))return e;let t=null;return e.split(`
17
+ `))&&Oe(t.key===`ArrowUp`?-1:1)){t.preventDefault();return}}t.key!==`Enter`||t.shiftKey||t.nativeEvent.isComposing||(t.preventDefault(),Ue(e?`queue`:`now`))},rows:1})]}),(0,Q.jsx)(`div`,{className:`composer-actions`,ref:E,children:e&&He?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-send`,title:l(`等这一轮结束后再发(回车默认就是它)`,`Send after this turn ends (the Enter default)`),onClick:()=>Ue(`queue`),children:l(`排队`,`Queue`)}),m?.engineCapabilities?.steer===!1?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-queue`,title:l(`插进当前这一轮(打断它,按新指示继续)`,`Insert into the running turn (interrupt it, continue with new instructions)`),onClick:()=>Ue(`steer`),children:l(`插队`,`Steer`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-stop`,onClick:()=>t&&jl(t),children:l(`停止`,`Stop`)})]}):e?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-stop`,onClick:()=>t&&(n?n.interrupt(t):jl(t)),children:l(`停止`,`Stop`)}):(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-send`,onClick:()=>Ue(`now`),disabled:!He,title:f.trim()===``&&Be!==``?l(`把这 ${Ve} 条注释发出去`,`Send these ${Ve} note(s)`):void 0,children:[`➤ `,l(`发送`,`Send`)]})})]}),Ne?(0,Q.jsx)(_p,{templates:Me,phrases:ke,running:e,onQuickPhrase:(t,n)=>{if(n===`fill`){p(t),w.current?.focus();return}if(e)return;let r=Date.now();r-O.current<hm||(O.current=r,ze(t))},onEdit:e=>Fe({template:e}),onCreate:()=>Fe({template:null}),onClose:()=>X(!1)}):null,Pe?(0,Q.jsx)(vp,{template:Pe.template,library:Me,conversationId:t,onClose:()=>Fe(null)}):null]})}function vm(e){return!Number.isFinite(e)||e<=0?`0`:e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}K`:`${(e/1e6).toFixed(2)}M`}var ym=250,bm=4e3;function xm(e){let t=0,n=0;for(let r=0;r<e.length;r+=1)e.charCodeAt(r)>=11904?t+=1:n+=1;return t+Math.round(n/4)}function Sm(e,t=Date.now(),n=bm){let r=t-n,i=e.filter(e=>e.ts>=r);if(i.length<2)return 0;let a=i[0],o=i[i.length-1];if(!a||!o)return 0;let s=(o.ts-a.ts)/1e3;if(s*1e3<ym)return 0;let c=o.tokens-a.tokens;return c>0?c/s:0}function Cm(e){return!Number.isFinite(e)||e<=0?`—`:`${e>=100?Math.round(e):Math.round(e*10)/10} t/s`}function wm(e){let t=(0,C.useRef)([]),n=(0,C.useRef)(e),[,r]=(0,C.useState)(0);return n.current=e,(0,C.useEffect)(()=>{let e=()=>{let e=Date.now(),i=t.current;i.push({ts:e,tokens:xm(n.current)});let a=e-bm-ym;for(;i.length>2&&(i[0]?.ts??0)<a;)i.shift();r(e=>e+1)};e();let i=setInterval(e,ym);return()=>{clearInterval(i),t.current=[]}},[]),{tokens:t.current[t.current.length-1]?.tokens??0,rate:Sm(t.current)}}function Tm(e){let t=Number.isFinite(e)?Math.max(0,e):0;if(t<1e3)return`${Math.round(t)}ms`;if(t<6e4)return t<1e4?`${(t/1e3).toFixed(1)}s`:`${Math.round(t/1e3)}s`;let n=Math.floor(t/6e4);if(n>=60)return`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`;let r=Math.round(t%6e4/1e3);return r>0?`${n}m${r}s`:`${n}m`}function Em(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t<3600?`${t}s`:Tm(t*1e3)}var Dm={},Om=null,km=0,Am=new Set;function jm(){km+=1;for(let e of Am)e()}function Mm(){Om||=fetch(`/api/skills`).then(e=>e.ok?e.json():null).then(e=>{let t=Array.isArray(e)?e:Array.isArray(e?.skills)?e.skills:null;if(!t)return;let n={};for(let e of t){let t=e;typeof t.id==`string`&&typeof t.name==`string`&&t.name!==``&&(n[t.id]=t.name)}Dm=n,jm()}).catch(()=>{})}function Nm(e){return Dm[e]??null}function Pm(e){return Mm(),Am.add(e),()=>{Am.delete(e)}}function Fm(){return km}function Im(){(0,C.useSyncExternalStore)((0,C.useCallback)(Pm,[]),Fm,Fm)}function Lm(e){return e.live&&e.endedAt===void 0}function Rm(e){let t=-1,n=-1,r=-1;e.forEach((e,i)=>{e.kind===`process`?(t<0&&(t=i),n=i):(e.kind===`error`||(e.text??``).trim()!==``)&&(r=i)});let i=t>=0;return{firstProcessAt:t,lastAnswerAt:r,lastProcessAt:n,hasAnswer:i&&r>n,insideFold:e=>i&&e<r}}function zm(e){return e.running?!0:!(e.index===e.lastAnswerAt&&e.lastAnswerAt>e.lastProcessAt)}function Bm(e){return e.manual===null?e.running?e.autoFoldRunning?`collapsed`:`all`:e.autoCollapse?`collapsed`:e.defaultOpen?`all`:`collapsed`:e.manual?`all`:`collapsed`}function Vm(e){return e.view!==`collapsed`||!e.hasProcess?!1:e.insideFold?!0:!e.running&&!e.hasAnswer}function Hm(e,t){return e&&!t}function Um(e){return`${e.code}\u0000${e.message}`}function Wm(e){let t=[],n=null,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a];if(o){if(o.kind===`thinking`||o.kind===`tool`){if(n||(n={kind:`process`,groups:[]},t.push(n)),o.kind===`thinking`){r+=1,n.groups.push({key:`think-${a}`,thinking:{text:o.text},tools:[]});continue}i+=1;let e=n.groups[n.groups.length-1];e?e.tools.push(o):n.groups.push({key:`lead-${a}`,thinking:null,tools:[o]})}else n=null,o.kind===`text`?t.push({kind:`text`,text:o.text,index:a}):t.push({kind:`error`,block:o,index:a})}}let a=new Map,o=new Map;for(let e=0;e<t.length;e+=1){let n=t[e];if(!n||n.kind!==`error`)continue;let r=Um(n.block);a.set(r,e),o.set(r,(o.get(r)??0)+(n.block.count??1))}if(a.size===0)return{segments:t,thinkingCount:r,toolCount:i};let s=[];for(let e=0;e<t.length;e+=1){let n=t[e];if(!n)continue;if(n.kind!==`error`){s.push(n);continue}let r=Um(n.block);a.get(r)===e&&s.push({kind:`error`,block:{...n.block,count:o.get(r)??1},index:e})}return{segments:s,thinkingCount:r,toolCount:i}}var Gm=`pop-agent:steer-expanded`,Km=200;function qm(e){if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=new Set,r=[];for(let e of t)typeof e!=`string`||e===``||n.has(e)||(n.add(e),r.push(e));return r}function Jm(e){return JSON.stringify([...e].slice(-200))}function Ym(e,t){let n=new Set(e);if(n.has(t))return n.delete(t),n;n.add(t);let r=n.size-Km;if(r>0)for(let e of n){if(r--<=0)break;n.delete(e)}return n}function Xm(e){return new Set(qm(e.getItem(Gm)))}function Zm(e,t){e.setItem(Gm,Jm(t))}function Qm(e){for(let t of e.split(`
18
+ `)){let e=t.trim();if(e!==``)return e}return``}function $m(e){if(e.length<2)return e;let t=e;for(let n=0;n<e.length;n+=1){let e=!1,n=[...t];for(let t=1;t<n.length;t+=1){let r=n[t],i=n[t-1];if(!r||!i||r.role!==`user`||r.steer!==!0||i.role!==`assistant`)continue;let a=i.ts,o=i.endedAt??1/0;r.ts<a||r.ts>o||(n[t-1]=r,n[t]=i,e=!0)}if(t=n,!e)break}return t}function eh({actions:e,running:t}){let n=Y(),[r,i]=(0,C.useState)(!1),a=e.map(e=>e.id).join(`|`);return(0,C.useEffect)(()=>{i(!1)},[a]),t||r||e.length===0?null:(0,Q.jsx)(`div`,{className:`action-row`,children:e.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`action-btn`,disabled:t,title:n(`${e.label}\n发送:${e.prompt}\n(Shift+点击只填入输入框)`,`${e.label}\nSend: ${e.prompt}\n(Shift+click to fill the input only)`),onClick:n=>{n.shiftKey?So(e.prompt):t||r||(i(!0),an(),Al(e.prompt))},children:e.label},e.id))})}function th(e){return[`ts`,`tsx`,`js`,`jsx`,`mjs`,`cjs`,`py`,`go`,`rs`,`java`,`kt`,`rb`,`php`,`sh`].includes(e)?`code`:[`css`,`scss`,`sass`,`less`,`html`,`vue`,`svelte`].includes(e)?`style`:`text`}function nh(e){return e===``?J(`文件`,`FILE`):e.length<=4?e.toUpperCase():e.slice(0,3).toUpperCase()}function rh({files:e,onOpen:t}){let n=Y();return e.length===0?null:(0,Q.jsxs)(`div`,{className:`msg-files`,children:[(0,Q.jsx)(`span`,{className:`msg-files-label`,title:n(`这一轮工具写过的文件(按第一次出现的顺序)`,`Files the tools wrote this turn (in order of first appearance)`),children:n(`改动 ${e.length} 个文件`,`${e.length} file(s) changed`)}),e.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`msg-file${e.outside?` msg-file-off`:``}`,disabled:e.outside||!t,title:e.outside?n(`${e.path}(在工作区之外,右侧预览读不了)`,`${e.path} (outside the workspace — the preview cannot read it)`):n(`${e.path} · 点一下在右侧打开`,`${e.path} · click to open it on the right`),onClick:()=>t?.(e),children:[(0,Q.jsx)(`span`,{className:`msg-file-badge msg-file-badge-${th(e.ext)}`,children:nh(e.ext)}),(0,Q.jsx)(`span`,{className:`msg-file-name`,children:e.name})]},e.path))]})}var ih=1400;function ah({text:e,className:t=`msg-action`,title:n=`复制`}){let[r,i]=(0,C.useState)(!1),a=Y(),o=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>{o.current!==null&&window.clearTimeout(o.current)},[]);let s=async()=>{await xp(e)&&(i(!0),o.current!==null&&window.clearTimeout(o.current),o.current=window.setTimeout(()=>i(!1),ih))};return(0,Q.jsx)(`button`,{type:`button`,className:`${t}${r?` is-copied`:``}`,title:r?a(`已复制到剪贴板`,`Copied to clipboard`):a(n),"aria-live":`polite`,onClick:()=>void s(),children:r?`✓ ${a(`已复制`,`Copied`)}`:`⧉ ${a(`复制`,`Copy`)}`})}function oh({text:e}){let t=Y(),[n,r]=(0,C.useState)(!1),i=(0,C.useRef)(null),a=Qt(),o=n||a;return(0,C.useEffect)(()=>()=>i.current?.(),[e]),(0,C.useEffect)(()=>tn(()=>{i.current&&i.current()}),[]),(0,Q.jsxs)(`button`,{type:`button`,className:`msg-foot-copy msg-foot-read-aloud`,onClick:()=>{if(i.current){i.current();return}if(a){nn(),St(),r(!1);return}let n=tt(e,1/0);if(!n){Z({text:t(`这条回复没有可朗读的文字`,`This reply has no text to read aloud`)});return}let o=!0,s=()=>{o&&(o=!1,i.current=null,r(!1))},c=()=>{o&&(nn(),St(),s())};i.current=c,r(!0),yt(n,Ke(),{onCancel:s,onEnd:c,onIssue:e=>{c(),Z({text:e})}})},disabled:!Ze(),"aria-pressed":o,title:Ze()?o?t(`停止朗读`,`Stop reading`):t(`朗读这条回复`,`Read this reply aloud`):t(`当前浏览器不支持所选语音引擎`,`This browser does not support the selected speech engine`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M7 3 3.5 6H1.5v4h2L7 13Z`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`M10 5.5a3.5 3.5 0 0 1 0 5m2-7a6.5 6.5 0 0 1 0 9`,strokeLinecap:`round`})]}),(0,Q.jsx)(`span`,{children:o?t(`停止`,`Stop`):t(`朗读`,`Read aloud`)})]})}function sh(){let[e,t]=(0,C.useState)(()=>Ke());return(0,C.useEffect)(()=>Ye(t),[]),e}function ch(e){if(!e.includes(`%`))return e;try{let t=decodeURIComponent(e);return t===e?e:t}catch{return e}}function lh(e){let t=e.trim();if(t===``)return null;if(/^https?:\/\//i.test(t)||t.startsWith(`/api/uploads/`)||t.startsWith(`/api/files/raw`))return t;let n=t.startsWith(`file://`)?t.slice(7).replace(/^\/(?=[A-Za-z]:[\\/])/,``):t;return/^(javascript|data|vbscript):/i.test(n)?null:`/api/files/raw?path=${encodeURIComponent(ch(n).replace(/^\.\//,``))}`}var uh=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`avif`,`bmp`,`svg`,`ico`]),dh=`\\.(?:png|jpe?g|gif|webp|avif|bmp|svg|ico)`;function fh(e){let t=e.trim().replace(/^<+|>+$/g,``).replace(/^`+|`+$/g,``);if(t===``||/\s/.test(t))return!1;let n=/\.([A-Za-z0-9]{2,5})$/.exec(t);return n?uh.has(n[1].toLowerCase()):!1}function ph(e){let t=e.split(/[\\/]/).pop()??e;return t.trim()===``?e:t}function mh(e,t){return`![${((t??``).trim()||ph(e)).replace(/[[\]]/g,``)}](<${e.replace(/>/g,`%3E`)}>)`}var hh=RegExp(`(?:~/|[A-Za-z]:[\\\\/]|/)[^\\s"'\`<>|*?]+${dh}\\b`,`gi`),gh=/^[\s,。、;:!?,;!?…—·()【】「」『』“”‘’"'《》]$/;function _h(e){if(e===``)return e;let t=e.replace(/(?<!!)\[([^\]\n]*)\]\(([^)\s]+)\)/g,(e,t,n)=>fh(n)?mh(n,t):e);return t.replace(hh,(e,n)=>{let r=n>0?t[n-1]:``;return r!==``&&!gh.test(r)?e:mh(e)})}function vh(e){if(!e.includes(`.`))return e;let t=``,n=0;for(let r of e.matchAll(/(`+)([^`]+?)\1/g)){let i=r.index??0;t+=_h(e.slice(n,i));let a=r[2]??``;t+=fh(a)?mh(a):r[0],n=i+r[0].length}return t+_h(e.slice(n))}function yh(e){if(!new RegExp(dh,`i`).test(e))return e;let t=null;return e.split(`
19
19
  `).map(e=>{let n=/^\s*(```|~~~)/.exec(e);return t===null?n?(t=n[1],e):/^\s*\|/.test(e)?e:vh(e):(n&&(t=null),e)}).join(`
20
20
  `)}var bh=/^\s*(?:!\[[^\]]*\]\(\s*<?[^)\s>]+>?\s*\)\s*)+$/;function xh(e){if(!new RegExp(dh,`i`).test(e))return e;let t=[],n=null,r=[],i=(e=!1)=>{r.length!==0&&(t.push(r.join(`
21
21
  `)),e||t.push(``),r=[])};for(let a of e.split(`
22
22
  `)){let e=/^\s*(```|~~~)/.exec(a);if(n!==null)i(),e&&(n=null),t.push(a);else if(e)i(),n=e[1],t.push(a);else if(a.trim()===``){if(r.length>0)continue;t.push(a)}else bh.test(a)?r.push(a.trim()):(i(),t.push(a))}return i(!0),t.join(`
23
- `)}function Sh(e){return typeof e==`string`?/language-([\w+-]+)/.exec(e)?.[1]??``:``}function Ch(e,t,n){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=1||!Th(n)?null:Math.round(e/Math.min(t,2))}function wh(e){let t=Ch(e.naturalWidth,e.dpr,e.src),n=e.cap!==null&&Number.isFinite(e.cap)&&e.cap>0?e.cap:null,r=t===null?n:n===null?t:Math.min(t,n),i=e.availableWidth;if(i!==null&&Number.isFinite(i)&&i>0){let e=Math.floor(i);r=r===null?e:Math.min(r,e)}return r}function Th(e){return e.startsWith(`/n/`)||e.startsWith(`/api/uploads/`)}function Eh(e,t,n,r){let[i,a]=(0,C.useState)(()=>ni(e,t,n,r));return(0,C.useEffect)(()=>ii(e,e=>a(ti(e,t,n,r))),[e,t,n,r]),[i,i=>ri(e,ti(i,t,n,r))]}var Dh=[{id:`light`,name:`清亮白`,nameEn:`Bright`,hint:`白底蓝调,默认`,hintEn:`White with blue accents (default)`,swatch:[`#ffffff`,`#eef1f5`,`#1f6feb`]},{id:`light-warm`,name:`暖纸`,nameEn:`Warm paper`,hint:`米白赭石,偏护眼`,hintEn:`Cream and ochre, easy on the eyes`,swatch:[`#fbf7f0`,`#eee4d4`,`#b4530a`]},{id:`light-cool`,name:`雾青`,nameEn:`Misty teal`,hint:`冷灰墨绿,最冷静`,hintEn:`Cool grey and pine, the calmest`,swatch:[`#f6f9f9`,`#e3ecec`,`#0f766e`]},{id:`dark`,name:`东京夜`,nameEn:`Tokyo night`,hint:`蓝紫夜色,Tokyo Night`,hintEn:`Blue-violet night, Tokyo Night`,swatch:[`#1a1b26`,`#292e42`,`#7aa2f7`]},{id:`dark-night`,name:`摩卡`,nameEn:`Mocha`,hint:`低饱和紫灰,Catppuccin`,hintEn:`Muted purple-grey, Catppuccin`,swatch:[`#1e1e2e`,`#313244`,`#cba6f7`]},{id:`dark-warm`,name:`北境`,nameEn:`Nord`,hint:`冷灰青,最冷静,Nord`,hintEn:`Cool grey-teal, the calmest, Nord`,swatch:[`#2e3440`,`#434c5e`,`#88c0d0`]},{id:`dark-vscode`,name:`VSCode 暗色`,nameEn:`VSCode Dark`,hint:`经典中性灰,VS Code Dark+`,hintEn:`Classic neutral grey, VS Code Dark+`,swatch:[`#1f1f1f`,`#252526`,`#3794ff`]}],Oh=`pop-agent.theme`,kh=`pop-agent:theme`;function Ah(e){return e.startsWith(`dark`)?`dark`:`light`}function jh(e){return Dh.find(t=>t.id===e)??null}function Mh(e){let t=jh(e);return t?t.id:`light`}var Nh=Dh[0];function Ph(){return Nh}function Fh(e){let t=jh(e)??Dh[0];Nh=t;let n=document.documentElement;n.setAttribute(`data-theme`,t.id),n.setAttribute(`data-theme-mode`,Ah(t.id));let r=document.querySelector(`meta[name="theme-color"]`);if(r){let e=getComputedStyle(n).getPropertyValue(`--bg`).trim();r.setAttribute(`content`,e||t.swatch[0])}return window.dispatchEvent(new CustomEvent(kh,{detail:t})),t}function Ih(){return Fh(Mh(localStorage.getItem(Oh))).id}function Lh(e){Fh(e);try{localStorage.setItem(Oh,e)}catch{}}function Rh(e){let t=t=>e(t.detail??Nh),n=t=>{t.key===Oh&&e(Fh(Mh(t.newValue)))};return window.addEventListener(kh,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(kh,t),window.removeEventListener(`storage`,n)}}var zh=!1,Bh=`-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif`,Vh=.8;function Hh(){let e=getComputedStyle(document.documentElement),t=(t,n)=>e.getPropertyValue(t).trim()||n;return{mode:document.documentElement.getAttribute(`data-theme-mode`)===`dark`?`dark`:`light`,bg:t(`--bg`,`#ffffff`),elev:t(`--bg-elev`,`#f7f8fa`),elev2:t(`--bg-elev-2`,`#eef1f5`),border:t(`--border`,`#e2e6ec`),borderStrong:t(`--border-strong`,`#cfd6df`),text:t(`--text`,`#1b2530`),textDim:t(`--text-dim`,`#4a5a6a`),accent:t(`--accent`,`#1f6feb`),green:t(`--green`,`#1a7f37`),amber:t(`--amber`,`#b06a00`)}}function Uh(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=t[1].length===3?t[1].replace(/./g,e=>e+e):t[1];return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function Wh(e,t,n){let r=Uh(e),i=Uh(t);if(!r||!i)return t;let a=e=>Math.round(r[e]+(i[e]-r[e])*n),o=e=>e.toString(16).padStart(2,`0`);return`#${o(a(0))}${o(a(1))}${o(a(2))}`}function Gh(e){let t=Wh(e.accent,e.bg,.88),n=Wh(e.green,e.bg,.88),r=Wh(e.amber,e.bg,.86);return{darkMode:e.mode===`dark`,fontFamily:Bh,fontSize:`14px`,background:e.bg,textColor:e.text,labelColor:e.text,titleColor:e.text,lineColor:e.textDim,defaultLinkColor:e.textDim,primaryColor:t,primaryTextColor:e.text,primaryBorderColor:e.accent,mainBkg:t,nodeBorder:e.accent,nodeTextColor:e.text,secondaryColor:n,secondaryTextColor:e.text,secondaryBorderColor:e.green,tertiaryColor:r,tertiaryTextColor:e.text,tertiaryBorderColor:e.amber,clusterBkg:e.elev,clusterBorder:e.borderStrong,edgeLabelBackground:e.elev2,labelBackground:e.elev2,noteBkgColor:r,noteTextColor:e.text,noteBorderColor:e.amber,errorBkgColor:Wh(e.border,e.bg,.5),errorTextColor:e.text,actorBkg:t,actorBorder:e.accent,actorTextColor:e.text,actorLineColor:e.borderStrong,signalColor:e.textDim,signalTextColor:e.text,labelBoxBkgColor:e.elev2,labelBoxBorderColor:e.borderStrong,labelTextColor:e.text,loopTextColor:e.text,activationBkgColor:Wh(e.accent,e.bg,.78),activationBorderColor:e.accent,sequenceNumberColor:e.bg,classText:e.text}}function Kh({code:e}){let t=J(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(0),u=(0,C.useRef)(``),d=(0,C.useRef)(null);(0,C.useEffect)(()=>Rh(()=>{zh=!1,u.current=``,l(e=>e+1)}),[]),(0,C.useEffect)(()=>{if(u.current===e)return;let t=!1;return(async()=>{try{let{default:n}=await De(async()=>{let{default:e}=await import(`./mermaid.core-CdVzG6_M.js`);return{default:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]));if(!zh){let e=Hh();n.initialize({startOnLoad:!1,securityLevel:`strict`,theme:`base`,themeVariables:Gh(e),themeCSS:`
23
+ `)}function Sh(e){return typeof e==`string`?/language-([\w+-]+)/.exec(e)?.[1]??``:``}function Ch(e,t,n){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=1||!Th(n)?null:Math.round(e/Math.min(t,2))}function wh(e){let t=Ch(e.naturalWidth,e.dpr,e.src),n=e.cap!==null&&Number.isFinite(e.cap)&&e.cap>0?e.cap:null,r=t===null?n:n===null?t:Math.min(t,n),i=e.availableWidth;if(i!==null&&Number.isFinite(i)&&i>0){let e=Math.floor(i);r=r===null?e:Math.min(r,e)}return r}function Th(e){return e.startsWith(`/n/`)||e.startsWith(`/api/uploads/`)}function Eh(e,t,n,r){let[i,a]=(0,C.useState)(()=>ni(e,t,n,r));return(0,C.useEffect)(()=>ii(e,e=>a(ti(e,t,n,r))),[e,t,n,r]),[i,i=>ri(e,ti(i,t,n,r))]}var Dh=[{id:`light`,name:`清亮白`,nameEn:`Bright`,hint:`白底蓝调,默认`,hintEn:`White with blue accents (default)`,swatch:[`#ffffff`,`#eef1f5`,`#1f6feb`]},{id:`light-warm`,name:`暖纸`,nameEn:`Warm paper`,hint:`米白赭石,偏护眼`,hintEn:`Cream and ochre, easy on the eyes`,swatch:[`#fbf7f0`,`#eee4d4`,`#b4530a`]},{id:`light-cool`,name:`雾青`,nameEn:`Misty teal`,hint:`冷灰墨绿,最冷静`,hintEn:`Cool grey and pine, the calmest`,swatch:[`#f6f9f9`,`#e3ecec`,`#0f766e`]},{id:`dark`,name:`东京夜`,nameEn:`Tokyo night`,hint:`蓝紫夜色,Tokyo Night`,hintEn:`Blue-violet night, Tokyo Night`,swatch:[`#1a1b26`,`#292e42`,`#7aa2f7`]},{id:`dark-night`,name:`摩卡`,nameEn:`Mocha`,hint:`低饱和紫灰,Catppuccin`,hintEn:`Muted purple-grey, Catppuccin`,swatch:[`#1e1e2e`,`#313244`,`#cba6f7`]},{id:`dark-warm`,name:`北境`,nameEn:`Nord`,hint:`冷灰青,最冷静,Nord`,hintEn:`Cool grey-teal, the calmest, Nord`,swatch:[`#2e3440`,`#434c5e`,`#88c0d0`]},{id:`dark-vscode`,name:`VSCode 暗色`,nameEn:`VSCode Dark`,hint:`经典中性灰,VS Code Dark+`,hintEn:`Classic neutral grey, VS Code Dark+`,swatch:[`#1f1f1f`,`#252526`,`#3794ff`]}],Oh=`pop-agent.theme`,kh=`pop-agent:theme`;function Ah(e){return e.startsWith(`dark`)?`dark`:`light`}function jh(e){return Dh.find(t=>t.id===e)??null}function Mh(e){let t=jh(e);return t?t.id:`light`}var Nh=Dh[0];function Ph(){return Nh}function Fh(e){let t=jh(e)??Dh[0];Nh=t;let n=document.documentElement;n.setAttribute(`data-theme`,t.id),n.setAttribute(`data-theme-mode`,Ah(t.id));let r=document.querySelector(`meta[name="theme-color"]`);if(r){let e=getComputedStyle(n).getPropertyValue(`--bg`).trim();r.setAttribute(`content`,e||t.swatch[0])}return window.dispatchEvent(new CustomEvent(kh,{detail:t})),t}function Ih(){return Fh(Mh(localStorage.getItem(Oh))).id}function Lh(e){Fh(e);try{localStorage.setItem(Oh,e)}catch{}}function Rh(e){let t=t=>e(t.detail??Nh),n=t=>{t.key===Oh&&e(Fh(Mh(t.newValue)))};return window.addEventListener(kh,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(kh,t),window.removeEventListener(`storage`,n)}}var zh=!1,Bh=`-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif`,Vh=.8;function Hh(){let e=getComputedStyle(document.documentElement),t=(t,n)=>e.getPropertyValue(t).trim()||n;return{mode:document.documentElement.getAttribute(`data-theme-mode`)===`dark`?`dark`:`light`,bg:t(`--bg`,`#ffffff`),elev:t(`--bg-elev`,`#f7f8fa`),elev2:t(`--bg-elev-2`,`#eef1f5`),border:t(`--border`,`#e2e6ec`),borderStrong:t(`--border-strong`,`#cfd6df`),text:t(`--text`,`#1b2530`),textDim:t(`--text-dim`,`#4a5a6a`),accent:t(`--accent`,`#1f6feb`),green:t(`--green`,`#1a7f37`),amber:t(`--amber`,`#b06a00`)}}function Uh(e){let t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let n=t[1].length===3?t[1].replace(/./g,e=>e+e):t[1];return[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)]}function Wh(e,t,n){let r=Uh(e),i=Uh(t);if(!r||!i)return t;let a=e=>Math.round(r[e]+(i[e]-r[e])*n),o=e=>e.toString(16).padStart(2,`0`);return`#${o(a(0))}${o(a(1))}${o(a(2))}`}function Gh(e){let t=Wh(e.accent,e.bg,.88),n=Wh(e.green,e.bg,.88),r=Wh(e.amber,e.bg,.86);return{darkMode:e.mode===`dark`,fontFamily:Bh,fontSize:`14px`,background:e.bg,textColor:e.text,labelColor:e.text,titleColor:e.text,lineColor:e.textDim,defaultLinkColor:e.textDim,primaryColor:t,primaryTextColor:e.text,primaryBorderColor:e.accent,mainBkg:t,nodeBorder:e.accent,nodeTextColor:e.text,secondaryColor:n,secondaryTextColor:e.text,secondaryBorderColor:e.green,tertiaryColor:r,tertiaryTextColor:e.text,tertiaryBorderColor:e.amber,clusterBkg:e.elev,clusterBorder:e.borderStrong,edgeLabelBackground:e.elev2,labelBackground:e.elev2,noteBkgColor:r,noteTextColor:e.text,noteBorderColor:e.amber,errorBkgColor:Wh(e.border,e.bg,.5),errorTextColor:e.text,actorBkg:t,actorBorder:e.accent,actorTextColor:e.text,actorLineColor:e.borderStrong,signalColor:e.textDim,signalTextColor:e.text,labelBoxBkgColor:e.elev2,labelBoxBorderColor:e.borderStrong,labelTextColor:e.text,loopTextColor:e.text,activationBkgColor:Wh(e.accent,e.bg,.78),activationBorderColor:e.accent,sequenceNumberColor:e.bg,classText:e.text}}function Kh({code:e}){let t=Y(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(0),u=(0,C.useRef)(``),d=(0,C.useRef)(null);(0,C.useEffect)(()=>Rh(()=>{zh=!1,u.current=``,l(e=>e+1)}),[]),(0,C.useEffect)(()=>{if(u.current===e)return;let t=!1;return(async()=>{try{let{default:n}=await Ee(async()=>{let{default:e}=await import(`./mermaid.core-CQFwDpsY.js`);return{default:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]));if(!zh){let e=Hh();n.initialize({startOnLoad:!1,securityLevel:`strict`,theme:`base`,themeVariables:Gh(e),themeCSS:`
24
24
  .edgeLabel, .edgeLabel p, .edgeLabel span { color: ${e.text}; fill: ${e.text}; }
25
25
  .edgeLabel rect, .edgeLabel .labelBkg { fill: ${e.elev2}; opacity: 1; }
26
26
  .nodeLabel, .label { color: ${e.text}; }
@@ -28,16 +28,16 @@ import{i as e,n as t,r as n,t as r}from"./react-TO3cgmuO.js";import{a as i,c as
28
28
  .node rect, .node polygon, .node circle, .node ellipse, .node path,
29
29
  .cluster rect, .label-container { filter: none; rx: 6px; ry: 6px; }
30
30
  `,flowchart:{htmlLabels:!1,useMaxWidth:!0,nodeSpacing:34,rankSpacing:46,padding:8,wrappingWidth:220},sequence:{useMaxWidth:!0},gantt:{useMaxWidth:!0}}),zh=!0}let i=`mmd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`,{svg:o}=await n.render(i,e);if(t)return;u.current=e,r(o),a(null)}catch(e){if(t)return;a(e instanceof Error?e.message:String(e))}})(),()=>{t=!0}},[e,c]);let f=n!==null&&!o&&i===null;return(0,C.useLayoutEffect)(()=>{if(!n||!f)return;let e=d.current,t=e?.querySelector(`svg`);if(!e||!t)return;let r=t.viewBox?.baseVal?.width??0;if(!r)return;t.style.maxWidth=`none`;let i=()=>{let n=getComputedStyle(e),i=(parseFloat(n.paddingLeft)||0)+(parseFloat(n.paddingRight)||0),a=Math.max(0,e.clientWidth-i);if(a<=0)return;let o=Math.min(r,a);o<r*Vh&&(o=Math.round(r*Vh)),t.style.width=`${Math.round(o)}px`,t.style.height=`auto`};i();let a=new ResizeObserver(i);return a.observe(e),()=>a.disconnect()},[n,f]),(0,Q.jsxs)(`div`,{className:`mermaid-block`,children:[(0,Q.jsxs)(`div`,{className:`mermaid-head`,children:[(0,Q.jsx)(`span`,{className:`mermaid-lang`,children:`mermaid`}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`mermaid-btn${f?` mermaid-btn-on`:``}`,onClick:()=>s(!1),disabled:n===null,children:`SVG`}),(0,Q.jsx)(`button`,{type:`button`,className:`mermaid-btn${f?``:` mermaid-btn-on`}`,onClick:()=>s(!0),children:t(`源代码`,`Source`)})]}),f?(0,Q.jsx)(`div`,{className:`mermaid-svg`,ref:d,dangerouslySetInnerHTML:{__html:n??``}}):(0,Q.jsx)(`pre`,{className:`mermaid-source mono`,children:e}),i?(0,Q.jsxs)(`div`,{className:`mermaid-error`,children:[t(`渲染失败:`,`Render failed: `),i]}):null]})}var qh=/https?:\/\/[^\s<>"'`|\\]+/gi,Jh=/[.,;:!?,。、;:!?]+$/,Yh=/^https?:\/\/[^/\s]+/i;function Xh(e){let t=e.replace(Jh,``);return Yh.test(t)?t:null}function Zh(e){let t=e.trim();return t===``||/\s/.test(t)?!1:Xh(t)!==null&&Xh(t)===t}function Qh(e){let t=[],n=0;for(let r of e.matchAll(qh)){let i=Xh(r[0]),a=r.index??0;i!==null&&(a>n&&t.push({text:e.slice(n,a)}),t.push({text:i,url:i}),n=a+i.length)}return n<e.length&&t.push({text:e.slice(n)}),t.length>0?t:[{text:e}]}var $h=null;function eg(e){$h=e}function tg(e){$h?.(e)}var ng=new Set(`md.markdown.txt.json.jsonl.yml.yaml.toml.ini.log.csv.tsv.html.htm.xml.css.scss.js.mjs.cjs.ts.tsx.jsx.py.go.rs.java.kt.swift.rb.php.sh.bash.zsh.png.jpg.jpeg.gif.webp.svg.pdf.doc.docx.xls.xlsx.zip`.split(`.`));function rg(e){let t=e.trim();if(t===``||t.length>300||/^https?:\/\//i.test(t)||/\s/.test(t))return!1;let n=/^[^\s]+\.([A-Za-z0-9]{1,8})$/.exec(t);return!(!n||!ng.has(n[1].toLowerCase()))}var ig=/(https?:\/\/[^\s<>"'`|\\]+)|((?:~\/|\.{0,2}\/)?[\w@.\-/()()\u4e00-\u9fff]+\.([A-Za-z0-9]{1,8})\b)/g;function ag(e){let t=[],n=0;for(let r of e.matchAll(ig)){if(r[1]!==void 0){let i=Xh(r[1]);if(i===null)continue;let a=r.index??0;a>n&&t.push({text:e.slice(n,a)}),t.push({text:i,url:i}),n=a+i.length;continue}let i=r[2],a=(r[3]??``).toLowerCase();if(!ng.has(a))continue;let o=r.index??0;o>n&&t.push({text:e.slice(n,o)}),t.push({text:i,path:i}),n=o+i.length}return n<e.length&&t.push({text:e.slice(n)}),t.length>0?t:[{text:e}]}function og(e){let t=e.split(`
31
- `).filter(e=>e.trim()!==``);return t.length<2?!1:t.filter(e=>ag(e).some(e=>e.path!==void 0||e.url!==void 0)).length*2>=t.length}function sg(e){let t=e.parentElement;return t?.classList.contains(`md-img-btn`)?t.parentElement:t}function cg(e){let t=sg(e);if(!t)return null;let n=getComputedStyle(t),r=(parseFloat(n.paddingLeft)||0)+(parseFloat(n.paddingRight)||0),i=t.clientWidth-r;return Number.isFinite(i)&&i>0?i:null}function lg({src:e,path:t,alt:n}){let[r]=Eh(Jr,400,0,4e3),[i,a]=(0,C.useState)(null),o=i===e,s=ch(t),c=(0,C.useRef)(null),l=(0,C.useCallback)(()=>{let t=c.current;if(!t||!t.complete||t.naturalWidth===0)return;let n=wh({naturalWidth:t.naturalWidth,dpr:window.devicePixelRatio||1,src:e,cap:r>0?r:null,availableWidth:cg(t)});n===null?t.style.removeProperty(`--md-img-cap`):t.style.setProperty(`--md-img-cap`,`${n}px`)},[r,e]);return(0,C.useEffect)(l,[l]),(0,C.useEffect)(()=>{let e=c.current,t=e?sg(e):null;if(!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>l());return n.observe(t),()=>n.disconnect()},[l]),o?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:q(`这张图没能加载,点这里在右侧打开这个文件`,`Could not load this image — open the file on the right`),onClick:()=>tg(s),children:s||n}):(0,Q.jsx)(`button`,{type:`button`,className:`md-img-btn`,title:q(`点击放大预览`,`Click to preview`),onClick:()=>ns(e,n),children:(0,Q.jsx)(`img`,{ref:c,className:`md-img`,src:e,alt:n,loading:`lazy`,onLoad:l,onError:()=>a(e)})})}function ug(e){return e.type===`text`?(e.value??``).trim()===``:e.type===`element`&&e.tagName===`br`}function dg(e){if(e.type!==`element`)return!1;if(e.tagName===`img`)return!0;if(e.tagName!==`a`)return!1;let t=e.properties?.href;return typeof t==`string`&&!/^https?:\/\//i.test(t)&&fh(t)}function fg(e){let t=e?.children;if(!Array.isArray(t)||t.length===0)return!1;let n=0;for(let e of t)if(dg(e))n+=1;else if(!ug(e))return!1;return n>0}function pg({href:e,children:t}){return(0,Q.jsx)(`a`,{className:`md-link`,href:e,target:`_blank`,rel:`noopener noreferrer`,title:q(`在新标签页打开`,`Open in a new tab`),children:t})}var mg={a:({href:e,children:t})=>{if(typeof e==`string`&&!/^https?:\/\//i.test(e)&&fh(e)){let n=lh(e);if(n)return(0,Q.jsx)(lg,{src:n,path:e,alt:typeof t==`string`?t:``})}return typeof e==`string`&&/^https?:\/\//i.test(e)?(0,Q.jsx)(pg,{href:e,children:t}):(0,Q.jsx)(`a`,{className:`md-link`,target:`_blank`,rel:`noopener noreferrer`,children:t})},img:({src:e,alt:t})=>{let n=typeof e==`string`?lh(e):null;return n?(0,Q.jsx)(lg,{src:n,path:typeof e==`string`?e:``,alt:t??``}):(0,Q.jsxs)(`span`,{className:`md-img-blocked`,children:[q(`图片已拦截`,`Image blocked`),` `,t??``]})},p:({node:e,children:t,...n})=>fg(e)?(0,Q.jsx)(`div`,{className:`md-img-grid`,children:t}):(0,Q.jsx)(`p`,{...n,children:t}),pre:({children:e,...t})=>(0,Q.jsx)(`div`,{className:`md-pre`,children:(0,Q.jsx)(`pre`,{...t,children:e})}),code:({className:e,children:t,...n})=>{let r=Sh(e),i=String(t).replace(/\n$/,``);return r===`mermaid`?(0,Q.jsx)(Kh,{code:i}):r!==``||typeof t==`string`&&t.includes(`
31
+ `).filter(e=>e.trim()!==``);return t.length<2?!1:t.filter(e=>ag(e).some(e=>e.path!==void 0||e.url!==void 0)).length*2>=t.length}function sg(e){let t=e.parentElement;return t?.classList.contains(`md-img-btn`)?t.parentElement:t}function cg(e){let t=sg(e);if(!t)return null;let n=getComputedStyle(t),r=(parseFloat(n.paddingLeft)||0)+(parseFloat(n.paddingRight)||0),i=t.clientWidth-r;return Number.isFinite(i)&&i>0?i:null}function lg({src:e,path:t,alt:n}){let[r]=Eh(Jr,400,0,4e3),[i,a]=(0,C.useState)(null),o=i===e,s=ch(t),c=(0,C.useRef)(null),l=(0,C.useCallback)(()=>{let t=c.current;if(!t||!t.complete||t.naturalWidth===0)return;let n=wh({naturalWidth:t.naturalWidth,dpr:window.devicePixelRatio||1,src:e,cap:r>0?r:null,availableWidth:cg(t)});n===null?t.style.removeProperty(`--md-img-cap`):t.style.setProperty(`--md-img-cap`,`${n}px`)},[r,e]);return(0,C.useEffect)(l,[l]),(0,C.useEffect)(()=>{let e=c.current,t=e?sg(e):null;if(!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>l());return n.observe(t),()=>n.disconnect()},[l]),o?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:J(`这张图没能加载,点这里在右侧打开这个文件`,`Could not load this image — open the file on the right`),onClick:()=>tg(s),children:s||n}):(0,Q.jsx)(`button`,{type:`button`,className:`md-img-btn`,title:J(`点击放大预览`,`Click to preview`),onClick:()=>ns(e,n),children:(0,Q.jsx)(`img`,{ref:c,className:`md-img`,src:e,alt:n,loading:`lazy`,onLoad:l,onError:()=>a(e)})})}function ug(e){return e.type===`text`?(e.value??``).trim()===``:e.type===`element`&&e.tagName===`br`}function dg(e){if(e.type!==`element`)return!1;if(e.tagName===`img`)return!0;if(e.tagName!==`a`)return!1;let t=e.properties?.href;return typeof t==`string`&&!/^https?:\/\//i.test(t)&&fh(t)}function fg(e){let t=e?.children;if(!Array.isArray(t)||t.length===0)return!1;let n=0;for(let e of t)if(dg(e))n+=1;else if(!ug(e))return!1;return n>0}function pg({href:e,children:t}){return(0,Q.jsx)(`a`,{className:`md-link`,href:e,target:`_blank`,rel:`noopener noreferrer`,title:J(`在新标签页打开`,`Open in a new tab`),children:t})}var mg={a:({href:e,children:t})=>{if(typeof e==`string`&&!/^https?:\/\//i.test(e)&&fh(e)){let n=lh(e);if(n)return(0,Q.jsx)(lg,{src:n,path:e,alt:typeof t==`string`?t:``})}return typeof e==`string`&&/^https?:\/\//i.test(e)?(0,Q.jsx)(pg,{href:e,children:t}):(0,Q.jsx)(`a`,{className:`md-link`,target:`_blank`,rel:`noopener noreferrer`,children:t})},img:({src:e,alt:t})=>{let n=typeof e==`string`?lh(e):null;return n?(0,Q.jsx)(lg,{src:n,path:typeof e==`string`?e:``,alt:t??``}):(0,Q.jsxs)(`span`,{className:`md-img-blocked`,children:[J(`图片已拦截`,`Image blocked`),` `,t??``]})},p:({node:e,children:t,...n})=>fg(e)?(0,Q.jsx)(`div`,{className:`md-img-grid`,children:t}):(0,Q.jsx)(`p`,{...n,children:t}),pre:({children:e,...t})=>(0,Q.jsx)(`div`,{className:`md-pre`,children:(0,Q.jsx)(`pre`,{...t,children:e})}),code:({className:e,children:t,...n})=>{let r=Sh(e),i=String(t).replace(/\n$/,``);return r===`mermaid`?(0,Q.jsx)(Kh,{code:i}):r!==``||typeof t==`string`&&t.includes(`
32
32
  `)?og(i)?(0,Q.jsxs)(Q.Fragment,{children:[r?(0,Q.jsx)(`span`,{className:`md-lang`,children:r}):null,(0,Q.jsx)(`code`,{className:`${e??``} md-path-block`,...n,children:i.split(`
33
- `).map((e,t)=>(0,Q.jsxs)(`span`,{className:`md-path-line`,children:[ag(e).map((e,t)=>e.url?(0,Q.jsx)(pg,{href:e.url,children:e.text},t):e.path?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:q(`在右侧预览这个文件`,`Preview this file on the right`),onClick:()=>tg(e.path),children:e.text},t):(0,Q.jsx)(`span`,{children:e.text},t)),`
34
- `]},t))})]}):(0,Q.jsxs)(Q.Fragment,{children:[r?(0,Q.jsx)(`span`,{className:`md-lang`,children:r}):null,(0,Q.jsx)(`code`,{className:e,...n,children:t})]}):Zh(i)?(0,Q.jsx)(pg,{href:i.trim(),children:t}):rg(i)?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:q(`在右侧预览这个文件`,`Preview this file on the right`),onClick:()=>tg(i.trim()),children:t}):(0,Q.jsx)(`code`,{className:e,...n,children:t})}},hg=150;function gg(e,t){let[n,r]=(0,C.useState)(e),i=(0,C.useRef)(e);i.current=e;let a=(0,C.useRef)(null);return(0,C.useEffect)(()=>{t?a.current===null&&(a.current=setTimeout(()=>{a.current=null,r(i.current)},hg)):(a.current!==null&&(clearTimeout(a.current),a.current=null),r(e))},[t,e]),(0,C.useEffect)(()=>()=>{a.current!==null&&clearTimeout(a.current)},[]),t?n:e}var _g=[b],vg=[[v,{detect:!0,ignoreMissing:!0}]],yg=[],bg=(0,C.memo)(function({text:e,live:t=!1,className:n}){let r=gg(e,t),i=(0,C.useMemo)(()=>xh(yh(r)),[r]);return(0,Q.jsx)(`div`,{className:n?`md ${n}`:`md`,children:(0,Q.jsx)(y,{remarkPlugins:_g,rehypePlugins:t?yg:vg,skipHtml:!0,components:mg,children:i})})}),xg=24;function Sg(e,t,n,r=xg){let i=Math.max(0,Math.min(t,e.length)),a=Math.max(i,Math.min(n,e.length)),o=i,s=a;for(;o<s&&/\s/.test(e[o]);)o+=1;for(;s>o&&/\s/.test(e[s-1]);)--s;return s<=o?null:{exact:e.slice(o,s),prefix:o>0?e.slice(Math.max(0,o-r),o):``,suffix:s<e.length?e.slice(s,Math.min(e.length,s+r)):``}}function Cg(e,t){if(t.exact===``)return null;let n=null,r=e.indexOf(t.exact);for(;r>=0;){let i=r+t.exact.length,a=wg(e,r,i,t);(n===null||a>n.score)&&(n={start:r,end:i,score:a}),r=e.indexOf(t.exact,r+1)}return n===null?null:{start:n.start,end:n.end}}function wg(e,t,n,r){let i=0;for(let n=1;n<=r.prefix.length&&t-n>=0&&e[t-n]===r.prefix[r.prefix.length-n];n+=1)i+=1;let a=0;for(let t=0;t<r.suffix.length&&n+t<e.length&&e[n+t]===r.suffix[t];t+=1)a+=1;return i+a}function Tg(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(let e=t.nextNode();e!==null;e=t.nextNode())n.push(e);return n}function Eg(e){return Tg(e).map(e=>e.data).join(``)}function Dg(e,t,n){if(n<=t)return null;let r=0,i=null,a=null;for(let o of Tg(e)){let e=o.data.length;if(i===null&&t<=r+e&&(i={node:o,offset:t-r}),a===null&&n<=r+e){a={node:o,offset:n-r};break}r+=e}if(i===null||a===null)return null;let o=document.createRange();return o.setStart(i.node,Math.max(0,i.offset)),o.setEnd(a.node,Math.max(0,a.offset)),o}function Og(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;let n=(t,n)=>{let r=document.createRange();r.selectNodeContents(e);try{r.setEnd(t,n)}catch{return null}return r.toString().length},r=n(t.startContainer,t.startOffset),i=n(t.endContainer,t.endOffset);return r===null||i===null?null:Sg(Eg(e),r,i)}function kg(e,t){let n=(e===null?null:e.nodeType===Node.ELEMENT_NODE?e:e.parentElement)?.closest(`article.msg`)??null;return n!==null&&t.contains(n)?n:null}function Ag(e,t,n){let r=e.querySelector(`.msg-body`);if(r===null)return null;let i=t===null?null:Og(r,t);if(i!==null)return i;let a=Eg(r).indexOf(n);return a<0?null:Sg(Eg(r),a,a+n.length)}function jg({container:e,onAddToSession:t,onAskInSideChat:n}){let r=J(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(``),u=(0,C.useRef)(null),d=(0,C.useRef)(!1);if((0,C.useEffect)(()=>{d.current=o},[o]),(0,C.useEffect)(()=>{i||(s(!1),l(``))},[i]),(0,C.useEffect)(()=>{if(!o)return;let e=e=>{u.current?.contains(e.target)||a(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[o]),(0,C.useEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{if(d.current)return;let e=window.getSelection();if(!e||e.isCollapsed||e.rangeCount===0){a(null);return}let n=e.toString().trim();if(n===``){a(null);return}let r=e.getRangeAt(0),i=kg(r.commonAncestorContainer,t);if(!i){a(null);return}let o=r.getBoundingClientRect();if(o.width===0&&o.height===0||o.bottom<0||o.top>window.innerHeight){a(null);return}let s=i.id.startsWith(`msg-`)?i.id.slice(4):``;a({text:n,centerX:o.left+o.width/2,top:o.top,bottom:o.bottom,inUser:i.classList.contains(`msg-user`),messageId:s,anchor:Ag(i,r.cloneRange(),n)})},r=()=>window.requestAnimationFrame(n),i=()=>{if(d.current)return;let e=window.getSelection();(!e||e.isCollapsed)&&a(null)},o=()=>a(null);return document.addEventListener(`mouseup`,r),document.addEventListener(`touchend`,r),document.addEventListener(`keyup`,r),document.addEventListener(`selectionchange`,i),window.addEventListener(`scroll`,o,!0),window.addEventListener(`resize`,o),()=>{document.removeEventListener(`mouseup`,r),document.removeEventListener(`touchend`,r),document.removeEventListener(`keyup`,r),document.removeEventListener(`selectionchange`,i),window.removeEventListener(`scroll`,o,!0),window.removeEventListener(`resize`,o)}},[e]),i===null)return null;let f=i.top<64,p={left:Math.min(Math.max(i.centerX,140),window.innerWidth-140),top:f?i.bottom+8:i.top-8,transform:f?`translate(-50%, 0)`:`translate(-50%, -100%)`},m=()=>{a(null),s(!1),l(``),window.getSelection()?.removeAllRanges()},h=e=>e.preventDefault(),g=()=>{t?.({text:i.text,messageId:i.messageId,anchor:i.anchor,comment:c.trim()}),m()};return o?(0,Q.jsxs)(`div`,{ref:u,className:`sel-toolbar sel-toolbar-comment`,style:p,role:`dialog`,"aria-label":r(`标注这一段`,`Annotate this passage`),children:[(0,Q.jsx)(`input`,{className:`sel-toolbar-input`,autoFocus:!0,value:c,placeholder:r(`写一句评论(可留空)`,`One line (optional)`),title:r(`写一句评论,回车收进会话`,`One line of comment; Enter adds it to this session`),"aria-label":r(`这一段的评论`,`Comment for this passage`),onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),g()):e.key===`Escape`&&(e.preventDefault(),m()),e.stopPropagation()}}),(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-ok`,title:r(`收进会话`,`Add to this session`),"aria-label":r(`收进会话`,`Add to this session`),onMouseDown:h,onClick:g,children:`✓`})]}):(0,Q.jsxs)(`div`,{ref:u,className:`sel-toolbar`,style:p,role:`toolbar`,"aria-label":r(`选中的文字`,`Selected text`),children:[t&&!i.inUser?(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{t({text:i.text,messageId:i.messageId,anchor:i.anchor,comment:``}),m()},title:r(`把这段收进这条会话:正文里留个编号,评论可以在输入框里那颗注释上补`,`Put this into this session: a number in the text; the note can be added inside the composer`),children:r(`添加到会话`,`Add to session`)}):null,t&&!i.inUser?(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{l(``),s(!0)},title:r(`标注这一段:写一句评论(可留空),正文里留个编号`,`Annotate this passage: one line of comment (optional), plus a number in the text`),children:r(`标注`,`Annotate`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{n(i.text),m()},children:r(`在临时会话中提问`,`Ask in a temp session`)})]})}var Mg=`annot-mark`;function Ng(){let e=CSS.highlights;return typeof e!=`object`||!e?null:e}function Pg(){let e=globalThis.Highlight;return typeof e==`function`?e:null}function Fg({container:e,annotations:t,onFocus:n}){let r=J(),i=(0,C.useRef)(null),[a,o]=(0,C.useState)([]);return(0,C.useLayoutEffect)(()=>{let n=e.current;if(n===null)return;let r=0,a=()=>{r=0;let e=i.current,a=n.getBoundingClientRect(),s=[],c=[],l=new Map;for(let e of n.querySelectorAll(`article.msg`))l.set(e.id,e);for(let r of t){if(Fu(r))continue;let i=l.get(`msg-${r.messageId}`)?.querySelector(`.msg-body`)??null;if(i===null)continue;let o=Cg(Eg(i),r.anchor);if(o===null)continue;let u=Dg(i,o.start,o.end);if(u===null||(c.push(u),e===null))continue;let d=u.getClientRects(),f=d.length>0?d[d.length-1]:u.getBoundingClientRect();(f.width!==0||f.height!==0)&&s.push({id:r.id,index:Qu(t,r.id),left:f.right-a.left+n.scrollLeft,top:f.bottom-a.top+n.scrollTop})}let u=Ng(),d=Pg();u!==null&&d!==null&&(c.length>0?u.set(Mg,new d(...c)):u.delete(Mg)),o(e=>e.length===s.length&&e.every((e,t)=>{let n=s[t];return n!==void 0&&e.id===n.id&&e.index===n.index&&Math.abs(e.left-n.left)<.5&&Math.abs(e.top-n.top)<.5})?e:s)},s=()=>{r===0&&(r=window.requestAnimationFrame(a))},c=new MutationObserver(e=>{let t=i.current;t!==null&&e.every(e=>t.contains(e.target))||s()});c.observe(n,{childList:!0,subtree:!0,characterData:!0});let l=new ResizeObserver(s);return l.observe(n),window.addEventListener(`resize`,s),s(),()=>{c.disconnect(),l.disconnect(),window.removeEventListener(`resize`,s),r!==0&&window.cancelAnimationFrame(r),Ng()?.delete(Mg)}},[e,t]),t.length===0?null:(0,Q.jsx)(`div`,{className:`annot-marks`,ref:i,children:a.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`annot-mark`,style:{left:e.left,top:e.top},title:r(`第 ${e.index} 条标注`,`Annotation ${e.index}`),"aria-label":r(`第 ${e.index} 条标注`,`Annotation ${e.index}`),onClick:()=>n?.(e.id),children:e.index},e.id))})}var Ig=2e3,Lg=200,Rg=120,zg=/^(bash|sh|shell|shell_command|exec|run|run_command|terminal|powershell)$/i,Bg=/^(read|view|cat|open|read_file|readfile)$/i,Vg=/^(list|ls|list_files|listfiles|glob|tree|dir)$/i,Hg=/^(grep|rg|search|find|search_files|find_files)$/i,Ug=/^(write|edit|str_replace|apply_patch|patch|multi_edit|multiedit|notebook_edit|create_file)$/i,Wg=/^(web_search|websearch|webfetch|web_fetch|fetch|browse|fetch_content)$/i,Gg=/^(agent|task|subagent|delegate)$/i,Kg=/^\s*(ls|dir|tree|find)\b/,qg=/^\s*(?:cd\s+\S+\s*&&\s*)*(curl|wget|http|httpie|aria2c)\b/;function Jg(e){return/(https?:\/\/[^\s'"|;&)]+)/.exec(e)?.[1]??null}var Yg=/(?:^|[\s&|;])(python3?|node|deno|bun|ruby|perl|php|bash|sh|zsh)\b/g,Xg=/(?:^|\s)(?:-e|--eval|-c|eval)\s+([\s\S]*)$/,Zg=/(?:^|[\s&|;])(?:pytest|py\.test|vitest|jest|mocha|ava|playwright\s+test|go\s+test|cargo\s+test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+(?:run\s+)?test)\b/,Qg=/(?:^|[\s&|;])(?:npm\s+run\s+build|pnpm\s+(?:run\s+)?build|yarn\s+(?:run\s+)?build|vite\s+build|tsc\b|make\b|cargo\s+build|go\s+build|webpack|rollup)\b/,$g=/(?:^|[\s&|;])(?:npm\s+(?:i|install|ci)|pnpm\s+(?:i|install|add)|yarn\s+(?:add|install)|pip3?\s+install|uv\s+(?:pip\s+)?install|brew\s+install|cargo\s+install)\b/,e_=/(?:^|[\s&|;])git\s+([a-z-]+)/,t_={commit:[`正在提交改动`,`已提交改动`],push:[`正在推送`,`已推送`],pull:[`正在拉取`,`已拉取`],fetch:[`正在同步远端`,`已同步远端`],status:[`正在看改动状态`,`已看改动状态`],diff:[`正在看差异`,`已看差异`],log:[`正在看提交历史`,`已看提交历史`],checkout:[`正在切分支`,`已切分支`],switch:[`正在切分支`,`已切分支`],merge:[`正在合并`,`已合并`],rebase:[`正在变基`,`已变基`],stash:[`正在暂存改动`,`已暂存改动`],add:[`正在暂存文件`,`已暂存文件`],clone:[`正在克隆仓库`,`已克隆仓库`]},n_={commit:[`Committing changes`,`Committed changes`],push:[`Pushing`,`Pushed`],pull:[`Pulling`,`Pulled`],fetch:[`Fetching from the remote`,`Fetched from the remote`],status:[`Checking the working tree`,`Checked the working tree`],diff:[`Reviewing the diff`,`Reviewed the diff`],log:[`Reading the commit history`,`Read the commit history`],checkout:[`Switching branches`,`Switched branches`],switch:[`Switching branches`,`Switched branches`],merge:[`Merging`,`Merged`],rebase:[`Rebasing`,`Rebased`],stash:[`Stashing changes`,`Stashed changes`],add:[`Staging files`,`Staged files`],clone:[`Cloning the repository`,`Cloned the repository`]};function r_(e){if(Zg.test(e))return{now:[`正在跑测试`,`Running the tests`],done:[`已跑完测试`,`Ran the tests`]};if(Qg.test(e))return{now:[`正在构建`,`Building`],done:[`已构建完成`,`Built`]};if($g.test(e))return{now:[`正在安装依赖`,`Installing dependencies`],done:[`已安装依赖`,`Installed dependencies`]};let t=e_.exec(e)?.[1],n=t?t_[t]:void 0;if(t&&n){let e=n_[t]??[`Running git ${t}`,`Ran git ${t}`];return{now:[n[0],e[0]],done:[n[1],e[1]]}}return null}var i_={python:`Python`,python3:`Python`,node:`Node`,deno:`Deno`,bun:`Bun`,ruby:`Ruby`,perl:`Perl`,bash:`shell`,sh:`shell`,zsh:`shell`};function a_(e){let t=e.indexOf(`<<`);if(t<0)return null;let n=/<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/.exec(e.slice(t))?.[1]??null,r=e.indexOf(`
33
+ `).map((e,t)=>(0,Q.jsxs)(`span`,{className:`md-path-line`,children:[ag(e).map((e,t)=>e.url?(0,Q.jsx)(pg,{href:e.url,children:e.text},t):e.path?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:J(`在右侧预览这个文件`,`Preview this file on the right`),onClick:()=>tg(e.path),children:e.text},t):(0,Q.jsx)(`span`,{children:e.text},t)),`
34
+ `]},t))})]}):(0,Q.jsxs)(Q.Fragment,{children:[r?(0,Q.jsx)(`span`,{className:`md-lang`,children:r}):null,(0,Q.jsx)(`code`,{className:e,...n,children:t})]}):Zh(i)?(0,Q.jsx)(pg,{href:i.trim(),children:t}):rg(i)?(0,Q.jsx)(`button`,{type:`button`,className:`md-path`,title:J(`在右侧预览这个文件`,`Preview this file on the right`),onClick:()=>tg(i.trim()),children:t}):(0,Q.jsx)(`code`,{className:e,...n,children:t})}},hg=150;function gg(e,t){let[n,r]=(0,C.useState)(e),i=(0,C.useRef)(e);i.current=e;let a=(0,C.useRef)(null);return(0,C.useEffect)(()=>{t?a.current===null&&(a.current=setTimeout(()=>{a.current=null,r(i.current)},hg)):(a.current!==null&&(clearTimeout(a.current),a.current=null),r(e))},[t,e]),(0,C.useEffect)(()=>()=>{a.current!==null&&clearTimeout(a.current)},[]),t?n:e}var _g=[b],vg=[[v,{detect:!0,ignoreMissing:!0}]],yg=[],bg=(0,C.memo)(function({text:e,live:t=!1,className:n}){let r=gg(e,t),i=(0,C.useMemo)(()=>xh(yh(r)),[r]);return(0,Q.jsx)(`div`,{className:n?`md ${n}`:`md`,children:(0,Q.jsx)(y,{remarkPlugins:_g,rehypePlugins:t?yg:vg,skipHtml:!0,components:mg,children:i})})}),xg=24;function Sg(e,t,n,r=xg){let i=Math.max(0,Math.min(t,e.length)),a=Math.max(i,Math.min(n,e.length)),o=i,s=a;for(;o<s&&/\s/.test(e[o]);)o+=1;for(;s>o&&/\s/.test(e[s-1]);)--s;return s<=o?null:{exact:e.slice(o,s),prefix:o>0?e.slice(Math.max(0,o-r),o):``,suffix:s<e.length?e.slice(s,Math.min(e.length,s+r)):``}}function Cg(e,t){if(t.exact===``)return null;let n=null,r=e.indexOf(t.exact);for(;r>=0;){let i=r+t.exact.length,a=wg(e,r,i,t);(n===null||a>n.score)&&(n={start:r,end:i,score:a}),r=e.indexOf(t.exact,r+1)}return n===null?null:{start:n.start,end:n.end}}function wg(e,t,n,r){let i=0;for(let n=1;n<=r.prefix.length&&t-n>=0&&e[t-n]===r.prefix[r.prefix.length-n];n+=1)i+=1;let a=0;for(let t=0;t<r.suffix.length&&n+t<e.length&&e[n+t]===r.suffix[t];t+=1)a+=1;return i+a}function Tg(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[];for(let e=t.nextNode();e!==null;e=t.nextNode())n.push(e);return n}function Eg(e){return Tg(e).map(e=>e.data).join(``)}function Dg(e,t,n){if(n<=t)return null;let r=0,i=null,a=null;for(let o of Tg(e)){let e=o.data.length;if(i===null&&t<=r+e&&(i={node:o,offset:t-r}),a===null&&n<=r+e){a={node:o,offset:n-r};break}r+=e}if(i===null||a===null)return null;let o=document.createRange();return o.setStart(i.node,Math.max(0,i.offset)),o.setEnd(a.node,Math.max(0,a.offset)),o}function Og(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))return null;let n=(t,n)=>{let r=document.createRange();r.selectNodeContents(e);try{r.setEnd(t,n)}catch{return null}return r.toString().length},r=n(t.startContainer,t.startOffset),i=n(t.endContainer,t.endOffset);return r===null||i===null?null:Sg(Eg(e),r,i)}function kg(e,t){let n=(e===null?null:e.nodeType===Node.ELEMENT_NODE?e:e.parentElement)?.closest(`article.msg`)??null;return n!==null&&t.contains(n)?n:null}function Ag(e,t,n){let r=e.querySelector(`.msg-body`);if(r===null)return null;let i=t===null?null:Og(r,t);if(i!==null)return i;let a=Eg(r).indexOf(n);return a<0?null:Sg(Eg(r),a,a+n.length)}function jg({container:e,onAddToSession:t,onAskInSideChat:n}){let r=Y(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(``),u=(0,C.useRef)(null),d=(0,C.useRef)(!1);if((0,C.useEffect)(()=>{d.current=o},[o]),(0,C.useEffect)(()=>{i||(s(!1),l(``))},[i]),(0,C.useEffect)(()=>{if(!o)return;let e=e=>{u.current?.contains(e.target)||a(null)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[o]),(0,C.useEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{if(d.current)return;let e=window.getSelection();if(!e||e.isCollapsed||e.rangeCount===0){a(null);return}let n=e.toString().trim();if(n===``){a(null);return}let r=e.getRangeAt(0),i=kg(r.commonAncestorContainer,t);if(!i){a(null);return}let o=r.getBoundingClientRect();if(o.width===0&&o.height===0||o.bottom<0||o.top>window.innerHeight){a(null);return}let s=i.id.startsWith(`msg-`)?i.id.slice(4):``;a({text:n,centerX:o.left+o.width/2,top:o.top,bottom:o.bottom,inUser:i.classList.contains(`msg-user`),messageId:s,anchor:Ag(i,r.cloneRange(),n)})},r=()=>window.requestAnimationFrame(n),i=()=>{if(d.current)return;let e=window.getSelection();(!e||e.isCollapsed)&&a(null)},o=()=>a(null);return document.addEventListener(`mouseup`,r),document.addEventListener(`touchend`,r),document.addEventListener(`keyup`,r),document.addEventListener(`selectionchange`,i),window.addEventListener(`scroll`,o,!0),window.addEventListener(`resize`,o),()=>{document.removeEventListener(`mouseup`,r),document.removeEventListener(`touchend`,r),document.removeEventListener(`keyup`,r),document.removeEventListener(`selectionchange`,i),window.removeEventListener(`scroll`,o,!0),window.removeEventListener(`resize`,o)}},[e]),i===null)return null;let f=i.top<64,p={left:Math.min(Math.max(i.centerX,140),window.innerWidth-140),top:f?i.bottom+8:i.top-8,transform:f?`translate(-50%, 0)`:`translate(-50%, -100%)`},m=()=>{a(null),s(!1),l(``),window.getSelection()?.removeAllRanges()},h=e=>e.preventDefault(),g=()=>{t?.({text:i.text,messageId:i.messageId,anchor:i.anchor,comment:c.trim()}),m()};return o?(0,Q.jsxs)(`div`,{ref:u,className:`sel-toolbar sel-toolbar-comment`,style:p,role:`dialog`,"aria-label":r(`标注这一段`,`Annotate this passage`),children:[(0,Q.jsx)(`input`,{className:`sel-toolbar-input`,autoFocus:!0,value:c,placeholder:r(`写一句评论(可留空)`,`One line (optional)`),title:r(`写一句评论,回车收进会话`,`One line of comment; Enter adds it to this session`),"aria-label":r(`这一段的评论`,`Comment for this passage`),onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),g()):e.key===`Escape`&&(e.preventDefault(),m()),e.stopPropagation()}}),(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-ok`,title:r(`收进会话`,`Add to this session`),"aria-label":r(`收进会话`,`Add to this session`),onMouseDown:h,onClick:g,children:`✓`})]}):(0,Q.jsxs)(`div`,{ref:u,className:`sel-toolbar`,style:p,role:`toolbar`,"aria-label":r(`选中的文字`,`Selected text`),children:[t&&!i.inUser?(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{t({text:i.text,messageId:i.messageId,anchor:i.anchor,comment:``}),m()},title:r(`把这段收进这条会话:正文里留个编号,评论可以在输入框里那颗注释上补`,`Put this into this session: a number in the text; the note can be added inside the composer`),children:r(`添加到会话`,`Add to session`)}):null,t&&!i.inUser?(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{l(``),s(!0)},title:r(`标注这一段:写一句评论(可留空),正文里留个编号`,`Annotate this passage: one line of comment (optional), plus a number in the text`),children:r(`标注`,`Annotate`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`sel-toolbar-btn`,onMouseDown:h,onClick:()=>{n(i.text),m()},children:r(`在临时会话中提问`,`Ask in a temp session`)})]})}var Mg=`annot-mark`;function Ng(){let e=CSS.highlights;return typeof e!=`object`||!e?null:e}function Pg(){let e=globalThis.Highlight;return typeof e==`function`?e:null}function Fg({container:e,annotations:t,onFocus:n}){let r=Y(),i=(0,C.useRef)(null),[a,o]=(0,C.useState)([]);return(0,C.useLayoutEffect)(()=>{let n=e.current;if(n===null)return;let r=0,a=()=>{r=0;let e=i.current,a=n.getBoundingClientRect(),s=[],c=[],l=new Map;for(let e of n.querySelectorAll(`article.msg`))l.set(e.id,e);for(let r of t){if(Fu(r))continue;let i=l.get(`msg-${r.messageId}`)?.querySelector(`.msg-body`)??null;if(i===null)continue;let o=Cg(Eg(i),r.anchor);if(o===null)continue;let u=Dg(i,o.start,o.end);if(u===null||(c.push(u),e===null))continue;let d=u.getClientRects(),f=d.length>0?d[d.length-1]:u.getBoundingClientRect();(f.width!==0||f.height!==0)&&s.push({id:r.id,index:Qu(t,r.id),left:f.right-a.left+n.scrollLeft,top:f.bottom-a.top+n.scrollTop})}let u=Ng(),d=Pg();u!==null&&d!==null&&(c.length>0?u.set(Mg,new d(...c)):u.delete(Mg)),o(e=>e.length===s.length&&e.every((e,t)=>{let n=s[t];return n!==void 0&&e.id===n.id&&e.index===n.index&&Math.abs(e.left-n.left)<.5&&Math.abs(e.top-n.top)<.5})?e:s)},s=()=>{r===0&&(r=window.requestAnimationFrame(a))},c=new MutationObserver(e=>{let t=i.current;t!==null&&e.every(e=>t.contains(e.target))||s()});c.observe(n,{childList:!0,subtree:!0,characterData:!0});let l=new ResizeObserver(s);return l.observe(n),window.addEventListener(`resize`,s),s(),()=>{c.disconnect(),l.disconnect(),window.removeEventListener(`resize`,s),r!==0&&window.cancelAnimationFrame(r),Ng()?.delete(Mg)}},[e,t]),t.length===0?null:(0,Q.jsx)(`div`,{className:`annot-marks`,ref:i,children:a.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`annot-mark`,style:{left:e.left,top:e.top},title:r(`第 ${e.index} 条标注`,`Annotation ${e.index}`),"aria-label":r(`第 ${e.index} 条标注`,`Annotation ${e.index}`),onClick:()=>n?.(e.id),children:e.index},e.id))})}var Ig=2e3,Lg=200,Rg=120,zg=/^(bash|sh|shell|shell_command|exec|run|run_command|terminal|powershell)$/i,Bg=/^(read|view|cat|open|read_file|readfile)$/i,Vg=/^(list|ls|list_files|listfiles|glob|tree|dir)$/i,Hg=/^(grep|rg|search|find|search_files|find_files)$/i,Ug=/^(write|edit|str_replace|apply_patch|patch|multi_edit|multiedit|notebook_edit|create_file)$/i,Wg=/^(web_search|websearch|webfetch|web_fetch|fetch|browse|fetch_content)$/i,Gg=/^(agent|task|subagent|delegate)$/i,Kg=/^\s*(ls|dir|tree|find)\b/,qg=/^\s*(?:cd\s+\S+\s*&&\s*)*(curl|wget|http|httpie|aria2c)\b/;function Jg(e){return/(https?:\/\/[^\s'"|;&)]+)/.exec(e)?.[1]??null}var Yg=/(?:^|[\s&|;])(python3?|node|deno|bun|ruby|perl|php|bash|sh|zsh)\b/g,Xg=/(?:^|\s)(?:-e|--eval|-c|eval)\s+([\s\S]*)$/,Zg=/(?:^|[\s&|;])(?:pytest|py\.test|vitest|jest|mocha|ava|playwright\s+test|go\s+test|cargo\s+test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+(?:run\s+)?test)\b/,Qg=/(?:^|[\s&|;])(?:npm\s+run\s+build|pnpm\s+(?:run\s+)?build|yarn\s+(?:run\s+)?build|vite\s+build|tsc\b|make\b|cargo\s+build|go\s+build|webpack|rollup)\b/,$g=/(?:^|[\s&|;])(?:npm\s+(?:i|install|ci)|pnpm\s+(?:i|install|add)|yarn\s+(?:add|install)|pip3?\s+install|uv\s+(?:pip\s+)?install|brew\s+install|cargo\s+install)\b/,e_=/(?:^|[\s&|;])git\s+([a-z-]+)/,t_={commit:[`正在提交改动`,`已提交改动`],push:[`正在推送`,`已推送`],pull:[`正在拉取`,`已拉取`],fetch:[`正在同步远端`,`已同步远端`],status:[`正在看改动状态`,`已看改动状态`],diff:[`正在看差异`,`已看差异`],log:[`正在看提交历史`,`已看提交历史`],checkout:[`正在切分支`,`已切分支`],switch:[`正在切分支`,`已切分支`],merge:[`正在合并`,`已合并`],rebase:[`正在变基`,`已变基`],stash:[`正在暂存改动`,`已暂存改动`],add:[`正在暂存文件`,`已暂存文件`],clone:[`正在克隆仓库`,`已克隆仓库`]},n_={commit:[`Committing changes`,`Committed changes`],push:[`Pushing`,`Pushed`],pull:[`Pulling`,`Pulled`],fetch:[`Fetching from the remote`,`Fetched from the remote`],status:[`Checking the working tree`,`Checked the working tree`],diff:[`Reviewing the diff`,`Reviewed the diff`],log:[`Reading the commit history`,`Read the commit history`],checkout:[`Switching branches`,`Switched branches`],switch:[`Switching branches`,`Switched branches`],merge:[`Merging`,`Merged`],rebase:[`Rebasing`,`Rebased`],stash:[`Stashing changes`,`Stashed changes`],add:[`Staging files`,`Staged files`],clone:[`Cloning the repository`,`Cloned the repository`]};function r_(e){if(Zg.test(e))return{now:[`正在跑测试`,`Running the tests`],done:[`已跑完测试`,`Ran the tests`]};if(Qg.test(e))return{now:[`正在构建`,`Building`],done:[`已构建完成`,`Built`]};if($g.test(e))return{now:[`正在安装依赖`,`Installing dependencies`],done:[`已安装依赖`,`Installed dependencies`]};let t=e_.exec(e)?.[1],n=t?t_[t]:void 0;if(t&&n){let e=n_[t]??[`Running git ${t}`,`Ran git ${t}`];return{now:[n[0],e[0]],done:[n[1],e[1]]}}return null}var i_={python:`Python`,python3:`Python`,node:`Node`,deno:`Deno`,bun:`Bun`,ruby:`Ruby`,perl:`Perl`,bash:`shell`,sh:`shell`,zsh:`shell`};function a_(e){let t=e.indexOf(`<<`);if(t<0)return null;let n=/<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/.exec(e.slice(t))?.[1]??null,r=e.indexOf(`
35
35
  `,t);if(r<0)return null;let i=e.slice(r+1).split(`
36
36
  `);n&&(i.at(-1)??``).trim()===n&&i.pop();let a=i.join(`
37
37
  `).trim();return a===``?null:a}function o_(e){let t=Xg.exec(e)?.[1]?.trim();if(!t)return null;let n=t[0];if((n===`'`||n===`"`)&&t.length>1){let e=t.slice(1),r=e.lastIndexOf(n),i=(r>=0?e.slice(0,r):e).trim();return i===``?null:i}return t}function s_(e){for(let t of e.matchAll(Yg)){let n=i_[t[1].toLowerCase()]??t[1],r=e.slice((t.index??0)+t[0].length),i=a_(r)??o_(r);if(i)return{lang:n,code:i}}return null}var c_={path:null,command:null,pattern:null,query:null,description:null};function l_(e,t=120){let n=(e.split(/\r?\n/,1)[0]??``).replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function u_(e,t=Lg){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function d_(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim()!==``)return t;if(Array.isArray(t)){let e=t.find(e=>typeof e==`string`&&e.trim()!==``);if(typeof e==`string`)return e}}return null}function f_(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16))).replace(/\\n/g,`
38
- `).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}function p_(e,t){let n=RegExp(`"${t}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(e);if(n?.[1]!==void 0&&n[1]!==``)return f_(n[1]);let r=RegExp(`"${t}"\\s*:\\s*"([\\s\\S]*)`).exec(e);return r?.[1]?f_(r[1]):null}function m_(e){let t=e.trim();if(t===``)return c_;let n;try{n=JSON.parse(t)}catch{return{path:p_(t,`path`)??p_(t,`file_path`),command:p_(t,`command`),pattern:p_(t,`pattern`)??p_(t,`regex`),query:p_(t,`query`)??p_(t,`url`),description:p_(t,`description`)}}if(typeof n==`string`)return{...c_,command:n};if(!n||typeof n!=`object`)return c_;let r=n;return{path:d_(r,[`path`,`file_path`,`filePath`,`file`,`target_file`]),command:d_(r,[`command`,`cmd`,`script`]),pattern:d_(r,[`pattern`,`regex`,`query`]),query:d_(r,[`query`,`queries`,`q`,`url`,`prompt`]),description:d_(r,[`description`,`task`,`prompt`,`subagent_type`])}}function h_(e){return e.split(/[-_.\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function g_(e){return h_(Nm(e)??e)}function __(e){return/(?:^|\/)skills\/([^/]+)\/SKILL\.md$/i.exec(e)?.[1]??null}function v_(e,t){if(!Bg.test(e))return null;let n=m_(t).path,r=n?__(n):null;return r?g_(r):null}function y_(e,t,n){let r=n&&n.trim()!==``?n:t,i=m_(r),a=i.path,o=a?D(a):null,s=(()=>{let e=r.trim();return e===``?null:u_(e)})(),c=v_(e,t);if(c)return{kind:`skill`,now:q(`正在读取 ${c} 技能`,`Reading the ${c} skill`),done:q(`已读取 ${c} 技能`,`Read the ${c} skill`),detail:null,full:null};if(zg.test(e)&&i.command&&Kg.test(i.command)){let e=i.command.trim().split(/\s+/).filter(e=>!e.startsWith(`-`)),t=e[1]?D(e[1]):null;return{kind:`list`,now:t?q(`正在列出 ${t}`,`Listing ${t}`):q(`正在列出目录`,`Listing a directory`),done:t?q(`已列出 ${t}`,`Listed ${t}`):q(`已列出目录`,`Listed a directory`),detail:null,full:null}}if(Vg.test(e)){let e=o??s;return{kind:`list`,now:e?q(`正在列出 ${e}`,`Listing ${e}`):q(`正在列出目录`,`Listing a directory`),done:e?q(`已列出 ${e}`,`Listed ${e}`):q(`已列出目录`,`Listed a directory`),detail:null,full:null}}if(Wg.test(e)){let e=i.query??i.pattern;return{kind:`web`,now:q(`正在联网查询`,`Searching the web`),done:q(`已联网查询`,`Searched the web`),detail:e?l_(e,80):s,full:e??s}}if(Ug.test(e)){let e=o??a??null;return{kind:`edit`,now:e?q(`正在修改 ${e}`,`Editing ${e}`):q(`正在修改文件`,`Editing a file`),done:e?q(`已修改 ${e}`,`Edited ${e}`):q(`已修改文件`,`Edited a file`),detail:null,full:null}}if(Bg.test(e)){let e=o??s;return{kind:`read`,now:e?q(`正在读取 ${e}`,`Reading ${e}`):q(`正在读取文件`,`Reading a file`),done:e?q(`已读取 ${e}`,`Read ${e}`):q(`已读取文件`,`Read a file`),detail:null,full:null}}if(Hg.test(e)){let e=i.pattern??s;return{kind:`search`,now:q(`正在检索`,`Searching`),done:q(`已检索`,`Searched`),detail:e?l_(e,80):null,full:e}}if(Gg.test(e)){let e=i.description?l_(i.description,60):null;return{kind:`agent`,now:q(`正在派出子代理`,`Starting a subagent`),done:q(`已派出子代理`,`Started a subagent`),detail:e,full:i.description}}if(zg.test(e)){let e=i.command;if(e&&qg.test(e)){let t=Jg(e),n=t?t.replace(/^https?:\/\//,``).split(`/`)[0]:null;return{kind:`web`,now:n?q(`正在抓取 ${n}`,`Fetching ${n}`):q(`正在联网抓取`,`Fetching a remote URL`),done:n?q(`已抓取 ${n}`,`Fetched ${n}`):q(`已联网抓取`,`Fetched a remote URL`),detail:t?u_(t):null,full:e}}let t=e?s_(e):null;if(t)return{kind:`run`,now:q(`正在跑 ${t.lang} 脚本`,`Running a ${t.lang} script`),done:q(`已跑完 ${t.lang} 脚本`,`Ran a ${t.lang} script`),detail:u_(t.code,Rg),full:t.code};let n=e?r_(e):null;return n?{kind:`run`,now:q(n.now[0],n.now[1]),done:q(n.done[0],n.done[1]),detail:e?u_(e):s,full:e??s}:{kind:`run`,now:q(`正在跑命令`,`Running a command`),done:q(`已跑完命令`,`Ran a command`),detail:e?u_(e):s,full:e??s}}return{kind:`other`,now:q(`正在执行 ${e}`,`Running ${e}`),done:q(`已执行 ${e}`,`Ran ${e}`),detail:s,full:r.trim()===``?null:r}}var b_={fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`};function x_({kind:e,className:t}){let n={viewBox:`0 0 16 16`,"aria-hidden":!0,className:t};return e===`thinking`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M6.9 2.6l1 2.5 2.5 1-2.5 1-1 2.5-1-2.5-2.5-1 2.5-1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M11.9 9.5l.6 1.5 1.5.6-1.5.6-.6 1.5-.6-1.5-1.5-.6 1.5-.6Z`,...b_})]}):e===`skill`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M8 4.3C7.1 3.4 5.6 3 3.1 3v8.3c2.4 0 3.9.4 4.9 1.3 1-.9 2.5-1.3 4.9-1.3V3c-2.5 0-4 .4-4.9 1.3Z`,...b_}),(0,Q.jsx)(`path`,{d:`M8 4.3v8.3`,...b_})]}):e===`read`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M4.1 2h4.5l3.1 3.1V13a1 1 0 0 1-1 1H4.1a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M8.5 2.1v3.3h3.2`,...b_}),(0,Q.jsx)(`path`,{d:`M5.3 8.2h5.4`,...b_}),(0,Q.jsx)(`path`,{d:`M5.3 10.5h3.6`,...b_})]}):e===`list`?(0,Q.jsx)(`svg`,{...n,children:(0,Q.jsx)(`path`,{d:`M2.4 12.2a1.2 1.2 0 0 1-1.2-1.2V5a1.2 1.2 0 0 1 1.2-1.2h3.1a1.2 1.2 0 0 1 .95.48l.6.8a1.2 1.2 0 0 0 .95.48h5.4a1.2 1.2 0 0 1 1.2 1.2v4.2a1.2 1.2 0 0 1-1.2 1.2Z`,...b_})}):e===`run`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`rect`,{x:`1.9`,y:`2.9`,width:`12.2`,height:`10.2`,rx:`1.8`,...b_}),(0,Q.jsx)(`path`,{d:`M4.6 6.3 6.6 8l-2 1.7`,...b_}),(0,Q.jsx)(`path`,{d:`M8.6 10.4h3`,...b_})]}):e===`web`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`circle`,{cx:`7.6`,cy:`7.6`,r:`5.1`,...b_}),(0,Q.jsx)(`path`,{d:`M2.5 7.6h10.2`,...b_}),(0,Q.jsx)(`ellipse`,{cx:`7.6`,cy:`7.6`,rx:`2.3`,ry:`5.1`,...b_})]}):e===`search`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`3.9`,...b_}),(0,Q.jsx)(`path`,{d:`M9.9 9.9 13.2 13.2`,...b_})]}):e===`edit`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M10.9 2.6 13.4 5.1 5.8 12.7l-3.1.6.6-3.1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M9.5 4 12 6.5`,...b_})]}):e===`agent`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`rect`,{x:`3`,y:`4.9`,width:`10`,height:`7.4`,rx:`2`,...b_}),(0,Q.jsx)(`path`,{d:`M8 4.9V2.7`,...b_}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.4`,r:`0.75`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.4`,r:`0.75`,fill:`currentColor`,stroke:`none`})]}):(0,Q.jsx)(`svg`,{...n,children:(0,Q.jsx)(`path`,{d:`M10.4 2.3a3.1 3.1 0 0 0-3.6 4.1l-4.3 4.3a1.3 1.3 0 0 0 1.8 1.8l4.3-4.3a3.1 3.1 0 0 0 4.1-3.6l-1.9 1.9-1.9-.4-.4-1.9Z`,...b_})})}var S_={running:`运行中…`,ok:`完成`,failed:`失败`},C_={running:`running…`,ok:`done`,failed:`failed`},w_=/^(bash|sh|shell|shell_command|exec|run|run_command|terminal)$/i;function T_(e){let t=(e.argsFull??e.argsSummary).trim();if(t===``)return null;try{let e=JSON.parse(t);if(typeof e==`string`)return e;if(e&&typeof e==`object`){let t=e.command;return typeof t==`string`&&t.trim()!==``?t:JSON.stringify(e,null,2)}}catch{}return t}function E_({block:e}){let t=J(),n=T_(e);return n===null||(e.argsFull===void 0||e.argsFull===e.argsSummary)&&!w_.test(e.name)?null:(0,Q.jsxs)(`div`,{className:`tool-command`,children:[(0,Q.jsxs)(`div`,{className:`tool-command-head`,children:[(0,Q.jsx)(`span`,{className:`tool-command-label`,children:w_.test(e.name)?t(`命令`,`Command`):t(`参数`,`Arguments`)}),(0,Q.jsx)(ah,{text:n,className:`msg-action tool-command-copy`,title:t(`复制完整命令`,`Copy the full command`)})]}),(0,Q.jsx)(`pre`,{className:`tool-command-text`,children:n})]})}function D_(e){return/"path"\s*:\s*"([^"]+\.(?:png|jpe?g|gif|webp|avif|svg|bmp))"/i.exec(e)?.[1]??null}function O_(e){return`/api/files/raw?path=${encodeURIComponent(e)}`}function k_({block:e}){let t=J(),n=D_(e.argsSummary);return n?(0,Q.jsx)(`button`,{type:`button`,className:`tool-image-wrap`,title:t(`${n}(点击放大预览)`,`${n} (click to preview)`),onClick:()=>ns(O_(n),D(n)||t(`图片`,`image`)),children:(0,Q.jsx)(`img`,{className:`tool-image`,src:O_(n),alt:D(n)||t(`图片`,`image`),loading:`lazy`})}):null}function A_({block:e}){let t=J(),[n,r]=(0,C.useState)(null),[i]=uf(ur,!1),a=n??i,o=R(String(e.outputExcerpt.length),null,e.status===`running`),s=y_(e.name,e.argsSummary),c=e.status===`running`?s.now:s.done;return(0,Q.jsxs)(`div`,{className:`tool tool-${e.status}`,children:[(0,Q.jsxs)(`details`,{open:a,onToggle:e=>{let t=e.currentTarget.open;t!==a&&r(t)},children:[(0,Q.jsxs)(`summary`,{className:`tool-head`,title:e.name,children:[(0,Q.jsx)(x_,{kind:s.kind,className:`tool-icon`}),(0,Q.jsx)(`span`,{className:`tool-name`,children:c}),s.detail?(0,Q.jsx)(`span`,{className:`tool-args`,children:s.detail}):null,(0,Q.jsxs)(`span`,{className:`tool-status tool-status-${e.status}`,children:[e.status===`running`?(0,Q.jsx)(`span`,{className:`tool-spinner`,"aria-hidden":`true`}):null,t(S_[e.status],C_[e.status]),e.exitCode===void 0?``:` · exit ${e.exitCode}`]})]}),(0,Q.jsx)(E_,{block:e}),(0,Q.jsx)(`pre`,{className:`tool-output`,ref:o.ref,children:e.outputExcerpt||t(`(还没有输出)`,`(no output yet)`)}),e.truncated?(0,Q.jsxs)(`div`,{className:`tool-truncated`,children:[q(`输出已截断:界面上只保留前`,`Output truncated: only the first`),` `,Ig,` `,q(`字`,`characters are shown`)]}):null]}),(0,Q.jsx)(k_,{block:e})]})}var j_={queued:`排队中`,running:`运行中`,completed:`已完成`,failed:`失败`,aborted:`已停止`},M_={queued:`queued`,running:`running`,completed:`done`,failed:`failed`,aborted:`stopped`};function N_(e){return q(j_[e],M_[e])}var P_=[`queued`,`running`];function F_(e){return P_.includes(e.status)}function I_(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return q(`${n} 秒前`,`${n}s ago`);let r=Math.round(n/60);if(r<60)return q(`${r} 分钟前`,`${r}m ago`);let i=Math.round(r/60);return i<24?q(`${i} 小时前`,`${i}h ago`):q(`${Math.round(i/24)} 天前`,`${Math.round(i/24)}d ago`)}function L_(e,t){let n=e.endedAt??t,r=Math.max(0,Math.round((n-e.startedAt)/1e3));if(r<60)return`${r}s`;let i=Math.floor(r/60);return i<60?`${i}m${String(r%60).padStart(2,`0`)}s`:`${Math.floor(i/60)}h${String(i%60).padStart(2,`0`)}m`}function R_(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}k`:`${(e/1e6).toFixed(1)}M`}function z_(e){return e>0&&e<.001?`<$0.001`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(3)}`}function B_(e,t){let n=0,r=0,i=0,a=0;for(let o of e)F_(o)&&(a+=1),n+=Math.max(0,(o.endedAt??t)-o.startedAt),r+=o.tokens?.total??0,i+=o.cost??0;return{running:a,ms:n,tokens:r,cost:i}}function V_(e){let t={count:0,input:0,output:0,total:0,cost:0};for(let n of e)t.count+=1,t.input+=n.tokens?.input??0,t.output+=n.tokens?.output??0,t.total+=n.tokens?.total??0,t.cost+=n.cost??0;return t}function H_(e,t){let n=new Map;if(e.length===0)return n;let r=t.filter(e=>Number.isFinite(e.ts)),i=r.filter(e=>e.role===`assistant`),a=e=>{let t=-1;for(let n=r.length-1;n>=0;--n){let i=r[n];if(i&&i.role===`user`&&i.ts<=e){t=n;break}}if(t<0)return null;let n=null;for(let e=t+1;e<r.length;e+=1){let t=r[e];if(!t||t.role===`user`)break;t.role===`assistant`&&(n=t)}return n};for(let t of e){let e=a(t.startedAt);if(e===null)for(let n of i)n.ts>t.startedAt||(e===null||n.ts>=e.ts)&&(e=n);if(e===null)continue;let r=n.get(e.id);r?r.push(t):n.set(e.id,[t])}return n}function U_(e,t){return e>0?q(`${e} 个在跑`,`${e} running`):q(`${t} 个已结束`,`${t} finished`)}function W_(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`}function G_({status:e}){return K_(e)?(0,Q.jsxs)(`svg`,{className:`agents-spin`,viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,opacity:`0.28`}),(0,Q.jsx)(`path`,{d:`M14.2 8A6.2 6.2 0 0 0 8 1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})]}):(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:e===`completed`?(0,Q.jsx)(`path`,{d:`m3.6 8.4 3 3 5.4-6.4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`}):(0,Q.jsx)(`path`,{d:`M4.6 4.6l6.8 6.8M11.4 4.6l-6.8 6.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`})})}function K_(e){return P_.includes(e)}function q_(e){return k(e,3)}function J_({run:e,now:t,queueHint:n}){let[r,i]=(0,C.useState)(!1),a=J(),o=F_(e),s=e.status===`failed`?e.error??``:e.result??``,c=e.activeTool,l=()=>i(e=>!e);return(0,Q.jsxs)(`li`,{className:`agents-run agents-strip-card agents-run-${e.status}`,children:[(0,Q.jsxs)(`div`,{className:`agents-run-head`,children:[(0,Q.jsxs)(`span`,{className:`agents-run-status agents-status-${e.status}`,children:[(0,Q.jsx)(G_,{status:e.status}),N_(e.status)]}),(0,Q.jsx)(`button`,{type:`button`,className:`agents-run-title agents-run-open`,title:`${e.task}\n\n${a(`点一下看它现在在跑什么`,`Click to see what it is doing right now`)}`,"aria-expanded":r,onClick:l,children:e.description||e.label}),o?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>Tl(e.id),title:e.status===`queued`?a(`取消排队(不动已开跑的)`,`Drop it from the queue (running ones keep going)`):a(`停掉这个子代理(不动主会话)`,`Stop this subagent (the main conversation keeps going)`),children:e.status===`queued`?a(`取消`,`Cancel`):a(`停止`,`Stop`)}):null]}),e.status===`queued`?(0,Q.jsxs)(`div`,{className:`agents-run-queue`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⏳`}),(0,Q.jsx)(`span`,{children:n??a(`排队中:等前面跑完就会自动开`,`Queued: it starts as soon as an earlier one finishes`)})]}):null,(0,Q.jsxs)(`div`,{className:`agents-run-meta`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:I_(e.startedAt,t)}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:L_(e,t)}),e.toolCalls?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:a(`${e.toolCalls} 次工具`,`${e.toolCalls} tool calls`)})]}):null,e.tokens?.total?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsxs)(`span`,{children:[R_(e.tokens.total),` tokens`]})]}):null,e.cost?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:z_(e.cost)})]}):null]}),o&&c?(0,Q.jsxs)(`div`,{className:`agents-run-now`,title:c.argsSummary,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),(0,Q.jsx)(`span`,{className:`agents-run-now-name`,children:c.name}),(0,Q.jsx)(`span`,{className:`agents-run-now-args`,children:c.argsSummary})]}):null,s||o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`agents-run-toggle`,onClick:l,children:r?a(`收起`,`Hide`):o?a(`看它现在在干什么`,`See what it is doing`):a(`查看结果`,`View result`)}),r?(0,Q.jsxs)(Q.Fragment,{children:[s?(0,Q.jsx)(`pre`,{className:`agents-run-body`,children:s}):(0,Q.jsx)(`pre`,{className:`agents-run-body agents-run-body-empty`,children:a(`还没有输出(模型还在想 / 正在跑工具)`,`Nothing yet — the model is still thinking or running a tool`)}),o&&c?(0,Q.jsxs)(`div`,{className:`agents-run-tool`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),` `,a(`正在跑 ${c.name} · ${Em((t-c.startedAt)/1e3)}`,`running ${c.name} · ${Em((t-c.startedAt)/1e3)}`)]}):null,e.sessionPath?(0,Q.jsxs)(`div`,{className:`agents-run-path`,title:e.sessionPath,children:[a(`会话文件:`,`Session file: `),q_(e.sessionPath)]}):null]}):null]}):null]})}var Y_=`pop-agent:agents-strip-open`;function X_({runs:e}){let t=J(),n=Ro(e=>e.snapshot),[r,i]=(0,C.useState)(()=>Date.now()),[a,o]=(0,C.useState)(()=>localStorage.getItem(Y_)!==`0`),s=[...e].sort((e,t)=>t.startedAt-e.startedAt),c=B_(s,r),l=c.running,u=n?.subagentSettings?.concurrency??4,d=new Map;s.filter(e=>e.status===`queued`).sort((e,t)=>e.startedAt-t.startedAt).forEach((e,n)=>{d.set(e.id,t(`排队第 ${n+1} 位 · 等前面跑完自动开(最多同时 ${u} 个)`,`Queued #${n+1} · starts when an earlier one finishes (max ${u} at a time)`))});let f=l>0;(0,C.useEffect)(()=>{if(!a&&!f)return;let e=setInterval(()=>i(Date.now()),f?1e3:1e4);return()=>clearInterval(e)},[a,f]),(0,C.useEffect)(()=>{localStorage.setItem(Y_,a?`1`:`0`)},[a]);let p=e.find(F_)?.id??null;return(0,C.useEffect)(()=>{p&&o(!0)},[p]),(0,C.useEffect)(()=>{o(localStorage.getItem(Y_)!==`0`)},[n?.active.conversationId]),s.length===0?null:(0,Q.jsxs)(`section`,{className:`agents-strip${f?` agents-strip-live`:``}`,"aria-label":t(`当前会话的子代理`),children:[(0,Q.jsxs)(`header`,{className:`agents-strip-bar`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`agents-strip-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,title:a?t(`收起子代理卡片`,`Collapse the subagent cards`):t(`展开子代理卡片`,`Expand the subagent cards`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:1.4,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`5.6`,width:`9.6`,height:`7.4`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.6V3.3`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.7`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.7`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M6.2 11h3.6`})]}),(0,Q.jsx)(`span`,{className:`agents-strip-name`,children:t(`子代理`)}),(0,Q.jsx)(`span`,{className:`agents-strip-count`,children:U_(l,s.length)}),(0,Q.jsx)(`svg`,{className:`agents-strip-caret${a?` agents-strip-caret-open`:``}`,viewBox:`0 0 16 16`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4 6.4 4 4 4-4`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,Q.jsxs)(`span`,{className:`agents-strip-total`,title:t(`统计本轮全部子代理(含已完成的)`),children:[c.ms>0?(0,Q.jsxs)(Q.Fragment,{children:[`⏱ `,W_(c.ms)]}):null,c.tokens>0?(0,Q.jsxs)(Q.Fragment,{children:[c.ms>0?` · `:``,R_(c.tokens),` tokens`]}):null,c.cost>0?(0,Q.jsxs)(Q.Fragment,{children:[` · `,z_(c.cost)]}):null]})]}),a?(0,Q.jsx)(`ul`,{className:`agents-strip-cards`,children:s.map(e=>(0,Q.jsx)(J_,{run:e,now:r,queueHint:d.get(e.id)},e.id))}):null]})}var Z_=/!\[([^\]]*)\]\((\/api\/uploads\/[a-z0-9-]{8,64})\)/g;function Q_({text:e}){let t=J(),n=[],r=e.replace(Z_,(e,t,r)=>(n.push({src:r,alt:t}),``)).trim();return(0,Q.jsxs)(Q.Fragment,{children:[r===``?null:(0,Q.jsx)(`div`,{className:`msg-user-text`,children:(0,Q.jsx)($_,{text:r})}),n.length>0?(0,Q.jsx)(`div`,{className:`msg-user-images`,children:n.map((e,n)=>(0,Q.jsx)(`button`,{type:`button`,className:`msg-user-img-btn`,title:e.alt||t(`查看图片`,`View image`),onClick:()=>ns(e.src,e.alt),children:(0,Q.jsx)(`img`,{className:`msg-user-img`,src:e.src,alt:e.alt,loading:`lazy`})},`${e.src}-${n}`))}):null]})}function $_({text:e}){let t=Qh(e);return t.every(e=>e.url===void 0)?(0,Q.jsx)(Q.Fragment,{children:e}):(0,Q.jsx)(Q.Fragment,{children:t.map((e,t)=>e.url?(0,Q.jsx)(`a`,{className:`msg-user-link`,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:q(`在新标签页打开`,`Open in a new tab`),children:e.text},t):(0,Q.jsx)(C.Fragment,{children:e.text},t))})}function ev(e){return e.toLocaleString(`en-US`)}function tv(e,t,n){let r=new Date(e),i=e=>String(e).padStart(2,`0`),a=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return t?`${n===!0?`${r.toLocaleDateString(`en-US`,{month:`short`})} ${r.getDate()}`:`${r.getMonth()+1}月${r.getDate()}日`} ${a}`:a}function nv({ts:e,title:t}){let{language:n}=je(),r=n===`en`;return(0,Q.jsxs)(`span`,{className:`msg-foot-stamp`,title:t,children:[(0,Q.jsx)(`span`,{className:`msg-foot-stamp-full`,children:tv(e,!0,r)}),(0,Q.jsx)(`span`,{className:`msg-foot-stamp-short`,children:tv(e,!1,r)})]})}function rv({text:e}){return(0,Q.jsx)(`span`,{className:`thinking-preview`,title:e,children:e})}function iv({text:e}){let t=J(),[n,r]=(0,C.useState)(null),[i]=uf(cr,!1),a=n??i,o=e.trim();if(o===``)return null;let s=o.replace(/\s+/g,` `).trim().slice(0,240);return(0,Q.jsxs)(`div`,{className:`thinking-block`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`thinking-head`,onClick:()=>r(!a),children:[(0,Q.jsxs)(`span`,{className:`thinking-label`,children:[t(`思考`,`Thinking`),a?``:t(`(点击展开)`,` (click to expand)`)]}),a?null:(0,Q.jsx)(rv,{text:s}),(0,Q.jsx)(`span`,{className:`thinking-caret`,children:a?`▾`:`▸`})]}),a?(0,Q.jsx)(`div`,{className:`thinking-body`,children:o}):null]})}function av({message:e}){let t=J(),n=wm(e.blocks.map(e=>e.kind===`text`||e.kind===`thinking`?e.text:``).join(``));return n.tokens===0?null:(0,Q.jsxs)(`span`,{className:`msg-live`,children:[(0,Q.jsxs)(`span`,{className:`msg-live-tokens mono`,title:t(`这条回复已生成的 token(流式期间按字符估算;跑完后尾注给引擎报的真实用量)`,`Tokens generated so far (estimated from characters while streaming; the footnote shows the engine's real usage afterwards)`),children:[(0,Q.jsx)(`span`,{className:`msg-live-arrow`,"aria-hidden":`true`,children:`↓`}),ev(n.tokens)]}),n.rate>0?(0,Q.jsx)(`span`,{className:`msg-live-rate mono`,title:t(`最近 4 秒的生成速度(token/秒)`,`Generation speed over the last 4 seconds (tokens/s)`),children:Cm(n.rate)}):null]})}function ov(e,t,n=2500){let[r,i]=(0,C.useState)(e);return(0,C.useEffect)(()=>{if(!e){i(!1);return}i(!1);let t=window.setTimeout(()=>i(!0),n);return()=>window.clearTimeout(t)},[e,t,n]),r}function sv({message:e,tool:t,retrying:n}){let r=J(),i=e.blocks.at(-1),a=i?.kind===`text`?i.text.trim():``,o=ov(a!==``,a.length),s=cv(t!==null),c=n?r(`模型调用被打断,正在自动重试(${n.attempt}/${n.maxAttempts})`,`Model call interrupted, retrying automatically (${n.attempt}/${n.maxAttempts})`):null,l=t?y_(t.name,t.argsSummary,t.argsFull):null,u=t?Math.max(0,Math.floor((s-t.startedAt)/1e3)):0,[d,f]=(0,C.useState)(!1),p=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!d)return;let e=e=>{p.current?.contains(e.target)||f(!1)},t=e=>{e.key===`Escape`&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[d]);let[m,h]=(0,C.useState)(null);if((0,C.useEffect)(()=>{if(!d){h(null);return}let e=()=>{let e=p.current?.getBoundingClientRect();e&&h(Math.max(180,Math.floor(e.top-10)))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[d]),a!==``&&!t&&!o&&!n)return null;let g=l?.full??null,_=g!==null&&g.trim()!==``;return(0,Q.jsxs)(`div`,{className:`msg-activity-wrap`,ref:p,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`msg-activity`,"aria-expanded":_?d:void 0,"aria-label":_?r(`展开看完整命令`,`Show the full command`):void 0,..._?{}:{tabIndex:-1},onClick:()=>{_&&f(e=>!e)},children:[(0,Q.jsx)(x_,{kind:l?l.kind:`thinking`,className:`msg-activity-icon`}),(0,Q.jsx)(`span`,{className:`msg-activity-label`,"aria-live":`polite`,children:l?l.now:c??r(`正在思考`,`Thinking`)}),l?.detail?(0,Q.jsx)(`span`,{className:`msg-activity-args mono`,children:l.detail}):null,u>=2?(0,Q.jsx)(`span`,{className:`msg-activity-time mono`,title:r(`这个工具已经跑了多久`,`How long this tool has been running`),children:Em(u)}):null]}),d&&_?(0,Q.jsxs)(`div`,{className:`msg-activity-pop`,role:`dialog`,"aria-label":l?.now??``,style:m===null?void 0:{maxHeight:`${m}px`},children:[(0,Q.jsxs)(`div`,{className:`msg-activity-pop-head`,children:[(0,Q.jsx)(x_,{kind:l?.kind??`thinking`,className:`msg-activity-pop-icon`}),(0,Q.jsx)(`span`,{className:`msg-activity-pop-title`,children:l?.now}),t?(0,Q.jsxs)(`span`,{className:`msg-activity-pop-meta mono`,children:[u>=1?Em(u):``,(0,Q.jsx)(`span`,{className:`msg-activity-pop-tool`,children:t.name})]}):null]}),(0,Q.jsx)(`div`,{className:`msg-activity-pop-foot`,children:(0,Q.jsx)(ah,{text:g,className:`msg-action msg-activity-pop-copy`,title:r(`复制这条完整命令`,`Copy this full command`)})}),(0,Q.jsx)(`pre`,{className:`msg-activity-pop-body mono`,children:g})]}):null]})}function cv(e){let[t,n]=(0,C.useState)(()=>Date.now());return(0,C.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(t)},[e]),t}function lv({message:e,modelLabel:t,live:n,activeTool:r=null,retrying:i=null,workspaceRoot:a,onOpenFile:o,subagentRuns:s,onFork:c,speechOn:l=!0}){let u=J();Im();let d=yp(e),f=e.role===`assistant`?jd(e,a):[],{segments:p,thinkingCount:m,toolCount:h}=Wm(e.blocks),{firstProcessAt:g,lastAnswerAt:_,lastProcessAt:v,hasAnswer:y,insideFold:b}=Rm(p),x=g>=0,S=Array.from(new Set(e.blocks.map(e=>e.kind===`tool`?v_(e.name,e.argsSummary):null).filter(e=>e!==null))),w=s?V_(s):null,T=w&&(w.total>0||w.cost>0)?w:null,E=e.blocks.reduce((e,t)=>e+(t.kind===`tool`&&t.endedAt?t.endedAt-t.startedAt:0),0)+(e.thinkingMs??0),D=Lm({live:n,endedAt:e.endedAt}),O=D,k=cv(O),A=Number.isFinite(e.ts)?e.ts:null,j=A===null?null:(e.endedAt??k)-A,M=j!==null&&(O||e.endedAt!==void 0)?Math.max(0,j):Math.max(0,E),N=Math.floor(M/1e3)*1e3,P=O?M<6e4?`${N/1e3}s`:Tm(N):Tm(M),[F,I]=(0,C.useState)(null),[L]=uf(cr,!1),[R]=uf(ur,!1),[z]=uf(dr,!0),[B]=uf(fr,!0),V=Bm({running:D,autoCollapse:z,autoFoldRunning:B,defaultOpen:L||R,manual:F}),H=V===`all`,U=(0,C.useRef)(D);(0,C.useEffect)(()=>{Hm(U.current,D)&&I(null),U.current=D},[D]);let W=(0,Q.jsxs)(`button`,{type:`button`,className:`msg-tools-toggle`,"aria-expanded":H,onClick:()=>I(!H),title:u(`思考、工具调用、以及中间那几段说明,按发生顺序排列(跑的时候铺着看,跑完自动收起;点这一行展开 / 收起)`,`Thinking, tool calls and the narration in between, in the order they happened (they stay open while the turn runs and fold away when it ends; click this line to expand/collapse)`),children:[(0,Q.jsx)(`span`,{className:`msg-tools-caret${H?` msg-tools-caret-open`:``}`,"aria-hidden":`true`}),m>0?(0,Q.jsx)(`span`,{className:`msg-process-meta`,children:u(`${m} 段思考`,`${m} thinking`)}):null,h>0?(0,Q.jsx)(`span`,{className:`msg-process-meta`,children:u(`${h} 次工具`,`${h} tools`)}):null,S.length>0?(0,Q.jsxs)(`span`,{className:`msg-process-meta msg-process-skills`,children:[u(`技能`,`Skills`),` `,S.join(` · `)]}):null,M>0?(0,Q.jsxs)(`span`,{className:`msg-process-meta msg-process-time`,title:O?u(`这一轮从开始到现在的墙上时间(每秒刷新)`,`Wall-clock time since this turn started (ticks every second)`):u(`这一轮的总耗时`,`Total time this turn took`),children:[u(`耗时`,`took`),` `,P]}):null,(0,Q.jsx)(`span`,{className:`msg-process-chevron${H?` msg-process-chevron-open`:``}`,"aria-hidden":`true`})]}),ee=(t,r)=>{if(t.kind===`process`){if(V===`collapsed`)return r===g?(0,Q.jsx)(C.Fragment,{children:W},`fold-${r}`):null;let e=t.groups.map(e=>({key:e.key,thinking:e.thinking,tools:e.tools.filter(e=>!(D&&e.status===`running`))})).filter(e=>e.thinking!==null||e.tools.length>0),n=e.length===0?null:(0,Q.jsx)(`div`,{className:`process-segment`,children:e.map(e=>(0,Q.jsxs)(`div`,{className:`process-group`,children:[e.thinking?(0,Q.jsx)(iv,{text:e.thinking.text}):null,e.tools.map((t,n)=>(0,Q.jsx)(A_,{block:t},t.toolCallId||`${e.key}-${n}`))]},e.key))});return r===g?(0,Q.jsxs)(C.Fragment,{children:[W,n]},`fold-${r}`):n?(0,Q.jsx)(C.Fragment,{children:n},`process-${r}`):null}if(t.kind===`text`){if(Vm({view:V,running:D,hasProcess:x,hasAnswer:y,insideFold:b(r)}))return null;if(e.role===`user`)return t.text.trim()?(0,Q.jsx)(Q_,{text:t.text},t.index):null;let i=zm({index:r,lastAnswerAt:_,lastProcessAt:v,running:D});return t.text.trim()?(0,Q.jsx)(bg,{text:t.text,live:n,className:i?`md-narration`:void 0},t.index):null}let i=t.block.count??1;return(0,Q.jsxs)(`div`,{className:`block-error`,children:[(0,Q.jsx)(`span`,{className:`block-error-code`,children:t.block.code}),(0,Q.jsx)(`span`,{className:`block-error-text`,children:t.block.message}),i>1?(0,Q.jsx)(`span`,{className:`block-error-count`,title:u(`这条错误出现了 ${i} 次(重试都失败了)`,`This error occurred ${i} times (every retry failed)`),children:`×${i}`}):null]},t.index)},G=[...e.blocks].reverse().find(e=>e.kind===`tool`&&e.status===`running`),K=G&&G.kind===`tool`?G.argsFull:void 0,te=r?{...r,argsFull:r.argsFull??K}:null,ne=e.endedAt??null,[re,ie]=(0,C.useState)(()=>!Xm(window.localStorage).has(e.id)),ae=()=>{let t=Ym(Xm(window.localStorage),e.id);Zm(window.localStorage,t),ie(!t.has(e.id))};return e.steer&&re?(0,Q.jsx)(`article`,{className:`msg msg-user msg-steer msg-steer-collapsed`,id:`msg-${e.id}`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`steer-collapsed-row`,onClick:ae,title:u(`展开这条插队消息`,`Expand this steered message`),children:[(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-steer`,children:u(`已插队`,`Steered`)}),(0,Q.jsx)(`span`,{className:`steer-collapsed-text`,children:Qm(d)}),(0,Q.jsx)(`span`,{className:`steer-collapsed-open`,"aria-hidden":`true`,children:`▸`}),(0,Q.jsx)(nv,{ts:e.ts,title:u(`这条消息的时间`,`When this message was sent`)})]})}):(0,Q.jsxs)(`article`,{className:`msg msg-${e.role}${e.steer?` msg-steer`:``}`,id:`msg-${e.id}`,children:[e.role===`assistant`?(0,Q.jsxs)(`header`,{className:`msg-head`,children:[e.role===`assistant`&&t!==``?(0,Q.jsx)(`span`,{className:`msg-model`,title:u(`这条消息生成时用的模型`,`The model that generated this message`),children:t}):null,n?(0,Q.jsx)(av,{message:e}):null]}):null,(0,Q.jsxs)(`div`,{className:`msg-bubble`,children:[e.steer?(0,Q.jsxs)(`header`,{className:`msg-head msg-steer-head`,children:[(0,Q.jsx)(`span`,{className:`msg-role`,children:u(`我`,`Me`)}),(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-steer`,children:u(`已插队`,`Steered`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>So(d),title:u(`移回输入框,改完再发`,`Move back to the input and send again`),children:`↩`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action msg-steer-fold`,"aria-expanded":!re,onClick:ae,title:u(`收起这条插队消息(已交给这一轮,撤不回)`,`Collapse this steered message (already handed to this turn, cannot be recalled)`),"aria-label":u(`收起这条插队消息`,`Collapse this steered message`),children:`▾`})]}):null,(0,Q.jsxs)(`div`,{className:`msg-body`,children:[x?(0,Q.jsx)(`div`,{className:`msg-process`,children:p.map(ee)}):p.map(ee),s&&s.length>0?(0,Q.jsx)(X_,{runs:s}):null,n?(0,Q.jsx)(sv,{message:e,tool:te,retrying:i}):null]})]}),e.role===`assistant`?(0,Q.jsxs)(`footer`,{className:`msg-foot`,children:[e.usage?(0,Q.jsx)(`span`,{className:`msg-usage mono`,children:fv(e.usage,u).map(e=>(0,Q.jsxs)(`span`,{className:`msg-usage-item`,title:e.title,children:[e.tag?(0,Q.jsx)(`span`,{className:`msg-usage-tag`,children:e.tag}):null,e.text]},e.key))}):null,T?(0,Q.jsxs)(`span`,{className:`msg-usage msg-usage-sub mono`,title:u(`子代理 ${T.count} 个(独立计费,不含左边的 in/out/cache):输入 ${ev(T.input)}、输出 ${ev(T.output)} tokens,花费 ${dv(T.cost)}。这一轮合计 ${dv((e.usage?.cost??0)+T.cost)}`,`${T.count} subagent(s), billed separately (not in the in/out/cache at left): input ${ev(T.input)}, output ${ev(T.output)} tokens, ${dv(T.cost)}. Turn total ${dv((e.usage?.cost??0)+T.cost)}`),children:[(0,Q.jsxs)(`span`,{className:`msg-usage-tag`,children:[`🤖 `,T.count]}),(0,Q.jsxs)(`span`,{className:`msg-usage-item`,children:[T.input>0?`in ${vm(T.input)}`:``,T.input>0&&T.output>0?` `:``,T.output>0?`out ${vm(T.output)}`:``]}),T.cost>0?(0,Q.jsx)(`span`,{className:`msg-usage-item msg-usage-cost`,children:dv(T.cost)}):null]}):null,l&&!n&&d.trim()?(0,Q.jsx)(oh,{text:d}):null,n?null:(0,Q.jsx)(ah,{text:d,className:`msg-foot-copy`,title:u(`复制这条回复`,`Copy this reply`)}),n||!c?null:(0,Q.jsxs)(`button`,{type:`button`,className:`msg-foot-copy msg-foot-fork`,onClick:()=>c(e.id),title:u(`从这里创建分支(原对话保持不变)`,`Branch from here (original chat stays unchanged)`),"aria-label":u(`从这里创建分支`,`Branch from here`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M4.4 3.6v6.2a2.4 2.4 0 0 0 2.4 2.4h2.4`,strokeLinecap:`round`}),(0,Q.jsx)(`circle`,{cx:`4.4`,cy:`2.6`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`4.4`,cy:`13.4`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`12.2`,cy:`12.2`,r:`1.5`})]}),(0,Q.jsx)(`span`,{children:u(`分叉`,`Fork`)})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(nv,{ts:ne??e.ts,title:ne===null?u(`这条回复开始的时间`,`When this reply started`):u(`这条回复完成的时间`,`When this reply finished`)})]}):null,e.role===`user`?(0,Q.jsxs)(`footer`,{className:`msg-user-foot`,children:[e.steer?null:(0,Q.jsxs)(`button`,{type:`button`,className:`msg-action`,onClick:()=>So(d),title:u(`把这条消息放回输入框,改完再发`,`Put this message back in the input, edit and send again`),children:[`↳ `,u(`编辑`,`Edit`)]}),(0,Q.jsx)(ah,{text:d,title:u(`复制这条消息`,`Copy this message`)}),(0,Q.jsx)(nv,{ts:e.ts,title:u(`这条消息的时间`,`When this message was sent`)})]}):null,e.role===`assistant`?(0,Q.jsx)(rh,{files:f,onOpen:o?e=>o(e.path,a):void 0}):null]})}function uv(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n&&n.role===`assistant`&&n.endedAt===void 0)return n}return null}function dv(e){return`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function fv(e,t){let n=[{key:`in`,tag:`in`,text:vm(e.input),title:t(`输入 ${ev(e.input)} tokens(这一轮发给模型的)`,`Input ${ev(e.input)} tokens (sent to the model this turn)`)},{key:`out`,tag:`out`,text:vm(e.output),title:t(`输出 ${ev(e.output)} tokens(模型写回来的)`,`Output ${ev(e.output)} tokens (written back by the model)`)}];return e.cacheRead>0&&n.push({key:`cacheRead`,tag:`cache`,text:vm(e.cacheRead),title:t(`缓存读 ${ev(e.cacheRead)} tokens(命中提示词缓存,按折扣计价)`,`Cache read ${ev(e.cacheRead)} tokens (prompt cache hit, billed at a discount)`)}),e.cacheWrite>0&&n.push({key:`cacheWrite`,tag:`cacheW`,text:vm(e.cacheWrite),title:t(`缓存写 ${ev(e.cacheWrite)} tokens(把前缀写进缓存,下次能命中)`,`Cache write ${ev(e.cacheWrite)} tokens (prefix stored for the next hit)`)}),e.cost&&n.push({key:`cost`,text:dv(e.cost),title:t(`这一轮的花费(pi 按 provider 配置的价格估算)`,`Cost of this turn (estimated from the provider prices pi has)`)}),n}var pv=(0,C.memo)(lv),mv=[];function hv({messages:e,hasMoreBefore:t,modelLabels:n,workspaceRoot:r=null,onOpenFile:i,onOpenPath:a,running:o=!1,activeTool:s=null,retrying:c=null,pending:l=[],onRecallPending:u,onCancelPending:d,actions:f=[],subagentRuns:p=mv,onFork:m,onAddSelectionToSession:h,onAskSelectionInSideChat:g,annotations:_,onFocusAnnotation:v}){let y=J(),b=(0,C.useRef)(null),[x]=uf(pr,!0),S=e=>e?n?.[e]||e.split(`/`).slice(1).join(`/`)||e:``;Bo(e),eg(a??null);let w=(0,C.useMemo)(()=>$m(e),[e]),T=sh().enabled,E=(0,C.useMemo)(()=>H_(p,w),[p,w]);if(e.length===0)return null;let D=o?uv(w)?.id??null:null,O=new Set;for(let e of E.values())for(let t of e)O.add(t.id);let k=p.filter(e=>F_(e)&&!O.has(e.id));return(0,Q.jsxs)(`div`,{className:`messages`,ref:b,children:[t?(0,Q.jsx)(`div`,{className:`more-before`,children:y(`更早的消息未在本页(分页在 M6)`,`Earlier messages are not on this page`)}):null,k.length>0?(0,Q.jsx)(`div`,{className:`agents-strip-orphan`,children:(0,Q.jsx)(X_,{runs:k})}):null,w.map(e=>(0,Q.jsx)(pv,{speechOn:T,message:e,modelLabel:S(e.model),live:e.id===D,activeTool:e.id===D?s:null,retrying:e.id===D?c:null,workspaceRoot:r,onOpenFile:i,subagentRuns:E.get(e.id),onFork:m},e.id)),l.length>0?(0,Q.jsx)(`div`,{className:`pending-sends`,children:l.map(e=>(0,Q.jsxs)(`article`,{className:`msg msg-user pending-item pending-${e.mode}`,id:`msg-${e.id}`,children:[(0,Q.jsxs)(`header`,{className:`msg-head`,children:[(0,Q.jsx)(`span`,{className:`msg-role`,children:y(`我`,`Me`)}),(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-${e.mode}`,children:e.mode===`steer`?y(`插队`,`Steer`):y(`排队`,`Queue`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:y(`移回输入框`,`Move back to the input`),onClick:()=>u?.(e.id),children:`↩`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:e.mode===`steer`?y(`取消插队(还没插进去,取消了就不会插进去)`,`Cancel the steer (not inserted yet)`):y(`取消这条`,`Cancel this one`),onClick:()=>d?.(e.id),children:`×`})]}),(0,Q.jsx)(`div`,{className:`msg-body`,children:e.text})]},e.id))}):null,(0,Q.jsx)(eh,{actions:f,running:o}),g&&x?(0,Q.jsx)(jg,{container:b,onAddToSession:h,onAskInSideChat:g}):null,_&&_.length>0?(0,Q.jsx)(Fg,{container:b,annotations:_,onFocus:v}):null]})}function gv(e){let t=`${e}${`=`.repeat((4-e.length%4)%4)}`.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function _v(){let e=navigator.userAgent,t=window.matchMedia?.(`(display-mode: standalone)`).matches?` PWA`:``;return/iPhone/i.test(e)?`iPhone${t||` · Safari`}`:/iPad/i.test(e)?`iPad${t||` · Safari`}`:/Android/i.test(e)?`Android · ${/EdgA/.test(e)?`Edge`:/Firefox/.test(e)?`Firefox`:`Chrome`}`:/Macintosh/i.test(e)?`Mac${t} · ${/Firefox/.test(e)?`Firefox`:/Edg/.test(e)?`Edge`:`Chrome`}`:/Windows/i.test(e)?`Windows · ${/Edg/.test(e)?`Edge`:`Chrome`}`:q(`未知设备`,`Unknown device`)}function vv(e,t){if(!e)return!1;let n=new Uint8Array(e);if(n.length!==t.length)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==t[e])return!1;return!0}async function yv(){try{let e=await fetch(`/api/push/config`);return e.ok?await e.json():null}catch{return null}}async function bv(e){let t=await fetch(`/api/push/config`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({subject:e})}),n=await t.json();return t.ok?{ok:!0,config:n}:{ok:!1,code:n.error?.code??`push.unknown`}}async function xv(){let e=await fetch(`/api/push/keys/regenerate`,{method:`POST`}),t=await e.json();if(!e.ok)return{ok:!1,code:t.error?.code??`push.unknown`};let n=t;return{ok:!0,config:n,cleared:n.cleared??0}}function Sv(){return`serviceWorker`in navigator&&`PushManager`in window}async function Cv(){return await navigator.serviceWorker.getRegistration(`/sw.js`)||navigator.serviceWorker.register(`/sw.js`)}async function wv(){return Sv()?await(await Cv()).pushManager.getSubscription()?`subscribed`:Notification.permission:`unsupported`}async function Tv(e=``){if(!Sv())return{ok:!1,message:q(`这个浏览器不支持推送(需要 https 或 localhost)`,`This browser does not support push (https or localhost required)`)};if(await Notification.requestPermission()!==`granted`)return{ok:!1,message:q(`通知权限被拒绝`,`Notification permission was denied`)};let t=await Cv(),{publicKey:n}=await(await fetch(`/api/push/key`)).json(),r=gv(n),i=await t.pushManager.getSubscription(),a=!1;i&&!vv(i.options.applicationServerKey,r)&&(await i.unsubscribe(),a=!0);let o=((a?null:i)??await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:r})).toJSON(),s=await fetch(`/api/push/subscribe`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":sessionStorage.getItem(`pop-agent-client`)??``},body:JSON.stringify({endpoint:o.endpoint,keys:o.keys,name:_v(),brandName:e})});return s.ok?a?{ok:!0,rekeyed:a}:{ok:!0}:{ok:!1,message:q(`订阅保存失败:HTTP ${s.status}`,`Saving the subscription failed: HTTP ${s.status}`)}}async function Ev(e){if(Sv())try{let t=await(await navigator.serviceWorker.getRegistration(`/sw.js`))?.pushManager.getSubscription();if(!t)return;await fetch(`/api/push/brand`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({endpoint:t.endpoint,brandName:e})})}catch{}}async function Dv(){if(!Sv())return{ok:!1,message:q(`不支持推送`,`Push is not supported`)};let e=await(await Cv()).pushManager.getSubscription();return e&&(await fetch(`/api/push/unsubscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({endpoint:e.endpoint})}),await e.unsubscribe()),{ok:!0}}var Ov=`pop-agent.brand.name`,kv=`pop-agent.brand.show`,Av=`pop-agent.brand.logo`,jv=`pop-agent.brand.logo.show`,Mv=`pop-agent:brand-name`,Nv=[Ov,kv,Av,jv];function Pv(e){return e?e.replace(/\s+/g,` `).trim().slice(0,24).trim():``}function Fv(){return Pv(Yr(Ov))}function Iv(){return Fv()||`PopAgent`}var Lv=800,Rv=null;function zv(e){let t=Pv(e);t!==Fv()&&(Xr(Ov,t),Gv(),Bv())}function Bv(){Rv!==null&&clearTimeout(Rv),Rv=setTimeout(()=>{Rv=null,Ev(Fv())},Lv)}function Vv(){zv(``)}function Hv(){return Zr(kv,!0)}function Uv(e){Qr(kv,e),Gv()}function Wv(e){let t=t=>{let n=t.detail;(!n?.key||Nv.includes(n.key))&&e()},n=t=>{(t.key===null||Nv.includes(t.key))&&e()};return window.addEventListener(Mv,t),window.addEventListener(`pop-agent:pref`,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Mv,t),window.removeEventListener(`pop-agent:pref`,t),window.removeEventListener(`storage`,n)}}function Gv(){window.dispatchEvent(new CustomEvent(Mv,{detail:{key:Ov}}))}function Kv(){return Yr(`pop-agent.brand.logo`)??``}function qv(e){let t=(e??``).trim();t!==(Yr(`pop-agent.brand.logo`)??``)&&(Xr(Av,t),Gv())}function Jv(){return Zr(jv,!0)}function Yv(e){Qr(jv,e),Gv()}function Xv(e){let t=$r(kv,e),n=Wv(()=>e(Hv()));return()=>{t(),n()}}function Zv(){let[e,t]=(0,C.useState)(()=>Qv());return(0,C.useEffect)(()=>{let e=Wv(()=>t(Qv())),n=Xv(e=>t(t=>t.shown===e?t:{...t,shown:e}));return()=>{e(),n()}},[]),{name:e.name,custom:e.custom,shown:e.shown,logo:e.logo,logoShown:e.logoShown,setName:zv,setShown:Uv,setLogo:qv,setLogoShown:Yv,reset:Vv}}function Qv(){return{name:Iv(),custom:Fv(),shown:Hv(),logo:Kv(),logoShown:Jv()}}function $v({webVersion:e,latestVersion:t,outdated:n,onUpgrade:r}){let i=J(),{name:a,logo:o}=Zv();return(0,Q.jsx)(`div`,{className:`newchat-meta`,children:(0,Q.jsxs)(`div`,{className:`newchat-brand`,children:[(0,Q.jsx)(`img`,{className:`newchat-icon`,src:o||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`newchat-brand-text`,children:[(0,Q.jsx)(`span`,{className:`newchat-name`,children:a}),(0,Q.jsxs)(`span`,{className:`newchat-versions mono`,children:[(0,Q.jsx)(`a`,{className:`newchat-version-link`,href:T,target:`_blank`,rel:`noreferrer`,title:n&&t?i(`上游已发布 v${t}(本机 v${e})· 点这里去仓库看更新日志`,`Upstream released v${t} (you are on v${e}) · open the repo for the changelog`):i(`${T}(点这里看更新日志 / 提 issue)`,`${T} (changelog / issues)`),children:i(`开源项目`)}),` v${e}`,n?(0,Q.jsxs)(`button`,{type:`button`,className:`newchat-version-badge`,disabled:!r,onClick:r,title:r?i(`在终端里执行 ${E}(回车自动敲)`,`Runs ${E} in a terminal (auto-submitted)`):i(`上游已发布 v${t??``},本机 v${e}`,`Upstream released v${t??``}, you are on v${e}`),children:[i(`↑ 有新版`),r?` · ${i(`点此升级`)}`:``]}):null]})]})]})})}function ey({templates:e,conversationId:t}){let n=J(),{language:r}=je(),[i,a]=(0,C.useState)(null);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`newchat-tpls`,role:`list`,"aria-label":n(`提示词列表`,`Prompt list`),children:[dp(e).map(e=>{let t=fp(e,r);return(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`tpl-card newchat-tpl`,onClick:()=>a({template:e}),title:n(`点击编辑`,`Click to edit`),children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e.icon}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:t.name}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:t.description})]},e.id)}),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`tpl-card tpl-card-new newchat-tpl`,onClick:()=>a({template:null}),children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:`+`}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:n(`新建模板`,`New template`)}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:n(`把常用工作流存成模板`,`Save a repeated workflow as a template`)})]})]}),i?(0,Q.jsx)(vp,{template:i.template,library:e,conversationId:t??null,onClose:()=>a(null)}):null]})}function ty(e){let t=e=>e.blocks.filter(e=>e.kind===`text`).map(e=>e.kind===`text`?e.text:``).join(` `).replace(/\s+/g,` `).trim(),n=[];return e.forEach((r,i)=>{if(r.role!==`user`)return;let a=e.slice(i+1).find(e=>e.role===`assistant`);n.push({id:r.id,index:n.length+1,question:t(r).slice(0,120)||q(`(空消息)`,`(empty message)`),answer:a?t(a).slice(0,160):``})}),n}function ny({messages:e}){let t=J(),[n,r]=(0,C.useState)(null),i=(0,C.useRef)(null),a=()=>{i.current&&clearTimeout(i.current),i.current=null},o=()=>{a(),i.current=setTimeout(()=>r(null),160)},s=(0,C.useMemo)(()=>ty(e),[e,t]),[c,l]=(0,C.useState)(0),u=(0,C.useRef)(null),d=(0,C.useRef)(null),f=(0,C.useRef)(null);if((0,C.useLayoutEffect)(()=>{if(n===null)return;let e=u.current,t=f.current,r=d.current?.children[n];if(!e||!t||!r)return;let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=t.querySelector(`.outline-entry-on`),s=o?o.getBoundingClientRect().top-a.top:0,c=r.getBoundingClientRect().top-i.top,p=Math.max(0,e.clientHeight-t.offsetHeight-8);l(Math.max(0,Math.min(c-s,p)))},[n,s.length]),s.length===0)return null;let p=e=>{document.getElementById(`msg-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})},m=n===null?[]:s.slice(Math.max(0,n-2),Math.min(s.length,n+3));return(0,Q.jsxs)(`div`,{className:`outline`,"aria-label":t(`对话大纲`),ref:u,children:[(0,Q.jsx)(`div`,{className:`outline-rail`,ref:d,onMouseLeave:o,onMouseEnter:a,children:s.map((e,i)=>(0,Q.jsx)(`button`,{type:`button`,className:`outline-dot${n===i?` outline-dot-on`:``}`,onMouseEnter:()=>r(i),onFocus:()=>r(i),onClick:()=>p(e.id),title:t(`第 ${e.index} 问`,`Question ${e.index}`)},e.id))}),n===null?null:(0,Q.jsxs)(`div`,{className:`outline-preview`,ref:f,style:{marginTop:c},onMouseEnter:a,onMouseLeave:o,children:[m.map(e=>{let r=s[n]?.id===e.id;return(0,Q.jsxs)(`button`,{type:`button`,className:`outline-entry${r?` outline-entry-on`:``}`,onClick:()=>p(e.id),title:t(`点击定位到这条消息`),children:[(0,Q.jsxs)(`div`,{className:`outline-item`,children:[(0,Q.jsx)(`span`,{className:`outline-num mono`,children:String(e.index).padStart(2,`0`)}),(0,Q.jsx)(`span`,{className:`outline-q`,children:e.question})]}),e.answer?(0,Q.jsxs)(`div`,{className:`outline-item outline-item-answer`,children:[(0,Q.jsx)(`span`,{className:`outline-num mono`,children:`A`}),(0,Q.jsx)(`span`,{className:`outline-a`,children:e.answer})]}):null]},e.id)}),(0,Q.jsx)(`div`,{className:`outline-hint`,children:t(`点击任意一条定位过去`)})]})]})}function ry(e){let t=e.indexOf(`/`);return t<=0||t===e.length-1?null:e.slice(0,t)}function iy(e){let t=ry(e.id);if(t===null)return e.label||e.id;let n=e.id.slice(t.length+1);return e.label===e.id?n:e.label}function ay(e,t){let n=new Map;for(let r of e){let e=ry(r.id),i=e??t.name,a=e??t.label,o=n.get(i);o?o.models.push(r):n.set(i,{id:i,label:a,models:[r]})}return[...n.values()]}function oy(e){let t=new Set;for(let n of e){let e=ry(n);e!==null&&t.add(e)}return t}function sy(e,t={}){return e.credential===`apiKey`||e.credential===`oauth`?!0:t.engineReady?.has(e.provider)??!1}function cy({provider:e,onClose:t,onImported:n}){let r=J(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(new Set),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(!1);(0,C.useEffect)(()=>{(async()=>{try{let t=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/remote-models`),n=await t.json();if(!t.ok){d(n.error?.message??`HTTP ${t.status}`),a([]);return}a(n.models??[])}catch(e){d(e instanceof Error?e.message:String(e)),a([])}})()},[e.provider]);let m=(i??[]).filter(e=>c.trim()===``||e.id.toLowerCase().includes(c.trim().toLowerCase())),h=m.filter(e=>!e.imported),g=async()=>{if(o.size!==0){p(!0);try{let r=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/import`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:[...o]})}),i=await r.json();r.ok?(n(),t()):d(i.error?.message??`HTTP ${r.status}`)}finally{p(!1)}}};return(0,Q.jsxs)(`div`,{className:`side-panel import-models`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:r(`导入模型`)}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.provider}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,children:r(`关闭`,`Close`)})]}),i===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`正在读取远端模型清单…`)}):null,u?(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[r(`读取失败:`,`Failed to load: `),u]}):null,i===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`side-field input`,value:c,onChange:e=>l(e.target.value),placeholder:r(`筛选模型 id…`)}),(0,Q.jsxs)(`div`,{className:`import-list`,children:[m.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有可导入的模型`)}):null,m.map(e=>(0,Q.jsxs)(`label`,{className:`import-row${e.imported?` import-row-done`:``}`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,disabled:e.imported,checked:e.imported||o.has(e.id),onChange:()=>s(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})}),(0,Q.jsx)(`span`,{className:`import-id mono`,children:e.id}),e.imported?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:r(`已导入`)}):null]},e.id))]}),(0,Q.jsxs)(`div`,{className:`import-foot`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s(new Set(h.map(e=>e.id))),disabled:h.length===0,children:r(`全选可导入(${h.length})`,`Select all importable (${h.length})`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s(new Set),disabled:o.size===0,children:r(`清除选择`,`Clear selection`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void g(),disabled:f||o.size===0,children:r(`导入 ${o.size} 个`,`Import ${o.size}`)})]})]})]})}var ly=[`input`,`output`,`cacheRead`,`cacheWrite`],uy={input:`输入`,output:`输出`,cacheRead:`缓存读`,cacheWrite:`缓存写`},dy={input:`Input`,output:`Output`,cacheRead:`Cache read`,cacheWrite:`Cache write`};function fy(e,t){let n=e.models.find(e=>e.id===t),r=n?.cost??{},i=e=>typeof e==`number`?String(e):``;return{id:t,name:n?.name??t,reasoning:n?.reasoning===!0,imageInput:n?.imageInput===!0,contextWindow:i(n?.contextWindow),maxTokens:i(n?.maxTokens),input:i(r.input),output:i(r.output),cacheRead:i(r.cacheRead),cacheWrite:i(r.cacheWrite),schedule:(n?.costSchedule??[]).map(e=>({start:e.start,end:e.end??``,input:i(e.input),output:i(e.output),cacheRead:i(e.cacheRead),cacheWrite:i(e.cacheWrite)}))}}function py(e){let t=/^\d{1,2}:\d{2}(?::\d{2})?$/,n=new Set;for(let[r,i]of e.entries()){let e=i.start.trim(),a=i.end.trim();if(!t.test(e))return q(`第 ${r+1} 段还没填开始时间`,`Segment ${r+1} has no start time`);if(n.has(e))return q(`${e} 这个开始时间填了两次(同一时刻只能有一段价格)`,`${e} is used twice (only one price per moment)`);if(n.add(e),a!==``&&a===e)return q(`第 ${r+1} 段的开始和结束时间相同`,`Segment ${r+1} starts and ends at the same time`);for(let e of ly){let t=i[e].trim();if(t===``)continue;let n=Number(t);if(!Number.isFinite(n)||n<0)return q(`第 ${r+1} 段的${uy[e]}必须是非负数`,`Segment ${r+1}: ${dy[e]} must be a non-negative number`)}}return null}function my(e){let t=new Set(e.map(e=>e.start)),n=e.at(-1)?.start??`11:00`,r=Number(n.slice(0,2));for(let e=1;e<=24;e+=1){let n=`${String((r+e)%24).padStart(2,`0`)}:00`;if(!t.has(n))return n}return`12:00`}function hy({provider:e,modelId:t,onClose:n}){let r=J(),[i,a]=(0,C.useState)(()=>fy(e,t)),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)(!1),v=(e,t)=>a(n=>({...n,[e]:t})),y=(e,t,n)=>a(r=>({...r,schedule:r.schedule.map((r,i)=>i===e?{...r,[t]:n}:r)})),b=()=>a(e=>({...e,schedule:[...e.schedule,{start:my(e.schedule),end:``,input:``,output:``,cacheRead:``,cacheWrite:``}]})),x=e=>a(t=>({...t,schedule:t.schedule.filter((t,n)=>n!==e)})),S=async()=>{let t=Date.now();_(!0),d(null);try{let t=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/catalog?model=${encodeURIComponent(i.id)}`),n=await t.json();if(!t.ok||!n.spec){d(r(`models.dev 里没查到,请手动填写`,`Not found on models.dev — please fill it in by hand`));return}let o=n.spec;a(e=>({...e,name:o.name||e.name,reasoning:o.reasoning,imageInput:o.imageInput,contextWindow:o.contextWindow===null?``:String(o.contextWindow),maxTokens:o.maxTokens===null?``:String(o.maxTokens),input:o.cost?String(o.cost.input??``):``,output:o.cost?String(o.cost.output??``):``,cacheRead:o.cost?String(o.cost.cacheRead??``):``,cacheWrite:o.cost?String(o.cost.cacheWrite??``):``})),d(r(`已填入`,`Filled in`))}finally{setTimeout(()=>_(!1),Math.max(0,400-(Date.now()-t)))}},w=async()=>{p(!0),h(null);let t=await pu(e.provider,i.id);h({ok:t.ok,text:t.ok?r(`已连接 · ${t.latencyMs}ms · HTTP ${t.status}`,`Connected · ${t.latencyMs}ms · HTTP ${t.status}`):r(`未连接 · ${t.message}`,`Not connected · ${t.message}`)}),p(!1)};return(0,Q.jsxs)(`div`,{className:`side-panel model-editor`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:r(`模型`,`Model`)}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.provider}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:()=>{let t=py(i.schedule);if(l(t),t)return;let n=i.schedule.map(e=>({start:e.start,...e.end.trim()===``?{}:{end:e.end},...ly.reduce((t,n)=>(e[n].trim()!==``&&(t[n]=e[n]),t),{})}));hu(e.provider,{id:i.id,name:i.name,reasoning:i.reasoning,imageInput:i.imageInput,contextWindow:i.contextWindow,maxTokens:i.maxTokens,cost:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite},costSchedule:n}),s(!0)},title:r(`保存模型信息(含分时价格)`,`Save the model (including time-of-day prices)`),children:r(`保存`,`Save`)}),m?(0,Q.jsx)(`span`,{className:`prov-test-pill${m.ok?` prov-test-ok`:` prov-test-fail`}`,children:m.text}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void w(),disabled:f,title:r(`发送一次最小 chat 请求(max_tokens=1)`,`Send one minimal chat request (max_tokens=1)`),children:f?r(`测试中…`,`Testing…`):r(`测试`,`Test`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{let t=e.source===`builtin`?r(`
38
+ `).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}function p_(e,t){let n=RegExp(`"${t}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(e);if(n?.[1]!==void 0&&n[1]!==``)return f_(n[1]);let r=RegExp(`"${t}"\\s*:\\s*"([\\s\\S]*)`).exec(e);return r?.[1]?f_(r[1]):null}function m_(e){let t=e.trim();if(t===``)return c_;let n;try{n=JSON.parse(t)}catch{return{path:p_(t,`path`)??p_(t,`file_path`),command:p_(t,`command`),pattern:p_(t,`pattern`)??p_(t,`regex`),query:p_(t,`query`)??p_(t,`url`),description:p_(t,`description`)}}if(typeof n==`string`)return{...c_,command:n};if(!n||typeof n!=`object`)return c_;let r=n;return{path:d_(r,[`path`,`file_path`,`filePath`,`file`,`target_file`]),command:d_(r,[`command`,`cmd`,`script`]),pattern:d_(r,[`pattern`,`regex`,`query`]),query:d_(r,[`query`,`queries`,`q`,`url`,`prompt`]),description:d_(r,[`description`,`task`,`prompt`,`subagent_type`])}}function h_(e){return e.split(/[-_.\s]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function g_(e){return h_(Nm(e)??e)}function __(e){return/(?:^|\/)skills\/([^/]+)\/SKILL\.md$/i.exec(e)?.[1]??null}function v_(e,t){if(!Bg.test(e))return null;let n=m_(t).path,r=n?__(n):null;return r?g_(r):null}function y_(e,t,n){let r=n&&n.trim()!==``?n:t,i=m_(r),a=i.path,o=a?D(a):null,s=(()=>{let e=r.trim();return e===``?null:u_(e)})(),c=v_(e,t);if(c)return{kind:`skill`,now:J(`正在读取 ${c} 技能`,`Reading the ${c} skill`),done:J(`已读取 ${c} 技能`,`Read the ${c} skill`),detail:null,full:null};if(zg.test(e)&&i.command&&Kg.test(i.command)){let e=i.command.trim().split(/\s+/).filter(e=>!e.startsWith(`-`)),t=e[1]?D(e[1]):null;return{kind:`list`,now:t?J(`正在列出 ${t}`,`Listing ${t}`):J(`正在列出目录`,`Listing a directory`),done:t?J(`已列出 ${t}`,`Listed ${t}`):J(`已列出目录`,`Listed a directory`),detail:null,full:null}}if(Vg.test(e)){let e=o??s;return{kind:`list`,now:e?J(`正在列出 ${e}`,`Listing ${e}`):J(`正在列出目录`,`Listing a directory`),done:e?J(`已列出 ${e}`,`Listed ${e}`):J(`已列出目录`,`Listed a directory`),detail:null,full:null}}if(Wg.test(e)){let e=i.query??i.pattern;return{kind:`web`,now:J(`正在联网查询`,`Searching the web`),done:J(`已联网查询`,`Searched the web`),detail:e?l_(e,80):s,full:e??s}}if(Ug.test(e)){let e=o??a??null;return{kind:`edit`,now:e?J(`正在修改 ${e}`,`Editing ${e}`):J(`正在修改文件`,`Editing a file`),done:e?J(`已修改 ${e}`,`Edited ${e}`):J(`已修改文件`,`Edited a file`),detail:null,full:null}}if(Bg.test(e)){let e=o??s;return{kind:`read`,now:e?J(`正在读取 ${e}`,`Reading ${e}`):J(`正在读取文件`,`Reading a file`),done:e?J(`已读取 ${e}`,`Read ${e}`):J(`已读取文件`,`Read a file`),detail:null,full:null}}if(Hg.test(e)){let e=i.pattern??s;return{kind:`search`,now:J(`正在检索`,`Searching`),done:J(`已检索`,`Searched`),detail:e?l_(e,80):null,full:e}}if(Gg.test(e)){let e=i.description?l_(i.description,60):null;return{kind:`agent`,now:J(`正在派出子代理`,`Starting a subagent`),done:J(`已派出子代理`,`Started a subagent`),detail:e,full:i.description}}if(zg.test(e)){let e=i.command;if(e&&qg.test(e)){let t=Jg(e),n=t?t.replace(/^https?:\/\//,``).split(`/`)[0]:null;return{kind:`web`,now:n?J(`正在抓取 ${n}`,`Fetching ${n}`):J(`正在联网抓取`,`Fetching a remote URL`),done:n?J(`已抓取 ${n}`,`Fetched ${n}`):J(`已联网抓取`,`Fetched a remote URL`),detail:t?u_(t):null,full:e}}let t=e?s_(e):null;if(t)return{kind:`run`,now:J(`正在跑 ${t.lang} 脚本`,`Running a ${t.lang} script`),done:J(`已跑完 ${t.lang} 脚本`,`Ran a ${t.lang} script`),detail:u_(t.code,Rg),full:t.code};let n=e?r_(e):null;return n?{kind:`run`,now:J(n.now[0],n.now[1]),done:J(n.done[0],n.done[1]),detail:e?u_(e):s,full:e??s}:{kind:`run`,now:J(`正在跑命令`,`Running a command`),done:J(`已跑完命令`,`Ran a command`),detail:e?u_(e):s,full:e??s}}return{kind:`other`,now:J(`正在执行 ${e}`,`Running ${e}`),done:J(`已执行 ${e}`,`Ran ${e}`),detail:s,full:r.trim()===``?null:r}}var b_={fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`};function x_({kind:e,className:t}){let n={viewBox:`0 0 16 16`,"aria-hidden":!0,className:t};return e===`thinking`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M6.9 2.6l1 2.5 2.5 1-2.5 1-1 2.5-1-2.5-2.5-1 2.5-1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M11.9 9.5l.6 1.5 1.5.6-1.5.6-.6 1.5-.6-1.5-1.5-.6 1.5-.6Z`,...b_})]}):e===`skill`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M8 4.3C7.1 3.4 5.6 3 3.1 3v8.3c2.4 0 3.9.4 4.9 1.3 1-.9 2.5-1.3 4.9-1.3V3c-2.5 0-4 .4-4.9 1.3Z`,...b_}),(0,Q.jsx)(`path`,{d:`M8 4.3v8.3`,...b_})]}):e===`read`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M4.1 2h4.5l3.1 3.1V13a1 1 0 0 1-1 1H4.1a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M8.5 2.1v3.3h3.2`,...b_}),(0,Q.jsx)(`path`,{d:`M5.3 8.2h5.4`,...b_}),(0,Q.jsx)(`path`,{d:`M5.3 10.5h3.6`,...b_})]}):e===`list`?(0,Q.jsx)(`svg`,{...n,children:(0,Q.jsx)(`path`,{d:`M2.4 12.2a1.2 1.2 0 0 1-1.2-1.2V5a1.2 1.2 0 0 1 1.2-1.2h3.1a1.2 1.2 0 0 1 .95.48l.6.8a1.2 1.2 0 0 0 .95.48h5.4a1.2 1.2 0 0 1 1.2 1.2v4.2a1.2 1.2 0 0 1-1.2 1.2Z`,...b_})}):e===`run`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`rect`,{x:`1.9`,y:`2.9`,width:`12.2`,height:`10.2`,rx:`1.8`,...b_}),(0,Q.jsx)(`path`,{d:`M4.6 6.3 6.6 8l-2 1.7`,...b_}),(0,Q.jsx)(`path`,{d:`M8.6 10.4h3`,...b_})]}):e===`web`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`circle`,{cx:`7.6`,cy:`7.6`,r:`5.1`,...b_}),(0,Q.jsx)(`path`,{d:`M2.5 7.6h10.2`,...b_}),(0,Q.jsx)(`ellipse`,{cx:`7.6`,cy:`7.6`,rx:`2.3`,ry:`5.1`,...b_})]}):e===`search`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`3.9`,...b_}),(0,Q.jsx)(`path`,{d:`M9.9 9.9 13.2 13.2`,...b_})]}):e===`edit`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`path`,{d:`M10.9 2.6 13.4 5.1 5.8 12.7l-3.1.6.6-3.1Z`,...b_}),(0,Q.jsx)(`path`,{d:`M9.5 4 12 6.5`,...b_})]}):e===`agent`?(0,Q.jsxs)(`svg`,{...n,children:[(0,Q.jsx)(`rect`,{x:`3`,y:`4.9`,width:`10`,height:`7.4`,rx:`2`,...b_}),(0,Q.jsx)(`path`,{d:`M8 4.9V2.7`,...b_}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.4`,r:`0.75`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.4`,r:`0.75`,fill:`currentColor`,stroke:`none`})]}):(0,Q.jsx)(`svg`,{...n,children:(0,Q.jsx)(`path`,{d:`M10.4 2.3a3.1 3.1 0 0 0-3.6 4.1l-4.3 4.3a1.3 1.3 0 0 0 1.8 1.8l4.3-4.3a3.1 3.1 0 0 0 4.1-3.6l-1.9 1.9-1.9-.4-.4-1.9Z`,...b_})})}var S_={running:`运行中…`,ok:`完成`,failed:`失败`},C_={running:`running…`,ok:`done`,failed:`failed`},w_=/^(bash|sh|shell|shell_command|exec|run|run_command|terminal)$/i;function T_(e){let t=(e.argsFull??e.argsSummary).trim();if(t===``)return null;try{let e=JSON.parse(t);if(typeof e==`string`)return e;if(e&&typeof e==`object`){let t=e.command;return typeof t==`string`&&t.trim()!==``?t:JSON.stringify(e,null,2)}}catch{}return t}function E_({block:e}){let t=Y(),n=T_(e);return n===null||(e.argsFull===void 0||e.argsFull===e.argsSummary)&&!w_.test(e.name)?null:(0,Q.jsxs)(`div`,{className:`tool-command`,children:[(0,Q.jsxs)(`div`,{className:`tool-command-head`,children:[(0,Q.jsx)(`span`,{className:`tool-command-label`,children:w_.test(e.name)?t(`命令`,`Command`):t(`参数`,`Arguments`)}),(0,Q.jsx)(ah,{text:n,className:`msg-action tool-command-copy`,title:t(`复制完整命令`,`Copy the full command`)})]}),(0,Q.jsx)(`pre`,{className:`tool-command-text`,children:n})]})}function D_(e){return/"path"\s*:\s*"([^"]+\.(?:png|jpe?g|gif|webp|avif|svg|bmp))"/i.exec(e)?.[1]??null}function O_(e){return`/api/files/raw?path=${encodeURIComponent(e)}`}function k_({block:e}){let t=Y(),n=D_(e.argsSummary);return n?(0,Q.jsx)(`button`,{type:`button`,className:`tool-image-wrap`,title:t(`${n}(点击放大预览)`,`${n} (click to preview)`),onClick:()=>ns(O_(n),D(n)||t(`图片`,`image`)),children:(0,Q.jsx)(`img`,{className:`tool-image`,src:O_(n),alt:D(n)||t(`图片`,`image`),loading:`lazy`})}):null}function A_({block:e}){let t=Y(),[n,r]=(0,C.useState)(null),[i]=uf(ur,!1),a=n??i,o=R(String(e.outputExcerpt.length),null,e.status===`running`),s=y_(e.name,e.argsSummary),c=e.status===`running`?s.now:s.done;return(0,Q.jsxs)(`div`,{className:`tool tool-${e.status}`,children:[(0,Q.jsxs)(`details`,{open:a,onToggle:e=>{let t=e.currentTarget.open;t!==a&&r(t)},children:[(0,Q.jsxs)(`summary`,{className:`tool-head`,title:e.name,children:[(0,Q.jsx)(x_,{kind:s.kind,className:`tool-icon`}),(0,Q.jsx)(`span`,{className:`tool-name`,children:c}),s.detail?(0,Q.jsx)(`span`,{className:`tool-args`,children:s.detail}):null,(0,Q.jsxs)(`span`,{className:`tool-status tool-status-${e.status}`,children:[e.status===`running`?(0,Q.jsx)(`span`,{className:`tool-spinner`,"aria-hidden":`true`}):null,t(S_[e.status],C_[e.status]),e.exitCode===void 0?``:` · exit ${e.exitCode}`]})]}),(0,Q.jsx)(E_,{block:e}),(0,Q.jsx)(`pre`,{className:`tool-output`,ref:o.ref,children:e.outputExcerpt||t(`(还没有输出)`,`(no output yet)`)}),e.truncated?(0,Q.jsxs)(`div`,{className:`tool-truncated`,children:[J(`输出已截断:界面上只保留前`,`Output truncated: only the first`),` `,Ig,` `,J(`字`,`characters are shown`)]}):null]}),(0,Q.jsx)(k_,{block:e})]})}var j_={queued:`排队中`,running:`运行中`,completed:`已完成`,failed:`失败`,aborted:`已停止`},M_={queued:`queued`,running:`running`,completed:`done`,failed:`failed`,aborted:`stopped`};function N_(e){return J(j_[e],M_[e])}var P_=[`queued`,`running`];function F_(e){return P_.includes(e.status)}function I_(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return J(`${n} 秒前`,`${n}s ago`);let r=Math.round(n/60);if(r<60)return J(`${r} 分钟前`,`${r}m ago`);let i=Math.round(r/60);return i<24?J(`${i} 小时前`,`${i}h ago`):J(`${Math.round(i/24)} 天前`,`${Math.round(i/24)}d ago`)}function L_(e,t){let n=e.endedAt??t,r=Math.max(0,Math.round((n-e.startedAt)/1e3));if(r<60)return`${r}s`;let i=Math.floor(r/60);return i<60?`${i}m${String(r%60).padStart(2,`0`)}s`:`${Math.floor(i/60)}h${String(i%60).padStart(2,`0`)}m`}function R_(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}k`:`${(e/1e6).toFixed(1)}M`}function z_(e){return e>0&&e<.001?`<$0.001`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(3)}`}function B_(e,t){let n=0,r=0,i=0,a=0;for(let o of e)F_(o)&&(a+=1),n+=Math.max(0,(o.endedAt??t)-o.startedAt),r+=o.tokens?.total??0,i+=o.cost??0;return{running:a,ms:n,tokens:r,cost:i}}function V_(e){let t={count:0,input:0,output:0,total:0,cost:0};for(let n of e)t.count+=1,t.input+=n.tokens?.input??0,t.output+=n.tokens?.output??0,t.total+=n.tokens?.total??0,t.cost+=n.cost??0;return t}function H_(e,t){let n=new Map;if(e.length===0)return n;let r=t.filter(e=>Number.isFinite(e.ts)),i=r.filter(e=>e.role===`assistant`),a=e=>{let t=-1;for(let n=r.length-1;n>=0;--n){let i=r[n];if(i&&i.role===`user`&&i.ts<=e){t=n;break}}if(t<0)return null;let n=null;for(let e=t+1;e<r.length;e+=1){let t=r[e];if(!t||t.role===`user`)break;t.role===`assistant`&&(n=t)}return n};for(let t of e){let e=a(t.startedAt);if(e===null)for(let n of i)n.ts>t.startedAt||(e===null||n.ts>=e.ts)&&(e=n);if(e===null)continue;let r=n.get(e.id);r?r.push(t):n.set(e.id,[t])}return n}function U_(e,t){return e>0?J(`${e} 个在跑`,`${e} running`):J(`${t} 个已结束`,`${t} finished`)}function W_(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h${String(n%60).padStart(2,`0`)}m`}function G_({status:e}){return K_(e)?(0,Q.jsxs)(`svg`,{className:`agents-spin`,viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`6.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,opacity:`0.28`}),(0,Q.jsx)(`path`,{d:`M14.2 8A6.2 6.2 0 0 0 8 1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})]}):(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:e===`completed`?(0,Q.jsx)(`path`,{d:`m3.6 8.4 3 3 5.4-6.4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`}):(0,Q.jsx)(`path`,{d:`M4.6 4.6l6.8 6.8M11.4 4.6l-6.8 6.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`})})}function K_(e){return P_.includes(e)}function q_(e){return k(e,3)}function J_({run:e,now:t,queueHint:n}){let[r,i]=(0,C.useState)(!1),a=Y(),o=F_(e),s=e.status===`failed`?e.error??``:e.result??``,c=e.activeTool,l=()=>i(e=>!e);return(0,Q.jsxs)(`li`,{className:`agents-run agents-strip-card agents-run-${e.status}`,children:[(0,Q.jsxs)(`div`,{className:`agents-run-head`,children:[(0,Q.jsxs)(`span`,{className:`agents-run-status agents-status-${e.status}`,children:[(0,Q.jsx)(G_,{status:e.status}),N_(e.status)]}),(0,Q.jsx)(`button`,{type:`button`,className:`agents-run-title agents-run-open`,title:`${e.task}\n\n${a(`点一下看它现在在跑什么`,`Click to see what it is doing right now`)}`,"aria-expanded":r,onClick:l,children:e.description||e.label}),o?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>Tl(e.id),title:e.status===`queued`?a(`取消排队(不动已开跑的)`,`Drop it from the queue (running ones keep going)`):a(`停掉这个子代理(不动主会话)`,`Stop this subagent (the main conversation keeps going)`),children:e.status===`queued`?a(`取消`,`Cancel`):a(`停止`,`Stop`)}):null]}),e.status===`queued`?(0,Q.jsxs)(`div`,{className:`agents-run-queue`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⏳`}),(0,Q.jsx)(`span`,{children:n??a(`排队中:等前面跑完就会自动开`,`Queued: it starts as soon as an earlier one finishes`)})]}):null,(0,Q.jsxs)(`div`,{className:`agents-run-meta`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:I_(e.startedAt,t)}),(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:L_(e,t)}),e.toolCalls?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:a(`${e.toolCalls} 次工具`,`${e.toolCalls} tool calls`)})]}):null,e.tokens?.total?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsxs)(`span`,{children:[R_(e.tokens.total),` tokens`]})]}):null,e.cost?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{children:`·`}),(0,Q.jsx)(`span`,{children:z_(e.cost)})]}):null]}),o&&c?(0,Q.jsxs)(`div`,{className:`agents-run-now`,title:c.argsSummary,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),(0,Q.jsx)(`span`,{className:`agents-run-now-name`,children:c.name}),(0,Q.jsx)(`span`,{className:`agents-run-now-args`,children:c.argsSummary})]}):null,s||o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`agents-run-toggle`,onClick:l,children:r?a(`收起`,`Hide`):o?a(`看它现在在干什么`,`See what it is doing`):a(`查看结果`,`View result`)}),r?(0,Q.jsxs)(Q.Fragment,{children:[s?(0,Q.jsx)(`pre`,{className:`agents-run-body`,children:s}):(0,Q.jsx)(`pre`,{className:`agents-run-body agents-run-body-empty`,children:a(`还没有输出(模型还在想 / 正在跑工具)`,`Nothing yet — the model is still thinking or running a tool`)}),o&&c?(0,Q.jsxs)(`div`,{className:`agents-run-tool`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),` `,a(`正在跑 ${c.name} · ${Em((t-c.startedAt)/1e3)}`,`running ${c.name} · ${Em((t-c.startedAt)/1e3)}`)]}):null,e.sessionPath?(0,Q.jsxs)(`div`,{className:`agents-run-path`,title:e.sessionPath,children:[a(`会话文件:`,`Session file: `),q_(e.sessionPath)]}):null]}):null]}):null]})}var Y_=`pop-agent:agents-strip-open`;function X_({runs:e}){let t=Y(),n=Ro(e=>e.snapshot),[r,i]=(0,C.useState)(()=>Date.now()),[a,o]=(0,C.useState)(()=>localStorage.getItem(Y_)!==`0`),s=[...e].sort((e,t)=>t.startedAt-e.startedAt),c=B_(s,r),l=c.running,u=n?.subagentSettings?.concurrency??4,d=new Map;s.filter(e=>e.status===`queued`).sort((e,t)=>e.startedAt-t.startedAt).forEach((e,n)=>{d.set(e.id,t(`排队第 ${n+1} 位 · 等前面跑完自动开(最多同时 ${u} 个)`,`Queued #${n+1} · starts when an earlier one finishes (max ${u} at a time)`))});let f=l>0;(0,C.useEffect)(()=>{if(!a&&!f)return;let e=setInterval(()=>i(Date.now()),f?1e3:1e4);return()=>clearInterval(e)},[a,f]),(0,C.useEffect)(()=>{localStorage.setItem(Y_,a?`1`:`0`)},[a]);let p=e.find(F_)?.id??null;return(0,C.useEffect)(()=>{p&&o(!0)},[p]),(0,C.useEffect)(()=>{o(localStorage.getItem(Y_)!==`0`)},[n?.active.conversationId]),s.length===0?null:(0,Q.jsxs)(`section`,{className:`agents-strip${f?` agents-strip-live`:``}`,"aria-label":t(`当前会话的子代理`),children:[(0,Q.jsxs)(`header`,{className:`agents-strip-bar`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`agents-strip-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,title:a?t(`收起子代理卡片`,`Collapse the subagent cards`):t(`展开子代理卡片`,`Expand the subagent cards`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:1.4,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`5.6`,width:`9.6`,height:`7.4`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.6V3.3`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.7`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.7`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M6.2 11h3.6`})]}),(0,Q.jsx)(`span`,{className:`agents-strip-name`,children:t(`子代理`)}),(0,Q.jsx)(`span`,{className:`agents-strip-count`,children:U_(l,s.length)}),(0,Q.jsx)(`svg`,{className:`agents-strip-caret${a?` agents-strip-caret-open`:``}`,viewBox:`0 0 16 16`,width:`12`,height:`12`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4 6.4 4 4 4-4`,strokeLinecap:`round`,strokeLinejoin:`round`})})]}),(0,Q.jsxs)(`span`,{className:`agents-strip-total`,title:t(`统计本轮全部子代理(含已完成的)`),children:[c.ms>0?(0,Q.jsxs)(Q.Fragment,{children:[`⏱ `,W_(c.ms)]}):null,c.tokens>0?(0,Q.jsxs)(Q.Fragment,{children:[c.ms>0?` · `:``,R_(c.tokens),` tokens`]}):null,c.cost>0?(0,Q.jsxs)(Q.Fragment,{children:[` · `,z_(c.cost)]}):null]})]}),a?(0,Q.jsx)(`ul`,{className:`agents-strip-cards`,children:s.map(e=>(0,Q.jsx)(J_,{run:e,now:r,queueHint:d.get(e.id)},e.id))}):null]})}var Z_=/!\[([^\]]*)\]\((\/api\/uploads\/[a-z0-9-]{8,64})\)/g;function Q_({text:e}){let t=Y(),n=[],r=e.replace(Z_,(e,t,r)=>(n.push({src:r,alt:t}),``)).trim();return(0,Q.jsxs)(Q.Fragment,{children:[r===``?null:(0,Q.jsx)(`div`,{className:`msg-user-text`,children:(0,Q.jsx)($_,{text:r})}),n.length>0?(0,Q.jsx)(`div`,{className:`msg-user-images`,children:n.map((e,n)=>(0,Q.jsx)(`button`,{type:`button`,className:`msg-user-img-btn`,title:e.alt||t(`查看图片`,`View image`),onClick:()=>ns(e.src,e.alt),children:(0,Q.jsx)(`img`,{className:`msg-user-img`,src:e.src,alt:e.alt,loading:`lazy`})},`${e.src}-${n}`))}):null]})}function $_({text:e}){let t=Qh(e);return t.every(e=>e.url===void 0)?(0,Q.jsx)(Q.Fragment,{children:e}):(0,Q.jsx)(Q.Fragment,{children:t.map((e,t)=>e.url?(0,Q.jsx)(`a`,{className:`msg-user-link`,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:J(`在新标签页打开`,`Open in a new tab`),children:e.text},t):(0,Q.jsx)(C.Fragment,{children:e.text},t))})}function ev(e){return e.toLocaleString(`en-US`)}function tv(e,t,n){let r=new Date(e),i=e=>String(e).padStart(2,`0`),a=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return t?`${n===!0?`${r.toLocaleDateString(`en-US`,{month:`short`})} ${r.getDate()}`:`${r.getMonth()+1}月${r.getDate()}日`} ${a}`:a}function nv({ts:e,title:t}){let{language:n}=Ae(),r=n===`en`;return(0,Q.jsxs)(`span`,{className:`msg-foot-stamp`,title:t,children:[(0,Q.jsx)(`span`,{className:`msg-foot-stamp-full`,children:tv(e,!0,r)}),(0,Q.jsx)(`span`,{className:`msg-foot-stamp-short`,children:tv(e,!1,r)})]})}function rv({text:e}){return(0,Q.jsx)(`span`,{className:`thinking-preview`,title:e,children:e})}function iv({text:e}){let t=Y(),[n,r]=(0,C.useState)(null),[i]=uf(cr,!1),a=n??i,o=e.trim();if(o===``)return null;let s=o.replace(/\s+/g,` `).trim().slice(0,240);return(0,Q.jsxs)(`div`,{className:`thinking-block`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`thinking-head`,onClick:()=>r(!a),children:[(0,Q.jsxs)(`span`,{className:`thinking-label`,children:[t(`思考`,`Thinking`),a?``:t(`(点击展开)`,` (click to expand)`)]}),a?null:(0,Q.jsx)(rv,{text:s}),(0,Q.jsx)(`span`,{className:`thinking-caret`,children:a?`▾`:`▸`})]}),a?(0,Q.jsx)(`div`,{className:`thinking-body`,children:o}):null]})}function av({message:e}){let t=Y(),n=wm(e.blocks.map(e=>e.kind===`text`||e.kind===`thinking`?e.text:``).join(``));return n.tokens===0?null:(0,Q.jsxs)(`span`,{className:`msg-live`,children:[(0,Q.jsxs)(`span`,{className:`msg-live-tokens mono`,title:t(`这条回复已生成的 token(流式期间按字符估算;跑完后尾注给引擎报的真实用量)`,`Tokens generated so far (estimated from characters while streaming; the footnote shows the engine's real usage afterwards)`),children:[(0,Q.jsx)(`span`,{className:`msg-live-arrow`,"aria-hidden":`true`,children:`↓`}),ev(n.tokens)]}),n.rate>0?(0,Q.jsx)(`span`,{className:`msg-live-rate mono`,title:t(`最近 4 秒的生成速度(token/秒)`,`Generation speed over the last 4 seconds (tokens/s)`),children:Cm(n.rate)}):null]})}function ov(e,t,n=2500){let[r,i]=(0,C.useState)(e);return(0,C.useEffect)(()=>{if(!e){i(!1);return}i(!1);let t=window.setTimeout(()=>i(!0),n);return()=>window.clearTimeout(t)},[e,t,n]),r}function sv({message:e,tool:t,retrying:n}){let r=Y(),i=e.blocks.at(-1),a=i?.kind===`text`?i.text.trim():``,o=ov(a!==``,a.length),s=cv(t!==null),c=n?r(`模型调用被打断,正在自动重试(${n.attempt}/${n.maxAttempts})`,`Model call interrupted, retrying automatically (${n.attempt}/${n.maxAttempts})`):null,l=t?y_(t.name,t.argsSummary,t.argsFull):null,u=t?Math.max(0,Math.floor((s-t.startedAt)/1e3)):0,[d,f]=(0,C.useState)(!1),p=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!d)return;let e=e=>{p.current?.contains(e.target)||f(!1)},t=e=>{e.key===`Escape`&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[d]);let[m,h]=(0,C.useState)(null);if((0,C.useEffect)(()=>{if(!d){h(null);return}let e=()=>{let e=p.current?.getBoundingClientRect();e&&h(Math.max(180,Math.floor(e.top-10)))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[d]),a!==``&&!t&&!o&&!n)return null;let g=l?.full??null,_=g!==null&&g.trim()!==``;return(0,Q.jsxs)(`div`,{className:`msg-activity-wrap`,ref:p,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`msg-activity`,"aria-expanded":_?d:void 0,"aria-label":_?r(`展开看完整命令`,`Show the full command`):void 0,..._?{}:{tabIndex:-1},onClick:()=>{_&&f(e=>!e)},children:[(0,Q.jsx)(x_,{kind:l?l.kind:`thinking`,className:`msg-activity-icon`}),(0,Q.jsx)(`span`,{className:`msg-activity-label`,"aria-live":`polite`,children:l?l.now:c??r(`正在思考`,`Thinking`)}),l?.detail?(0,Q.jsx)(`span`,{className:`msg-activity-args mono`,children:l.detail}):null,u>=2?(0,Q.jsx)(`span`,{className:`msg-activity-time mono`,title:r(`这个工具已经跑了多久`,`How long this tool has been running`),children:Em(u)}):null]}),d&&_?(0,Q.jsxs)(`div`,{className:`msg-activity-pop`,role:`dialog`,"aria-label":l?.now??``,style:m===null?void 0:{maxHeight:`${m}px`},children:[(0,Q.jsxs)(`div`,{className:`msg-activity-pop-head`,children:[(0,Q.jsx)(x_,{kind:l?.kind??`thinking`,className:`msg-activity-pop-icon`}),(0,Q.jsx)(`span`,{className:`msg-activity-pop-title`,children:l?.now}),t?(0,Q.jsxs)(`span`,{className:`msg-activity-pop-meta mono`,children:[u>=1?Em(u):``,(0,Q.jsx)(`span`,{className:`msg-activity-pop-tool`,children:t.name})]}):null]}),(0,Q.jsx)(`div`,{className:`msg-activity-pop-foot`,children:(0,Q.jsx)(ah,{text:g,className:`msg-action msg-activity-pop-copy`,title:r(`复制这条完整命令`,`Copy this full command`)})}),(0,Q.jsx)(`pre`,{className:`msg-activity-pop-body mono`,children:g})]}):null]})}function cv(e){let[t,n]=(0,C.useState)(()=>Date.now());return(0,C.useEffect)(()=>{if(!e)return;n(Date.now());let t=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(t)},[e]),t}function lv({message:e,modelLabel:t,live:n,activeTool:r=null,retrying:i=null,workspaceRoot:a,onOpenFile:o,subagentRuns:s,onFork:c,speechOn:l=!0}){let u=Y();Im();let d=yp(e),f=e.role===`assistant`?jd(e,a):[],{segments:p,thinkingCount:m,toolCount:h}=Wm(e.blocks),{firstProcessAt:g,lastAnswerAt:_,lastProcessAt:v,hasAnswer:y,insideFold:b}=Rm(p),x=g>=0,S=Array.from(new Set(e.blocks.map(e=>e.kind===`tool`?v_(e.name,e.argsSummary):null).filter(e=>e!==null))),w=s?V_(s):null,T=w&&(w.total>0||w.cost>0)?w:null,E=e.blocks.reduce((e,t)=>e+(t.kind===`tool`&&t.endedAt?t.endedAt-t.startedAt:0),0)+(e.thinkingMs??0),D=Lm({live:n,endedAt:e.endedAt}),O=D,k=cv(O),A=Number.isFinite(e.ts)?e.ts:null,j=A===null?null:(e.endedAt??k)-A,M=j!==null&&(O||e.endedAt!==void 0)?Math.max(0,j):Math.max(0,E),N=Math.floor(M/1e3)*1e3,P=O?M<6e4?`${N/1e3}s`:Tm(N):Tm(M),[F,I]=(0,C.useState)(null),[L]=uf(cr,!1),[R]=uf(ur,!1),[z]=uf(dr,!0),[B]=uf(fr,!0),V=Bm({running:D,autoCollapse:z,autoFoldRunning:B,defaultOpen:L||R,manual:F}),H=V===`all`,U=(0,C.useRef)(D);(0,C.useEffect)(()=>{Hm(U.current,D)&&I(null),U.current=D},[D]);let W=(0,Q.jsxs)(`button`,{type:`button`,className:`msg-tools-toggle`,"aria-expanded":H,onClick:()=>I(!H),title:u(`思考、工具调用、以及中间那几段说明,按发生顺序排列(跑的时候铺着看,跑完自动收起;点这一行展开 / 收起)`,`Thinking, tool calls and the narration in between, in the order they happened (they stay open while the turn runs and fold away when it ends; click this line to expand/collapse)`),children:[(0,Q.jsx)(`span`,{className:`msg-tools-caret${H?` msg-tools-caret-open`:``}`,"aria-hidden":`true`}),m>0?(0,Q.jsx)(`span`,{className:`msg-process-meta`,children:u(`${m} 段思考`,`${m} thinking`)}):null,h>0?(0,Q.jsx)(`span`,{className:`msg-process-meta`,children:u(`${h} 次工具`,`${h} tools`)}):null,S.length>0?(0,Q.jsxs)(`span`,{className:`msg-process-meta msg-process-skills`,children:[u(`技能`,`Skills`),` `,S.join(` · `)]}):null,M>0?(0,Q.jsxs)(`span`,{className:`msg-process-meta msg-process-time`,title:O?u(`这一轮从开始到现在的墙上时间(每秒刷新)`,`Wall-clock time since this turn started (ticks every second)`):u(`这一轮的总耗时`,`Total time this turn took`),children:[u(`耗时`,`took`),` `,P]}):null,(0,Q.jsx)(`span`,{className:`msg-process-chevron${H?` msg-process-chevron-open`:``}`,"aria-hidden":`true`})]}),ee=(t,r)=>{if(t.kind===`process`){if(V===`collapsed`)return r===g?(0,Q.jsx)(C.Fragment,{children:W},`fold-${r}`):null;let e=t.groups.map(e=>({key:e.key,thinking:e.thinking,tools:e.tools.filter(e=>!(D&&e.status===`running`))})).filter(e=>e.thinking!==null||e.tools.length>0),n=e.length===0?null:(0,Q.jsx)(`div`,{className:`process-segment`,children:e.map(e=>(0,Q.jsxs)(`div`,{className:`process-group`,children:[e.thinking?(0,Q.jsx)(iv,{text:e.thinking.text}):null,e.tools.map((t,n)=>(0,Q.jsx)(A_,{block:t},t.toolCallId||`${e.key}-${n}`))]},e.key))});return r===g?(0,Q.jsxs)(C.Fragment,{children:[W,n]},`fold-${r}`):n?(0,Q.jsx)(C.Fragment,{children:n},`process-${r}`):null}if(t.kind===`text`){if(Vm({view:V,running:D,hasProcess:x,hasAnswer:y,insideFold:b(r)}))return null;if(e.role===`user`)return t.text.trim()?(0,Q.jsx)(Q_,{text:t.text},t.index):null;let i=zm({index:r,lastAnswerAt:_,lastProcessAt:v,running:D});return t.text.trim()?(0,Q.jsx)(bg,{text:t.text,live:n,className:i?`md-narration`:void 0},t.index):null}let i=t.block.count??1;return(0,Q.jsxs)(`div`,{className:`block-error`,children:[(0,Q.jsx)(`span`,{className:`block-error-code`,children:t.block.code}),(0,Q.jsx)(`span`,{className:`block-error-text`,children:t.block.message}),i>1?(0,Q.jsx)(`span`,{className:`block-error-count`,title:u(`这条错误出现了 ${i} 次(重试都失败了)`,`This error occurred ${i} times (every retry failed)`),children:`×${i}`}):null]},t.index)},G=[...e.blocks].reverse().find(e=>e.kind===`tool`&&e.status===`running`),K=G&&G.kind===`tool`?G.argsFull:void 0,te=r?{...r,argsFull:r.argsFull??K}:null,ne=e.endedAt??null,[re,ie]=(0,C.useState)(()=>!Xm(window.localStorage).has(e.id)),ae=()=>{let t=Ym(Xm(window.localStorage),e.id);Zm(window.localStorage,t),ie(!t.has(e.id))};return e.steer&&re?(0,Q.jsx)(`article`,{className:`msg msg-user msg-steer msg-steer-collapsed`,id:`msg-${e.id}`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`steer-collapsed-row`,onClick:ae,title:u(`展开这条插队消息`,`Expand this steered message`),children:[(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-steer`,children:u(`已插队`,`Steered`)}),(0,Q.jsx)(`span`,{className:`steer-collapsed-text`,children:Qm(d)}),(0,Q.jsx)(`span`,{className:`steer-collapsed-open`,"aria-hidden":`true`,children:`▸`}),(0,Q.jsx)(nv,{ts:e.ts,title:u(`这条消息的时间`,`When this message was sent`)})]})}):(0,Q.jsxs)(`article`,{className:`msg msg-${e.role}${e.steer?` msg-steer`:``}`,id:`msg-${e.id}`,children:[e.role===`assistant`?(0,Q.jsxs)(`header`,{className:`msg-head`,children:[e.role===`assistant`&&t!==``?(0,Q.jsx)(`span`,{className:`msg-model`,title:u(`这条消息生成时用的模型`,`The model that generated this message`),children:t}):null,n?(0,Q.jsx)(av,{message:e}):null]}):null,(0,Q.jsxs)(`div`,{className:`msg-bubble`,children:[e.steer?(0,Q.jsxs)(`header`,{className:`msg-head msg-steer-head`,children:[(0,Q.jsx)(`span`,{className:`msg-role`,children:u(`我`,`Me`)}),(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-steer`,children:u(`已插队`,`Steered`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>So(d),title:u(`移回输入框,改完再发`,`Move back to the input and send again`),children:`↩`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action msg-steer-fold`,"aria-expanded":!re,onClick:ae,title:u(`收起这条插队消息(已交给这一轮,撤不回)`,`Collapse this steered message (already handed to this turn, cannot be recalled)`),"aria-label":u(`收起这条插队消息`,`Collapse this steered message`),children:`▾`})]}):null,(0,Q.jsxs)(`div`,{className:`msg-body`,children:[x?(0,Q.jsx)(`div`,{className:`msg-process`,children:p.map(ee)}):p.map(ee),s&&s.length>0?(0,Q.jsx)(X_,{runs:s}):null,n?(0,Q.jsx)(sv,{message:e,tool:te,retrying:i}):null]})]}),e.role===`assistant`?(0,Q.jsxs)(`footer`,{className:`msg-foot`,children:[e.usage?(0,Q.jsx)(`span`,{className:`msg-usage mono`,children:fv(e.usage,u).map(e=>(0,Q.jsxs)(`span`,{className:`msg-usage-item`,title:e.title,children:[e.tag?(0,Q.jsx)(`span`,{className:`msg-usage-tag`,children:e.tag}):null,e.text]},e.key))}):null,T?(0,Q.jsxs)(`span`,{className:`msg-usage msg-usage-sub mono`,title:u(`子代理 ${T.count} 个(独立计费,不含左边的 in/out/cache):输入 ${ev(T.input)}、输出 ${ev(T.output)} tokens,花费 ${dv(T.cost)}。这一轮合计 ${dv((e.usage?.cost??0)+T.cost)}`,`${T.count} subagent(s), billed separately (not in the in/out/cache at left): input ${ev(T.input)}, output ${ev(T.output)} tokens, ${dv(T.cost)}. Turn total ${dv((e.usage?.cost??0)+T.cost)}`),children:[(0,Q.jsxs)(`span`,{className:`msg-usage-tag`,children:[`🤖 `,T.count]}),(0,Q.jsxs)(`span`,{className:`msg-usage-item`,children:[T.input>0?`in ${vm(T.input)}`:``,T.input>0&&T.output>0?` `:``,T.output>0?`out ${vm(T.output)}`:``]}),T.cost>0?(0,Q.jsx)(`span`,{className:`msg-usage-item msg-usage-cost`,children:dv(T.cost)}):null]}):null,l&&!n&&d.trim()?(0,Q.jsx)(oh,{text:d}):null,n?null:(0,Q.jsx)(ah,{text:d,className:`msg-foot-copy`,title:u(`复制这条回复`,`Copy this reply`)}),n||!c?null:(0,Q.jsxs)(`button`,{type:`button`,className:`msg-foot-copy msg-foot-fork`,onClick:()=>c(e.id),title:u(`从这里创建分支(原对话保持不变)`,`Branch from here (original chat stays unchanged)`),"aria-label":u(`从这里创建分支`,`Branch from here`),children:[(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M4.4 3.6v6.2a2.4 2.4 0 0 0 2.4 2.4h2.4`,strokeLinecap:`round`}),(0,Q.jsx)(`circle`,{cx:`4.4`,cy:`2.6`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`4.4`,cy:`13.4`,r:`1.5`}),(0,Q.jsx)(`circle`,{cx:`12.2`,cy:`12.2`,r:`1.5`})]}),(0,Q.jsx)(`span`,{children:u(`分叉`,`Fork`)})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(nv,{ts:ne??e.ts,title:ne===null?u(`这条回复开始的时间`,`When this reply started`):u(`这条回复完成的时间`,`When this reply finished`)})]}):null,e.role===`user`?(0,Q.jsxs)(`footer`,{className:`msg-user-foot`,children:[e.steer?null:(0,Q.jsxs)(`button`,{type:`button`,className:`msg-action`,onClick:()=>So(d),title:u(`把这条消息放回输入框,改完再发`,`Put this message back in the input, edit and send again`),children:[`↳ `,u(`编辑`,`Edit`)]}),(0,Q.jsx)(ah,{text:d,title:u(`复制这条消息`,`Copy this message`)}),(0,Q.jsx)(nv,{ts:e.ts,title:u(`这条消息的时间`,`When this message was sent`)})]}):null,e.role===`assistant`?(0,Q.jsx)(rh,{files:f,onOpen:o?e=>o(e.path,a):void 0}):null]})}function uv(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n&&n.role===`assistant`&&n.endedAt===void 0)return n}return null}function dv(e){return`$${e<.01?e.toFixed(4):e.toFixed(2)}`}function fv(e,t){let n=[{key:`in`,tag:`in`,text:vm(e.input),title:t(`输入 ${ev(e.input)} tokens(这一轮发给模型的)`,`Input ${ev(e.input)} tokens (sent to the model this turn)`)},{key:`out`,tag:`out`,text:vm(e.output),title:t(`输出 ${ev(e.output)} tokens(模型写回来的)`,`Output ${ev(e.output)} tokens (written back by the model)`)}];return e.cacheRead>0&&n.push({key:`cacheRead`,tag:`cache`,text:vm(e.cacheRead),title:t(`缓存读 ${ev(e.cacheRead)} tokens(命中提示词缓存,按折扣计价)`,`Cache read ${ev(e.cacheRead)} tokens (prompt cache hit, billed at a discount)`)}),e.cacheWrite>0&&n.push({key:`cacheWrite`,tag:`cacheW`,text:vm(e.cacheWrite),title:t(`缓存写 ${ev(e.cacheWrite)} tokens(把前缀写进缓存,下次能命中)`,`Cache write ${ev(e.cacheWrite)} tokens (prefix stored for the next hit)`)}),e.cost&&n.push({key:`cost`,text:dv(e.cost),title:t(`这一轮的花费(pi 按 provider 配置的价格估算)`,`Cost of this turn (estimated from the provider prices pi has)`)}),n}var pv=(0,C.memo)(lv),mv=[];function hv({messages:e,hasMoreBefore:t,modelLabels:n,workspaceRoot:r=null,onOpenFile:i,onOpenPath:a,running:o=!1,activeTool:s=null,retrying:c=null,pending:l=[],onRecallPending:u,onCancelPending:d,actions:f=[],subagentRuns:p=mv,onFork:m,onAddSelectionToSession:h,onAskSelectionInSideChat:g,annotations:_,onFocusAnnotation:v}){let y=Y(),b=(0,C.useRef)(null),[x]=uf(pr,!0),S=e=>e?n?.[e]||e.split(`/`).slice(1).join(`/`)||e:``;Bo(e),eg(a??null);let w=(0,C.useMemo)(()=>$m(e),[e]),T=sh().enabled,E=(0,C.useMemo)(()=>H_(p,w),[p,w]);if(e.length===0)return null;let D=o?uv(w)?.id??null:null,O=new Set;for(let e of E.values())for(let t of e)O.add(t.id);let k=p.filter(e=>F_(e)&&!O.has(e.id));return(0,Q.jsxs)(`div`,{className:`messages`,ref:b,children:[t?(0,Q.jsx)(`div`,{className:`more-before`,children:y(`更早的消息未在本页(分页在 M6)`,`Earlier messages are not on this page`)}):null,k.length>0?(0,Q.jsx)(`div`,{className:`agents-strip-orphan`,children:(0,Q.jsx)(X_,{runs:k})}):null,w.map(e=>(0,Q.jsx)(pv,{speechOn:T,message:e,modelLabel:S(e.model),live:e.id===D,activeTool:e.id===D?s:null,retrying:e.id===D?c:null,workspaceRoot:r,onOpenFile:i,subagentRuns:E.get(e.id),onFork:m},e.id)),l.length>0?(0,Q.jsx)(`div`,{className:`pending-sends`,children:l.map(e=>(0,Q.jsxs)(`article`,{className:`msg msg-user pending-item pending-${e.mode}`,id:`msg-${e.id}`,children:[(0,Q.jsxs)(`header`,{className:`msg-head`,children:[(0,Q.jsx)(`span`,{className:`msg-role`,children:y(`我`,`Me`)}),(0,Q.jsx)(`span`,{className:`sent-tag sent-tag-${e.mode}`,children:e.mode===`steer`?y(`插队`,`Steer`):y(`排队`,`Queue`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:y(`移回输入框`,`Move back to the input`),onClick:()=>u?.(e.id),children:`↩`}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:e.mode===`steer`?y(`取消插队(还没插进去,取消了就不会插进去)`,`Cancel the steer (not inserted yet)`):y(`取消这条`,`Cancel this one`),onClick:()=>d?.(e.id),children:`×`})]}),(0,Q.jsx)(`div`,{className:`msg-body`,children:e.text})]},e.id))}):null,(0,Q.jsx)(eh,{actions:f,running:o}),g&&x?(0,Q.jsx)(jg,{container:b,onAddToSession:h,onAskInSideChat:g}):null,_&&_.length>0?(0,Q.jsx)(Fg,{container:b,annotations:_,onFocus:v}):null]})}function gv(e){let t=`${e}${`=`.repeat((4-e.length%4)%4)}`.replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function _v(){let e=navigator.userAgent,t=window.matchMedia?.(`(display-mode: standalone)`).matches?` PWA`:``;return/iPhone/i.test(e)?`iPhone${t||` · Safari`}`:/iPad/i.test(e)?`iPad${t||` · Safari`}`:/Android/i.test(e)?`Android · ${/EdgA/.test(e)?`Edge`:/Firefox/.test(e)?`Firefox`:`Chrome`}`:/Macintosh/i.test(e)?`Mac${t} · ${/Firefox/.test(e)?`Firefox`:/Edg/.test(e)?`Edge`:`Chrome`}`:/Windows/i.test(e)?`Windows · ${/Edg/.test(e)?`Edge`:`Chrome`}`:J(`未知设备`,`Unknown device`)}function vv(e,t){if(!e)return!1;let n=new Uint8Array(e);if(n.length!==t.length)return!1;for(let e=0;e<n.length;e+=1)if(n[e]!==t[e])return!1;return!0}async function yv(){try{let e=await fetch(`/api/push/config`);return e.ok?await e.json():null}catch{return null}}async function bv(e){let t=await fetch(`/api/push/config`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({subject:e})}),n=await t.json();return t.ok?{ok:!0,config:n}:{ok:!1,code:n.error?.code??`push.unknown`}}async function xv(){let e=await fetch(`/api/push/keys/regenerate`,{method:`POST`}),t=await e.json();if(!e.ok)return{ok:!1,code:t.error?.code??`push.unknown`};let n=t;return{ok:!0,config:n,cleared:n.cleared??0}}function Sv(){return`serviceWorker`in navigator&&`PushManager`in window}async function Cv(){return await navigator.serviceWorker.getRegistration(`/sw.js`)||navigator.serviceWorker.register(`/sw.js`)}async function wv(){return Sv()?await(await Cv()).pushManager.getSubscription()?`subscribed`:Notification.permission:`unsupported`}async function Tv(e=``){if(!Sv())return{ok:!1,message:J(`这个浏览器不支持推送(需要 https 或 localhost)`,`This browser does not support push (https or localhost required)`)};if(await Notification.requestPermission()!==`granted`)return{ok:!1,message:J(`通知权限被拒绝`,`Notification permission was denied`)};let t=await Cv(),{publicKey:n}=await(await fetch(`/api/push/key`)).json(),r=gv(n),i=await t.pushManager.getSubscription(),a=!1;i&&!vv(i.options.applicationServerKey,r)&&(await i.unsubscribe(),a=!0);let o=((a?null:i)??await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:r})).toJSON(),s=await fetch(`/api/push/subscribe`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":sessionStorage.getItem(`pop-agent-client`)??``},body:JSON.stringify({endpoint:o.endpoint,keys:o.keys,name:_v(),brandName:e})});return s.ok?a?{ok:!0,rekeyed:a}:{ok:!0}:{ok:!1,message:J(`订阅保存失败:HTTP ${s.status}`,`Saving the subscription failed: HTTP ${s.status}`)}}async function Ev(e){if(Sv())try{let t=await(await navigator.serviceWorker.getRegistration(`/sw.js`))?.pushManager.getSubscription();if(!t)return;await fetch(`/api/push/brand`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({endpoint:t.endpoint,brandName:e})})}catch{}}async function Dv(){if(!Sv())return{ok:!1,message:J(`不支持推送`,`Push is not supported`)};let e=await(await Cv()).pushManager.getSubscription();return e&&(await fetch(`/api/push/unsubscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({endpoint:e.endpoint})}),await e.unsubscribe()),{ok:!0}}var Ov=`pop-agent.brand.name`,kv=`pop-agent.brand.show`,Av=`pop-agent.brand.logo`,jv=`pop-agent.brand.logo.show`,Mv=`pop-agent:brand-name`,Nv=[Ov,kv,Av,jv];function Pv(e){return e?e.replace(/\s+/g,` `).trim().slice(0,24).trim():``}function Fv(){return Pv(Yr(Ov))}function Iv(){return Fv()||`PopAgent`}var Lv=800,Rv=null;function zv(e){let t=Pv(e);t!==Fv()&&(Xr(Ov,t),Gv(),Bv())}function Bv(){Rv!==null&&clearTimeout(Rv),Rv=setTimeout(()=>{Rv=null,Ev(Fv())},Lv)}function Vv(){zv(``)}function Hv(){return Zr(kv,!0)}function Uv(e){Qr(kv,e),Gv()}function Wv(e){let t=t=>{let n=t.detail;(!n?.key||Nv.includes(n.key))&&e()},n=t=>{(t.key===null||Nv.includes(t.key))&&e()};return window.addEventListener(Mv,t),window.addEventListener(`pop-agent:pref`,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Mv,t),window.removeEventListener(`pop-agent:pref`,t),window.removeEventListener(`storage`,n)}}function Gv(){window.dispatchEvent(new CustomEvent(Mv,{detail:{key:Ov}}))}function Kv(){return Yr(`pop-agent.brand.logo`)??``}function qv(e){let t=(e??``).trim();t!==(Yr(`pop-agent.brand.logo`)??``)&&(Xr(Av,t),Gv())}function Jv(){return Zr(jv,!0)}function Yv(e){Qr(jv,e),Gv()}function Xv(e){let t=$r(kv,e),n=Wv(()=>e(Hv()));return()=>{t(),n()}}function Zv(){let[e,t]=(0,C.useState)(()=>Qv());return(0,C.useEffect)(()=>{let e=Wv(()=>t(Qv())),n=Xv(e=>t(t=>t.shown===e?t:{...t,shown:e}));return()=>{e(),n()}},[]),{name:e.name,custom:e.custom,shown:e.shown,logo:e.logo,logoShown:e.logoShown,setName:zv,setShown:Uv,setLogo:qv,setLogoShown:Yv,reset:Vv}}function Qv(){return{name:Iv(),custom:Fv(),shown:Hv(),logo:Kv(),logoShown:Jv()}}function $v({webVersion:e,latestVersion:t,outdated:n,onUpgrade:r,desktop:i=!1}){let a=Y(),{name:o,logo:s}=Zv();return(0,Q.jsx)(`div`,{className:`newchat-meta`,children:(0,Q.jsxs)(`div`,{className:`newchat-brand`,children:[(0,Q.jsx)(`img`,{className:`newchat-icon`,src:s||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`newchat-brand-text`,children:[(0,Q.jsx)(`span`,{className:`newchat-name`,children:o}),(0,Q.jsxs)(`span`,{className:`newchat-versions mono`,children:[(0,Q.jsx)(`a`,{className:`newchat-version-link`,href:T,target:`_blank`,rel:`noreferrer`,title:n&&t?a(`上游已发布 v${t}(本机 v${e})· 点这里去仓库看更新日志`,`Upstream released v${t} (you are on v${e}) · open the repo for the changelog`):a(`${T}(点这里看更新日志 / 提 issue)`,`${T} (changelog / issues)`),children:a(`开源项目`)}),` v${e}`,n?(0,Q.jsxs)(`button`,{type:`button`,className:`newchat-version-badge`,disabled:!r,onClick:r,title:r?i?a(`打开发布页下载 v${t??`新版本`} 安装包(当前 v${e})`,`Open the releases page to download v${t??`the new build`} (you are on v${e})`):a(`在终端里执行 ${E}(回车自动敲)`,`Runs ${E} in a terminal (auto-submitted)`):a(`上游已发布 v${t??``},本机 v${e}`,`Upstream released v${t??``}, you are on v${e}`),children:[a(`↑ 有新版`),r?` · ${a(`点此升级`)}`:``]}):null]})]})]})})}function ey({templates:e,conversationId:t}){let n=Y(),{language:r}=Ae(),[i,a]=(0,C.useState)(null);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`newchat-tpls`,role:`list`,"aria-label":n(`提示词列表`,`Prompt list`),children:[dp(e).map(e=>{let t=fp(e,r);return(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`tpl-card newchat-tpl`,onClick:()=>a({template:e}),title:n(`点击编辑`,`Click to edit`),children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:e.icon}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:t.name}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:t.description})]},e.id)}),(0,Q.jsxs)(`button`,{type:`button`,role:`listitem`,className:`tpl-card tpl-card-new newchat-tpl`,onClick:()=>a({template:null}),children:[(0,Q.jsx)(`span`,{className:`tpl-icon`,"aria-hidden":`true`,children:`+`}),(0,Q.jsx)(`span`,{className:`tpl-name`,children:n(`新建模板`,`New template`)}),(0,Q.jsx)(`span`,{className:`tpl-desc`,children:n(`把常用工作流存成模板`,`Save a repeated workflow as a template`)})]})]}),i?(0,Q.jsx)(vp,{template:i.template,library:e,conversationId:t??null,onClose:()=>a(null)}):null]})}function ty(e){let t=e=>e.blocks.filter(e=>e.kind===`text`).map(e=>e.kind===`text`?e.text:``).join(` `).replace(/\s+/g,` `).trim(),n=[];return e.forEach((r,i)=>{if(r.role!==`user`)return;let a=e.slice(i+1).find(e=>e.role===`assistant`);n.push({id:r.id,index:n.length+1,question:t(r).slice(0,120)||J(`(空消息)`,`(empty message)`),answer:a?t(a).slice(0,160):``})}),n}function ny({messages:e}){let t=Y(),[n,r]=(0,C.useState)(null),i=(0,C.useRef)(null),a=()=>{i.current&&clearTimeout(i.current),i.current=null},o=()=>{a(),i.current=setTimeout(()=>r(null),160)},s=(0,C.useMemo)(()=>ty(e),[e,t]),[c,l]=(0,C.useState)(0),u=(0,C.useRef)(null),d=(0,C.useRef)(null),f=(0,C.useRef)(null);if((0,C.useLayoutEffect)(()=>{if(n===null)return;let e=u.current,t=f.current,r=d.current?.children[n];if(!e||!t||!r)return;let i=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=t.querySelector(`.outline-entry-on`),s=o?o.getBoundingClientRect().top-a.top:0,c=r.getBoundingClientRect().top-i.top,p=Math.max(0,e.clientHeight-t.offsetHeight-8);l(Math.max(0,Math.min(c-s,p)))},[n,s.length]),s.length===0)return null;let p=e=>{document.getElementById(`msg-${e}`)?.scrollIntoView({behavior:`smooth`,block:`start`})},m=n===null?[]:s.slice(Math.max(0,n-2),Math.min(s.length,n+3));return(0,Q.jsxs)(`div`,{className:`outline`,"aria-label":t(`对话大纲`),ref:u,children:[(0,Q.jsx)(`div`,{className:`outline-rail`,ref:d,onMouseLeave:o,onMouseEnter:a,children:s.map((e,i)=>(0,Q.jsx)(`button`,{type:`button`,className:`outline-dot${n===i?` outline-dot-on`:``}`,onMouseEnter:()=>r(i),onFocus:()=>r(i),onClick:()=>p(e.id),title:t(`第 ${e.index} 问`,`Question ${e.index}`)},e.id))}),n===null?null:(0,Q.jsxs)(`div`,{className:`outline-preview`,ref:f,style:{marginTop:c},onMouseEnter:a,onMouseLeave:o,children:[m.map(e=>{let r=s[n]?.id===e.id;return(0,Q.jsxs)(`button`,{type:`button`,className:`outline-entry${r?` outline-entry-on`:``}`,onClick:()=>p(e.id),title:t(`点击定位到这条消息`),children:[(0,Q.jsxs)(`div`,{className:`outline-item`,children:[(0,Q.jsx)(`span`,{className:`outline-num mono`,children:String(e.index).padStart(2,`0`)}),(0,Q.jsx)(`span`,{className:`outline-q`,children:e.question})]}),e.answer?(0,Q.jsxs)(`div`,{className:`outline-item outline-item-answer`,children:[(0,Q.jsx)(`span`,{className:`outline-num mono`,children:`A`}),(0,Q.jsx)(`span`,{className:`outline-a`,children:e.answer})]}):null]},e.id)}),(0,Q.jsx)(`div`,{className:`outline-hint`,children:t(`点击任意一条定位过去`)})]})]})}function ry(e){let t=e.indexOf(`/`);return t<=0||t===e.length-1?null:e.slice(0,t)}function iy(e){let t=ry(e.id);if(t===null)return e.label||e.id;let n=e.id.slice(t.length+1);return e.label===e.id?n:e.label}function ay(e,t){let n=new Map;for(let r of e){let e=ry(r.id),i=e??t.name,a=e??t.label,o=n.get(i);o?o.models.push(r):n.set(i,{id:i,label:a,models:[r]})}return[...n.values()]}function oy(e){let t=new Set;for(let n of e){let e=ry(n);e!==null&&t.add(e)}return t}function sy(e,t={}){return e.credential===`apiKey`||e.credential===`oauth`?!0:t.engineReady?.has(e.provider)??!1}function cy({provider:e,onClose:t,onImported:n}){let r=Y(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(new Set),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(!1);(0,C.useEffect)(()=>{(async()=>{try{let t=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/remote-models`),n=await t.json();if(!t.ok){d(n.error?.message??`HTTP ${t.status}`),a([]);return}a(n.models??[])}catch(e){d(e instanceof Error?e.message:String(e)),a([])}})()},[e.provider]);let m=(i??[]).filter(e=>c.trim()===``||e.id.toLowerCase().includes(c.trim().toLowerCase())),h=m.filter(e=>!e.imported),g=async()=>{if(o.size!==0){p(!0);try{let r=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/import`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:[...o]})}),i=await r.json();r.ok?(n(),t()):d(i.error?.message??`HTTP ${r.status}`)}finally{p(!1)}}};return(0,Q.jsxs)(`div`,{className:`side-panel import-models`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:r(`导入模型`)}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.provider}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,children:r(`关闭`,`Close`)})]}),i===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`正在读取远端模型清单…`)}):null,u?(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[r(`读取失败:`,`Failed to load: `),u]}):null,i===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`input`,{className:`side-field input`,value:c,onChange:e=>l(e.target.value),placeholder:r(`筛选模型 id…`)}),(0,Q.jsxs)(`div`,{className:`import-list`,children:[m.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有可导入的模型`)}):null,m.map(e=>(0,Q.jsxs)(`label`,{className:`import-row${e.imported?` import-row-done`:``}`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,disabled:e.imported,checked:e.imported||o.has(e.id),onChange:()=>s(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n})}),(0,Q.jsx)(`span`,{className:`import-id mono`,children:e.id}),e.imported?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:r(`已导入`)}):null]},e.id))]}),(0,Q.jsxs)(`div`,{className:`import-foot`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s(new Set(h.map(e=>e.id))),disabled:h.length===0,children:r(`全选可导入(${h.length})`,`Select all importable (${h.length})`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s(new Set),disabled:o.size===0,children:r(`清除选择`,`Clear selection`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void g(),disabled:f||o.size===0,children:r(`导入 ${o.size} 个`,`Import ${o.size}`)})]})]})]})}var ly=[`input`,`output`,`cacheRead`,`cacheWrite`],uy={input:`输入`,output:`输出`,cacheRead:`缓存读`,cacheWrite:`缓存写`},dy={input:`Input`,output:`Output`,cacheRead:`Cache read`,cacheWrite:`Cache write`};function fy(e,t){let n=e.models.find(e=>e.id===t),r=n?.cost??{},i=e=>typeof e==`number`?String(e):``;return{id:t,name:n?.name??t,reasoning:n?.reasoning===!0,imageInput:n?.imageInput===!0,contextWindow:i(n?.contextWindow),maxTokens:i(n?.maxTokens),input:i(r.input),output:i(r.output),cacheRead:i(r.cacheRead),cacheWrite:i(r.cacheWrite),schedule:(n?.costSchedule??[]).map(e=>({start:e.start,end:e.end??``,input:i(e.input),output:i(e.output),cacheRead:i(e.cacheRead),cacheWrite:i(e.cacheWrite)}))}}function py(e){let t=/^\d{1,2}:\d{2}(?::\d{2})?$/,n=new Set;for(let[r,i]of e.entries()){let e=i.start.trim(),a=i.end.trim();if(!t.test(e))return J(`第 ${r+1} 段还没填开始时间`,`Segment ${r+1} has no start time`);if(n.has(e))return J(`${e} 这个开始时间填了两次(同一时刻只能有一段价格)`,`${e} is used twice (only one price per moment)`);if(n.add(e),a!==``&&a===e)return J(`第 ${r+1} 段的开始和结束时间相同`,`Segment ${r+1} starts and ends at the same time`);for(let e of ly){let t=i[e].trim();if(t===``)continue;let n=Number(t);if(!Number.isFinite(n)||n<0)return J(`第 ${r+1} 段的${uy[e]}必须是非负数`,`Segment ${r+1}: ${dy[e]} must be a non-negative number`)}}return null}function my(e){let t=new Set(e.map(e=>e.start)),n=e.at(-1)?.start??`11:00`,r=Number(n.slice(0,2));for(let e=1;e<=24;e+=1){let n=`${String((r+e)%24).padStart(2,`0`)}:00`;if(!t.has(n))return n}return`12:00`}function hy({provider:e,modelId:t,onClose:n}){let r=Y(),[i,a]=(0,C.useState)(()=>fy(e,t)),[o,s]=(0,C.useState)(!1),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)(!1),v=(e,t)=>a(n=>({...n,[e]:t})),y=(e,t,n)=>a(r=>({...r,schedule:r.schedule.map((r,i)=>i===e?{...r,[t]:n}:r)})),b=()=>a(e=>({...e,schedule:[...e.schedule,{start:my(e.schedule),end:``,input:``,output:``,cacheRead:``,cacheWrite:``}]})),x=e=>a(t=>({...t,schedule:t.schedule.filter((t,n)=>n!==e)})),S=async()=>{let t=Date.now();_(!0),d(null);try{let t=await fetch(`/api/providers/${encodeURIComponent(e.provider)}/catalog?model=${encodeURIComponent(i.id)}`),n=await t.json();if(!t.ok||!n.spec){d(r(`models.dev 里没查到,请手动填写`,`Not found on models.dev — please fill it in by hand`));return}let o=n.spec;a(e=>({...e,name:o.name||e.name,reasoning:o.reasoning,imageInput:o.imageInput,contextWindow:o.contextWindow===null?``:String(o.contextWindow),maxTokens:o.maxTokens===null?``:String(o.maxTokens),input:o.cost?String(o.cost.input??``):``,output:o.cost?String(o.cost.output??``):``,cacheRead:o.cost?String(o.cost.cacheRead??``):``,cacheWrite:o.cost?String(o.cost.cacheWrite??``):``})),d(r(`已填入`,`Filled in`))}finally{setTimeout(()=>_(!1),Math.max(0,400-(Date.now()-t)))}},w=async()=>{p(!0),h(null);let t=await pu(e.provider,i.id);h({ok:t.ok,text:t.ok?r(`已连接 · ${t.latencyMs}ms · HTTP ${t.status}`,`Connected · ${t.latencyMs}ms · HTTP ${t.status}`):r(`未连接 · ${t.message}`,`Not connected · ${t.message}`)}),p(!1)};return(0,Q.jsxs)(`div`,{className:`side-panel model-editor`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:r(`模型`,`Model`)}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.provider}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:()=>{let t=py(i.schedule);if(l(t),t)return;let n=i.schedule.map(e=>({start:e.start,...e.end.trim()===``?{}:{end:e.end},...ly.reduce((t,n)=>(e[n].trim()!==``&&(t[n]=e[n]),t),{})}));hu(e.provider,{id:i.id,name:i.name,reasoning:i.reasoning,imageInput:i.imageInput,contextWindow:i.contextWindow,maxTokens:i.maxTokens,cost:{input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite},costSchedule:n}),s(!0)},title:r(`保存模型信息(含分时价格)`,`Save the model (including time-of-day prices)`),children:r(`保存`,`Save`)}),m?(0,Q.jsx)(`span`,{className:`prov-test-pill${m.ok?` prov-test-ok`:` prov-test-fail`}`,children:m.text}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void w(),disabled:f,title:r(`发送一次最小 chat 请求(max_tokens=1)`,`Send one minimal chat request (max_tokens=1)`),children:f?r(`测试中…`,`Testing…`):r(`测试`,`Test`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{let t=e.source===`builtin`?r(`
39
39
  (这是 pi 内置 provider,移除后会写一份自定义条目来覆盖它的模型表)`,`
40
- (pi built-in provider: removing writes a custom entry that overrides its model list)`):``;window.confirm(r(`从「${e.provider}」移除模型 ${i.id}?${t}`,`Remove model ${i.id} from “${e.provider}”?${t}`))&&(_u(e.provider,i.id),n())},children:r(`移除`,`Remove`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:n,children:r(`关闭`,`Close`)})]}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`ID(必填)`,`ID (required)`)}),(0,Q.jsx)(`input`,{value:i.id,readOnly:!0,title:r(`ID 是主键,改名等于新建一个模型`,`The ID is the key — renaming it creates a new model`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:`Name`}),(0,Q.jsx)(`input`,{value:i.name,onChange:e=>v(`name`,e.target.value),placeholder:`DeepSeek V4.1 Flash`})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`能力`,`Capabilities`)}),(0,Q.jsxs)(`label`,{className:`side-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.reasoning,onChange:e=>v(`reasoning`,e.target.checked)}),r(`推理 / 思考`,`Reasoning / thinking`)]}),(0,Q.jsxs)(`label`,{className:`side-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.imageInput,onChange:e=>v(`imageInput`,e.target.checked)}),r(`图片输入`,`Image input`)]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`模型规格`,`Model limits`)}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`上下文窗口(tokens)`,`Context window (tokens)`)}),(0,Q.jsx)(`input`,{inputMode:`numeric`,value:i.contextWindow,onChange:e=>v(`contextWindow`,e.target.value),placeholder:`1000000`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`最大输出 tokens`,`Max output tokens`)}),(0,Q.jsx)(`input`,{inputMode:`numeric`,value:i.maxTokens,onChange:e=>v(`maxTokens`,e.target.value),placeholder:`384000`})]})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`每百万 tokens 价格(全天价;留空 = 未提供)`,`Price per million tokens (flat all-day rate; empty = not provided)`)}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`输入`,`Input`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.input,onChange:e=>v(`input`,e.target.value),placeholder:r(`未提供`,`not provided`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`输出`,`Output`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.output,onChange:e=>v(`output`,e.target.value),placeholder:r(`未提供`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`缓存读`,`Cache read`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.cacheRead,onChange:e=>v(`cacheRead`,e.target.value),placeholder:r(`未提供`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`缓存写`,`Cache write`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.cacheWrite,onChange:e=>v(`cacheWrite`,e.target.value),placeholder:r(`未提供`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`分时价格(可选,按本机时区)`,`Time-of-day prices (optional, local timezone)`)}),i.schedule.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`不填时段 = 全天都用上面的价格`,`No segments = the flat price above applies all day`)}):null,i.schedule.map((e,t)=>(0,Q.jsxs)(`div`,{className:`price-seg`,children:[(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`开始`,`Start`)}),(0,Q.jsx)(`input`,{type:`time`,value:e.start,onChange:e=>y(t,`start`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`结束(空 = 到下一段)`,`End (empty = until the next segment)`)}),(0,Q.jsx)(`input`,{type:`time`,value:e.end,onChange:e=>y(t,`end`,e.target.value)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>x(t),title:r(`删掉这一段(删完就回到全天一个价)`,`Delete this segment (back to one all-day price)`),children:r(`删`,`Del`)})]}),(0,Q.jsx)(`div`,{className:`side-field-row`,children:ly.map(n=>(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(uy[n],dy[n])}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:e[n],onChange:e=>y(t,n,e.target.value),placeholder:r(`同全天价`,`same as flat`)})]},n))})]},t)),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:b,title:r(`加一段高峰 / 低峰价格`,`Add a peak / off-peak segment`),children:[`+ `,r(`添加时段`,`Add segment`)]}),i.schedule.length>0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`每段从开始时间生效,直到下一段开始;没填结束的最后一段会跨零点接到最早那段。段内价格留空 = 沿用上面的全天价;想精确控制某几个小时就填结束时间。`,`Each segment applies from its start time until the next one starts; a last segment without an end wraps past midnight into the earliest one. Leaving a segment's price empty reuses the flat rate; fill the end time to target specific hours.`)}):null]}),(0,Q.jsx)(`div`,{className:`import-foot`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,title:r(`从 models.dev 查这个模型的公开规格(只作建议值,会覆盖当前已填的规格)`,`Look up public specs on models.dev (suggestions only; overwrites the values above)`),onClick:()=>void S(),disabled:g,children:g?r(`填充中…`,`Filling…`):r(`填入模型信息`,`Fill in model specs`)})}),u?(0,Q.jsx)(`div`,{className:u.startsWith(r(`已填入`,`Filled in`))?`side-ok`:`side-panel-hint side-error`,children:u}):null,o?(0,Q.jsx)(`div`,{className:`side-ok`,children:r(`已提交(服务端校验通过才会写入;失败原因会显示在弹窗顶部)`,`Submitted (written only after server validation; failures show at the top)`)}):null,e.source===`builtin`?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[r(`当前是 pi 内置 provider:保存会直接写回`,`This is a pi built-in provider: saving writes straight back to`),` `,(0,Q.jsx)(`span`,{className:`mono`,children:`~/.pi/agent/models.json`})]}):null,c?(0,Q.jsxs)(`div`,{className:`side-error side-panel-hint`,children:[r(`分时价格:`,`Time-of-day prices: `),c,r(`(尚未提交)`,` (not submitted yet)`)]}):null]})}function gy({initial:e,onSaved:t,formRef:n}){let[r,i]=(0,C.useState)(e?.provider??``),[a,o]=(0,C.useState)(e?.baseUrl??``),[s,c]=(0,C.useState)(e?.api||`openai-completions`),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(``),[p,m]=(0,C.useState)((e?.models??[]).map(e=>({id:e.id,on:!0}))),[h,g]=(0,C.useState)(``),_=(e?.models.length??0)===0&&(e?.modelCount??0)>0,v=J(),[y,b]=(0,C.useState)(null),[x,S]=(0,C.useState)(!1),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(0),[O,k]=(0,C.useState)({}),[A,j]=(0,C.useState)(!1),[M,N]=(0,C.useState)(0),[P,F]=(0,C.useState)(0),I=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>I.current?.abort(),[]);let L=async()=>{S(!0),T(null);try{let e=await fetch(`/api/providers/remote-models`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:r,baseUrl:a,api:s,...l.trim()===``?{}:{apiKey:l.trim()},...Object.keys(W).length>0?{headers:W}:{}})}),t=await e.json(),n=(t.models??[]).map(e=>e.id);if(!e.ok||n.length===0){T(t.error?.message??v(`这个地址没有返回可用的模型`,`This endpoint returned no usable models`));return}m(e=>{let t=new Set(e.map(e=>e.id));return[...e,...n.filter(e=>!t.has(e)).map(e=>({id:e,on:!1}))]}),D(n.length),b({kind:`ok`,text:v(`已获取 ${n.length} 个模型:勾选要用的,再保存`,`Fetched ${n.length} models — tick the ones you need, then save`)})}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(!1)}},R=p.filter(e=>e.on).map(e=>e.id),z=async()=>{let t=e?.provider,n=R.slice();if(!t||n.length===0||I.current)return;let r=new AbortController;I.current=r,j(!0),N(0),F(n.length),k({});let i=0;for(let e of n){if(r.signal.aborted)break;try{let n=await fetch(`/api/providers/${encodeURIComponent(t)}/models/${encodeURIComponent(e)}/test`,{method:`POST`,signal:r.signal}),i=await n.json();k(t=>({...t,[e]:i.ok?{ok:!0,text:[i.latencyMs===void 0?null:`${i.latencyMs}ms`,i.message??null].filter(e=>e!==null&&e!==``).join(` · `)}:{ok:!1,text:v(`失败 ${i.message??i.error?.message??`HTTP ${n.status}`}`,`Failed: ${i.message??i.error?.message??`HTTP ${n.status}`}`).trim()}}))}catch(t){if(r.signal.aborted)break;k(n=>({...n,[e]:{ok:!1,text:t instanceof Error?t.message:v(`失败`,`Failed`)}}))}i+=1,N(i)}I.current=null,j(!1)},B=(e,t)=>m(n=>n.map(n=>n.id===e?{...n,on:t}:n)),V=e=>m(t=>t.filter(t=>t.id!==e)),H=e=>m(t=>t.map(t=>({...t,on:e}))),U=()=>{let e=h.trim();e===``||p.some(t=>t.id===e)||m(t=>[...t,{id:e,on:!0}]),g(``)},W=Object.fromEntries(d.split(/\r?\n/).map(e=>e.split(/:(.*)/s)).filter(([e,t])=>!!(e?.trim()&&t?.trim())).map(([e,t])=>[e.trim(),t.trim()])),ee=()=>({provider:r,...e&&e.provider!==r.trim()?{previousProvider:e.provider}:{},baseUrl:a,api:s,...l.trim()===``?{}:{apiKey:l.trim()},...Object.keys(W).length>0?{headers:W}:{},models:R.map(e=>({id:e}))}),G=()=>{yu(ee()),t?.(r.trim()),b({kind:`ok`,text:v(`已提交,结果会以提示形式出现在对话区`,`Submitted — the result appears as a notice in the conversation`)}),u(``)};return(0,C.useImperativeHandle)(n,()=>({save:G})),(0,Q.jsxs)(`div`,{className:`side-panel`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`provider(小写,作为 provider/model 前缀)`,`provider (lowercase; used as the provider/model prefix)`)}),(0,Q.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`my-endpoint`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:`base url`}),(0,Q.jsx)(`input`,{value:a,onChange:e=>o(e.target.value),placeholder:`https://api.example.com/v1`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`api 形态`,`API shape`)}),(0,Q.jsxs)(`select`,{value:s,onChange:e=>c(e.target.value),children:[(0,Q.jsx)(`option`,{value:`openai-completions`,children:`openai-completions`}),(0,Q.jsx)(`option`,{value:`openai-responses`,children:`openai-responses`}),(0,Q.jsx)(`option`,{value:`anthropic-messages`,children:`anthropic-messages`}),(0,Q.jsx)(`option`,{value:`openai-codex-responses`,children:`openai-codex-responses`}),(0,Q.jsx)(`option`,{value:`typesafe-system-one`,children:`typesafe-system-one`})]})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{children:[`API Key`,v(`(`,` (`),e?.hasKey?v(`已有 ${e.keyHint??``},留空即不修改`,`Saved ${e.keyHint??``} — leave empty to keep it`):e?.credential===`oauth`?v(`已用订阅登录${e.oauth?.accountHint?`(账号 ${e.oauth.accountHint})`:``},留空即继续用订阅额度`,`Signed in${e.oauth?.accountHint?` (${e.oauth.accountHint})`:``} — leave empty to keep using subscription quota`):_?v(`填一把就能用`,`just add a key`):v(`新增 provider 必填`,`required for a new provider`),v(`)`,`)`)]}),(0,Q.jsx)(`input`,{type:`password`,value:l,onChange:e=>u(e.target.value),placeholder:`sk-…`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`自定义 Headers(每行 Name: Value)`,`Custom headers (one Name: Value per line)`)}),(0,Q.jsx)(`textarea`,{rows:3,value:d,onChange:e=>f(e.target.value),placeholder:e?.headerNames?.length?v(`已有:${e.headerNames.join(`, `)};留空保持不变`,`Saved: ${e.headerNames.join(`, `)} — leave empty to keep`):`X-Client: pop-agent`})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{className:`prov-field-head`,children:[v(`模型(勾选的才保存)`,`Models (only ticked ones are saved)`),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[R.length,`/`,p.length]}),(0,Q.jsxs)(`span`,{className:`prov-check-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>H(!0),disabled:p.every(e=>e.on),title:v(`全部勾上(保存时全部写进 provider)`,`Tick everything (all get written to the provider)`),children:v(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>H(!1),disabled:p.every(e=>!e.on),title:v(`全部不勾(保存时一个模型都不写)`,`Tick nothing (no model is written)`),children:v(`全不选`,`Select none`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:`auto`},onClick:()=>void z(),disabled:!e||A||R.length===0,title:e?A?v(`正在逐个测速`,`Testing models`):v(`逐个测试勾选的模型,每个模型会发一次最小请求`,`Tests each ticked model with one minimal request`):v(`先保存 provider,再用已保存的配置测速`,`Save the provider first, then test with its saved config`),children:A?v(`测速中…`,`Testing…`):v(`⏱ 批量测速`,`⏱ Test speed`)}),A?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>I.current?.abort(),title:v(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),children:[`■ `,v(`停止`,`Stop`),` `,M,`/`,P]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void L(),disabled:x||a.trim()===``,title:v(`调一次 GET /models 把可用模型拉回来,勾选要用的那些`,`Call GET /models to fetch the available models, then tick the ones you need`),children:x?v(`获取中…`,`Fetching…`):v(`⬇️ 从 API 获取`,`⬇️ Fetch from API`)})]}),p.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:v(`还没有模型:点「从 API 获取」,或在下面手填一个 id`,`No models yet — fetch from the API, or add an id by hand below`)}):(0,Q.jsx)(`div`,{className:`prov-checklist`,children:p.map(e=>(0,Q.jsxs)(`div`,{className:`prov-check-row${e.on?` prov-check-on`:``}`,children:[(0,Q.jsxs)(`label`,{className:`prov-check-label`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.on,onChange:t=>B(e.id,t.target.checked)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.id})]}),(0,Q.jsx)(_y,{result:O[e.id]}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:v(`从列表里删掉这一行`,`Remove this row`),onClick:()=>V(e.id),children:v(`移除`,`Remove`)})]},e.id))}),(0,Q.jsxs)(`div`,{className:`prov-add-row`,children:[(0,Q.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&U()},placeholder:v(`手动加一个模型 id,回车添加`,`Add a model id by hand, press Enter`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:U,disabled:h.trim()===``,children:v(`添加`,`Add`)})]})]}),w?(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[v(`获取失败:`,`Fetch failed: `),w]}):null,E>0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[v(`已从接口取回`,`Fetched`),` `,E,` `,v(`个模型:勾上要用的,再保存`,`models — tick the ones you need, then save`)]}):null,y?(0,Q.jsx)(`div`,{className:y.kind===`ok`?`side-ok`:`side-panel-hint side-error`,children:y.text}):null]})}function _y({result:e}){return e?(0,Q.jsx)(`span`,{className:`prov-latency prov-check-latency${e.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:e.text,children:e.text}):null}function vy(e){let t=J(),n=e.snapshot,r=n?.engine??``,i=n?.models??[],a=n?.model??null,o=ay(i,{name:r,label:e.engineOption?.label??r.toUpperCase()}),s=n?.engineCapabilities.modelProbe===!0,[c,l]=(0,C.useState)(null),u=o.find(e=>e.id===c)??o[0]??null,[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(!0),[h,g]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:engine-model-list-width`));return Number.isFinite(e)&&e>=140&&e<=420?e:190});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:engine-model-list-width`,String(h))},[h]);let _=(0,C.useRef)(!1),v=e=>{e.preventDefault(),_.current=!0;let t=e.clientX,n=h,r=e=>{_.current&&g(Math.min(420,Math.max(140,n+(e.clientX-t))))},i=()=>{_.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},[y,b]=(0,C.useState)({}),[x,S]=(0,C.useState)(null),[w,T]=(0,C.useState)(null),E=(0,C.useRef)(null),D=async e=>{if(e.length===0||x!==null)return;let n=new AbortController;E.current=n,b({}),T({done:0,total:e.length});let r=0;for(let i of e){if(n.signal.aborted)break;S(i);let a=await mu(i,n.signal),o=a.tps??a.averageTps??null,s=a.ttftMs===null||a.ttftMs===void 0?null:yy(a.ttftMs),c=a.ok?[t(s?`首字 ${s}`:`首字 ?`,s?`first ${s}`:`first ?`),t(o===null?`速度 ?`:`${o} tok/s${a.tps===null?`(均速)`:``}`,o===null?`speed ?`:`${o} tok/s${a.tps===null?` (avg)`:``}`)].join(` · `):t(`失败:${a.message??`未知错误`}`,`Failed: ${a.message??`unknown error`}`),l=c.length>42?`${c.slice(0,40)}…`:c;b(e=>({...e,[i]:{ok:a.ok,text:l,detail:c}})),r+=1,T({done:r,total:e.length})}S(null),T(null),E.current=null},O=e.engineOption?.label??r;return(0,Q.jsxs)(`div`,{className:`prov-shell engine-models`,style:{"--prov-list-width":`${h}px`},children:[(0,Q.jsxs)(`aside`,{className:`prov-list`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-list-head prov-list-toggle`,title:p?t(`收起服务商列表`,`Collapse the provider list`):t(`展开服务商列表`,`Expand the provider list`),onClick:()=>m(e=>!e),children:(0,Q.jsxs)(`span`,{className:`prov-list-toggle-label`,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${p?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),t(`供应商`,`Providers`)]})}),(0,Q.jsx)(`div`,{className:`prov-list-body${p?``:` prov-list-body-closed`}`,children:(0,Q.jsxs)(`div`,{className:`prov-list-scroll`,children:[o.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t(`引擎还没报上来模型:先新建一个会话`,`The engine has not reported any models yet — create a conversation first`)}):null,o.map(e=>{let n=u?.id===e.id,r=d===e.id&&e.models.length>0;return(0,Q.jsxs)(`div`,{className:`prov-block${n?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${n?` prov-item-on`:``}`,"aria-expanded":r,title:e.id,onClick:()=>{l(e.id),f(r?null:e.id)},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[e.models.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${r?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,children:e.label})]}),(0,Q.jsx)(`span`,{className:`prov-item-state`,children:`${e.models.length} ${t(`个模型`,`models`)}`})]}),r?(0,Q.jsx)(`div`,{className:`prov-models-inline`,children:e.models.map(n=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-inline-row`,title:n.id,onClick:()=>l(e.id),children:[(0,Q.jsx)(`span`,{className:`prov-inline-name`,children:iy(n)}),n.id===a?(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:t(`当前`,`current`)}):null]},n.id))}):null]},e.id)})]})})]}),(0,Q.jsx)(`div`,{className:`prov-resizer`,role:`separator`,"aria-orientation":`vertical`,title:t(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:v,onDoubleClick:()=>g(190)}),(0,Q.jsxs)(`section`,{className:`prov-detail`,children:[(0,Q.jsxs)(`div`,{className:`prov-tabs`,children:[(0,Q.jsx)(`span`,{className:`prov-engine-badge`,children:e.engineOption?.badge??r.toUpperCase()}),(0,Q.jsx)(`strong`,{className:`prov-detail-title`,children:u?.label??O}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[u?u.models.length:0,` `,t(`个模型`,`models`)]}),s&&u&&u.models.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x!==null,title:t(`对每个模型各发一次真实请求(会消耗少量额度),测首字延迟与出字速度`,`Sends one real request per model (costs a little quota) and measures time-to-first-token and tokens/s`),onClick:()=>{window.confirm(t(`会对 ${u.models.length} 个模型各发一次真实请求(消耗少量额度),继续?`,`This sends one real request per model (${u.models.length} total) and spends a little quota. Continue?`))&&D(u.models.map(e=>e.id))},children:w?t(`测速中… ${w.done}/${w.total}`,`Testing… ${w.done}/${w.total}`):t(`⏱ 批量测速`,`⏱ Test speed`)}),w?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,title:t(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),onClick:()=>E.current?.abort(),children:[`■ `,t(`停止`,`Stop`)]}):null]}):null]}),(0,Q.jsxs)(`div`,{className:`prov-detail-body`,children:[(0,Q.jsx)(`p`,{className:`prov-engine-note`,children:t(`这些是引擎自己报上来的模型(codex 读 model/list,claude / opencode / dsh 读会话里的模型表),本工作台不改它。换模型用输入区的模型下拉;测速是让引擎真跑一个最小回合,不读它的凭证。`,`These models come straight from the engine (codex via model/list, claude / opencode / dsh via their session model table); this workbench does not edit them. Switch models from the composer; testing runs one minimal turn inside the engine and never touches its credentials.`)}),u===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:i.length===0?t(`引擎还没报上来任何模型:先新建一个会话(claude / opencode 要开会话才拿得到模型表),或确认引擎已装好并登录。`,`The engine has not reported any models yet: create a conversation first (claude / opencode only expose their model table once a session exists), or check that the engine is installed and signed in.`):t(`左边挑一个供应商看模型。`,`Pick a provider on the left to see its models.`)}):(0,Q.jsx)(`div`,{className:`engine-model-list`,children:u.models.map(e=>{let n=y[e.id],r=e.id===a;return(0,Q.jsxs)(`div`,{className:`engine-model-row${r?` engine-model-row-on`:``}`,children:[(0,Q.jsx)(`span`,{className:`engine-model-name`,title:e.id,children:iy(e)}),(0,Q.jsx)(`span`,{className:`engine-model-id mono`,children:e.id}),r?(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:t(`当前`,`current`)}):null,s?(0,Q.jsx)(`span`,{className:`engine-model-probe`,children:x===e.id?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`测速中…`,`Testing…`)}):n?(0,Q.jsx)(`span`,{className:`prov-latency${n.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:n.detail,children:n.text}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x!==null,title:t(`发一次真实请求测这个模型(会消耗少量额度)`,`Sends one real request to measure this model (costs a little quota)`),onClick:()=>void D([e.id]),children:t(`测速`,`Test`)})}):null]},e.id)})})]})]})]})}function yy(e){return e>=1e3?`${(e/1e3).toFixed(2)}s`:`${Math.round(e)}ms`}function by({entry:e,onClose:t,onChanged:n,onImportModels:r,enabledModels:i=[],canTest:a=!1}){let o=J(),[s,c]=(0,C.useState)(`idle`),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(null),[y,b]=(0,C.useState)(``),[x,S]=(0,C.useState)(!1),[w,T]=(0,C.useState)(!1),[E,D]=(0,C.useState)({}),[O,k]=(0,C.useState)(null),[A,j]=(0,C.useState)(null),M=(0,C.useRef)(null),N=(0,C.useRef)(null),P=(0,C.useRef)(!1),F=(0,C.useCallback)(()=>{N.current?.close(),N.current=null},[]);(0,C.useEffect)(()=>{c(`idle`),u(null),f(null),m(null),g(null),v(null),b(``),P.current=!1,F(),M.current?.abort(),M.current=null,D({}),k(null),j(null)},[e.id,F]),(0,C.useEffect)(()=>F,[F]);let I=(0,C.useCallback)(async(t,n)=>{if(n.trim()!==``){S(!0),v(null);try{let r=await fetch(`/api/subscriptions/${encodeURIComponent(e.id)}/login`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({token:t,code:n.trim()})}),i=await r.json();if(!r.ok){v(i.error?.message??`HTTP ${r.status}`);return}m(e=>e&&e.token===t?null:e),g(null),b(``)}catch(e){v(e instanceof Error?e.message:String(e))}finally{S(!1)}}},[e.id]),L=(0,C.useCallback)(()=>{F(),P.current=!1,c(`connecting`),u(null),f(null),m(null),g(null),v(null),b(``);let t=new EventSource(`/api/subscriptions/${encodeURIComponent(e.id)}/login`);N.current=t,t.onmessage=e=>{let r=JSON.parse(e.data);r.type===`auth`?(c(`running`),u({url:r.url??``,instructions:r.instructions??null}),r.url&&window.open(r.url,`_blank`,`noopener,noreferrer`)):r.type===`device_code`?(c(`running`),f({userCode:r.userCode??``,verificationUri:r.verificationUri??``,seconds:r.expiresInSeconds??null}),r.verificationUri&&window.open(r.verificationUri,`_blank`,`noopener,noreferrer`)):r.type===`prompt_request`&&r.token?(c(`running`),m({kind:`text`,token:r.token,message:r.message??``,placeholder:r.placeholder??null,secret:r.secret===!0})):r.type===`select_request`&&r.token?(c(`running`),m({kind:`select`,token:r.token,message:r.message??``,options:r.options??[]})):r.type===`progress`?(c(`running`),g(r.message??null)):r.type===`info`?g(r.message??null):r.type===`success`?(P.current=!0,t.close(),N.current=null,c(`done`),g(null),m(null),n()):r.type===`error`?(P.current=!0,t.close(),N.current=null,c(`error`),g(null),v(r.message??o(`登录失败`,`Sign-in failed`))):r.type===`cancelled`&&(P.current=!0,t.close(),N.current=null,c(`idle`),g(null))},t.onerror=()=>{t.close(),N.current=null,!P.current&&(c(`error`),g(null),v(o(`和服务器的连接断了:重试一次(登录可能已经在中途被取消)`,`Lost the connection to the server — try again (the sign-in may have been cancelled midway)`)))}},[e.id,n,F]),R=(0,C.useCallback)(async()=>{T(!0),v(null);try{let t=await fetch(`/api/subscriptions/${encodeURIComponent(e.id)}/logout`,{method:`POST`}),r=await t.json();if(!t.ok){v(r.error?.message??`HTTP ${t.status}`);return}c(`idle`),n()}catch(e){v(e instanceof Error?e.message:String(e))}finally{T(!1)}},[e.id,n]),z=s===`connecting`||s===`running`,B=e.models??[],V=e.connected&&r!==void 0,H=t=>Bf(i,e.id,t),U=B.filter(e=>H(e.id)).map(e=>e.id),W=B.length>0&&U.length===B.length,ee=U.length===0,G=async t=>{if(t.length===0||M.current!==null)return;let n=new AbortController;M.current=n,D({}),j({done:0,total:t.length});let r=0;for(let i of t){if(n.signal.aborted)break;k(i);let a;try{let t=await fetch(`/api/providers/${encodeURIComponent(e.id)}/models/${encodeURIComponent(i)}/test`,{method:`POST`,signal:n.signal}),r=await t.json(),s=r.ok?[r.latencyMs===void 0?null:`${r.latencyMs}ms`,r.message??null].filter(e=>e!==null&&e!==``).join(` · `):o(`失败:${r.message??r.error?.message??`HTTP ${t.status}`}`,`Failed: ${r.message??r.error?.message??`HTTP ${t.status}`}`);a={ok:r.ok===!0,text:s.length>42?`${s.slice(0,40)}…`:s,detail:s}}catch(e){if(n.signal.aborted)break;let t=e instanceof Error?e.message:String(e);a={ok:!1,text:t.slice(0,40),detail:t}}D(e=>({...e,[i]:a})),r+=1,j({done:r,total:t.length})}k(null),j(null),M.current=null};return(0,Q.jsxs)(`div`,{className:`side-panel subs-detail`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.id}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),e.connected?(0,Q.jsx)(`span`,{className:`subs-state subs-state-on`,children:o(`已连接`,`Connected`)}):(0,Q.jsx)(`span`,{className:`subs-state`,children:o(`未连接`,`Not connected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,title:o(`回到 provider 列表`,`Back to the provider list`),children:`✕`})]}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e.subscription?o(`用你的订阅账号登录:额度算在订阅里,不按 API key 计费。凭据由引擎写进 ~/.pi/agent/auth.json。`,`Sign in with your subscription: usage counts against the subscription, not an API key. The engine writes the credential to ~/.pi/agent/auth.json.`):o(`用 OAuth 登录这个 provider(凭据由引擎写进 ~/.pi/agent/auth.json)。`,`Sign in to this provider with OAuth (the engine writes the credential to ~/.pi/agent/auth.json).`),(0,Q.jsxs)(`div`,{children:[o(`当前`,`Currently`),` `,e.modelCount,` `,o(`个模型。`,`models.`),` `,e.supportsApiKey?o(`它也支持 API key —— 那条路在左侧 provider 表单里。`,`It also accepts an API key — that route lives in the provider form on the left.`):``]})]}),l?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:l.instructions??o(`在授权页完成登录。`,`Finish signing in on the authorization page.`)}),(0,Q.jsx)(`a`,{className:`subs-link`,href:l.url,target:`_blank`,rel:`noopener noreferrer`,children:o(`打开授权页(浏览器没自动弹出时点这里)`,`Open the authorization page (click here if the browser did not open)`)})]}):null,d?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[o(`在验证页输入下面这串码`,`Enter this code on the verification page`),d.seconds?` (${Math.round(d.seconds/60)} ${o(`分钟内有效`,`min to enter`)})`:``,o(`:`,`:`)]}),(0,Q.jsx)(`div`,{className:`subs-code mono`,children:d.userCode}),(0,Q.jsx)(`a`,{className:`subs-link`,href:d.verificationUri,target:`_blank`,rel:`noopener noreferrer`,children:d.verificationUri})]}):null,p?.kind===`select`?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:p.message}),(0,Q.jsx)(`div`,{className:`subs-options`,children:p.options.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x,title:e.description??e.id,onClick:()=>void I(p.token,e.id),children:e.label},e.id))})]}):null,p?.kind===`text`?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:p.message}),(0,Q.jsx)(`input`,{type:p.secret?`password`:`text`,value:y,autoFocus:!0,autoComplete:`off`,placeholder:p.placeholder??o(`粘贴授权码或回调地址`,`Paste the authorization code or callback URL`),onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&I(p.token,y)}})]}),(0,Q.jsx)(`div`,{className:`subs-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:x||y.trim()===``,onClick:()=>void I(p.token,y),children:x?o(`校验中…`,`Checking…`):o(`提交`,`Submit`)})})]}):null,h?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:h}):null,_?(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:_}):null,s===`done`?(0,Q.jsx)(`div`,{className:`side-ok`,children:o(`已连接:模型表已重载,聊天里可以直接选它的模型了。`,`Connected — the model list was reloaded; you can pick its models in the chat now.`)}):null,(0,Q.jsx)(`div`,{className:`import-foot`,children:e.connected?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:L,disabled:w||z,children:o(`重新登录`,`Sign in again`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>void R(),disabled:w,children:o(`退出登录`,`Sign out`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:L,disabled:z,children:z?o(`登录中…`,`Signing in…`):o(`连接 ${e.name} 账号`,`Connect the ${e.name} account`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),z?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{F(),c(`idle`),m(null),u(null),f(null),g(null)},children:o(`取消`,`Cancel`)}):null]})}),B.length>0||V?(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{className:`prov-field-head`,children:[o(`模型(勾选的才启用)`,`Models (only ticked ones are enabled)`),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[U.length,`/`,B.length]}),(0,Q.jsxs)(`span`,{className:`prov-check-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:W,onClick:()=>gu(e.id,!0),title:o(`全部启用(写进 pi 的 settings.json)`,`Enable everything (written to pi's settings.json)`),children:o(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:ee,onClick:()=>gu(e.id,!1),title:o(`全部停用(对话里就选不到它们了)`,`Disable everything (they disappear from the composer)`),children:o(`全不选`,`Select none`)})]}),a?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:`auto`},disabled:O!==null||U.length===0,title:U.length===0?o(`先勾选要测的模型`,`Tick the models you want to test first`):o(`对勾选的 ${U.length} 个模型各发一次真实请求(消耗少量订阅额度),测首字延迟与出字速度`,`Sends one real request for each of the ${U.length} ticked models (spends a little subscription quota) and measures time-to-first-token and tokens/s`),onClick:()=>{let e=U.slice();window.confirm(o(`会对 ${e.length} 个模型各发一次真实请求(消耗少量额度),继续?`,`This sends one real request per model (${e.length} total) and spends a little quota. Continue?`))&&G(e)},children:A?o(`测速中… ${A.done}/${A.total}`,`Testing… ${A.done}/${A.total}`):o(`⏱ 批量测速`,`⏱ Test speed`)}):null,A?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,style:{marginLeft:a?0:`auto`},title:o(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),onClick:()=>M.current?.abort(),children:[`■ `,o(`停止`,`Stop`)]}):null,V?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:a?0:`auto`},onClick:r,disabled:w||z,title:o(`从订阅拉取可用模型,再勾选要启用的`,`Fetch available models from the subscription, then tick the ones to enable`),children:[`⬇️ `,o(`从订阅获取模型`,`Fetch models from subscription`)]}):null]}),B.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:o(`还没有导入模型:点「从订阅获取模型」`,`No models imported yet — click “Fetch models from subscription”`)}):(0,Q.jsx)(`div`,{className:`prov-checklist`,children:B.map(t=>{let n=H(t.id);return(0,Q.jsxs)(`div`,{className:`prov-check-row${n?` prov-check-on`:``}`,children:[(0,Q.jsxs)(`label`,{className:`prov-check-label`,title:n?o(`已启用:点击停用(写进 pi 的 settings.json)`,`Enabled — click to disable (written to pi's settings.json)`):o(`未启用:点击启用`,`Disabled — click to enable`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>gu(e.id,!n,t.id)}),(0,Q.jsx)(`span`,{className:`mono`,children:t.id})]}),(0,Q.jsx)(xy,{result:E[t.id],busy:O===t.id})]},t.id)})})]}):null]})}function xy({result:e,busy:t}){let n=J();return t?(0,Q.jsx)(`span`,{className:`prov-latency prov-latency-idle`,children:n(`测速中…`,`Testing…`)}):e?(0,Q.jsx)(`span`,{className:`prov-latency prov-check-latency${e.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:e.detail,children:e.text}):null}function Sy({tab:e,onTab:t,subscriptions:n,catalog:r,onPickSubscription:i,onPickBuiltin:a,onPickCustom:o}){let s=J(),c=[{id:`subscription`,label:s(`订阅服务`,`Subscriptions`),count:n.length},{id:`builtin`,label:s(`官方内置`,`Built-in`),count:r.length},{id:`custom`,label:s(`自己输入`,`Custom`),count:0}];return(0,Q.jsxs)(`div`,{className:`prov-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:s(`添加服务商`,`Add a provider`)}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`按来源选一种:订阅登录 / pi 目录里的 / 自己填`,`Pick a source: subscription, pi's catalog, or your own`)})]}),(0,Q.jsx)(`div`,{className:`prov-tabs`,children:c.map(n=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-tab${e===n.id?` prov-tab-on`:``}`,onClick:()=>t(n.id),children:[n.label,n.count>0?` ${n.count}`:``]},n.id))}),e===`subscription`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[n.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`引擎没报上来可订阅的渠道。`,`The engine reported no subscription providers.`)}):null,n.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-add-row`,onClick:()=>i(e.id),children:[(0,Q.jsx)(`span`,{className:`prov-add-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`prov-sub-state${e.connected?` prov-sub-state-on`:``}`,children:e.connected?s(`已登录 · 点开管理`,`Signed in · open to manage`):e.subscription?s(`订阅额度 · 点开登录`,`Subscription quota · click to sign in`):s(`OAuth · 点开登录`,`OAuth · click to sign in`)})]},e.id))]}):null,e===`builtin`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`pi 自己的目录里还没配 key 的。点一下就能填一把 key,模型表由目录提供。`,`Providers in pi's own catalog that have no key yet — click one to paste a key; the model list comes from the catalog.`)}),r.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`目录里的都已经配好了。`,`Everything in the catalog is configured.`)}):null,r.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-add-row`,onClick:()=>a(e.provider),children:[(0,Q.jsx)(`span`,{className:`prov-add-name`,children:e.label??e.provider}),(0,Q.jsx)(`span`,{className:`prov-item-sub`,children:e.needsExtraConfig?s(`需额外配置`,`Needs setup`):e.oauthOnly?s(`只能订阅登录`,`Subscription only`):s(`${e.modelCount??0} 个模型`,`${e.modelCount??0} models`)})]},e.provider))]}):null,e===`custom`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`自己填 base url / api 形态 / 模型清单。适合自建网关、局域网里的模型服务。`,`Fill in base url, API shape and the model list yourself — useful for your own gateway or a model server on the LAN.`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,children:[`+ `,s(`新建自定义服务商`,`New custom provider`)]})]}):null]})}function Cy(){let e=J(),t=Ro(e=>e.snapshot),n=(t?.engine??`pi`)===`pi`,r=t?.providers??[],i=t?.enabledModels??[],a=e=>i.length===0||i.some(t=>t===`${e.provider}/**`||t.startsWith(`${e.provider}/`)),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(!0),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)([]),[v,y]=(0,C.useState)(null),[b,x]=(0,C.useState)(!1),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(null),D=(0,C.useRef)(null),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:provider-list-width`));return Number.isFinite(e)&&e>=140&&e<=420?e:190});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:provider-list-width`,String(O))},[O]);let A=()=>{(async()=>{try{let e=await fetch(`/api/subscriptions`);if(!e.ok)return;let t=await e.json();_(t.providers??[])}catch{}})()};(0,C.useEffect)(A,[t?.engine]);let j=g.find(e=>e.id===m)??null,M=g.map((e,t)=>({entry:e,index:t})).sort((e,t)=>Number(t.entry.connected)-Number(e.entry.connected)||e.index-t.index).map(e=>e.entry),N=oy((t?.models??[]).map(e=>e.id)),P=e=>sy(e,{engineReady:N}),F=M.filter(e=>e.connected),I=new Set(F.map(e=>e.id)),L=r.filter(e=>e.official===!0&&P(e)&&!I.has(e.provider)),R=r.filter(e=>e.official!==!0&&P(e)&&!I.has(e.provider)),z=r.filter(e=>e.official===!0&&!P(e)&&(e.modelCount??0)>0),B=e=>r.find(t=>t.provider===e)??null,V=(0,C.useRef)(!1),H=e=>{e.preventDefault(),V.current=!0;let t=e.clientX,n=O,r=e=>{V.current&&k(Math.min(420,Math.max(140,n+(e.clientX-t))))},i=()=>{V.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},U=r.find(e=>e.provider===o)??r[0]??null,W=b||U===null,ee=u===null,G=(e,t)=>Bf(i,e,t),K=e=>e.models.filter(t=>G(e.provider,t.id)).length,te=r.reduce((e,t)=>e+t.models.length,0),ne=r.reduce((e,t)=>e+K(t),0);if(!n){let e=(t?.engines??[]).find(e=>e.name===t?.engine);return(0,Q.jsx)(vy,{snapshot:t,engineOption:e})}let re=t=>{let n=!b&&u===null&&!j&&U?.provider===t.provider,r=n&&v!==t.provider,i=t.models;return(0,Q.jsxs)(`div`,{className:`prov-block${n?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${n?` prov-item-on`:``}`,"aria-expanded":i.length>0?r:void 0,onClick:()=>{n&&v!==t.provider?y(t.provider):(y(null),p(null),d(null),x(!1),w(!1),E(null),h(null),s(t.provider))},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[i.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${r?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,title:t.label?`${t.label}(${t.provider})`:t.provider,children:t.label??t.provider})]}),t.credential===`apiKey`?null:t.credential===`oauth`?(0,Q.jsx)(`span`,{className:`prov-item-state${t.oauth?.expired?` prov-item-state-warn`:` prov-item-state-on`}`,title:t.oauth?.expired?e(`订阅登录的凭据已过期:点开「订阅服务」重新登录`,`Subscription credential expired — open Subscriptions and sign in again`):e(`订阅已登录${t.oauth?.accountHint?`(账号 ${t.oauth.accountHint})`:``}:不需要 API key,走订阅额度`,`Signed in${t.oauth?.accountHint?` (${t.oauth.accountHint})`:``}: no API key needed, subscription quota is used`),children:t.oauth?.expired?e(`订阅已过期`,`Expired`):e(`订阅已登录`,`Signed in`)}):N.has(t.provider)?(0,Q.jsx)(`span`,{className:`prov-item-state prov-item-state-on`,title:e(`引擎已经报上来它的模型(凭证由引擎自己解析,不在这份配置里):能直接用,换模型用输入区的下拉`,`The engine already reports its models (credentials are resolved by the engine, not stored here): ready to use — switch models from the composer`),children:e(`引擎已可用`,`Ready`)}):(0,Q.jsx)(`span`,{className:`prov-item-state`,title:t.needsExtraConfig?e(`除了 API key 还要端点 / 云凭证:去「配置」里补齐`,`Needs an endpoint or cloud credentials on top of the API key — fill them in Config`):t.oauthOnly?e(`这个 provider 只支持订阅登录:去上面「订阅服务」里登录`,`This provider only supports subscription sign-in — use Subscriptions above`):e(`填一把 API key 就能用`,`Ready once you add an API key`),children:t.needsExtraConfig?e(`需额外配置`,`Needs setup`):t.oauthOnly?e(`仅订阅登录`,`Subscription only`):e(`无 key`,`No key`)})]}),(0,Q.jsxs)(wy,{open:r,children:[i.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t.models.length===0&&t.modelCount?e(`还没配 key 用不了:填一把就能用(引擎目录里 ${t.modelCount} 个模型)`,`Not usable yet — add an API key (${t.modelCount} models in the engine catalog)`):t.models.length===0?e(`这个 provider 下没有模型`,`No models under this provider`):e(`这个 provider 下没有启用的模型`,`No enabled models under this provider`)}):null,i.map(n=>{let i=G(t.provider,n.id);return(0,Q.jsxs)(`div`,{className:`prov-inline-row${r&&T===n.id&&U?.provider===t.provider?` prov-inline-row-on`:``}`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-inline-open`,"aria-current":r&&T===n.id&&U?.provider===t.provider,title:n.id,onClick:()=>{w(!1),E(n.id)},children:(0,Q.jsxs)(`span`,{className:`prov-inline-name`,children:[n.name,n.name===n.id?null:(0,Q.jsx)(`em`,{className:`prov-inline-id mono`,children:n.id})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`prov-model-toggle${i?` prov-model-toggle-on`:``}`,role:`switch`,"aria-checked":i,"aria-label":`${i?e(`停用`,`Disable`):e(`启用`,`Enable`)} ${n.name}`,title:i?e(`点击停用`,`Click to disable`):e(`点击启用`,`Click to enable`),onClick:()=>gu(t.provider,!i,n.id),children:(0,Q.jsx)(`span`,{className:`prov-dot`})})]},n.id)})]})]},t.provider)};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`prov-global-bar`,children:[(0,Q.jsx)(`span`,{className:`mono prov-global-path`,children:`~/.pi/agent/settings.json`}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已启用`,`Enabled`),` `,ne,`/`,te]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>gu(`*`,!0),disabled:i.length===0,title:e(`清空 enabledModels 白名单 —— pi 的语义是「不限制」即全部可用`,`Clear the enabledModels allowlist — for pi, no restriction means everything is available`),children:e(`启用全部模型`,`Enable all models`)})]}),(0,Q.jsxs)(`div`,{className:`prov-shell`,style:{"--prov-list-width":`${O}px`},children:[(0,Q.jsxs)(`aside`,{className:`prov-list`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-list-head prov-list-toggle`,"aria-expanded":c,title:c?e(`收起服务商列表`,`Collapse the provider list`):e(`展开服务商列表`,`Expand the provider list`),onClick:()=>l(e=>!e),children:(0,Q.jsxs)(`span`,{className:`prov-list-toggle-label`,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${c?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),e(`服务商`,`Providers`)]})}),(0,Q.jsx)(`div`,{className:`prov-list-body${c?``:` prov-list-body-closed`}`,children:(0,Q.jsxs)(`div`,{className:`prov-list-scroll`,children:[F.length+L.length+R.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`还没有服务商,点下面添加`,`No providers yet — add one below`)}):null,F.map(t=>{let n=B(t.id),r=n?.models??[],i=!b&&u===null&&m===t.id,a=i&&f===t.id;return(0,Q.jsxs)(`div`,{className:`prov-block${i?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${i?` prov-item-on`:``}`,"aria-expanded":r.length>0?a:void 0,title:a?e(`收起模型`,`Collapse models`):e(`选中并展开模型`,`Select and expand models`),onClick:()=>{p(r.length>0&&!a?t.id:null),d(null),x(!1),w(!1),E(null),h(t.id)},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[r.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${a?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,children:t.name}),(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:e(`订阅`,`Sub`)})]}),(0,Q.jsx)(`span`,{className:`prov-item-state${t.connected?` prov-item-state-on`:``}`,children:t.connected?e(`已连接`,`Connected`):t.subscription?e(`订阅额度 · 未连接`,`Subscription quota · not connected`):e(`OAuth · 未连接`,`OAuth · not connected`)})]}),(0,Q.jsx)(wy,{open:a&&r.length>0,children:r.map(r=>{let i=G(t.id,r.id);return(0,Q.jsxs)(`div`,{className:`prov-inline-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-inline-open${T===r.id&&m===t.id?` prov-inline-open-on`:``}`,title:r.id,onClick:()=>{n&&s(n.provider),x(!1),w(!1),E(r.id)},children:(0,Q.jsxs)(`span`,{className:`prov-inline-name`,children:[r.name,r.name===r.id?null:(0,Q.jsx)(`em`,{className:`prov-inline-id mono`,children:r.id})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`prov-model-toggle${i?` prov-model-toggle-on`:``}`,role:`switch`,"aria-checked":i,"aria-label":`${i?e(`停用`,`Disable`):e(`启用`,`Enable`)} ${r.name}`,title:i?e(`点击停用`,`Click to disable`):e(`点击启用`,`Click to enable`),onClick:()=>gu(t.id,!i,r.id),children:(0,Q.jsx)(`span`,{className:`prov-dot`})})]},r.id)})})]},t.id)}),L.map(re),R.map(re)]})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny prov-add`,onClick:()=>{d(e=>e===null?`subscription`:null),x(!1),w(!1),E(null),h(null)},children:[`+ `,e(`添加服务商`,`Add a provider`)]})]}),(0,Q.jsx)(`div`,{className:`prov-resizer`,role:`separator`,"aria-orientation":`vertical`,title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:H,onDoubleClick:()=>k(190)}),(0,Q.jsx)(`section`,{className:`prov-detail${ee?` prov-detail-panel`:``}`,children:u===null?j&&!T&&!S?(0,Q.jsx)(by,{entry:j,enabledModels:i,canTest:B(j.id)!==null,onClose:()=>h(null),onChanged:()=>{A(),uu()},...j.id===`openai-codex`&&j.connected?{onImportModels:()=>{let e=B(j.id);e&&(s(e.provider),w(!0))}}:{}},j.id):T&&U?(0,Q.jsx)(hy,{provider:U,modelId:T,onClose:()=>E(null)},`${U.provider}/${T}`):S&&U?(0,Q.jsx)(cy,{provider:U,onClose:()=>w(!1),onImported:()=>{w(!1),A(),uu()}}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`prov-tabs`,children:[(0,Q.jsx)(`strong`,{className:`prov-detail-title`,children:b?e(`添加服务商`,`Add provider`):e(`配置`,`Config`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),U&&!b?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[K(U),`/`,U.models.length,` `,e(`启用`,`enabled`)]}),(0,Q.jsxs)(`label`,{className:`prov-switch`,title:e(`停用后这个 provider 的模型不再出现在选择器里`,`When disabled, this provider's models no longer appear in the picker`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a(U),onChange:e=>gu(U.provider,e.target.checked)}),(0,Q.jsx)(`span`,{className:`prov-switch-track`,"aria-hidden":`true`})]})]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary prov-save-button`,onClick:()=>D.current?.save(),children:e(`保存`,`Save`)}),U&&!b?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{let t=U.source===`builtin`?e(`(会从 ~/.pi/agent/models.json 里整条删掉)`,` (the entry is removed from ~/.pi/agent/models.json)`):``;window.confirm(e(`删除 provider「${U.provider}」?它的 api key 也会一起删。${t}`,`Delete provider “${U.provider}”? Its API key is deleted too.${t}`))&&(vu(U.provider),s(null))},children:e(`删除`,`Delete`)}):null]}),(0,Q.jsx)(gy,{formRef:D,initial:W?null:U,onSaved:e=>{x(!1),s(e)}},W?`new`:U?.provider)]}):(0,Q.jsx)(Sy,{tab:u,onTab:d,subscriptions:M,catalog:z,onPickSubscription:e=>{d(null),h(e)},onPickBuiltin:e=>{d(null),s(e)},onPickCustom:()=>{d(null),x(!0)}})})]})]})}function wy({open:e,children:t}){return(0,Q.jsx)(`div`,{className:`prov-models-collapse${e?` prov-models-collapse-open`:``}`,"aria-hidden":!e,inert:!e,children:(0,Q.jsx)(`div`,{className:`prov-models-collapse-inner`,children:(0,Q.jsx)(`div`,{className:`prov-models-inline`,children:t})})})}function Ty(){let[e,t]=(0,C.useState)(()=>Ph());return(0,C.useEffect)(()=>Rh(t),[]),{theme:e,setTheme:Lh}}function Ey(e){return[{id:`s`,label:`特小`,labelEn:`Extra small`,px:e-2},{id:`m`,label:`标准`,labelEn:`Default`,px:e},{id:`l`,label:`大`,labelEn:`Large`,px:e+2},{id:`xl`,label:`特大`,labelEn:`Extra large`,px:e+4}]}var Dy={chat:Ey(14),project:Ey(14),session:Ey(14)},Oy={chat:14,project:14,session:14};function ky(e,t=`chat`){return Dy[t].find(t=>t.id===e)??null}function Ay(e,t=`chat`){if(!Number.isFinite(e))return Oy[t];let n=Math.round(Math.min(Math.max(e,2),30)/2)*2;return Math.min(Math.max(n,2),30)}function jy(e,t=`chat`){if(e==null||e===``)return Oy[t];let n=Number(e);if(Number.isFinite(n))return Ay(n,t);let r=ky(e,t);return r?r.px:Oy[t]}function My(e){return`${Ay(e)}px`}function Ny(e,t=`chat`){let n=Ay(e,t);return Dy[t].find(e=>e.px===n)?.id??null}var Py={chat:12,project:13,session:12};function Fy(e){let t=Py[e];return[t-2,t,t+2,t+4]}function Iy(e,t=`chat`){if(!Number.isFinite(e))return Oy[t];let n=Math.min(Math.max(e,2),30),r=Fy(t).indexOf(n);return r>=0?Dy[t][r]?.px??Oy[t]:Ay(n+(Oy[t]-Py[t]),t)}function Ly(e,t=`chat`){let n=Number(e);return Number.isFinite(n)?Iy(n,t):jy(e,t)}var Ry=[{id:`narrow`,label:`窄`,labelEn:`Narrow`,px:720},{id:`normal`,label:`标准`,labelEn:`Default`,px:900},{id:`wide`,label:`宽`,labelEn:`Wide`,px:1100},{id:`full`,label:`满宽`,labelEn:`Full width`,px:0}],zy=Ry.find(e=>e.id===`normal`)?.px??900,By=`pop-agent.chat-font.v2`,Vy=`pop-agent.chat-font`,Hy=`pop-agent.chat-width`,Uy=`pop-agent:chat-display`;function Wy(e){return Ry.find(t=>t.id===e)??null}function Gy(e){return jy(e,`chat`)}function Ky(e){if(typeof localStorage>`u`)return e;try{let t=localStorage.getItem(By);if(t!==null&&t!==``)return Gy(t);let n=localStorage.getItem(Vy);if(n!==null&&n!==``){let e=Ly(n,`chat`);return localStorage.setItem(By,String(e)),e}return e}catch{return e}}function qy(e){if(e===null||e===``)return zy;let t=Wy(e);return t?t.px:/^\d+$/.test(e.trim())?Jy(Number(e)):zy}function Jy(e){if(!Number.isFinite(e)||e<=0)return 0;let t=Math.round((e-360)/20);return 360+Math.max(0,t)*20}function Yy(){let e=e=>360+Math.max(1,Math.floor((e-360)/20))*20,t=()=>{let t=typeof window>`u`?1440:window.innerWidth||1440;return e(Math.max(720,t-320))};if(typeof document>`u`)return t();let n=document.querySelector(`.workspace`);if(!(n instanceof HTMLElement))return t();let r=getComputedStyle(n),i=(parseFloat(r.paddingLeft)||0)+(parseFloat(r.paddingRight)||0),a=n.clientWidth-i;return a>380?e(a):t()}function Xy(e,t){return{size:My(e),maxWidth:t>0?`${t}px`:`100%`}}function Zy(){return Ky(Oy.chat)}function Qy(){return qy(typeof localStorage>`u`?null:localStorage.getItem(Hy))}function $y(e,t){let n=Xy(e,t),r=document.documentElement.style;r.setProperty(`--chat-font-size`,n.size),r.setProperty(`--chat-max-width`,n.maxWidth),document.documentElement.dataset.chatWidth=t>0?`custom`:`full`,window.dispatchEvent(new CustomEvent(Uy,{detail:{font:e,width:t}}))}function eb(){$y(Zy(),Qy())}function tb(e,t){try{localStorage.setItem(e,t)}catch{}}function nb(e){let t=Ay(e,`chat`);tb(By,String(t)),$y(t,Qy())}function rb(e){let t=Jy(e);tb(Hy,String(t)),$y(Zy(),t)}function ib(e){let t=t=>{let n=t.detail;n&&e(n)},n=t=>{if(t.key!==By&&t.key!==Hy)return;let n={font:Zy(),width:Qy()};$y(n.font,n.width),e(n)};return window.addEventListener(Uy,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Uy,t),window.removeEventListener(`storage`,n)}}function ab(){let[e,t]=(0,C.useState)(()=>({font:Zy(),width:Qy()}));return(0,C.useEffect)(()=>ib(t),[]),{font:e.font,width:e.width,setFont:nb,setWidth:rb}}var ob=`pop-agent.appbar-scale.v2`,sb=`pop-agent.appbar-scale`,cb=1.15,lb=[{id:`s`,label:`特小`,labelEn:`Tiny`,percent:60},{id:`m`,label:`紧凑`,labelEn:`Compact`,percent:75},{id:`l`,label:`标准`,labelEn:`Standard`,percent:100},{id:`xl`,label:`特大`,labelEn:`Extra large`,percent:120}];function ub(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,60),120)/5)*5:100}function db(e){if(e==null||e===``)return 100;let t=Number(e);if(Number.isFinite(t))return ub(t);let n=lb.find(t=>t.id===e);return n?n.percent:100}var fb={s:70,m:85,l:100,xl:115};function pb(e){let t=Number(e);return ub((Number.isFinite(t)?t:fb[e]??100)/cb)}function mb(e){let t=ub(e)/100*cb;return String(Math.round(t*1e4)/1e4)}function hb(e){let t=ub(e);return lb.find(e=>e.percent===t)?.id??null}var gb=`pop-agent:appbar-scale`;function _b(){if(typeof localStorage>`u`)return 100;try{let e=localStorage.getItem(ob);if(e!==null&&e!==``)return db(e);let t=localStorage.getItem(sb);if(t===null||t===``)return 100;let n=pb(t);try{localStorage.setItem(ob,String(n))}catch{}return n}catch{return 100}}function vb(){return _b()}function yb(e){let t=ub(e);document.documentElement.style.setProperty(`--appbar-scale`,mb(t)),window.dispatchEvent(new CustomEvent(gb,{detail:t}))}function bb(){yb(_b())}function xb(e){let t=ub(e);try{localStorage.setItem(ob,String(t))}catch{}yb(t)}function Sb(e){let t=t=>{let n=t.detail;typeof n==`number`&&e(n)},n=t=>{if(t.key!==ob)return;let n=_b();yb(n),e(n)};return window.addEventListener(gb,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(gb,t),window.removeEventListener(`storage`,n)}}function Cb(){let[e,t]=(0,C.useState)(vb);return(0,C.useEffect)(()=>Sb(t),[]),{percent:e,setPercent:xb}}var wb=`pop-agent.sidebar-project-font.v2`,Tb=`pop-agent.sidebar-project-font`,Eb=`pop-agent.sidebar-session-font.v2`,Db=`pop-agent.sidebar-session-font`,Ob=`pop-agent:sidebar-font`;function kb(e,t,n){if(typeof localStorage>`u`)return Oy[n];try{let r=localStorage.getItem(e);if(r!==null&&r!==``)return jy(r,n);let i=localStorage.getItem(t);if(i!==null&&i!==``){let t=Ly(i,n);return localStorage.setItem(e,String(t)),t}return Oy[n]}catch{return Oy[n]}}function Ab(){return kb(wb,Tb,`project`)}function jb(){return kb(Eb,Db,`session`)}function Mb(){return{project:Ab(),session:jb()}}function Nb(e){let t=document.documentElement.style;t.setProperty(`--side-project-font-size`,My(e.project)),t.setProperty(`--side-session-font-size`,My(e.session)),window.dispatchEvent(new CustomEvent(Ob,{detail:e}))}function Pb(){Nb(Mb())}function Fb(e,t){try{localStorage.setItem(e,t)}catch{}}function Ib(e){let t=Ay(e,`project`);Fb(wb,String(t)),Nb({project:t,session:jb()})}function Lb(e){let t=Ay(e,`session`);Fb(Eb,String(t)),Nb({project:Ab(),session:t})}function Rb(e){let t=t=>{let n=t.detail;n&&e(n)},n=t=>{if(t.key!==wb&&t.key!==Eb)return;let n=Mb();Nb(n),e(n)};return window.addEventListener(Ob,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Ob,t),window.removeEventListener(`storage`,n)}}function zb(){let[e,t]=(0,C.useState)(Mb);return(0,C.useEffect)(()=>Rb(t),[]),{...e,setProject:Ib,setSession:Lb}}function Bb(){return bp(Sr,Er,wr)}var Vb=192,Hb=8388608,Ub=409600;function Wb(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=new Image;i.onload=()=>{URL.revokeObjectURL(r),t(i)},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(q(`这张图片打不开,换一张 PNG / JPG / WebP 试试`,`This image cannot be opened — try a PNG / JPG / WebP`)))},i.src=r})}async function Gb(e){if(!e.type.startsWith(`image/`))throw Error(q(`这不是图片文件`,`This is not an image file`));if(e.size>Hb)throw Error(q(`图片太大了(请选 8MB 以内的)`,`The image is too big (pick one under 8MB)`));let t=await Wb(e),n=Math.min(t.naturalWidth||t.width,t.naturalHeight||t.height);if(!n)throw Error(q(`这张图片打不开,换一张 PNG / JPG / WebP 试试`,`This image cannot be opened — try a PNG / JPG / WebP`));let r=document.createElement(`canvas`);r.width=Vb,r.height=Vb;let i=r.getContext(`2d`);if(!i)throw Error(q(`这个浏览器画不了图(canvas 不可用)`,`This browser cannot draw images (canvas is unavailable)`));let a=((t.naturalWidth||t.width)-n)/2,o=((t.naturalHeight||t.height)-n)/2;i.imageSmoothingQuality=`high`,i.drawImage(t,a,o,n,n,0,0,Vb,Vb);let s=r.toDataURL(`image/webp`,.92),c=s.startsWith(`data:image/webp`)?s:r.toDataURL(`image/png`);if(c.length>Ub)throw Error(q(`这张图压缩后还是太大,换一张简单点的图试试`,`This image is still too big after compression — try a simpler one`));return c}var Kb=[...Br],qb=`pop-agent.statusbar-order.v1`,Jb=`pop-agent:statusbar-order`,Yb=new Set(Kb);function Xb(e){let t=Array.isArray(e)?e:[],n=[];for(let e of t)typeof e==`string`&&Yb.has(e)&&(n.includes(e)||n.push(e));for(let e of Kb)n.includes(e)||n.push(e);return n}function Zb(){let e=Yr(qb);if(!e)return[...Kb];try{return Xb(JSON.parse(e))}catch{return[...Kb]}}function Qb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function $b(e){let t=Xb(e);return Xr(qb,JSON.stringify(t)),window.dispatchEvent(new CustomEvent(Jb,{detail:t})),t}function ex(e,t,n){let r=Math.max(0,Math.min(t,e.length-1)),i=Math.max(0,Math.min(n,e.length-1));if(r===i)return[...e];let a=[...e],[o]=a.splice(r,1);return o&&a.splice(i,0,o),a}function tx(){let[e,t]=(0,C.useState)(()=>Zb());return(0,C.useEffect)(()=>{let e=e=>{let n=Xb(e);t(e=>Qb(e,n)?e:n)},n=t=>e(t.detail),r=t=>{if(t.key===null||t.key===qb){if(t.key===null)e(null);else try{e(t.newValue?JSON.parse(t.newValue):null)}catch{e(null)}}};return window.addEventListener(Jb,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(Jb,n),window.removeEventListener(`storage`,r)}},[]),[e,e=>t($b(e))]}function nx({name:e}){let t={viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0};return e===`models`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`2.8`,y:`5.4`,width:`10.4`,height:`7.6`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.4V3.4`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.6`,r:`0.85`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`9.2`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`9.2`,r:`0.8`,fill:`currentColor`,stroke:`none`})]}):e===`skills`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`5.9`,width:`11.6`,height:`7.4`,rx:`1.7`}),(0,Q.jsx)(`path`,{d:`M6.1 5.9V4.3c0-.6.5-1.1 1.1-1.1h1.6c.6 0 1.1.5 1.1 1.1v1.6`}),(0,Q.jsx)(`path`,{d:`M2.2 9.3h11.6`})]}):e===`push`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`path`,{d:`M4.3 11.1V7.7a3.7 3.7 0 1 1 7.4 0v3.4l1.1 1.5H3.2l1.1-1.5Z`}),(0,Q.jsx)(`path`,{d:`M6.5 14.1a1.6 1.6 0 0 0 3 0`})]}):e===`plugins`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`4.2`,y:`6.6`,width:`7.6`,height:`6.2`,rx:`1.6`}),(0,Q.jsx)(`path`,{d:`M6.2 6.6V3.9M9.8 6.6V3.9`}),(0,Q.jsx)(`path`,{d:`M8 12.8v1.6`})]}):e===`voice`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`6.2`,y:`2.2`,width:`3.6`,height:`6.6`,rx:`1.8`}),(0,Q.jsx)(`path`,{d:`M4.4 8.2a3.6 3.6 0 0 0 7.2 0`}),(0,Q.jsx)(`path`,{d:`M8 11.8v2`}),(0,Q.jsx)(`path`,{d:`M12.6 4.2a4.4 4.4 0 0 1 0 4.6M3.4 4.2a4.4 4.4 0 0 0 0 4.6`})]}):e===`agents`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`5.6`,width:`9.6`,height:`7.4`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.6V3.3`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.5`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.6`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.6`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M6.2 10.9h3.6`})]}):e===`computer`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`1.8`,y:`2.6`,width:`12.4`,height:`8.6`,rx:`1.3`}),(0,Q.jsx)(`path`,{d:`M5.6 13.6h4.8M8 11.2v2.4`})]}):e===`cron`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.8`}),(0,Q.jsx)(`path`,{d:`M8 4.5V8l2.5 1.5`})]}):e===`mcp`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`1.9`,y:`3.2`,width:`8.6`,height:`3.9`,rx:`1.1`}),(0,Q.jsx)(`rect`,{x:`1.9`,y:`8.9`,width:`8.6`,height:`3.9`,rx:`1.1`}),(0,Q.jsx)(`circle`,{cx:`4`,cy:`5.15`,r:`0.6`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`4`,cy:`10.85`,r:`0.6`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M10.5 5.15h1.4a1.2 1.2 0 0 1 1.2 1.2v3.3a1.2 1.2 0 0 0 1.2 1.2H15`})]}):(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`path`,{d:`M2.6 5.4h10.8M2.6 10.6h10.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`5.4`,r:`1.7`,fill:`var(--bg-elev)`}),(0,Q.jsx)(`circle`,{cx:`10.2`,cy:`10.6`,r:`1.7`,fill:`var(--bg-elev)`})]})}var rx=[`ui`,`general`,`appearance`,`theme`,`language`,`shortcuts`,`remote`],ix=`pop-agent.settings-tab-order.v1`,ax=`pop-agent:settings-tab-order`,ox=new Set(rx);function sx(e){let t=Array.isArray(e)?e:[],n=[];for(let e of t)typeof e==`string`&&ox.has(e)&&(n.includes(e)||n.push(e));for(let e of rx)n.includes(e)||n.push(e);return n}function cx(e){if(!e)return[...rx];try{return sx(JSON.parse(e))}catch{return[...rx]}}function lx(){return cx(Yr(ix))}function ux(e){let t=sx(e);return Xr(ix,JSON.stringify(t)),typeof window<`u`&&window.dispatchEvent(new CustomEvent(ax,{detail:t})),t}function dx(){return lx()[0]??rx[0]}function fx(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function px(e,t,n){let r=Math.max(0,Math.min(t,e.length-1)),i=Math.max(0,Math.min(n,e.length-1));if(r===i)return[...e];let a=[...e],[o]=a.splice(r,1);return o&&a.splice(i,0,o),a}function mx(e,t,n){let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(Math.round(n),r.length)),a=[...r];return a.splice(i,0,t),a}function hx(e,t,n,r){let i=e.indexOf(t),a=0;for(let t=0;t<e.length;t+=1){if(t===i)continue;let e=r[t];e&&n>e.left+e.width/2&&(a+=1)}return a}function gx(e,t,n){let r=new Map;for(let i of e){let e=t.indexOf(i),a=n[e];e<0||!a||r.set(i,a.left)}return r}function _x(){let[e,t]=(0,C.useState)(()=>lx());return(0,C.useEffect)(()=>{let e=e=>{let n=sx(e);t(e=>fx(e,n)?e:n)},n=t=>e(t.detail),r=t=>{(t.key===null||t.key===ix)&&e(cx(t.newValue))};return window.addEventListener(ax,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(ax,n),window.removeEventListener(`storage`,r)}},[]),[e,(0,C.useCallback)(e=>{let n=ux(e);t(e=>fx(e,n)?e:n)},[])]}var vx=5,yx=350,bx=`is-tab-sort-dragging`;function xx({order:e,active:t,label:n,onSelect:r,onOrderChange:i}){let a=(0,C.useRef)(null),o=(0,C.useRef)(null),[s,c]=(0,C.useState)(null),l=(0,C.useRef)(null),u=(0,C.useRef)(!1),d=(0,C.useRef)(null),f=e=>{l.current=e,c(e),e?document.documentElement.classList.add(bx):document.documentElement.classList.remove(bx)};(0,C.useEffect)(()=>()=>{document.documentElement.classList.remove(bx),d.current!==null&&window.clearTimeout(d.current)},[]);let p=()=>{let t=a.current;if(!t)return null;let n=[];for(let r of e){let e=t.querySelector(`[data-settings-tab="${r}"]`);if(!e)return null;let i=e.getBoundingClientRect();n.push({left:i.left,width:i.width})}return n},m=(e,t)=>{try{e?.hasPointerCapture(t)&&e.releasePointerCapture(t)}catch{}},h=(e,t)=>{if(!(e.button!==0||l.current)&&!Tf()){o.current={pointerId:e.pointerId,id:t,startX:e.clientX,startY:e.clientY};try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}}},g=t=>{let n=o.current;if(!n||n.pointerId!==t.pointerId)return;let r=t.clientX-n.startX,i=t.clientY-n.startY,a=l.current;if(!a){if(Math.max(Math.abs(r),Math.abs(i))<vx)return;if(Math.abs(i)>Math.abs(r)){o.current=null,m(t.currentTarget,t.pointerId);return}let a=p(),s=e.indexOf(n.id);if(!a||s<0){o.current=null;return}t.preventDefault(),f({id:n.id,fromIndex:s,slots:a,toIndex:s,dx:r});return}t.preventDefault();let s=a.slots[a.fromIndex];if(!s)return;let c=s.left+s.width/2+r;f({...a,dx:r,toIndex:hx(e,a.id,c,a.slots)})},_=t=>{let n=l.current;o.current=null,n&&(f(null),u.current=!0,d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{u.current=!1},yx),t&&i(mx(e,n.id,n.toIndex)))},v=e=>{o.current?.pointerId===e.pointerId&&(m(e.currentTarget,e.pointerId),_(!0))},y=e=>{o.current?.pointerId===e.pointerId&&(m(e.currentTarget,e.pointerId),_(!1))},b=t=>{let n=t.key===`ArrowRight`?1:t.key===`ArrowLeft`?-1:0;if(!n)return;let o=t.target.closest(`[data-settings-tab]`)?.dataset.settingsTab,s=o?e.indexOf(o):-1;if(s<0)return;if(t.preventDefault(),t.altKey){let t=s+n;if(t<0||t>e.length-1)return;i(px(e,s,t));return}let c=e[(s+n+e.length)%e.length];c&&(r(c),a.current?.querySelector(`[data-settings-tab="${c}"]`)?.focus())},x=s?mx(e,s.id,s.toIndex):e,S=s?gx(e,x,s.slots):null,w=t=>{if(!s||!S)return 0;if(t===s.id)return s.dx;let n=s.slots[e.indexOf(t)]?.left,r=S.get(t);return n===void 0||r===void 0?0:r-n};return(0,Q.jsx)(`div`,{ref:a,className:`settings-tabs`,role:`tablist`,onKeyDown:b,children:e.map(e=>{let i=s?.id===e,a=[`settings-tab`,t===e?`settings-tab-on`:``,s?`settings-tab-reordering`:``,i?`settings-tab-dragging`:``].filter(Boolean).join(` `),o=w(e);return(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"data-settings-tab":e,"aria-selected":t===e,tabIndex:t===e?0:-1,className:a,draggable:!1,style:s?{transform:`translate3d(${o}px, 0, 0)`,transition:i?`none`:void 0}:void 0,onPointerDown:t=>h(t,e),onPointerMove:g,onPointerUp:v,onPointerCancel:y,onClick:()=>{u.current||r(e)},children:n(e)},e)})})}var Sx={maxFailures:3,lockMinutes:30};function Cx(e){return{maxFailures:typeof e?.maxFailures==`number`?e.maxFailures:Sx.maxFailures,lockMinutes:typeof e?.lockMinutes==`number`?e.lockMinutes:Sx.lockMinutes}}async function wx(e){try{let t=await e.json();return typeof t==`object`&&t?t:null}catch{return null}}function Tx(e,t){return typeof e?.error==`string`&&e.error!==``?e.error:q(`请求失败(HTTP ${t})`,`Request failed (HTTP ${t})`)}async function Ex(){try{let e=await fetch(`/api/auth/password`,{cache:`no-store`,credentials:`same-origin`}),t=await wx(e);return!e.ok||t?.ok!==!0?{ok:!1,error:Tx(t,e.status)}:{ok:!0,set:t.set===!0,guard:Cx(t)}}catch{return{ok:!1,error:q(`网络异常,请重试`,`Network error — try again`)}}}async function Dx(e,t){try{let n=await fetch(`/api/auth/password`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t===void 0?{password:e}:{password:e,currentPassword:t}),cache:`no-store`,credentials:`same-origin`}),r=await wx(n);return!n.ok||r?.ok!==!0?{ok:!1,error:Tx(r,n.status)}:{ok:!0}}catch{return{ok:!1,error:q(`网络异常,请重试`,`Network error — try again`)}}}async function Ox(){try{let e=await fetch(`/api/auth/activity`,{cache:`no-store`,credentials:`same-origin`}),t=await wx(e);if(!e.ok||t?.ok!==!0)return{ok:!1,error:Tx(t,e.status)};let n=Array.isArray(t.entries)?t.entries:[],r=[];for(let e of n){if(typeof e!=`object`||!e)continue;let t=e,n=t.kind;(n===`success`||n===`failure`||n===`locked`)&&typeof t.at==`number`&&typeof t.address==`string`&&r.push({at:t.at,address:t.address,kind:n,...typeof t.attempts==`number`?{attempts:t.attempts}:{},...typeof t.lockMinutes==`number`?{lockMinutes:t.lockMinutes}:{}})}return{ok:!0,entries:r}}catch{return{ok:!1,error:q(`网络异常,请重试`,`Network error — try again`)}}}async function kx(e){try{let t=await fetch(`/api/auth/guard`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),cache:`no-store`,credentials:`same-origin`}),n=await wx(t);return!t.ok||n?.ok!==!0?{ok:!1,error:Tx(n,t.status)}:{ok:!0,guard:Cx(n)}}catch{return{ok:!1,error:q(`网络异常,请重试`,`Network error — try again`)}}}function Ax(){let e=J(),[t,n]=xc(),r=oc(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null);return(0,C.useEffect)(()=>{if(!i)return;let o=null,c=o=>{if(Gs(o)){s(e(`「${cc(o,r)}」会被浏览器先吃掉(比如开关标签页/窗口),换个组合`,`${cc(o,r)} is reserved by the browser — pick another combo`));return}let c=ic(t,o,i);if(c){let t=ac(c);s(e(`「${cc(o,r)}」已经给「${t.zh}」了,先把它清掉或换一个`,`${cc(o,r)} is already used by “${t.en}” — clear it or pick another`))}else n({...t,[i]:o}),a(null),s(null)},l=e=>{if(zs(e),e.preventDefault(),e.stopPropagation(),e.key===`Escape`&&!e.metaKey&&!e.ctrlKey&&!e.altKey){a(null),s(null),o=null;return}if(qs(e)){o=e.code??``;return}o=null;let t=Hs(e);t&&c(t)},u=e=>{if(zs(e),o===null||(e.code??``)!==o)return;o=null,e.preventDefault(),e.stopPropagation();let t=Js(e);t&&c(t)},d=e=>{e.target?.closest?.(`.shortcut-row`)||a(null)};return window.addEventListener(`keydown`,l,!0),window.addEventListener(`keyup`,u,!0),window.addEventListener(`pointerdown`,d,!0),()=>{window.removeEventListener(`keydown`,l,!0),window.removeEventListener(`keyup`,u,!0),window.removeEventListener(`pointerdown`,d,!0)}},[i,t,n,r,e]),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`快捷键`,`Shortcuts`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:r?e("macOS:Mod = ⌘;想要真正的 ⌃ 就录 ⌃ + 非字母键(如 ⌃`)","macOS: Mod = ⌘; for a real ⌃ combo record ⌃ plus a non-letter key (e.g. ⌃`)"):e(`这里写 Ctrl 的地方,macOS 上是 ⌘`,`Where it says Ctrl, macOS uses ⌘`)})]}),(0,Q.jsx)(`div`,{className:`shortcuts-list`,children:ws.map(o=>{let c=t[o.id],l=i===o.id;return(0,Q.jsxs)(`div`,{className:`shortcut-row${l?` shortcut-row-rec`:``}`,children:[(0,Q.jsxs)(`div`,{className:`shortcut-info`,children:[(0,Q.jsx)(`span`,{className:`shortcut-name`,children:e(o.label,o.labelEn)}),o.hint?(0,Q.jsx)(`span`,{className:`shortcut-hint`,children:e(o.hint,o.hintEn??o.hint)}):null]}),(0,Q.jsxs)(`div`,{className:`shortcut-keys`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-combo${l?` shortcut-combo-rec`:``}${c?``:` shortcut-combo-empty`}`,"aria-label":e(`${o.label} 的快捷键`,`${o.labelEn} shortcut`),onClick:()=>{s(null),a(l?null:o.id)},title:l?e(`按 Esc 取消`,`Press Esc to cancel`):e(`点一下,然后按新的组合键(也可以只按一颗修饰键 / F1–F12)`,`Click, then press a combo (or a single modifier / F1–F12)`),children:l?e(`按下组合键 / 单键…`,`Press a combo or a single key…`):c?cc(c,r):e(`未设置`,`Unbound`)}),(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-clear`,disabled:!c,onClick:()=>{a(null),s(null),n({...t,[o.id]:null})},title:e(`清除这个快捷键(不设置)`,`Clear this shortcut (unbound)`),"aria-label":e(`清除「${o.label}」的快捷键`,`Clear ${o.labelEn} shortcut`),children:`✕`})]})]},o.id)})}),o?(0,Q.jsx)(`div`,{className:`shortcut-notice`,role:`status`,children:o}):null,(0,Q.jsxs)(`div`,{className:`shortcut-foot`,children:[(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`组合键要带 ⌘/Ctrl 或 Alt。也可以绑单键:单独一颗修饰键(右⌘ / 右⌥ / ⌃ / Alt)或功能键 F1–F12;裸字母、数字不行(在输入框里打字就会触发动作)。同一组合只能给一个动作。`,`Combos need ⌘/Ctrl or Alt. Single keys are allowed too: one modifier alone (right ⌘ / right ⌥ / ⌃ / Alt) or a function key F1–F12; bare letters and digits are not (typing would trigger actions). Each combo belongs to one action.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>gc(),title:e(`浮层列出当前所有绑定(也可以按 ⌘/ 打开)`,`Lists every binding in an overlay (⌘/ works too)`),children:e(`打开速查表`,`Open cheat sheet`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{a(null),s(null),n(Xs())},children:e(`恢复默认设置`,`Restore defaults`)})]})]})}var jx=`/favicon.svg?v=9`;function Mx(){let[e,t]=(0,C.useState)(dx),[n,r]=_x(),i=J(),a={ui:i(`界面`,`Interface`),general:i(`对话`,`Chat`),appearance:i(`外观`,`Appearance`),theme:i(`主题`,`Theme`),language:i(`语言`,`Language`),shortcuts:i(`快捷键`,`Shortcuts`),remote:i(`远程`,`Remote`)},o=n.includes(e)?e:n[0]??`ui`;return(0,Q.jsxs)(`div`,{className:`settings-stack`,children:[(0,Q.jsx)(xx,{order:n,active:o,label:e=>a[e],onSelect:e=>t(e),onOrderChange:r}),o===`general`?(0,Q.jsx)(Ix,{}):o===`appearance`?(0,Q.jsx)($x,{}):o===`theme`?(0,Q.jsx)(eS,{}):o===`language`?(0,Q.jsx)(Fx,{}):o===`shortcuts`?(0,Q.jsx)(Ax,{}):o===`remote`?(0,Q.jsx)(Px,{}):(0,Q.jsx)(zx,{})]})}function Nx(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Px(){let e=J(),t=Jc(),n=typeof location>`u`?``:location.host,[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(Sx),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)([]),[y,b]=(0,C.useState)(``),[x,S]=(0,C.useState)(!1),w=(0,C.useCallback)(()=>{S(!0),Ox().then(e=>{S(!1),e.ok?(b(``),v(e.entries)):b(e.error)})},[]);(0,C.useEffect)(()=>{w()},[w]),(0,C.useEffect)(()=>{Ex().then(e=>{e.ok?(i(e.set),m(e.guard),o(``)):o(e.error)})},[t]);let T=()=>{g(!0),kx(p).then(t=>{g(!1),t.ok?(m(t.guard),Z({text:e(`已保存:连续错 ${t.guard.maxFailures} 次,暂停 ${t.guard.lockMinutes} 分钟`,`Saved: pause ${t.guard.lockMinutes} min after ${t.guard.maxFailures} wrong tries`)})):Z({text:t.error})})},E=()=>{let n=s.trim();n.length<4?Z({text:e(`密码至少 4 位`,`Use at least 4 characters`)}):t&&r&&l===``?Z({text:e(`先输入当前密码`,`Enter the current password first`)}):(f(!0),Dx(n,t?l:void 0).then(t=>{f(!1),t.ok?(i(!0),o(``),c(``),u(``),Z({text:e(`访问密码已保存,立即生效`,`Password saved — active now`)})):Z({text:t.error})}))},D=r===null?a===``?e(`读取中…`,`Loading…`):a:r?e(`已设置`,`Set`):e(`未设置`,`Not set`);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`访问方式`,`Access`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:t?e(`通过 ${n} 远程访问`,`Remote — ${n}`):e(`本机访问(免密)`,`This machine (no password)`)})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:t?e(`远程访问必须输密码;域名 / 外网 IP / 局域网 IP 都能访问。这里改密码要先输入当前密码,登录保护与登录活动也在这里查看(活动里的 IP 已打码)。`,`Remote access always needs the password. Changing it here needs the current password. Login protection and login activity are here too (IPs in the activity list are masked).`):e(`本机直连(127.0.0.1)不需要密码。设一个之后,远程用任意域名 / 局域网 IP / 隧道地址打开都要先输它。`,`The local address (127.0.0.1) needs no password. Once set, any remote address — domain, LAN IP or tunnel — will ask for it.`)}),t?(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>Yc(),children:e(`退出登录`,`Sign out`)}),(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`清掉这台浏览器上的登录 cookie(有效期 7 天,每次访问顺延)。`,`Clears the login cookie in this browser (valid 7 days, renewed on every visit).`)})]}):null,(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`访问密码`,`Password`)}),t&&r?(0,Q.jsx)(`input`,{className:`settings-input settings-password-input`,type:`password`,value:l,autoComplete:`current-password`,placeholder:e(`当前密码`,`Current password`),"aria-label":e(`当前密码`,`Current password`),onChange:e=>u(e.target.value)}):null,(0,Q.jsx)(`input`,{className:`settings-input settings-password-input`,type:`password`,value:s,autoComplete:`new-password`,placeholder:r?e(`输入新密码以修改(至少 4 位)`,`New password to change it (min 4)`):e(`设置访问密码(至少 4 位)`,`Set a password (min 4)`),onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!d&&E()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:E,disabled:d||s.trim()===``,children:d?e(`保存中…`,`Saving…`):e(`保存`,`Save`)}),(0,Q.jsxs)(`span`,{className:`settings-hint`,children:[e(`当前:`,`Now: `),D]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`密码存在数据目录的 password 文件里(默认 ~/.pop-agent/password),保存后立即生效,不用重启。忘了就删掉这个文件再重启,或者启动时带 pop -P <新密码>(也会写进去)。`,`Stored in the data directory's password file (default ~/.pop-agent/password). It applies immediately — no restart. Forgot it? Delete that file and restart, or start with pop -P <new password> (that is saved too).`)}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`登录保护`,`Login protection`)}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`连续错`,`After`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:20,value:p.maxFailures,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&m(e=>({...e,maxFailures:Math.min(20,Math.max(1,Math.round(t)))}))}}),(0,Q.jsx)(`span`,{children:e(`次后,暂停`,`wrong tries, pause for`)})]}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:1440,value:p.lockMinutes,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&m(e=>({...e,lockMinutes:Math.min(1440,Math.max(1,Math.round(t)))}))}}),(0,Q.jsx)(`span`,{children:e(`分钟`,`minutes`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:T,disabled:h,children:h?e(`保存中…`,`Saving…`):e(`保存`,`Save`)})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`同一个来源连续输错密码到达这个次数,就暂停一段时间,不再比对密码(挡在线爆破)。默认 3 次 / 30 分钟;锁会落盘,重启服务也不会放行。填 1–20 次、1–1440 分钟。`,`After this many wrong passwords from the same source, sign-in is paused for a while (anti-brute-force). Default: 3 tries / 30 minutes. Locks are persisted across restarts. Range: 1–20 tries, 1–1440 minutes.`)}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`登录活动`,`Login activity`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:w,disabled:x,children:x?e(`刷新中…`,`Refreshing…`):e(`刷新`,`Refresh`)}),(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`最近 200 条,最新的在最前面。`,`Latest 200 events, newest first.`)})]}),y===``?null:(0,Q.jsx)(`div`,{className:`settings-hint`,children:y}),(0,Q.jsx)(`div`,{className:`settings-activity`,children:_.length===0?(0,Q.jsx)(`div`,{className:`settings-hint`,children:x?e(`读取中…`,`Loading…`):e(`还没有登录记录。`,`No sign-in activity yet.`)}):_.map(t=>(0,Q.jsxs)(`div`,{className:`settings-activity-row settings-activity-${t.kind}`,children:[(0,Q.jsx)(`span`,{className:`settings-activity-time`,children:Nx(t.at)}),(0,Q.jsx)(`span`,{className:`settings-activity-ip`,children:t.address}),(0,Q.jsx)(`span`,{className:`settings-activity-kind`,children:t.kind===`success`?e(`登录成功`,`Signed in`):t.kind===`locked`?e(`连续错 ${t.attempts??0} 次,已暂停 ${t.lockMinutes??0} 分钟`,`${t.attempts??0} wrong tries — paused ${t.lockMinutes??0} min`):e(`密码错误(连续第 ${t.attempts??1} 次)`,`Wrong password (try ${t.attempts??1})`)})]},`${t.at}-${t.address}-${t.kind}`))})]})]})}function Fx(){let e=J(),{language:t,setLanguage:n}=je();return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`语言`,`Language`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`界面文字用哪种语言`,`Which language the interface uses`)})]}),(0,Q.jsx)(`div`,{className:`settings-langs`,children:ge.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${t===r.id?` settings-lang-on`:``}`,title:r.label,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-language`,value:r.id,checked:t===r.id,onChange:()=>n(r.id)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:r.label}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.id===`en`?e(`默认`,`Default`):e(`浏览器是中文时默认`,`Default when your browser is Chinese`)})]},r.id))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;默认英文,浏览器语言是中文的首次打开用中文。`,`Takes effect immediately, nothing to save. The choice is stored on this machine (localStorage) and survives reloads; it does not touch the server or your other devices. English is the default — a Chinese browser gets Chinese on first launch.`)})]})})}function Ix(){let e=J(),t=Ro(e=>e.snapshot),n=t?.settings.thinkCount??5,r=t?.settings.thinkTimeoutSec??20,[i,a]=(0,C.useState)({count:n,timeoutSec:r}),[o,s]=(0,C.useState)(!1);return(0,C.useEffect)(()=>{o||a({count:n,timeoutSec:r})},[n,r,o]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Kx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`想想`,`Think`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`下一步建议`,`Next-step suggestions`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny settings-head-action`,onClick:()=>{bu({thinkCount:i.count,thinkTimeoutSec:i.timeoutSec}),s(!1)},disabled:!o,children:e(`保存`,`Save`)})]}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`一次生成`,`Generate`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:5,value:i.count,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&(a(e=>({...e,count:Math.min(5,Math.max(1,Math.round(t)))})),s(!0))}}),(0,Q.jsx)(`span`,{children:e(`条`,`items`)})]}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`最多等`,`Wait up to`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:5,max:180,step:5,value:i.timeoutSec,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&(a(e=>({...e,timeoutSec:Math.min(180,Math.max(5,Math.round(t)))})),s(!0))}}),(0,Q.jsx)(`span`,{children:e(`秒`,`s`)})]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`「想想」用一次隐藏回合让模型出建议(不进对话)。超过这个时间还没出结果就中断,可以再点一次。`,`Think runs a hidden turn to get suggestions (it never enters the conversation). If it takes longer than this, the turn is aborted and you can click again.`)})]}),(0,Q.jsx)(Lx,{}),(0,Q.jsx)(Rx,{})]})}function Lx(){let e=J(),[t,n]=uf(pr,!0);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`标注`,`Annotations`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`选中文字后浮出的小工具栏`,`The toolbar that pops up on text selection`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>n(e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:`✍️`}),e(`开启选中标注`,`Enable selection annotations`)]})}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`打开时,在对话里选中一段文字会浮出「添加到会话 / 标注 / 在临时会话中提问」;关掉后选字就只是选字(复制、搜索都不受打扰)。已标好的内容照旧显示。只存本机,手机和桌面各记各的。`,`On: selecting text in the conversation shows Add to session / Annotate / Ask in the side chat. Off: selecting text is just selecting (copying stays unobstructed). Existing annotations are kept. Stored per device.`)})]})}function Rx(){let e=J(),[t,n]=uf(cr,!1),[r,i]=uf(ur,!1),[a,o]=uf(dr,!0),[s,c]=uf(fr,!0);return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`过程`,`Process`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`思考块 + 工具卡`,`Thinking blocks + tool cards`)})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked)}),e(`会话过程折叠`,`Collapse session process`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),e(`会话完成折叠`,`Collapse when the session completes`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!t,onChange:e=>n(!e.target.checked)}),e(`会话思考折叠`,`Collapse thinking blocks`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!r,onChange:e=>i(!e.target.checked)}),e(`会话工具折叠`,`Collapse tool cards`)]})]})})}function zx(){let e=J();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(qx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏高度`,`Top bar size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`整条顶栏连同里面的按钮 / 图标一起缩放(100% = 标准大小,也就是默认值)`,`Scales the whole top bar, its buttons and icons (100% = the standard size, also the default)`)})]}),(0,Q.jsx)(Xx,{})]}),(0,Q.jsx)(Hx,{}),(0,Q.jsx)(Ux,{}),(0,Q.jsx)(Wx,{}),(0,Q.jsx)(Gx,{})]})}var Bx=[{value:320,label:`小`,labelEn:`S`},{value:400,label:`中`,labelEn:`M`},{value:520,label:`大`,labelEn:`L`},{value:720,label:`特大`,labelEn:`XL`},{value:0,label:`原尺寸`,labelEn:`Natural`}];function Vx(){let e=J(),[t,n]=Eh(Jr,400,0,4e3);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`图片`,`Images`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`对话里图片的最大显示宽度`,`Max width of images in the chat`)})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-5 settings-langs-compact`,children:Bx.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${t===r.value?` settings-lang-on`:``}`,title:r.value>0?`${r.value}px`:e(`不额外收窄,按图片本身大小`,`No extra cap`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-chat-image-width`,value:r.value,checked:t===r.value,onChange:()=>n(r.value)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:e(r.label,r.labelEn)}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.value>0?`${r.value}px`:e(`不设上限`,`No cap`)})]},r.value))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`截图先按设备像素比折回真实大小,再套这个上限;点图仍可看原图。改完立刻生效,不用保存。`,`Screenshots are first scaled back to their real size, then capped by this width. Click an image for the original. Applies immediately, nothing to save.`)})]})}function Hx(){let e=J(),[t,n]=Eh(qr,10,1,50);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`左侧栏`,`Left sidebar`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`每个项目摆多少会话`,`Sessions per project`)})]}),(0,Q.jsx)(`div`,{className:`settings-row`,children:(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`每个项目显示`,`Show`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:50,value:t,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&n(t)}}),(0,Q.jsx)(`span`,{children:e(`条`,`sessions`)})]})}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`默认 10 条,范围 1–50。超出的折成一行「还有 N 个…」,点一下全展开。改完立刻生效,不用保存。`,`Default 10, range 1–50. The rest collapse into one “and N more…” row that expands on click. Applies immediately, nothing to save.`)})]})}function Ux(){let e=J(),[t,n]=Bb(),[r,i]=uf(Nr,!1);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏`,`Top bar`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`那一排入口显示哪些`,`Which entries that row shows`)})]}),(0,Q.jsxs)(`div`,{className:`settings-checks`,children:[Sr.map(r=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[r],onChange:e=>n(r,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:r})}),e(jr[r],Mr[r])]},r)),(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>i(e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:`💬`}),e(`临时会话`,`Temp session`)]})]})]})}function Wx(){let e=J(),[t,n]=bp(Dr,Or),r={label:e(`文`,`T`),icon:e(`图`,`▣`)};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏文字与图标`,`Top bar labels & icons`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`每个入口显示什么`,`What each entry shows`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:Dr.map(i=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[i],onChange:e=>n(i,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:r[i]}),e(kr[i],Ar[i])]},i))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`只影响顶栏那一排。两个都不勾时仍然画图标 —— 一排看不见的按钮就等于把入口弄丢了。`,`Top bar row only. With both off the icon still shows: a row of invisible buttons would just lose the entries.`)})]})}function Gx(){let e=J(),[t,n]=bp(Br,Wr,Hr),[r,i]=tx(),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),l={settings:`⚙️`,approval:`🔓`,engine:`◉`,queued:`⏳`,running:`◌`,context:`◔`,history:`📜`,prompt:`🧾`,terminal:`🖥️`,top:`⬆️`};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`底部`,`Bottom`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`显隐与从左到右的顺序`,`Visibility and left-to-right order`)})]}),(0,Q.jsx)(`div`,{className:`statusbar-settings-list`,children:r.map(u=>(0,Q.jsxs)(`div`,{className:`statusbar-setting-row${a===u?` is-dragging`:``}${s===u&&a!==u?` is-drag-over`:``}`,draggable:!0,onDragStart:e=>{o(u),c(null),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,u)},onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,a!==u&&c(u)},onDragLeave:()=>{s===u&&c(null)},onDrop:e=>{e.preventDefault();let t=e.dataTransfer.getData(`text/plain`),n=r.indexOf(t),a=r.indexOf(u);n>=0&&a>=0&&i(ex(r,n,a)),o(null),c(null)},onDragEnd:()=>{o(null),c(null)},children:[(0,Q.jsx)(`span`,{className:`statusbar-setting-grip`,"aria-hidden":`true`,children:`⠿`}),(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u===`settings`||t[u],disabled:u===`settings`,onChange:e=>n(u,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:l[u]}),e(Gr[u],Kr[u])]})]},u))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`拖动左侧的点状把手可以改变状态栏从左到右的顺序;取消勾选即可隐藏对应项目。「设置」始终保留,避免把自己关掉后找不回来。`,`Drag the dotted handle to change the left-to-right order. Uncheck an item to hide it. Settings always stays available so you cannot lock yourself out.`)})]})}function Kx(){let e=J(),[t,n]=bp(Pr,Lr,Ir),r={model:`▣`,thinking:`⚡`,templates:`✏️`,think:`💡`,quick:`💬`};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`对话窗口`,`Composer`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`输入框上方那一排`,`The row above the input`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:Pr.map(i=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[i],onChange:e=>n(i,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:r[i]}),e(Rr[i],zr[i])]},i))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`这三块都只存本机 —— 手机、平板、桌面各一份,同一条设置在不同设备上可以不一样。快捷指令的短语内容在本页「快捷短语」里改(那份是多设备一致的),这里只管要不要在输入框上方显示。`,`These three are stored per device — phone, tablet and desktop can differ. The phrase text itself is edited under Quick phrases on this page (shared across devices); this only controls whether the row is shown.`)})]})}function qx(){let e=J(),{shown:t,logo:n,logoShown:r,setShown:i,setLogo:a,setLogoShown:o}=Zv(),s=(0,C.useRef)(null);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏名称`,`Top-bar name`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`顶栏那个 logo 和它后面那串名字`,`The logo in the top bar and the name after it`)})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>o(e.target.checked)}),e(`在顶栏显示 logo`,`Show the logo in the top bar`)]}),(0,Q.jsxs)(`div`,{className:`brand-logo-row`,children:[(0,Q.jsx)(`img`,{className:`brand-logo-preview`,src:n||jx,alt:``,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s.current?.click(),title:e(`选一张图片当顶栏 logo(会缩到 192px 存在本机)`,`Pick an image as the top-bar logo (scaled to 192px, stored on this device)`),children:e(`更换 logo`,`Change logo`)}),n?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>a(``),children:e(`用回默认 logo`,`Use default logo`)}):null,(0,Q.jsx)(`input`,{ref:s,className:`brand-logo-file`,type:`file`,accept:`image/*`,"aria-label":e(`选择 logo 图片`,`Choose a logo image`),onChange:t=>{let n=t.target.files?.[0];t.target.value=``,n&&Gb(n).then(e=>a(e)).catch(t=>{Z({text:t instanceof Error?t.message:e(`这张图用不了`,`That image did not work`)})})}})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>i(e.target.checked)}),e(`在顶栏显示名称`,`Show the name in the top bar`)]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`顶栏显示的就是产品名,不再支持自定义改名。`,`The top bar shows the product name; custom renaming is no longer available.`)})]})}function Jx({name:e,layer:t,value:n,onChange:r}){let i=J(),a=Ny(n,t),o=Dy[t];return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:i(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:e,type:`range`,min:2,max:30,step:2,value:n,"aria-label":i(`字号(2–30 像素)`,`Font size (2–30 px)`),"aria-valuetext":`${n}px`,onChange:e=>r(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[2,`px`]}),(0,Q.jsxs)(`span`,{children:[30,`px`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[n,`px`]})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:o.map(t=>(0,Q.jsxs)(`label`,{className:`settings-lang${a===t.id?` settings-lang-on`:``}`,title:i(`一键设为 ${t.px}px`,`Set to ${t.px}px`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`${e}-preset`,value:t.id,checked:a===t.id,onChange:()=>r(t.px)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,style:{fontSize:`${t.px}px`},children:i(t.label,t.labelEn)}),(0,Q.jsxs)(`span`,{className:`settings-lang-hint`,children:[t.px,`px`]})]},t.id))})]})}function Yx({value:e,onChange:t}){let n=J(),[r,i]=(0,C.useState)(Yy);(0,C.useEffect)(()=>{i(Yy())},[]);let a=e<=0||e>=r,o=a?r:e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:n(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-chat-width`,type:`range`,min:360,max:r,step:20,value:o,"aria-label":n(`内容宽度(360px 到满宽)`,`Content width (360px to full)`),"aria-valuetext":a?n(`满宽`,`Full width`):`${o}px`,onChange:e=>{let n=Number(e.target.value);t(n>=r?0:n)}}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[360,`px`]}),(0,Q.jsx)(`span`,{children:n(`满宽`,`Full width`)})]})]}),(0,Q.jsx)(`span`,{className:`settings-font-value mono`,children:a?n(`满宽`,`Full`):`${e}px`})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:Ry.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${r.px===e?` settings-lang-on`:``}`,title:r.px>0?`${r.px}px`:n(`铺满整个对话区`,`Fill the whole area`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-chat-width`,value:r.id,checked:r.px===e,onChange:()=>t(r.px)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:n(r.label,r.labelEn)}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.px>0?`${r.px}px`:n(`默认`,`Default`)})]},r.id))})]})}function Xx(){let e=J(),{percent:t,setPercent:n}=Cb(),r=hb(t);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:e(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-appbar-scale`,type:`range`,min:60,max:120,step:5,value:t,"aria-label":e(`顶栏大小(60%–120%)`,`Top bar size (60%–120%)`),"aria-valuetext":`${t}%`,onChange:e=>n(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[60,`%`]}),(0,Q.jsxs)(`span`,{children:[120,`%`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[t,`%`]})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:lb.map(t=>(0,Q.jsxs)(`label`,{className:`settings-lang${r===t.id?` settings-lang-on`:``}`,title:e(`一键设为 ${t.percent}%`,`Set to ${t.percent}%`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-appbar-scale-preset`,value:t.id,checked:r===t.id,onChange:()=>n(t.percent)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:e(t.label,t.labelEn)}),(0,Q.jsxs)(`span`,{className:`settings-lang-hint`,children:[t.percent,`%`]})]},t.id))})]})}function Zx({theme:e,active:t,onPick:n}){let r=J();return(0,Q.jsxs)(`button`,{type:`button`,className:`theme-card${t?` theme-card-on`:``}`,"aria-pressed":t,title:`${r(e.name,e.nameEn)} — ${r(e.hint,e.hintEn)}`,onClick:n,children:[(0,Q.jsxs)(`span`,{className:`theme-preview`,style:{background:e.swatch[0]},children:[(0,Q.jsx)(`span`,{className:`theme-preview-bar`,style:{background:e.swatch[1]}}),(0,Q.jsx)(`span`,{className:`theme-preview-bar theme-preview-bar-short`,style:{background:e.swatch[1]}}),(0,Q.jsx)(`span`,{className:`theme-preview-dot`,style:{background:e.swatch[2]}})]}),(0,Q.jsxs)(`span`,{className:`theme-name`,children:[r(e.name,e.nameEn),t?(0,Q.jsx)(`span`,{className:`theme-check`,"aria-hidden":`true`,children:`✓`}):null]}),(0,Q.jsx)(`span`,{className:`theme-hint`,children:r(e.hint,e.hintEn)})]})}function Qx(){let e=J(),[t,n]=Eh(br,14,8,24);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`命令行字号(终端)`,`Command-line font size (terminal)`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`右侧终端面板里的字(也能在终端里用 ⌘/Ctrl + 滚轮调)`,`Text inside the terminal panel (or ⌘/Ctrl + wheel in it)`)})]}),(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:e(`字号`,`Size`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-terminal-font`,type:`range`,min:8,max:24,step:1,value:t,"aria-label":e(`命令行字号(8–24 像素)`,`Command-line font size (8–24 px)`),"aria-valuetext":`${t}px`,onChange:e=>n(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[8,`px`]}),(0,Q.jsxs)(`span`,{children:[24,`px`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[t,`px`]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`只存本机,立即生效。终端里 ⌘/Ctrl + 滚轮、⌘/Ctrl + = / - 也能调,⌘/Ctrl + 0 恢复 14px。`,`Stored on this device and applied immediately. You can also use ⌘/Ctrl + wheel or ⌘/Ctrl + = / - inside the terminal; ⌘/Ctrl + 0 resets to 14px.`)})]})}function $x(){let e=J(),{font:t,width:n,setFont:r,setWidth:i}=ab(),a=zb();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Qx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`聊天字体大小`,`Chat font size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`只影响对话正文(代码块、表格跟着缩放)`,`Affects message text only (code and tables scale with it)`)})]}),(0,Q.jsx)(Jx,{name:`settings-chat-font`,layer:`chat`,value:t,onChange:r})]}),(0,Q.jsx)(Vx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`侧栏项目名大小`,`Sidebar project name size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`项目列表里那一行文件夹名`,`The folder name rows in the project list`)})]}),(0,Q.jsx)(Jx,{name:`settings-side-project-font`,layer:`project`,value:a.project,onChange:a.setProject})]}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`侧栏会话名大小`,`Sidebar session name size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`会话标题;时间、置顶项目名等跟着按比例缩`,`Session titles; timestamps and the pinned project label scale with them`)})]}),(0,Q.jsx)(Jx,{name:`settings-side-session-font`,layer:`session`,value:a.session,onChange:a.setSession})]}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`聊天内容宽度`,`Chat content width`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`对话列的最大宽度(窄屏自动铺满)`,`Max width of the conversation column (narrow screens fill it)`)})]}),(0,Q.jsx)(Yx,{value:n,onChange:i})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;首次是标准字号 + 标准宽度。`,`Takes effect immediately, nothing to save. Stored on this machine (localStorage); it survives reloads and does not touch the server or other devices. The first run uses the standard size and standard width.`)})]})}function eS(){let e=J(),{theme:t,setTheme:n}=Ty(),r=[{mode:`light`,label:e(`浅色`,`Light`),hint:e(`白天 / 亮环境`,`Daylight / bright rooms`)},{mode:`dark`,label:e(`深色`,`Dark`),hint:e(`夜里 / 暗环境`,`Night / dim rooms`)}];return(0,Q.jsxs)(Q.Fragment,{children:[r.map(e=>(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e.hint})]}),(0,Q.jsx)(`div`,{className:`theme-grid`,children:Dh.filter(t=>Ah(t.id)===e.mode).map(e=>(0,Q.jsx)(Zx,{theme:e,active:t.id===e.id,onPick:()=>n(e.id)},e.id))})]},e.mode)),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;首次使用是「清亮白」。`,`Takes effect immediately, nothing to save. Stored on this machine (localStorage); it survives reloads and does not touch the server or other devices. The first run uses the bright default theme.`)})]})}function tS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function nS(e){return e.toLocaleString(`zh-CN`)}function rS(e,t){let n=t.trim().toLowerCase();if(n===``)return e;let r=n.split(/\s+/);return e.filter(e=>{let t=`${e.name} ${e.id} ${e.description}`.toLowerCase();return r.every(e=>t.includes(e))})}function iS(e){return[...e].sort((e,t)=>{let n=e=>/^skill\.md$/i.test(e)?0:/^references\//i.test(e)?2:1;return n(e)-n(t)||e.localeCompare(t)})}function aS({skill:e,detail:t,busy:n,confirmRemove:r,onFile:i,onToggle:a,onRemove:o}){let s=J(),c=iS(e.files);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`skills-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge${e.enabled?` skill-badge-on`:``}`,children:e.enabled?s(`已启用`,`Enabled`):s(`已停用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:n,onClick:a,children:e.enabled?s(`停用`,`Disable`):s(`启用`,`Enable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${r===e.id?` btn-danger`:``}`,disabled:n,onClick:o,title:s(`整目录删除(含 scripts / references)`,`Delete the whole folder (scripts / references included)`),children:r===e.id?s(`确认删除`,`Confirm delete`):s(`删除`,`Delete`)})]}),(0,Q.jsxs)(`div`,{className:`skills-detail-meta`,children:[(0,Q.jsx)(`span`,{className:`skills-label`,children:s(`目录`,`Folder`)}),(0,Q.jsx)(`span`,{className:`mono skill-slug`,children:e.id}),(0,Q.jsx)(`span`,{className:`skills-label`,children:s(`文件`,`File`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[c.length,` `,s(`个`,``)]})]}),e.description===``?null:(0,Q.jsx)(`p`,{className:`skills-desc`,children:e.description}),(0,Q.jsx)(`div`,{className:`skills-file-chips`,children:c.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`skills-file${t?.path===e?` skills-file-on`:``}`,onClick:()=>i(e),children:e},e))}),t===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`点上面的文件名看内容。`,`Click a file name above to see its content.`)}):t.preview===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`读取中…`,`Loading…`)}):t.preview.binary?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`这是二进制文件,不能预览`,`This is a binary file and cannot be previewed`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count mono`,children:[t.path,` · `,nS(t.preview.bytes),` `,s(`字节`,`bytes`)]}),(0,Q.jsx)(`pre`,{className:`skills-preview mono`,children:t.preview.text})]})]})}function oS({skills:e,tab:t,onTab:n,query:r,onQuery:i,byTab:a,shown:o,selected:s,selecting:c,picked:l,onPicked:u,onSelecting:d,busy:f,confirmRemove:p,installOpen:m,onOpenInstall:h,onOpenDetail:g,onBatchEnabled:_,onBatchRemove:v,onEnableAll:y}){let b=J(),x=e=>{let t=new Set(l);t.has(e)?t.delete(e):t.add(e),u(t)},S=e.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`skills-list-col`,children:[(0,Q.jsx)(`div`,{className:`skills-tabbar`,role:`tablist`,"aria-label":b(`技能筛选`,`Skill filter`),children:[{key:`all`,label:b(`全部`,`All`),count:e.length},{key:`enabled`,label:b(`启用`,`Enabled`),count:S},{key:`disabled`,label:b(`禁用`,`Disabled`),count:e.length-S}].map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":t===e.key,className:`skills-tab${t===e.key?` skills-tab-on`:``}`,onClick:()=>n(e.key),children:[e.label,(0,Q.jsx)(`span`,{className:`skills-tab-count`,children:e.count})]},e.key))}),(0,Q.jsx)(`input`,{className:`skills-input skills-search`,value:r,placeholder:t===`all`?b(`搜索已安装的技能…`,`Search installed skills…`):b(`在「${t===`enabled`?`启用`:`禁用`}」里搜索…`,`Search among ${t===`enabled`?`enabled`:`disabled`} skills…`),onChange:e=>i(e.target.value),"aria-label":b(`搜索已安装的技能`,`Search installed skills`)}),(0,Q.jsxs)(`div`,{className:`skills-list-head`,children:[(0,Q.jsx)(`span`,{children:c?b(`已选 ${l.size}`,`${l.size} selected`):t===`all`?b(`已安装`,`Installed`):t===`enabled`?b(`已启用`,`Enabled`):b(`已禁用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:r.trim()===``?b(`${o.length} 个`,`${o.length}`):b(`匹配 ${o.length} / ${a.length}`,`${o.length} / ${a.length} matching`)}),(0,Q.jsx)(`button`,{type:`button`,className:`skills-select-toggle${c?` skills-select-toggle-on`:``}`,onClick:()=>d(!c),title:c?b(`退出多选`,`Leave multi-select`):b(`多选:可批量启用 / 停用 / 删除`,`Multi-select: enable / disable / delete in bulk`),children:c?b(`完成`,`Done`):b(`多选`,`Multi-select`)})]}),(0,Q.jsx)(`div`,{className:`skills-list-scroll`,children:o.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:e.length===0?b(`还没有技能,点下面「安装技能」`,`No skills yet — use “Install skill” below`):t===`disabled`?b(`没有禁用的技能`,`No disabled skills`):t===`enabled`?b(`没有启用的技能`,`No enabled skills`):b(`没有匹配的技能`,`No matching skills`)}):o.map(e=>{let t=l.has(e.id);return(0,Q.jsxs)(`button`,{type:`button`,className:`skill-item${c?` skill-item-pick`:``}${t?` skill-item-picked`:``}${s===e.id&&!c?` skill-item-on`:``}${e.enabled?``:` skill-item-off`}`,onClick:()=>c?x(e.id):g(e),title:c?b(`选择 ${e.name}`,`Select ${e.name}`):e.description,children:[c?(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>void 0,tabIndex:-1,"aria-label":b(`选择 ${e.name}`,`Select ${e.name}`)}):(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`skill-item-name`,children:e.name})]},e.id)})}),c?(0,Q.jsxs)(`div`,{className:`skills-batch`,children:[(0,Q.jsxs)(`div`,{className:`skills-batch-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:o.length===0,onClick:()=>u(o.every(e=>l.has(e.id))?new Set:new Set(o.map(e=>e.id))),children:o.length>0&&o.every(e=>l.has(e.id))?b(`全不选`,`Select none`):`${b(`全选`,`Select all`)} ${o.length}`}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>u(new Set),children:b(`清空`,`Clear`)})]}),(0,Q.jsxs)(`div`,{className:`skills-batch-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>_(!0),title:b(`把勾选的技能全部启用`,`Enable every ticked skill`),children:b(`批量启用`,`Enable selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>_(!1),title:b(`把勾选的技能全部停用(改名 SKILL.md)`,`Disable every ticked skill (renames SKILL.md)`),children:b(`批量禁用`,`Disable selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${p===`batch`?` btn-danger`:``}`,disabled:f||l.size===0,onClick:v,title:b(`整目录删除,不可恢复`,`Delete the whole folder — this cannot be undone`),children:p===`batch`?b(`确认删除 ${l.size} 个`,`Confirm delete ${l.size}`):b(`批量删除`,`Delete selected`)})]})]}):(0,Q.jsxs)(`div`,{className:`skills-left-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${m?` btn-on`:``}`,onClick:h,children:[`+ `,b(`安装技能`,`Install skill`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||a.every(e=>e.enabled),onClick:y,title:b(`把当前页签里停用的技能全部启用`,`Enable all disabled skills in this tab`),children:b(`全启用`,`Enable all`)})]})]})}function sS({root:e,onInstalled:t,onOpenGit:n}){let r=J(),[i,a]=(0,C.useState)(``),[o,s]=(0,C.useState)(``),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)([]),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(1),[g,_]=(0,C.useState)(!1),[v,y]=(0,C.useState)(null),[b,x]=(0,C.useState)(null),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(null),D=(0,C.useRef)(0);(0,C.useEffect)(()=>{let e=window.setTimeout(()=>s(i.trim()),400);return()=>window.clearTimeout(e)},[i]);let O=(0,C.useCallback)(async(e,t)=>{let n=++D.current;w(!0),x(null);try{let r=new URLSearchParams({q:o,category:c,page:String(e)}),i=await fetch(`/api/skills/hub?${r.toString()}`),a=await i.json();if(n!==D.current)return;if(!i.ok){x(tS(a,i.status)),t||p([]);return}a.categories&&d(a.categories);let s=a.skills??[];p(e=>t&&e!==null?[...e,...s]:s),h(e),_(a.hasMore===!0),y(a.total??null)}catch(e){if(n!==D.current)return;x(e instanceof Error?e.message:String(e)),t||p([])}finally{n===D.current&&w(!1)}},[o,c]);(0,C.useEffect)(()=>{O(1,!1)},[O]);let k=async e=>{E(e.slug);try{let n=await(await fetch(`/api/skills/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:`hub`,slug:e.slug,name:e.slug})})).json();t(n),n.notice!==void 0&&p(t=>t?.map(t=>t.slug===e.slug?{...t,installed:!0}:t)??null)}catch(e){t({installError:e instanceof Error?e.message:String(e)})}finally{E(null)}};return(0,Q.jsxs)(`div`,{className:`skills-hub`,children:[(0,Q.jsxs)(`form`,{className:`skills-hub-search`,onSubmit:e=>{e.preventDefault(),s(i.trim()),O(1,!1)},children:[(0,Q.jsx)(`input`,{className:`skills-input`,value:i,placeholder:r(`搜索 SkillHub 的技能(名字、用途、关键词)`,`Search SkillHub skills (name, purpose, keywords)`),onChange:e=>a(e.target.value)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-tiny btn-primary-add`,disabled:S,children:S?r(`搜索中…`,`Searching…`):r(`搜索`,`Search`)})]}),(0,Q.jsx)(`div`,{className:`skills-hub-cats`,children:(u.length>0?u:[{key:``,label:`全部`}]).map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`skills-cat${c===e.key?` skills-cat-on`:``}`,onClick:()=>{l(e.key),s(i.trim())},children:r(e.label)},e.key||`all`))}),(0,Q.jsxs)(`div`,{className:`skills-hub-meta`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[v===null?``:r(`共 ${nS(v)} 个技能`,`${nS(v)} skills in total`),f===null?``:` · ${r(`已列出`,`showing`)} ${f.length}`,` · `,r(`安装到`,`installed to`),` `,(0,Q.jsx)(`code`,{children:e})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:n,children:[r(`从 Git 仓库装`,`Install from a Git repo`),` ↗`]})]}),b===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:b}),f===null&&S?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`正在读取技能库…`,`Loading the skill hub…`)}):null,f!==null&&f.length===0&&!S?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有匹配的技能,换个词或换个分类试试。`,`No matching skills — try another word or category.`)}):null,(0,Q.jsx)(`div`,{className:`skills-hub-list`,children:(f??[]).map((t,n)=>(0,Q.jsxs)(`div`,{className:`skill-card`,children:[(0,Q.jsxs)(`div`,{className:`skill-card-head`,children:[(0,Q.jsx)(`span`,{className:`skill-card-name`,children:t.name}),t.installed?(0,Q.jsx)(`span`,{className:`mcp-badge skill-badge-on`,children:r(`已安装`,`Installed`)}):(0,Q.jsx)(`span`,{className:`mcp-badge`,children:r(`未安装`,`Not installed`)}),t.author?(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`作者`,`by`),` `,t.author]}):null,t.categoryLabel?(0,Q.jsx)(`span`,{className:`mcp-badge`,children:r(t.categoryLabel)}):null,t.downloads===void 0?null:(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`下载`,`Downloads`),` `,nS(t.downloads)]}),t.stars===void 0?null:(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`收藏`,`Stars`),` `,nS(t.stars)]})]}),t.description===``?null:(0,Q.jsx)(`p`,{className:`skill-card-desc`,children:t.description}),(0,Q.jsxs)(`div`,{className:`skill-card-foot`,children:[(0,Q.jsx)(`span`,{className:`skill-slug mono`,children:t.slug}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),t.homepage?(0,Q.jsxs)(`a`,{className:`mcp-catalog-link`,href:t.homepage,target:`_blank`,rel:`noreferrer`,children:[r(`详情`,`Details`),` ↗`]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:T!==null||t.installed===!0,onClick:()=>void k(t),title:t.installed?r(`本机已有同名目录`,`A folder with this name already exists`):r(`装到 ${e}/${t.slug}`,`Installs to ${e}/${t.slug}`),children:T===t.slug?r(`安装中…`,`Installing…`):t.installed?r(`已安装`,`Installed`):r(`安装`,`Install`)})]})]},`${t.slug}-${n}`))},`${o}|${c}`),g?(0,Q.jsx)(`div`,{className:`skills-hub-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:S,onClick:()=>void O(m+1,!0),children:S?r(`加载中…`,`Loading…`):r(`加载更多`,`Load more`)})}):null,(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[r(`技能来自`,`Skills come from`),` `,(0,Q.jsx)(`code`,{children:`skillhub.tencent.com`}),r(`(公开接口,5 分钟内重复搜索走缓存)。安装 = 下载 zip 整目录解到`,`(public API; repeated searches within 5 minutes are cached). Installing = download the zip and unpack the whole folder into`),` `,(0,Q.jsx)(`code`,{children:e}),r(`,同名已存在不会覆盖。`,`; an existing folder with the same name is never overwritten.`)]})]})}var cS=`---
40
+ (pi built-in provider: removing writes a custom entry that overrides its model list)`):``;window.confirm(r(`从「${e.provider}」移除模型 ${i.id}?${t}`,`Remove model ${i.id} from “${e.provider}”?${t}`))&&(_u(e.provider,i.id),n())},children:r(`移除`,`Remove`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:n,children:r(`关闭`,`Close`)})]}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`ID(必填)`,`ID (required)`)}),(0,Q.jsx)(`input`,{value:i.id,readOnly:!0,title:r(`ID 是主键,改名等于新建一个模型`,`The ID is the key — renaming it creates a new model`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:`Name`}),(0,Q.jsx)(`input`,{value:i.name,onChange:e=>v(`name`,e.target.value),placeholder:`DeepSeek V4.1 Flash`})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`能力`,`Capabilities`)}),(0,Q.jsxs)(`label`,{className:`side-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.reasoning,onChange:e=>v(`reasoning`,e.target.checked)}),r(`推理 / 思考`,`Reasoning / thinking`)]}),(0,Q.jsxs)(`label`,{className:`side-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:i.imageInput,onChange:e=>v(`imageInput`,e.target.checked)}),r(`图片输入`,`Image input`)]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`模型规格`,`Model limits`)}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`上下文窗口(tokens)`,`Context window (tokens)`)}),(0,Q.jsx)(`input`,{inputMode:`numeric`,value:i.contextWindow,onChange:e=>v(`contextWindow`,e.target.value),placeholder:`1000000`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`最大输出 tokens`,`Max output tokens`)}),(0,Q.jsx)(`input`,{inputMode:`numeric`,value:i.maxTokens,onChange:e=>v(`maxTokens`,e.target.value),placeholder:`384000`})]})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`每百万 tokens 价格(全天价;留空 = 未提供)`,`Price per million tokens (flat all-day rate; empty = not provided)`)}),(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`输入`,`Input`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.input,onChange:e=>v(`input`,e.target.value),placeholder:r(`未提供`,`not provided`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`输出`,`Output`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.output,onChange:e=>v(`output`,e.target.value),placeholder:r(`未提供`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`缓存读`,`Cache read`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.cacheRead,onChange:e=>v(`cacheRead`,e.target.value),placeholder:r(`未提供`)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`缓存写`,`Cache write`)}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:i.cacheWrite,onChange:e=>v(`cacheWrite`,e.target.value),placeholder:r(`未提供`)})]})]})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`分时价格(可选,按本机时区)`,`Time-of-day prices (optional, local timezone)`)}),i.schedule.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`不填时段 = 全天都用上面的价格`,`No segments = the flat price above applies all day`)}):null,i.schedule.map((e,t)=>(0,Q.jsxs)(`div`,{className:`price-seg`,children:[(0,Q.jsxs)(`div`,{className:`side-field-row`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`开始`,`Start`)}),(0,Q.jsx)(`input`,{type:`time`,value:e.start,onChange:e=>y(t,`start`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(`结束(空 = 到下一段)`,`End (empty = until the next segment)`)}),(0,Q.jsx)(`input`,{type:`time`,value:e.end,onChange:e=>y(t,`end`,e.target.value)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>x(t),title:r(`删掉这一段(删完就回到全天一个价)`,`Delete this segment (back to one all-day price)`),children:r(`删`,`Del`)})]}),(0,Q.jsx)(`div`,{className:`side-field-row`,children:ly.map(n=>(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:r(uy[n],dy[n])}),(0,Q.jsx)(`input`,{inputMode:`decimal`,value:e[n],onChange:e=>y(t,n,e.target.value),placeholder:r(`同全天价`,`same as flat`)})]},n))})]},t)),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:b,title:r(`加一段高峰 / 低峰价格`,`Add a peak / off-peak segment`),children:[`+ `,r(`添加时段`,`Add segment`)]}),i.schedule.length>0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`每段从开始时间生效,直到下一段开始;没填结束的最后一段会跨零点接到最早那段。段内价格留空 = 沿用上面的全天价;想精确控制某几个小时就填结束时间。`,`Each segment applies from its start time until the next one starts; a last segment without an end wraps past midnight into the earliest one. Leaving a segment's price empty reuses the flat rate; fill the end time to target specific hours.`)}):null]}),(0,Q.jsx)(`div`,{className:`import-foot`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,title:r(`从 models.dev 查这个模型的公开规格(只作建议值,会覆盖当前已填的规格)`,`Look up public specs on models.dev (suggestions only; overwrites the values above)`),onClick:()=>void S(),disabled:g,children:g?r(`填充中…`,`Filling…`):r(`填入模型信息`,`Fill in model specs`)})}),u?(0,Q.jsx)(`div`,{className:u.startsWith(r(`已填入`,`Filled in`))?`side-ok`:`side-panel-hint side-error`,children:u}):null,o?(0,Q.jsx)(`div`,{className:`side-ok`,children:r(`已提交(服务端校验通过才会写入;失败原因会显示在弹窗顶部)`,`Submitted (written only after server validation; failures show at the top)`)}):null,e.source===`builtin`?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[r(`当前是 pi 内置 provider:保存会直接写回`,`This is a pi built-in provider: saving writes straight back to`),` `,(0,Q.jsx)(`span`,{className:`mono`,children:`~/.pi/agent/models.json`})]}):null,c?(0,Q.jsxs)(`div`,{className:`side-error side-panel-hint`,children:[r(`分时价格:`,`Time-of-day prices: `),c,r(`(尚未提交)`,` (not submitted yet)`)]}):null]})}function gy({initial:e,onSaved:t,formRef:n}){let[r,i]=(0,C.useState)(e?.provider??``),[a,o]=(0,C.useState)(e?.baseUrl??``),[s,c]=(0,C.useState)(e?.api||`openai-completions`),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(``),[p,m]=(0,C.useState)((e?.models??[]).map(e=>({id:e.id,on:!0}))),[h,g]=(0,C.useState)(``),_=(e?.models.length??0)===0&&(e?.modelCount??0)>0,v=Y(),[y,b]=(0,C.useState)(null),[x,S]=(0,C.useState)(!1),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(0),[O,k]=(0,C.useState)({}),[A,j]=(0,C.useState)(!1),[M,N]=(0,C.useState)(0),[P,F]=(0,C.useState)(0),I=(0,C.useRef)(null);(0,C.useEffect)(()=>()=>I.current?.abort(),[]);let L=async()=>{S(!0),T(null);try{let e=await fetch(`/api/providers/remote-models`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:r,baseUrl:a,api:s,...l.trim()===``?{}:{apiKey:l.trim()},...Object.keys(W).length>0?{headers:W}:{}})}),t=await e.json(),n=(t.models??[]).map(e=>e.id);if(!e.ok||n.length===0){T(t.error?.message??v(`这个地址没有返回可用的模型`,`This endpoint returned no usable models`));return}m(e=>{let t=new Set(e.map(e=>e.id));return[...e,...n.filter(e=>!t.has(e)).map(e=>({id:e,on:!1}))]}),D(n.length),b({kind:`ok`,text:v(`已获取 ${n.length} 个模型:勾选要用的,再保存`,`Fetched ${n.length} models — tick the ones you need, then save`)})}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(!1)}},R=p.filter(e=>e.on).map(e=>e.id),z=async()=>{let t=e?.provider,n=R.slice();if(!t||n.length===0||I.current)return;let r=new AbortController;I.current=r,j(!0),N(0),F(n.length),k({});let i=0;for(let e of n){if(r.signal.aborted)break;try{let n=await fetch(`/api/providers/${encodeURIComponent(t)}/models/${encodeURIComponent(e)}/test`,{method:`POST`,signal:r.signal}),i=await n.json();k(t=>({...t,[e]:i.ok?{ok:!0,text:[i.latencyMs===void 0?null:`${i.latencyMs}ms`,i.message??null].filter(e=>e!==null&&e!==``).join(` · `)}:{ok:!1,text:v(`失败 ${i.message??i.error?.message??`HTTP ${n.status}`}`,`Failed: ${i.message??i.error?.message??`HTTP ${n.status}`}`).trim()}}))}catch(t){if(r.signal.aborted)break;k(n=>({...n,[e]:{ok:!1,text:t instanceof Error?t.message:v(`失败`,`Failed`)}}))}i+=1,N(i)}I.current=null,j(!1)},B=(e,t)=>m(n=>n.map(n=>n.id===e?{...n,on:t}:n)),V=e=>m(t=>t.filter(t=>t.id!==e)),H=e=>m(t=>t.map(t=>({...t,on:e}))),U=()=>{let e=h.trim();e===``||p.some(t=>t.id===e)||m(t=>[...t,{id:e,on:!0}]),g(``)},W=Object.fromEntries(d.split(/\r?\n/).map(e=>e.split(/:(.*)/s)).filter(([e,t])=>!!(e?.trim()&&t?.trim())).map(([e,t])=>[e.trim(),t.trim()])),ee=()=>({provider:r,...e&&e.provider!==r.trim()?{previousProvider:e.provider}:{},baseUrl:a,api:s,...l.trim()===``?{}:{apiKey:l.trim()},...Object.keys(W).length>0?{headers:W}:{},models:R.map(e=>({id:e}))}),G=()=>{yu(ee()),t?.(r.trim()),b({kind:`ok`,text:v(`已提交,结果会以提示形式出现在对话区`,`Submitted — the result appears as a notice in the conversation`)}),u(``)};return(0,C.useImperativeHandle)(n,()=>({save:G})),(0,Q.jsxs)(`div`,{className:`side-panel`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`provider(小写,作为 provider/model 前缀)`,`provider (lowercase; used as the provider/model prefix)`)}),(0,Q.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`my-endpoint`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:`base url`}),(0,Q.jsx)(`input`,{value:a,onChange:e=>o(e.target.value),placeholder:`https://api.example.com/v1`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`api 形态`,`API shape`)}),(0,Q.jsxs)(`select`,{value:s,onChange:e=>c(e.target.value),children:[(0,Q.jsx)(`option`,{value:`openai-completions`,children:`openai-completions`}),(0,Q.jsx)(`option`,{value:`openai-responses`,children:`openai-responses`}),(0,Q.jsx)(`option`,{value:`anthropic-messages`,children:`anthropic-messages`}),(0,Q.jsx)(`option`,{value:`openai-codex-responses`,children:`openai-codex-responses`}),(0,Q.jsx)(`option`,{value:`typesafe-system-one`,children:`typesafe-system-one`})]})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{children:[`API Key`,v(`(`,` (`),e?.hasKey?v(`已有 ${e.keyHint??``},留空即不修改`,`Saved ${e.keyHint??``} — leave empty to keep it`):e?.credential===`oauth`?v(`已用订阅登录${e.oauth?.accountHint?`(账号 ${e.oauth.accountHint})`:``},留空即继续用订阅额度`,`Signed in${e.oauth?.accountHint?` (${e.oauth.accountHint})`:``} — leave empty to keep using subscription quota`):_?v(`填一把就能用`,`just add a key`):v(`新增 provider 必填`,`required for a new provider`),v(`)`,`)`)]}),(0,Q.jsx)(`input`,{type:`password`,value:l,onChange:e=>u(e.target.value),placeholder:`sk-…`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:v(`自定义 Headers(每行 Name: Value)`,`Custom headers (one Name: Value per line)`)}),(0,Q.jsx)(`textarea`,{rows:3,value:d,onChange:e=>f(e.target.value),placeholder:e?.headerNames?.length?v(`已有:${e.headerNames.join(`, `)};留空保持不变`,`Saved: ${e.headerNames.join(`, `)} — leave empty to keep`):`X-Client: pop-agent`})]}),(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{className:`prov-field-head`,children:[v(`模型(勾选的才保存)`,`Models (only ticked ones are saved)`),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[R.length,`/`,p.length]}),(0,Q.jsxs)(`span`,{className:`prov-check-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>H(!0),disabled:p.every(e=>e.on),title:v(`全部勾上(保存时全部写进 provider)`,`Tick everything (all get written to the provider)`),children:v(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>H(!1),disabled:p.every(e=>!e.on),title:v(`全部不勾(保存时一个模型都不写)`,`Tick nothing (no model is written)`),children:v(`全不选`,`Select none`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:`auto`},onClick:()=>void z(),disabled:!e||A||R.length===0,title:e?A?v(`正在逐个测速`,`Testing models`):v(`逐个测试勾选的模型,每个模型会发一次最小请求`,`Tests each ticked model with one minimal request`):v(`先保存 provider,再用已保存的配置测速`,`Save the provider first, then test with its saved config`),children:A?v(`测速中…`,`Testing…`):v(`⏱ 批量测速`,`⏱ Test speed`)}),A?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>I.current?.abort(),title:v(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),children:[`■ `,v(`停止`,`Stop`),` `,M,`/`,P]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void L(),disabled:x||a.trim()===``,title:v(`调一次 GET /models 把可用模型拉回来,勾选要用的那些`,`Call GET /models to fetch the available models, then tick the ones you need`),children:x?v(`获取中…`,`Fetching…`):v(`⬇️ 从 API 获取`,`⬇️ Fetch from API`)})]}),p.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:v(`还没有模型:点「从 API 获取」,或在下面手填一个 id`,`No models yet — fetch from the API, or add an id by hand below`)}):(0,Q.jsx)(`div`,{className:`prov-checklist`,children:p.map(e=>(0,Q.jsxs)(`div`,{className:`prov-check-row${e.on?` prov-check-on`:``}`,children:[(0,Q.jsxs)(`label`,{className:`prov-check-label`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:e.on,onChange:t=>B(e.id,t.target.checked)}),(0,Q.jsx)(`span`,{className:`mono`,children:e.id})]}),(0,Q.jsx)(_y,{result:O[e.id]}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,title:v(`从列表里删掉这一行`,`Remove this row`),onClick:()=>V(e.id),children:v(`移除`,`Remove`)})]},e.id))}),(0,Q.jsxs)(`div`,{className:`prov-add-row`,children:[(0,Q.jsx)(`input`,{value:h,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&U()},placeholder:v(`手动加一个模型 id,回车添加`,`Add a model id by hand, press Enter`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:U,disabled:h.trim()===``,children:v(`添加`,`Add`)})]})]}),w?(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[v(`获取失败:`,`Fetch failed: `),w]}):null,E>0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[v(`已从接口取回`,`Fetched`),` `,E,` `,v(`个模型:勾上要用的,再保存`,`models — tick the ones you need, then save`)]}):null,y?(0,Q.jsx)(`div`,{className:y.kind===`ok`?`side-ok`:`side-panel-hint side-error`,children:y.text}):null]})}function _y({result:e}){return e?(0,Q.jsx)(`span`,{className:`prov-latency prov-check-latency${e.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:e.text,children:e.text}):null}function vy(e){let t=Y(),n=e.snapshot,r=n?.engine??``,i=n?.models??[],a=n?.model??null,o=ay(i,{name:r,label:e.engineOption?.label??r.toUpperCase()}),s=n?.engineCapabilities.modelProbe===!0,[c,l]=(0,C.useState)(null),u=o.find(e=>e.id===c)??o[0]??null,[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(!0),[h,g]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:engine-model-list-width`));return Number.isFinite(e)&&e>=140&&e<=420?e:190});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:engine-model-list-width`,String(h))},[h]);let _=(0,C.useRef)(!1),v=e=>{e.preventDefault(),_.current=!0;let t=e.clientX,n=h,r=e=>{_.current&&g(Math.min(420,Math.max(140,n+(e.clientX-t))))},i=()=>{_.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},[y,b]=(0,C.useState)({}),[x,S]=(0,C.useState)(null),[w,T]=(0,C.useState)(null),E=(0,C.useRef)(null),D=async e=>{if(e.length===0||x!==null)return;let n=new AbortController;E.current=n,b({}),T({done:0,total:e.length});let r=0;for(let i of e){if(n.signal.aborted)break;S(i);let a=await mu(i,n.signal),o=a.tps??a.averageTps??null,s=a.ttftMs===null||a.ttftMs===void 0?null:yy(a.ttftMs),c=a.ok?[t(s?`首字 ${s}`:`首字 ?`,s?`first ${s}`:`first ?`),t(o===null?`速度 ?`:`${o} tok/s${a.tps===null?`(均速)`:``}`,o===null?`speed ?`:`${o} tok/s${a.tps===null?` (avg)`:``}`)].join(` · `):t(`失败:${a.message??`未知错误`}`,`Failed: ${a.message??`unknown error`}`),l=c.length>42?`${c.slice(0,40)}…`:c;b(e=>({...e,[i]:{ok:a.ok,text:l,detail:c}})),r+=1,T({done:r,total:e.length})}S(null),T(null),E.current=null},O=e.engineOption?.label??r;return(0,Q.jsxs)(`div`,{className:`prov-shell engine-models`,style:{"--prov-list-width":`${h}px`},children:[(0,Q.jsxs)(`aside`,{className:`prov-list`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-list-head prov-list-toggle`,title:p?t(`收起服务商列表`,`Collapse the provider list`):t(`展开服务商列表`,`Expand the provider list`),onClick:()=>m(e=>!e),children:(0,Q.jsxs)(`span`,{className:`prov-list-toggle-label`,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${p?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),t(`供应商`,`Providers`)]})}),(0,Q.jsx)(`div`,{className:`prov-list-body${p?``:` prov-list-body-closed`}`,children:(0,Q.jsxs)(`div`,{className:`prov-list-scroll`,children:[o.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t(`引擎还没报上来模型:先新建一个会话`,`The engine has not reported any models yet — create a conversation first`)}):null,o.map(e=>{let n=u?.id===e.id,r=d===e.id&&e.models.length>0;return(0,Q.jsxs)(`div`,{className:`prov-block${n?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${n?` prov-item-on`:``}`,"aria-expanded":r,title:e.id,onClick:()=>{l(e.id),f(r?null:e.id)},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[e.models.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${r?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,children:e.label})]}),(0,Q.jsx)(`span`,{className:`prov-item-state`,children:`${e.models.length} ${t(`个模型`,`models`)}`})]}),r?(0,Q.jsx)(`div`,{className:`prov-models-inline`,children:e.models.map(n=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-inline-row`,title:n.id,onClick:()=>l(e.id),children:[(0,Q.jsx)(`span`,{className:`prov-inline-name`,children:iy(n)}),n.id===a?(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:t(`当前`,`current`)}):null]},n.id))}):null]},e.id)})]})})]}),(0,Q.jsx)(`div`,{className:`prov-resizer`,role:`separator`,"aria-orientation":`vertical`,title:t(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:v,onDoubleClick:()=>g(190)}),(0,Q.jsxs)(`section`,{className:`prov-detail`,children:[(0,Q.jsxs)(`div`,{className:`prov-tabs`,children:[(0,Q.jsx)(`span`,{className:`prov-engine-badge`,children:e.engineOption?.badge??r.toUpperCase()}),(0,Q.jsx)(`strong`,{className:`prov-detail-title`,children:u?.label??O}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[u?u.models.length:0,` `,t(`个模型`,`models`)]}),s&&u&&u.models.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x!==null,title:t(`对每个模型各发一次真实请求(会消耗少量额度),测首字延迟与出字速度`,`Sends one real request per model (costs a little quota) and measures time-to-first-token and tokens/s`),onClick:()=>{window.confirm(t(`会对 ${u.models.length} 个模型各发一次真实请求(消耗少量额度),继续?`,`This sends one real request per model (${u.models.length} total) and spends a little quota. Continue?`))&&D(u.models.map(e=>e.id))},children:w?t(`测速中… ${w.done}/${w.total}`,`Testing… ${w.done}/${w.total}`):t(`⏱ 批量测速`,`⏱ Test speed`)}),w?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,title:t(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),onClick:()=>E.current?.abort(),children:[`■ `,t(`停止`,`Stop`)]}):null]}):null]}),(0,Q.jsxs)(`div`,{className:`prov-detail-body`,children:[(0,Q.jsx)(`p`,{className:`prov-engine-note`,children:t(`这些是引擎自己报上来的模型(codex 读 model/list,claude / opencode / dsh 读会话里的模型表),本工作台不改它。换模型用输入区的模型下拉;测速是让引擎真跑一个最小回合,不读它的凭证。`,`These models come straight from the engine (codex via model/list, claude / opencode / dsh via their session model table); this workbench does not edit them. Switch models from the composer; testing runs one minimal turn inside the engine and never touches its credentials.`)}),u===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:i.length===0?t(`引擎还没报上来任何模型:先新建一个会话(claude / opencode 要开会话才拿得到模型表),或确认引擎已装好并登录。`,`The engine has not reported any models yet: create a conversation first (claude / opencode only expose their model table once a session exists), or check that the engine is installed and signed in.`):t(`左边挑一个供应商看模型。`,`Pick a provider on the left to see its models.`)}):(0,Q.jsx)(`div`,{className:`engine-model-list`,children:u.models.map(e=>{let n=y[e.id],r=e.id===a;return(0,Q.jsxs)(`div`,{className:`engine-model-row${r?` engine-model-row-on`:``}`,children:[(0,Q.jsx)(`span`,{className:`engine-model-name`,title:e.id,children:iy(e)}),(0,Q.jsx)(`span`,{className:`engine-model-id mono`,children:e.id}),r?(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:t(`当前`,`current`)}):null,s?(0,Q.jsx)(`span`,{className:`engine-model-probe`,children:x===e.id?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`测速中…`,`Testing…`)}):n?(0,Q.jsx)(`span`,{className:`prov-latency${n.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:n.detail,children:n.text}):(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x!==null,title:t(`发一次真实请求测这个模型(会消耗少量额度)`,`Sends one real request to measure this model (costs a little quota)`),onClick:()=>void D([e.id]),children:t(`测速`,`Test`)})}):null]},e.id)})})]})]})]})}function yy(e){return e>=1e3?`${(e/1e3).toFixed(2)}s`:`${Math.round(e)}ms`}function by({entry:e,onClose:t,onChanged:n,onImportModels:r,enabledModels:i=[],canTest:a=!1}){let o=Y(),[s,c]=(0,C.useState)(`idle`),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(null),[y,b]=(0,C.useState)(``),[x,S]=(0,C.useState)(!1),[w,T]=(0,C.useState)(!1),[E,D]=(0,C.useState)({}),[O,k]=(0,C.useState)(null),[A,j]=(0,C.useState)(null),M=(0,C.useRef)(null),N=(0,C.useRef)(null),P=(0,C.useRef)(!1),F=(0,C.useCallback)(()=>{N.current?.close(),N.current=null},[]);(0,C.useEffect)(()=>{c(`idle`),u(null),f(null),m(null),g(null),v(null),b(``),P.current=!1,F(),M.current?.abort(),M.current=null,D({}),k(null),j(null)},[e.id,F]),(0,C.useEffect)(()=>F,[F]);let I=(0,C.useCallback)(async(t,n)=>{if(n.trim()!==``){S(!0),v(null);try{let r=await fetch(`/api/subscriptions/${encodeURIComponent(e.id)}/login`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({token:t,code:n.trim()})}),i=await r.json();if(!r.ok){v(i.error?.message??`HTTP ${r.status}`);return}m(e=>e&&e.token===t?null:e),g(null),b(``)}catch(e){v(e instanceof Error?e.message:String(e))}finally{S(!1)}}},[e.id]),L=(0,C.useCallback)(()=>{F(),P.current=!1,c(`connecting`),u(null),f(null),m(null),g(null),v(null),b(``);let t=new EventSource(`/api/subscriptions/${encodeURIComponent(e.id)}/login`);N.current=t,t.onmessage=e=>{let r=JSON.parse(e.data);r.type===`auth`?(c(`running`),u({url:r.url??``,instructions:r.instructions??null}),r.url&&window.open(r.url,`_blank`,`noopener,noreferrer`)):r.type===`device_code`?(c(`running`),f({userCode:r.userCode??``,verificationUri:r.verificationUri??``,seconds:r.expiresInSeconds??null}),r.verificationUri&&window.open(r.verificationUri,`_blank`,`noopener,noreferrer`)):r.type===`prompt_request`&&r.token?(c(`running`),m({kind:`text`,token:r.token,message:r.message??``,placeholder:r.placeholder??null,secret:r.secret===!0})):r.type===`select_request`&&r.token?(c(`running`),m({kind:`select`,token:r.token,message:r.message??``,options:r.options??[]})):r.type===`progress`?(c(`running`),g(r.message??null)):r.type===`info`?g(r.message??null):r.type===`success`?(P.current=!0,t.close(),N.current=null,c(`done`),g(null),m(null),n()):r.type===`error`?(P.current=!0,t.close(),N.current=null,c(`error`),g(null),v(r.message??o(`登录失败`,`Sign-in failed`))):r.type===`cancelled`&&(P.current=!0,t.close(),N.current=null,c(`idle`),g(null))},t.onerror=()=>{t.close(),N.current=null,!P.current&&(c(`error`),g(null),v(o(`和服务器的连接断了:重试一次(登录可能已经在中途被取消)`,`Lost the connection to the server — try again (the sign-in may have been cancelled midway)`)))}},[e.id,n,F]),R=(0,C.useCallback)(async()=>{T(!0),v(null);try{let t=await fetch(`/api/subscriptions/${encodeURIComponent(e.id)}/logout`,{method:`POST`}),r=await t.json();if(!t.ok){v(r.error?.message??`HTTP ${t.status}`);return}c(`idle`),n()}catch(e){v(e instanceof Error?e.message:String(e))}finally{T(!1)}},[e.id,n]),z=s===`connecting`||s===`running`,B=e.models??[],V=e.connected&&r!==void 0,H=t=>Bf(i,e.id,t),U=B.filter(e=>H(e.id)).map(e=>e.id),W=B.length>0&&U.length===B.length,ee=U.length===0,G=async t=>{if(t.length===0||M.current!==null)return;let n=new AbortController;M.current=n,D({}),j({done:0,total:t.length});let r=0;for(let i of t){if(n.signal.aborted)break;k(i);let a;try{let t=await fetch(`/api/providers/${encodeURIComponent(e.id)}/models/${encodeURIComponent(i)}/test`,{method:`POST`,signal:n.signal}),r=await t.json(),s=r.ok?[r.latencyMs===void 0?null:`${r.latencyMs}ms`,r.message??null].filter(e=>e!==null&&e!==``).join(` · `):o(`失败:${r.message??r.error?.message??`HTTP ${t.status}`}`,`Failed: ${r.message??r.error?.message??`HTTP ${t.status}`}`);a={ok:r.ok===!0,text:s.length>42?`${s.slice(0,40)}…`:s,detail:s}}catch(e){if(n.signal.aborted)break;let t=e instanceof Error?e.message:String(e);a={ok:!1,text:t.slice(0,40),detail:t}}D(e=>({...e,[i]:a})),r+=1,j({done:r,total:t.length})}k(null),j(null),M.current=null};return(0,Q.jsxs)(`div`,{className:`side-panel subs-detail`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:e.name}),(0,Q.jsx)(`span`,{className:`side-panel-count mono`,children:e.id}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),e.connected?(0,Q.jsx)(`span`,{className:`subs-state subs-state-on`,children:o(`已连接`,`Connected`)}):(0,Q.jsx)(`span`,{className:`subs-state`,children:o(`未连接`,`Not connected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,title:o(`回到 provider 列表`,`Back to the provider list`),children:`✕`})]}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e.subscription?o(`用你的订阅账号登录:额度算在订阅里,不按 API key 计费。凭据由引擎写进 ~/.pi/agent/auth.json。`,`Sign in with your subscription: usage counts against the subscription, not an API key. The engine writes the credential to ~/.pi/agent/auth.json.`):o(`用 OAuth 登录这个 provider(凭据由引擎写进 ~/.pi/agent/auth.json)。`,`Sign in to this provider with OAuth (the engine writes the credential to ~/.pi/agent/auth.json).`),(0,Q.jsxs)(`div`,{children:[o(`当前`,`Currently`),` `,e.modelCount,` `,o(`个模型。`,`models.`),` `,e.supportsApiKey?o(`它也支持 API key —— 那条路在左侧 provider 表单里。`,`It also accepts an API key — that route lives in the provider form on the left.`):``]})]}),l?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:l.instructions??o(`在授权页完成登录。`,`Finish signing in on the authorization page.`)}),(0,Q.jsx)(`a`,{className:`subs-link`,href:l.url,target:`_blank`,rel:`noopener noreferrer`,children:o(`打开授权页(浏览器没自动弹出时点这里)`,`Open the authorization page (click here if the browser did not open)`)})]}):null,d?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[o(`在验证页输入下面这串码`,`Enter this code on the verification page`),d.seconds?` (${Math.round(d.seconds/60)} ${o(`分钟内有效`,`min to enter`)})`:``,o(`:`,`:`)]}),(0,Q.jsx)(`div`,{className:`subs-code mono`,children:d.userCode}),(0,Q.jsx)(`a`,{className:`subs-link`,href:d.verificationUri,target:`_blank`,rel:`noopener noreferrer`,children:d.verificationUri})]}):null,p?.kind===`select`?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:p.message}),(0,Q.jsx)(`div`,{className:`subs-options`,children:p.options.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:x,title:e.description??e.id,onClick:()=>void I(p.token,e.id),children:e.label},e.id))})]}):null,p?.kind===`text`?(0,Q.jsxs)(`div`,{className:`subs-block`,children:[(0,Q.jsxs)(`label`,{className:`side-field`,children:[(0,Q.jsx)(`span`,{children:p.message}),(0,Q.jsx)(`input`,{type:p.secret?`password`:`text`,value:y,autoFocus:!0,autoComplete:`off`,placeholder:p.placeholder??o(`粘贴授权码或回调地址`,`Paste the authorization code or callback URL`),onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&I(p.token,y)}})]}),(0,Q.jsx)(`div`,{className:`subs-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:x||y.trim()===``,onClick:()=>void I(p.token,y),children:x?o(`校验中…`,`Checking…`):o(`提交`,`Submit`)})})]}):null,h?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:h}):null,_?(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:_}):null,s===`done`?(0,Q.jsx)(`div`,{className:`side-ok`,children:o(`已连接:模型表已重载,聊天里可以直接选它的模型了。`,`Connected — the model list was reloaded; you can pick its models in the chat now.`)}):null,(0,Q.jsx)(`div`,{className:`import-foot`,children:e.connected?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:L,disabled:w||z,children:o(`重新登录`,`Sign in again`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>void R(),disabled:w,children:o(`退出登录`,`Sign out`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,onClick:L,disabled:z,children:z?o(`登录中…`,`Signing in…`):o(`连接 ${e.name} 账号`,`Connect the ${e.name} account`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),z?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{F(),c(`idle`),m(null),u(null),f(null),g(null)},children:o(`取消`,`Cancel`)}):null]})}),B.length>0||V?(0,Q.jsxs)(`div`,{className:`side-field`,children:[(0,Q.jsxs)(`span`,{className:`prov-field-head`,children:[o(`模型(勾选的才启用)`,`Models (only ticked ones are enabled)`),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[U.length,`/`,B.length]}),(0,Q.jsxs)(`span`,{className:`prov-check-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:W,onClick:()=>gu(e.id,!0),title:o(`全部启用(写进 pi 的 settings.json)`,`Enable everything (written to pi's settings.json)`),children:o(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:ee,onClick:()=>gu(e.id,!1),title:o(`全部停用(对话里就选不到它们了)`,`Disable everything (they disappear from the composer)`),children:o(`全不选`,`Select none`)})]}),a?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:`auto`},disabled:O!==null||U.length===0,title:U.length===0?o(`先勾选要测的模型`,`Tick the models you want to test first`):o(`对勾选的 ${U.length} 个模型各发一次真实请求(消耗少量订阅额度),测首字延迟与出字速度`,`Sends one real request for each of the ${U.length} ticked models (spends a little subscription quota) and measures time-to-first-token and tokens/s`),onClick:()=>{let e=U.slice();window.confirm(o(`会对 ${e.length} 个模型各发一次真实请求(消耗少量额度),继续?`,`This sends one real request per model (${e.length} total) and spends a little quota. Continue?`))&&G(e)},children:A?o(`测速中… ${A.done}/${A.total}`,`Testing… ${A.done}/${A.total}`):o(`⏱ 批量测速`,`⏱ Test speed`)}):null,A?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,style:{marginLeft:a?0:`auto`},title:o(`停止测速,已测出的结果会保留`,`Stop testing and keep the results already measured`),onClick:()=>M.current?.abort(),children:[`■ `,o(`停止`,`Stop`)]}):null,V?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,style:{marginLeft:a?0:`auto`},onClick:r,disabled:w||z,title:o(`从订阅拉取可用模型,再勾选要启用的`,`Fetch available models from the subscription, then tick the ones to enable`),children:[`⬇️ `,o(`从订阅获取模型`,`Fetch models from subscription`)]}):null]}),B.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:o(`还没有导入模型:点「从订阅获取模型」`,`No models imported yet — click “Fetch models from subscription”`)}):(0,Q.jsx)(`div`,{className:`prov-checklist`,children:B.map(t=>{let n=H(t.id);return(0,Q.jsxs)(`div`,{className:`prov-check-row${n?` prov-check-on`:``}`,children:[(0,Q.jsxs)(`label`,{className:`prov-check-label`,title:n?o(`已启用:点击停用(写进 pi 的 settings.json)`,`Enabled — click to disable (written to pi's settings.json)`):o(`未启用:点击启用`,`Disabled — click to enable`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>gu(e.id,!n,t.id)}),(0,Q.jsx)(`span`,{className:`mono`,children:t.id})]}),(0,Q.jsx)(xy,{result:E[t.id],busy:O===t.id})]},t.id)})})]}):null]})}function xy({result:e,busy:t}){let n=Y();return t?(0,Q.jsx)(`span`,{className:`prov-latency prov-latency-idle`,children:n(`测速中…`,`Testing…`)}):e?(0,Q.jsx)(`span`,{className:`prov-latency prov-check-latency${e.ok?` prov-latency-ok`:` prov-latency-fail`}`,title:e.detail,children:e.text}):null}function Sy({tab:e,onTab:t,subscriptions:n,catalog:r,onPickSubscription:i,onPickBuiltin:a,onPickCustom:o}){let s=Y(),c=[{id:`subscription`,label:s(`订阅服务`,`Subscriptions`),count:n.length},{id:`builtin`,label:s(`官方内置`,`Built-in`),count:r.length},{id:`custom`,label:s(`自己输入`,`Custom`),count:0}];return(0,Q.jsxs)(`div`,{className:`prov-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`side-panel-head`,children:[(0,Q.jsx)(`strong`,{children:s(`添加服务商`,`Add a provider`)}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`按来源选一种:订阅登录 / pi 目录里的 / 自己填`,`Pick a source: subscription, pi's catalog, or your own`)})]}),(0,Q.jsx)(`div`,{className:`prov-tabs`,children:c.map(n=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-tab${e===n.id?` prov-tab-on`:``}`,onClick:()=>t(n.id),children:[n.label,n.count>0?` ${n.count}`:``]},n.id))}),e===`subscription`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[n.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`引擎没报上来可订阅的渠道。`,`The engine reported no subscription providers.`)}):null,n.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-add-row`,onClick:()=>i(e.id),children:[(0,Q.jsx)(`span`,{className:`prov-add-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`prov-sub-state${e.connected?` prov-sub-state-on`:``}`,children:e.connected?s(`已登录 · 点开管理`,`Signed in · open to manage`):e.subscription?s(`订阅额度 · 点开登录`,`Subscription quota · click to sign in`):s(`OAuth · 点开登录`,`OAuth · click to sign in`)})]},e.id))]}):null,e===`builtin`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`pi 自己的目录里还没配 key 的。点一下就能填一把 key,模型表由目录提供。`,`Providers in pi's own catalog that have no key yet — click one to paste a key; the model list comes from the catalog.`)}),r.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`目录里的都已经配好了。`,`Everything in the catalog is configured.`)}):null,r.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`prov-add-row`,onClick:()=>a(e.provider),children:[(0,Q.jsx)(`span`,{className:`prov-add-name`,children:e.label??e.provider}),(0,Q.jsx)(`span`,{className:`prov-item-sub`,children:e.needsExtraConfig?s(`需额外配置`,`Needs setup`):e.oauthOnly?s(`只能订阅登录`,`Subscription only`):s(`${e.modelCount??0} 个模型`,`${e.modelCount??0} models`)})]},e.provider))]}):null,e===`custom`?(0,Q.jsxs)(`div`,{className:`prov-add-list`,children:[(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`自己填 base url / api 形态 / 模型清单。适合自建网关、局域网里的模型服务。`,`Fill in base url, API shape and the model list yourself — useful for your own gateway or a model server on the LAN.`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,children:[`+ `,s(`新建自定义服务商`,`New custom provider`)]})]}):null]})}function Cy(){let e=Y(),t=Ro(e=>e.snapshot),n=(t?.engine??`pi`)===`pi`,r=t?.providers??[],i=t?.enabledModels??[],a=e=>i.length===0||i.some(t=>t===`${e.provider}/**`||t.startsWith(`${e.provider}/`)),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(!0),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)([]),[v,y]=(0,C.useState)(null),[b,x]=(0,C.useState)(!1),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(null),D=(0,C.useRef)(null),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:provider-list-width`));return Number.isFinite(e)&&e>=140&&e<=420?e:190});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:provider-list-width`,String(O))},[O]);let A=()=>{(async()=>{try{let e=await fetch(`/api/subscriptions`);if(!e.ok)return;let t=await e.json();_(t.providers??[])}catch{}})()};(0,C.useEffect)(A,[t?.engine]);let j=g.find(e=>e.id===m)??null,M=g.map((e,t)=>({entry:e,index:t})).sort((e,t)=>Number(t.entry.connected)-Number(e.entry.connected)||e.index-t.index).map(e=>e.entry),N=oy((t?.models??[]).map(e=>e.id)),P=e=>sy(e,{engineReady:N}),F=M.filter(e=>e.connected),I=new Set(F.map(e=>e.id)),L=r.filter(e=>e.official===!0&&P(e)&&!I.has(e.provider)),R=r.filter(e=>e.official!==!0&&P(e)&&!I.has(e.provider)),z=r.filter(e=>e.official===!0&&!P(e)&&(e.modelCount??0)>0),B=e=>r.find(t=>t.provider===e)??null,V=(0,C.useRef)(!1),H=e=>{e.preventDefault(),V.current=!0;let t=e.clientX,n=O,r=e=>{V.current&&k(Math.min(420,Math.max(140,n+(e.clientX-t))))},i=()=>{V.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},U=r.find(e=>e.provider===o)??r[0]??null,W=b||U===null,ee=u===null,G=(e,t)=>Bf(i,e,t),K=e=>e.models.filter(t=>G(e.provider,t.id)).length,te=r.reduce((e,t)=>e+t.models.length,0),ne=r.reduce((e,t)=>e+K(t),0);if(!n){let e=(t?.engines??[]).find(e=>e.name===t?.engine);return(0,Q.jsx)(vy,{snapshot:t,engineOption:e})}let re=t=>{let n=!b&&u===null&&!j&&U?.provider===t.provider,r=n&&v!==t.provider,i=t.models;return(0,Q.jsxs)(`div`,{className:`prov-block${n?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${n?` prov-item-on`:``}`,"aria-expanded":i.length>0?r:void 0,onClick:()=>{n&&v!==t.provider?y(t.provider):(y(null),p(null),d(null),x(!1),w(!1),E(null),h(null),s(t.provider))},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[i.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${r?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,title:t.label?`${t.label}(${t.provider})`:t.provider,children:t.label??t.provider})]}),t.credential===`apiKey`?null:t.credential===`oauth`?(0,Q.jsx)(`span`,{className:`prov-item-state${t.oauth?.expired?` prov-item-state-warn`:` prov-item-state-on`}`,title:t.oauth?.expired?e(`订阅登录的凭据已过期:点开「订阅服务」重新登录`,`Subscription credential expired — open Subscriptions and sign in again`):e(`订阅已登录${t.oauth?.accountHint?`(账号 ${t.oauth.accountHint})`:``}:不需要 API key,走订阅额度`,`Signed in${t.oauth?.accountHint?` (${t.oauth.accountHint})`:``}: no API key needed, subscription quota is used`),children:t.oauth?.expired?e(`订阅已过期`,`Expired`):e(`订阅已登录`,`Signed in`)}):N.has(t.provider)?(0,Q.jsx)(`span`,{className:`prov-item-state prov-item-state-on`,title:e(`引擎已经报上来它的模型(凭证由引擎自己解析,不在这份配置里):能直接用,换模型用输入区的下拉`,`The engine already reports its models (credentials are resolved by the engine, not stored here): ready to use — switch models from the composer`),children:e(`引擎已可用`,`Ready`)}):(0,Q.jsx)(`span`,{className:`prov-item-state`,title:t.needsExtraConfig?e(`除了 API key 还要端点 / 云凭证:去「配置」里补齐`,`Needs an endpoint or cloud credentials on top of the API key — fill them in Config`):t.oauthOnly?e(`这个 provider 只支持订阅登录:去上面「订阅服务」里登录`,`This provider only supports subscription sign-in — use Subscriptions above`):e(`填一把 API key 就能用`,`Ready once you add an API key`),children:t.needsExtraConfig?e(`需额外配置`,`Needs setup`):t.oauthOnly?e(`仅订阅登录`,`Subscription only`):e(`无 key`,`No key`)})]}),(0,Q.jsxs)(wy,{open:r,children:[i.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t.models.length===0&&t.modelCount?e(`还没配 key 用不了:填一把就能用(引擎目录里 ${t.modelCount} 个模型)`,`Not usable yet — add an API key (${t.modelCount} models in the engine catalog)`):t.models.length===0?e(`这个 provider 下没有模型`,`No models under this provider`):e(`这个 provider 下没有启用的模型`,`No enabled models under this provider`)}):null,i.map(n=>{let i=G(t.provider,n.id);return(0,Q.jsxs)(`div`,{className:`prov-inline-row${r&&T===n.id&&U?.provider===t.provider?` prov-inline-row-on`:``}`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-inline-open`,"aria-current":r&&T===n.id&&U?.provider===t.provider,title:n.id,onClick:()=>{w(!1),E(n.id)},children:(0,Q.jsxs)(`span`,{className:`prov-inline-name`,children:[n.name,n.name===n.id?null:(0,Q.jsx)(`em`,{className:`prov-inline-id mono`,children:n.id})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`prov-model-toggle${i?` prov-model-toggle-on`:``}`,role:`switch`,"aria-checked":i,"aria-label":`${i?e(`停用`,`Disable`):e(`启用`,`Enable`)} ${n.name}`,title:i?e(`点击停用`,`Click to disable`):e(`点击启用`,`Click to enable`),onClick:()=>gu(t.provider,!i,n.id),children:(0,Q.jsx)(`span`,{className:`prov-dot`})})]},n.id)})]})]},t.provider)};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`prov-global-bar`,children:[(0,Q.jsx)(`span`,{className:`mono prov-global-path`,children:`~/.pi/agent/settings.json`}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已启用`,`Enabled`),` `,ne,`/`,te]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>gu(`*`,!0),disabled:i.length===0,title:e(`清空 enabledModels 白名单 —— pi 的语义是「不限制」即全部可用`,`Clear the enabledModels allowlist — for pi, no restriction means everything is available`),children:e(`启用全部模型`,`Enable all models`)})]}),(0,Q.jsxs)(`div`,{className:`prov-shell`,style:{"--prov-list-width":`${O}px`},children:[(0,Q.jsxs)(`aside`,{className:`prov-list`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-list-head prov-list-toggle`,"aria-expanded":c,title:c?e(`收起服务商列表`,`Collapse the provider list`):e(`展开服务商列表`,`Expand the provider list`),onClick:()=>l(e=>!e),children:(0,Q.jsxs)(`span`,{className:`prov-list-toggle-label`,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${c?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),e(`服务商`,`Providers`)]})}),(0,Q.jsx)(`div`,{className:`prov-list-body${c?``:` prov-list-body-closed`}`,children:(0,Q.jsxs)(`div`,{className:`prov-list-scroll`,children:[F.length+L.length+R.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`还没有服务商,点下面添加`,`No providers yet — add one below`)}):null,F.map(t=>{let n=B(t.id),r=n?.models??[],i=!b&&u===null&&m===t.id,a=i&&f===t.id;return(0,Q.jsxs)(`div`,{className:`prov-block${i?` prov-block-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`prov-item${i?` prov-item-on`:``}`,"aria-expanded":r.length>0?a:void 0,title:a?e(`收起模型`,`Collapse models`):e(`选中并展开模型`,`Select and expand models`),onClick:()=>{p(r.length>0&&!a?t.id:null),d(null),x(!1),w(!1),E(null),h(t.id)},children:[(0,Q.jsxs)(`span`,{className:`prov-item-name`,children:[r.length>0?(0,Q.jsx)(`span`,{className:`prov-caret${a?` prov-caret-open`:``}`,"aria-hidden":`true`}):(0,Q.jsx)(`span`,{className:`prov-caret prov-caret-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`prov-item-label`,children:t.name}),(0,Q.jsx)(`span`,{className:`prov-sub-badge`,children:e(`订阅`,`Sub`)})]}),(0,Q.jsx)(`span`,{className:`prov-item-state${t.connected?` prov-item-state-on`:``}`,children:t.connected?e(`已连接`,`Connected`):t.subscription?e(`订阅额度 · 未连接`,`Subscription quota · not connected`):e(`OAuth · 未连接`,`OAuth · not connected`)})]}),(0,Q.jsx)(wy,{open:a&&r.length>0,children:r.map(r=>{let i=G(t.id,r.id);return(0,Q.jsxs)(`div`,{className:`prov-inline-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`prov-inline-open${T===r.id&&m===t.id?` prov-inline-open-on`:``}`,title:r.id,onClick:()=>{n&&s(n.provider),x(!1),w(!1),E(r.id)},children:(0,Q.jsxs)(`span`,{className:`prov-inline-name`,children:[r.name,r.name===r.id?null:(0,Q.jsx)(`em`,{className:`prov-inline-id mono`,children:r.id})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`prov-model-toggle${i?` prov-model-toggle-on`:``}`,role:`switch`,"aria-checked":i,"aria-label":`${i?e(`停用`,`Disable`):e(`启用`,`Enable`)} ${r.name}`,title:i?e(`点击停用`,`Click to disable`):e(`点击启用`,`Click to enable`),onClick:()=>gu(t.id,!i,r.id),children:(0,Q.jsx)(`span`,{className:`prov-dot`})})]},r.id)})})]},t.id)}),L.map(re),R.map(re)]})}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny prov-add`,onClick:()=>{d(e=>e===null?`subscription`:null),x(!1),w(!1),E(null),h(null)},children:[`+ `,e(`添加服务商`,`Add a provider`)]})]}),(0,Q.jsx)(`div`,{className:`prov-resizer`,role:`separator`,"aria-orientation":`vertical`,title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:H,onDoubleClick:()=>k(190)}),(0,Q.jsx)(`section`,{className:`prov-detail${ee?` prov-detail-panel`:``}`,children:u===null?j&&!T&&!S?(0,Q.jsx)(by,{entry:j,enabledModels:i,canTest:B(j.id)!==null,onClose:()=>h(null),onChanged:()=>{A(),uu()},...j.id===`openai-codex`&&j.connected?{onImportModels:()=>{let e=B(j.id);e&&(s(e.provider),w(!0))}}:{}},j.id):T&&U?(0,Q.jsx)(hy,{provider:U,modelId:T,onClose:()=>E(null)},`${U.provider}/${T}`):S&&U?(0,Q.jsx)(cy,{provider:U,onClose:()=>w(!1),onImported:()=>{w(!1),A(),uu()}}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`prov-tabs`,children:[(0,Q.jsx)(`strong`,{className:`prov-detail-title`,children:b?e(`添加服务商`,`Add provider`):e(`配置`,`Config`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),U&&!b?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[K(U),`/`,U.models.length,` `,e(`启用`,`enabled`)]}),(0,Q.jsxs)(`label`,{className:`prov-switch`,title:e(`停用后这个 provider 的模型不再出现在选择器里`,`When disabled, this provider's models no longer appear in the picker`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a(U),onChange:e=>gu(U.provider,e.target.checked)}),(0,Q.jsx)(`span`,{className:`prov-switch-track`,"aria-hidden":`true`})]})]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary prov-save-button`,onClick:()=>D.current?.save(),children:e(`保存`,`Save`)}),U&&!b?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{let t=U.source===`builtin`?e(`(会从 ~/.pi/agent/models.json 里整条删掉)`,` (the entry is removed from ~/.pi/agent/models.json)`):``;window.confirm(e(`删除 provider「${U.provider}」?它的 api key 也会一起删。${t}`,`Delete provider “${U.provider}”? Its API key is deleted too.${t}`))&&(vu(U.provider),s(null))},children:e(`删除`,`Delete`)}):null]}),(0,Q.jsx)(gy,{formRef:D,initial:W?null:U,onSaved:e=>{x(!1),s(e)}},W?`new`:U?.provider)]}):(0,Q.jsx)(Sy,{tab:u,onTab:d,subscriptions:M,catalog:z,onPickSubscription:e=>{d(null),h(e)},onPickBuiltin:e=>{d(null),s(e)},onPickCustom:()=>{d(null),x(!0)}})})]})]})}function wy({open:e,children:t}){return(0,Q.jsx)(`div`,{className:`prov-models-collapse${e?` prov-models-collapse-open`:``}`,"aria-hidden":!e,inert:!e,children:(0,Q.jsx)(`div`,{className:`prov-models-collapse-inner`,children:(0,Q.jsx)(`div`,{className:`prov-models-inline`,children:t})})})}function Ty(){let[e,t]=(0,C.useState)(()=>Ph());return(0,C.useEffect)(()=>Rh(t),[]),{theme:e,setTheme:Lh}}function Ey(e){return[{id:`s`,label:`特小`,labelEn:`Extra small`,px:e-2},{id:`m`,label:`标准`,labelEn:`Default`,px:e},{id:`l`,label:`大`,labelEn:`Large`,px:e+2},{id:`xl`,label:`特大`,labelEn:`Extra large`,px:e+4}]}var Dy={chat:Ey(14),project:Ey(14),session:Ey(14)},Oy={chat:14,project:14,session:14};function ky(e,t=`chat`){return Dy[t].find(t=>t.id===e)??null}function Ay(e,t=`chat`){if(!Number.isFinite(e))return Oy[t];let n=Math.round(Math.min(Math.max(e,2),30)/2)*2;return Math.min(Math.max(n,2),30)}function jy(e,t=`chat`){if(e==null||e===``)return Oy[t];let n=Number(e);if(Number.isFinite(n))return Ay(n,t);let r=ky(e,t);return r?r.px:Oy[t]}function My(e){return`${Ay(e)}px`}function Ny(e,t=`chat`){let n=Ay(e,t);return Dy[t].find(e=>e.px===n)?.id??null}var Py={chat:12,project:13,session:12};function Fy(e){let t=Py[e];return[t-2,t,t+2,t+4]}function Iy(e,t=`chat`){if(!Number.isFinite(e))return Oy[t];let n=Math.min(Math.max(e,2),30),r=Fy(t).indexOf(n);return r>=0?Dy[t][r]?.px??Oy[t]:Ay(n+(Oy[t]-Py[t]),t)}function Ly(e,t=`chat`){let n=Number(e);return Number.isFinite(n)?Iy(n,t):jy(e,t)}var Ry=[{id:`narrow`,label:`窄`,labelEn:`Narrow`,px:720},{id:`normal`,label:`标准`,labelEn:`Default`,px:900},{id:`wide`,label:`宽`,labelEn:`Wide`,px:1100},{id:`full`,label:`满宽`,labelEn:`Full width`,px:0}],zy=Ry.find(e=>e.id===`normal`)?.px??900,By=`pop-agent.chat-font.v2`,Vy=`pop-agent.chat-font`,Hy=`pop-agent.chat-width`,Uy=`pop-agent:chat-display`;function Wy(e){return Ry.find(t=>t.id===e)??null}function Gy(e){return jy(e,`chat`)}function Ky(e){if(typeof localStorage>`u`)return e;try{let t=localStorage.getItem(By);if(t!==null&&t!==``)return Gy(t);let n=localStorage.getItem(Vy);if(n!==null&&n!==``){let e=Ly(n,`chat`);return localStorage.setItem(By,String(e)),e}return e}catch{return e}}function qy(e){if(e===null||e===``)return zy;let t=Wy(e);return t?t.px:/^\d+$/.test(e.trim())?Jy(Number(e)):zy}function Jy(e){if(!Number.isFinite(e)||e<=0)return 0;let t=Math.round((e-360)/20);return 360+Math.max(0,t)*20}function Yy(){let e=e=>360+Math.max(1,Math.floor((e-360)/20))*20,t=()=>{let t=typeof window>`u`?1440:window.innerWidth||1440;return e(Math.max(720,t-320))};if(typeof document>`u`)return t();let n=document.querySelector(`.workspace`);if(!(n instanceof HTMLElement))return t();let r=getComputedStyle(n),i=(parseFloat(r.paddingLeft)||0)+(parseFloat(r.paddingRight)||0),a=n.clientWidth-i;return a>380?e(a):t()}function Xy(e,t){return{size:My(e),maxWidth:t>0?`${t}px`:`100%`}}function Zy(){return Ky(Oy.chat)}function Qy(){return qy(typeof localStorage>`u`?null:localStorage.getItem(Hy))}function $y(e,t){let n=Xy(e,t),r=document.documentElement.style;r.setProperty(`--chat-font-size`,n.size),r.setProperty(`--chat-max-width`,n.maxWidth),document.documentElement.dataset.chatWidth=t>0?`custom`:`full`,window.dispatchEvent(new CustomEvent(Uy,{detail:{font:e,width:t}}))}function eb(){$y(Zy(),Qy())}function tb(e,t){try{localStorage.setItem(e,t)}catch{}}function nb(e){let t=Ay(e,`chat`);tb(By,String(t)),$y(t,Qy())}function rb(e){let t=Jy(e);tb(Hy,String(t)),$y(Zy(),t)}function ib(e){let t=t=>{let n=t.detail;n&&e(n)},n=t=>{if(t.key!==By&&t.key!==Hy)return;let n={font:Zy(),width:Qy()};$y(n.font,n.width),e(n)};return window.addEventListener(Uy,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Uy,t),window.removeEventListener(`storage`,n)}}function ab(){let[e,t]=(0,C.useState)(()=>({font:Zy(),width:Qy()}));return(0,C.useEffect)(()=>ib(t),[]),{font:e.font,width:e.width,setFont:nb,setWidth:rb}}var ob=`pop-agent.appbar-scale.v2`,sb=`pop-agent.appbar-scale`,cb=1.15,lb=[{id:`s`,label:`特小`,labelEn:`Tiny`,percent:60},{id:`m`,label:`紧凑`,labelEn:`Compact`,percent:75},{id:`l`,label:`标准`,labelEn:`Standard`,percent:100},{id:`xl`,label:`特大`,labelEn:`Extra large`,percent:120}];function ub(e){return Number.isFinite(e)?Math.round(Math.min(Math.max(e,60),120)/5)*5:100}function db(e){if(e==null||e===``)return 100;let t=Number(e);if(Number.isFinite(t))return ub(t);let n=lb.find(t=>t.id===e);return n?n.percent:100}var fb={s:70,m:85,l:100,xl:115};function pb(e){let t=Number(e);return ub((Number.isFinite(t)?t:fb[e]??100)/cb)}function mb(e){let t=ub(e)/100*cb;return String(Math.round(t*1e4)/1e4)}function hb(e){let t=ub(e);return lb.find(e=>e.percent===t)?.id??null}var gb=`pop-agent:appbar-scale`;function _b(){if(typeof localStorage>`u`)return 100;try{let e=localStorage.getItem(ob);if(e!==null&&e!==``)return db(e);let t=localStorage.getItem(sb);if(t===null||t===``)return 100;let n=pb(t);try{localStorage.setItem(ob,String(n))}catch{}return n}catch{return 100}}function vb(){return _b()}function yb(e){let t=ub(e);document.documentElement.style.setProperty(`--appbar-scale`,mb(t)),window.dispatchEvent(new CustomEvent(gb,{detail:t}))}function bb(){yb(_b())}function xb(e){let t=ub(e);try{localStorage.setItem(ob,String(t))}catch{}yb(t)}function Sb(e){let t=t=>{let n=t.detail;typeof n==`number`&&e(n)},n=t=>{if(t.key!==ob)return;let n=_b();yb(n),e(n)};return window.addEventListener(gb,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(gb,t),window.removeEventListener(`storage`,n)}}function Cb(){let[e,t]=(0,C.useState)(vb);return(0,C.useEffect)(()=>Sb(t),[]),{percent:e,setPercent:xb}}var wb=`pop-agent.sidebar-project-font.v2`,Tb=`pop-agent.sidebar-project-font`,Eb=`pop-agent.sidebar-session-font.v2`,Db=`pop-agent.sidebar-session-font`,Ob=`pop-agent:sidebar-font`;function kb(e,t,n){if(typeof localStorage>`u`)return Oy[n];try{let r=localStorage.getItem(e);if(r!==null&&r!==``)return jy(r,n);let i=localStorage.getItem(t);if(i!==null&&i!==``){let t=Ly(i,n);return localStorage.setItem(e,String(t)),t}return Oy[n]}catch{return Oy[n]}}function Ab(){return kb(wb,Tb,`project`)}function jb(){return kb(Eb,Db,`session`)}function Mb(){return{project:Ab(),session:jb()}}function Nb(e){let t=document.documentElement.style;t.setProperty(`--side-project-font-size`,My(e.project)),t.setProperty(`--side-session-font-size`,My(e.session)),window.dispatchEvent(new CustomEvent(Ob,{detail:e}))}function Pb(){Nb(Mb())}function Fb(e,t){try{localStorage.setItem(e,t)}catch{}}function Ib(e){let t=Ay(e,`project`);Fb(wb,String(t)),Nb({project:t,session:jb()})}function Lb(e){let t=Ay(e,`session`);Fb(Eb,String(t)),Nb({project:Ab(),session:t})}function Rb(e){let t=t=>{let n=t.detail;n&&e(n)},n=t=>{if(t.key!==wb&&t.key!==Eb)return;let n=Mb();Nb(n),e(n)};return window.addEventListener(Ob,t),window.addEventListener(`storage`,n),()=>{window.removeEventListener(Ob,t),window.removeEventListener(`storage`,n)}}function zb(){let[e,t]=(0,C.useState)(Mb);return(0,C.useEffect)(()=>Rb(t),[]),{...e,setProject:Ib,setSession:Lb}}function Bb(){return bp(Sr,Er,wr)}var Vb=192,Hb=8388608,Ub=409600;function Wb(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=new Image;i.onload=()=>{URL.revokeObjectURL(r),t(i)},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(J(`这张图片打不开,换一张 PNG / JPG / WebP 试试`,`This image cannot be opened — try a PNG / JPG / WebP`)))},i.src=r})}async function Gb(e){if(!e.type.startsWith(`image/`))throw Error(J(`这不是图片文件`,`This is not an image file`));if(e.size>Hb)throw Error(J(`图片太大了(请选 8MB 以内的)`,`The image is too big (pick one under 8MB)`));let t=await Wb(e),n=Math.min(t.naturalWidth||t.width,t.naturalHeight||t.height);if(!n)throw Error(J(`这张图片打不开,换一张 PNG / JPG / WebP 试试`,`This image cannot be opened — try a PNG / JPG / WebP`));let r=document.createElement(`canvas`);r.width=Vb,r.height=Vb;let i=r.getContext(`2d`);if(!i)throw Error(J(`这个浏览器画不了图(canvas 不可用)`,`This browser cannot draw images (canvas is unavailable)`));let a=((t.naturalWidth||t.width)-n)/2,o=((t.naturalHeight||t.height)-n)/2;i.imageSmoothingQuality=`high`,i.drawImage(t,a,o,n,n,0,0,Vb,Vb);let s=r.toDataURL(`image/webp`,.92),c=s.startsWith(`data:image/webp`)?s:r.toDataURL(`image/png`);if(c.length>Ub)throw Error(J(`这张图压缩后还是太大,换一张简单点的图试试`,`This image is still too big after compression — try a simpler one`));return c}var Kb=[...Br],qb=`pop-agent.statusbar-order.v1`,Jb=`pop-agent:statusbar-order`,Yb=new Set(Kb);function Xb(e){let t=Array.isArray(e)?e:[],n=[];for(let e of t)typeof e==`string`&&Yb.has(e)&&(n.includes(e)||n.push(e));for(let e of Kb)n.includes(e)||n.push(e);return n}function Zb(){let e=Yr(qb);if(!e)return[...Kb];try{return Xb(JSON.parse(e))}catch{return[...Kb]}}function Qb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function $b(e){let t=Xb(e);return Xr(qb,JSON.stringify(t)),window.dispatchEvent(new CustomEvent(Jb,{detail:t})),t}function ex(e,t,n){let r=Math.max(0,Math.min(t,e.length-1)),i=Math.max(0,Math.min(n,e.length-1));if(r===i)return[...e];let a=[...e],[o]=a.splice(r,1);return o&&a.splice(i,0,o),a}function tx(){let[e,t]=(0,C.useState)(()=>Zb());return(0,C.useEffect)(()=>{let e=e=>{let n=Xb(e);t(e=>Qb(e,n)?e:n)},n=t=>e(t.detail),r=t=>{if(t.key===null||t.key===qb){if(t.key===null)e(null);else try{e(t.newValue?JSON.parse(t.newValue):null)}catch{e(null)}}};return window.addEventListener(Jb,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(Jb,n),window.removeEventListener(`storage`,r)}},[]),[e,e=>t($b(e))]}function nx({name:e}){let t={viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0};return e===`models`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`2.8`,y:`5.4`,width:`10.4`,height:`7.6`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.4V3.4`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.6`,r:`0.85`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`9.2`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`9.2`,r:`0.8`,fill:`currentColor`,stroke:`none`})]}):e===`skills`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`5.9`,width:`11.6`,height:`7.4`,rx:`1.7`}),(0,Q.jsx)(`path`,{d:`M6.1 5.9V4.3c0-.6.5-1.1 1.1-1.1h1.6c.6 0 1.1.5 1.1 1.1v1.6`}),(0,Q.jsx)(`path`,{d:`M2.2 9.3h11.6`})]}):e===`push`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`path`,{d:`M4.3 11.1V7.7a3.7 3.7 0 1 1 7.4 0v3.4l1.1 1.5H3.2l1.1-1.5Z`}),(0,Q.jsx)(`path`,{d:`M6.5 14.1a1.6 1.6 0 0 0 3 0`})]}):e===`plugins`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`4.2`,y:`6.6`,width:`7.6`,height:`6.2`,rx:`1.6`}),(0,Q.jsx)(`path`,{d:`M6.2 6.6V3.9M9.8 6.6V3.9`}),(0,Q.jsx)(`path`,{d:`M8 12.8v1.6`})]}):e===`voice`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`6.2`,y:`2.2`,width:`3.6`,height:`6.6`,rx:`1.8`}),(0,Q.jsx)(`path`,{d:`M4.4 8.2a3.6 3.6 0 0 0 7.2 0`}),(0,Q.jsx)(`path`,{d:`M8 11.8v2`}),(0,Q.jsx)(`path`,{d:`M12.6 4.2a4.4 4.4 0 0 1 0 4.6M3.4 4.2a4.4 4.4 0 0 0 0 4.6`})]}):e===`agents`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`5.6`,width:`9.6`,height:`7.4`,rx:`2.2`}),(0,Q.jsx)(`path`,{d:`M8 5.6V3.3`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.5`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`8.6`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`8.6`,r:`0.7`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M6.2 10.9h3.6`})]}):e===`computer`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`1.8`,y:`2.6`,width:`12.4`,height:`8.6`,rx:`1.3`}),(0,Q.jsx)(`path`,{d:`M5.6 13.6h4.8M8 11.2v2.4`})]}):e===`cron`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`5.8`}),(0,Q.jsx)(`path`,{d:`M8 4.5V8l2.5 1.5`})]}):e===`mcp`?(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`rect`,{x:`1.9`,y:`3.2`,width:`8.6`,height:`3.9`,rx:`1.1`}),(0,Q.jsx)(`rect`,{x:`1.9`,y:`8.9`,width:`8.6`,height:`3.9`,rx:`1.1`}),(0,Q.jsx)(`circle`,{cx:`4`,cy:`5.15`,r:`0.6`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`4`,cy:`10.85`,r:`0.6`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`path`,{d:`M10.5 5.15h1.4a1.2 1.2 0 0 1 1.2 1.2v3.3a1.2 1.2 0 0 0 1.2 1.2H15`})]}):(0,Q.jsxs)(`svg`,{...t,children:[(0,Q.jsx)(`path`,{d:`M2.6 5.4h10.8M2.6 10.6h10.8`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`5.4`,r:`1.7`,fill:`var(--bg-elev)`}),(0,Q.jsx)(`circle`,{cx:`10.2`,cy:`10.6`,r:`1.7`,fill:`var(--bg-elev)`})]})}var rx=[`ui`,`general`,`appearance`,`theme`,`language`,`shortcuts`,`remote`],ix=`pop-agent.settings-tab-order.v1`,ax=`pop-agent:settings-tab-order`,ox=new Set(rx);function sx(e){let t=Array.isArray(e)?e:[],n=[];for(let e of t)typeof e==`string`&&ox.has(e)&&(n.includes(e)||n.push(e));for(let e of rx)n.includes(e)||n.push(e);return n}function cx(e){if(!e)return[...rx];try{return sx(JSON.parse(e))}catch{return[...rx]}}function lx(){return cx(Yr(ix))}function ux(e){let t=sx(e);return Xr(ix,JSON.stringify(t)),typeof window<`u`&&window.dispatchEvent(new CustomEvent(ax,{detail:t})),t}function dx(){return lx()[0]??rx[0]}function fx(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function px(e,t,n){let r=Math.max(0,Math.min(t,e.length-1)),i=Math.max(0,Math.min(n,e.length-1));if(r===i)return[...e];let a=[...e],[o]=a.splice(r,1);return o&&a.splice(i,0,o),a}function mx(e,t,n){let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(Math.round(n),r.length)),a=[...r];return a.splice(i,0,t),a}function hx(e,t,n,r){let i=e.indexOf(t),a=0;for(let t=0;t<e.length;t+=1){if(t===i)continue;let e=r[t];e&&n>e.left+e.width/2&&(a+=1)}return a}function gx(e,t,n){let r=new Map;for(let i of e){let e=t.indexOf(i),a=n[e];e<0||!a||r.set(i,a.left)}return r}function _x(){let[e,t]=(0,C.useState)(()=>lx());return(0,C.useEffect)(()=>{let e=e=>{let n=sx(e);t(e=>fx(e,n)?e:n)},n=t=>e(t.detail),r=t=>{(t.key===null||t.key===ix)&&e(cx(t.newValue))};return window.addEventListener(ax,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(ax,n),window.removeEventListener(`storage`,r)}},[]),[e,(0,C.useCallback)(e=>{let n=ux(e);t(e=>fx(e,n)?e:n)},[])]}var vx=5,yx=350,bx=`is-tab-sort-dragging`;function xx({order:e,active:t,label:n,onSelect:r,onOrderChange:i}){let a=(0,C.useRef)(null),o=(0,C.useRef)(null),[s,c]=(0,C.useState)(null),l=(0,C.useRef)(null),u=(0,C.useRef)(!1),d=(0,C.useRef)(null),f=e=>{l.current=e,c(e),e?document.documentElement.classList.add(bx):document.documentElement.classList.remove(bx)};(0,C.useEffect)(()=>()=>{document.documentElement.classList.remove(bx),d.current!==null&&window.clearTimeout(d.current)},[]);let p=()=>{let t=a.current;if(!t)return null;let n=[];for(let r of e){let e=t.querySelector(`[data-settings-tab="${r}"]`);if(!e)return null;let i=e.getBoundingClientRect();n.push({left:i.left,width:i.width})}return n},m=(e,t)=>{try{e?.hasPointerCapture(t)&&e.releasePointerCapture(t)}catch{}},h=(e,t)=>{if(!(e.button!==0||l.current)&&!Tf()){o.current={pointerId:e.pointerId,id:t,startX:e.clientX,startY:e.clientY};try{e.currentTarget.setPointerCapture(e.pointerId)}catch{}}},g=t=>{let n=o.current;if(!n||n.pointerId!==t.pointerId)return;let r=t.clientX-n.startX,i=t.clientY-n.startY,a=l.current;if(!a){if(Math.max(Math.abs(r),Math.abs(i))<vx)return;if(Math.abs(i)>Math.abs(r)){o.current=null,m(t.currentTarget,t.pointerId);return}let a=p(),s=e.indexOf(n.id);if(!a||s<0){o.current=null;return}t.preventDefault(),f({id:n.id,fromIndex:s,slots:a,toIndex:s,dx:r});return}t.preventDefault();let s=a.slots[a.fromIndex];if(!s)return;let c=s.left+s.width/2+r;f({...a,dx:r,toIndex:hx(e,a.id,c,a.slots)})},_=t=>{let n=l.current;o.current=null,n&&(f(null),u.current=!0,d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{u.current=!1},yx),t&&i(mx(e,n.id,n.toIndex)))},v=e=>{o.current?.pointerId===e.pointerId&&(m(e.currentTarget,e.pointerId),_(!0))},y=e=>{o.current?.pointerId===e.pointerId&&(m(e.currentTarget,e.pointerId),_(!1))},b=t=>{let n=t.key===`ArrowRight`?1:t.key===`ArrowLeft`?-1:0;if(!n)return;let o=t.target.closest(`[data-settings-tab]`)?.dataset.settingsTab,s=o?e.indexOf(o):-1;if(s<0)return;if(t.preventDefault(),t.altKey){let t=s+n;if(t<0||t>e.length-1)return;i(px(e,s,t));return}let c=e[(s+n+e.length)%e.length];c&&(r(c),a.current?.querySelector(`[data-settings-tab="${c}"]`)?.focus())},x=s?mx(e,s.id,s.toIndex):e,S=s?gx(e,x,s.slots):null,w=t=>{if(!s||!S)return 0;if(t===s.id)return s.dx;let n=s.slots[e.indexOf(t)]?.left,r=S.get(t);return n===void 0||r===void 0?0:r-n};return(0,Q.jsx)(`div`,{ref:a,className:`settings-tabs`,role:`tablist`,onKeyDown:b,children:e.map(e=>{let i=s?.id===e,a=[`settings-tab`,t===e?`settings-tab-on`:``,s?`settings-tab-reordering`:``,i?`settings-tab-dragging`:``].filter(Boolean).join(` `),o=w(e);return(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"data-settings-tab":e,"aria-selected":t===e,tabIndex:t===e?0:-1,className:a,draggable:!1,style:s?{transform:`translate3d(${o}px, 0, 0)`,transition:i?`none`:void 0}:void 0,onPointerDown:t=>h(t,e),onPointerMove:g,onPointerUp:v,onPointerCancel:y,onClick:()=>{u.current||r(e)},children:n(e)},e)})})}var Sx={maxFailures:3,lockMinutes:30};function Cx(e){return{maxFailures:typeof e?.maxFailures==`number`?e.maxFailures:Sx.maxFailures,lockMinutes:typeof e?.lockMinutes==`number`?e.lockMinutes:Sx.lockMinutes}}async function wx(e){try{let t=await e.json();return typeof t==`object`&&t?t:null}catch{return null}}function Tx(e,t){return typeof e?.error==`string`&&e.error!==``?e.error:J(`请求失败(HTTP ${t})`,`Request failed (HTTP ${t})`)}async function Ex(){try{let e=await fetch(`/api/auth/password`,{cache:`no-store`,credentials:`same-origin`}),t=await wx(e);return!e.ok||t?.ok!==!0?{ok:!1,error:Tx(t,e.status)}:{ok:!0,set:t.set===!0,guard:Cx(t)}}catch{return{ok:!1,error:J(`网络异常,请重试`,`Network error — try again`)}}}async function Dx(e,t){try{let n=await fetch(`/api/auth/password`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t===void 0?{password:e}:{password:e,currentPassword:t}),cache:`no-store`,credentials:`same-origin`}),r=await wx(n);return!n.ok||r?.ok!==!0?{ok:!1,error:Tx(r,n.status)}:{ok:!0}}catch{return{ok:!1,error:J(`网络异常,请重试`,`Network error — try again`)}}}async function Ox(){try{let e=await fetch(`/api/auth/activity`,{cache:`no-store`,credentials:`same-origin`}),t=await wx(e);if(!e.ok||t?.ok!==!0)return{ok:!1,error:Tx(t,e.status)};let n=Array.isArray(t.entries)?t.entries:[],r=[];for(let e of n){if(typeof e!=`object`||!e)continue;let t=e,n=t.kind;(n===`success`||n===`failure`||n===`locked`)&&typeof t.at==`number`&&typeof t.address==`string`&&r.push({at:t.at,address:t.address,kind:n,...typeof t.attempts==`number`?{attempts:t.attempts}:{},...typeof t.lockMinutes==`number`?{lockMinutes:t.lockMinutes}:{}})}return{ok:!0,entries:r}}catch{return{ok:!1,error:J(`网络异常,请重试`,`Network error — try again`)}}}async function kx(e){try{let t=await fetch(`/api/auth/guard`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),cache:`no-store`,credentials:`same-origin`}),n=await wx(t);return!t.ok||n?.ok!==!0?{ok:!1,error:Tx(n,t.status)}:{ok:!0,guard:Cx(n)}}catch{return{ok:!1,error:J(`网络异常,请重试`,`Network error — try again`)}}}function Ax(){let e=Y(),[t,n]=xc(),r=oc(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null);return(0,C.useEffect)(()=>{if(!i)return;let o=null,c=o=>{if(Gs(o)){s(e(`「${cc(o,r)}」会被浏览器先吃掉(比如开关标签页/窗口),换个组合`,`${cc(o,r)} is reserved by the browser — pick another combo`));return}let c=ic(t,o,i);if(c){let t=ac(c);s(e(`「${cc(o,r)}」已经给「${t.zh}」了,先把它清掉或换一个`,`${cc(o,r)} is already used by “${t.en}” — clear it or pick another`))}else n({...t,[i]:o}),a(null),s(null)},l=e=>{if(zs(e),e.preventDefault(),e.stopPropagation(),e.key===`Escape`&&!e.metaKey&&!e.ctrlKey&&!e.altKey){a(null),s(null),o=null;return}if(qs(e)){o=e.code??``;return}o=null;let t=Hs(e);t&&c(t)},u=e=>{if(zs(e),o===null||(e.code??``)!==o)return;o=null,e.preventDefault(),e.stopPropagation();let t=Js(e);t&&c(t)},d=e=>{e.target?.closest?.(`.shortcut-row`)||a(null)};return window.addEventListener(`keydown`,l,!0),window.addEventListener(`keyup`,u,!0),window.addEventListener(`pointerdown`,d,!0),()=>{window.removeEventListener(`keydown`,l,!0),window.removeEventListener(`keyup`,u,!0),window.removeEventListener(`pointerdown`,d,!0)}},[i,t,n,r,e]),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`快捷键`,`Shortcuts`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:r?e("macOS:Mod = ⌘;想要真正的 ⌃ 就录 ⌃ + 非字母键(如 ⌃`)","macOS: Mod = ⌘; for a real ⌃ combo record ⌃ plus a non-letter key (e.g. ⌃`)"):e(`这里写 Ctrl 的地方,macOS 上是 ⌘`,`Where it says Ctrl, macOS uses ⌘`)})]}),(0,Q.jsx)(`div`,{className:`shortcuts-list`,children:ws.map(o=>{let c=t[o.id],l=i===o.id;return(0,Q.jsxs)(`div`,{className:`shortcut-row${l?` shortcut-row-rec`:``}`,children:[(0,Q.jsxs)(`div`,{className:`shortcut-info`,children:[(0,Q.jsx)(`span`,{className:`shortcut-name`,children:e(o.label,o.labelEn)}),o.hint?(0,Q.jsx)(`span`,{className:`shortcut-hint`,children:e(o.hint,o.hintEn??o.hint)}):null]}),(0,Q.jsxs)(`div`,{className:`shortcut-keys`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-combo${l?` shortcut-combo-rec`:``}${c?``:` shortcut-combo-empty`}`,"aria-label":e(`${o.label} 的快捷键`,`${o.labelEn} shortcut`),onClick:()=>{s(null),a(l?null:o.id)},title:l?e(`按 Esc 取消`,`Press Esc to cancel`):e(`点一下,然后按新的组合键(也可以只按一颗修饰键 / F1–F12)`,`Click, then press a combo (or a single modifier / F1–F12)`),children:l?e(`按下组合键 / 单键…`,`Press a combo or a single key…`):c?cc(c,r):e(`未设置`,`Unbound`)}),(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-clear`,disabled:!c,onClick:()=>{a(null),s(null),n({...t,[o.id]:null})},title:e(`清除这个快捷键(不设置)`,`Clear this shortcut (unbound)`),"aria-label":e(`清除「${o.label}」的快捷键`,`Clear ${o.labelEn} shortcut`),children:`✕`})]})]},o.id)})}),o?(0,Q.jsx)(`div`,{className:`shortcut-notice`,role:`status`,children:o}):null,(0,Q.jsxs)(`div`,{className:`shortcut-foot`,children:[(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`组合键要带 ⌘/Ctrl 或 Alt。也可以绑单键:单独一颗修饰键(右⌘ / 右⌥ / ⌃ / Alt)或功能键 F1–F12;裸字母、数字不行(在输入框里打字就会触发动作)。同一组合只能给一个动作。`,`Combos need ⌘/Ctrl or Alt. Single keys are allowed too: one modifier alone (right ⌘ / right ⌥ / ⌃ / Alt) or a function key F1–F12; bare letters and digits are not (typing would trigger actions). Each combo belongs to one action.`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>gc(),title:e(`浮层列出当前所有绑定(也可以按 ⌘/ 打开)`,`Lists every binding in an overlay (⌘/ works too)`),children:e(`打开速查表`,`Open cheat sheet`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{a(null),s(null),n(Xs())},children:e(`恢复默认设置`,`Restore defaults`)})]})]})}var jx=`/favicon.svg?v=9`;function Mx(){let[e,t]=(0,C.useState)(dx),[n,r]=_x(),i=Y(),a={ui:i(`界面`,`Interface`),general:i(`对话`,`Chat`),appearance:i(`外观`,`Appearance`),theme:i(`主题`,`Theme`),language:i(`语言`,`Language`),shortcuts:i(`快捷键`,`Shortcuts`),remote:i(`远程`,`Remote`)},o=n.includes(e)?e:n[0]??`ui`;return(0,Q.jsxs)(`div`,{className:`settings-stack`,children:[(0,Q.jsx)(xx,{order:n,active:o,label:e=>a[e],onSelect:e=>t(e),onOrderChange:r}),o===`general`?(0,Q.jsx)(Ix,{}):o===`appearance`?(0,Q.jsx)($x,{}):o===`theme`?(0,Q.jsx)(eS,{}):o===`language`?(0,Q.jsx)(Fx,{}):o===`shortcuts`?(0,Q.jsx)(Ax,{}):o===`remote`?(0,Q.jsx)(Px,{}):(0,Q.jsx)(zx,{})]})}function Nx(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Px(){let e=Y(),t=Jc(),n=typeof location>`u`?``:location.host,[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(Sx),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)([]),[y,b]=(0,C.useState)(``),[x,S]=(0,C.useState)(!1),w=(0,C.useCallback)(()=>{S(!0),Ox().then(e=>{S(!1),e.ok?(b(``),v(e.entries)):b(e.error)})},[]);(0,C.useEffect)(()=>{w()},[w]),(0,C.useEffect)(()=>{Ex().then(e=>{e.ok?(i(e.set),m(e.guard),o(``)):o(e.error)})},[t]);let T=()=>{g(!0),kx(p).then(t=>{g(!1),t.ok?(m(t.guard),Z({text:e(`已保存:连续错 ${t.guard.maxFailures} 次,暂停 ${t.guard.lockMinutes} 分钟`,`Saved: pause ${t.guard.lockMinutes} min after ${t.guard.maxFailures} wrong tries`)})):Z({text:t.error})})},E=()=>{let n=s.trim();n.length<4?Z({text:e(`密码至少 4 位`,`Use at least 4 characters`)}):t&&r&&l===``?Z({text:e(`先输入当前密码`,`Enter the current password first`)}):(f(!0),Dx(n,t?l:void 0).then(t=>{f(!1),t.ok?(i(!0),o(``),c(``),u(``),Z({text:e(`访问密码已保存,立即生效`,`Password saved — active now`)})):Z({text:t.error})}))},D=r===null?a===``?e(`读取中…`,`Loading…`):a:r?e(`已设置`,`Set`):e(`未设置`,`Not set`);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`访问方式`,`Access`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:t?e(`通过 ${n} 远程访问`,`Remote — ${n}`):e(`本机访问(免密)`,`This machine (no password)`)})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:t?e(`远程访问必须输密码;域名 / 外网 IP / 局域网 IP 都能访问。这里改密码要先输入当前密码,登录保护与登录活动也在这里查看(活动里的 IP 已打码)。`,`Remote access always needs the password. Changing it here needs the current password. Login protection and login activity are here too (IPs in the activity list are masked).`):e(`本机直连(127.0.0.1)不需要密码。设一个之后,远程用任意域名 / 局域网 IP / 隧道地址打开都要先输它。`,`The local address (127.0.0.1) needs no password. Once set, any remote address — domain, LAN IP or tunnel — will ask for it.`)}),t?(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>Yc(),children:e(`退出登录`,`Sign out`)}),(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`清掉这台浏览器上的登录 cookie(有效期 7 天,每次访问顺延)。`,`Clears the login cookie in this browser (valid 7 days, renewed on every visit).`)})]}):null,(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`访问密码`,`Password`)}),t&&r?(0,Q.jsx)(`input`,{className:`settings-input settings-password-input`,type:`password`,value:l,autoComplete:`current-password`,placeholder:e(`当前密码`,`Current password`),"aria-label":e(`当前密码`,`Current password`),onChange:e=>u(e.target.value)}):null,(0,Q.jsx)(`input`,{className:`settings-input settings-password-input`,type:`password`,value:s,autoComplete:`new-password`,placeholder:r?e(`输入新密码以修改(至少 4 位)`,`New password to change it (min 4)`):e(`设置访问密码(至少 4 位)`,`Set a password (min 4)`),onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!d&&E()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:E,disabled:d||s.trim()===``,children:d?e(`保存中…`,`Saving…`):e(`保存`,`Save`)}),(0,Q.jsxs)(`span`,{className:`settings-hint`,children:[e(`当前:`,`Now: `),D]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`密码存在数据目录的 password 文件里(默认 ~/.pop-agent/password),保存后立即生效,不用重启。忘了就删掉这个文件再重启,或者启动时带 pop -P <新密码>(也会写进去)。`,`Stored in the data directory's password file (default ~/.pop-agent/password). It applies immediately — no restart. Forgot it? Delete that file and restart, or start with pop -P <new password> (that is saved too).`)}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`登录保护`,`Login protection`)}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`连续错`,`After`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:20,value:p.maxFailures,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&m(e=>({...e,maxFailures:Math.min(20,Math.max(1,Math.round(t)))}))}}),(0,Q.jsx)(`span`,{children:e(`次后,暂停`,`wrong tries, pause for`)})]}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:1440,value:p.lockMinutes,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&m(e=>({...e,lockMinutes:Math.min(1440,Math.max(1,Math.round(t)))}))}}),(0,Q.jsx)(`span`,{children:e(`分钟`,`minutes`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:T,disabled:h,children:h?e(`保存中…`,`Saving…`):e(`保存`,`Save`)})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`同一个来源连续输错密码到达这个次数,就暂停一段时间,不再比对密码(挡在线爆破)。默认 3 次 / 30 分钟;锁会落盘,重启服务也不会放行。填 1–20 次、1–1440 分钟。`,`After this many wrong passwords from the same source, sign-in is paused for a while (anti-brute-force). Default: 3 tries / 30 minutes. Locks are persisted across restarts. Range: 1–20 tries, 1–1440 minutes.`)}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsx)(`span`,{className:`settings-field`,children:e(`登录活动`,`Login activity`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:w,disabled:x,children:x?e(`刷新中…`,`Refreshing…`):e(`刷新`,`Refresh`)}),(0,Q.jsx)(`span`,{className:`settings-hint`,children:e(`最近 200 条,最新的在最前面。`,`Latest 200 events, newest first.`)})]}),y===``?null:(0,Q.jsx)(`div`,{className:`settings-hint`,children:y}),(0,Q.jsx)(`div`,{className:`settings-activity`,children:_.length===0?(0,Q.jsx)(`div`,{className:`settings-hint`,children:x?e(`读取中…`,`Loading…`):e(`还没有登录记录。`,`No sign-in activity yet.`)}):_.map(t=>(0,Q.jsxs)(`div`,{className:`settings-activity-row settings-activity-${t.kind}`,children:[(0,Q.jsx)(`span`,{className:`settings-activity-time`,children:Nx(t.at)}),(0,Q.jsx)(`span`,{className:`settings-activity-ip`,children:t.address}),(0,Q.jsx)(`span`,{className:`settings-activity-kind`,children:t.kind===`success`?e(`登录成功`,`Signed in`):t.kind===`locked`?e(`连续错 ${t.attempts??0} 次,已暂停 ${t.lockMinutes??0} 分钟`,`${t.attempts??0} wrong tries — paused ${t.lockMinutes??0} min`):e(`密码错误(连续第 ${t.attempts??1} 次)`,`Wrong password (try ${t.attempts??1})`)})]},`${t.at}-${t.address}-${t.kind}`))})]})]})}function Fx(){let e=Y(),{language:t,setLanguage:n}=Ae();return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`语言`,`Language`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`界面文字用哪种语言`,`Which language the interface uses`)})]}),(0,Q.jsx)(`div`,{className:`settings-langs`,children:he.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${t===r.id?` settings-lang-on`:``}`,title:r.label,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-language`,value:r.id,checked:t===r.id,onChange:()=>n(r.id)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:r.label}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.id===`en`?e(`默认`,`Default`):e(`浏览器是中文时默认`,`Default when your browser is Chinese`)})]},r.id))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;默认英文,浏览器语言是中文的首次打开用中文。`,`Takes effect immediately, nothing to save. The choice is stored on this machine (localStorage) and survives reloads; it does not touch the server or your other devices. English is the default — a Chinese browser gets Chinese on first launch.`)})]})})}function Ix(){let e=Y(),t=Ro(e=>e.snapshot),n=t?.settings.thinkCount??5,r=t?.settings.thinkTimeoutSec??20,[i,a]=(0,C.useState)({count:n,timeoutSec:r}),[o,s]=(0,C.useState)(!1);return(0,C.useEffect)(()=>{o||a({count:n,timeoutSec:r})},[n,r,o]),(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Kx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`想想`,`Think`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`下一步建议`,`Next-step suggestions`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny settings-head-action`,onClick:()=>{bu({thinkCount:i.count,thinkTimeoutSec:i.timeoutSec}),s(!1)},disabled:!o,children:e(`保存`,`Save`)})]}),(0,Q.jsxs)(`div`,{className:`settings-row`,children:[(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`一次生成`,`Generate`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:5,value:i.count,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&(a(e=>({...e,count:Math.min(5,Math.max(1,Math.round(t)))})),s(!0))}}),(0,Q.jsx)(`span`,{children:e(`条`,`items`)})]}),(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`最多等`,`Wait up to`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:5,max:180,step:5,value:i.timeoutSec,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&(a(e=>({...e,timeoutSec:Math.min(180,Math.max(5,Math.round(t)))})),s(!0))}}),(0,Q.jsx)(`span`,{children:e(`秒`,`s`)})]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`「想想」用一次隐藏回合让模型出建议(不进对话)。超过这个时间还没出结果就中断,可以再点一次。`,`Think runs a hidden turn to get suggestions (it never enters the conversation). If it takes longer than this, the turn is aborted and you can click again.`)})]}),(0,Q.jsx)(Lx,{}),(0,Q.jsx)(Rx,{})]})}function Lx(){let e=Y(),[t,n]=uf(pr,!0);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`标注`,`Annotations`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`选中文字后浮出的小工具栏`,`The toolbar that pops up on text selection`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>n(e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:`✍️`}),e(`开启选中标注`,`Enable selection annotations`)]})}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`打开时,在对话里选中一段文字会浮出「添加到会话 / 标注 / 在临时会话中提问」;关掉后选字就只是选字(复制、搜索都不受打扰)。已标好的内容照旧显示。只存本机,手机和桌面各记各的。`,`On: selecting text in the conversation shows Add to session / Annotate / Ask in the side chat. Off: selecting text is just selecting (copying stays unobstructed). Existing annotations are kept. Stored per device.`)})]})}function Rx(){let e=Y(),[t,n]=uf(cr,!1),[r,i]=uf(ur,!1),[a,o]=uf(dr,!0),[s,c]=uf(fr,!0);return(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`过程`,`Process`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`思考块 + 工具卡`,`Thinking blocks + tool cards`)})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked)}),e(`会话过程折叠`,`Collapse session process`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),e(`会话完成折叠`,`Collapse when the session completes`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!t,onChange:e=>n(!e.target.checked)}),e(`会话思考折叠`,`Collapse thinking blocks`)]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:!r,onChange:e=>i(!e.target.checked)}),e(`会话工具折叠`,`Collapse tool cards`)]})]})})}function zx(){let e=Y();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(qx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏高度`,`Top bar size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`整条顶栏连同里面的按钮 / 图标一起缩放(100% = 标准大小,也就是默认值)`,`Scales the whole top bar, its buttons and icons (100% = the standard size, also the default)`)})]}),(0,Q.jsx)(Xx,{})]}),(0,Q.jsx)(Hx,{}),(0,Q.jsx)(Ux,{}),(0,Q.jsx)(Wx,{}),(0,Q.jsx)(Gx,{})]})}var Bx=[{value:320,label:`小`,labelEn:`S`},{value:400,label:`中`,labelEn:`M`},{value:520,label:`大`,labelEn:`L`},{value:720,label:`特大`,labelEn:`XL`},{value:0,label:`原尺寸`,labelEn:`Natural`}];function Vx(){let e=Y(),[t,n]=Eh(Jr,400,0,4e3);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`图片`,`Images`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`对话里图片的最大显示宽度`,`Max width of images in the chat`)})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-5 settings-langs-compact`,children:Bx.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${t===r.value?` settings-lang-on`:``}`,title:r.value>0?`${r.value}px`:e(`不额外收窄,按图片本身大小`,`No extra cap`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-chat-image-width`,value:r.value,checked:t===r.value,onChange:()=>n(r.value)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:e(r.label,r.labelEn)}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.value>0?`${r.value}px`:e(`不设上限`,`No cap`)})]},r.value))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`截图先按设备像素比折回真实大小,再套这个上限;点图仍可看原图。改完立刻生效,不用保存。`,`Screenshots are first scaled back to their real size, then capped by this width. Click an image for the original. Applies immediately, nothing to save.`)})]})}function Hx(){let e=Y(),[t,n]=Eh(qr,10,1,50);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`左侧栏`,`Left sidebar`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`每个项目摆多少会话`,`Sessions per project`)})]}),(0,Q.jsx)(`div`,{className:`settings-row`,children:(0,Q.jsxs)(`label`,{className:`settings-field`,children:[(0,Q.jsx)(`span`,{children:e(`每个项目显示`,`Show`)}),(0,Q.jsx)(`input`,{className:`settings-number`,type:`number`,inputMode:`numeric`,min:1,max:50,value:t,onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&n(t)}}),(0,Q.jsx)(`span`,{children:e(`条`,`sessions`)})]})}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`默认 10 条,范围 1–50。超出的折成一行「还有 N 个…」,点一下全展开。改完立刻生效,不用保存。`,`Default 10, range 1–50. The rest collapse into one “and N more…” row that expands on click. Applies immediately, nothing to save.`)})]})}function Ux(){let e=Y(),[t,n]=Bb(),[r,i]=uf(Nr,!1);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏`,`Top bar`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`那一排入口显示哪些`,`Which entries that row shows`)})]}),(0,Q.jsxs)(`div`,{className:`settings-checks`,children:[Sr.map(r=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[r],onChange:e=>n(r,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:r})}),e(jr[r],Mr[r])]},r)),(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>i(e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:`💬`}),e(`临时会话`,`Temp session`)]})]})]})}function Wx(){let e=Y(),[t,n]=bp(Dr,Or),r={label:e(`文`,`T`),icon:e(`图`,`▣`)};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏文字与图标`,`Top bar labels & icons`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`每个入口显示什么`,`What each entry shows`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:Dr.map(i=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[i],onChange:e=>n(i,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:r[i]}),e(kr[i],Ar[i])]},i))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`只影响顶栏那一排。两个都不勾时仍然画图标 —— 一排看不见的按钮就等于把入口弄丢了。`,`Top bar row only. With both off the icon still shows: a row of invisible buttons would just lose the entries.`)})]})}function Gx(){let e=Y(),[t,n]=bp(Br,Wr,Hr),[r,i]=tx(),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),l={settings:`⚙️`,approval:`🔓`,engine:`◉`,queued:`⏳`,running:`◌`,context:`◔`,history:`📜`,prompt:`🧾`,terminal:`🖥️`,top:`⬆️`};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`底部`,`Bottom`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`显隐与从左到右的顺序`,`Visibility and left-to-right order`)})]}),(0,Q.jsx)(`div`,{className:`statusbar-settings-list`,children:r.map(u=>(0,Q.jsxs)(`div`,{className:`statusbar-setting-row${a===u?` is-dragging`:``}${s===u&&a!==u?` is-drag-over`:``}`,draggable:!0,onDragStart:e=>{o(u),c(null),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,u)},onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,a!==u&&c(u)},onDragLeave:()=>{s===u&&c(null)},onDrop:e=>{e.preventDefault();let t=e.dataTransfer.getData(`text/plain`),n=r.indexOf(t),a=r.indexOf(u);n>=0&&a>=0&&i(ex(r,n,a)),o(null),c(null)},onDragEnd:()=>{o(null),c(null)},children:[(0,Q.jsx)(`span`,{className:`statusbar-setting-grip`,"aria-hidden":`true`,children:`⠿`}),(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:u===`settings`||t[u],disabled:u===`settings`,onChange:e=>n(u,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:l[u]}),e(Gr[u],Kr[u])]})]},u))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`拖动左侧的点状把手可以改变状态栏从左到右的顺序;取消勾选即可隐藏对应项目。「设置」始终保留,避免把自己关掉后找不回来。`,`Drag the dotted handle to change the left-to-right order. Uncheck an item to hide it. Settings always stays available so you cannot lock yourself out.`)})]})}function Kx(){let e=Y(),[t,n]=bp(Pr,Lr,Ir),r={model:`▣`,thinking:`⚡`,templates:`✏️`,think:`💡`,quick:`💬`};return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`对话窗口`,`Composer`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`输入框上方那一排`,`The row above the input`)})]}),(0,Q.jsx)(`div`,{className:`settings-checks`,children:Pr.map(i=>(0,Q.jsxs)(`label`,{className:`settings-toggle settings-check`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t[i],onChange:e=>n(i,e.target.checked)}),(0,Q.jsx)(`span`,{className:`settings-check-icon`,"aria-hidden":`true`,children:r[i]}),e(Rr[i],zr[i])]},i))}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`这三块都只存本机 —— 手机、平板、桌面各一份,同一条设置在不同设备上可以不一样。快捷指令的短语内容在本页「快捷短语」里改(那份是多设备一致的),这里只管要不要在输入框上方显示。`,`These three are stored per device — phone, tablet and desktop can differ. The phrase text itself is edited under Quick phrases on this page (shared across devices); this only controls whether the row is shown.`)})]})}function qx(){let e=Y(),{shown:t,logo:n,logoShown:r,setShown:i,setLogo:a,setLogoShown:o}=Zv(),s=(0,C.useRef)(null);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`顶栏名称`,`Top-bar name`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`顶栏那个 logo 和它后面那串名字`,`The logo in the top bar and the name after it`)})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>o(e.target.checked)}),e(`在顶栏显示 logo`,`Show the logo in the top bar`)]}),(0,Q.jsxs)(`div`,{className:`brand-logo-row`,children:[(0,Q.jsx)(`img`,{className:`brand-logo-preview`,src:n||jx,alt:``,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>s.current?.click(),title:e(`选一张图片当顶栏 logo(会缩到 192px 存在本机)`,`Pick an image as the top-bar logo (scaled to 192px, stored on this device)`),children:e(`更换 logo`,`Change logo`)}),n?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>a(``),children:e(`用回默认 logo`,`Use default logo`)}):null,(0,Q.jsx)(`input`,{ref:s,className:`brand-logo-file`,type:`file`,accept:`image/*`,"aria-label":e(`选择 logo 图片`,`Choose a logo image`),onChange:t=>{let n=t.target.files?.[0];t.target.value=``,n&&Gb(n).then(e=>a(e)).catch(t=>{Z({text:t instanceof Error?t.message:e(`这张图用不了`,`That image did not work`)})})}})]}),(0,Q.jsxs)(`label`,{className:`settings-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>i(e.target.checked)}),e(`在顶栏显示名称`,`Show the name in the top bar`)]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`顶栏显示的就是产品名,不再支持自定义改名。`,`The top bar shows the product name; custom renaming is no longer available.`)})]})}function Jx({name:e,layer:t,value:n,onChange:r}){let i=Y(),a=Ny(n,t),o=Dy[t];return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:i(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:e,type:`range`,min:2,max:30,step:2,value:n,"aria-label":i(`字号(2–30 像素)`,`Font size (2–30 px)`),"aria-valuetext":`${n}px`,onChange:e=>r(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[2,`px`]}),(0,Q.jsxs)(`span`,{children:[30,`px`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[n,`px`]})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:o.map(t=>(0,Q.jsxs)(`label`,{className:`settings-lang${a===t.id?` settings-lang-on`:``}`,title:i(`一键设为 ${t.px}px`,`Set to ${t.px}px`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`${e}-preset`,value:t.id,checked:a===t.id,onChange:()=>r(t.px)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,style:{fontSize:`${t.px}px`},children:i(t.label,t.labelEn)}),(0,Q.jsxs)(`span`,{className:`settings-lang-hint`,children:[t.px,`px`]})]},t.id))})]})}function Yx({value:e,onChange:t}){let n=Y(),[r,i]=(0,C.useState)(Yy);(0,C.useEffect)(()=>{i(Yy())},[]);let a=e<=0||e>=r,o=a?r:e;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:n(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-chat-width`,type:`range`,min:360,max:r,step:20,value:o,"aria-label":n(`内容宽度(360px 到满宽)`,`Content width (360px to full)`),"aria-valuetext":a?n(`满宽`,`Full width`):`${o}px`,onChange:e=>{let n=Number(e.target.value);t(n>=r?0:n)}}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[360,`px`]}),(0,Q.jsx)(`span`,{children:n(`满宽`,`Full width`)})]})]}),(0,Q.jsx)(`span`,{className:`settings-font-value mono`,children:a?n(`满宽`,`Full`):`${e}px`})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:Ry.map(r=>(0,Q.jsxs)(`label`,{className:`settings-lang${r.px===e?` settings-lang-on`:``}`,title:r.px>0?`${r.px}px`:n(`铺满整个对话区`,`Fill the whole area`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-chat-width`,value:r.id,checked:r.px===e,onChange:()=>t(r.px)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:n(r.label,r.labelEn)}),(0,Q.jsx)(`span`,{className:`settings-lang-hint`,children:r.px>0?`${r.px}px`:n(`默认`,`Default`)})]},r.id))})]})}function Xx(){let e=Y(),{percent:t,setPercent:n}=Cb(),r=hb(t);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:e(`自定义`,`Custom`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-appbar-scale`,type:`range`,min:60,max:120,step:5,value:t,"aria-label":e(`顶栏大小(60%–120%)`,`Top bar size (60%–120%)`),"aria-valuetext":`${t}%`,onChange:e=>n(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[60,`%`]}),(0,Q.jsxs)(`span`,{children:[120,`%`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[t,`%`]})]}),(0,Q.jsx)(`div`,{className:`settings-langs settings-langs-4 settings-langs-compact`,children:lb.map(t=>(0,Q.jsxs)(`label`,{className:`settings-lang${r===t.id?` settings-lang-on`:``}`,title:e(`一键设为 ${t.percent}%`,`Set to ${t.percent}%`),children:[(0,Q.jsx)(`input`,{type:`radio`,name:`settings-appbar-scale-preset`,value:t.id,checked:r===t.id,onChange:()=>n(t.percent)}),(0,Q.jsx)(`span`,{className:`settings-lang-name`,children:e(t.label,t.labelEn)}),(0,Q.jsxs)(`span`,{className:`settings-lang-hint`,children:[t.percent,`%`]})]},t.id))})]})}function Zx({theme:e,active:t,onPick:n}){let r=Y();return(0,Q.jsxs)(`button`,{type:`button`,className:`theme-card${t?` theme-card-on`:``}`,"aria-pressed":t,title:`${r(e.name,e.nameEn)} — ${r(e.hint,e.hintEn)}`,onClick:n,children:[(0,Q.jsxs)(`span`,{className:`theme-preview`,style:{background:e.swatch[0]},children:[(0,Q.jsx)(`span`,{className:`theme-preview-bar`,style:{background:e.swatch[1]}}),(0,Q.jsx)(`span`,{className:`theme-preview-bar theme-preview-bar-short`,style:{background:e.swatch[1]}}),(0,Q.jsx)(`span`,{className:`theme-preview-dot`,style:{background:e.swatch[2]}})]}),(0,Q.jsxs)(`span`,{className:`theme-name`,children:[r(e.name,e.nameEn),t?(0,Q.jsx)(`span`,{className:`theme-check`,"aria-hidden":`true`,children:`✓`}):null]}),(0,Q.jsx)(`span`,{className:`theme-hint`,children:r(e.hint,e.hintEn)})]})}function Qx(){let e=Y(),[t,n]=Eh(br,14,8,24);return(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`命令行字号(终端)`,`Command-line font size (terminal)`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`右侧终端面板里的字(也能在终端里用 ⌘/Ctrl + 滚轮调)`,`Text inside the terminal panel (or ⌘/Ctrl + wheel in it)`)})]}),(0,Q.jsxs)(`div`,{className:`settings-font-slider`,children:[(0,Q.jsx)(`span`,{className:`settings-font-label`,children:e(`字号`,`Size`)}),(0,Q.jsxs)(`div`,{className:`settings-font-track`,children:[(0,Q.jsx)(`input`,{id:`settings-terminal-font`,type:`range`,min:8,max:24,step:1,value:t,"aria-label":e(`命令行字号(8–24 像素)`,`Command-line font size (8–24 px)`),"aria-valuetext":`${t}px`,onChange:e=>n(Number(e.target.value))}),(0,Q.jsxs)(`div`,{className:`settings-font-bounds`,"aria-hidden":`true`,children:[(0,Q.jsxs)(`span`,{children:[8,`px`]}),(0,Q.jsxs)(`span`,{children:[24,`px`]})]})]}),(0,Q.jsxs)(`span`,{className:`settings-font-value mono`,children:[t,`px`]})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`只存本机,立即生效。终端里 ⌘/Ctrl + 滚轮、⌘/Ctrl + = / - 也能调,⌘/Ctrl + 0 恢复 14px。`,`Stored on this device and applied immediately. You can also use ⌘/Ctrl + wheel or ⌘/Ctrl + = / - inside the terminal; ⌘/Ctrl + 0 resets to 14px.`)})]})}function $x(){let e=Y(),{font:t,width:n,setFont:r,setWidth:i}=ab(),a=zb();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Qx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`聊天字体大小`,`Chat font size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`只影响对话正文(代码块、表格跟着缩放)`,`Affects message text only (code and tables scale with it)`)})]}),(0,Q.jsx)(Jx,{name:`settings-chat-font`,layer:`chat`,value:t,onChange:r})]}),(0,Q.jsx)(Vx,{}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`侧栏项目名大小`,`Sidebar project name size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`项目列表里那一行文件夹名`,`The folder name rows in the project list`)})]}),(0,Q.jsx)(Jx,{name:`settings-side-project-font`,layer:`project`,value:a.project,onChange:a.setProject})]}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`侧栏会话名大小`,`Sidebar session name size`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`会话标题;时间、置顶项目名等跟着按比例缩`,`Session titles; timestamps and the pinned project label scale with them`)})]}),(0,Q.jsx)(Jx,{name:`settings-side-session-font`,layer:`session`,value:a.session,onChange:a.setSession})]}),(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e(`聊天内容宽度`,`Chat content width`)}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e(`对话列的最大宽度(窄屏自动铺满)`,`Max width of the conversation column (narrow screens fill it)`)})]}),(0,Q.jsx)(Yx,{value:n,onChange:i})]}),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;首次是标准字号 + 标准宽度。`,`Takes effect immediately, nothing to save. Stored on this machine (localStorage); it survives reloads and does not touch the server or other devices. The first run uses the standard size and standard width.`)})]})}function eS(){let e=Y(),{theme:t,setTheme:n}=Ty(),r=[{mode:`light`,label:e(`浅色`,`Light`),hint:e(`白天 / 亮环境`,`Daylight / bright rooms`)},{mode:`dark`,label:e(`深色`,`Dark`),hint:e(`夜里 / 暗环境`,`Night / dim rooms`)}];return(0,Q.jsxs)(Q.Fragment,{children:[r.map(e=>(0,Q.jsxs)(`div`,{className:`settings-panel`,children:[(0,Q.jsxs)(`div`,{className:`settings-head`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsx)(`span`,{className:`settings-sub`,children:e.hint})]}),(0,Q.jsx)(`div`,{className:`theme-grid`,children:Dh.filter(t=>Ah(t.id)===e.mode).map(e=>(0,Q.jsx)(Zx,{theme:e,active:t.id===e.id,onPick:()=>n(e.id)},e.id))})]},e.mode)),(0,Q.jsx)(`div`,{className:`settings-hint`,children:e(`点一下立即生效,不用保存。选择存在本机(localStorage),刷新后保持,不影响服务端和其它设备;首次使用是「清亮白」。`,`Takes effect immediately, nothing to save. Stored on this machine (localStorage); it survives reloads and does not touch the server or other devices. The first run uses the bright default theme.`)})]})}function tS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function nS(e){return e.toLocaleString(`zh-CN`)}function rS(e,t){let n=t.trim().toLowerCase();if(n===``)return e;let r=n.split(/\s+/);return e.filter(e=>{let t=`${e.name} ${e.id} ${e.description}`.toLowerCase();return r.every(e=>t.includes(e))})}function iS(e){return[...e].sort((e,t)=>{let n=e=>/^skill\.md$/i.test(e)?0:/^references\//i.test(e)?2:1;return n(e)-n(t)||e.localeCompare(t)})}function aS({skill:e,detail:t,busy:n,confirmRemove:r,onFile:i,onToggle:a,onRemove:o}){let s=Y(),c=iS(e.files);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`skills-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge${e.enabled?` skill-badge-on`:``}`,children:e.enabled?s(`已启用`,`Enabled`):s(`已停用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:n,onClick:a,children:e.enabled?s(`停用`,`Disable`):s(`启用`,`Enable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${r===e.id?` btn-danger`:``}`,disabled:n,onClick:o,title:s(`整目录删除(含 scripts / references)`,`Delete the whole folder (scripts / references included)`),children:r===e.id?s(`确认删除`,`Confirm delete`):s(`删除`,`Delete`)})]}),(0,Q.jsxs)(`div`,{className:`skills-detail-meta`,children:[(0,Q.jsx)(`span`,{className:`skills-label`,children:s(`目录`,`Folder`)}),(0,Q.jsx)(`span`,{className:`mono skill-slug`,children:e.id}),(0,Q.jsx)(`span`,{className:`skills-label`,children:s(`文件`,`File`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[c.length,` `,s(`个`,``)]})]}),e.description===``?null:(0,Q.jsx)(`p`,{className:`skills-desc`,children:e.description}),(0,Q.jsx)(`div`,{className:`skills-file-chips`,children:c.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`skills-file${t?.path===e?` skills-file-on`:``}`,onClick:()=>i(e),children:e},e))}),t===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`点上面的文件名看内容。`,`Click a file name above to see its content.`)}):t.preview===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`读取中…`,`Loading…`)}):t.preview.binary?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`这是二进制文件,不能预览`,`This is a binary file and cannot be previewed`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count mono`,children:[t.path,` · `,nS(t.preview.bytes),` `,s(`字节`,`bytes`)]}),(0,Q.jsx)(`pre`,{className:`skills-preview mono`,children:t.preview.text})]})]})}function oS({skills:e,tab:t,onTab:n,query:r,onQuery:i,byTab:a,shown:o,selected:s,selecting:c,picked:l,onPicked:u,onSelecting:d,busy:f,confirmRemove:p,installOpen:m,onOpenInstall:h,onOpenDetail:g,onBatchEnabled:_,onBatchRemove:v,onEnableAll:y}){let b=Y(),x=e=>{let t=new Set(l);t.has(e)?t.delete(e):t.add(e),u(t)},S=e.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`skills-list-col`,children:[(0,Q.jsx)(`div`,{className:`skills-tabbar`,role:`tablist`,"aria-label":b(`技能筛选`,`Skill filter`),children:[{key:`all`,label:b(`全部`,`All`),count:e.length},{key:`enabled`,label:b(`启用`,`Enabled`),count:S},{key:`disabled`,label:b(`禁用`,`Disabled`),count:e.length-S}].map(e=>(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":t===e.key,className:`skills-tab${t===e.key?` skills-tab-on`:``}`,onClick:()=>n(e.key),children:[e.label,(0,Q.jsx)(`span`,{className:`skills-tab-count`,children:e.count})]},e.key))}),(0,Q.jsx)(`input`,{className:`skills-input skills-search`,value:r,placeholder:t===`all`?b(`搜索已安装的技能…`,`Search installed skills…`):b(`在「${t===`enabled`?`启用`:`禁用`}」里搜索…`,`Search among ${t===`enabled`?`enabled`:`disabled`} skills…`),onChange:e=>i(e.target.value),"aria-label":b(`搜索已安装的技能`,`Search installed skills`)}),(0,Q.jsxs)(`div`,{className:`skills-list-head`,children:[(0,Q.jsx)(`span`,{children:c?b(`已选 ${l.size}`,`${l.size} selected`):t===`all`?b(`已安装`,`Installed`):t===`enabled`?b(`已启用`,`Enabled`):b(`已禁用`,`Disabled`)}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:r.trim()===``?b(`${o.length} 个`,`${o.length}`):b(`匹配 ${o.length} / ${a.length}`,`${o.length} / ${a.length} matching`)}),(0,Q.jsx)(`button`,{type:`button`,className:`skills-select-toggle${c?` skills-select-toggle-on`:``}`,onClick:()=>d(!c),title:c?b(`退出多选`,`Leave multi-select`):b(`多选:可批量启用 / 停用 / 删除`,`Multi-select: enable / disable / delete in bulk`),children:c?b(`完成`,`Done`):b(`多选`,`Multi-select`)})]}),(0,Q.jsx)(`div`,{className:`skills-list-scroll`,children:o.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:e.length===0?b(`还没有技能,点下面「安装技能」`,`No skills yet — use “Install skill” below`):t===`disabled`?b(`没有禁用的技能`,`No disabled skills`):t===`enabled`?b(`没有启用的技能`,`No enabled skills`):b(`没有匹配的技能`,`No matching skills`)}):o.map(e=>{let t=l.has(e.id);return(0,Q.jsxs)(`button`,{type:`button`,className:`skill-item${c?` skill-item-pick`:``}${t?` skill-item-picked`:``}${s===e.id&&!c?` skill-item-on`:``}${e.enabled?``:` skill-item-off`}`,onClick:()=>c?x(e.id):g(e),title:c?b(`选择 ${e.name}`,`Select ${e.name}`):e.description,children:[c?(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>void 0,tabIndex:-1,"aria-label":b(`选择 ${e.name}`,`Select ${e.name}`)}):(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`skill-item-name`,children:e.name})]},e.id)})}),c?(0,Q.jsxs)(`div`,{className:`skills-batch`,children:[(0,Q.jsxs)(`div`,{className:`skills-batch-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:o.length===0,onClick:()=>u(o.every(e=>l.has(e.id))?new Set:new Set(o.map(e=>e.id))),children:o.length>0&&o.every(e=>l.has(e.id))?b(`全不选`,`Select none`):`${b(`全选`,`Select all`)} ${o.length}`}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>u(new Set),children:b(`清空`,`Clear`)})]}),(0,Q.jsxs)(`div`,{className:`skills-batch-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>_(!0),title:b(`把勾选的技能全部启用`,`Enable every ticked skill`),children:b(`批量启用`,`Enable selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||l.size===0,onClick:()=>_(!1),title:b(`把勾选的技能全部停用(改名 SKILL.md)`,`Disable every ticked skill (renames SKILL.md)`),children:b(`批量禁用`,`Disable selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${p===`batch`?` btn-danger`:``}`,disabled:f||l.size===0,onClick:v,title:b(`整目录删除,不可恢复`,`Delete the whole folder — this cannot be undone`),children:p===`batch`?b(`确认删除 ${l.size} 个`,`Confirm delete ${l.size}`):b(`批量删除`,`Delete selected`)})]})]}):(0,Q.jsxs)(`div`,{className:`skills-left-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${m?` btn-on`:``}`,onClick:h,children:[`+ `,b(`安装技能`,`Install skill`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:f||a.every(e=>e.enabled),onClick:y,title:b(`把当前页签里停用的技能全部启用`,`Enable all disabled skills in this tab`),children:b(`全启用`,`Enable all`)})]})]})}function sS({root:e,onInstalled:t,onOpenGit:n}){let r=Y(),[i,a]=(0,C.useState)(``),[o,s]=(0,C.useState)(``),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)([]),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(1),[g,_]=(0,C.useState)(!1),[v,y]=(0,C.useState)(null),[b,x]=(0,C.useState)(null),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(null),D=(0,C.useRef)(0);(0,C.useEffect)(()=>{let e=window.setTimeout(()=>s(i.trim()),400);return()=>window.clearTimeout(e)},[i]);let O=(0,C.useCallback)(async(e,t)=>{let n=++D.current;w(!0),x(null);try{let r=new URLSearchParams({q:o,category:c,page:String(e)}),i=await fetch(`/api/skills/hub?${r.toString()}`),a=await i.json();if(n!==D.current)return;if(!i.ok){x(tS(a,i.status)),t||p([]);return}a.categories&&d(a.categories);let s=a.skills??[];p(e=>t&&e!==null?[...e,...s]:s),h(e),_(a.hasMore===!0),y(a.total??null)}catch(e){if(n!==D.current)return;x(e instanceof Error?e.message:String(e)),t||p([])}finally{n===D.current&&w(!1)}},[o,c]);(0,C.useEffect)(()=>{O(1,!1)},[O]);let k=async e=>{E(e.slug);try{let n=await(await fetch(`/api/skills/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:`hub`,slug:e.slug,name:e.slug})})).json();t(n),n.notice!==void 0&&p(t=>t?.map(t=>t.slug===e.slug?{...t,installed:!0}:t)??null)}catch(e){t({installError:e instanceof Error?e.message:String(e)})}finally{E(null)}};return(0,Q.jsxs)(`div`,{className:`skills-hub`,children:[(0,Q.jsxs)(`form`,{className:`skills-hub-search`,onSubmit:e=>{e.preventDefault(),s(i.trim()),O(1,!1)},children:[(0,Q.jsx)(`input`,{className:`skills-input`,value:i,placeholder:r(`搜索 SkillHub 的技能(名字、用途、关键词)`,`Search SkillHub skills (name, purpose, keywords)`),onChange:e=>a(e.target.value)}),(0,Q.jsx)(`button`,{type:`submit`,className:`btn btn-tiny btn-primary-add`,disabled:S,children:S?r(`搜索中…`,`Searching…`):r(`搜索`,`Search`)})]}),(0,Q.jsx)(`div`,{className:`skills-hub-cats`,children:(u.length>0?u:[{key:``,label:`全部`}]).map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`skills-cat${c===e.key?` skills-cat-on`:``}`,onClick:()=>{l(e.key),s(i.trim())},children:r(e.label)},e.key||`all`))}),(0,Q.jsxs)(`div`,{className:`skills-hub-meta`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[v===null?``:r(`共 ${nS(v)} 个技能`,`${nS(v)} skills in total`),f===null?``:` · ${r(`已列出`,`showing`)} ${f.length}`,` · `,r(`安装到`,`installed to`),` `,(0,Q.jsx)(`code`,{children:e})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:n,children:[r(`从 Git 仓库装`,`Install from a Git repo`),` ↗`]})]}),b===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:b}),f===null&&S?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`正在读取技能库…`,`Loading the skill hub…`)}):null,f!==null&&f.length===0&&!S?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有匹配的技能,换个词或换个分类试试。`,`No matching skills — try another word or category.`)}):null,(0,Q.jsx)(`div`,{className:`skills-hub-list`,children:(f??[]).map((t,n)=>(0,Q.jsxs)(`div`,{className:`skill-card`,children:[(0,Q.jsxs)(`div`,{className:`skill-card-head`,children:[(0,Q.jsx)(`span`,{className:`skill-card-name`,children:t.name}),t.installed?(0,Q.jsx)(`span`,{className:`mcp-badge skill-badge-on`,children:r(`已安装`,`Installed`)}):(0,Q.jsx)(`span`,{className:`mcp-badge`,children:r(`未安装`,`Not installed`)}),t.author?(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`作者`,`by`),` `,t.author]}):null,t.categoryLabel?(0,Q.jsx)(`span`,{className:`mcp-badge`,children:r(t.categoryLabel)}):null,t.downloads===void 0?null:(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`下载`,`Downloads`),` `,nS(t.downloads)]}),t.stars===void 0?null:(0,Q.jsxs)(`span`,{className:`mcp-badge`,children:[r(`收藏`,`Stars`),` `,nS(t.stars)]})]}),t.description===``?null:(0,Q.jsx)(`p`,{className:`skill-card-desc`,children:t.description}),(0,Q.jsxs)(`div`,{className:`skill-card-foot`,children:[(0,Q.jsx)(`span`,{className:`skill-slug mono`,children:t.slug}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),t.homepage?(0,Q.jsxs)(`a`,{className:`mcp-catalog-link`,href:t.homepage,target:`_blank`,rel:`noreferrer`,children:[r(`详情`,`Details`),` ↗`]}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:T!==null||t.installed===!0,onClick:()=>void k(t),title:t.installed?r(`本机已有同名目录`,`A folder with this name already exists`):r(`装到 ${e}/${t.slug}`,`Installs to ${e}/${t.slug}`),children:T===t.slug?r(`安装中…`,`Installing…`):t.installed?r(`已安装`,`Installed`):r(`安装`,`Install`)})]})]},`${t.slug}-${n}`))},`${o}|${c}`),g?(0,Q.jsx)(`div`,{className:`skills-hub-more`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:S,onClick:()=>void O(m+1,!0),children:S?r(`加载中…`,`Loading…`):r(`加载更多`,`Load more`)})}):null,(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[r(`技能来自`,`Skills come from`),` `,(0,Q.jsx)(`code`,{children:`skillhub.tencent.com`}),r(`(公开接口,5 分钟内重复搜索走缓存)。安装 = 下载 zip 整目录解到`,`(public API; repeated searches within 5 minutes are cached). Installing = download the zip and unpack the whole folder into`),` `,(0,Q.jsx)(`code`,{children:e}),r(`,同名已存在不会覆盖。`,`; an existing folder with the same name is never overwritten.`)]})]})}var cS=`---
41
41
  name: my-skill
42
42
  description: 什么时候用这个技能
43
43
  ---
@@ -51,7 +51,7 @@ description: when to use this skill
51
51
 
52
52
  # my-skill
53
53
 
54
- how to do it…`;function uS({root:e,tab:t,onTab:n,onInstalled:r}){let i=J(),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(``),[h,g]=(0,C.useState)(``),_=async e=>await(await fetch(`/api/skills/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json(),v=async()=>{u(`list`),f(null),c(null);try{let e=await _({source:`git`,repoUrl:a});e.ok===!0?c(e.skills):f(e.error??e.installError??i(`拉取失败`,`Failed to fetch`))}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}},y=async e=>{u(e);try{let t=await _({source:`git`,repoUrl:a,skill:e});r(t),t.notice===void 0?t.installError!==void 0&&f(t.installError):c(t=>t?.filter(t=>t!==e)??null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}},b=async()=>{u(`create`);try{let e=await _({source:`manual`,name:p,raw:h});r(e),e.notice===void 0?e.installError!==void 0&&f(e.installError):(m(``),g(``))}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}};return(0,Q.jsxs)(`div`,{className:`skills-install-pane`,children:[(0,Q.jsxs)(`div`,{className:`skills-tabs`,role:`tablist`,"aria-label":i(`安装方式`,`Install method`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>n(`hub`),children:i(`技能库`,`Skill hub`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===`git`,className:`skills-tab${t===`git`?` skills-tab-on`:``}`,onClick:()=>n(`git`),children:i(`Git 仓库`,`Git repo`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===`manual`,className:`skills-tab${t===`manual`?` skills-tab-on`:``}`,onClick:()=>n(`manual`),children:i(`手动创建`,`Create by hand`)})]}),d===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:d}),t===`git`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-repo-url`,children:i(`Git 仓库地址`,`Git repo URL`)}),(0,Q.jsxs)(`div`,{className:`skills-row`,children:[(0,Q.jsx)(`input`,{id:`skill-repo-url`,className:`skills-input mono`,value:a,placeholder:i(`https://github.com/anthropics/skills 或 git@github.com:user/repo.git`,`https://github.com/anthropics/skills or git@github.com:user/repo.git`),onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&a.trim()!==``&&v()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l!==null||a.trim()===``,onClick:()=>void v(),children:l===`list`?i(`克隆中…`,`Cloning…`):i(`拉取列表`,`Fetch the list`)})]}),(0,Q.jsxs)(`span`,{className:`side-panel-hint`,children:[i(`会把仓库浅克隆一份(`,`Shallow-clones the repo (`),(0,Q.jsx)(`code`,{children:`--depth 1`}),i(`)到临时目录,列出根目录与`,`) into a temp folder and lists the folders in the root and in`),` `,(0,Q.jsx)(`code`,{children:`skills/`}),i(` 下带 `,` subfolders with `),(0,Q.jsx)(`code`,{children:`SKILL.md`}),i(`的目录,装完即删。安装是`,` — the clone is deleted afterwards. Installing copies`),(0,Q.jsx)(`strong`,{children:i(`整目录`)}),i(`复制(脚本、references 都带上)。`,` (scripts and references included).`)]}),s===null?null:(0,Q.jsxs)(`div`,{className:`skills-repo-list`,children:[(0,Q.jsxs)(`span`,{className:`skills-label`,children:[i(`仓库里有`,`The repo has`),` `,s.length,` `,i(`个技能`,`skills`)]}),s.map(t=>(0,Q.jsxs)(`div`,{className:`skills-repo-row`,children:[(0,Q.jsx)(`span`,{className:`skill-slug mono`,children:t}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l!==null,onClick:()=>void y(t),title:i(`装到 ${e}/${t}`,`Install into ${e}/${t}`),children:l===t?i(`安装中…`,`Installing…`):i(`安装`,`Install`)})]},t))]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-manual-name`,children:i(`技能名(目录名)`,`Skill name (folder name)`)}),(0,Q.jsx)(`input`,{id:`skill-manual-name`,className:`skills-input`,value:p,placeholder:`my-skill`,onChange:e=>m(e.target.value)}),(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-manual-raw`,children:i(`SKILL.md(可留空,留空就写一份骨架)`,`SKILL.md (optional — leave empty to write a skeleton)`)}),(0,Q.jsx)(`textarea`,{id:`skill-manual-raw`,className:`skills-input skills-textarea mono`,value:h,placeholder:i(cS,lS),onChange:e=>g(e.target.value)}),(0,Q.jsxs)(`div`,{className:`skills-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:l!==null||p.trim()===``,onClick:()=>void b(),children:l===`create`?i(`创建中…`,`Creating…`):i(`创建`,`Create`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[i(`写到`,`Written to`),` `,e,`/<name>/SKILL.md`]})]})]})]})}var dS=`pop-agent:skills-list-width`;function fS(){let e=J(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(!1),[d,f]=(0,C.useState)(``),[p,m]=(0,C.useState)(`all`),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(new Set),[y,b]=(0,C.useState)(null),[x,S]=(0,C.useState)({kind:`detail`}),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(null),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(dS));return Number.isFinite(e)&&e>=180&&e<=520?e:260});(0,C.useEffect)(()=>{localStorage.setItem(dS,String(O))},[O]);let A=(0,C.useRef)(!1),j=e=>{e.preventDefault(),A.current=!0;let t=e.clientX,n=O,r=e=>{A.current&&k(Math.min(520,Math.max(180,n+(e.clientX-t))))},i=()=>{A.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},M=(0,C.useCallback)(e=>{e.skills&&n(e.skills)},[]),N=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/skills`),t=await e.json();if(!e.ok){o(tS(t,e.status));return}n(t.skills??[]),t.root!==void 0&&i(t.root),o(null),b(e=>{if(e!==null)return e;let n=t.skills?.[0];return n!==void 0&&R(n,iS(n.files)[0]??`SKILL.md`),n?.id??null})}catch(e){o(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{N()},[N]);let P=e=>{if(M(e),e.notice!==void 0){c(e.notice),o(null);let n=e.skills?.find(e=>!t?.some(t=>t.id===e.id));n&&(b(n.id),S({kind:`detail`}),R(n,iS(n.files)[0]??`SKILL.md`))}e.installError!==void 0&&o(e.installError)},F=async(t,n)=>{if(t.length!==0){u(!0);try{let r=await fetch(`/api/skills/enabled`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:t,enabled:n})}),i=await r.json();r.ok?(i.errors??[]).length>0&&o((i.errors??[]).join(`;`)):o(i.error?.message??`HTTP ${r.status}`),M(i),v(new Set),c(n?e(`已启用`,`Enabled`):e(`已停用`,`Disabled`))}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1)}}},I=async e=>{if(e.length!==0){u(!0);try{let t=await(await fetch(`/api/skills/remove`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:e})})).json();M(t),t.notice!==void 0&&(c(t.notice),v(new Set),t.skills!==void 0&&(b(t.skills[0]?.id??null),T(null))),t.removeError!==void 0&&o(t.removeError)}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1),D(null)}}},L=async e=>{u(!0);try{let t=await(await fetch(`/api/skills/remove`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e})})).json();M(t),t.notice!==void 0&&(c(t.notice),t.skills!==void 0&&b(t.skills[0]?.id??null),T(null)),t.removeError!==void 0&&o(t.removeError)}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1),D(null)}},R=async(t,n)=>{T({path:n,preview:null});let r=await fetch(`/api/skills/${encodeURIComponent(t.id)}/file?path=${encodeURIComponent(n)}`),i=await r.json();T({path:n,preview:r.ok?{text:i.text??``,bytes:i.bytes??0,binary:i.binary===!0}:{text:i.error?.message??e(`读取失败`,`Failed to read`),bytes:0,binary:!1}})};if(t===null)return(0,Q.jsx)(`div`,{className:`skills`,children:a===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取技能目录…`,`Reading the skills folder…`)}):(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[e(`读不到技能目录:`,`Cannot read the skills folder: `),a]})});let z=t.filter(e=>p===`all`||(p===`enabled`?e.enabled:!e.enabled)),B=rS(z,d),V=t.find(e=>e.id===y)??null,H=t.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`skills`,children:[(0,Q.jsxs)(`div`,{className:`skills-shell`,style:{"--skills-list-width":`${O}px`},children:[(0,Q.jsx)(oS,{skills:t,tab:p,onTab:e=>{m(e),v(new Set)},query:d,onQuery:f,byTab:z,shown:B,selected:y,selecting:h,picked:_,onPicked:v,onSelecting:e=>{g(e),v(new Set)},busy:l,confirmRemove:E,installOpen:x.kind===`install`,onOpenInstall:()=>S(x.kind===`install`?{kind:`detail`}:{kind:`install`,tab:`hub`}),onOpenDetail:e=>{b(e.id),S({kind:`detail`}),R(e,iS(e.files)[0]??`SKILL.md`)},onBatchEnabled:e=>void F([..._],e),onBatchRemove:()=>E===`batch`?void I([..._]):D(`batch`),onEnableAll:()=>void F(z.filter(e=>!e.enabled).map(e=>e.id),!0)}),(0,Q.jsx)(`div`,{className:`skills-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整技能列表宽度`,`Resize the skills list`),title:e(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:j,onDoubleClick:()=>k(260)}),(0,Q.jsx)(`div`,{className:`skills-detail${x.kind===`detail`?``:` skills-detail-pane`}`,children:x.kind===`install`&&x.tab===`hub`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`skills-tabs`,role:`tablist`,"aria-label":e(`安装方式`,`Install method`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!0,className:`skills-tab skills-tab-on`,children:e(`技能库`,`Skill hub`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>S({kind:`install`,tab:`git`}),children:e(`Git 仓库`,`Git repo`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>S({kind:`install`,tab:`manual`}),children:e(`手动创建`,`Create by hand`)})]}),(0,Q.jsx)(sS,{root:r,onInstalled:P,onOpenGit:()=>S({kind:`install`,tab:`git`})})]}):x.kind===`install`?(0,Q.jsx)(uS,{root:r,tab:x.tab===`manual`?`manual`:`git`,onTab:e=>S({kind:`install`,tab:e}),onInstalled:P}):V===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`左边挑一个技能,或者点「+ 安装技能」去技能库装。`,`Pick a skill on the left, or use “+ Install skill” to browse the hub.`)}):(0,Q.jsx)(aS,{skill:V,detail:w,busy:l,confirmRemove:E,onFile:e=>void R(V,e),onToggle:()=>void F([V.id],!V.enabled),onRemove:()=>E===V.id?void L(V.id):D(V.id)})})]}),(0,Q.jsxs)(`div`,{className:`skills-bar`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已安装`,`Installed`),` `,t.length,` `,e(`个`,``),` · `,e(`已启用`,`enabled`),` `,H,` ·`,` `,e(`目录`,`folder`),` `,(0,Q.jsx)(`code`,{children:r})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l,onClick:()=>void N(),children:e(`刷新`,`Refresh`)})]}),a===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:a}),s===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s})]})}var pS={codemode:`代码模式(默认)`,deferred:`搜索后声明`,direct:`直接声明`,hidden:`不暴露`},mS={codemode:`Code mode (default)`,deferred:`Declared after search`,direct:`Declared directly`,hidden:`Hidden`},hS={codemode:`只列出服务器名称和简介,代码模式脚本按需搜索它的工具。`,deferred:`模型先用 tool_search 搜到、下一轮才声明出来,然后直接调用。`,direct:`像内置工具一样直接声明给模型,最省事也最占上下文。`,hidden:`注册但不暴露:工具还在,模型碰不到。`},gS={codemode:`Only the server name and summary are listed; code-mode scripts search its tools on demand.`,deferred:`The model finds it with tool_search, it is declared on the next turn, then called directly.`,direct:`Declared to the model like a built-in tool: simplest, but uses the most context.`,hidden:`Registered but hidden: the tools exist, the model cannot reach them.`};function _S(e){return e!==void 0&&/requires authentication|unauthori[sz]ed|invalid_token|\b401\b/i.test(e)}var vS={global:`全局`,project:`项目`},yS={global:`Global`,project:`Project`};function bS(e){return`${e.scope}:${e.name}`}function xS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function SS(e){return[e.command??``,...e.args??[]].filter(e=>e!==``).join(` `)}function CS(e){return e.startsWith(`!`)}function wS(e){let t=J(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(``),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(`global`),[g,_]=(0,C.useState)(null),[v,y]=(0,C.useState)(!0),[b,x]=(0,C.useState)(null),[S,w]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:engine-mcp-list-width`));return Number.isFinite(e)&&e>=160&&e<=520?e:220});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:engine-mcp-list-width`,String(S))},[S]);let T=(0,C.useRef)(!1),E=e=>{e.preventDefault(),T.current=!0;let t=e.clientX,n=S,r=e=>{T.current&&w(Math.min(520,Math.max(160,n+(e.clientX-t))))},i=()=>{T.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},D=(0,C.useCallback)(async()=>{y(!0);try{let e=await fetch(`/api/mcp`),t=await e.json();if(!e.ok){a(typeof t.error==`string`?t.error:`HTTP ${e.status}`);return}r(t),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}finally{y(!1)}},[]);(0,C.useEffect)(()=>{D()},[D,e.engine]);let O=async(e,t)=>{l(t),s(null);try{let t=await(await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json();r(t),s(t.actionError??t.notice??null);let n=t.added?.[0];if(e.action===`add`&&n!==void 0){let t=e.scope===`project`?`project`:`global`;x(`${t}:${n}`)}}catch(e){s(e instanceof Error?e.message:String(e))}finally{l(null),_(null)}},k=n?.can,A=n?.servers??[],j=A.find(e=>bS(e)===b)??null,M=[`project`,`global`].map(e=>({scope:e,items:A.filter(t=>t.scope===e)})).filter(e=>e.items.length>0||e.scope===`global`&&A.length===0);return(0,Q.jsxs)(`div`,{className:`mcp engine-panel engine-panel-mcp`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-head`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-engine`,children:n?.engine??e.engine}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:n?.source??e.source??``}),(0,Q.jsxs)(`span`,{className:`engine-panel-count`,children:[n?.enabled??0,`/`,n?.total??0,` `,t(`启用`,`enabled`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`engine-panel-refresh`,onClick:()=>void D(),disabled:c!==null,children:t(`刷新`,`Refresh`)})]}),i?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:i}):null,n?.errors?.map(e=>(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:e},e)),o?(0,Q.jsx)(`div`,{className:`engine-panel-notice`,children:o}):null,(0,Q.jsxs)(`div`,{className:`mcp-shell`,style:{"--mcp-list-width":`${S}px`},children:[(0,Q.jsxs)(`div`,{className:`mcp-list`,children:[(0,Q.jsxs)(`div`,{className:`mcp-list-scroll`,children:[v&&n===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t(`正在读当前引擎的 MCP 配置…`,`Reading the current engine's MCP config…`)}):null,M.map(e=>(0,Q.jsxs)(`div`,{className:`mcp-group`,children:[(0,Q.jsxs)(`div`,{className:`mcp-group-head`,children:[(0,Q.jsx)(`span`,{children:e.scope===`project`?t(`项目`,`Project`):t(`全局`,`Global`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.items.filter(e=>e.enabled).length,`/`,e.items.length]})]}),e.items.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:t(`还没有 MCP 服务器`,`No MCP servers yet`)}):e.items.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`mcp-item${b===bS(e)?` mcp-item-on`:``}${e.enabled?``:` mcp-item-off`}`,title:e.description??e.name,onClick:()=>{x(bS(e)),p(!1)},children:[(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`mcp-item-name`,children:e.name})]},bS(e))),e.scope===`project`&&e.items.length>0&&n?.projectPath?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:n.projectPath,children:n.projectPath}):null,e.scope===`global`&&n?.globalPath?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:n.globalPath,children:n.globalPath}):null]},e.scope))]}),k?.add?(0,Q.jsx)(`div`,{className:`mcp-left-actions`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${f?` btn-on`:``}`,onClick:()=>p(e=>!e),children:[`+ `,t(`添加 MCP`,`Add MCP`)]})}):null]}),(0,Q.jsx)(`div`,{className:`mcp-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":t(`调整服务器列表宽度`,`Resize the server list`),title:t(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:E,onDoubleClick:()=>w(220)}),(0,Q.jsx)(`div`,{className:`mcp-detail${f?` mcp-detail-pane`:``}`,children:f?(0,Q.jsxs)(`div`,{className:`mcp-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`strong`,{children:t(`添加 MCP`,`Add MCP`)}),n?.projectPath!==void 0&&n.projectPath!==``?(0,Q.jsx)(`div`,{className:`mcp-scope-tabs`,children:[`global`,`project`].map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`mcp-scope-tab${m===e?` mcp-scope-tab-on`:``}`,onClick:()=>h(e),children:e===`global`?t(`全局`,`Global`):t(`项目`,`Project`)},e))}):null,(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`写进引擎自己的配置文件`,`Written into the engine's own config`)})]}),(0,Q.jsx)(`textarea`,{value:u,onChange:e=>d(e.target.value),placeholder:t(`粘一段就行:URL / 命令行 / 各家 CLI 的 mcp add 命令 / JSON`,"Paste anything: a URL, a command line, a vendor `mcp add` command, or JSON"),rows:6}),(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:c!==null||u.trim()===``,onClick:async()=>{await O({action:`add`,text:u,scope:m},`add`),d(``),p(!1)},children:c===`add`?t(`添加中…`,`Adding…`):t(`添加`,`Add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>p(!1),children:t(`取消`,`Cancel`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:(m===`project`?n?.projectPath:n?.globalPath)??``})]})]}):j===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:A.length===0?t(`这个引擎还没有 MCP 服务器:点左下角「+ 添加 MCP」加一台(会写进 ${n?.globalPath??`它自己的配置`})。`,`This engine has no MCP servers yet — use "+ Add MCP" in the bottom-left (it writes into ${n?.globalPath??`its own config`}).`):t(`左边挑一台服务器看详情。`,`Pick a server on the left to see details.`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mcp-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge`,children:t(vS[j.scope],yS[j.scope])}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:j.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),k?.toggle?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:c!==null,onClick:()=>void O({action:`set-enabled`,name:j.name,scope:j.scope,enabled:!j.enabled},`toggle:${bS(j)}`),children:j.enabled?t(`停用`,`Disable`):t(`启用`,`Enable`)}):null,k?.remove?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${g===bS(j)?` btn-danger`:``}`,disabled:c!==null,onClick:()=>{g===bS(j)?(O({action:`remove`,name:j.name,scope:j.scope},`remove:${bS(j)}`),x(null)):_(bS(j))},children:g===bS(j)?t(`确认删除`,`Confirm`):t(`删除`,`Remove`)}):null]}),(0,Q.jsxs)(`div`,{className:`mcp-body`,children:[(0,Q.jsx)(TS,{label:t(`状态`,`Status`),children:(0,Q.jsx)(`span`,{className:j.enabled?`mcp-state-on`:`mcp-state-off`,children:j.enabled?t(`已启用`,`enabled`):t(`已停用`,`disabled`)})}),(0,Q.jsxs)(TS,{label:t(`作用域`,`Scope`),children:[t(vS[j.scope],yS[j.scope]),` ·`,` `,(0,Q.jsx)(`code`,{className:`mono`,children:j.source})]}),(0,Q.jsx)(TS,{label:t(`传输`,`Transport`),children:j.transport}),(0,Q.jsx)(TS,{label:j.transport===`http`?`URL`:t(`命令`,`Command`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.transport===`http`?j.url??``:SS(j)})}),j.cwd!==void 0&&j.cwd!==``?(0,Q.jsx)(TS,{label:t(`工作目录`,`cwd`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.cwd})}):null,j.env&&Object.keys(j.env).length>0?(0,Q.jsx)(TS,{label:t(`环境变量`,`Env`),children:(0,Q.jsx)(`span`,{className:`mono`,children:Object.keys(j.env).map(e=>`${e}=***`).join(` `)})}):null,j.headers&&Object.keys(j.headers).length>0?(0,Q.jsx)(TS,{label:t(`请求头`,`Headers`),children:(0,Q.jsx)(`span`,{className:`mono`,children:Object.keys(j.headers).map(e=>`${e}: ***`).join(` `)})}):null,j.envRefs.length>0?(0,Q.jsx)(TS,{label:t(`引用的变量`,`Referenced vars`),children:(0,Q.jsx)(`span`,{className:`mono`,children:j.envRefs.map(e=>`${e.key} → ${e.variable}`).join(` `)})}):null,(0,Q.jsx)(TS,{label:t(`工具`,`Tools`),children:j.tools!==void 0&&j.tools.length>0?(0,Q.jsxs)(`span`,{children:[`${j.tools.length} ${t(`个`,``)}`,(0,Q.jsx)(`span`,{className:`side-panel-count`,children:`${t(`:`,`: `)}${j.tools.slice(0,8).map(e=>e.name).join(` · `)}${j.tools.length>8?` …`:``}`})]}):(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`引擎没报工具清单(打开会话后由引擎自己加载)`,`The engine did not report a tool list`)})}),j.description!==void 0&&j.description!==``?(0,Q.jsx)(TS,{label:t(`描述`,`Description`),children:j.description}):null,j.note!==void 0&&j.note!==``?(0,Q.jsx)(TS,{label:t(`说明`,`Note`),children:j.note}):null,j.override!==void 0&&j.override!==``?(0,Q.jsx)(TS,{label:t(`覆盖`,`Override`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.override})}):null]})]})})]}),(0,Q.jsx)(`div`,{className:`engine-panel-foot`,children:t(`这些配置属于当前引擎自己;切换引擎会换成那个引擎的清单。`,`These settings belong to the current engine; switching engines switches the list.`)})]})}function TS({label:e,children:t}){return(0,Q.jsxs)(`div`,{className:`mcp-row`,children:[(0,Q.jsx)(`span`,{className:`mcp-row-key`,children:e}),(0,Q.jsx)(`span`,{className:`mcp-row-value`,children:t})]})}function ES(e){let t=J(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(``),f=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/plugins`),t=await e.json();if(!e.ok){a(typeof t.error==`string`?t.error:`HTTP ${e.status}`);return}r(t),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{f()},[f,e.engine]);let p=async(e,t)=>{l(t),s(null);try{let t=await(await fetch(`/api/plugins`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json();r(t),s(t.actionError??t.notice??null)}catch(e){s(e instanceof Error?e.message:String(e))}finally{l(null)}},m=n?.can,h=n?.packages??[];return(0,Q.jsxs)(`div`,{className:`engine-panel`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-head`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-engine`,children:n?.engine??e.engine}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:n?.source??``}),(0,Q.jsx)(`button`,{type:`button`,className:`engine-panel-refresh`,onClick:()=>void f(),disabled:c!==null,children:t(`刷新`,`Refresh`)})]}),n?.note?(0,Q.jsx)(`div`,{className:`engine-panel-note-text`,children:n.note}):null,i?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:i}):null,n?.error?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:n.error}):null,o?(0,Q.jsx)(`div`,{className:`engine-panel-notice`,children:o}):null,n?.diagnostics?.map(e=>(0,Q.jsx)(`div`,{className:`engine-panel-row-note`,children:e.message},`${e.type}:${e.message}`)),m?.install?(0,Q.jsxs)(`div`,{className:`engine-panel-add`,children:[(0,Q.jsx)(`input`,{value:u,onChange:e=>d(e.target.value),placeholder:t(`插件 id(形如 name@marketplace)`,`plugin id, e.g. name@marketplace`)}),(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null||u.trim()===``,onClick:async()=>{await p({action:`install`,source:u.trim()},`install`),d(``)},children:t(`安装`,`Install`)})]}):null,h.length===0?(0,Q.jsx)(`div`,{className:`engine-panel-empty`,children:t(`这个引擎目前没有插件。`,`This engine currently has no plugins.`)}):(0,Q.jsx)(`div`,{className:`engine-panel-list`,children:h.map(e=>(0,Q.jsxs)(`div`,{className:`engine-panel-row`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-row-main`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-row-name`,children:e.name??e.source}),e.version?(0,Q.jsxs)(`span`,{className:`engine-panel-tag`,children:[`v`,e.version]}):null,(0,Q.jsx)(`span`,{className:`engine-panel-tag`,children:e.status===`missing`?t(`未安装`,`not installed`):e.status===`disabled`?t(`已停用`,`disabled`):e.status}),e.disabled&&e.status!==`disabled`?(0,Q.jsx)(`span`,{className:`engine-panel-tag`,children:t(`已停用`,`disabled`)}):null]}),e.description?(0,Q.jsx)(`div`,{className:`engine-panel-row-note`,children:e.description}):null,(0,Q.jsx)(`code`,{className:`engine-panel-row-cmd`,children:e.installedPath??e.source}),(0,Q.jsxs)(`div`,{className:`engine-panel-row-actions`,children:[m?.toggle?(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null,onClick:()=>void p({action:e.disabled?`enable`:`disable`,source:e.source},e.source),children:e.disabled?t(`启用`,`Enable`):t(`停用`,`Disable`)}):null,m?.remove?(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null,onClick:()=>void p({action:`remove`,source:e.source},e.source),children:t(`卸载`,`Remove`)}):null]})]},e.source))}),(0,Q.jsx)(`div`,{className:`engine-panel-foot`,children:t(`这些插件属于当前引擎自己;切换引擎会换成那个引擎的清单。`,`These plugins belong to the current engine; switching engines switches the list.`)})]})}var DS={extensions:`扩展`,skills:`技能`,prompts:`模板`,themes:`主题`},OS={extensions:`extensions`,skills:`skills`,prompts:`prompts`,themes:`themes`},kS={loaded:`已加载`,installed:`已安装`,missing:`缺失`,disabled:`已停用`},AS={loaded:`loaded`,installed:`installed`,missing:`missing`,disabled:`disabled`};function jS(e){return`${e.scope}:${e.source}`}function MS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function NS(e){let t=Object.keys(DS).filter(t=>e[t]>0).map(t=>`${q(DS[t],OS[t])} ${e[t]}`);return t.length>0?t.join(` · `):q(`没有加载出资源`,`no resources loaded`)}function PS(){let e=J(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(`global`),[p,m]=(0,C.useState)(null),h=e=>{e.packages&&n(e),i(e.actionError??(typeof e.error==`string`?e.error:null)),o(e.notice??null)},g=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/plugins`),t=await e.json();if(!e.ok){i(MS(t,e.status));return}h(t)}catch(e){i(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{g()},[g]);let _=async(e,t)=>{let n=e+`:`+(t?jS(t):`new`);c(n),o(null);try{let n=await fetch(`/api/plugins`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:e,source:t?.source??l,scope:t?.scope??d})}),r=await n.json();if(!n.ok){i(MS(r,n.status));return}h(r),e===`install`&&u(``)}catch(e){i(e instanceof Error?e.message:String(e))}finally{c(null),m(null)}};if(t===null)return(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取插件…`,`Loading plugins…`)});let v=t.packages??[],y=t.extensions??[],b=t.diagnostics??[],x=[{scope:`global`,label:e(`全局`,`Global`),items:v.filter(e=>e.scope===`global`)},{scope:`project`,label:e(`项目`,`Project`),items:v.filter(e=>e.scope===`project`)}].filter(e=>e.items.length>0),S=t=>{let n=jS(t),r=s!==null;return(0,Q.jsxs)(`div`,{className:`plugin-row${t.disabled?` plugin-row-off`:``}`,children:[(0,Q.jsxs)(`div`,{className:`plugin-main`,children:[(0,Q.jsxs)(`span`,{className:`plugin-name`,children:[t.name??t.source,t.disabled?(0,Q.jsx)(`span`,{className:`plugin-badge`,children:e(`已停用`,`Disabled`)}):null,t.filtered&&!t.disabled?(0,Q.jsx)(`span`,{className:`plugin-badge plugin-badge-filtered`,children:e(`已过滤`,`Filtered`)}):null,t.version?(0,Q.jsxs)(`span`,{className:`plugin-version`,children:[`v`,t.version]}):null,!t.version&&t.configuredVersion?(0,Q.jsx)(`span`,{className:`plugin-version`,children:t.configuredVersion}):null]}),(0,Q.jsxs)(`span`,{className:`plugin-meta`,title:t.resources.length>0?t.resources.map(e=>e.relativePath).join(`
54
+ how to do it…`;function uS({root:e,tab:t,onTab:n,onInstalled:r}){let i=Y(),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(``),[h,g]=(0,C.useState)(``),_=async e=>await(await fetch(`/api/skills/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json(),v=async()=>{u(`list`),f(null),c(null);try{let e=await _({source:`git`,repoUrl:a});e.ok===!0?c(e.skills):f(e.error??e.installError??i(`拉取失败`,`Failed to fetch`))}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}},y=async e=>{u(e);try{let t=await _({source:`git`,repoUrl:a,skill:e});r(t),t.notice===void 0?t.installError!==void 0&&f(t.installError):c(t=>t?.filter(t=>t!==e)??null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}},b=async()=>{u(`create`);try{let e=await _({source:`manual`,name:p,raw:h});r(e),e.notice===void 0?e.installError!==void 0&&f(e.installError):(m(``),g(``))}catch(e){f(e instanceof Error?e.message:String(e))}finally{u(null)}};return(0,Q.jsxs)(`div`,{className:`skills-install-pane`,children:[(0,Q.jsxs)(`div`,{className:`skills-tabs`,role:`tablist`,"aria-label":i(`安装方式`,`Install method`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>n(`hub`),children:i(`技能库`,`Skill hub`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===`git`,className:`skills-tab${t===`git`?` skills-tab-on`:``}`,onClick:()=>n(`git`),children:i(`Git 仓库`,`Git repo`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===`manual`,className:`skills-tab${t===`manual`?` skills-tab-on`:``}`,onClick:()=>n(`manual`),children:i(`手动创建`,`Create by hand`)})]}),d===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:d}),t===`git`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-repo-url`,children:i(`Git 仓库地址`,`Git repo URL`)}),(0,Q.jsxs)(`div`,{className:`skills-row`,children:[(0,Q.jsx)(`input`,{id:`skill-repo-url`,className:`skills-input mono`,value:a,placeholder:i(`https://github.com/anthropics/skills 或 git@github.com:user/repo.git`,`https://github.com/anthropics/skills or git@github.com:user/repo.git`),onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&a.trim()!==``&&v()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l!==null||a.trim()===``,onClick:()=>void v(),children:l===`list`?i(`克隆中…`,`Cloning…`):i(`拉取列表`,`Fetch the list`)})]}),(0,Q.jsxs)(`span`,{className:`side-panel-hint`,children:[i(`会把仓库浅克隆一份(`,`Shallow-clones the repo (`),(0,Q.jsx)(`code`,{children:`--depth 1`}),i(`)到临时目录,列出根目录与`,`) into a temp folder and lists the folders in the root and in`),` `,(0,Q.jsx)(`code`,{children:`skills/`}),i(` 下带 `,` subfolders with `),(0,Q.jsx)(`code`,{children:`SKILL.md`}),i(`的目录,装完即删。安装是`,` — the clone is deleted afterwards. Installing copies`),(0,Q.jsx)(`strong`,{children:i(`整目录`)}),i(`复制(脚本、references 都带上)。`,` (scripts and references included).`)]}),s===null?null:(0,Q.jsxs)(`div`,{className:`skills-repo-list`,children:[(0,Q.jsxs)(`span`,{className:`skills-label`,children:[i(`仓库里有`,`The repo has`),` `,s.length,` `,i(`个技能`,`skills`)]}),s.map(t=>(0,Q.jsxs)(`div`,{className:`skills-repo-row`,children:[(0,Q.jsx)(`span`,{className:`skill-slug mono`,children:t}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l!==null,onClick:()=>void y(t),title:i(`装到 ${e}/${t}`,`Install into ${e}/${t}`),children:l===t?i(`安装中…`,`Installing…`):i(`安装`,`Install`)})]},t))]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-manual-name`,children:i(`技能名(目录名)`,`Skill name (folder name)`)}),(0,Q.jsx)(`input`,{id:`skill-manual-name`,className:`skills-input`,value:p,placeholder:`my-skill`,onChange:e=>m(e.target.value)}),(0,Q.jsx)(`label`,{className:`skills-label`,htmlFor:`skill-manual-raw`,children:i(`SKILL.md(可留空,留空就写一份骨架)`,`SKILL.md (optional — leave empty to write a skeleton)`)}),(0,Q.jsx)(`textarea`,{id:`skill-manual-raw`,className:`skills-input skills-textarea mono`,value:h,placeholder:i(cS,lS),onChange:e=>g(e.target.value)}),(0,Q.jsxs)(`div`,{className:`skills-row`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:l!==null||p.trim()===``,onClick:()=>void b(),children:l===`create`?i(`创建中…`,`Creating…`):i(`创建`,`Create`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[i(`写到`,`Written to`),` `,e,`/<name>/SKILL.md`]})]})]})]})}var dS=`pop-agent:skills-list-width`;function fS(){let e=Y(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(!1),[d,f]=(0,C.useState)(``),[p,m]=(0,C.useState)(`all`),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(new Set),[y,b]=(0,C.useState)(null),[x,S]=(0,C.useState)({kind:`detail`}),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(null),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(dS));return Number.isFinite(e)&&e>=180&&e<=520?e:260});(0,C.useEffect)(()=>{localStorage.setItem(dS,String(O))},[O]);let A=(0,C.useRef)(!1),j=e=>{e.preventDefault(),A.current=!0;let t=e.clientX,n=O,r=e=>{A.current&&k(Math.min(520,Math.max(180,n+(e.clientX-t))))},i=()=>{A.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},M=(0,C.useCallback)(e=>{e.skills&&n(e.skills)},[]),N=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/skills`),t=await e.json();if(!e.ok){o(tS(t,e.status));return}n(t.skills??[]),t.root!==void 0&&i(t.root),o(null),b(e=>{if(e!==null)return e;let n=t.skills?.[0];return n!==void 0&&R(n,iS(n.files)[0]??`SKILL.md`),n?.id??null})}catch(e){o(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{N()},[N]);let P=e=>{if(M(e),e.notice!==void 0){c(e.notice),o(null);let n=e.skills?.find(e=>!t?.some(t=>t.id===e.id));n&&(b(n.id),S({kind:`detail`}),R(n,iS(n.files)[0]??`SKILL.md`))}e.installError!==void 0&&o(e.installError)},F=async(t,n)=>{if(t.length!==0){u(!0);try{let r=await fetch(`/api/skills/enabled`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:t,enabled:n})}),i=await r.json();r.ok?(i.errors??[]).length>0&&o((i.errors??[]).join(`;`)):o(i.error?.message??`HTTP ${r.status}`),M(i),v(new Set),c(n?e(`已启用`,`Enabled`):e(`已停用`,`Disabled`))}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1)}}},I=async e=>{if(e.length!==0){u(!0);try{let t=await(await fetch(`/api/skills/remove`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({ids:e})})).json();M(t),t.notice!==void 0&&(c(t.notice),v(new Set),t.skills!==void 0&&(b(t.skills[0]?.id??null),T(null))),t.removeError!==void 0&&o(t.removeError)}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1),D(null)}}},L=async e=>{u(!0);try{let t=await(await fetch(`/api/skills/remove`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e})})).json();M(t),t.notice!==void 0&&(c(t.notice),t.skills!==void 0&&b(t.skills[0]?.id??null),T(null)),t.removeError!==void 0&&o(t.removeError)}catch(e){o(e instanceof Error?e.message:String(e))}finally{u(!1),D(null)}},R=async(t,n)=>{T({path:n,preview:null});let r=await fetch(`/api/skills/${encodeURIComponent(t.id)}/file?path=${encodeURIComponent(n)}`),i=await r.json();T({path:n,preview:r.ok?{text:i.text??``,bytes:i.bytes??0,binary:i.binary===!0}:{text:i.error?.message??e(`读取失败`,`Failed to read`),bytes:0,binary:!1}})};if(t===null)return(0,Q.jsx)(`div`,{className:`skills`,children:a===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取技能目录…`,`Reading the skills folder…`)}):(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[e(`读不到技能目录:`,`Cannot read the skills folder: `),a]})});let z=t.filter(e=>p===`all`||(p===`enabled`?e.enabled:!e.enabled)),B=rS(z,d),V=t.find(e=>e.id===y)??null,H=t.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`skills`,children:[(0,Q.jsxs)(`div`,{className:`skills-shell`,style:{"--skills-list-width":`${O}px`},children:[(0,Q.jsx)(oS,{skills:t,tab:p,onTab:e=>{m(e),v(new Set)},query:d,onQuery:f,byTab:z,shown:B,selected:y,selecting:h,picked:_,onPicked:v,onSelecting:e=>{g(e),v(new Set)},busy:l,confirmRemove:E,installOpen:x.kind===`install`,onOpenInstall:()=>S(x.kind===`install`?{kind:`detail`}:{kind:`install`,tab:`hub`}),onOpenDetail:e=>{b(e.id),S({kind:`detail`}),R(e,iS(e.files)[0]??`SKILL.md`)},onBatchEnabled:e=>void F([..._],e),onBatchRemove:()=>E===`batch`?void I([..._]):D(`batch`),onEnableAll:()=>void F(z.filter(e=>!e.enabled).map(e=>e.id),!0)}),(0,Q.jsx)(`div`,{className:`skills-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整技能列表宽度`,`Resize the skills list`),title:e(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:j,onDoubleClick:()=>k(260)}),(0,Q.jsx)(`div`,{className:`skills-detail${x.kind===`detail`?``:` skills-detail-pane`}`,children:x.kind===`install`&&x.tab===`hub`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`skills-tabs`,role:`tablist`,"aria-label":e(`安装方式`,`Install method`),children:[(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!0,className:`skills-tab skills-tab-on`,children:e(`技能库`,`Skill hub`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>S({kind:`install`,tab:`git`}),children:e(`Git 仓库`,`Git repo`)}),(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`skills-tab`,onClick:()=>S({kind:`install`,tab:`manual`}),children:e(`手动创建`,`Create by hand`)})]}),(0,Q.jsx)(sS,{root:r,onInstalled:P,onOpenGit:()=>S({kind:`install`,tab:`git`})})]}):x.kind===`install`?(0,Q.jsx)(uS,{root:r,tab:x.tab===`manual`?`manual`:`git`,onTab:e=>S({kind:`install`,tab:e}),onInstalled:P}):V===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`左边挑一个技能,或者点「+ 安装技能」去技能库装。`,`Pick a skill on the left, or use “+ Install skill” to browse the hub.`)}):(0,Q.jsx)(aS,{skill:V,detail:w,busy:l,confirmRemove:E,onFile:e=>void R(V,e),onToggle:()=>void F([V.id],!V.enabled),onRemove:()=>E===V.id?void L(V.id):D(V.id)})})]}),(0,Q.jsxs)(`div`,{className:`skills-bar`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已安装`,`Installed`),` `,t.length,` `,e(`个`,``),` · `,e(`已启用`,`enabled`),` `,H,` ·`,` `,e(`目录`,`folder`),` `,(0,Q.jsx)(`code`,{children:r})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l,onClick:()=>void N(),children:e(`刷新`,`Refresh`)})]}),a===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:a}),s===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s})]})}var pS={codemode:`代码模式(默认)`,deferred:`搜索后声明`,direct:`直接声明`,hidden:`不暴露`},mS={codemode:`Code mode (default)`,deferred:`Declared after search`,direct:`Declared directly`,hidden:`Hidden`},hS={codemode:`只列出服务器名称和简介,代码模式脚本按需搜索它的工具。`,deferred:`模型先用 tool_search 搜到、下一轮才声明出来,然后直接调用。`,direct:`像内置工具一样直接声明给模型,最省事也最占上下文。`,hidden:`注册但不暴露:工具还在,模型碰不到。`},gS={codemode:`Only the server name and summary are listed; code-mode scripts search its tools on demand.`,deferred:`The model finds it with tool_search, it is declared on the next turn, then called directly.`,direct:`Declared to the model like a built-in tool: simplest, but uses the most context.`,hidden:`Registered but hidden: the tools exist, the model cannot reach them.`};function _S(e){return e!==void 0&&/requires authentication|unauthori[sz]ed|invalid_token|\b401\b/i.test(e)}var vS={global:`全局`,project:`项目`},yS={global:`Global`,project:`Project`};function bS(e){return`${e.scope}:${e.name}`}function xS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function SS(e){return[e.command??``,...e.args??[]].filter(e=>e!==``).join(` `)}function CS(e){return e.startsWith(`!`)}function wS(e){let t=Y(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(``),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(`global`),[g,_]=(0,C.useState)(null),[v,y]=(0,C.useState)(!0),[b,x]=(0,C.useState)(null),[S,w]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:engine-mcp-list-width`));return Number.isFinite(e)&&e>=160&&e<=520?e:220});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:engine-mcp-list-width`,String(S))},[S]);let T=(0,C.useRef)(!1),E=e=>{e.preventDefault(),T.current=!0;let t=e.clientX,n=S,r=e=>{T.current&&w(Math.min(520,Math.max(160,n+(e.clientX-t))))},i=()=>{T.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},D=(0,C.useCallback)(async()=>{y(!0);try{let e=await fetch(`/api/mcp`),t=await e.json();if(!e.ok){a(typeof t.error==`string`?t.error:`HTTP ${e.status}`);return}r(t),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}finally{y(!1)}},[]);(0,C.useEffect)(()=>{D()},[D,e.engine]);let O=async(e,t)=>{l(t),s(null);try{let t=await(await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json();r(t),s(t.actionError??t.notice??null);let n=t.added?.[0];if(e.action===`add`&&n!==void 0){let t=e.scope===`project`?`project`:`global`;x(`${t}:${n}`)}}catch(e){s(e instanceof Error?e.message:String(e))}finally{l(null),_(null)}},k=n?.can,A=n?.servers??[],j=A.find(e=>bS(e)===b)??null,M=[`project`,`global`].map(e=>({scope:e,items:A.filter(t=>t.scope===e)})).filter(e=>e.items.length>0||e.scope===`global`&&A.length===0);return(0,Q.jsxs)(`div`,{className:`mcp engine-panel engine-panel-mcp`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-head`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-engine`,children:n?.engine??e.engine}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:n?.source??e.source??``}),(0,Q.jsxs)(`span`,{className:`engine-panel-count`,children:[n?.enabled??0,`/`,n?.total??0,` `,t(`启用`,`enabled`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`engine-panel-refresh`,onClick:()=>void D(),disabled:c!==null,children:t(`刷新`,`Refresh`)})]}),i?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:i}):null,n?.errors?.map(e=>(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:e},e)),o?(0,Q.jsx)(`div`,{className:`engine-panel-notice`,children:o}):null,(0,Q.jsxs)(`div`,{className:`mcp-shell`,style:{"--mcp-list-width":`${S}px`},children:[(0,Q.jsxs)(`div`,{className:`mcp-list`,children:[(0,Q.jsxs)(`div`,{className:`mcp-list-scroll`,children:[v&&n===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:t(`正在读当前引擎的 MCP 配置…`,`Reading the current engine's MCP config…`)}):null,M.map(e=>(0,Q.jsxs)(`div`,{className:`mcp-group`,children:[(0,Q.jsxs)(`div`,{className:`mcp-group-head`,children:[(0,Q.jsx)(`span`,{children:e.scope===`project`?t(`项目`,`Project`):t(`全局`,`Global`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.items.filter(e=>e.enabled).length,`/`,e.items.length]})]}),e.items.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:t(`还没有 MCP 服务器`,`No MCP servers yet`)}):e.items.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`mcp-item${b===bS(e)?` mcp-item-on`:``}${e.enabled?``:` mcp-item-off`}`,title:e.description??e.name,onClick:()=>{x(bS(e)),p(!1)},children:[(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`mcp-item-name`,children:e.name})]},bS(e))),e.scope===`project`&&e.items.length>0&&n?.projectPath?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:n.projectPath,children:n.projectPath}):null,e.scope===`global`&&n?.globalPath?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:n.globalPath,children:n.globalPath}):null]},e.scope))]}),k?.add?(0,Q.jsx)(`div`,{className:`mcp-left-actions`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${f?` btn-on`:``}`,onClick:()=>p(e=>!e),children:[`+ `,t(`添加 MCP`,`Add MCP`)]})}):null]}),(0,Q.jsx)(`div`,{className:`mcp-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":t(`调整服务器列表宽度`,`Resize the server list`),title:t(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:E,onDoubleClick:()=>w(220)}),(0,Q.jsx)(`div`,{className:`mcp-detail${f?` mcp-detail-pane`:``}`,children:f?(0,Q.jsxs)(`div`,{className:`mcp-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`strong`,{children:t(`添加 MCP`,`Add MCP`)}),n?.projectPath!==void 0&&n.projectPath!==``?(0,Q.jsx)(`div`,{className:`mcp-scope-tabs`,children:[`global`,`project`].map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`mcp-scope-tab${m===e?` mcp-scope-tab-on`:``}`,onClick:()=>h(e),children:e===`global`?t(`全局`,`Global`):t(`项目`,`Project`)},e))}):null,(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`写进引擎自己的配置文件`,`Written into the engine's own config`)})]}),(0,Q.jsx)(`textarea`,{value:u,onChange:e=>d(e.target.value),placeholder:t(`粘一段就行:URL / 命令行 / 各家 CLI 的 mcp add 命令 / JSON`,"Paste anything: a URL, a command line, a vendor `mcp add` command, or JSON"),rows:6}),(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:c!==null||u.trim()===``,onClick:async()=>{await O({action:`add`,text:u,scope:m},`add`),d(``),p(!1)},children:c===`add`?t(`添加中…`,`Adding…`):t(`添加`,`Add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>p(!1),children:t(`取消`,`Cancel`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:(m===`project`?n?.projectPath:n?.globalPath)??``})]})]}):j===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:A.length===0?t(`这个引擎还没有 MCP 服务器:点左下角「+ 添加 MCP」加一台(会写进 ${n?.globalPath??`它自己的配置`})。`,`This engine has no MCP servers yet — use "+ Add MCP" in the bottom-left (it writes into ${n?.globalPath??`its own config`}).`):t(`左边挑一台服务器看详情。`,`Pick a server on the left to see details.`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mcp-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge`,children:t(vS[j.scope],yS[j.scope])}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:j.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),k?.toggle?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:c!==null,onClick:()=>void O({action:`set-enabled`,name:j.name,scope:j.scope,enabled:!j.enabled},`toggle:${bS(j)}`),children:j.enabled?t(`停用`,`Disable`):t(`启用`,`Enable`)}):null,k?.remove?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${g===bS(j)?` btn-danger`:``}`,disabled:c!==null,onClick:()=>{g===bS(j)?(O({action:`remove`,name:j.name,scope:j.scope},`remove:${bS(j)}`),x(null)):_(bS(j))},children:g===bS(j)?t(`确认删除`,`Confirm`):t(`删除`,`Remove`)}):null]}),(0,Q.jsxs)(`div`,{className:`mcp-body`,children:[(0,Q.jsx)(TS,{label:t(`状态`,`Status`),children:(0,Q.jsx)(`span`,{className:j.enabled?`mcp-state-on`:`mcp-state-off`,children:j.enabled?t(`已启用`,`enabled`):t(`已停用`,`disabled`)})}),(0,Q.jsxs)(TS,{label:t(`作用域`,`Scope`),children:[t(vS[j.scope],yS[j.scope]),` ·`,` `,(0,Q.jsx)(`code`,{className:`mono`,children:j.source})]}),(0,Q.jsx)(TS,{label:t(`传输`,`Transport`),children:j.transport}),(0,Q.jsx)(TS,{label:j.transport===`http`?`URL`:t(`命令`,`Command`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.transport===`http`?j.url??``:SS(j)})}),j.cwd!==void 0&&j.cwd!==``?(0,Q.jsx)(TS,{label:t(`工作目录`,`cwd`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.cwd})}):null,j.env&&Object.keys(j.env).length>0?(0,Q.jsx)(TS,{label:t(`环境变量`,`Env`),children:(0,Q.jsx)(`span`,{className:`mono`,children:Object.keys(j.env).map(e=>`${e}=***`).join(` `)})}):null,j.headers&&Object.keys(j.headers).length>0?(0,Q.jsx)(TS,{label:t(`请求头`,`Headers`),children:(0,Q.jsx)(`span`,{className:`mono`,children:Object.keys(j.headers).map(e=>`${e}: ***`).join(` `)})}):null,j.envRefs.length>0?(0,Q.jsx)(TS,{label:t(`引用的变量`,`Referenced vars`),children:(0,Q.jsx)(`span`,{className:`mono`,children:j.envRefs.map(e=>`${e.key} → ${e.variable}`).join(` `)})}):null,(0,Q.jsx)(TS,{label:t(`工具`,`Tools`),children:j.tools!==void 0&&j.tools.length>0?(0,Q.jsxs)(`span`,{children:[`${j.tools.length} ${t(`个`,``)}`,(0,Q.jsx)(`span`,{className:`side-panel-count`,children:`${t(`:`,`: `)}${j.tools.slice(0,8).map(e=>e.name).join(` · `)}${j.tools.length>8?` …`:``}`})]}):(0,Q.jsx)(`span`,{className:`side-panel-count`,children:t(`引擎没报工具清单(打开会话后由引擎自己加载)`,`The engine did not report a tool list`)})}),j.description!==void 0&&j.description!==``?(0,Q.jsx)(TS,{label:t(`描述`,`Description`),children:j.description}):null,j.note!==void 0&&j.note!==``?(0,Q.jsx)(TS,{label:t(`说明`,`Note`),children:j.note}):null,j.override!==void 0&&j.override!==``?(0,Q.jsx)(TS,{label:t(`覆盖`,`Override`),children:(0,Q.jsx)(`code`,{className:`mono`,children:j.override})}):null]})]})})]}),(0,Q.jsx)(`div`,{className:`engine-panel-foot`,children:t(`这些配置属于当前引擎自己;切换引擎会换成那个引擎的清单。`,`These settings belong to the current engine; switching engines switches the list.`)})]})}function TS({label:e,children:t}){return(0,Q.jsxs)(`div`,{className:`mcp-row`,children:[(0,Q.jsx)(`span`,{className:`mcp-row-key`,children:e}),(0,Q.jsx)(`span`,{className:`mcp-row-value`,children:t})]})}function ES(e){let t=Y(),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(``),f=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/plugins`),t=await e.json();if(!e.ok){a(typeof t.error==`string`?t.error:`HTTP ${e.status}`);return}r(t),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{f()},[f,e.engine]);let p=async(e,t)=>{l(t),s(null);try{let t=await(await fetch(`/api/plugins`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)})).json();r(t),s(t.actionError??t.notice??null)}catch(e){s(e instanceof Error?e.message:String(e))}finally{l(null)}},m=n?.can,h=n?.packages??[];return(0,Q.jsxs)(`div`,{className:`engine-panel`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-head`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-engine`,children:n?.engine??e.engine}),(0,Q.jsx)(`code`,{className:`engine-panel-source`,children:n?.source??``}),(0,Q.jsx)(`button`,{type:`button`,className:`engine-panel-refresh`,onClick:()=>void f(),disabled:c!==null,children:t(`刷新`,`Refresh`)})]}),n?.note?(0,Q.jsx)(`div`,{className:`engine-panel-note-text`,children:n.note}):null,i?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:i}):null,n?.error?(0,Q.jsx)(`div`,{className:`engine-panel-error`,children:n.error}):null,o?(0,Q.jsx)(`div`,{className:`engine-panel-notice`,children:o}):null,n?.diagnostics?.map(e=>(0,Q.jsx)(`div`,{className:`engine-panel-row-note`,children:e.message},`${e.type}:${e.message}`)),m?.install?(0,Q.jsxs)(`div`,{className:`engine-panel-add`,children:[(0,Q.jsx)(`input`,{value:u,onChange:e=>d(e.target.value),placeholder:t(`插件 id(形如 name@marketplace)`,`plugin id, e.g. name@marketplace`)}),(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null||u.trim()===``,onClick:async()=>{await p({action:`install`,source:u.trim()},`install`),d(``)},children:t(`安装`,`Install`)})]}):null,h.length===0?(0,Q.jsx)(`div`,{className:`engine-panel-empty`,children:t(`这个引擎目前没有插件。`,`This engine currently has no plugins.`)}):(0,Q.jsx)(`div`,{className:`engine-panel-list`,children:h.map(e=>(0,Q.jsxs)(`div`,{className:`engine-panel-row`,children:[(0,Q.jsxs)(`div`,{className:`engine-panel-row-main`,children:[(0,Q.jsx)(`span`,{className:`engine-panel-row-name`,children:e.name??e.source}),e.version?(0,Q.jsxs)(`span`,{className:`engine-panel-tag`,children:[`v`,e.version]}):null,(0,Q.jsx)(`span`,{className:`engine-panel-tag`,children:e.status===`missing`?t(`未安装`,`not installed`):e.status===`disabled`?t(`已停用`,`disabled`):e.status}),e.disabled&&e.status!==`disabled`?(0,Q.jsx)(`span`,{className:`engine-panel-tag`,children:t(`已停用`,`disabled`)}):null]}),e.description?(0,Q.jsx)(`div`,{className:`engine-panel-row-note`,children:e.description}):null,(0,Q.jsx)(`code`,{className:`engine-panel-row-cmd`,children:e.installedPath??e.source}),(0,Q.jsxs)(`div`,{className:`engine-panel-row-actions`,children:[m?.toggle?(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null,onClick:()=>void p({action:e.disabled?`enable`:`disable`,source:e.source},e.source),children:e.disabled?t(`启用`,`Enable`):t(`停用`,`Disable`)}):null,m?.remove?(0,Q.jsx)(`button`,{type:`button`,disabled:c!==null,onClick:()=>void p({action:`remove`,source:e.source},e.source),children:t(`卸载`,`Remove`)}):null]})]},e.source))}),(0,Q.jsx)(`div`,{className:`engine-panel-foot`,children:t(`这些插件属于当前引擎自己;切换引擎会换成那个引擎的清单。`,`These plugins belong to the current engine; switching engines switches the list.`)})]})}var DS={extensions:`扩展`,skills:`技能`,prompts:`模板`,themes:`主题`},OS={extensions:`extensions`,skills:`skills`,prompts:`prompts`,themes:`themes`},kS={loaded:`已加载`,installed:`已安装`,missing:`缺失`,disabled:`已停用`},AS={loaded:`loaded`,installed:`installed`,missing:`missing`,disabled:`disabled`};function jS(e){return`${e.scope}:${e.source}`}function MS(e,t){return typeof e.error==`string`?e.error:e.error?.message??`HTTP ${t}`}function NS(e){let t=Object.keys(DS).filter(t=>e[t]>0).map(t=>`${J(DS[t],OS[t])} ${e[t]}`);return t.length>0?t.join(` · `):J(`没有加载出资源`,`no resources loaded`)}function PS(){let e=Y(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(``),[d,f]=(0,C.useState)(`global`),[p,m]=(0,C.useState)(null),h=e=>{e.packages&&n(e),i(e.actionError??(typeof e.error==`string`?e.error:null)),o(e.notice??null)},g=(0,C.useCallback)(async()=>{try{let e=await fetch(`/api/plugins`),t=await e.json();if(!e.ok){i(MS(t,e.status));return}h(t)}catch(e){i(e instanceof Error?e.message:String(e))}},[]);(0,C.useEffect)(()=>{g()},[g]);let _=async(e,t)=>{let n=e+`:`+(t?jS(t):`new`);c(n),o(null);try{let n=await fetch(`/api/plugins`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:e,source:t?.source??l,scope:t?.scope??d})}),r=await n.json();if(!n.ok){i(MS(r,n.status));return}h(r),e===`install`&&u(``)}catch(e){i(e instanceof Error?e.message:String(e))}finally{c(null),m(null)}};if(t===null)return(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取插件…`,`Loading plugins…`)});let v=t.packages??[],y=t.extensions??[],b=t.diagnostics??[],x=[{scope:`global`,label:e(`全局`,`Global`),items:v.filter(e=>e.scope===`global`)},{scope:`project`,label:e(`项目`,`Project`),items:v.filter(e=>e.scope===`project`)}].filter(e=>e.items.length>0),S=t=>{let n=jS(t),r=s!==null;return(0,Q.jsxs)(`div`,{className:`plugin-row${t.disabled?` plugin-row-off`:``}`,children:[(0,Q.jsxs)(`div`,{className:`plugin-main`,children:[(0,Q.jsxs)(`span`,{className:`plugin-name`,children:[t.name??t.source,t.disabled?(0,Q.jsx)(`span`,{className:`plugin-badge`,children:e(`已停用`,`Disabled`)}):null,t.filtered&&!t.disabled?(0,Q.jsx)(`span`,{className:`plugin-badge plugin-badge-filtered`,children:e(`已过滤`,`Filtered`)}):null,t.version?(0,Q.jsxs)(`span`,{className:`plugin-version`,children:[`v`,t.version]}):null,!t.version&&t.configuredVersion?(0,Q.jsx)(`span`,{className:`plugin-version`,children:t.configuredVersion}):null]}),(0,Q.jsxs)(`span`,{className:`plugin-meta`,title:t.resources.length>0?t.resources.map(e=>e.relativePath).join(`
55
55
  `):void 0,children:[(0,Q.jsx)(`span`,{className:`plugin-status plugin-status-${t.status}`,children:e(kS[t.status],AS[t.status])}),t.disabled?``:` · ${NS(t.counts)}`,t.description?` · ${t.description}`:``]}),(0,Q.jsx)(`span`,{className:`plugin-source mono`,title:t.installedPath??t.source,children:t.source})]}),(0,Q.jsxs)(`div`,{className:`plugin-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:r,onClick:()=>void _(`update`,t),title:e(`更新到源里的最新版本(钉了版本的源不会动)`,`Update to the latest version in the source (pinned versions stay put)`),children:s===`update:${n}`?e(`更新中…`,`Updating…`):e(`更新`,`Update`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${p===n?` btn-danger`:``}`,disabled:r,onClick:()=>p===n?void _(`remove`,t):m(n),onBlur:()=>m(e=>e===n?null:e),children:s===`remove:${n}`?e(`卸载中…`,`Removing…`):p===n?e(`确认卸载`,`Confirm remove`):e(`卸载`,`Remove`)}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":!t.disabled,"aria-label":`${t.disabled?e(`启用`,`Enable`):e(`停用`,`Disable`)} ${t.name??t.source}`,className:`plugin-switch${t.disabled?``:` plugin-switch-on`}`,disabled:r,onClick:()=>void _(t.disabled?`enable`:`disable`,t),children:t.disabled?e(`已停用`,`Disabled`):e(`已启用`,`Enabled`)})]})]},n)};return(0,Q.jsxs)(`div`,{className:`plugins`,children:[(0,Q.jsxs)(`div`,{className:`plugins-bar`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[v.length,` `,e(`个插件包`,`plugin packages`),` · `,y.length,` `,e(`个本机扩展`,`local extensions`),t.totals?` · ${e(`已加载`,`loaded`)}: ${NS(t.totals)}`:``]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null,onClick:()=>void g(),children:e(`刷新`,`Refresh`)})]}),(0,Q.jsxs)(`div`,{className:`plugins-install`,children:[(0,Q.jsx)(`input`,{className:`plugins-install-input mono`,value:l,placeholder:e(`npm:@scope/pi-plugin 或 git:https://github.com/user/repo 或 /本地目录`,`npm:@scope/pi-plugin or git:https://github.com/user/repo or /local/folder`),onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&l.trim()!==``&&_(`install`)}}),(0,Q.jsxs)(`select`,{className:`plugins-install-scope`,value:d,onChange:e=>f(e.target.value===`project`?`project`:`global`),title:e(`装到哪一份配置`,`Which config it installs into`),children:[(0,Q.jsx)(`option`,{value:`global`,children:e(`全局`,`Global`)}),(0,Q.jsx)(`option`,{value:`project`,disabled:t.projectLoaded===!1,children:e(`项目`,`Project`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null||l.trim()===``,onClick:()=>void _(`install`),children:s===`install:new`?e(`安装中…`,`Installing…`):e(`安装`,`Install`)})]}),r?(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:r}):null,a?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:a}):null,(0,Q.jsxs)(`div`,{className:`plugins-body`,children:[x.length===0&&y.length===0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e(`还没有插件。上面粘贴 npm / git / 本地目录装一个;也可以直接跑`,`No plugins yet. Paste an npm / git / local folder above to install one — or just run`),` `,(0,Q.jsx)(`code`,{children:e(`pi install npm:包名`)}),e(`。`,`.`)]}):null,x.map(t=>(0,Q.jsxs)(`div`,{className:`plugins-group`,children:[(0,Q.jsxs)(`div`,{className:`plugins-group-head`,children:[(0,Q.jsx)(`span`,{children:t.label}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[t.items.length,` `,e(`个包`,`packages`),` ·`,` `,t.scope===`global`?`~/.pi/agent/settings.json`:e(`<项目>/.pi/settings.json`,`<project>/.pi/settings.json`)]})]}),(0,Q.jsx)(`div`,{className:`plugin-list`,children:t.items.map(S)})]},t.scope)),(0,Q.jsxs)(`div`,{className:`plugins-group`,children:[(0,Q.jsxs)(`div`,{className:`plugins-group-head`,children:[(0,Q.jsx)(`span`,{children:e(`本机扩展`,`Local extensions`)}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:e(`不属于任何包的单文件扩展`,`Single-file extensions that belong to no package`)})]}),y.length===0?(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e(`没有本机扩展。写一个 .ts 扔进`,`No local extensions. Drop a .ts file into`),` `,(0,Q.jsx)(`code`,{children:`~/.pi/agent/extensions/`}),` `,e(`就会出现在这里。`,`and it will show up here.`)]}):(0,Q.jsx)(`div`,{className:`plugin-list`,children:y.map(t=>(0,Q.jsxs)(`div`,{className:`plugin-row${t.enabled?``:` plugin-row-off`}`,children:[(0,Q.jsxs)(`div`,{className:`plugin-main`,children:[(0,Q.jsxs)(`span`,{className:`plugin-name`,children:[t.name,(0,Q.jsx)(`span`,{className:`plugin-badge`,children:t.scope===`project`?e(`项目`,`Project`):e(`全局`,`Global`)})]}),(0,Q.jsx)(`span`,{className:`plugin-source mono`,title:t.path,children:t.path})]}),(0,Q.jsx)(`span`,{className:`plugin-meta`,children:t.enabled?e(`已启用`,`Enabled`):e(`已停用`,`Disabled`)})]},t.path))})]}),b.length>0?(0,Q.jsx)(`div`,{className:`plugins-diagnostics`,children:b.map((e,t)=>(0,Q.jsxs)(`div`,{className:`side-panel-hint${e.type===`error`?` side-error`:``}`,children:[e.source?(0,Q.jsx)(`code`,{children:e.source}):null,` `,e.message]},`${e.source??``}-${t}`))}):null]}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e(`资源构成与状态来自 pi 自己解析的结果,所以这里显示的就是会话真正加载的东西。启停只改「加载不加载」,不删文件;装 / 卸 / 更新会动 pi 的安装目录。以上都`,`Resources and their status come from pi's own resolution, so this is exactly what the session loads. Enabling or disabling only toggles loading (no files are deleted); install / remove / update touch pi's install directory. All of it is`),(0,Q.jsx)(`strong`,{children:e(`对新会话生效`,`effective for new sessions`)}),e(` —— 已经开着的对话在启动时就把扩展加载完了。`,` — conversations already open loaded their extensions at startup.`)]})]})}var FS=[{label:`URL`,value:`https://mcp.example.com/mcp`,hint:`streamable HTTP 地址`},{label:`命令行`,value:`npx -y @modelcontextprotocol/server-filesystem .`,hint:`stdio:npx / uvx / node / 绝对路径都行`},{label:`pi mcp add`,value:`pi mcp add docs --url https://mcp.example.com/mcp`,hint:`也认 claude / codex / gemini 的 mcp add`},{label:`JSON`,value:`{
56
56
  "mcpServers": {
57
57
  "filesystem": {
@@ -59,21 +59,21 @@ how to do it…`;function uS({root:e,tab:t,onTab:n,onInstalled:r}){let i=J(),[a,
59
59
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
60
60
  }
61
61
  }
62
- }`,hint:`mcpServers / VS Code 的 servers / 单条片段都认`}],IS=[{href:`https://glama.ai/mcp/servers`,label:`glama.ai`},{href:`https://smithery.ai/servers`,label:`smithery.ai`},{href:`https://mcp.so/`,label:`mcp.so`},{href:`https://registry.modelcontextprotocol.io/`,label:`MCP Registry`},{href:`https://github.com/mcp`,label:`github.com/mcp`}];function LS({text:e,onText:t,scope:n,scopePath:r,onScope:i,busy:a,onSubmit:o,onCancel:s}){let c=J(),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)([]),[p,m]=(0,C.useState)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(0),_=(0,C.useCallback)(async e=>{if(e.trim()===``){u(null),f([]),m(null);return}let t=++g.current;try{let n=await(await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`parse`,text:e})})).json();if(t!==g.current)return;if(f(n.notes??[]),n.actionError!==void 0){u(null),m(n.actionError);return}m(null),u((n.preview??[]).map(e=>({name:e.name,target:e.config.url??[e.config.command??``,...e.config.args??[]].filter(e=>e!==``).join(` `)})))}catch(e){if(t!==g.current)return;m(e instanceof Error?e.message:String(e)),u(null)}},[]);(0,C.useEffect)(()=>(h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>void _(e),350),()=>{h.current!==null&&window.clearTimeout(h.current)}),[e,_]);let v=!a&&e.trim()!==``&&p===null&&(l?.length??0)>0;return(0,Q.jsxs)(`div`,{className:`mcp-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:c(`添加 MCP`,`Add MCP`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),IS.map(e=>(0,Q.jsx)(`a`,{className:`mcp-catalog-link`,href:e.href,target:`_blank`,rel:`noreferrer`,children:e.label},e.href))]}),(0,Q.jsxs)(`div`,{className:`mcp-scope-row`,children:[(0,Q.jsx)(`div`,{className:`mcp-scope-tabs`,role:`tablist`,"aria-label":c(`写到哪个作用域`,`Which scope to write to`),children:[`global`,`project`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":n===e,className:`mcp-scope-tab${n===e?` mcp-scope-tab-on`:``}`,onClick:()=>i(e),children:e===`global`?c(`全局`,`Global`):c(`项目`,`Project`)},e))}),(0,Q.jsx)(`span`,{className:`mcp-value mono mcp-scope-path`,title:r,children:r})]}),(0,Q.jsx)(`label`,{className:`mcp-add-label`,htmlFor:`mcp-add-text`,children:c(`要添加的服务器`,`Server to add`)}),(0,Q.jsx)(`textarea`,{id:`mcp-add-text`,className:`mcp-add-text mono`,value:e,spellCheck:!1,placeholder:`https://mcp.example.com/mcp
62
+ }`,hint:`mcpServers / VS Code 的 servers / 单条片段都认`}],IS=[{href:`https://glama.ai/mcp/servers`,label:`glama.ai`},{href:`https://smithery.ai/servers`,label:`smithery.ai`},{href:`https://mcp.so/`,label:`mcp.so`},{href:`https://registry.modelcontextprotocol.io/`,label:`MCP Registry`},{href:`https://github.com/mcp`,label:`github.com/mcp`}];function LS({text:e,onText:t,scope:n,scopePath:r,onScope:i,busy:a,onSubmit:o,onCancel:s}){let c=Y(),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)([]),[p,m]=(0,C.useState)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(0),_=(0,C.useCallback)(async e=>{if(e.trim()===``){u(null),f([]),m(null);return}let t=++g.current;try{let n=await(await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:`parse`,text:e})})).json();if(t!==g.current)return;if(f(n.notes??[]),n.actionError!==void 0){u(null),m(n.actionError);return}m(null),u((n.preview??[]).map(e=>({name:e.name,target:e.config.url??[e.config.command??``,...e.config.args??[]].filter(e=>e!==``).join(` `)})))}catch(e){if(t!==g.current)return;m(e instanceof Error?e.message:String(e)),u(null)}},[]);(0,C.useEffect)(()=>(h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>void _(e),350),()=>{h.current!==null&&window.clearTimeout(h.current)}),[e,_]);let v=!a&&e.trim()!==``&&p===null&&(l?.length??0)>0;return(0,Q.jsxs)(`div`,{className:`mcp-add-pane`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:c(`添加 MCP`,`Add MCP`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),IS.map(e=>(0,Q.jsx)(`a`,{className:`mcp-catalog-link`,href:e.href,target:`_blank`,rel:`noreferrer`,children:e.label},e.href))]}),(0,Q.jsxs)(`div`,{className:`mcp-scope-row`,children:[(0,Q.jsx)(`div`,{className:`mcp-scope-tabs`,role:`tablist`,"aria-label":c(`写到哪个作用域`,`Which scope to write to`),children:[`global`,`project`].map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":n===e,className:`mcp-scope-tab${n===e?` mcp-scope-tab-on`:``}`,onClick:()=>i(e),children:e===`global`?c(`全局`,`Global`):c(`项目`,`Project`)},e))}),(0,Q.jsx)(`span`,{className:`mcp-value mono mcp-scope-path`,title:r,children:r})]}),(0,Q.jsx)(`label`,{className:`mcp-add-label`,htmlFor:`mcp-add-text`,children:c(`要添加的服务器`,`Server to add`)}),(0,Q.jsx)(`textarea`,{id:`mcp-add-text`,className:`mcp-add-text mono`,value:e,spellCheck:!1,placeholder:`https://mcp.example.com/mcp
63
63
  npx -y @scope/server
64
64
  pi mcp add docs --url https://mcp.example.com/mcp
65
65
  { "mcpServers": { … } }`,onChange:e=>t(e.target.value),onKeyDown:t=>{(t.metaKey||t.ctrlKey)&&t.key===`Enter`&&v&&o(e)}}),(0,Q.jsxs)(`div`,{className:`mcp-add-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:!v,onClick:()=>o(e),children:a?c(`添加中…`,`Adding…`):c(`添加`,`Add`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:s,children:c(`取消`,`Cancel`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:c(`⌘/Ctrl + Enter 也能提交`,`⌘/Ctrl + Enter also submits`)})]}),p===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:p}),l!==null&&l.length>0?(0,Q.jsxs)(`div`,{className:`mcp-add-preview`,children:[(0,Q.jsx)(`span`,{className:`mcp-add-label`,children:c(`会写成`,`Will be written as`)}),l.map(e=>(0,Q.jsxs)(`div`,{className:`mcp-add-preview-row`,children:[(0,Q.jsx)(`span`,{className:`mcp-tool`,children:e.name}),(0,Q.jsx)(`span`,{className:`mcp-value mono`,title:e.target,children:e.target})]},e.name))]}):null,d.length>0?(0,Q.jsx)(`ul`,{className:`mcp-add-notes`,children:d.map((e,t)=>(0,Q.jsx)(`li`,{children:e},`${t}-${e}`))}):null,(0,Q.jsxs)(`div`,{className:`mcp-add-samples`,children:[(0,Q.jsx)(`span`,{className:`mcp-add-label`,children:c(`支持的格式(点一下填入示例)`,`Supported formats (click to fill an example)`)}),FS.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`mcp-sample`,onClick:()=>t(e.value),children:[(0,Q.jsx)(`span`,{className:`mcp-sample-label`,children:c(e.label)}),(0,Q.jsx)(`span`,{className:`mcp-sample-value mono`,children:e.value.split(`
66
- `)[0]}),(0,Q.jsx)(`span`,{className:`mcp-sample-hint`,children:c(e.hint)})]},e.label))]}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[c(`写进 pi 自己的`,`Written into pi's own`),` `,(0,Q.jsx)(`code`,{children:`mcp.json`}),c(`,`,`, `),(0,Q.jsx)(`strong`,{children:c(`对新会话生效`,`effective for new sessions`)}),c(`。同名不会覆盖:会自动加序号(预览里会写出来)。需要密钥的服务器,先把值写成`,`. Existing names are never overwritten — a suffix is added (shown in the preview). For servers that need a secret, write the value as`),` `,(0,Q.jsx)(`code`,{children:"${ENV_NAME}"}),c(`,面板里能看出这台机器上有没有设。`,`; the panel shows whether it is set on this machine.`)]})]})}function RS({servers:e,projectPath:t,globalPath:n,selected:r,pane:i,busy:a,onSelect:o,onToggleScope:s,onPane:c}){let l=J(),u=[{scope:`project`,label:l(`项目`,`Project`),path:t,items:e.filter(e=>e.scope===`project`)},{scope:`global`,label:l(`全局`,`Global`),path:n,items:e.filter(e=>e.scope===`global`)}];return(0,Q.jsxs)(`div`,{className:`mcp-list`,children:[(0,Q.jsx)(`div`,{className:`mcp-list-scroll`,children:u.map(e=>(0,Q.jsxs)(`div`,{className:`mcp-group`,children:[(0,Q.jsxs)(`div`,{className:`mcp-group-head`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.items.filter(e=>e.enabled).length,`/`,e.items.length]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e.items.length>0&&e.items.every(e=>e.enabled),"aria-label":l(`${e.label}的服务器全部${e.items.every(e=>e.enabled)?`停用`:`启用`}`,`${e.items.every(e=>e.enabled)?`Disable`:`Enable`} every server in ${e.label}`),className:`mcp-switch${e.items.some(e=>e.enabled)?` mcp-switch-on`:``}`,disabled:e.items.length===0||a,title:l(`${e.label}这一份配置里的服务器一起开 / 关`,`Turn every server in this ${e.label} config on / off together`),onClick:()=>s(e.scope,!e.items.every(e=>e.enabled)),children:e.items.every(e=>e.enabled)?l(`全关`,`All off`):l(`全开`,`All on`)})]}),e.items.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:e.scope===`project`?l(`这个项目没有自己的 MCP`,`This project has no MCP servers of its own`):l(`还没有 MCP 服务器`,`No MCP servers yet`)}):e.items.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`mcp-item${r===bS(e)?` mcp-item-on`:``}${e.enabled?``:` mcp-item-off`}`,onClick:()=>o(bS(e)),title:e.description??e.name,children:[(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`mcp-item-name`,children:e.name})]},bS(e))),e.items.length>0&&e.path?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:e.path,children:e.path}):null]},e.scope))}),(0,Q.jsxs)(`div`,{className:`mcp-left-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${i===`add`?` btn-on`:``}`,onClick:()=>c(`add`),children:[`+ `,l(`添加 MCP`,`Add MCP`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${i===`market`?` btn-on`:``}`,onClick:()=>c(`market`),title:l(`从公开注册中心一键添加`,`Add from the public registry in one click`),children:l(`市场`,`Market`)})]})]})}function zS({server:e,busy:t,login:n,onExposure:r,onLogin:i,onLoginCancel:a,onRecheck:o}){let s=J(),c=e.probe,l=c!==void 0&&!c.ok&&_S(c.error),u=c?c.ok?s(`连接成功 · ${c.tools.length} 个工具 · ${c.ms}ms`,`Connected · ${c.tools.length} tools · ${c.ms}ms`):s(`连接失败 · ${c.error??`未知错误`}`,`Failed · ${c.error??`unknown error`}`):s(`还没测过`,`Not tested yet`);return(0,Q.jsxs)(`div`,{className:`mcp-body`,children:[(0,Q.jsxs)(BS,{label:s(`状态`,`Status`),children:[(0,Q.jsx)(`span`,{className:e.enabled?`mcp-state-on`:`mcp-state-off`,children:e.enabled?s(`已启用`,`Enabled`):s(`已停用`,`Disabled`)}),(0,Q.jsxs)(`span`,{className:c&&!c.ok?`side-error`:`side-panel-count`,children:[` · `,u]})]}),l||e.transport===`http`&&(e.auth!==void 0||n!==void 0)?(0,Q.jsx)(BS,{label:s(`授权`,`Authorization`),children:(0,Q.jsxs)(`span`,{className:`mcp-auth`,children:[n?.status===`waiting`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`在浏览器里完成授权`,`Finish authorization in the browser`),n.url===void 0?s(`(正在准备授权页…)`,` (preparing the authorization page…)`):s(`,完成后回来点「我已授权」`,`, then come back and click “I've authorized”`),s(`:`,`:`)]}),n.url===void 0?null:(0,Q.jsx)(`a`,{className:`mcp-catalog-link mcp-auth-url mono`,href:n.url,target:`_blank`,rel:`noreferrer`,children:s(`打开授权页 ↗`,`Open the authorization page ↗`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,children:s(`我已授权,重测`,`I've authorized — retest`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:a,children:s(`取消`,`Cancel`)})]}):e.auth?.present&&e.auth.expired?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`存过凭据但已过期(pi 会在真正调用时用 refresh token 续期;连不上就重新登录一次)`,`Credentials saved but expired (pi renews them with the refresh token on real calls; sign in again if it cannot connect)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:i,children:s(`重新登录`,`Sign in again`)})]}):e.auth?.present?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`mcp-auth-ok`,children:[s(`已登录`,`Signed in`),e.auth.scope?` (${e.auth.scope})`:``]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:i,children:s(`重新登录`,`Sign in again`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`这台是远程 HTTP 服务器,要 OAuth 授权才能用(对面回了 401 / requires authentication)。 登录用 pi 自己的`,`This is a remote HTTP server; it needs OAuth authorization (the other side returned 401 / requires authentication). Sign in with pi's own`),` `,(0,Q.jsx)(`code`,{children:`pi mcp login`}),` `,s(`流程,凭据写进`),` `,(0,Q.jsx)(`code`,{children:`mcp-auth.json`}),s(`,会话也跟着用。`,`, and sessions use them too.`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:t,onClick:i,children:t?s(`准备中…`,`Preparing…`):s(`登录`,`Sign in`)})]}),n?.status===`failed`?(0,Q.jsx)(`span`,{className:`side-error`,children:n.message??s(`登录失败`,`Sign-in failed`)}):null]})}):null,(0,Q.jsx)(BS,{label:s(`简介`,`About`),children:e.description??(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`没写。这一句会进系统提示,帮模型知道该不该用这台服务器。`,`Not set. This line goes into the system prompt so the model knows whether to use this server.`)})}),e.transport===`stdio`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(BS,{label:s(`命令`,`Command`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:SS(e)}),(0,Q.jsx)(ah,{text:SS(e),className:`btn btn-tiny`,title:s(`复制命令`,`Copy command`)})]}),e.cwd?(0,Q.jsx)(BS,{label:s(`工作目录`,`Working directory`),children:e.cwd}):null]}):(0,Q.jsxs)(BS,{label:s(`地址`,`URL`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:e.url}),(0,Q.jsx)(ah,{text:e.url??``,className:`btn btn-tiny`,title:s(`复制地址`,`Copy URL`)})]}),Object.keys(e.env??{}).length>0?(0,Q.jsx)(BS,{label:s(`环境变量`,`Environment`),children:Object.entries(e.env??{}).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-tool`,title:CS(t)?s(`整条值是一条命令:pi 会跑它,把 stdout 当值`,`The whole value is a command: pi runs it and uses stdout as the value`):void 0,children:[e,`=`,t]},`env-${e}`))}):null,Object.keys(e.headers??{}).length>0?(0,Q.jsx)(BS,{label:s(`请求头`,`Headers`),children:Object.entries(e.headers??{}).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-tool`,children:[e,`: `,t]},`header-${e}`))}):null,e.envRefs.length>0?(0,Q.jsx)(BS,{label:s(`主机环境变量`,`Host environment`),children:(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.transport===`http`?s(`请求头里的变量取自运行 Pi Web 的这台机器:`,`Header values are read from the machine running Pi Web:`):s(`启动它的命令会拿到运行 Pi Web 的这台机器上的变量:`,`The launch command gets the variables of the machine running Pi Web:`),e.envRefs.map(e=>(0,Q.jsxs)(`span`,{className:`mcp-ref${e.present?` mcp-ref-ok`:` mcp-ref-missing`}`,children:[s(`${e.key} 里的 ${e.variable}`,`${e.variable} on ${e.key}`),e.present?s(` 已设置`,` set`):s(` 未设置`,` not set`)]},`${e.key}-${e.variable}`))]})}):null,(0,Q.jsxs)(BS,{label:s(`工具`,`Tools`),children:[(0,Q.jsx)(`select`,{className:`mcp-exposure`,value:e.exposure,disabled:t,onChange:e=>r(e.target.value),children:Object.keys(pS).map(e=>(0,Q.jsx)(`option`,{value:e,children:s(pS[e],mS[e])},e))}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(hS[e.exposure],gS[e.exposure])}),e.toolExposure?(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`单个工具另有设置:`,`Per-tool overrides:`),Object.entries(e.toolExposure).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-ref`,children:[e,` → `,s(pS[t],mS[t])]},e))]}):null]}),c?.ok&&c.tools.length>0?(0,Q.jsx)(BS,{label:s(`工具清单`,`Tools found`),children:(0,Q.jsx)(`div`,{className:`mcp-tools`,children:c.tools.map(e=>(0,Q.jsx)(`span`,{className:`mcp-tool`,title:e.description,children:e.name},e.name))})}):null,c&&!c.ok&&c.stderr?(0,Q.jsx)(BS,{label:`stderr`,children:(0,Q.jsx)(`pre`,{className:`mcp-stderr`,children:c.stderr})}):null,(0,Q.jsx)(BS,{label:s(`超时`,`Timeout`),children:(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.timeout} 秒(配置里的 timeout;不写就是 60)`,`${e.timeout}s (timeout from the config; 60 if unset)`)})}),(0,Q.jsxs)(BS,{label:s(`文件`,`File`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:e.source}),e.override?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.override} 里有本项目的覆盖项`,`${e.override} has overrides for this project`)}):null]})]})}function BS({label:e,children:t}){return(0,Q.jsxs)(`div`,{className:`mcp-row`,children:[(0,Q.jsx)(`span`,{className:`mcp-row-key`,children:e}),(0,Q.jsx)(`span`,{className:`mcp-row-value`,children:t})]})}var VS=[{id:`registry`,label:`官方注册中心`,hint:`registry.modelcontextprotocol.io(npm / PyPI 与远程地址)`},{id:`smithery`,label:`Smithery`,hint:`smithery.ai 托管的远程服务器,第一次连接可能要登录`},{id:`github`,label:`官方参考服务器`,hint:`modelcontextprotocol/servers 仓库`}];function HS(e){return e.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/`([^`]+)`/g,`$1`).replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,`$1`)}function US(e){return e.config.url===void 0?[e.config.command??``,...e.config.args??[]].filter(e=>e!==``).join(` `):e.config.url}function WS(e,t){return e.startsWith(`版本 `)?`${t(`版本`,`Version`)} ${e.slice(3)}`:t(e)}function GS({installed:e,busy:t,source:n,onSource:r,query:i,onQuery:a,onAdd:o}){let s=J(),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(!1),[g,_]=(0,C.useState)(0);(0,C.useEffect)(()=>{let e=window.setTimeout(()=>l(i.trim()),400);return()=>window.clearTimeout(e)},[i]),(0,C.useEffect)(()=>{let e=!1;return h(!0),p(null),(async()=>{try{let t=new URLSearchParams({source:n,q:c});g>0&&t.set(`refresh`,`1`);let r=await fetch(`/api/mcp/market?${t.toString()}`),i=await r.json();if(e)return;if(!r.ok||i.ok===!1){d(null),p(i.error??`HTTP ${r.status}`);return}d(i.entries??[]),p(i.error??null)}catch(t){if(e)return;d(null),p(t instanceof Error?t.message:String(t))}finally{e||h(!1)}})(),()=>{e=!0}},[n,c,g]);let v=(0,C.useCallback)(()=>_(e=>e+1),[]),y=VS.find(e=>e.id===n),b=new Set(e);return(0,Q.jsxs)(`div`,{className:`mcp-market`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:s(`MCP 市场`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:u===null?``:s(`${u.length} 个`,`${u.length}`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:m,onClick:v,title:s(`忽略缓存重新拉一次`,`Fetch again, ignoring the cache`),children:m?s(`拉取中…`,`Fetching…`):s(`刷新`,`Refresh`)})]}),(0,Q.jsxs)(`div`,{className:`mcp-market-bar`,children:[(0,Q.jsx)(`select`,{className:`mcp-market-source`,value:n,onChange:e=>r(e.target.value),title:s(`从哪个源拉`),children:VS.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:s(e.label)},e.id))}),(0,Q.jsx)(`input`,{className:`mcp-market-search`,value:i,placeholder:s(`搜索名称、包名或能力描述…`),onChange:e=>a(e.target.value)})]}),y?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(y.hint)}):null,f===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:f}),u===null&&m?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`正在拉取市场清单…(官方注册中心首次要十几秒)`)}):null,u!==null&&u.length===0&&!m?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`这个源里没有匹配的服务器,换个词或换个源试试。`)}):null,(0,Q.jsx)(`div`,{className:`mcp-market-list`,children:(u??[]).map(e=>{let n=b.has(e.name);return(0,Q.jsxs)(`div`,{className:`mcp-market-card`,children:[(0,Q.jsxs)(`div`,{className:`mcp-market-card-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-market-title`,children:e.title}),e.verified?(0,Q.jsx)(`span`,{className:`mcp-badge`,children:s(`官方`)}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),e.homepage?(0,Q.jsxs)(`a`,{className:`mcp-catalog-link`,href:e.homepage,target:`_blank`,rel:`noreferrer`,children:[s(`主页`,`Home`),` ↗`]}):null]}),e.description?(0,Q.jsx)(`p`,{className:`mcp-market-desc`,children:HS(e.description)}):null,(0,Q.jsxs)(`div`,{className:`mcp-market-target`,children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,title:US(e),children:e.pkg??US(e)}),e.downloads===void 0?null:(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.downloads.toLocaleString()} 次使用`,`${e.downloads.toLocaleString()} uses`)})]}),e.needsEnv&&e.needsEnv.length>0?(0,Q.jsxs)(`div`,{className:`mcp-market-needs`,children:[s(`装好后还要补环境变量:`,`Set these environment variables after installing:`),e.needsEnv.map(e=>(0,Q.jsx)(`span`,{className:`mcp-tool`,children:e},e))]}):null,e.note?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:WS(e.note,s)}):null,(0,Q.jsxs)(`div`,{className:`mcp-market-actions`,children:[n?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`已有同名配置`)}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:()=>o(e,`global`),title:s(`写进 ~/.pi/agent/mcp.json`),children:[`+ `,s(`添加全局`,`Add globally`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:()=>o(e,`project`),title:s(`写进当前项目的 .pi/mcp.json`),children:[`+ `,s(`添加项目`,`Add to project`)]})]})]},e.id)})}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[s(`清单来自公开注册中心(1 小时磁盘缓存)。一键添加只写 mcp.json 里那一条配置,卡上写明要补的环境变量,`,`The list comes from the public registry (1-hour disk cache). One-click add writes only the single mcp.json entry; missing environment variables are listed on the card —`),(0,Q.jsx)(`strong`,{children:s(`对新会话生效`,`effective for new sessions`)}),s(`。`,`.`)]})]})}function KS(){let e=J(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)({kind:`detail`}),[h,g]=(0,C.useState)(`global`),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(`registry`),[x,S]=(0,C.useState)(``),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(!0),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:mcp-list-width`));return Number.isFinite(e)&&e>=160&&e<=520?e:220});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:mcp-list-width`,String(O))},[O]);let A=(0,C.useRef)(!1),j=e=>{e.preventDefault(),A.current=!0;let t=e.clientX,n=O,r=e=>{A.current&&k(Math.min(520,Math.max(160,n+(e.clientX-t))))},i=()=>{A.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},M=()=>k(220);(0,C.useEffect)(()=>{if(w?.state.status!==`waiting`)return;let e={name:w.name,scope:w.scope},t=window.setInterval(()=>void F(`login-status`,e),2e3);return()=>window.clearInterval(t)},[w?.state.status,w?.name,w?.scope]),(0,C.useEffect)(()=>{w?.state.status===`done`&&F(`test`,{name:w.name,scope:w.scope})},[w?.state.status,w?.name,w?.scope]);let N=e=>{e.servers&&n(e),i(e.actionError??(typeof e.error==`string`?e.error:null)),o(e.notice??null)},P=(0,C.useCallback)(async()=>{i(null),D(!0);try{let e=await fetch(`/api/mcp`),t=await qS(e);if(t.view===void 0){i(t.error??`HTTP ${e.status}`);return}if(!e.ok){i(xS(t.view,e.status));return}N(t.view)}catch(e){i(e instanceof Error?e.message:String(e))}finally{D(!1)}},[]);(0,C.useEffect)(()=>{P()},[P]);let F=async(e,t,n={})=>{let r=`${e}:${t?bS(t):String(n.scope??`new`)}`;c(r),o(null);try{let r=await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:e,name:t?.name,scope:t?.scope??n.scope,...n})}),a=await r.json();if(!r.ok){i(xS(a,r.status));return}if(N(a),a.login!==void 0){let e=t?.scope??n.scope??`global`;T({name:a.login.name,scope:e,state:a.login})}if(e===`add`&&a.servers){m({kind:`detail`});let e=n.scope??h,t=a.added?.[0],r=a.servers.find(n=>n.scope===e&&(t===void 0||n.name===t));r&&u(bS(r))}e===`remove`&&t&&l===bS(t)&&u(null)}catch(e){i(e instanceof Error?e.message:String(e))}finally{c(null),f(null)}};if(t===null)return(0,Q.jsx)(`div`,{className:`mcp mcp-boot`,children:r===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取 MCP 配置…`,`Reading the MCP config…`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[e(`读不到 MCP 配置:`,`Cannot read the MCP config: `),r]}),(0,Q.jsx)(`div`,{className:`mcp-boot-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:E,onClick:()=>void P(),children:E?e(`重试中…`,`Retrying…`):e(`重试`,`Retry`)})})]})});let I=t.servers??[],L=I.find(e=>bS(e)===l)??null,R=t.total??I.length,z=t.enabled??I.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`mcp`,children:[(0,Q.jsxs)(`div`,{className:`mcp-shell`,style:{"--mcp-list-width":`${O}px`},children:[(0,Q.jsx)(RS,{servers:I,projectPath:t.projectPath??``,globalPath:t.globalPath??``,selected:l,pane:p.kind,busy:s!==null,onSelect:e=>{u(e),m({kind:`detail`})},onToggleScope:(e,t)=>void F(`set-scope-enabled`,void 0,{scope:e,enabled:t}),onPane:e=>m(p.kind===e?{kind:`detail`}:{kind:e})}),(0,Q.jsx)(`div`,{className:`mcp-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整服务器列表宽度`,`Resize the server list`),title:e(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:j,onDoubleClick:M}),(0,Q.jsx)(`div`,{className:`mcp-detail${p.kind===`detail`?``:` mcp-detail-pane`}`,children:p.kind===`add`?(0,Q.jsx)(LS,{text:_,onText:v,scope:h,scopePath:h===`project`?t.projectPath??``:t.globalPath??``,onScope:g,busy:s!==null,onCancel:()=>m({kind:`detail`}),onSubmit:e=>void F(`add`,void 0,{text:e,scope:h})}):p.kind===`market`?(0,Q.jsx)(GS,{installed:I.map(e=>e.name),busy:s!==null,source:y,onSource:b,query:x,onQuery:S,onAdd:(e,t)=>void F(`add`,void 0,{scope:t,name:e.name,config:e.config,description:e.description===``?void 0:e.description})}):L===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`左边挑一个服务器看详情。`,`Pick a server on the left to see details.`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mcp-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge`,children:e(vS[L.scope],yS[L.scope])}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:L.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null,onClick:()=>void F(`test`,L),title:e(`按配置真连一次:握手 + 列出工具,然后关掉`,`Actually connect once using the config: handshake + list tools, then disconnect`),children:s?.startsWith(`test:`)?e(`连接中…`,`Connecting…`):e(`测试连接`,`Test connection`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${d===bS(L)?` btn-danger`:``}`,disabled:s!==null,onClick:()=>d===bS(L)?void F(`remove`,L):f(bS(L)),onBlur:()=>f(e=>e===bS(L)?null:e),children:s?.startsWith(`remove:`)?e(`移除中…`,`Removing…`):d===bS(L)?e(`确认移除`,`Confirm remove`):e(`移除`,`Remove`)}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":L.enabled,className:`mcp-switch${L.enabled?` mcp-switch-on`:``}`,disabled:s!==null,onClick:()=>void F(`set-enabled`,L,{enabled:!L.enabled}),children:L.enabled?e(`已启用`,`Enabled`):e(`已停用`,`Disabled`)})]}),(0,Q.jsx)(zS,{server:L,busy:s!==null,login:w?.name===L.name?w.state:void 0,onExposure:e=>void F(`set-exposure`,L,{exposure:e}),onLogin:()=>void F(`login`,L),onLoginCancel:()=>{F(`login-cancel`,L),T(null)},onRecheck:()=>{F(`login-status`,L).then(()=>F(`test`,L))}})]})})]}),(0,Q.jsxs)(`div`,{className:`mcp-bar`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已开启`,`Enabled`),` `,z,`/`,R,` `,e(`个服务器`,`servers`),t.autoEnableCodemode===!1?e(` · 代码模式不会自动打开`,` · code mode is not enabled automatically`):``]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null,onClick:()=>void P(),children:e(`刷新`,`Refresh`)})]}),r?(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:r}):null,a?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:a}):null,(t.errors??[]).length>0?(0,Q.jsx)(`div`,{className:`mcp-diagnostics`,children:(t.errors??[]).map((e,t)=>(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:e},`${t}-${e}`))}):null,(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e(`配置读的就是 pi 自己的`,`The config is pi's own`),` `,(0,Q.jsx)(`code`,{children:`mcp.json`}),e(`(`,` (`),e(`项目覆盖全局,只写 enabled / exposure 的项目条目是覆盖项`,`project entries override global ones; entries that only set enabled / exposure act as overrides`),e(`)。`,`). `),e(`启停与暴露方式写回同一个文件,`,`Enable flags and exposure are written back to the same file, `),(0,Q.jsx)(`strong`,{children:e(`对新会话生效`,`effective for new sessions`)}),e(`;「测试连接」只握手 + 列工具,不调用任何工具。`,`; “Test connection” only handshakes and lists tools — it calls no tools.`)]})]})}async function qS(e){let t=await e.text();try{return{view:JSON.parse(t)}}catch{let n=t.replace(/<[^>]*>/g,` `).replace(/\s+/g,` `).trim().slice(0,120);return{error:e.status===404?q(`服务端没有 /api/mcp 这个接口(大概率是跑着旧版本):重启 Pi Web 后再打开这个面板`,`The server has no /api/mcp endpoint (probably an older build) — restart Pi Web and reopen this panel`):`HTTP ${e.status}${n===``?``:`${q(`:`,`: `)}${n}`}`}}}var JS=e=>{if(!e)return`—`;let t=Date.now()-e;return t<6e4?q(`刚刚`,`just now`):t<36e5?q(`${Math.floor(t/6e4)} 分钟前`,`${Math.floor(t/6e4)} min ago`):t<864e5?q(`${Math.floor(t/36e5)} 小时前`,`${Math.floor(t/36e5)} h ago`):q(`${Math.floor(t/864e5)} 天前`,`${Math.floor(t/864e5)} d ago`)},YS=e=>e.toLowerCase().startsWith(`mailto:`)?e.slice(7):e,XS=e=>{switch(e){case`push.subject.scheme`:return q(`只接受邮箱或 https 地址(推送网关不认 http / 其它协议)`,`Only an email or an https URL is accepted (the push gateways reject http and other schemes)`);case`push.subject.host`:return q(`域名要带真实后缀:localhost / 内网名 Apple 会直接拒(403 BadJwtToken)`,`The domain needs a real suffix: Apple rejects localhost and LAN names outright (403 BadJwtToken)`);case`push.subject.empty`:return q(`不能为空`,`Must not be empty`);default:return q(`格式不合法`,`Invalid format`)}};function ZS(){let e=J(),{name:t,custom:n}=Zv(),[r,i]=(0,C.useState)([]),[a,o]=(0,C.useState)(new Set),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(!1),[d,f]=(0,C.useState)(`default`),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(!1),x=async()=>{let e=await yv();g(e),v(e?YS(e.subject):``)},S=async()=>{try{f(await wv())}catch{f(`unsupported`)}},w=async()=>{m(!0),c(null);try{let t=await Tv(n);c(t.ok?t.rekeyed?e(`这台设备已按服务端新密钥重建订阅`,`This device re-subscribed with the server's new key`):e(`这台设备已注册推送`,`Push registered for this device`):t.message),t.ok&&await k()}catch(t){c(e(`注册失败:${t instanceof Error?t.message:String(t)}(需要 https 或 localhost,且允许通知)`,`Registration failed: ${t instanceof Error?t.message:String(t)} (needs https or localhost, and notifications allowed)`))}finally{m(!1),await S()}},T=async()=>{m(!0),c(null);try{let t=await Dv();c(t.ok?e(`已取消这台设备的订阅`,`Subscription cancelled for this device`):t.message),await k()}catch(t){c(e(`取消失败:${t instanceof Error?t.message:String(t)}`,`Cancel failed: ${t instanceof Error?t.message:String(t)}`))}finally{m(!1),await S()}},E=async()=>{try{if(!Sv()){c(e(`这个浏览器不支持通知(需要 https 或 localhost)`,`This browser does not support notifications (needs https or localhost)`));return}if((Notification.permission===`granted`?`granted`:await Notification.requestPermission())!==`granted`){c(e(`通知权限没给,弹不出来`,`Notification permission was not granted, so nothing can show`));return}let n=await navigator.serviceWorker.getRegistration(`/sw.js`),r={body:e(`这是本地通知测试,不经过服务端。`,`This is a local notification test; it does not go through the server.`),icon:`/icons/icon-192.png`,tag:`pop-agent-local`};n?await n.showNotification(t,r):new Notification(t,r),c(e(`已发出本地通知(没看到的话检查系统通知设置)`,`Local notification sent (check the system notification settings if you did not see it)`))}catch(t){c(e(`本地通知失败:${t instanceof Error?t.message:String(t)}`,`Local notification failed: ${t instanceof Error?t.message:String(t)}`))}},D=async()=>{b(!0),c(null);try{let t=await bv(_);if(!t.ok){let n=XS(t.code);c(e(`保存失败:${n}`,`Save failed: ${n}`));return}g(t.config),v(YS(t.config.subject)),c(e(`联系方式已保存(不影响已注册的设备)`,`Contact saved (registered devices are unaffected)`))}finally{b(!1)}},O=async()=>{if(window.confirm(e(`换一对新密钥?所有已订阅设备都会失效(旧订阅会被清空),需要每台设备重新点「注册推送」。这台设备会自动重订。`,`Replace the key pair? Every subscribed device stops working (old subscriptions are cleared) and each one has to register again. This device re-registers automatically.`))){b(!0),c(null);try{let t=d===`subscribed`,r=await xv();if(!r.ok){c(r.code===`push.keys_locked`?e(`密钥由环境变量 VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY 指定,要换得改环境变量`,`The keys come from VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY; change them there`):e(`换密钥失败:${r.code}`,`Replacing the keys failed: ${r.code}`));return}g(r.config),v(YS(r.config.subject)),await k();let i=``;if(t){let t=await Tv(n);i=t.ok?e(`本机已用新密钥重新注册`,`This device re-registered with the new key`):e(`本机重订失败:${t.message}`,`Re-registering this device failed: ${t.message}`),await S(),await k()}c([e(`已换新密钥(清空 ${r.cleared} 台旧订阅)`,`Keys replaced (${r.cleared} old subscriptions cleared)`),i].filter(e=>e!==``).join(e(`;`,`; `)))}finally{b(!1)}}},k=async()=>{let e=await(await fetch(`/api/push/subscriptions`)).json();i(e.devices??[]),o(t=>new Set([...t].filter(t=>(e.devices??[]).some(e=>e.endpoint===t))))};(0,C.useEffect)(()=>{k(),S(),x()},[]);let A=async(e,t)=>{u(!0);try{await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},...t}),await k()}finally{u(!1)}},j=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),M=Sv(),N=typeof Notification>`u`?`unsupported`:Notification.permission,P=N===`granted`?e(`已允许`,`Granted`):N===`denied`?e(`已拒绝`,`Denied`):N===`unsupported`?`—`:e(`未授权`,`Not granted`);return(0,Q.jsxs)(`div`,{className:`push-panel`,children:[(0,Q.jsxs)(`section`,{className:`push-env`,children:[(0,Q.jsx)(`div`,{className:`push-env-title`,children:e(`服务端密钥`,`Server key`)}),(0,Q.jsxs)(`div`,{className:`push-config-row`,children:[(0,Q.jsx)(`span`,{className:`push-config-label`,children:e(`公钥`,`Public key`)}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,title:h?.publicKey??``,children:[(0,Q.jsx)(`code`,{className:`mono`,children:h?`${h.fingerprint}…`:`…`}),(0,Q.jsx)(`em`,{className:h?.keySource===`env`?`push-tag-off`:`push-tag-ok`,children:h?.keySource===`env`?e(`环境变量`,`env`):e(`数据目录`,`data dir`)})]}),h?.keyCreatedAt?(0,Q.jsxs)(`span`,{className:`push-config-note`,children:[e(`生成于`,`created`),` `,JS(h.keyCreatedAt)]}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,disabled:y||h?.locked.keys===!0,title:h?.locked.keys?e(`密钥由环境变量指定,要换得改环境变量`,`Keys come from env vars; change them there`):void 0,onClick:()=>void O(),children:e(`重新生成密钥`,`Regenerate keys`)})]}),(0,Q.jsxs)(`div`,{className:`push-config-row`,children:[(0,Q.jsx)(`span`,{className:`push-config-label`,children:e(`联系方式`,`Contact`)}),(0,Q.jsx)(`input`,{className:`push-config-input`,type:`text`,inputMode:`email`,value:_,placeholder:`you@example.com`,disabled:y||h?.locked.subject===!0,onChange:e=>v(e.target.value),onKeyDown:e=>{e.key===`Enter`&&D()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:y||h===null||_===YS(h.subject),onClick:()=>void D(),children:e(`保存`,`Save`)})]}),h&&!h.subjectValid?(0,Q.jsxs)(`div`,{className:`push-config-warn`,children:[`⚠ `,XS(h.subjectProblem)]}):null]}),(0,Q.jsxs)(`section`,{className:`push-env`,children:[(0,Q.jsx)(`div`,{className:`push-env-title`,children:e(`本机推送`,`Push on this device`)}),(0,Q.jsxs)(`div`,{className:`push-env-chips`,children:[(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`浏览器支持`,`Browser support`),(0,Q.jsx)(`em`,{className:M?`push-tag-ok`:`push-tag-off`,children:M?e(`支持`,`Supported`):e(`不支持`,`Unsupported`)})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`通知权限`,`Notification permission`),(0,Q.jsx)(`em`,{className:N===`granted`?`push-tag-ok`:`push-tag-off`,children:P})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[`Service Worker`,(0,Q.jsx)(`em`,{className:d===`unsupported`?`push-tag-off`:`push-tag-ok`,children:d===`unsupported`?e(`不可用`,`Unavailable`):e(`已就绪`,`Ready`)})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`当前订阅`,`Subscription`),(0,Q.jsx)(`em`,{className:d===`subscribed`?`push-tag-ok`:`push-tag-off`,children:d===`subscribed`?e(`已订阅`,`Subscribed`):e(`未订阅`,`Not subscribed`)})]})]}),(0,Q.jsxs)(`div`,{className:`push-env-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-tiny`,disabled:p,onClick:()=>void w(),children:d===`subscribed`?e(`重新注册`,`Register again`):e(`注册推送`,`Register for push`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p,onClick:()=>void E(),children:e(`本地通知测试`,`Local notification test`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p||d!==`subscribed`,onClick:()=>void T(),children:e(`取消订阅`,`Unsubscribe`)})]}),(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`推送需要 https 或 localhost(手机上请用域名);注册后「目标设备」里会出现这台设备。`,`Push needs https or localhost (use a domain name on phones); once registered, this device appears under Targets.`)})]}),(0,Q.jsxs)(`section`,{className:`push-devices`,children:[(0,Q.jsxs)(`div`,{className:`push-head`,children:[(0,Q.jsx)(`strong`,{children:e(`推送消息`,`Push a message`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`目标设备`,`Targets`),` `,r.length,` `,e(`台`,`devices`)]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(new Set(r.map(e=>e.endpoint))),children:e(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(new Set),children:e(`全不选`,`Select none`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void k(),children:[`⟳ `,e(`刷新`,`Refresh`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{window.confirm(e(`清空全部订阅设备?之后所有设备都收不到推送。`,`Clear every subscribed device? No device will receive pushes afterwards.`))&&A(`/api/push/clear`).then(()=>c(e(`已清空全部设备`,`All devices cleared`)))},children:e(`清空全部设备`,`Clear all devices`)})]}),r.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`还没有订阅设备。点上面的「注册推送」把当前这台浏览器订进来(需要 https 或 localhost)。`,`No subscribed devices yet — use “Register for push” above to subscribe this browser (needs https or localhost).`)}):null,(0,Q.jsx)(`div`,{className:`push-list`,children:r.map(t=>(0,Q.jsxs)(`div`,{className:`push-row${a.has(t.endpoint)?` push-row-on`:``}`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.has(t.endpoint),onChange:()=>j(t.endpoint)}),(0,Q.jsxs)(`div`,{className:`push-row-main`,children:[(0,Q.jsx)(`div`,{className:`push-row-name`,children:t.name}),(0,Q.jsx)(`div`,{className:`push-row-endpoint mono`,title:t.endpoint,children:t.endpoint}),(0,Q.jsxs)(`div`,{className:`push-row-meta`,children:[e(`注册`,`Registered`),` `,JS(t.createdAt),t.lastSentAt?` · ${e(`上次推送`,`last push`)} ${JS(t.lastSentAt)} (${t.lastStatus??`—`})`:``]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>{let n=window.prompt(e(`设备别名`,`Device alias`),t.name);n!==null&&n.trim()!==``&&A(`/api/push/rename`,{body:JSON.stringify({endpoint:t.endpoint,name:n.trim()})})},children:e(`重命名`,`Rename`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:l,onClick:()=>void A(`/api/push/test`,{body:JSON.stringify({endpoints:[t.endpoint]})}).then(()=>c(e(`已单独推送给「${t.name}」`,`Pushed to “${t.name}” only`))),children:e(`仅推它`,`Push to this one`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>void A(`/api/push/delete`,{body:JSON.stringify({endpoint:t.endpoint})}),children:e(`删除`,`Delete`)})]},t.endpoint))}),(0,Q.jsxs)(`div`,{className:`push-foot`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l,onClick:()=>void A(`/api/push/test`,{body:JSON.stringify(a.size>0?{endpoints:[...a]}:{})}).then(()=>c(a.size>0?e(`已推送给选中的 ${a.size} 台`,`Pushed to ${a.size} selected devices`):e(`已推送给全部设备`,`Pushed to all devices`))),children:[e(`推送测试消息`,`Send a test push`),a.size>0?` (${a.size} ${e(`选中`,`selected`)})`:` (${e(`全部设备`,`all devices`)})`]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`})]})]}),s?(0,Q.jsx)(`div`,{className:`side-ok`,children:s}):null]})}var QS=[`start`,`steer`,`done`,`error`,`approval`],$S=[{db:0,zh:`关闭 · 0(不挡人,开自动增益)`,en:`Off · 0 (no gate, auto gain on)`},{db:6,zh:`宽松 · 6 dB(小声也能进,偶尔收进旁人)`,en:`Loose · 6 dB (quiet voice gets in)`},{db:12,zh:`中等 · 12 dB(默认档,挡住一米外的聊天)`,en:`Medium · 12 dB (default)`},{db:18,zh:`偏严 · 18 dB(基本要正对着说)`,en:`Strict · 18 dB (near-field only)`},{db:24,zh:`很严 · 24 dB(几乎只认贴嘴)`,en:`Very strict · 24 dB`}];function eC(){let e=J(),[t,n]=uf(ef,!0),[r,i]=lf(),[a,o]=(0,C.useState)(()=>U()),[s,c]=(0,C.useState)(()=>qe()),l=bi(),u=Ro(e=>e.snapshot?.engineCapabilities?.steer!==!1),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(null),_=(0,C.useCallback)((e=!1)=>{fetch(`/api/asr/status${e?`?start=1`:``}`).then(async e=>{if(!e.ok)return;let t=await e.json();f(t),t.state===`ready`&&mi()}).catch(()=>void 0)},[]),v=d?.state===`starting`||d?.state===`authorizing`;(0,C.useEffect)(()=>{if(!v)return;let e=window.setInterval(()=>_(),1200);return()=>window.clearInterval(e)},[v,_]);let y=()=>{f(e=>({...e??{},state:`starting`,message:void 0})),_(!0)},b=()=>{p||(m(!0),g(null),fetch(`/api/asr/install`,{method:`POST`,credentials:`same-origin`}).then(async t=>{let n=await t.json().catch(()=>({}));!t.ok||n.ok!==!0?g(n.message??e(`安装失败`,`Install failed`)):(mi(),_(!0))}).catch(t=>g(t instanceof Error?t.message:e(`安装请求失败了`,`The install request failed`))).finally(()=>m(!1)))};(0,C.useEffect)(()=>_(),[]);let[x,S]=(0,C.useState)(()=>$e()),[w,T]=(0,C.useState)([]),[E,D]=(0,C.useState)(!1),[O,k]=(0,C.useState)(null),[A,j]=(0,C.useState)(null),[M,N]=(0,C.useState)(!1),[P,F]=(0,C.useState)(!1),I=(0,C.useRef)(!1);(0,C.useEffect)(()=>()=>{I.current&&Ct()},[]);let[L,R]=(0,C.useState)(null),z=Qe(s),B=(s.provider??`browser`)!==`browser`,H=s.provider===`kokoro`||s.provider===`qwen3`?s.provider:`edge`,ee=s.provider===`kokoro`?s.kokoroVoice:s.provider===`qwen3`?s.qwen3Voice:s.edgeVoice,G=x.some(e=>e.voiceURI===s.voiceURI)?s.voiceURI:``,K=s.voiceURI!==``&&G===``?$e({includeOnline:!0}).find(e=>e.voiceURI===s.voiceURI):void 0;(0,C.useEffect)(()=>(S($e({onlyOnline:s.allowOnline})),et(()=>S($e({onlyOnline:s.allowOnline})))),[s.allowOnline]),(0,C.useEffect)(()=>{if(!B)return;let t=new AbortController,n=!1,r=window.setTimeout(()=>t.abort(),15e3);return D(!0),k(null),ze(t.signal,H).then(e=>{n||T(e)}).catch(()=>{n||k(e(`音色列表加载失败,可以使用默认音色试听`,`Unable to load voices; you can still preview the default voice`))}).finally(()=>{window.clearTimeout(r),n||D(!1)}),()=>{n=!0,window.clearTimeout(r),t.abort()}},[B,H,e]);let te=e=>{let t={...a,...e};o(t),W(t)},ne=e=>{(e.provider!==void 0||e.voiceURI!==void 0||e.edgeVoice!==void 0||e.kokoroVoice!==void 0||e.qwen3Voice!==void 0)&&(Ct(),j(null),R(null),N(!1));let t={...s,...e};c(t),Ye(t)},re=e=>ne({allowOnline:e}),ie=!B&&s.allowOnline&&x.length===0,ae=e=>{if(e===`steer`){Na(`steer`,{force:!0,volume:Math.max(.05,a.volume/100)});return}let t=qe().enabled;Ia({kind:e,voiceEnabled:t,readReplies:!1,hasReply:!1})===`clip`&&e!==`start`?Na(e,{force:!0,volume:Math.max(.05,a.volume/100)}):fe(e,{...a,enabled:!0,[e]:!0,volume:a.volume})},oe=t=>{Na(`done`,{force:!0,language:t,volume:Math.max(.05,a.volume/100)}),j(null),R(t===`en`?e(`已播放英文片段「Task complete.」`,`Played the English clip "Task complete."`):t===`zh`?e(`已播放中文片段「任务已完成」`,`Played the Chinese clip "任务已完成"`):e(`已播放本地语音片段(跟当前界面语言)`,`Played the bundled clip (current UI language)`)),window.setTimeout(()=>R(null),2400)},se=()=>{Ct(),j(null),N(!1),R(e(`正在准备语音…`,`Preparing speech…`)),F(!0),I.current=!0;let t=()=>{I.current=!1,F(!1)};bt(Ge(),{...s,enabled:!0},{onStart:()=>{I.current=!0,F(!0),j(null),R(e(`正在念:语音播报正常`,`Speaking: speech is working`))},onCancel:()=>{t(),R(null)},onEnd:()=>{t(),R(null)},onIssue:(e,n)=>{t(),R(null),j(e),N(n.wakeable)}})},ce=()=>{j(null),N(!1),R(e(`正在唤醒系统语音服务…`,`Waking the system speech service…`)),gt(()=>se(),400)},le=async()=>{j(null),R(e(`正在诊断…(约 2.5 秒)`,`Diagnosing… (about 2.5s)`));let t=await St();t.available?t.started?R(e(`诊断:合成器正常(${t.ms}ms 内开始;音色 ${t.voices} 个,其中在线 ${t.online} 个)。若还是听不到,问题在音量 / 输出设备,不在浏览器。`,`Diagnosis: the synthesizer responds (started within ${t.ms}ms; ${t.voices} voices, ${t.online} online). If you still hear nothing, the problem is volume / output device.`)):t.error?(R(null),N(!0),j(e(`诊断:系统报错「${t.error}」— ${rt(t.error)}`,`Diagnosis: error "${t.error}" — ${rt(t.error)}`))):(R(null),N(!0),j(e(`诊断:合成器 ${t.ms}ms 内既没开始也没报错(音色 ${t.voices} 个,在线 ${t.online} 个)→ 系统的语音服务卡死了。重启浏览器;macOS 还可执行 killall speechsynthesisd`,`Diagnosis: no start and no error within ${t.ms}ms (${t.voices} voices, ${t.online} online) → the OS speech service is stuck. Restart the browser; on macOS try killall speechsynthesisd`))):(R(null),j(e(`诊断:这个浏览器没有语音合成(speechSynthesis)能力`,`Diagnosis: this browser has no speech synthesis`)))};return(0,Q.jsxs)(`div`,{className:`voice-panel`,children:[(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🔊`}),` `,e(`启用声音`,`Enable sounds`)]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.enabled,onChange:()=>te({enabled:!a.enabled})})]}),QS.map(t=>(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(V[t].title,V[t].titleEn),`(`,e(V[t].hint,V[t].hintEn),`)`]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny voice-try`,onClick:e=>{e.preventDefault(),ae(t)},children:e(`试听`,`Preview`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:a[t],onChange:()=>te({[t]:!a[t]})})]},t))]}),(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🔊`}),` `,e(`启用语音播报(完成 / 出错播提示音)`,`Enable speech (cue on finish / error)`)]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.enabled,onChange:()=>ne({enabled:!s.enabled})})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读回复(边输出边按句念)`,`Read replies aloud (as it streams)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.readReplies,onChange:()=>ne({readReplies:!s.readReplies})})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:B?H===`edge`?e(`语音引擎(在线,文字发到微软)`,`Speech engine (online, text goes to Microsoft)`):e(`语音引擎(本机 MLX,不联网)`,`Speech engine (local MLX, offline)`):e(`语音引擎`,`Speech engine`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:s.provider??`browser`,onChange:e=>ne({provider:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`browser`,children:e(`浏览器语音`,`Browser speech`)}),(0,Q.jsx)(`option`,{value:`edge`,children:e(`微软 Edge TTS(在线)`,`Microsoft Edge TTS (online)`)}),(0,Q.jsx)(`option`,{value:`kokoro`,children:e(`Kokoro(本地)`,`Kokoro (local)`)}),(0,Q.jsx)(`option`,{value:`qwen3`,children:e(`Qwen3-TTS(本地)`,`Qwen3-TTS (local)`)})]})]}),B?(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语音`,`Voice`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:ee??``,onChange:e=>ne(H===`kokoro`?{kokoroVoice:e.target.value}:H===`qwen3`?{qwen3Voice:e.target.value}:{edgeVoice:e.target.value}),disabled:E,children:[w.some(e=>e.id===ee)?null:(0,Q.jsx)(`option`,{value:ee??``,children:E?e(`正在加载音色…`,`Loading voices…`):ee??e(`默认音色`,`Default voice`)}),w.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.name,e.lang?`(${e.lang})`:``]},e.id))]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语音`,`Voice`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:G,onChange:e=>ne({voiceURI:e.target.value}),title:e(`浏览器里可用的音色(取决于系统装了什么语音)`,`Voices available in the browser (depends on what the OS has installed)`),children:[(0,Q.jsx)(`option`,{value:``,children:e(`自动(跟随系统语言)`,`Auto (match the system language)`)}),x.map(t=>(0,Q.jsxs)(`option`,{value:t.voiceURI,children:[t.name,`(`,t.lang,t.localService?``:e(`,在线`,`, online`),`)`]},t.voiceURI)),K?(0,Q.jsxs)(`option`,{value:K.voiceURI,children:[K.name,`(`,K.lang,K.localService?e(`,本机;已保留`,`, local; kept`):e(`,在线;已保留`,`, online; kept`),`)`]}):null]})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`只列在线音色(本机音色念不出来)`,`Online voices only (local ones never start)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.allowOnline,onChange:()=>re(!s.allowOnline)})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读小宠物(一直待在右下角,可拖动)`,`Reading pet (always in the bottom-right, draggable)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>n(e.target.checked)})]}),t?(0,Q.jsxs)(`div`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`宠物形象`,`Pet`)}),(0,Q.jsx)(`div`,{className:`speech-pet-picker`,children:nf.map(t=>(0,Q.jsx)(`button`,{type:`button`,className:`speech-pet-pick${r===t.emoji?` is-on`:``}`,onClick:()=>i(t.emoji),"aria-pressed":r===t.emoji,title:e(t.zh,t.en),children:t.emoji},t.emoji))})]}):null,(0,Q.jsxs)(`div`,{className:`voice-row-pair`,children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语速`,`Rate`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.5,max:2,step:.1,value:s.rate,onChange:e=>ne({rate:Number(e.target.value)})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[s.rate.toFixed(1),`×`]})]})]}),(0,Q.jsxs)(`div`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`提示音音量`,`Cue volume`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line`,children:[(0,Q.jsx)(`input`,{type:`range`,min:0,max:100,step:5,value:a.volume,onChange:e=>te({volume:Number(e.target.value)}),onMouseUp:()=>ae(`done`),title:e(`调完松手会试听一声`,`Plays a sample when you let go`)}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[a.volume,`%`]})]})]})]}),B&&O?(0,Q.jsx)(`div`,{className:`voice-issue`,role:`status`,children:O}):null,ie?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:e(`没找到在线音色:Chrome 的 Google 音色要联网才会加载(断网时只能选「自动」或取消勾选看本机音色)`,`No online voice found: Chrome loads Google voices from the network`)}):null,(0,Q.jsxs)(`div`,{className:`voice-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>oe(),title:e(`播一段本地语音片段(跟当前界面语言)`,`Plays a bundled clip (current UI language)`),children:e(`试听`,`Preview`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>oe(`en`),title:e(`播英文片段(不用先切界面语言)`,`Plays the English clip without switching the UI language`),children:e(`试听英文`,`Preview (EN)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:se,disabled:!z||P,title:e(`用所选语音引擎试听一句话`,`Previews a sentence using the selected speech engine`),children:e(`测朗读`,`Test reading`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:nn,title:e(`停掉正在念的内容;这一轮剩下的文字也不再自动念`,`Stops the current sentence; the rest of this turn stays silent`),children:e(`停止`,`Stop`)}),B?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void le(),title:e(`绕过本项目所有设置,直接问浏览器能不能念`,`Bypasses all settings and asks the browser directly`),children:e(`诊断`,`Diagnose`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{Ct(),ne({...Ue,voiceURI:s.voiceURI})},children:e(`恢复默认`,`Restore defaults`)})]}),L?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:L}):null,A?(0,Q.jsxs)(`div`,{className:`voice-issue`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:A}),M&&z&&!B?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:ce,disabled:P,title:e(`先念一句静音的唤醒句把系统语音服务踢醒,再重放一次试听(省得你去终端 killall)`,`Plays a silent wake-up utterance, then retries the sample (no need to killall anything)`),children:e(`唤醒并重试`,`Wake & retry`)}):null]}):null]}),(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsx)(`div`,{className:`voice-row`,children:(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🎤`}),` `,e(`语音输入(点麦克风浮条说话)`,`Voice input (tap the mic bubble)`)]})}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`说完自动发送(停 ${(l.silenceMs/1e3).toFixed(1)} 秒就发)`,`Send when I stop talking (after ${(l.silenceMs/1e3).toFixed(1)}s)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.autoSend,onChange:()=>yi({...l,autoSend:!l.autoSend})})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`等多久发送(停顿多长算说完)`,`Silence before sending (how long counts)`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line voice-slider-compact`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.6,max:10,step:.2,value:l.silenceMs/1e3,onChange:e=>yi({...l,silenceMs:Number(e.target.value)*1e3})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[(l.silenceMs/1e3).toFixed(1),`s`]})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读恢复延迟(安静多久后接着念)`,`Resume reading after (silence needed)`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line voice-slider-compact`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.6,max:10,step:.2,value:l.readingResumeMs/1e3,onChange:e=>yi({...l,readingResumeMs:Number(e.target.value)*1e3})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[(l.readingResumeMs/1e3).toFixed(1),`s`]})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`连续听写(发完继续听,麦克风常亮)`,`Keep listening (mic stays open)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.continuous,onChange:()=>yi({...l,continuous:!l.continuous})})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`近讲灵敏度(越大越只认近处;0 = 关闭)`,`Near-field only (higher = nearer only; 0 = off)`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:String(l.nearTalkDb),onChange:e=>yi({...l,nearTalkDb:Number(e.target.value)}),children:[$S.some(e=>e.db===l.nearTalkDb)?null:(0,Q.jsx)(`option`,{value:String(l.nearTalkDb),children:e(`当前 · ${l.nearTalkDb} dB`,`Current · ${l.nearTalkDb} dB`)}),$S.map(t=>(0,Q.jsx)(`option`,{value:String(t.db),children:e(t.zh,t.en)},t.db))]})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`识别引擎(自动 = 先本地,带标点)`,`Recognition engine (auto = local first)`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:l.engine,onChange:e=>yi({...l,engine:e.target.value===`browser`||e.target.value===`local`?e.target.value:`auto`}),children:[(0,Q.jsx)(`option`,{value:`auto`,children:e(`自动(优先本地)`,`Auto (local first)`)}),(0,Q.jsx)(`option`,{value:`local`,children:e(`本地(macOS 离线)`,`Local (macOS, offline)`)}),(0,Q.jsx)(`option`,{value:`browser`,children:e(`Chrome 原生(需连 Google)`,`Chrome (needs Google)`)})]})]}),l.engine===`browser`?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-status`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(`本地识别`,`Local recognition`),(0,Q.jsx)(`span`,{className:`voice-row-hint`,children:d===null||d.state===`idle`?e(`还没启动过`,`Not started yet`):d.state===`ready`?e(`就绪(${d.locale??`zh-CN`},离线)`,`Ready (${d.locale??`zh-CN`}, offline)`):d.state===`authorizing`?e(`等待系统授权:屏幕上的提示点「允许」即可`,`Waiting for permission — click Allow in the system prompt`):d.state===`starting`?e(`正在启动…`,`Starting…`):d.state===`missing`?e(`还没装:一个后台小工具,点一下就能装好`,`Not installed yet — a small background helper, one click installs it`):d.message??d.state})]}),d?.state===`missing`?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p||d.install?.canAutoInstall===!1,onClick:b,title:e(`下载并装好本地识别(不用装 Xcode)`,`Download and install it — no Xcode needed`),children:p?e(`正在安装…`,`Installing…`):e(`安装本地识别`,`Install it`)}):d?.state===`ready`?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:v,"aria-busy":v,onClick:y,title:v?e(`正在启动,请稍等…`,`Starting — hang on…`):e(`启动本地识别(首次会弹一次系统授权)`,`Start the local engine (one system permission prompt the first time)`),children:v?e(`正在启动…`,`Starting…`):e(`启动 / 重试`,`Start / retry`)})]}),d?.state===`missing`&&d.install?.canAutoInstall!==!1?(0,Q.jsxs)(`div`,{className:`voice-install`,children:[(0,Q.jsxs)(`ol`,{className:`voice-install-steps`,children:[(0,Q.jsx)(`li`,{children:e(`点「安装本地识别」:服务端会下载并解压到 Application Support(可离线、不联网识别)`,`Click “Install it” — the server downloads and unpacks it into Application Support (recognition itself stays offline)`)}),(0,Q.jsx)(`li`,{children:e(`装好后这里会变成「就绪」;第一次说话会弹一次系统授权,点「允许」即可`,`This row turns into “Ready”. The first time you speak, macOS asks once for permission — click Allow`)})]}),(0,Q.jsxs)(`div`,{className:`voice-install-actions`,children:[d.install?(0,Q.jsx)(`a`,{className:`btn btn-tiny`,href:d.install.downloadUrl,target:`_blank`,rel:`noreferrer`,title:d.install.appPath,children:e(`手动下载 zip`,`Download the zip`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>_(),children:e(`装好了,重新检测`,`Installed — check again`)})]}),h?(0,Q.jsx)(`div`,{className:`voice-issue`,role:`status`,children:(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:h})}):null]}):null,d?.state===`missing`&&d.install?.canAutoInstall===!1?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:e(`本地识别只有 macOS 版(跑服务端的那台机器);这台机器请把上面的「识别引擎」改成 Chrome 原生`,`Local recognition is macOS-only (on the machine running the server) — switch the engine above to Chrome`)})}):null]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(`说完时正在跑`,`While a turn is running`),(0,Q.jsx)(`span`,{className:`voice-row-hint`,children:u?e(`排队 = 等这一轮结束再发;插队 = 打断它,按新指令继续`,`Queue = sends after this turn; Steer = interrupts it and continues with the new instruction`):e(`当前引擎只能排队(插队需要 Pi 引擎)`,`This engine can only queue — steering requires the Pi engine`)})]}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:l.submitMode,disabled:!u,onChange:e=>yi({...l,submitMode:e.target.value===`steer`?`steer`:`queue`}),children:[(0,Q.jsx)(`option`,{value:`queue`,children:e(`排队`,`Queue`)}),(0,Q.jsx)(`option`,{value:`steer`,children:e(`插队`,`Steer`)})]})]})]})]})}var tC=[`read`,`bash`,`edit`,`write`,`grep`,`find`,`ls`];function nC({profile:e,onClose:t}){let n=J(),[r,i]=(0,C.useState)(e),a=Ro(e=>e.snapshot),o=(0,C.useMemo)(()=>Gf(a?.models??[],a?.enabledModels??[]),[a?.models,a?.enabledModels]),s=e=>i(t=>({...t,...e})),c=e=>s({tools:r.tools.includes(e)?r.tools.filter(t=>t!==e):[...r.tools,e]});return(0,Q.jsxs)(`div`,{className:`agents-form`,children:[(0,Q.jsxs)(`div`,{className:`agents-form-row`,children:[(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`子代理 ID`,`Subagent ID`)}),(0,Q.jsx)(`input`,{value:r.id,disabled:!!r.builtin,onChange:e=>s({id:e.target.value}),placeholder:`review`})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`显示名称`,`Display name`)}),(0,Q.jsx)(`input`,{value:r.label,onChange:e=>s({label:e.target.value}),placeholder:`Review`})]})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`描述(模型靠它决定什么时候用谁)`,`Description (the model uses it to decide when to use which)`)}),(0,Q.jsx)(`input`,{value:r.description,onChange:e=>s({description:e.target.value}),placeholder:n(`代码 / 方案 / PR 审查:有证据的发现与合并结论`,`Code / design / PR review: findings with evidence and a merge verdict`)})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`系统指令`,`System instructions`)}),(0,Q.jsx)(`textarea`,{value:r.systemPrompt,onChange:e=>s({systemPrompt:e.target.value}),rows:8,placeholder:`Explore the codebase to answer the delegated question. Do not modify files…`})]}),(0,Q.jsxs)(`div`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`工具`,`Tools`)}),(0,Q.jsx)(`div`,{className:`agents-tools`,children:tC.map(e=>(0,Q.jsxs)(`label`,{className:`agents-tool`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.tools.includes(e),onChange:()=>c(e)}),e]},e))})]}),(0,Q.jsxs)(`div`,{className:`agents-form-row`,children:[(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`模型(留空 = 跟随默认)`,`Model (empty = follow the default)`)}),(0,Q.jsxs)(`select`,{value:r.model??``,onChange:e=>s({model:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:n(`跟随默认模型`,`Follow the default model`)}),o.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`思考级别`,`Thinking level`)}),(0,Q.jsxs)(`select`,{value:r.thinking??``,onChange:e=>s({thinking:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:n(`跟随默认`,`Follow the default`)}),[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`].map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`agents-field agents-field-narrow`,children:[(0,Q.jsx)(`span`,{children:n(`最大轮次`,`Max turns`)}),(0,Q.jsx)(`input`,{type:`number`,min:1,max:200,value:r.maxTurns??``,onChange:e=>s({maxTurns:Number(e.target.value)||void 0})})]})]}),(0,Q.jsxs)(`div`,{className:`agents-form-actions`,children:[(0,Q.jsx)(`span`,{className:`agents-hint`,children:r.builtin?n(`内置模板:保存会生成一个同名用户文件(可再改回来)`,`Built-in template: saving creates a user file with the same name (you can revert later)`):n(`保存后对新建的子代理生效`,`Applies to subagents created after saving`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,children:n(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:r.id.trim()===``||r.systemPrompt.trim()===``,onClick:()=>{El({...r,id:r.id.trim(),label:r.label.trim()||r.id.trim()}),t()},children:n(`保存`,`Save`)})]})]})}var rC=`pop-agent:agents-list-width`,iC=168,aC=420,oC=232;function sC(e){return Math.min(aC,Math.max(iC,Math.round(e)))}function cC(){let e=J(),t=Ro(e=>e.snapshot),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(rC));return Number.isFinite(e)&&e>0?sC(e):oC}),o=(0,C.useRef)(!1);(0,C.useEffect)(()=>{localStorage.setItem(rC,String(i))},[i]);let s=e=>{e.preventDefault(),o.current=!0;let t=e.clientX,n=i,r=e=>{o.current&&a(sC(n+(e.clientX-t)))},s=()=>{o.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,s)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,s)},c=t?.subagentProfiles??[],l=t?.subagentSettings??{enabled:!0,concurrency:4},u=t?.engineCapabilities.subagents===!0,d=t?.engineCapabilities.subagentToolWhitelist;return(0,Q.jsxs)(`div`,{className:`agents-panel`,style:{"--agents-list-w":`${i}px`},children:[(0,Q.jsxs)(`header`,{className:`agents-head`,children:[(0,Q.jsxs)(`div`,{className:`agents-head-title`,children:[(0,Q.jsx)(`strong`,{children:e(`子代理`,`Subagents`)}),(0,Q.jsx)(`span`,{className:`agents-hint`,children:d===!1?e(`职责分工(委派说明)· 运行记录看对话下方`,`Roles as delegation briefs · run history sits below the conversation`):e(`职责分工与工具白名单 · 运行记录看对话下方`,`Roles and tool allowlists · run history sits below the conversation`)})]}),(0,Q.jsxs)(`div`,{className:`agents-head-actions`,children:[(0,Q.jsxs)(`label`,{className:`agents-toggle`,title:e(`关掉之后 Agent 工具不再暴露给模型(已有的模板保留)`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.enabled,onChange:e=>Ol({enabled:e.target.checked})}),e(`启用子代理`,`Enable subagents`)]}),(0,Q.jsxs)(`label`,{className:`agents-toggle agents-toggle-concurrency`,title:e(`最多同时开几个子代理,超出的排队`),children:[e(`默认同时开`,`Run at most`),(0,Q.jsx)(`select`,{value:l.concurrency,onChange:e=>Ol({concurrency:Number(e.target.value)}),children:[1,2,3,4,5,6,8,10,12].map(t=>(0,Q.jsx)(`option`,{value:t,children:e(`${t} 个`,`${t}`)},t))})]})]})]}),u?d===!1?(0,Q.jsx)(`div`,{className:`agents-banner`,children:e(`${t?.engine} 的子代理由引擎自己发起(模型调 spawn_agent),隔离靠沙箱与审批,所以模板里的工具勾选对它不生效。模板的「名称 + 说明」会作为委派说明注入新会话 —— 想让它真的只读,靠的是审批与沙箱,不是这里的勾选。`,`On ${t?.engine}, subagents are spawned by the engine itself (spawn_agent) and isolated by sandbox + approvals, so the per-tool ticks do not apply. A template's name and description are injected into new sessions as delegation briefs; read-only-ness comes from the sandbox and approvals, not from the ticks.`)}):null:(0,Q.jsx)(`div`,{className:`agents-banner`,children:t?.engine===`pi`||t?.engine===void 0?e(`当前服务还没有子代理能力:更新后请重启一次服务(pop restart),面板里的模板不受影响。`,`This service cannot run subagents yet: restart it after updating (pop restart). The templates in this panel are unaffected.`):e(`当前引擎(${t?.engine})不能跑子代理:切到 pi 原生引擎即可;模板可以先在这里配置。`,`The current engine (${t?.engine}) cannot run subagents: switch to the native pi engine. Templates can still be configured here.`)}),(0,Q.jsxs)(`div`,{className:`agents-body`,children:[(0,Q.jsxs)(`section`,{className:`agents-col agents-col-profiles`,children:[(0,Q.jsxs)(`div`,{className:`agents-col-head`,children:[(0,Q.jsx)(`span`,{children:e(`模板(${c.length})`,`Templates (${c.length})`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>r({id:``,label:``,description:``,systemPrompt:`Complete the delegated task end to end. Report what you changed with file paths.`,tools:[`read`,`grep`,`find`,`ls`],enabled:!0,builtin:!1}),children:[`+ `,e(`新建`,`New`)]})]}),c.length===0?(0,Q.jsxs)(`div`,{className:`agents-empty`,children:[(0,Q.jsx)(`p`,{children:e(`还没有可用的模板。`,`No templates available yet.`)}),(0,Q.jsx)(`p`,{className:`agents-hint`,children:e(`点上面的「+ 新建」建一个;内置的 explore / general-purpose / plan 会随服务一起出现。`,`Use “+ New” above to create one; the built-in explore / general-purpose / plan appear automatically.`)})]}):(0,Q.jsx)(`ul`,{className:`agents-profile-list`,children:c.map(t=>(0,Q.jsxs)(`li`,{className:`agents-profile${n?.id===t.id?` agents-profile-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`agents-profile-main`,onClick:()=>r(t),title:t.description?e(t.description,t.descriptionEn):t.id,children:[(0,Q.jsxs)(`span`,{className:`agents-profile-name`,children:[t.label,t.builtin?(0,Q.jsx)(`em`,{className:`agents-badge`,children:e(`内置`,`Built-in`)}):null]}),(0,Q.jsx)(`span`,{className:`agents-profile-desc`,children:t.description?e(t.description,t.descriptionEn):t.id})]}),(0,Q.jsx)(`label`,{className:`agents-profile-switch`,title:t.enabled?e(`停用`,`Disable`):e(`启用`,`Enable`),children:(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.enabled,onChange:e=>El({...t,enabled:e.target.checked})})}),t.builtin?null:(0,Q.jsx)(`button`,{type:`button`,className:`agents-profile-del`,title:e(`删除这个模板(内置模板可以改成同名用户文件再删,等于恢复默认)`),onClick:()=>Dl(t.id),children:`✕`})]},t.id))})]}),(0,Q.jsx)(`div`,{className:`agents-split`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整模板栏宽度`,`Resize the template column`),title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:s,onDoubleClick:()=>a(oC)}),(0,Q.jsx)(`section`,{className:`agents-col agents-col-runs`,children:n?(0,Q.jsx)(nC,{profile:n,onClose:()=>r(null)},`${n.id}-${n.builtin}`):(0,Q.jsxs)(`div`,{className:`agents-empty`,children:[(0,Q.jsx)(`p`,{children:c.length===0?e(`还没有模板:点左边「+ 新建」建一个。`,`No templates yet — use “+ New” on the left.`):e(`左边点一个模板就能改它的指令、工具白名单与模型。`,`Pick a template on the left to edit its instructions, tool allowlist and model.`)}),(0,Q.jsx)(`p`,{className:`agents-hint`,children:d===!1?e(`子代理跑起来之后,卡片会直接出现在对话下方(可就地看结果、可单独停掉);这里只管「谁能被委派」,隔离由引擎的沙箱与审批决定。`,`Once a subagent runs, its card shows up right below the conversation (read the result in place, stop it on its own); this panel only decides who can be delegated — isolation comes from the engine's sandbox and approvals.`):e(`子代理跑起来之后,卡片会直接出现在对话下方(带耗时 / token / 花费,可就地看结果、可单独停掉);这里只管「谁能被委派、用什么工具」。`,`Once a subagent runs, its card shows up right below the conversation (with duration / tokens / cost; read the result in place, stop it on its own); this panel only decides who can be delegated and with which tools.`)})]})})]})]})}var lC=5e3;function uC(e){let{name:t,workspace:n,prompt:r,expression:i,timezone:a,enabled:o,mode:s,allowWrites:c,sessionId:l,model:u}=e;return{name:t,workspace:n,prompt:r,expression:i,timezone:a,enabled:o,mode:s,allowWrites:c,sessionId:l,model:u}}function dC(e=``){return{name:``,workspace:e,prompt:``,expression:`0 9 * * *`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`,enabled:!0,mode:`text`,allowWrites:!1,sessionId:``,model:``}}var fC=e=>String(e).padStart(2,`0`);function pC(e){let t={preset:`advanced`,time:`09:00`,weekday:`1`,every:`5`,dayOfMonth:`1`},[n,r,i,a,o,s]=e.trim().split(/\s+/);if(s||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||a!==`*`)return t;let c=e=>/^\d{1,2}$/.test(e);if(/^\*\/\d{1,2}$/.test(n)&&r===`*`&&i===`*`&&o===`*`){let e=Number(n.slice(2));return e>=1&&e<=59?{...t,preset:`minutes`,every:String(e)}:t}if(n===`0`&&/^\*\/\d{1,2}$/.test(r)&&i===`*`&&o===`*`){let e=Number(r.slice(2));return e>=1&&e<=23?{...t,preset:`hours`,every:String(e)}:t}if(!c(n)||!c(r)||Number(n)>59||Number(r)>23)return t;let l=`${fC(Number(r))}:${fC(Number(n))}`;return i===`*`&&o===`*`?{...t,preset:`daily`,time:l}:i===`*`&&o===`1-5`?{...t,preset:`weekday`,time:l}:i===`*`&&/^[0-6]$/.test(o)?{...t,preset:`weekly`,time:l,weekday:o}:c(i)&&Number(i)>=1&&Number(i)<=31&&o===`*`?{...t,preset:`monthly`,time:l,dayOfMonth:String(Number(i))}:t}function mC(e,t=``){let{preset:n}=e;if(n===`advanced`)return t;if(n===`minutes`)return`*/${hC(e.every,59)} * * * *`;if(n===`hours`)return`0 */${hC(e.every,23)} * * *`;let[r,i]=(e.time||`09:00`).split(`:`),a=`${Number(i??0)} ${Number(r??9)}`;return n===`daily`?`${a} * * *`:n===`weekday`?`${a} * * 1-5`:n===`weekly`?`${a} * * ${gC(e.weekday)}`:`${a} ${Math.min(31,Math.max(1,Math.round(Number(e.dayOfMonth))||1))} * *`}function hC(e,t){let n=Math.round(Number(e));return Number.isFinite(n)?Math.min(t,Math.max(1,n)):1}function gC(e){let t=Math.round(Number(e));return String(Number.isFinite(t)&&t>=0&&t<=6?t:1)}function _C(e,t){return!!(e.name.trim()&&e.prompt.trim()&&e.timezone.trim()&&t.includes(e.workspace)&&e.expression.trim().split(/\s+/).length===5)}async function vC(e,t,n,r){let i=await fetch(`/api/cron${e}`,{method:t,credentials:`same-origin`,cache:`no-store`,signal:r,...n===void 0?{}:{headers:{"content-type":`application/json`},body:JSON.stringify(n)}});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(typeof e?.error==`string`&&e.error?e.error:q(`请求失败(HTTP ${i.status})`,`Request failed (HTTP ${i.status})`))}return i}async function yC(e){return(await vC(``,`GET`,void 0,e)).json()}async function bC(e){return(await vC(`/options`,`GET`,void 0,e)).json()}async function xC(e,t,n){return(await(await vC(`/preview`,`POST`,{expression:e,timezone:t},n)).json()).times}async function SC(e,t,n){await vC(t===void 0?`/jobs`:`/jobs/${encodeURIComponent(t)}`,t===void 0?`POST`:`PUT`,uC(e),n)}async function CC(e,t){await vC(`/jobs/${encodeURIComponent(e)}`,`DELETE`,void 0,t)}async function wC(e,t){await vC(`/jobs/${encodeURIComponent(e)}/run`,`POST`,void 0,t)}function TC(e,t=!1){if(!e)return`—`;let n=new Date(e);if(Number.isNaN(n.getTime()))return e;let r=e=>String(e).padStart(2,`0`),i=t?` ${new Intl.DateTimeFormat(void 0,{weekday:`short`}).format(n)}`:``;return`${r(n.getMonth()+1)}-${r(n.getDate())}${i} ${r(n.getHours())}:${r(n.getMinutes())}`}function EC(e,t,n=lC){let r=new AbortController,i,a=async()=>{try{let t=await yC(r.signal);r.signal.aborted||e(t)}catch(e){r.signal.aborted||t(e)}finally{r.signal.aborted||(i=setTimeout(()=>void a(),n))}};return a(),()=>{r.abort(),clearTimeout(i)}}function DC({initial:e,workspaces:t,options:n,busy:r,onSave:i,onCancel:a}){let o=J(),[s,c]=(0,C.useState)(()=>({...e,expression:e.expression.trim().split(/\s+/).join(` `)})),[l,u]=(0,C.useState)(()=>pC(e.expression)),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(``),_=JSON.stringify([s.expression,s.timezone]),v=d?.key===_?d:null,y=s.expression.trim().split(/\s+/).length===5&&!!s.timezone.trim();(0,C.useEffect)(()=>{if(!y)return;let e=new AbortController,t=setTimeout(()=>{xC(s.expression,s.timezone,e.signal).then(t=>{e.signal.aborted||f({key:_,times:t,error:``})},t=>{e.signal.aborted||f({key:_,times:[],error:t instanceof Error?t.message:String(t)})})},350);return()=>{clearTimeout(t),e.abort()}},[s.expression,s.timezone,_,y]);let b=(e,t)=>c(n=>({...n,[e]:t})),x=e=>{let t={...l,...e};u(t),t.preset!==`advanced`&&b(`expression`,mC(t,s.expression))},S=e=>{e.preventDefault(),!r&&_C(s,t)&&v&&!v.error&&i({...s,name:s.name.trim(),timezone:s.timezone.trim()})},w=async()=>{if(s.prompt.trim()!==``&&!window.confirm(o(`AI 生成的内容会覆盖当前提示词,继续吗?`,`AI will replace the current prompt. Continue?`)))return;g(``),m(!0);let e=await fu({name:s.name.trim()});m(!1),e.ok?b(`prompt`,e.text):g(e.message)},T=[o(`周日`,`Sunday`),o(`周一`,`Monday`),o(`周二`,`Tuesday`),o(`周三`,`Wednesday`),o(`周四`,`Thursday`),o(`周五`,`Friday`),o(`周六`,`Saturday`)],E=[o(`分钟`,`Minute`),o(`小时`,`Hour`),o(`日`,`Day`),o(`月`,`Month`),o(`星期`,`Weekday`)],D=n.sessions.filter(e=>e.workspace===s.workspace),O=s.expression.split(` `);return(0,Q.jsxs)(`form`,{className:`cron-editor`,onSubmit:S,children:[(0,Q.jsx)(`h3`,{children:o(`任务设置`,`Job settings`)}),(0,Q.jsxs)(`fieldset`,{disabled:r,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`名称`,`Name`),(0,Q.jsx)(`input`,{required:!0,value:s.name,onChange:e=>b(`name`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`工作目录`,`Workspace`),(0,Q.jsxs)(`select`,{"aria-label":o(`工作目录`,`Workspace`),required:!0,value:s.workspace,onChange:e=>{c(t=>({...t,workspace:e.target.value,sessionId:``}))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:o(`选择已注册的工作目录`,`Select a registered workspace`)}),!t.includes(s.workspace)&&s.workspace?(0,Q.jsxs)(`option`,{value:s.workspace,disabled:!0,children:[s.workspace,` — `,o(`未注册`,`Unregistered`)]}):null,t.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),t.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`请先注册一个项目工作目录。`,`Register a project workspace first.`)}):null,(0,Q.jsxs)(`div`,{className:`cron-field`,children:[(0,Q.jsxs)(`div`,{className:`cron-prompt-head`,children:[(0,Q.jsx)(`span`,{children:o(`提示词`,`Prompt`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p||s.name.trim()===``,onClick:()=>void w(),title:o(`根据任务名称,写一段要做的事(会覆盖当前提示词)`,`Write the task from its name (replaces the prompt)`),children:[`✨ `,p?o(`生成中…`,`Generating…`):o(`AI 生成`,`Generate with AI`)]})]}),(0,Q.jsx)(`textarea`,{"aria-label":o(`提示词`,`Prompt`),required:!0,rows:5,value:s.prompt,onChange:e=>b(`prompt`,e.target.value)}),h?(0,Q.jsx)(`p`,{className:`cron-hint cron-warn`,role:`alert`,children:h}):null]}),(0,Q.jsx)(`div`,{className:`cron-form-row`,children:(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`任务类型`,`Task type`),(0,Q.jsxs)(`select`,{"aria-label":o(`任务类型`,`Task type`),value:s.mode,onChange:e=>b(`mode`,e.target.value===`agent`?`agent`:`text`),children:[(0,Q.jsx)(`option`,{value:`text`,children:o(`文本任务(不读写仓库)`,`Text task (no repo access)`)}),(0,Q.jsx)(`option`,{value:`agent`,children:o(`Agent 任务(真开会话执行)`,`Agent task (runs in a session)`)})]})]})}),s.mode===`agent`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`Agent 任务会在该工作区新建一个会话并真跑一遍:能读文件、跑命令。每次运行都会在侧栏留下一条会话记录。`,`Agent tasks open a real session in this workspace: they can read files and run commands. Every run leaves a session in the sidebar.`)}),(0,Q.jsxs)(`div`,{className:`cron-form-row`,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`会话`,`Session`),(0,Q.jsxs)(`select`,{"aria-label":o(`会话`,`Session`),value:D.some(e=>e.id===s.sessionId)?s.sessionId:``,onChange:e=>b(`sessionId`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`每次新建会话`,`New session each run`)}),D.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.title||e.id},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`模型`,`Model`),(0,Q.jsxs)(`select`,{"aria-label":o(`模型`,`Model`),value:s.model,onChange:e=>b(`model`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:s.sessionId?o(`沿用该会话原来的模型`,`Keep the session's model`):o(`跟随项目默认模型`,`Use the project default`)}),n.models.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),s.sessionId?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`会在这个会话里继续跑:提示词与结果都会进它的历史,同步删掉会话后任务会报错停下。`,`Runs inside that session: prompt and result go into its history; deleting the session makes the job fail.`)}):null,(0,Q.jsxs)(`label`,{className:`cron-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.allowWrites,onChange:e=>b(`allowWrites`,e.target.checked)}),o(`允许改动文件(无人值守时会自动执行写操作)`,`Allow file writes (unattended writes run without confirmation)`)]}),s.allowWrites?(0,Q.jsx)(`p`,{className:`cron-hint cron-warn`,children:o(`已开启:运行期间 agent 的写操作不会问你,可能直接改掉工作区文件。请确认工作目录里没有不想被改的东西。`,`Enabled: the agent's writes will not ask you, and it may modify this workspace directly. Make sure nothing here is unsafe to change.`)}):(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`未开启时:需要审批的操作会被自动拒绝,agent 只能读 —— 适合「每天检查并汇报」,不适合「自动修 bug」。`,`While off, anything needing approval is auto-denied and the agent can only read — fine for daily checks, not for auto-fixing code.`)})]}):(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`文本任务只把提示词发给模型,不读文件、不跑命令 —— 便宜且可预测。要让它干活请选 Agent 任务。`,`Text tasks only send the prompt to a model: no file access, no commands — cheap and predictable. Choose Agent task to actually do work.`)}),(0,Q.jsxs)(`div`,{className:`cron-form-row`,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`计划`,`Schedule`),(0,Q.jsxs)(`select`,{"aria-label":o(`计划`,`Schedule`),value:l.preset,onChange:e=>x({preset:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`minutes`,children:o(`每隔几分钟`,`Every N minutes`)}),(0,Q.jsx)(`option`,{value:`hours`,children:o(`每隔几小时`,`Every N hours`)}),(0,Q.jsx)(`option`,{value:`daily`,children:o(`每天`,`Daily`)}),(0,Q.jsx)(`option`,{value:`weekday`,children:o(`工作日`,`Weekdays`)}),(0,Q.jsx)(`option`,{value:`weekly`,children:o(`每周`,`Weekly`)}),(0,Q.jsx)(`option`,{value:`monthly`,children:o(`每月`,`Monthly`)}),(0,Q.jsx)(`option`,{value:`advanced`,children:o(`高级(五字段)`,`Advanced (five fields)`)})]})]}),l.preset===`weekly`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`星期`,`Weekday`),(0,Q.jsx)(`select`,{"aria-label":o(`星期`,`Weekday`),value:l.weekday,onChange:e=>x({preset:`weekly`,weekday:e.target.value}),children:T.map((e,t)=>(0,Q.jsx)(`option`,{value:String(t),children:e},t))})]}):null,l.preset===`monthly`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`每月几号`,`Day of month`),(0,Q.jsx)(`select`,{"aria-label":o(`每月几号`,`Day of month`),value:l.dayOfMonth,onChange:e=>x({dayOfMonth:e.target.value}),children:Array.from({length:31},(e,t)=>String(t+1)).map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}):null,l.preset===`minutes`||l.preset===`hours`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[l.preset===`minutes`?o(`每隔(分钟)`,`Every (minutes)`):o(`每隔(小时)`,`Every (hours)`),(0,Q.jsx)(`input`,{type:`number`,required:!0,min:1,max:l.preset===`minutes`?59:23,value:l.every,onChange:e=>x({every:e.target.value})})]}):null,l.preset!==`advanced`&&l.preset!==`minutes`&&l.preset!==`hours`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`时间`,`Time`),(0,Q.jsx)(`input`,{type:`time`,required:!0,value:l.time,onChange:e=>x({time:e.target.value})})]}):null]}),l.preset===`advanced`?(0,Q.jsx)(`div`,{className:`cron-fields`,children:E.map((e,t)=>(0,Q.jsxs)(`label`,{className:`cron-field`,children:[e,(0,Q.jsx)(`input`,{required:!0,spellCheck:!1,value:O[t]??``,onChange:e=>{let n=Array.from({length:5},(e,t)=>O[t]??``);n[t]=e.target.value.replace(/\s/g,``),b(`expression`,n.join(` `))}})]},t))}):null,(0,Q.jsx)(`code`,{className:`cron-expression`,children:s.expression}),l.preset===`minutes`||l.preset===`hours`?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`每 ${l.every} ${l.preset===`minutes`?`分钟`:`小时`}运行一次(按整点对齐,如每 15 分钟在 :00 / :15 / :30 / :45)`,`Runs every ${l.every} ${l.preset===`minutes`?`minutes`:`hours`} (aligned to the clock: every 15 minutes fires at :00 / :15 / :30 / :45)`)}):null,(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`时区`,`Timezone`),(0,Q.jsx)(`input`,{required:!0,placeholder:`Asia/Shanghai`,spellCheck:!1,value:s.timezone,onChange:e=>b(`timezone`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`cron-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.enabled,onChange:e=>b(`enabled`,e.target.checked)}),o(`启用`,`Enabled`)]})]}),(0,Q.jsxs)(`section`,{className:`cron-preview`,"aria-live":`polite`,"aria-busy":y&&!v,children:[(0,Q.jsx)(`strong`,{children:o(`下次运行预览`,`Upcoming runs`)}),y?v?v.error?(0,Q.jsx)(`p`,{role:`alert`,children:v.error}):v.times.length===0?(0,Q.jsx)(`p`,{children:o(`没有即将运行的时间`,`No upcoming runs`)}):(0,Q.jsx)(`ul`,{children:v.times.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`time`,{dateTime:e,children:TC(e,!0)})},`${e}-${t}`))}):(0,Q.jsx)(`p`,{children:o(`正在预览…`,`Loading preview…`)}):(0,Q.jsx)(`p`,{children:o(`请输入五字段表达式和时区。`,`Enter a five-field expression and timezone.`)})]}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:r||!_C(s,t)||!v||!!v.error,children:r?o(`保存中…`,`Saving…`):o(`保存`,`Save`)}),(0,Q.jsx)(`button`,{className:`btn`,type:`button`,disabled:r,onClick:a,children:o(`取消`,`Cancel`)})]})]})}function OC(){let e=J(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)({sessions:[],models:[]}),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)(0),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(null),y=(0,C.useRef)(null);(0,C.useEffect)(()=>EC(e=>{n(e),o(``)},e=>o(e instanceof Error?e.message:String(e))),[l]),(0,C.useEffect)(()=>()=>y.current?.abort(),[]),(0,C.useEffect)(()=>{let e=new AbortController;return bC(e.signal).then(t=>{e.signal.aborted||i(t)},()=>void 0),()=>e.abort()},[l]);let b=async e=>{if(y.current)return!1;let t=new AbortController;y.current=t,f(!0),c(``);try{return await e(t.signal),!t.signal.aborted&&(u(e=>e+1),!0)}catch(e){return t.signal.aborted||c(e instanceof Error?e.message:String(e)),!1}finally{t.signal.aborted||(y.current=null,f(!1))}},x={queued:e(`排队中`,`Queued`),running:e(`运行中`,`Running`),succeeded:e(`已成功`,`Succeeded`),failed:e(`已失败`,`Failed`),interrupted:e(`已中断`,`Interrupted`),skipped:e(`已跳过`,`Skipped`)},S=e=>{c(``),v(null),m(e?{id:e.id,draft:uC(e)}:{draft:dC(t?.workspaces[0])})},w=t?.jobs??[],T=t=>w.find(e=>e.id===t)?.name??e(`(已删除的任务)`,`(deleted job)`),E=(t?.runs??[]).filter(e=>h===null||e.jobId===h);return(0,Q.jsxs)(`div`,{className:`cron-panel`,children:[(0,Q.jsxs)(`header`,{className:`cron-head`,children:[(0,Q.jsx)(`h2`,{children:e(`定时任务`,`Cron`)}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>u(e=>e+1),children:e(`刷新`,`Refresh`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d||!t,onClick:()=>S(),children:e(`新建任务`,`New job`)})]})]}),(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`自动刷新。运行历史和结果仅以文本显示,不会打开普通代理会话。`,`Refreshes automatically. Run history and results are shown as text; no regular agent session is opened.`)}),a?(0,Q.jsx)(`div`,{className:`cron-error`,role:`alert`,children:a}):null,s?(0,Q.jsx)(`div`,{className:`cron-error`,role:`alert`,children:s}):null,!t&&!a?(0,Q.jsx)(`p`,{role:`status`,children:e(`加载中…`,`Loading…`)}):null,(0,Q.jsxs)(`div`,{className:`cron-layout`,children:[(0,Q.jsxs)(`section`,{className:`cron-jobs`,"aria-label":e(`定时任务`,`Cron`),children:[t&&w.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`暂无定时任务`,`No scheduled jobs yet`)}):null,w.map(t=>(0,Q.jsxs)(`article`,{className:`cron-job${h===t.id?` cron-job-selected`:``}`,children:[(0,Q.jsxs)(`div`,{className:`cron-job-heading`,children:[(0,Q.jsx)(`h3`,{children:t.name}),(0,Q.jsxs)(`span`,{className:`cron-job-tags`,children:[t.mode===`agent`?(0,Q.jsx)(`span`,{className:`cron-badge`,children:t.allowWrites?e(`Agent · 可写`,`Agent · writes`):e(`Agent · 只读`,`Agent · read-only`)}):(0,Q.jsx)(`span`,{className:`cron-badge cron-badge-plain`,children:e(`文本`,`Text`)}),(0,Q.jsx)(`span`,{className:`cron-hint`,children:t.enabled?e(`已启用`,`Enabled`):e(`已暂停`,`Paused`)})]})]}),(0,Q.jsx)(`p`,{className:`cron-workspace`,children:t.workspace}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`code`,{children:t.expression}),` · `,t.timezone]}),t.mode===`agent`&&(t.sessionId||t.model)?(0,Q.jsxs)(`p`,{className:`cron-hint`,children:[t.sessionId?`${e(`续跑会话`,`Session`)}: ${r.sessions.find(e=>e.id===t.sessionId)?.title??t.sessionId}`:e(`每次新建会话`,`New session each run`),t.model?` · ${e(`模型`,`Model`)}: ${t.model}`:``]}):null,(0,Q.jsxs)(`p`,{className:`cron-hint`,children:[e(`下次运行`,`Next run`),`:`,` `,t.nextRunAt?(0,Q.jsx)(`time`,{dateTime:t.nextRunAt,children:TC(t.nextRunAt)}):`—`]}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>S(t),children:e(`编辑`,`Edit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>void b(e=>SC({...uC(t),enabled:!t.enabled},t.id,e)),children:t.enabled?e(`暂停`,`Pause`):e(`启用`,`Enable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>{g(t.id),b(e=>wC(t.id,e))},children:e(`立即运行`,`Run now`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,"aria-pressed":h===t.id,onClick:()=>g(h===t.id?null:t.id),children:e(`历史`,`History`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>v(t.id),children:e(`删除`,`Delete`)})]}),_===t.id?(0,Q.jsxs)(`div`,{className:`cron-delete`,role:`group`,"aria-label":e(`确认删除`,`Confirm deletion`),children:[(0,Q.jsx)(`span`,{children:e(`删除此定时任务?`,`Delete this scheduled job?`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>void b(e=>CC(t.id,e)).then(e=>{e&&(v(null),h===t.id&&g(null),p?.id===t.id&&m(null))}),children:e(`确认删除`,`Confirm deletion`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>v(null),children:e(`取消`,`Cancel`)})]}):null]},t.id))]}),(0,Q.jsxs)(`div`,{className:`cron-detail`,children:[p?(0,Q.jsx)(DC,{options:r,initial:p.draft,workspaces:t?.workspaces??[],busy:d,onCancel:()=>m(null),onSave:async e=>{await b(t=>SC(e,p.id,t))&&m(null)}},p.id??`new`):null,(0,Q.jsxs)(`section`,{className:`cron-history`,"aria-label":e(`运行历史`,`Run history`),children:[(0,Q.jsxs)(`div`,{className:`cron-job-heading`,children:[(0,Q.jsxs)(`h3`,{children:[e(`运行历史`,`Run history`),h?` · ${T(h)}`:``]}),h?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>g(null),children:e(`全部任务`,`All jobs`)}):null]}),t&&E.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`暂无运行记录`,`No runs yet`)}):null,E.map(t=>(0,Q.jsxs)(`details`,{className:`cron-run`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`cron-status cron-status-${t.status}`,children:x[t.status]}),(0,Q.jsx)(`span`,{children:T(t.jobId)}),(0,Q.jsx)(`span`,{className:`cron-hint`,children:t.trigger===`manual`?e(`手动`,`Manual`):e(`计划`,`Scheduled`)}),(0,Q.jsx)(`time`,{dateTime:t.startedAt??t.scheduledAt,children:TC(t.startedAt??t.scheduledAt)})]}),(0,Q.jsx)(`dl`,{children:[[e(`计划时间`,`Scheduled at`),t.scheduledAt],[e(`开始时间`,`Started at`),t.startedAt],[e(`结束时间`,`Finished at`),t.finishedAt]].map(([e,t])=>t?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:e}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`time`,{dateTime:t,children:TC(t)})})]},e):null)}),t.result===void 0?null:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:e(`结果`,`Result`)}),(0,Q.jsx)(`pre`,{className:`cron-result`,children:t.result})]}),t.error===void 0?null:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:e(`错误`,`Error`)}),(0,Q.jsx)(`pre`,{className:`cron-result cron-error`,children:t.error})]})]},t.id))]})]})]})]})}var kC={min:.25,max:4},AC={min:0,max:200};async function jC(e,t){let n=await fetch(`/api/computer${e}`,{method:t?.method??`GET`,credentials:`same-origin`,cache:`no-store`,...t?.signal?{signal:t.signal}:{},...t?.body===void 0?{}:{headers:{"content-type":`application/json`},body:JSON.stringify(t.body)}}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}var MC=()=>jC(`/status`),NC=(e,t)=>jC(`/apps?query=${encodeURIComponent(e)}`,{signal:t}),PC=()=>jC(`/settings`),FC=e=>jC(`/settings`,{method:`PUT`,body:e}),IC=()=>jC(`/request-access`,{method:`POST`}),LC=e=>jC(`/open-privacy`,{method:`POST`,body:{pane:e}}),RC=e=>jC(`/skill`,{method:`POST`,body:{enabled:e}});function zC(){let e=J(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)([]),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(0),[h,g]=(0,C.useState)(``),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(!1),[x,S]=(0,C.useState)(null),w=async()=>{S(null);try{let[e,t]=await Promise.all([MC(),PC()]);n(e),i(t),o(t.unprotectedApps.join(`
66
+ `)[0]}),(0,Q.jsx)(`span`,{className:`mcp-sample-hint`,children:c(e.hint)})]},e.label))]}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[c(`写进 pi 自己的`,`Written into pi's own`),` `,(0,Q.jsx)(`code`,{children:`mcp.json`}),c(`,`,`, `),(0,Q.jsx)(`strong`,{children:c(`对新会话生效`,`effective for new sessions`)}),c(`。同名不会覆盖:会自动加序号(预览里会写出来)。需要密钥的服务器,先把值写成`,`. Existing names are never overwritten — a suffix is added (shown in the preview). For servers that need a secret, write the value as`),` `,(0,Q.jsx)(`code`,{children:"${ENV_NAME}"}),c(`,面板里能看出这台机器上有没有设。`,`; the panel shows whether it is set on this machine.`)]})]})}function RS({servers:e,projectPath:t,globalPath:n,selected:r,pane:i,busy:a,onSelect:o,onToggleScope:s,onPane:c}){let l=Y(),u=[{scope:`project`,label:l(`项目`,`Project`),path:t,items:e.filter(e=>e.scope===`project`)},{scope:`global`,label:l(`全局`,`Global`),path:n,items:e.filter(e=>e.scope===`global`)}];return(0,Q.jsxs)(`div`,{className:`mcp-list`,children:[(0,Q.jsx)(`div`,{className:`mcp-list-scroll`,children:u.map(e=>(0,Q.jsxs)(`div`,{className:`mcp-group`,children:[(0,Q.jsxs)(`div`,{className:`mcp-group-head`,children:[(0,Q.jsx)(`span`,{children:e.label}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.items.filter(e=>e.enabled).length,`/`,e.items.length]}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e.items.length>0&&e.items.every(e=>e.enabled),"aria-label":l(`${e.label}的服务器全部${e.items.every(e=>e.enabled)?`停用`:`启用`}`,`${e.items.every(e=>e.enabled)?`Disable`:`Enable`} every server in ${e.label}`),className:`mcp-switch${e.items.some(e=>e.enabled)?` mcp-switch-on`:``}`,disabled:e.items.length===0||a,title:l(`${e.label}这一份配置里的服务器一起开 / 关`,`Turn every server in this ${e.label} config on / off together`),onClick:()=>s(e.scope,!e.items.every(e=>e.enabled)),children:e.items.every(e=>e.enabled)?l(`全关`,`All off`):l(`全开`,`All on`)})]}),e.items.length===0?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:e.scope===`project`?l(`这个项目没有自己的 MCP`,`This project has no MCP servers of its own`):l(`还没有 MCP 服务器`,`No MCP servers yet`)}):e.items.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`mcp-item${r===bS(e)?` mcp-item-on`:``}${e.enabled?``:` mcp-item-off`}`,onClick:()=>o(bS(e)),title:e.description??e.name,children:[(0,Q.jsx)(`span`,{className:`mcp-dot${e.enabled?` mcp-dot-on`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`mcp-item-name`,children:e.name})]},bS(e))),e.items.length>0&&e.path?(0,Q.jsx)(`span`,{className:`mcp-list-path mono`,title:e.path,children:e.path}):null]},e.scope))}),(0,Q.jsxs)(`div`,{className:`mcp-left-actions`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny${i===`add`?` btn-on`:``}`,onClick:()=>c(`add`),children:[`+ `,l(`添加 MCP`,`Add MCP`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${i===`market`?` btn-on`:``}`,onClick:()=>c(`market`),title:l(`从公开注册中心一键添加`,`Add from the public registry in one click`),children:l(`市场`,`Market`)})]})]})}function zS({server:e,busy:t,login:n,onExposure:r,onLogin:i,onLoginCancel:a,onRecheck:o}){let s=Y(),c=e.probe,l=c!==void 0&&!c.ok&&_S(c.error),u=c?c.ok?s(`连接成功 · ${c.tools.length} 个工具 · ${c.ms}ms`,`Connected · ${c.tools.length} tools · ${c.ms}ms`):s(`连接失败 · ${c.error??`未知错误`}`,`Failed · ${c.error??`unknown error`}`):s(`还没测过`,`Not tested yet`);return(0,Q.jsxs)(`div`,{className:`mcp-body`,children:[(0,Q.jsxs)(BS,{label:s(`状态`,`Status`),children:[(0,Q.jsx)(`span`,{className:e.enabled?`mcp-state-on`:`mcp-state-off`,children:e.enabled?s(`已启用`,`Enabled`):s(`已停用`,`Disabled`)}),(0,Q.jsxs)(`span`,{className:c&&!c.ok?`side-error`:`side-panel-count`,children:[` · `,u]})]}),l||e.transport===`http`&&(e.auth!==void 0||n!==void 0)?(0,Q.jsx)(BS,{label:s(`授权`,`Authorization`),children:(0,Q.jsxs)(`span`,{className:`mcp-auth`,children:[n?.status===`waiting`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`在浏览器里完成授权`,`Finish authorization in the browser`),n.url===void 0?s(`(正在准备授权页…)`,` (preparing the authorization page…)`):s(`,完成后回来点「我已授权」`,`, then come back and click “I've authorized”`),s(`:`,`:`)]}),n.url===void 0?null:(0,Q.jsx)(`a`,{className:`mcp-catalog-link mcp-auth-url mono`,href:n.url,target:`_blank`,rel:`noreferrer`,children:s(`打开授权页 ↗`,`Open the authorization page ↗`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:o,children:s(`我已授权,重测`,`I've authorized — retest`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:a,children:s(`取消`,`Cancel`)})]}):e.auth?.present&&e.auth.expired?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`存过凭据但已过期(pi 会在真正调用时用 refresh token 续期;连不上就重新登录一次)`,`Credentials saved but expired (pi renews them with the refresh token on real calls; sign in again if it cannot connect)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:i,children:s(`重新登录`,`Sign in again`)})]}):e.auth?.present?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`mcp-auth-ok`,children:[s(`已登录`,`Signed in`),e.auth.scope?` (${e.auth.scope})`:``]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:i,children:s(`重新登录`,`Sign in again`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`这台是远程 HTTP 服务器,要 OAuth 授权才能用(对面回了 401 / requires authentication)。 登录用 pi 自己的`,`This is a remote HTTP server; it needs OAuth authorization (the other side returned 401 / requires authentication). Sign in with pi's own`),` `,(0,Q.jsx)(`code`,{children:`pi mcp login`}),` `,s(`流程,凭据写进`),` `,(0,Q.jsx)(`code`,{children:`mcp-auth.json`}),s(`,会话也跟着用。`,`, and sessions use them too.`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-add`,disabled:t,onClick:i,children:t?s(`准备中…`,`Preparing…`):s(`登录`,`Sign in`)})]}),n?.status===`failed`?(0,Q.jsx)(`span`,{className:`side-error`,children:n.message??s(`登录失败`,`Sign-in failed`)}):null]})}):null,(0,Q.jsx)(BS,{label:s(`简介`,`About`),children:e.description??(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`没写。这一句会进系统提示,帮模型知道该不该用这台服务器。`,`Not set. This line goes into the system prompt so the model knows whether to use this server.`)})}),e.transport===`stdio`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(BS,{label:s(`命令`,`Command`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:SS(e)}),(0,Q.jsx)(ah,{text:SS(e),className:`btn btn-tiny`,title:s(`复制命令`,`Copy command`)})]}),e.cwd?(0,Q.jsx)(BS,{label:s(`工作目录`,`Working directory`),children:e.cwd}):null]}):(0,Q.jsxs)(BS,{label:s(`地址`,`URL`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:e.url}),(0,Q.jsx)(ah,{text:e.url??``,className:`btn btn-tiny`,title:s(`复制地址`,`Copy URL`)})]}),Object.keys(e.env??{}).length>0?(0,Q.jsx)(BS,{label:s(`环境变量`,`Environment`),children:Object.entries(e.env??{}).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-tool`,title:CS(t)?s(`整条值是一条命令:pi 会跑它,把 stdout 当值`,`The whole value is a command: pi runs it and uses stdout as the value`):void 0,children:[e,`=`,t]},`env-${e}`))}):null,Object.keys(e.headers??{}).length>0?(0,Q.jsx)(BS,{label:s(`请求头`,`Headers`),children:Object.entries(e.headers??{}).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-tool`,children:[e,`: `,t]},`header-${e}`))}):null,e.envRefs.length>0?(0,Q.jsx)(BS,{label:s(`主机环境变量`,`Host environment`),children:(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e.transport===`http`?s(`请求头里的变量取自运行 Pi Web 的这台机器:`,`Header values are read from the machine running Pi Web:`):s(`启动它的命令会拿到运行 Pi Web 的这台机器上的变量:`,`The launch command gets the variables of the machine running Pi Web:`),e.envRefs.map(e=>(0,Q.jsxs)(`span`,{className:`mcp-ref${e.present?` mcp-ref-ok`:` mcp-ref-missing`}`,children:[s(`${e.key} 里的 ${e.variable}`,`${e.variable} on ${e.key}`),e.present?s(` 已设置`,` set`):s(` 未设置`,` not set`)]},`${e.key}-${e.variable}`))]})}):null,(0,Q.jsxs)(BS,{label:s(`工具`,`Tools`),children:[(0,Q.jsx)(`select`,{className:`mcp-exposure`,value:e.exposure,disabled:t,onChange:e=>r(e.target.value),children:Object.keys(pS).map(e=>(0,Q.jsx)(`option`,{value:e,children:s(pS[e],mS[e])},e))}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(hS[e.exposure],gS[e.exposure])}),e.toolExposure?(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[s(`单个工具另有设置:`,`Per-tool overrides:`),Object.entries(e.toolExposure).map(([e,t])=>(0,Q.jsxs)(`span`,{className:`mcp-ref`,children:[e,` → `,s(pS[t],mS[t])]},e))]}):null]}),c?.ok&&c.tools.length>0?(0,Q.jsx)(BS,{label:s(`工具清单`,`Tools found`),children:(0,Q.jsx)(`div`,{className:`mcp-tools`,children:c.tools.map(e=>(0,Q.jsx)(`span`,{className:`mcp-tool`,title:e.description,children:e.name},e.name))})}):null,c&&!c.ok&&c.stderr?(0,Q.jsx)(BS,{label:`stderr`,children:(0,Q.jsx)(`pre`,{className:`mcp-stderr`,children:c.stderr})}):null,(0,Q.jsx)(BS,{label:s(`超时`,`Timeout`),children:(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.timeout} 秒(配置里的 timeout;不写就是 60)`,`${e.timeout}s (timeout from the config; 60 if unset)`)})}),(0,Q.jsxs)(BS,{label:s(`文件`,`File`),children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,children:e.source}),e.override?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.override} 里有本项目的覆盖项`,`${e.override} has overrides for this project`)}):null]})]})}function BS({label:e,children:t}){return(0,Q.jsxs)(`div`,{className:`mcp-row`,children:[(0,Q.jsx)(`span`,{className:`mcp-row-key`,children:e}),(0,Q.jsx)(`span`,{className:`mcp-row-value`,children:t})]})}var VS=[{id:`registry`,label:`官方注册中心`,hint:`registry.modelcontextprotocol.io(npm / PyPI 与远程地址)`},{id:`smithery`,label:`Smithery`,hint:`smithery.ai 托管的远程服务器,第一次连接可能要登录`},{id:`github`,label:`官方参考服务器`,hint:`modelcontextprotocol/servers 仓库`}];function HS(e){return e.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/`([^`]+)`/g,`$1`).replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,`$1`)}function US(e){return e.config.url===void 0?[e.config.command??``,...e.config.args??[]].filter(e=>e!==``).join(` `):e.config.url}function WS(e,t){return e.startsWith(`版本 `)?`${t(`版本`,`Version`)} ${e.slice(3)}`:t(e)}function GS({installed:e,busy:t,source:n,onSource:r,query:i,onQuery:a,onAdd:o}){let s=Y(),[c,l]=(0,C.useState)(``),[u,d]=(0,C.useState)(null),[f,p]=(0,C.useState)(null),[m,h]=(0,C.useState)(!1),[g,_]=(0,C.useState)(0);(0,C.useEffect)(()=>{let e=window.setTimeout(()=>l(i.trim()),400);return()=>window.clearTimeout(e)},[i]),(0,C.useEffect)(()=>{let e=!1;return h(!0),p(null),(async()=>{try{let t=new URLSearchParams({source:n,q:c});g>0&&t.set(`refresh`,`1`);let r=await fetch(`/api/mcp/market?${t.toString()}`),i=await r.json();if(e)return;if(!r.ok||i.ok===!1){d(null),p(i.error??`HTTP ${r.status}`);return}d(i.entries??[]),p(i.error??null)}catch(t){if(e)return;d(null),p(t instanceof Error?t.message:String(t))}finally{e||h(!1)}})(),()=>{e=!0}},[n,c,g]);let v=(0,C.useCallback)(()=>_(e=>e+1),[]),y=VS.find(e=>e.id===n),b=new Set(e);return(0,Q.jsxs)(`div`,{className:`mcp-market`,children:[(0,Q.jsxs)(`div`,{className:`mcp-add-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:s(`MCP 市场`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:u===null?``:s(`${u.length} 个`,`${u.length}`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:m,onClick:v,title:s(`忽略缓存重新拉一次`,`Fetch again, ignoring the cache`),children:m?s(`拉取中…`,`Fetching…`):s(`刷新`,`Refresh`)})]}),(0,Q.jsxs)(`div`,{className:`mcp-market-bar`,children:[(0,Q.jsx)(`select`,{className:`mcp-market-source`,value:n,onChange:e=>r(e.target.value),title:s(`从哪个源拉`),children:VS.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:s(e.label)},e.id))}),(0,Q.jsx)(`input`,{className:`mcp-market-search`,value:i,placeholder:s(`搜索名称、包名或能力描述…`),onChange:e=>a(e.target.value)})]}),y?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(y.hint)}):null,f===null?null:(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:f}),u===null&&m?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`正在拉取市场清单…(官方注册中心首次要十几秒)`)}):null,u!==null&&u.length===0&&!m?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:s(`这个源里没有匹配的服务器,换个词或换个源试试。`)}):null,(0,Q.jsx)(`div`,{className:`mcp-market-list`,children:(u??[]).map(e=>{let n=b.has(e.name);return(0,Q.jsxs)(`div`,{className:`mcp-market-card`,children:[(0,Q.jsxs)(`div`,{className:`mcp-market-card-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-market-title`,children:e.title}),e.verified?(0,Q.jsx)(`span`,{className:`mcp-badge`,children:s(`官方`)}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),e.homepage?(0,Q.jsxs)(`a`,{className:`mcp-catalog-link`,href:e.homepage,target:`_blank`,rel:`noreferrer`,children:[s(`主页`,`Home`),` ↗`]}):null]}),e.description?(0,Q.jsx)(`p`,{className:`mcp-market-desc`,children:HS(e.description)}):null,(0,Q.jsxs)(`div`,{className:`mcp-market-target`,children:[(0,Q.jsx)(`span`,{className:`mcp-value mono`,title:US(e),children:e.pkg??US(e)}),e.downloads===void 0?null:(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`${e.downloads.toLocaleString()} 次使用`,`${e.downloads.toLocaleString()} uses`)})]}),e.needsEnv&&e.needsEnv.length>0?(0,Q.jsxs)(`div`,{className:`mcp-market-needs`,children:[s(`装好后还要补环境变量:`,`Set these environment variables after installing:`),e.needsEnv.map(e=>(0,Q.jsx)(`span`,{className:`mcp-tool`,children:e},e))]}):null,e.note?(0,Q.jsx)(`div`,{className:`side-panel-count`,children:WS(e.note,s)}):null,(0,Q.jsxs)(`div`,{className:`mcp-market-actions`,children:[n?(0,Q.jsx)(`span`,{className:`side-panel-count`,children:s(`已有同名配置`)}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:()=>o(e,`global`),title:s(`写进 ~/.pi/agent/mcp.json`),children:[`+ `,s(`添加全局`,`Add globally`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:t,onClick:()=>o(e,`project`),title:s(`写进当前项目的 .pi/mcp.json`),children:[`+ `,s(`添加项目`,`Add to project`)]})]})]},e.id)})}),(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[s(`清单来自公开注册中心(1 小时磁盘缓存)。一键添加只写 mcp.json 里那一条配置,卡上写明要补的环境变量,`,`The list comes from the public registry (1-hour disk cache). One-click add writes only the single mcp.json entry; missing environment variables are listed on the card —`),(0,Q.jsx)(`strong`,{children:s(`对新会话生效`,`effective for new sessions`)}),s(`。`,`.`)]})]})}function KS(){let e=Y(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(null),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)({kind:`detail`}),[h,g]=(0,C.useState)(`global`),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(`registry`),[x,S]=(0,C.useState)(``),[w,T]=(0,C.useState)(null),[E,D]=(0,C.useState)(!0),[O,k]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(`pop-agent:mcp-list-width`));return Number.isFinite(e)&&e>=160&&e<=520?e:220});(0,C.useEffect)(()=>{localStorage.setItem(`pop-agent:mcp-list-width`,String(O))},[O]);let A=(0,C.useRef)(!1),j=e=>{e.preventDefault(),A.current=!0;let t=e.clientX,n=O,r=e=>{A.current&&k(Math.min(520,Math.max(160,n+(e.clientX-t))))},i=()=>{A.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,i)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,i)},M=()=>k(220);(0,C.useEffect)(()=>{if(w?.state.status!==`waiting`)return;let e={name:w.name,scope:w.scope},t=window.setInterval(()=>void F(`login-status`,e),2e3);return()=>window.clearInterval(t)},[w?.state.status,w?.name,w?.scope]),(0,C.useEffect)(()=>{w?.state.status===`done`&&F(`test`,{name:w.name,scope:w.scope})},[w?.state.status,w?.name,w?.scope]);let N=e=>{e.servers&&n(e),i(e.actionError??(typeof e.error==`string`?e.error:null)),o(e.notice??null)},P=(0,C.useCallback)(async()=>{i(null),D(!0);try{let e=await fetch(`/api/mcp`),t=await qS(e);if(t.view===void 0){i(t.error??`HTTP ${e.status}`);return}if(!e.ok){i(xS(t.view,e.status));return}N(t.view)}catch(e){i(e instanceof Error?e.message:String(e))}finally{D(!1)}},[]);(0,C.useEffect)(()=>{P()},[P]);let F=async(e,t,n={})=>{let r=`${e}:${t?bS(t):String(n.scope??`new`)}`;c(r),o(null);try{let r=await fetch(`/api/mcp`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({action:e,name:t?.name,scope:t?.scope??n.scope,...n})}),a=await r.json();if(!r.ok){i(xS(a,r.status));return}if(N(a),a.login!==void 0){let e=t?.scope??n.scope??`global`;T({name:a.login.name,scope:e,state:a.login})}if(e===`add`&&a.servers){m({kind:`detail`});let e=n.scope??h,t=a.added?.[0],r=a.servers.find(n=>n.scope===e&&(t===void 0||n.name===t));r&&u(bS(r))}e===`remove`&&t&&l===bS(t)&&u(null)}catch(e){i(e instanceof Error?e.message:String(e))}finally{c(null),f(null)}};if(t===null)return(0,Q.jsx)(`div`,{className:`mcp mcp-boot`,children:r===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`正在读取 MCP 配置…`,`Reading the MCP config…`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`side-panel-hint side-error`,children:[e(`读不到 MCP 配置:`,`Cannot read the MCP config: `),r]}),(0,Q.jsx)(`div`,{className:`mcp-boot-actions`,children:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:E,onClick:()=>void P(),children:E?e(`重试中…`,`Retrying…`):e(`重试`,`Retry`)})})]})});let I=t.servers??[],L=I.find(e=>bS(e)===l)??null,R=t.total??I.length,z=t.enabled??I.filter(e=>e.enabled).length;return(0,Q.jsxs)(`div`,{className:`mcp`,children:[(0,Q.jsxs)(`div`,{className:`mcp-shell`,style:{"--mcp-list-width":`${O}px`},children:[(0,Q.jsx)(RS,{servers:I,projectPath:t.projectPath??``,globalPath:t.globalPath??``,selected:l,pane:p.kind,busy:s!==null,onSelect:e=>{u(e),m({kind:`detail`})},onToggleScope:(e,t)=>void F(`set-scope-enabled`,void 0,{scope:e,enabled:t}),onPane:e=>m(p.kind===e?{kind:`detail`}:{kind:e})}),(0,Q.jsx)(`div`,{className:`mcp-list-resizer`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整服务器列表宽度`,`Resize the server list`),title:e(`左右拖动调整列表宽度(双击复位)`,`Drag to resize the list (double-click to reset)`),onPointerDown:j,onDoubleClick:M}),(0,Q.jsx)(`div`,{className:`mcp-detail${p.kind===`detail`?``:` mcp-detail-pane`}`,children:p.kind===`add`?(0,Q.jsx)(LS,{text:_,onText:v,scope:h,scopePath:h===`project`?t.projectPath??``:t.globalPath??``,onScope:g,busy:s!==null,onCancel:()=>m({kind:`detail`}),onSubmit:e=>void F(`add`,void 0,{text:e,scope:h})}):p.kind===`market`?(0,Q.jsx)(GS,{installed:I.map(e=>e.name),busy:s!==null,source:y,onSource:b,query:x,onQuery:S,onAdd:(e,t)=>void F(`add`,void 0,{scope:t,name:e.name,config:e.config,description:e.description===``?void 0:e.description})}):L===null?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`左边挑一个服务器看详情。`,`Pick a server on the left to see details.`)}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`mcp-detail-head`,children:[(0,Q.jsx)(`span`,{className:`mcp-badge`,children:e(vS[L.scope],yS[L.scope])}),(0,Q.jsx)(`span`,{className:`mcp-detail-name`,children:L.name}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null,onClick:()=>void F(`test`,L),title:e(`按配置真连一次:握手 + 列出工具,然后关掉`,`Actually connect once using the config: handshake + list tools, then disconnect`),children:s?.startsWith(`test:`)?e(`连接中…`,`Connecting…`):e(`测试连接`,`Test connection`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${d===bS(L)?` btn-danger`:``}`,disabled:s!==null,onClick:()=>d===bS(L)?void F(`remove`,L):f(bS(L)),onBlur:()=>f(e=>e===bS(L)?null:e),children:s?.startsWith(`remove:`)?e(`移除中…`,`Removing…`):d===bS(L)?e(`确认移除`,`Confirm remove`):e(`移除`,`Remove`)}),(0,Q.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":L.enabled,className:`mcp-switch${L.enabled?` mcp-switch-on`:``}`,disabled:s!==null,onClick:()=>void F(`set-enabled`,L,{enabled:!L.enabled}),children:L.enabled?e(`已启用`,`Enabled`):e(`已停用`,`Disabled`)})]}),(0,Q.jsx)(zS,{server:L,busy:s!==null,login:w?.name===L.name?w.state:void 0,onExposure:e=>void F(`set-exposure`,L,{exposure:e}),onLogin:()=>void F(`login`,L),onLoginCancel:()=>{F(`login-cancel`,L),T(null)},onRecheck:()=>{F(`login-status`,L).then(()=>F(`test`,L))}})]})})]}),(0,Q.jsxs)(`div`,{className:`mcp-bar`,children:[(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`已开启`,`Enabled`),` `,z,`/`,R,` `,e(`个服务器`,`servers`),t.autoEnableCodemode===!1?e(` · 代码模式不会自动打开`,` · code mode is not enabled automatically`):``]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:s!==null,onClick:()=>void P(),children:e(`刷新`,`Refresh`)})]}),r?(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:r}):null,a?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:a}):null,(t.errors??[]).length>0?(0,Q.jsx)(`div`,{className:`mcp-diagnostics`,children:(t.errors??[]).map((e,t)=>(0,Q.jsx)(`div`,{className:`side-panel-hint side-error`,children:e},`${t}-${e}`))}):null,(0,Q.jsxs)(`div`,{className:`side-panel-hint`,children:[e(`配置读的就是 pi 自己的`,`The config is pi's own`),` `,(0,Q.jsx)(`code`,{children:`mcp.json`}),e(`(`,` (`),e(`项目覆盖全局,只写 enabled / exposure 的项目条目是覆盖项`,`project entries override global ones; entries that only set enabled / exposure act as overrides`),e(`)。`,`). `),e(`启停与暴露方式写回同一个文件,`,`Enable flags and exposure are written back to the same file, `),(0,Q.jsx)(`strong`,{children:e(`对新会话生效`,`effective for new sessions`)}),e(`;「测试连接」只握手 + 列工具,不调用任何工具。`,`; “Test connection” only handshakes and lists tools — it calls no tools.`)]})]})}async function qS(e){let t=await e.text();try{return{view:JSON.parse(t)}}catch{let n=t.replace(/<[^>]*>/g,` `).replace(/\s+/g,` `).trim().slice(0,120);return{error:e.status===404?J(`服务端没有 /api/mcp 这个接口(大概率是跑着旧版本):重启 Pi Web 后再打开这个面板`,`The server has no /api/mcp endpoint (probably an older build) — restart Pi Web and reopen this panel`):`HTTP ${e.status}${n===``?``:`${J(`:`,`: `)}${n}`}`}}}var JS=e=>{if(!e)return`—`;let t=Date.now()-e;return t<6e4?J(`刚刚`,`just now`):t<36e5?J(`${Math.floor(t/6e4)} 分钟前`,`${Math.floor(t/6e4)} min ago`):t<864e5?J(`${Math.floor(t/36e5)} 小时前`,`${Math.floor(t/36e5)} h ago`):J(`${Math.floor(t/864e5)} 天前`,`${Math.floor(t/864e5)} d ago`)},YS=e=>e.toLowerCase().startsWith(`mailto:`)?e.slice(7):e,XS=e=>{switch(e){case`push.subject.scheme`:return J(`只接受邮箱或 https 地址(推送网关不认 http / 其它协议)`,`Only an email or an https URL is accepted (the push gateways reject http and other schemes)`);case`push.subject.host`:return J(`域名要带真实后缀:localhost / 内网名 Apple 会直接拒(403 BadJwtToken)`,`The domain needs a real suffix: Apple rejects localhost and LAN names outright (403 BadJwtToken)`);case`push.subject.empty`:return J(`不能为空`,`Must not be empty`);default:return J(`格式不合法`,`Invalid format`)}};function ZS(){let e=Y(),{name:t,custom:n}=Zv(),[r,i]=(0,C.useState)([]),[a,o]=(0,C.useState)(new Set),[s,c]=(0,C.useState)(null),[l,u]=(0,C.useState)(!1),[d,f]=(0,C.useState)(`default`),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(!1),x=async()=>{let e=await yv();g(e),v(e?YS(e.subject):``)},S=async()=>{try{f(await wv())}catch{f(`unsupported`)}},w=async()=>{m(!0),c(null);try{let t=await Tv(n);c(t.ok?t.rekeyed?e(`这台设备已按服务端新密钥重建订阅`,`This device re-subscribed with the server's new key`):e(`这台设备已注册推送`,`Push registered for this device`):t.message),t.ok&&await k()}catch(t){c(e(`注册失败:${t instanceof Error?t.message:String(t)}(需要 https 或 localhost,且允许通知)`,`Registration failed: ${t instanceof Error?t.message:String(t)} (needs https or localhost, and notifications allowed)`))}finally{m(!1),await S()}},T=async()=>{m(!0),c(null);try{let t=await Dv();c(t.ok?e(`已取消这台设备的订阅`,`Subscription cancelled for this device`):t.message),await k()}catch(t){c(e(`取消失败:${t instanceof Error?t.message:String(t)}`,`Cancel failed: ${t instanceof Error?t.message:String(t)}`))}finally{m(!1),await S()}},E=async()=>{try{if(!Sv()){c(e(`这个浏览器不支持通知(需要 https 或 localhost)`,`This browser does not support notifications (needs https or localhost)`));return}if((Notification.permission===`granted`?`granted`:await Notification.requestPermission())!==`granted`){c(e(`通知权限没给,弹不出来`,`Notification permission was not granted, so nothing can show`));return}let n=await navigator.serviceWorker.getRegistration(`/sw.js`),r={body:e(`这是本地通知测试,不经过服务端。`,`This is a local notification test; it does not go through the server.`),icon:`/icons/icon-192.png`,tag:`pop-agent-local`};n?await n.showNotification(t,r):new Notification(t,r),c(e(`已发出本地通知(没看到的话检查系统通知设置)`,`Local notification sent (check the system notification settings if you did not see it)`))}catch(t){c(e(`本地通知失败:${t instanceof Error?t.message:String(t)}`,`Local notification failed: ${t instanceof Error?t.message:String(t)}`))}},D=async()=>{b(!0),c(null);try{let t=await bv(_);if(!t.ok){let n=XS(t.code);c(e(`保存失败:${n}`,`Save failed: ${n}`));return}g(t.config),v(YS(t.config.subject)),c(e(`联系方式已保存(不影响已注册的设备)`,`Contact saved (registered devices are unaffected)`))}finally{b(!1)}},O=async()=>{if(window.confirm(e(`换一对新密钥?所有已订阅设备都会失效(旧订阅会被清空),需要每台设备重新点「注册推送」。这台设备会自动重订。`,`Replace the key pair? Every subscribed device stops working (old subscriptions are cleared) and each one has to register again. This device re-registers automatically.`))){b(!0),c(null);try{let t=d===`subscribed`,r=await xv();if(!r.ok){c(r.code===`push.keys_locked`?e(`密钥由环境变量 VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY 指定,要换得改环境变量`,`The keys come from VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY; change them there`):e(`换密钥失败:${r.code}`,`Replacing the keys failed: ${r.code}`));return}g(r.config),v(YS(r.config.subject)),await k();let i=``;if(t){let t=await Tv(n);i=t.ok?e(`本机已用新密钥重新注册`,`This device re-registered with the new key`):e(`本机重订失败:${t.message}`,`Re-registering this device failed: ${t.message}`),await S(),await k()}c([e(`已换新密钥(清空 ${r.cleared} 台旧订阅)`,`Keys replaced (${r.cleared} old subscriptions cleared)`),i].filter(e=>e!==``).join(e(`;`,`; `)))}finally{b(!1)}}},k=async()=>{let e=await(await fetch(`/api/push/subscriptions`)).json();i(e.devices??[]),o(t=>new Set([...t].filter(t=>(e.devices??[]).some(e=>e.endpoint===t))))};(0,C.useEffect)(()=>{k(),S(),x()},[]);let A=async(e,t)=>{u(!0);try{await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},...t}),await k()}finally{u(!1)}},j=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),M=Sv(),N=typeof Notification>`u`?`unsupported`:Notification.permission,P=N===`granted`?e(`已允许`,`Granted`):N===`denied`?e(`已拒绝`,`Denied`):N===`unsupported`?`—`:e(`未授权`,`Not granted`);return(0,Q.jsxs)(`div`,{className:`push-panel`,children:[(0,Q.jsxs)(`section`,{className:`push-env`,children:[(0,Q.jsx)(`div`,{className:`push-env-title`,children:e(`服务端密钥`,`Server key`)}),(0,Q.jsxs)(`div`,{className:`push-config-row`,children:[(0,Q.jsx)(`span`,{className:`push-config-label`,children:e(`公钥`,`Public key`)}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,title:h?.publicKey??``,children:[(0,Q.jsx)(`code`,{className:`mono`,children:h?`${h.fingerprint}…`:`…`}),(0,Q.jsx)(`em`,{className:h?.keySource===`env`?`push-tag-off`:`push-tag-ok`,children:h?.keySource===`env`?e(`环境变量`,`env`):e(`数据目录`,`data dir`)})]}),h?.keyCreatedAt?(0,Q.jsxs)(`span`,{className:`push-config-note`,children:[e(`生成于`,`created`),` `,JS(h.keyCreatedAt)]}):null,(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,disabled:y||h?.locked.keys===!0,title:h?.locked.keys?e(`密钥由环境变量指定,要换得改环境变量`,`Keys come from env vars; change them there`):void 0,onClick:()=>void O(),children:e(`重新生成密钥`,`Regenerate keys`)})]}),(0,Q.jsxs)(`div`,{className:`push-config-row`,children:[(0,Q.jsx)(`span`,{className:`push-config-label`,children:e(`联系方式`,`Contact`)}),(0,Q.jsx)(`input`,{className:`push-config-input`,type:`text`,inputMode:`email`,value:_,placeholder:`you@example.com`,disabled:y||h?.locked.subject===!0,onChange:e=>v(e.target.value),onKeyDown:e=>{e.key===`Enter`&&D()}}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:y||h===null||_===YS(h.subject),onClick:()=>void D(),children:e(`保存`,`Save`)})]}),h&&!h.subjectValid?(0,Q.jsxs)(`div`,{className:`push-config-warn`,children:[`⚠ `,XS(h.subjectProblem)]}):null]}),(0,Q.jsxs)(`section`,{className:`push-env`,children:[(0,Q.jsx)(`div`,{className:`push-env-title`,children:e(`本机推送`,`Push on this device`)}),(0,Q.jsxs)(`div`,{className:`push-env-chips`,children:[(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`浏览器支持`,`Browser support`),(0,Q.jsx)(`em`,{className:M?`push-tag-ok`:`push-tag-off`,children:M?e(`支持`,`Supported`):e(`不支持`,`Unsupported`)})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`通知权限`,`Notification permission`),(0,Q.jsx)(`em`,{className:N===`granted`?`push-tag-ok`:`push-tag-off`,children:P})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[`Service Worker`,(0,Q.jsx)(`em`,{className:d===`unsupported`?`push-tag-off`:`push-tag-ok`,children:d===`unsupported`?e(`不可用`,`Unavailable`):e(`已就绪`,`Ready`)})]}),(0,Q.jsxs)(`span`,{className:`push-env-chip`,children:[e(`当前订阅`,`Subscription`),(0,Q.jsx)(`em`,{className:d===`subscribed`?`push-tag-ok`:`push-tag-off`,children:d===`subscribed`?e(`已订阅`,`Subscribed`):e(`未订阅`,`Not subscribed`)})]})]}),(0,Q.jsxs)(`div`,{className:`push-env-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary-tiny`,disabled:p,onClick:()=>void w(),children:d===`subscribed`?e(`重新注册`,`Register again`):e(`注册推送`,`Register for push`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p,onClick:()=>void E(),children:e(`本地通知测试`,`Local notification test`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p||d!==`subscribed`,onClick:()=>void T(),children:e(`取消订阅`,`Unsubscribe`)})]}),(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`推送需要 https 或 localhost(手机上请用域名);注册后「目标设备」里会出现这台设备。`,`Push needs https or localhost (use a domain name on phones); once registered, this device appears under Targets.`)})]}),(0,Q.jsxs)(`section`,{className:`push-devices`,children:[(0,Q.jsxs)(`div`,{className:`push-head`,children:[(0,Q.jsx)(`strong`,{children:e(`推送消息`,`Push a message`)}),(0,Q.jsxs)(`span`,{className:`side-panel-count`,children:[e(`目标设备`,`Targets`),` `,r.length,` `,e(`台`,`devices`)]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(new Set(r.map(e=>e.endpoint))),children:e(`全选`,`Select all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(new Set),children:e(`全不选`,`Select none`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void k(),children:[`⟳ `,e(`刷新`,`Refresh`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-danger`,onClick:()=>{window.confirm(e(`清空全部订阅设备?之后所有设备都收不到推送。`,`Clear every subscribed device? No device will receive pushes afterwards.`))&&A(`/api/push/clear`).then(()=>c(e(`已清空全部设备`,`All devices cleared`)))},children:e(`清空全部设备`,`Clear all devices`)})]}),r.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:e(`还没有订阅设备。点上面的「注册推送」把当前这台浏览器订进来(需要 https 或 localhost)。`,`No subscribed devices yet — use “Register for push” above to subscribe this browser (needs https or localhost).`)}):null,(0,Q.jsx)(`div`,{className:`push-list`,children:r.map(t=>(0,Q.jsxs)(`div`,{className:`push-row${a.has(t.endpoint)?` push-row-on`:``}`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.has(t.endpoint),onChange:()=>j(t.endpoint)}),(0,Q.jsxs)(`div`,{className:`push-row-main`,children:[(0,Q.jsx)(`div`,{className:`push-row-name`,children:t.name}),(0,Q.jsx)(`div`,{className:`push-row-endpoint mono`,title:t.endpoint,children:t.endpoint}),(0,Q.jsxs)(`div`,{className:`push-row-meta`,children:[e(`注册`,`Registered`),` `,JS(t.createdAt),t.lastSentAt?` · ${e(`上次推送`,`last push`)} ${JS(t.lastSentAt)} (${t.lastStatus??`—`})`:``]})]}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>{let n=window.prompt(e(`设备别名`,`Device alias`),t.name);n!==null&&n.trim()!==``&&A(`/api/push/rename`,{body:JSON.stringify({endpoint:t.endpoint,name:n.trim()})})},children:e(`重命名`,`Rename`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,disabled:l,onClick:()=>void A(`/api/push/test`,{body:JSON.stringify({endpoints:[t.endpoint]})}).then(()=>c(e(`已单独推送给「${t.name}」`,`Pushed to “${t.name}” only`))),children:e(`仅推它`,`Push to this one`)}),(0,Q.jsx)(`button`,{type:`button`,className:`msg-action`,onClick:()=>void A(`/api/push/delete`,{body:JSON.stringify({endpoint:t.endpoint})}),children:e(`删除`,`Delete`)})]},t.endpoint))}),(0,Q.jsxs)(`div`,{className:`push-foot`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:l,onClick:()=>void A(`/api/push/test`,{body:JSON.stringify(a.size>0?{endpoints:[...a]}:{})}).then(()=>c(a.size>0?e(`已推送给选中的 ${a.size} 台`,`Pushed to ${a.size} selected devices`):e(`已推送给全部设备`,`Pushed to all devices`))),children:[e(`推送测试消息`,`Send a test push`),a.size>0?` (${a.size} ${e(`选中`,`selected`)})`:` (${e(`全部设备`,`all devices`)})`]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`})]})]}),s?(0,Q.jsx)(`div`,{className:`side-ok`,children:s}):null]})}var QS=[`start`,`steer`,`done`,`error`,`approval`],$S=[{db:0,zh:`关闭 · 0(不挡人,开自动增益)`,en:`Off · 0 (no gate, auto gain on)`},{db:6,zh:`宽松 · 6 dB(小声也能进,偶尔收进旁人)`,en:`Loose · 6 dB (quiet voice gets in)`},{db:12,zh:`中等 · 12 dB(默认档,挡住一米外的聊天)`,en:`Medium · 12 dB (default)`},{db:18,zh:`偏严 · 18 dB(基本要正对着说)`,en:`Strict · 18 dB (near-field only)`},{db:24,zh:`很严 · 24 dB(几乎只认贴嘴)`,en:`Very strict · 24 dB`}];function eC(){let e=Y(),[t,n]=uf(ef,!0),[r,i]=lf(),[a,o]=(0,C.useState)(()=>U()),[s,c]=(0,C.useState)(()=>Ke()),l=bi(),u=Ro(e=>e.snapshot?.engineCapabilities?.steer!==!1),[d,f]=(0,C.useState)(null),[p]=(0,C.useState)(null),m=(0,C.useCallback)((e=!1)=>{fetch(`/api/asr/status${e?`?start=1`:``}`).then(async e=>{if(!e.ok)return;let t=await e.json();f(t),t.state===`ready`&&mi()}).catch(()=>void 0)},[]),h=d?.state===`starting`||d?.state===`authorizing`;(0,C.useEffect)(()=>{if(!h)return;let e=window.setInterval(()=>m(),1200);return()=>window.clearInterval(e)},[h,m]);let g=()=>{f(e=>({...e??{},state:`starting`,message:void 0})),m(!0)},_=()=>{let e=d?.install?.downloadUrl;e&&window.open(e,`_blank`,`noopener,noreferrer`)};(0,C.useEffect)(()=>m(),[]);let[v,y]=(0,C.useState)(()=>Qe()),[b,x]=(0,C.useState)([]),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(null),[D,O]=(0,C.useState)(null),[k,A]=(0,C.useState)(!1),[j,M]=(0,C.useState)(!1),N=(0,C.useRef)(!1);(0,C.useEffect)(()=>()=>{N.current&&St()},[]);let[P,F]=(0,C.useState)(null),I=Ze(s),L=(s.provider??`browser`)!==`browser`,R=s.provider===`kokoro`||s.provider===`qwen3`?s.provider:`edge`,z=s.provider===`kokoro`?s.kokoroVoice:s.provider===`qwen3`?s.qwen3Voice:s.edgeVoice,B=v.some(e=>e.voiceURI===s.voiceURI)?s.voiceURI:``,H=s.voiceURI!==``&&B===``?Qe({includeOnline:!0}).find(e=>e.voiceURI===s.voiceURI):void 0;(0,C.useEffect)(()=>(y(Qe({onlyOnline:s.allowOnline})),$e(()=>y(Qe({onlyOnline:s.allowOnline})))),[s.allowOnline]),(0,C.useEffect)(()=>{if(!L)return;let t=new AbortController,n=!1,r=window.setTimeout(()=>t.abort(),15e3);return w(!0),E(null),Re(t.signal,R).then(e=>{n||x(e)}).catch(()=>{n||E(e(`音色列表加载失败,可以使用默认音色试听`,`Unable to load voices; you can still preview the default voice`))}).finally(()=>{window.clearTimeout(r),n||w(!1)}),()=>{n=!0,window.clearTimeout(r),t.abort()}},[L,R,e]);let ee=e=>{let t={...a,...e};o(t),W(t)},G=e=>{(e.provider!==void 0||e.voiceURI!==void 0||e.edgeVoice!==void 0||e.kokoroVoice!==void 0||e.qwen3Voice!==void 0)&&(St(),O(null),F(null),A(!1));let t={...s,...e};c(t),Je(t)},K=e=>G({allowOnline:e}),te=!L&&s.allowOnline&&v.length===0,ne=e=>{if(e===`steer`){Na(`steer`,{force:!0,volume:Math.max(.05,a.volume/100)});return}let t=Ke().enabled;Ia({kind:e,voiceEnabled:t,readReplies:!1,hasReply:!1})===`clip`&&e!==`start`?Na(e,{force:!0,volume:Math.max(.05,a.volume/100)}):q(e,{...a,enabled:!0,[e]:!0,volume:a.volume})},re=t=>{Na(`done`,{force:!0,language:t,volume:Math.max(.05,a.volume/100)}),O(null),F(t===`en`?e(`已播放英文片段「Task complete.」`,`Played the English clip "Task complete."`):t===`zh`?e(`已播放中文片段「任务已完成」`,`Played the Chinese clip "任务已完成"`):e(`已播放本地语音片段(跟当前界面语言)`,`Played the bundled clip (current UI language)`)),window.setTimeout(()=>F(null),2400)},ie=()=>{St(),O(null),A(!1),F(e(`正在准备语音…`,`Preparing speech…`)),M(!0),N.current=!0;let t=()=>{N.current=!1,M(!1)};yt(We(),{...s,enabled:!0},{onStart:()=>{N.current=!0,M(!0),O(null),F(e(`正在念:语音播报正常`,`Speaking: speech is working`))},onCancel:()=>{t(),F(null)},onEnd:()=>{t(),F(null)},onIssue:(e,n)=>{t(),F(null),O(e),A(n.wakeable)}})},ae=()=>{O(null),A(!1),F(e(`正在唤醒系统语音服务…`,`Waking the system speech service…`)),ht(()=>ie(),400)},oe=async()=>{O(null),F(e(`正在诊断…(约 2.5 秒)`,`Diagnosing… (about 2.5s)`));let t=await xt();t.available?t.started?F(e(`诊断:合成器正常(${t.ms}ms 内开始;音色 ${t.voices} 个,其中在线 ${t.online} 个)。若还是听不到,问题在音量 / 输出设备,不在浏览器。`,`Diagnosis: the synthesizer responds (started within ${t.ms}ms; ${t.voices} voices, ${t.online} online). If you still hear nothing, the problem is volume / output device.`)):t.error?(F(null),A(!0),O(e(`诊断:系统报错「${t.error}」— ${nt(t.error)}`,`Diagnosis: error "${t.error}" — ${nt(t.error)}`))):(F(null),A(!0),O(e(`诊断:合成器 ${t.ms}ms 内既没开始也没报错(音色 ${t.voices} 个,在线 ${t.online} 个)→ 系统的语音服务卡死了。重启浏览器;macOS 还可执行 killall speechsynthesisd`,`Diagnosis: no start and no error within ${t.ms}ms (${t.voices} voices, ${t.online} online) → the OS speech service is stuck. Restart the browser; on macOS try killall speechsynthesisd`))):(F(null),O(e(`诊断:这个浏览器没有语音合成(speechSynthesis)能力`,`Diagnosis: this browser has no speech synthesis`)))};return(0,Q.jsxs)(`div`,{className:`voice-panel`,children:[(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🔊`}),` `,e(`启用声音`,`Enable sounds`)]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:a.enabled,onChange:()=>ee({enabled:!a.enabled})})]}),QS.map(t=>(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(V[t].title,V[t].titleEn),`(`,e(V[t].hint,V[t].hintEn),`)`]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny voice-try`,onClick:e=>{e.preventDefault(),ne(t)},children:e(`试听`,`Preview`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:a[t],onChange:()=>ee({[t]:!a[t]})})]},t))]}),(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🔊`}),` `,e(`启用语音播报(完成 / 出错播提示音)`,`Enable speech (cue on finish / error)`)]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.enabled,onChange:()=>G({enabled:!s.enabled})})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读回复(边输出边按句念)`,`Read replies aloud (as it streams)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.readReplies,onChange:()=>G({readReplies:!s.readReplies})})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:L?R===`edge`?e(`语音引擎(在线,文字发到微软)`,`Speech engine (online, text goes to Microsoft)`):e(`语音引擎(本机 MLX,不联网)`,`Speech engine (local MLX, offline)`):e(`语音引擎`,`Speech engine`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:s.provider??`browser`,onChange:e=>G({provider:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`browser`,children:e(`浏览器语音`,`Browser speech`)}),(0,Q.jsx)(`option`,{value:`edge`,children:e(`微软 Edge TTS(在线)`,`Microsoft Edge TTS (online)`)}),(0,Q.jsx)(`option`,{value:`kokoro`,children:e(`Kokoro(本地)`,`Kokoro (local)`)}),(0,Q.jsx)(`option`,{value:`qwen3`,children:e(`Qwen3-TTS(本地)`,`Qwen3-TTS (local)`)})]})]}),L?(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语音`,`Voice`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:z??``,onChange:e=>G(R===`kokoro`?{kokoroVoice:e.target.value}:R===`qwen3`?{qwen3Voice:e.target.value}:{edgeVoice:e.target.value}),disabled:S,children:[b.some(e=>e.id===z)?null:(0,Q.jsx)(`option`,{value:z??``,children:S?e(`正在加载音色…`,`Loading voices…`):z??e(`默认音色`,`Default voice`)}),b.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.name,e.lang?`(${e.lang})`:``]},e.id))]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-select voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语音`,`Voice`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:B,onChange:e=>G({voiceURI:e.target.value}),title:e(`浏览器里可用的音色(取决于系统装了什么语音)`,`Voices available in the browser (depends on what the OS has installed)`),children:[(0,Q.jsx)(`option`,{value:``,children:e(`自动(跟随系统语言)`,`Auto (match the system language)`)}),v.map(t=>(0,Q.jsxs)(`option`,{value:t.voiceURI,children:[t.name,`(`,t.lang,t.localService?``:e(`,在线`,`, online`),`)`]},t.voiceURI)),H?(0,Q.jsxs)(`option`,{value:H.voiceURI,children:[H.name,`(`,H.lang,H.localService?e(`,本机;已保留`,`, local; kept`):e(`,在线;已保留`,`, online; kept`),`)`]}):null]})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`只列在线音色(本机音色念不出来)`,`Online voices only (local ones never start)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.allowOnline,onChange:()=>K(!s.allowOnline)})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读小宠物(一直待在右下角,可拖动)`,`Reading pet (always in the bottom-right, draggable)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:t,onChange:e=>n(e.target.checked)})]}),t?(0,Q.jsxs)(`div`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`宠物形象`,`Pet`)}),(0,Q.jsx)(`div`,{className:`speech-pet-picker`,children:nf.map(t=>(0,Q.jsx)(`button`,{type:`button`,className:`speech-pet-pick${r===t.emoji?` is-on`:``}`,onClick:()=>i(t.emoji),"aria-pressed":r===t.emoji,title:e(t.zh,t.en),children:t.emoji},t.emoji))})]}):null,(0,Q.jsxs)(`div`,{className:`voice-row-pair`,children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`语速`,`Rate`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.5,max:2,step:.1,value:s.rate,onChange:e=>G({rate:Number(e.target.value)})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[s.rate.toFixed(1),`×`]})]})]}),(0,Q.jsxs)(`div`,{className:`voice-row voice-row-stacked`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`提示音音量`,`Cue volume`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line`,children:[(0,Q.jsx)(`input`,{type:`range`,min:0,max:100,step:5,value:a.volume,onChange:e=>ee({volume:Number(e.target.value)}),onMouseUp:()=>ne(`done`),title:e(`调完松手会试听一声`,`Plays a sample when you let go`)}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[a.volume,`%`]})]})]})]}),L&&T?(0,Q.jsx)(`div`,{className:`voice-issue`,role:`status`,children:T}):null,te?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:e(`没找到在线音色:Chrome 的 Google 音色要联网才会加载(断网时只能选「自动」或取消勾选看本机音色)`,`No online voice found: Chrome loads Google voices from the network`)}):null,(0,Q.jsxs)(`div`,{className:`voice-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>re(),title:e(`播一段本地语音片段(跟当前界面语言)`,`Plays a bundled clip (current UI language)`),children:e(`试听`,`Preview`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>re(`en`),title:e(`播英文片段(不用先切界面语言)`,`Plays the English clip without switching the UI language`),children:e(`试听英文`,`Preview (EN)`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:ie,disabled:!I||j,title:e(`用所选语音引擎试听一句话`,`Previews a sentence using the selected speech engine`),children:e(`测朗读`,`Test reading`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:nn,title:e(`停掉正在念的内容;这一轮剩下的文字也不再自动念`,`Stops the current sentence; the rest of this turn stays silent`),children:e(`停止`,`Stop`)}),L?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>void oe(),title:e(`绕过本项目所有设置,直接问浏览器能不能念`,`Bypasses all settings and asks the browser directly`),children:e(`诊断`,`Diagnose`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{St(),G({...He,voiceURI:s.voiceURI})},children:e(`恢复默认`,`Restore defaults`)})]}),P?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:P}):null,D?(0,Q.jsxs)(`div`,{className:`voice-issue`,role:`status`,children:[(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:D}),k&&I&&!L?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:ae,disabled:j,title:e(`先念一句静音的唤醒句把系统语音服务踢醒,再重放一次试听(省得你去终端 killall)`,`Plays a silent wake-up utterance, then retries the sample (no need to killall anything)`),children:e(`唤醒并重试`,`Wake & retry`)}):null]}):null]}),(0,Q.jsxs)(`section`,{className:`voice-section`,children:[(0,Q.jsx)(`div`,{className:`voice-row`,children:(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`🎤`}),` `,e(`语音输入(点麦克风浮条说话)`,`Voice input (tap the mic bubble)`)]})}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`说完自动发送(停 ${(l.silenceMs/1e3).toFixed(1)} 秒就发)`,`Send when I stop talking (after ${(l.silenceMs/1e3).toFixed(1)}s)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.autoSend,onChange:()=>yi({...l,autoSend:!l.autoSend})})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`等多久发送(停顿多长算说完)`,`Silence before sending (how long counts)`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line voice-slider-compact`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.6,max:10,step:.2,value:l.silenceMs/1e3,onChange:e=>yi({...l,silenceMs:Number(e.target.value)*1e3})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[(l.silenceMs/1e3).toFixed(1),`s`]})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`朗读恢复延迟(安静多久后接着念)`,`Resume reading after (silence needed)`)}),(0,Q.jsxs)(`span`,{className:`voice-slider-line voice-slider-compact`,children:[(0,Q.jsx)(`input`,{type:`range`,min:.6,max:10,step:.2,value:l.readingResumeMs/1e3,onChange:e=>yi({...l,readingResumeMs:Number(e.target.value)*1e3})}),(0,Q.jsxs)(`span`,{className:`voice-value mono`,children:[(l.readingResumeMs/1e3).toFixed(1),`s`]})]})]}),(0,Q.jsxs)(`label`,{className:`voice-row`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`连续听写(发完继续听,麦克风常亮)`,`Keep listening (mic stays open)`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.continuous,onChange:()=>yi({...l,continuous:!l.continuous})})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`近讲灵敏度(越大越只认近处;0 = 关闭)`,`Near-field only (higher = nearer only; 0 = off)`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:String(l.nearTalkDb),onChange:e=>yi({...l,nearTalkDb:Number(e.target.value)}),children:[$S.some(e=>e.db===l.nearTalkDb)?null:(0,Q.jsx)(`option`,{value:String(l.nearTalkDb),children:e(`当前 · ${l.nearTalkDb} dB`,`Current · ${l.nearTalkDb} dB`)}),$S.map(t=>(0,Q.jsx)(`option`,{value:String(t.db),children:e(t.zh,t.en)},t.db))]})]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsx)(`span`,{className:`voice-row-label`,children:e(`识别引擎(自动 = 先本地,带标点)`,`Recognition engine (auto = local first)`)}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:l.engine,onChange:e=>yi({...l,engine:e.target.value===`browser`||e.target.value===`local`?e.target.value:`auto`}),children:[(0,Q.jsx)(`option`,{value:`auto`,children:e(`自动(优先本地)`,`Auto (local first)`)}),(0,Q.jsx)(`option`,{value:`local`,children:e(`本地(macOS 离线)`,`Local (macOS, offline)`)}),(0,Q.jsx)(`option`,{value:`browser`,children:e(`Chrome 原生(需连 Google)`,`Chrome (needs Google)`)})]})]}),l.engine===`browser`?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`voice-row voice-row-status`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(`本地识别`,`Local recognition`),(0,Q.jsx)(`span`,{className:`voice-row-hint`,children:d===null||d.state===`idle`?e(`还没启动过`,`Not started yet`):d.state===`ready`?e(`就绪(${d.locale??`zh-CN`},离线)`,`Ready (${d.locale??`zh-CN`}, offline)`):d.state===`authorizing`?e(`等待系统授权:屏幕上的提示点「允许」即可`,`Waiting for permission — click Allow in the system prompt`):d.state===`starting`?e(`正在启动…`,`Starting…`):d.state===`missing`?e(`还没装:本地识别在 Agent Computer 里(和电脑控制同一个程序)`,`Not installed — local recognition lives in Agent Computer (same helper as computer control)`):d.message??d.state})]}),d?.state===`missing`?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d.install?.canAutoInstall===!1,onClick:_,title:e(`下载并装好本地识别(不用装 Xcode)`,`Download and install it — no Xcode needed`),children:e(`下载 Agent Computer.app`,`Download Agent Computer.app`)}):d?.state===`ready`?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:h,"aria-busy":h,onClick:g,title:h?e(`正在启动,请稍等…`,`Starting — hang on…`):e(`启动本地识别(首次会弹一次系统授权)`,`Start the local engine (one system permission prompt the first time)`),children:h?e(`正在启动…`,`Starting…`):e(`启动 / 重试`,`Start / retry`)})]}),d?.state===`missing`&&d.install?.canAutoInstall!==!1?(0,Q.jsxs)(`div`,{className:`voice-install`,children:[(0,Q.jsxs)(`ol`,{className:`voice-install-steps`,children:[(0,Q.jsx)(`li`,{children:e(`点「下载 Agent Computer.app」,解压后右键打开(首次打开若被系统拦,右键 →「打开」)`,`Click “Download Agent Computer.app”, unzip, then right-click → Open (macOS blocks the first launch otherwise)`)}),(0,Q.jsx)(`li`,{children:e(`打开后会要麦克风与语音识别授权,允许之后这里变成「就绪」`,`It asks for microphone and speech recognition permission — after Allow, this row turns into “Ready”`)})]}),(0,Q.jsxs)(`div`,{className:`voice-install-actions`,children:[d.install?(0,Q.jsx)(`a`,{className:`btn btn-tiny`,href:d.install.downloadUrl,target:`_blank`,rel:`noreferrer`,title:d.install.appPath,children:e(`手动下载 zip`,`Download the zip`)}):null,(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>m(),children:e(`装好了,重新检测`,`Installed — check again`)})]}),p?(0,Q.jsx)(`div`,{className:`voice-issue`,role:`status`,children:(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:p})}):null]}):null,d?.state===`missing`&&d.install?.canAutoInstall===!1?(0,Q.jsx)(`div`,{className:`voice-issue voice-status`,role:`status`,children:(0,Q.jsx)(`span`,{className:`voice-issue-text`,children:e(`本地识别只有 macOS 版(跑服务端的那台机器);这台机器请把上面的「识别引擎」改成 Chrome 原生`,`Local recognition is macOS-only (on the machine running the server) — switch the engine above to Chrome`)})}):null]}),(0,Q.jsxs)(`label`,{className:`voice-row voice-row-select`,children:[(0,Q.jsxs)(`span`,{className:`voice-row-label`,children:[e(`说完时正在跑`,`While a turn is running`),(0,Q.jsx)(`span`,{className:`voice-row-hint`,children:u?e(`排队 = 等这一轮结束再发;插队 = 打断它,按新指令继续`,`Queue = sends after this turn; Steer = interrupts it and continues with the new instruction`):e(`当前引擎只能排队(插队需要 Pi 引擎)`,`This engine can only queue — steering requires the Pi engine`)})]}),(0,Q.jsxs)(`select`,{className:`voice-select`,value:l.submitMode,disabled:!u,onChange:e=>yi({...l,submitMode:e.target.value===`steer`?`steer`:`queue`}),children:[(0,Q.jsx)(`option`,{value:`queue`,children:e(`排队`,`Queue`)}),(0,Q.jsx)(`option`,{value:`steer`,children:e(`插队`,`Steer`)})]})]})]})]})}var tC=[`read`,`bash`,`edit`,`write`,`grep`,`find`,`ls`];function nC({profile:e,onClose:t}){let n=Y(),[r,i]=(0,C.useState)(e),a=Ro(e=>e.snapshot),o=(0,C.useMemo)(()=>Gf(a?.models??[],a?.enabledModels??[]),[a?.models,a?.enabledModels]),s=e=>i(t=>({...t,...e})),c=e=>s({tools:r.tools.includes(e)?r.tools.filter(t=>t!==e):[...r.tools,e]});return(0,Q.jsxs)(`div`,{className:`agents-form`,children:[(0,Q.jsxs)(`div`,{className:`agents-form-row`,children:[(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`子代理 ID`,`Subagent ID`)}),(0,Q.jsx)(`input`,{value:r.id,disabled:!!r.builtin,onChange:e=>s({id:e.target.value}),placeholder:`review`})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`显示名称`,`Display name`)}),(0,Q.jsx)(`input`,{value:r.label,onChange:e=>s({label:e.target.value}),placeholder:`Review`})]})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`描述(模型靠它决定什么时候用谁)`,`Description (the model uses it to decide when to use which)`)}),(0,Q.jsx)(`input`,{value:r.description,onChange:e=>s({description:e.target.value}),placeholder:n(`代码 / 方案 / PR 审查:有证据的发现与合并结论`,`Code / design / PR review: findings with evidence and a merge verdict`)})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`系统指令`,`System instructions`)}),(0,Q.jsx)(`textarea`,{value:r.systemPrompt,onChange:e=>s({systemPrompt:e.target.value}),rows:8,placeholder:`Explore the codebase to answer the delegated question. Do not modify files…`})]}),(0,Q.jsxs)(`div`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`工具`,`Tools`)}),(0,Q.jsx)(`div`,{className:`agents-tools`,children:tC.map(e=>(0,Q.jsxs)(`label`,{className:`agents-tool`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.tools.includes(e),onChange:()=>c(e)}),e]},e))})]}),(0,Q.jsxs)(`div`,{className:`agents-form-row`,children:[(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`模型(留空 = 跟随默认)`,`Model (empty = follow the default)`)}),(0,Q.jsxs)(`select`,{value:r.model??``,onChange:e=>s({model:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:n(`跟随默认模型`,`Follow the default model`)}),o.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`agents-field`,children:[(0,Q.jsx)(`span`,{children:n(`思考级别`,`Thinking level`)}),(0,Q.jsxs)(`select`,{value:r.thinking??``,onChange:e=>s({thinking:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:n(`跟随默认`,`Follow the default`)}),[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`].map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`agents-field agents-field-narrow`,children:[(0,Q.jsx)(`span`,{children:n(`最大轮次`,`Max turns`)}),(0,Q.jsx)(`input`,{type:`number`,min:1,max:200,value:r.maxTurns??``,onChange:e=>s({maxTurns:Number(e.target.value)||void 0})})]})]}),(0,Q.jsxs)(`div`,{className:`agents-form-actions`,children:[(0,Q.jsx)(`span`,{className:`agents-hint`,children:r.builtin?n(`内置模板:保存会生成一个同名用户文件(可再改回来)`,`Built-in template: saving creates a user file with the same name (you can revert later)`):n(`保存后对新建的子代理生效`,`Applies to subagents created after saving`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:t,children:n(`取消`,`Cancel`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny btn-primary`,disabled:r.id.trim()===``||r.systemPrompt.trim()===``,onClick:()=>{El({...r,id:r.id.trim(),label:r.label.trim()||r.id.trim()}),t()},children:n(`保存`,`Save`)})]})]})}var rC=`pop-agent:agents-list-width`,iC=168,aC=420,oC=232;function sC(e){return Math.min(aC,Math.max(iC,Math.round(e)))}function cC(){let e=Y(),t=Ro(e=>e.snapshot),[n,r]=(0,C.useState)(null),[i,a]=(0,C.useState)(()=>{let e=Number(localStorage.getItem(rC));return Number.isFinite(e)&&e>0?sC(e):oC}),o=(0,C.useRef)(!1);(0,C.useEffect)(()=>{localStorage.setItem(rC,String(i))},[i]);let s=e=>{e.preventDefault(),o.current=!0;let t=e.clientX,n=i,r=e=>{o.current&&a(sC(n+(e.clientX-t)))},s=()=>{o.current=!1,document.removeEventListener(`pointermove`,r),document.removeEventListener(`pointerup`,s)};document.addEventListener(`pointermove`,r),document.addEventListener(`pointerup`,s)},c=t?.subagentProfiles??[],l=t?.subagentSettings??{enabled:!0,concurrency:4},u=t?.engineCapabilities.subagents===!0,d=t?.engineCapabilities.subagentToolWhitelist;return(0,Q.jsxs)(`div`,{className:`agents-panel`,style:{"--agents-list-w":`${i}px`},children:[(0,Q.jsxs)(`header`,{className:`agents-head`,children:[(0,Q.jsxs)(`div`,{className:`agents-head-title`,children:[(0,Q.jsx)(`strong`,{children:e(`子代理`,`Subagents`)}),(0,Q.jsx)(`span`,{className:`agents-hint`,children:d===!1?e(`职责分工(委派说明)· 运行记录看对话下方`,`Roles as delegation briefs · run history sits below the conversation`):e(`职责分工与工具白名单 · 运行记录看对话下方`,`Roles and tool allowlists · run history sits below the conversation`)})]}),(0,Q.jsxs)(`div`,{className:`agents-head-actions`,children:[(0,Q.jsxs)(`label`,{className:`agents-toggle`,title:e(`关掉之后 Agent 工具不再暴露给模型(已有的模板保留)`),children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:l.enabled,onChange:e=>Ol({enabled:e.target.checked})}),e(`启用子代理`,`Enable subagents`)]}),(0,Q.jsxs)(`label`,{className:`agents-toggle agents-toggle-concurrency`,title:e(`最多同时开几个子代理,超出的排队`),children:[e(`默认同时开`,`Run at most`),(0,Q.jsx)(`select`,{value:l.concurrency,onChange:e=>Ol({concurrency:Number(e.target.value)}),children:[1,2,3,4,5,6,8,10,12].map(t=>(0,Q.jsx)(`option`,{value:t,children:e(`${t} 个`,`${t}`)},t))})]})]})]}),u?d===!1?(0,Q.jsx)(`div`,{className:`agents-banner`,children:e(`${t?.engine} 的子代理由引擎自己发起(模型调 spawn_agent),隔离靠沙箱与审批,所以模板里的工具勾选对它不生效。模板的「名称 + 说明」会作为委派说明注入新会话 —— 想让它真的只读,靠的是审批与沙箱,不是这里的勾选。`,`On ${t?.engine}, subagents are spawned by the engine itself (spawn_agent) and isolated by sandbox + approvals, so the per-tool ticks do not apply. A template's name and description are injected into new sessions as delegation briefs; read-only-ness comes from the sandbox and approvals, not from the ticks.`)}):null:(0,Q.jsx)(`div`,{className:`agents-banner`,children:t?.engine===`pi`||t?.engine===void 0?e(`当前服务还没有子代理能力:更新后请重启一次服务(pop restart),面板里的模板不受影响。`,`This service cannot run subagents yet: restart it after updating (pop restart). The templates in this panel are unaffected.`):e(`当前引擎(${t?.engine})不能跑子代理:切到 pi 原生引擎即可;模板可以先在这里配置。`,`The current engine (${t?.engine}) cannot run subagents: switch to the native pi engine. Templates can still be configured here.`)}),(0,Q.jsxs)(`div`,{className:`agents-body`,children:[(0,Q.jsxs)(`section`,{className:`agents-col agents-col-profiles`,children:[(0,Q.jsxs)(`div`,{className:`agents-col-head`,children:[(0,Q.jsx)(`span`,{children:e(`模板(${c.length})`,`Templates (${c.length})`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>r({id:``,label:``,description:``,systemPrompt:`Complete the delegated task end to end. Report what you changed with file paths.`,tools:[`read`,`grep`,`find`,`ls`],enabled:!0,builtin:!1}),children:[`+ `,e(`新建`,`New`)]})]}),c.length===0?(0,Q.jsxs)(`div`,{className:`agents-empty`,children:[(0,Q.jsx)(`p`,{children:e(`还没有可用的模板。`,`No templates available yet.`)}),(0,Q.jsx)(`p`,{className:`agents-hint`,children:e(`点上面的「+ 新建」建一个;内置的 explore / general-purpose / plan 会随服务一起出现。`,`Use “+ New” above to create one; the built-in explore / general-purpose / plan appear automatically.`)})]}):(0,Q.jsx)(`ul`,{className:`agents-profile-list`,children:c.map(t=>(0,Q.jsxs)(`li`,{className:`agents-profile${n?.id===t.id?` agents-profile-on`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`agents-profile-main`,onClick:()=>r(t),title:t.description?e(t.description,t.descriptionEn):t.id,children:[(0,Q.jsxs)(`span`,{className:`agents-profile-name`,children:[t.label,t.builtin?(0,Q.jsx)(`em`,{className:`agents-badge`,children:e(`内置`,`Built-in`)}):null]}),(0,Q.jsx)(`span`,{className:`agents-profile-desc`,children:t.description?e(t.description,t.descriptionEn):t.id})]}),(0,Q.jsx)(`label`,{className:`agents-profile-switch`,title:t.enabled?e(`停用`,`Disable`):e(`启用`,`Enable`),children:(0,Q.jsx)(`input`,{type:`checkbox`,checked:t.enabled,onChange:e=>El({...t,enabled:e.target.checked})})}),t.builtin?null:(0,Q.jsx)(`button`,{type:`button`,className:`agents-profile-del`,title:e(`删除这个模板(内置模板可以改成同名用户文件再删,等于恢复默认)`),onClick:()=>Dl(t.id),children:`✕`})]},t.id))})]}),(0,Q.jsx)(`div`,{className:`agents-split`,role:`separator`,"aria-orientation":`vertical`,"aria-label":e(`调整模板栏宽度`,`Resize the template column`),title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:s,onDoubleClick:()=>a(oC)}),(0,Q.jsx)(`section`,{className:`agents-col agents-col-runs`,children:n?(0,Q.jsx)(nC,{profile:n,onClose:()=>r(null)},`${n.id}-${n.builtin}`):(0,Q.jsxs)(`div`,{className:`agents-empty`,children:[(0,Q.jsx)(`p`,{children:c.length===0?e(`还没有模板:点左边「+ 新建」建一个。`,`No templates yet — use “+ New” on the left.`):e(`左边点一个模板就能改它的指令、工具白名单与模型。`,`Pick a template on the left to edit its instructions, tool allowlist and model.`)}),(0,Q.jsx)(`p`,{className:`agents-hint`,children:d===!1?e(`子代理跑起来之后,卡片会直接出现在对话下方(可就地看结果、可单独停掉);这里只管「谁能被委派」,隔离由引擎的沙箱与审批决定。`,`Once a subagent runs, its card shows up right below the conversation (read the result in place, stop it on its own); this panel only decides who can be delegated — isolation comes from the engine's sandbox and approvals.`):e(`子代理跑起来之后,卡片会直接出现在对话下方(带耗时 / token / 花费,可就地看结果、可单独停掉);这里只管「谁能被委派、用什么工具」。`,`Once a subagent runs, its card shows up right below the conversation (with duration / tokens / cost; read the result in place, stop it on its own); this panel only decides who can be delegated and with which tools.`)})]})})]})]})}var lC=5e3;function uC(e){let{name:t,workspace:n,prompt:r,expression:i,timezone:a,enabled:o,mode:s,allowWrites:c,sessionId:l,model:u}=e;return{name:t,workspace:n,prompt:r,expression:i,timezone:a,enabled:o,mode:s,allowWrites:c,sessionId:l,model:u}}function dC(e=``){return{name:``,workspace:e,prompt:``,expression:`0 9 * * *`,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`,enabled:!0,mode:`text`,allowWrites:!1,sessionId:``,model:``}}var fC=e=>String(e).padStart(2,`0`);function pC(e){let t={preset:`advanced`,time:`09:00`,weekday:`1`,every:`5`,dayOfMonth:`1`},[n,r,i,a,o,s]=e.trim().split(/\s+/);if(s||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||a!==`*`)return t;let c=e=>/^\d{1,2}$/.test(e);if(/^\*\/\d{1,2}$/.test(n)&&r===`*`&&i===`*`&&o===`*`){let e=Number(n.slice(2));return e>=1&&e<=59?{...t,preset:`minutes`,every:String(e)}:t}if(n===`0`&&/^\*\/\d{1,2}$/.test(r)&&i===`*`&&o===`*`){let e=Number(r.slice(2));return e>=1&&e<=23?{...t,preset:`hours`,every:String(e)}:t}if(!c(n)||!c(r)||Number(n)>59||Number(r)>23)return t;let l=`${fC(Number(r))}:${fC(Number(n))}`;return i===`*`&&o===`*`?{...t,preset:`daily`,time:l}:i===`*`&&o===`1-5`?{...t,preset:`weekday`,time:l}:i===`*`&&/^[0-6]$/.test(o)?{...t,preset:`weekly`,time:l,weekday:o}:c(i)&&Number(i)>=1&&Number(i)<=31&&o===`*`?{...t,preset:`monthly`,time:l,dayOfMonth:String(Number(i))}:t}function mC(e,t=``){let{preset:n}=e;if(n===`advanced`)return t;if(n===`minutes`)return`*/${hC(e.every,59)} * * * *`;if(n===`hours`)return`0 */${hC(e.every,23)} * * *`;let[r,i]=(e.time||`09:00`).split(`:`),a=`${Number(i??0)} ${Number(r??9)}`;return n===`daily`?`${a} * * *`:n===`weekday`?`${a} * * 1-5`:n===`weekly`?`${a} * * ${gC(e.weekday)}`:`${a} ${Math.min(31,Math.max(1,Math.round(Number(e.dayOfMonth))||1))} * *`}function hC(e,t){let n=Math.round(Number(e));return Number.isFinite(n)?Math.min(t,Math.max(1,n)):1}function gC(e){let t=Math.round(Number(e));return String(Number.isFinite(t)&&t>=0&&t<=6?t:1)}function _C(e,t){return!!(e.name.trim()&&e.prompt.trim()&&e.timezone.trim()&&t.includes(e.workspace)&&e.expression.trim().split(/\s+/).length===5)}async function vC(e,t,n,r){let i=await fetch(`/api/cron${e}`,{method:t,credentials:`same-origin`,cache:`no-store`,signal:r,...n===void 0?{}:{headers:{"content-type":`application/json`},body:JSON.stringify(n)}});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(typeof e?.error==`string`&&e.error?e.error:J(`请求失败(HTTP ${i.status})`,`Request failed (HTTP ${i.status})`))}return i}async function yC(e){return(await vC(``,`GET`,void 0,e)).json()}async function bC(e){return(await vC(`/options`,`GET`,void 0,e)).json()}async function xC(e,t,n){return(await(await vC(`/preview`,`POST`,{expression:e,timezone:t},n)).json()).times}async function SC(e,t,n){await vC(t===void 0?`/jobs`:`/jobs/${encodeURIComponent(t)}`,t===void 0?`POST`:`PUT`,uC(e),n)}async function CC(e,t){await vC(`/jobs/${encodeURIComponent(e)}`,`DELETE`,void 0,t)}async function wC(e,t){await vC(`/jobs/${encodeURIComponent(e)}/run`,`POST`,void 0,t)}function TC(e,t=!1){if(!e)return`—`;let n=new Date(e);if(Number.isNaN(n.getTime()))return e;let r=e=>String(e).padStart(2,`0`),i=t?` ${new Intl.DateTimeFormat(void 0,{weekday:`short`}).format(n)}`:``;return`${r(n.getMonth()+1)}-${r(n.getDate())}${i} ${r(n.getHours())}:${r(n.getMinutes())}`}function EC(e,t,n=lC){let r=new AbortController,i,a=async()=>{try{let t=await yC(r.signal);r.signal.aborted||e(t)}catch(e){r.signal.aborted||t(e)}finally{r.signal.aborted||(i=setTimeout(()=>void a(),n))}};return a(),()=>{r.abort(),clearTimeout(i)}}function DC({initial:e,workspaces:t,options:n,busy:r,onSave:i,onCancel:a}){let o=Y(),[s,c]=(0,C.useState)(()=>({...e,expression:e.expression.trim().split(/\s+/).join(` `)})),[l,u]=(0,C.useState)(()=>pC(e.expression)),[d,f]=(0,C.useState)(null),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(``),_=JSON.stringify([s.expression,s.timezone]),v=d?.key===_?d:null,y=s.expression.trim().split(/\s+/).length===5&&!!s.timezone.trim();(0,C.useEffect)(()=>{if(!y)return;let e=new AbortController,t=setTimeout(()=>{xC(s.expression,s.timezone,e.signal).then(t=>{e.signal.aborted||f({key:_,times:t,error:``})},t=>{e.signal.aborted||f({key:_,times:[],error:t instanceof Error?t.message:String(t)})})},350);return()=>{clearTimeout(t),e.abort()}},[s.expression,s.timezone,_,y]);let b=(e,t)=>c(n=>({...n,[e]:t})),x=e=>{let t={...l,...e};u(t),t.preset!==`advanced`&&b(`expression`,mC(t,s.expression))},S=e=>{e.preventDefault(),!r&&_C(s,t)&&v&&!v.error&&i({...s,name:s.name.trim(),timezone:s.timezone.trim()})},w=async()=>{if(s.prompt.trim()!==``&&!window.confirm(o(`AI 生成的内容会覆盖当前提示词,继续吗?`,`AI will replace the current prompt. Continue?`)))return;g(``),m(!0);let e=await fu({name:s.name.trim()});m(!1),e.ok?b(`prompt`,e.text):g(e.message)},T=[o(`周日`,`Sunday`),o(`周一`,`Monday`),o(`周二`,`Tuesday`),o(`周三`,`Wednesday`),o(`周四`,`Thursday`),o(`周五`,`Friday`),o(`周六`,`Saturday`)],E=[o(`分钟`,`Minute`),o(`小时`,`Hour`),o(`日`,`Day`),o(`月`,`Month`),o(`星期`,`Weekday`)],D=n.sessions.filter(e=>e.workspace===s.workspace),O=s.expression.split(` `);return(0,Q.jsxs)(`form`,{className:`cron-editor`,onSubmit:S,children:[(0,Q.jsx)(`h3`,{children:o(`任务设置`,`Job settings`)}),(0,Q.jsxs)(`fieldset`,{disabled:r,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`名称`,`Name`),(0,Q.jsx)(`input`,{required:!0,value:s.name,onChange:e=>b(`name`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`工作目录`,`Workspace`),(0,Q.jsxs)(`select`,{"aria-label":o(`工作目录`,`Workspace`),required:!0,value:s.workspace,onChange:e=>{c(t=>({...t,workspace:e.target.value,sessionId:``}))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:o(`选择已注册的工作目录`,`Select a registered workspace`)}),!t.includes(s.workspace)&&s.workspace?(0,Q.jsxs)(`option`,{value:s.workspace,disabled:!0,children:[s.workspace,` — `,o(`未注册`,`Unregistered`)]}):null,t.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),t.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`请先注册一个项目工作目录。`,`Register a project workspace first.`)}):null,(0,Q.jsxs)(`div`,{className:`cron-field`,children:[(0,Q.jsxs)(`div`,{className:`cron-prompt-head`,children:[(0,Q.jsx)(`span`,{children:o(`提示词`,`Prompt`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:p||s.name.trim()===``,onClick:()=>void w(),title:o(`根据任务名称,写一段要做的事(会覆盖当前提示词)`,`Write the task from its name (replaces the prompt)`),children:[`✨ `,p?o(`生成中…`,`Generating…`):o(`AI 生成`,`Generate with AI`)]})]}),(0,Q.jsx)(`textarea`,{"aria-label":o(`提示词`,`Prompt`),required:!0,rows:5,value:s.prompt,onChange:e=>b(`prompt`,e.target.value)}),h?(0,Q.jsx)(`p`,{className:`cron-hint cron-warn`,role:`alert`,children:h}):null]}),(0,Q.jsx)(`div`,{className:`cron-form-row`,children:(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`任务类型`,`Task type`),(0,Q.jsxs)(`select`,{"aria-label":o(`任务类型`,`Task type`),value:s.mode,onChange:e=>b(`mode`,e.target.value===`agent`?`agent`:`text`),children:[(0,Q.jsx)(`option`,{value:`text`,children:o(`文本任务(不读写仓库)`,`Text task (no repo access)`)}),(0,Q.jsx)(`option`,{value:`agent`,children:o(`Agent 任务(真开会话执行)`,`Agent task (runs in a session)`)})]})]})}),s.mode===`agent`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`Agent 任务会在该工作区新建一个会话并真跑一遍:能读文件、跑命令。每次运行都会在侧栏留下一条会话记录。`,`Agent tasks open a real session in this workspace: they can read files and run commands. Every run leaves a session in the sidebar.`)}),(0,Q.jsxs)(`div`,{className:`cron-form-row`,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`会话`,`Session`),(0,Q.jsxs)(`select`,{"aria-label":o(`会话`,`Session`),value:D.some(e=>e.id===s.sessionId)?s.sessionId:``,onChange:e=>b(`sessionId`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:o(`每次新建会话`,`New session each run`)}),D.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.title||e.id},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`模型`,`Model`),(0,Q.jsxs)(`select`,{"aria-label":o(`模型`,`Model`),value:s.model,onChange:e=>b(`model`,e.target.value),children:[(0,Q.jsx)(`option`,{value:``,children:s.sessionId?o(`沿用该会话原来的模型`,`Keep the session's model`):o(`跟随项目默认模型`,`Use the project default`)}),n.models.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),s.sessionId?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`会在这个会话里继续跑:提示词与结果都会进它的历史,同步删掉会话后任务会报错停下。`,`Runs inside that session: prompt and result go into its history; deleting the session makes the job fail.`)}):null,(0,Q.jsxs)(`label`,{className:`cron-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.allowWrites,onChange:e=>b(`allowWrites`,e.target.checked)}),o(`允许改动文件(无人值守时会自动执行写操作)`,`Allow file writes (unattended writes run without confirmation)`)]}),s.allowWrites?(0,Q.jsx)(`p`,{className:`cron-hint cron-warn`,children:o(`已开启:运行期间 agent 的写操作不会问你,可能直接改掉工作区文件。请确认工作目录里没有不想被改的东西。`,`Enabled: the agent's writes will not ask you, and it may modify this workspace directly. Make sure nothing here is unsafe to change.`)}):(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`未开启时:需要审批的操作会被自动拒绝,agent 只能读 —— 适合「每天检查并汇报」,不适合「自动修 bug」。`,`While off, anything needing approval is auto-denied and the agent can only read — fine for daily checks, not for auto-fixing code.`)})]}):(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`文本任务只把提示词发给模型,不读文件、不跑命令 —— 便宜且可预测。要让它干活请选 Agent 任务。`,`Text tasks only send the prompt to a model: no file access, no commands — cheap and predictable. Choose Agent task to actually do work.`)}),(0,Q.jsxs)(`div`,{className:`cron-form-row`,children:[(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`计划`,`Schedule`),(0,Q.jsxs)(`select`,{"aria-label":o(`计划`,`Schedule`),value:l.preset,onChange:e=>x({preset:e.target.value}),children:[(0,Q.jsx)(`option`,{value:`minutes`,children:o(`每隔几分钟`,`Every N minutes`)}),(0,Q.jsx)(`option`,{value:`hours`,children:o(`每隔几小时`,`Every N hours`)}),(0,Q.jsx)(`option`,{value:`daily`,children:o(`每天`,`Daily`)}),(0,Q.jsx)(`option`,{value:`weekday`,children:o(`工作日`,`Weekdays`)}),(0,Q.jsx)(`option`,{value:`weekly`,children:o(`每周`,`Weekly`)}),(0,Q.jsx)(`option`,{value:`monthly`,children:o(`每月`,`Monthly`)}),(0,Q.jsx)(`option`,{value:`advanced`,children:o(`高级(五字段)`,`Advanced (five fields)`)})]})]}),l.preset===`weekly`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`星期`,`Weekday`),(0,Q.jsx)(`select`,{"aria-label":o(`星期`,`Weekday`),value:l.weekday,onChange:e=>x({preset:`weekly`,weekday:e.target.value}),children:T.map((e,t)=>(0,Q.jsx)(`option`,{value:String(t),children:e},t))})]}):null,l.preset===`monthly`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`每月几号`,`Day of month`),(0,Q.jsx)(`select`,{"aria-label":o(`每月几号`,`Day of month`),value:l.dayOfMonth,onChange:e=>x({dayOfMonth:e.target.value}),children:Array.from({length:31},(e,t)=>String(t+1)).map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))})]}):null,l.preset===`minutes`||l.preset===`hours`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[l.preset===`minutes`?o(`每隔(分钟)`,`Every (minutes)`):o(`每隔(小时)`,`Every (hours)`),(0,Q.jsx)(`input`,{type:`number`,required:!0,min:1,max:l.preset===`minutes`?59:23,value:l.every,onChange:e=>x({every:e.target.value})})]}):null,l.preset!==`advanced`&&l.preset!==`minutes`&&l.preset!==`hours`?(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`时间`,`Time`),(0,Q.jsx)(`input`,{type:`time`,required:!0,value:l.time,onChange:e=>x({time:e.target.value})})]}):null]}),l.preset===`advanced`?(0,Q.jsx)(`div`,{className:`cron-fields`,children:E.map((e,t)=>(0,Q.jsxs)(`label`,{className:`cron-field`,children:[e,(0,Q.jsx)(`input`,{required:!0,spellCheck:!1,value:O[t]??``,onChange:e=>{let n=Array.from({length:5},(e,t)=>O[t]??``);n[t]=e.target.value.replace(/\s/g,``),b(`expression`,n.join(` `))}})]},t))}):null,(0,Q.jsx)(`code`,{className:`cron-expression`,children:s.expression}),l.preset===`minutes`||l.preset===`hours`?(0,Q.jsx)(`p`,{className:`cron-hint`,children:o(`每 ${l.every} ${l.preset===`minutes`?`分钟`:`小时`}运行一次(按整点对齐,如每 15 分钟在 :00 / :15 / :30 / :45)`,`Runs every ${l.every} ${l.preset===`minutes`?`minutes`:`hours`} (aligned to the clock: every 15 minutes fires at :00 / :15 / :30 / :45)`)}):null,(0,Q.jsxs)(`label`,{className:`cron-field`,children:[o(`时区`,`Timezone`),(0,Q.jsx)(`input`,{required:!0,placeholder:`Asia/Shanghai`,spellCheck:!1,value:s.timezone,onChange:e=>b(`timezone`,e.target.value)})]}),(0,Q.jsxs)(`label`,{className:`cron-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:s.enabled,onChange:e=>b(`enabled`,e.target.checked)}),o(`启用`,`Enabled`)]})]}),(0,Q.jsxs)(`section`,{className:`cron-preview`,"aria-live":`polite`,"aria-busy":y&&!v,children:[(0,Q.jsx)(`strong`,{children:o(`下次运行预览`,`Upcoming runs`)}),y?v?v.error?(0,Q.jsx)(`p`,{role:`alert`,children:v.error}):v.times.length===0?(0,Q.jsx)(`p`,{children:o(`没有即将运行的时间`,`No upcoming runs`)}):(0,Q.jsx)(`ul`,{children:v.times.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`time`,{dateTime:e,children:TC(e,!0)})},`${e}-${t}`))}):(0,Q.jsx)(`p`,{children:o(`正在预览…`,`Loading preview…`)}):(0,Q.jsx)(`p`,{children:o(`请输入五字段表达式和时区。`,`Enter a five-field expression and timezone.`)})]}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{className:`btn btn-primary`,type:`submit`,disabled:r||!_C(s,t)||!v||!!v.error,children:r?o(`保存中…`,`Saving…`):o(`保存`,`Save`)}),(0,Q.jsx)(`button`,{className:`btn`,type:`button`,disabled:r,onClick:a,children:o(`取消`,`Cancel`)})]})]})}function OC(){let e=Y(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)({sessions:[],models:[]}),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)(0),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(null),[h,g]=(0,C.useState)(null),[_,v]=(0,C.useState)(null),y=(0,C.useRef)(null);(0,C.useEffect)(()=>EC(e=>{n(e),o(``)},e=>o(e instanceof Error?e.message:String(e))),[l]),(0,C.useEffect)(()=>()=>y.current?.abort(),[]),(0,C.useEffect)(()=>{let e=new AbortController;return bC(e.signal).then(t=>{e.signal.aborted||i(t)},()=>void 0),()=>e.abort()},[l]);let b=async e=>{if(y.current)return!1;let t=new AbortController;y.current=t,f(!0),c(``);try{return await e(t.signal),!t.signal.aborted&&(u(e=>e+1),!0)}catch(e){return t.signal.aborted||c(e instanceof Error?e.message:String(e)),!1}finally{t.signal.aborted||(y.current=null,f(!1))}},x={queued:e(`排队中`,`Queued`),running:e(`运行中`,`Running`),succeeded:e(`已成功`,`Succeeded`),failed:e(`已失败`,`Failed`),interrupted:e(`已中断`,`Interrupted`),skipped:e(`已跳过`,`Skipped`)},S=e=>{c(``),v(null),m(e?{id:e.id,draft:uC(e)}:{draft:dC(t?.workspaces[0])})},w=t?.jobs??[],T=t=>w.find(e=>e.id===t)?.name??e(`(已删除的任务)`,`(deleted job)`),E=(t?.runs??[]).filter(e=>h===null||e.jobId===h);return(0,Q.jsxs)(`div`,{className:`cron-panel`,children:[(0,Q.jsxs)(`header`,{className:`cron-head`,children:[(0,Q.jsx)(`h2`,{children:e(`定时任务`,`Cron`)}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>u(e=>e+1),children:e(`刷新`,`Refresh`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d||!t,onClick:()=>S(),children:e(`新建任务`,`New job`)})]})]}),(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`自动刷新。运行历史和结果仅以文本显示,不会打开普通代理会话。`,`Refreshes automatically. Run history and results are shown as text; no regular agent session is opened.`)}),a?(0,Q.jsx)(`div`,{className:`cron-error`,role:`alert`,children:a}):null,s?(0,Q.jsx)(`div`,{className:`cron-error`,role:`alert`,children:s}):null,!t&&!a?(0,Q.jsx)(`p`,{role:`status`,children:e(`加载中…`,`Loading…`)}):null,(0,Q.jsxs)(`div`,{className:`cron-layout`,children:[(0,Q.jsxs)(`section`,{className:`cron-jobs`,"aria-label":e(`定时任务`,`Cron`),children:[t&&w.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`暂无定时任务`,`No scheduled jobs yet`)}):null,w.map(t=>(0,Q.jsxs)(`article`,{className:`cron-job${h===t.id?` cron-job-selected`:``}`,children:[(0,Q.jsxs)(`div`,{className:`cron-job-heading`,children:[(0,Q.jsx)(`h3`,{children:t.name}),(0,Q.jsxs)(`span`,{className:`cron-job-tags`,children:[t.mode===`agent`?(0,Q.jsx)(`span`,{className:`cron-badge`,children:t.allowWrites?e(`Agent · 可写`,`Agent · writes`):e(`Agent · 只读`,`Agent · read-only`)}):(0,Q.jsx)(`span`,{className:`cron-badge cron-badge-plain`,children:e(`文本`,`Text`)}),(0,Q.jsx)(`span`,{className:`cron-hint`,children:t.enabled?e(`已启用`,`Enabled`):e(`已暂停`,`Paused`)})]})]}),(0,Q.jsx)(`p`,{className:`cron-workspace`,children:t.workspace}),(0,Q.jsxs)(`p`,{children:[(0,Q.jsx)(`code`,{children:t.expression}),` · `,t.timezone]}),t.mode===`agent`&&(t.sessionId||t.model)?(0,Q.jsxs)(`p`,{className:`cron-hint`,children:[t.sessionId?`${e(`续跑会话`,`Session`)}: ${r.sessions.find(e=>e.id===t.sessionId)?.title??t.sessionId}`:e(`每次新建会话`,`New session each run`),t.model?` · ${e(`模型`,`Model`)}: ${t.model}`:``]}):null,(0,Q.jsxs)(`p`,{className:`cron-hint`,children:[e(`下次运行`,`Next run`),`:`,` `,t.nextRunAt?(0,Q.jsx)(`time`,{dateTime:t.nextRunAt,children:TC(t.nextRunAt)}):`—`]}),(0,Q.jsxs)(`div`,{className:`cron-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>S(t),children:e(`编辑`,`Edit`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>void b(e=>SC({...uC(t),enabled:!t.enabled},t.id,e)),children:t.enabled?e(`暂停`,`Pause`):e(`启用`,`Enable`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>{g(t.id),b(e=>wC(t.id,e))},children:e(`立即运行`,`Run now`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,"aria-pressed":h===t.id,onClick:()=>g(h===t.id?null:t.id),children:e(`历史`,`History`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>v(t.id),children:e(`删除`,`Delete`)})]}),_===t.id?(0,Q.jsxs)(`div`,{className:`cron-delete`,role:`group`,"aria-label":e(`确认删除`,`Confirm deletion`),children:[(0,Q.jsx)(`span`,{children:e(`删除此定时任务?`,`Delete this scheduled job?`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>void b(e=>CC(t.id,e)).then(e=>{e&&(v(null),h===t.id&&g(null),p?.id===t.id&&m(null))}),children:e(`确认删除`,`Confirm deletion`)}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,disabled:d,onClick:()=>v(null),children:e(`取消`,`Cancel`)})]}):null]},t.id))]}),(0,Q.jsxs)(`div`,{className:`cron-detail`,children:[p?(0,Q.jsx)(DC,{options:r,initial:p.draft,workspaces:t?.workspaces??[],busy:d,onCancel:()=>m(null),onSave:async e=>{await b(t=>SC(e,p.id,t))&&m(null)}},p.id??`new`):null,(0,Q.jsxs)(`section`,{className:`cron-history`,"aria-label":e(`运行历史`,`Run history`),children:[(0,Q.jsxs)(`div`,{className:`cron-job-heading`,children:[(0,Q.jsxs)(`h3`,{children:[e(`运行历史`,`Run history`),h?` · ${T(h)}`:``]}),h?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>g(null),children:e(`全部任务`,`All jobs`)}):null]}),t&&E.length===0?(0,Q.jsx)(`p`,{className:`cron-hint`,children:e(`暂无运行记录`,`No runs yet`)}):null,E.map(t=>(0,Q.jsxs)(`details`,{className:`cron-run`,children:[(0,Q.jsxs)(`summary`,{children:[(0,Q.jsx)(`span`,{className:`cron-status cron-status-${t.status}`,children:x[t.status]}),(0,Q.jsx)(`span`,{children:T(t.jobId)}),(0,Q.jsx)(`span`,{className:`cron-hint`,children:t.trigger===`manual`?e(`手动`,`Manual`):e(`计划`,`Scheduled`)}),(0,Q.jsx)(`time`,{dateTime:t.startedAt??t.scheduledAt,children:TC(t.startedAt??t.scheduledAt)})]}),(0,Q.jsx)(`dl`,{children:[[e(`计划时间`,`Scheduled at`),t.scheduledAt],[e(`开始时间`,`Started at`),t.startedAt],[e(`结束时间`,`Finished at`),t.finishedAt]].map(([e,t])=>t?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{children:e}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(`time`,{dateTime:t,children:TC(t)})})]},e):null)}),t.result===void 0?null:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:e(`结果`,`Result`)}),(0,Q.jsx)(`pre`,{className:`cron-result`,children:t.result})]}),t.error===void 0?null:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{children:e(`错误`,`Error`)}),(0,Q.jsx)(`pre`,{className:`cron-result cron-error`,children:t.error})]})]},t.id))]})]})]})]})}var kC={min:.25,max:4},AC={min:0,max:200};async function jC(e,t){let n=await fetch(`/api/computer${e}`,{method:t?.method??`GET`,credentials:`same-origin`,cache:`no-store`,...t?.signal?{signal:t.signal}:{},...t?.body===void 0?{}:{headers:{"content-type":`application/json`},body:JSON.stringify(t.body)}}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}var MC=()=>jC(`/status`),NC=(e,t)=>jC(`/apps?query=${encodeURIComponent(e)}`,{signal:t}),PC=()=>jC(`/settings`),FC=e=>jC(`/settings`,{method:`PUT`,body:e}),IC=()=>jC(`/request-access`,{method:`POST`}),LC=e=>jC(`/open-privacy`,{method:`POST`,body:{pane:e}}),RC=e=>jC(`/skill`,{method:`POST`,body:{enabled:e}});function zC(){let e=Y(),[t,n]=(0,C.useState)(null),[r,i]=(0,C.useState)(null),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(``),[l,u]=(0,C.useState)([]),[d,f]=(0,C.useState)(!1),[p,m]=(0,C.useState)(0),[h,g]=(0,C.useState)(``),[_,v]=(0,C.useState)(``),[y,b]=(0,C.useState)(!1),[x,S]=(0,C.useState)(null),w=async()=>{S(null);try{let[e,t]=await Promise.all([MC(),PC()]);n(e),i(t),o(t.unprotectedApps.join(`
67
67
  `)),g(String(t.pointerSpeed)),v(String(t.typingKeyDelayMs))}catch(e){S(e instanceof Error?e.message:String(e))}};(0,C.useEffect)(()=>{w()},[]);let T=async e=>{b(!0),S(null);try{await e()}catch(e){S(e instanceof Error?e.message:String(e))}finally{b(!1)}};(0,C.useEffect)(()=>{if(!d)return;let e=new AbortController,t=setTimeout(()=>{NC(s,e.signal).then(t=>{e.signal.aborted||(u(t.apps),m(0))}).catch(()=>{e.signal.aborted||u([])})},180);return()=>{e.abort(),clearTimeout(t)}},[s,d]);let E=e=>{let t=a.split(`
68
68
  `).map(e=>e.trim()).filter(Boolean);t.includes(e)||o([...t,e].join(`
69
- `)),c(``),f(!1)},D=e=>T(async()=>{i(await FC(e))}),O=()=>T(async()=>{n(await RC(!(t?.skill.enabled??!1)))}),k=()=>{let t=Number(h);!Number.isFinite(t)||t<kC.min||t>kC.max?S(e(`指针速度必须在 ${kC.min}–${kC.max} 之间`,`Pointer speed must be between ${kC.min} and ${kC.max}`)):D({pointerSpeed:t})},A=()=>{let t=Number(_);!Number.isInteger(t)||t<AC.min||t>AC.max?S(e(`逐键间隔必须是 ${AC.min}–${AC.max} 之间的整数`,`Key delay must be a whole number between ${AC.min} and ${AC.max}`)):D({typingKeyDelayMs:t})},j=()=>{let e=a.split(/[\n,]/).map(e=>e.trim()).filter(Boolean);D({unprotectedApps:e})},M=t?.skill.enabled??!1,N=t?.permissions?.accessibility===!0&&t?.permissions?.screenRecording===!0;return(0,Q.jsxs)(`div`,{className:`computer-panel`,children:[(0,Q.jsxs)(`header`,{className:`computer-head`,children:[(0,Q.jsx)(`h2`,{children:e(`电脑控制`,`Computer control`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void w(),disabled:y,children:e(`刷新`,`Refresh`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`让 agent 在你的电脑上操作真实应用:读取界面、点击、输入、按快捷键。需要一个单独安装的 macOS 小工具 Agent Computer.app 在跑(还要授权辅助功能与屏幕录制)。`,`Lets the agent operate real apps on your computer: read the UI, click, type, press keys. Needs the separately installed macOS helper Agent Computer.app (plus Accessibility and Screen Recording grants).`)}),x?(0,Q.jsx)(`div`,{className:`computer-error`,role:`alert`,children:x}):null,t&&t.comingSoon?(0,Q.jsx)(`div`,{className:`computer-notice`,role:`status`,children:e(`Windows 版的电脑控制敬请期待:macOS 上已经可用,Windows 还在做。`,`Computer control on Windows is coming soon — it already works on macOS.`)}):t&&!t.supported&&t.platform!==`darwin`?(0,Q.jsx)(`div`,{className:`computer-error`,role:`alert`,children:e(`这台机器上电脑控制不可用:目前只支持 macOS。`,`Computer control is unavailable on this machine: macOS only for now.`)}):null,(0,Q.jsx)(`section`,{className:`computer-section`,"aria-label":e(`总开关`,`Master switch`),children:(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsxs)(`span`,{className:`computer-row-label`,children:[(0,Q.jsx)(`strong`,{children:e(`启用电脑控制`,`Enable computer control`)}),(0,Q.jsx)(`span`,{className:`computer-hint`,children:e(`开启后会在 ~/.agents/skills/agent-computer 写入技能,所有能用 bash 的引擎都可以调用。关闭则把它改名为禁用。`,`Writes the agent-computer skill to ~/.agents/skills. Any engine with bash can use it. Turning it off renames the skill to disabled.`)})]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:M,disabled:y||!t||!t.supported,onChange:()=>void O()})]})}),t?.install?(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`安装 helper`,`Install the helper`),children:[(0,Q.jsx)(`h3`,{children:e(`还差一个本机 helper`,`One local helper left`)}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`操作桌面应用需要一个独立的 macOS 小工具。它不在 npm 包里(要单独分发),装好之后回到这一页就能看到「运行中」。`,`This needs a small macOS helper. It ships separately from the npm package; once installed, come back and this page shows Running.`)}),(0,Q.jsx)(`ol`,{className:`computer-install-steps`,children:t.install.steps.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),(0,Q.jsxs)(`div`,{className:`computer-install-actions`,children:[(0,Q.jsx)(`a`,{className:`computer-btn`,href:t.install.downloadUrl,target:`_blank`,rel:`noreferrer`,children:e(`下载 Agent Computer.app`,`Download Agent Computer.app`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(w),children:e(`装好了,重新检测`,`Installed — check again`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`已经装到别的位置?启动工作台时设置 AGENT_COMPUTER_APP=/路径/Agent Computer.app 即可。`,`Installed somewhere else? Start the workbench with AGENT_COMPUTER_APP=/path/to/Agent Computer.app`)})]}):null,(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`helper 状态`,`Helper status`),children:[(0,Q.jsx)(`h3`,{children:e(`helper 状态`,`Helper status`)}),(0,Q.jsxs)(`ul`,{className:`computer-status`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`安装`,`Installed`)}),(0,Q.jsx)(`span`,{className:t?.helper.installed?`computer-ok`:`computer-bad`,children:t?.helper.installed?t.helper.path:e(`未安装(先下载 Agent Computer.app)`,`Not installed (download Agent Computer.app first)`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`运行`,`Running`)}),(0,Q.jsx)(`span`,{className:t?.running?`computer-ok`:`computer-bad`,children:t?.running?`${e(`已连接`,`Connected`)}${t.helperVersion?` · ${t.helperVersion}`:``}`:t?.error??e(`未连接`,`Not connected`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`辅助功能权限`,`Accessibility`)}),(0,Q.jsx)(`span`,{className:t?.permissions?.accessibility?`computer-ok`:`computer-bad`,children:t?.permissions?.accessibility?e(`已授予`,`Granted`):e(`未授予`,`Not granted`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`屏幕录制权限`,`Screen recording`)}),(0,Q.jsx)(`span`,{className:t?.permissions?.screenRecording?`computer-ok`:`computer-bad`,children:t?.permissions?.screenRecording?e(`已授予`,`Granted`):e(`未授予`,`Not granted`)})]})]}),t&&t.running&&!N?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`还缺权限。点下面的按钮会直接跳到系统设置里对应的那一页;勾上之后回到这里点「刷新」。`,`Some permissions are missing. The buttons below open the right pane in System Settings; tick the app, then hit Refresh here.`)}),(0,Q.jsxs)(`div`,{className:`computer-install-actions`,children:[t.permissions?.accessibility?null:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(async()=>{await IC(),await LC(`accessibility`),await w()}),children:e(`打开辅助功能设置`,`Open Accessibility settings`)}),t.permissions?.screenRecording?null:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(async()=>{await IC(),await LC(`screen`),await w()}),children:e(`打开屏幕录制设置`,`Open Screen Recording settings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(w),children:e(`刷新`,`Refresh`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`屏幕录制勾上后如果仍显示未授予,把 PopAgent 完全退出再打开(macOS 要重启负责录屏的那个进程才认)。`,`If Screen Recording still shows as not granted, quit PopAgent completely and reopen it (macOS re-reads that grant on process start).`)})]}):null]}),r?(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`设置`,`Settings`),children:[(0,Q.jsx)(`h3`,{children:e(`设置`,`Settings`)}),(0,Q.jsxs)(`div`,{className:`computer-block`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:(0,Q.jsx)(`strong`,{children:e(`屏幕上显示什么`,`What shows on screen`)})}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`AI 操作时可以显示三种提示,都可以单独关掉:右下角的小浮窗、屏幕边缘的水印、跟随光标的蓝色指针。`,`Three optional indicators while the AI works: the preview window, an edge watermark, and a pointer ring following the cursor.`)})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`实时预览浮窗(能看到它在操作什么)`,`Live preview window`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.previewEnabled,disabled:y,onChange:()=>void D({previewEnabled:!r.previewEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`AI 操作水印(屏幕边缘 + 顶部提示)`,`AI activity watermark`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.watermarkEnabled,disabled:y,onChange:()=>void D({watermarkEnabled:!r.watermarkEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`agent 的指针动画(跟随光标的蓝圈)`,`Agent pointer ring`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.pointerEnabled,disabled:y,onChange:()=>void D({pointerEnabled:!r.pointerEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`需要前台的步骤可以短暂借用前台`,`Briefly borrow the foreground when needed`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.borrowFront,disabled:y,onChange:()=>void D({borrowFront:!r.borrowFront})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsxs)(`span`,{className:`computer-row-label`,children:[(0,Q.jsx)(`strong`,{children:e(`允许在你空闲时激活目标应用`,`Allow activating the target app while you are idle`)}),(0,Q.jsx)(`span`,{className:`computer-hint`,children:e(`默认关。开启后 agent 可能把窗口切到最前面。`,`Off by default. When on, the agent may bring the window to the front.`)})]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.activateTarget,disabled:y,onChange:()=>void D({activateTarget:!r.activateTarget})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`指针速度`,`Pointer speed`)}),(0,Q.jsx)(`input`,{type:`number`,className:`computer-num`,min:kC.min,max:kC.max,step:.25,value:h,disabled:y,onChange:e=>g(e.target.value),onBlur:k,onKeyDown:e=>e.key===`Enter`&&k()})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`逐键输入间隔(毫秒)`,`Delay between typed keys (ms)`)}),(0,Q.jsx)(`input`,{type:`number`,className:`computer-num`,min:AC.min,max:AC.max,step:1,value:_,disabled:y,onChange:e=>v(e.target.value),onBlur:A,onKeyDown:e=>e.key===`Enter`&&A()})]}),(0,Q.jsxs)(`div`,{className:`computer-block`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:(0,Q.jsx)(`strong`,{children:e(`解除保护的应用(bundle id,一行一个)`,`Unprotected apps (bundle id, one per line)`)})}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`默认保护系统认证、系统设置等。这里加入的应用会被允许操作。密码管理器始终需要你在 helper 里确认,不受此处影响。`,`System authentication and System Settings stay protected by default. Apps listed here become allowed. Password managers still need your confirmation in the helper.`)}),(0,Q.jsxs)(`div`,{className:`computer-app-search`,children:[(0,Q.jsx)(`input`,{type:`text`,className:`computer-app-input`,value:s,disabled:y,placeholder:e(`搜索应用名,比如「微信」,点候选直接加进去`,`Search an app, e.g. "WeChat"`),onChange:e=>{c(e.target.value),f(!0)},onFocus:()=>f(!0),onBlur:()=>setTimeout(()=>f(!1),150),onKeyDown:e=>{if(e.key===`ArrowDown`)e.preventDefault(),f(!0),m(e=>Math.min(e+1,l.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),m(e=>Math.max(e-1,0));else if(e.key===`Enter`){let t=l[p];t&&(e.preventDefault(),E(t.bundleId))}else e.key===`Escape`&&f(!1)}}),d&&l.length>0?(0,Q.jsx)(`ul`,{className:`computer-app-options`,role:`listbox`,children:l.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{type:`button`,className:`computer-app-option${t===p?` is-active`:``}`,role:`option`,"aria-selected":t===p,onMouseDown:t=>{t.preventDefault(),E(e.bundleId)},children:[(0,Q.jsx)(`span`,{className:`computer-app-name`,children:e.name}),(0,Q.jsx)(`small`,{children:e.bundleId})]})},e.bundleId))}):null]}),(0,Q.jsx)(`textarea`,{className:`computer-apps`,rows:4,value:a,disabled:y,placeholder:`com.apple.Notes`,onChange:e=>o(e.target.value)}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,disabled:y,onClick:j,children:e(`保存名单`,`Save list`)})})]})]}):null]})}function BC(e,t,n,r){let i=e.filter(e=>e!==t),a=i.length;for(let e=0;e<i.length;e+=1){let t=r.get(i[e]);if(t&&n<t.left+t.width/2){a=e;break}}return a}function VC(e,t,n){let r=new Map,i=1/0;for(let n of e){let e=t.get(n);e&&(i=Math.min(i,e.left))}if(!Number.isFinite(i))return r;for(let a of e){let e=t.get(a);e&&(r.set(a,i),i+=e.width+n)}return r}var HC=`pop-agent.panel-order.v1`,UC=`pop-agent:panel-order`,WC=[`voice`,`skills`,`push`,`plugins`,`mcp`,`models`,`agents`,`cron`,`computer`,`settings`],GC=new Set(WC);function KC(e){let t=Array.isArray(e)?e:[],n=t.filter((e,n)=>typeof e==`string`&&GC.has(e)&&t.indexOf(e)===n);return[...n,...WC.filter(e=>!n.includes(e))]}function qC(e){if(!e)return[...WC];try{return KC(JSON.parse(e))}catch{return[...WC]}}function JC(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function YC(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(Math.round(n),r.length)),a=[...r];return a.splice(i,0,t),a}function XC(){let[e,t]=(0,C.useState)(()=>qC(Yr(HC)));return(0,C.useEffect)(()=>{let e=e=>{let n=KC(e);t(e=>JC(e,n)?e:n)},n=t=>e(t.detail),r=t=>{t.key===HC&&e(qC(t.newValue))};return window.addEventListener(UC,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(UC,n),window.removeEventListener(`storage`,r)}},[]),[e,(0,C.useCallback)(e=>{let n=KC(e);t(e=>JC(e,n)?e:n),Xr(HC,JSON.stringify(n)),window.dispatchEvent(new CustomEvent(UC,{detail:n}))},[])]}var ZC=5,QC=180,$C=`is-panel-tab-dragging`;function ew({order:e,active:t,label:n,onSelect:r,onOrderChange:i,onHeadPointerDown:a,onHeadDoubleClick:o,headTitle:s}){let c=J(),l=(0,C.useRef)(null),[u,d]=(0,C.useState)(null),f=(0,C.useRef)(null),p=(0,C.useRef)(null),m=(0,C.useRef)(null),h=(0,C.useRef)(!1),g=(0,C.useRef)(null),_=e=>{f.current=e,d(e)};(0,C.useEffect)(()=>()=>{p.current?.(),m.current!==null&&window.clearTimeout(m.current),g.current!==null&&window.clearTimeout(g.current),document.documentElement.classList.remove($C)},[]);let v=(t,n)=>{if(t.stopPropagation(),t.button!==0||f.current||Tf())return;let r=t.pointerId,a=t.currentTarget,o=[...e],s=t.clientX,c=t.clientY,u=s,d=c,v=!1,y=!1,b=null,x=o,S=e=>{JC(x,e)||(x=e,i(e))},C=()=>{if(!v||y)return;let e=f.current,t=e?.boxes.get(n);if(!e||!t)return;let r=u-s,i=t.left+t.width/2+r,a=BC(o,n,i,e.boxes),c=YC(o,n,a);_({...e,dx:r,previewOrder:c,phase:`dragging`}),S(c)},w=e=>{if(y)return;y=!0,A();let t=f.current;if(!t)return;let n=e?t.baseOrder:t.previewOrder;S(n),_({...t,previewOrder:n,phase:`settling`}),h.current=!0,g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{h.current=!1},400);let r=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;m.current=window.setTimeout(()=>{m.current=null,_(null)},r?0:QC)},T=e=>{if(!(e.pointerId!==r||y)){if(u=e.clientX,d=e.clientY,!v){let e=u-s,t=d-c;if(Math.max(Math.abs(e),Math.abs(t))<ZC)return;if(Math.abs(t)>Math.abs(e)){A();return}let i=l.current;if(!i)return;let f=new Map;for(let e of o){let t=i.querySelector(`[data-panel-key="${e}"]`);if(!t)continue;let n=t.getBoundingClientRect();f.set(e,{left:n.left,width:n.width})}if(f.size!==o.length){A();return}v=!0;try{a.setPointerCapture(r)}catch{}document.documentElement.classList.add($C);let p=Number.parseFloat(window.getComputedStyle(i).columnGap)||0;_({key:n,baseOrder:o,previewOrder:o,boxes:f,gap:p,dx:e,phase:`dragging`})}e.preventDefault(),b===null&&(b=window.requestAnimationFrame(()=>{b=null,C()}))}},E=e=>{e.pointerId!==r||y||(v?(e.preventDefault(),b!==null&&window.cancelAnimationFrame(b),b=null,C(),w(!1)):A())},D=e=>{e.pointerId!==r||y||(v?w(!0):A())},O=e=>{e.key===`Escape`&&(v?(e.preventDefault(),w(!0)):A())},k=()=>{v?w(!0):A()};function A(){document.removeEventListener(`pointermove`,T),document.removeEventListener(`pointerup`,E),document.removeEventListener(`pointercancel`,D),document.removeEventListener(`keydown`,O),window.removeEventListener(`blur`,k),b!==null&&window.cancelAnimationFrame(b),b=null,document.documentElement.classList.remove($C);try{a.hasPointerCapture(r)&&a.releasePointerCapture(r)}catch{}p.current===A&&(p.current=null)}p.current?.(),p.current=A,document.addEventListener(`pointermove`,T,{passive:!1}),document.addEventListener(`pointerup`,E),document.addEventListener(`pointercancel`,D),document.addEventListener(`keydown`,O),window.addEventListener(`blur`,k)},y=u?.baseOrder??e,b=u?VC(u.previewOrder,u.boxes,u.gap):null,x=e=>{if(!u||!b)return;let t=u.boxes.get(e),n=b.get(e);if(t&&n!==void 0)return`translate3d(${e===u.key&&u.phase===`dragging`?u.dx:n-t.left}px, 0, 0)`};return(0,Q.jsx)(`div`,{ref:l,className:`big-modal-head`,role:`tablist`,"aria-label":c(`工作台面板`),onPointerDown:a,onDoubleClick:o,title:s,children:y.map(e=>{let i=u?.key===e,a=[`big-tab`,t===e?`big-tab-on`:``,u?`big-tab-reordering`:``,i&&u.phase===`dragging`?`big-tab-dragging`:``,i&&u.phase===`settling`?`big-tab-settling`:``].filter(Boolean).join(` `);return(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":t===e,"data-panel-key":e,className:a,style:{transform:x(e)},draggable:!1,title:`${n(e)} · ${c(`拖动排序`,`Drag to reorder`)}`,onPointerDown:t=>v(t,e),onClick:()=>{h.current||r(e)},children:[(0,Q.jsx)(`span`,{className:`big-tab-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:e})}),n(e)]},e)})})}var tw=180;function nw(e){let t=new Map;for(let n of Array.from(e.children)){if(!(n instanceof HTMLElement))continue;let e=n.dataset.panelKey;e&&t.set(e,n.offsetLeft)}return t}function rw(e){let t=window.getComputedStyle(e).transform;if(!t||t===`none`)return 0;try{return new DOMMatrixReadOnly(t).m41}catch{return 0}}function iw({order:e,className:t,children:n}){let r=(0,C.useRef)(null),i=(0,C.useRef)(new Map),a=(0,C.useRef)(null),o=e.join(`|`);return(0,C.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let t=new ResizeObserver(()=>{i.current=nw(e)});a.current=t,t.observe(e);for(let n of Array.from(e.children))t.observe(n);return()=>{t.disconnect(),a.current=null}},[]),(0,C.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let t=new Map,n=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;for(let r of Array.from(e.children)){if(!(r instanceof HTMLElement))continue;a.current?.observe(r);let e=r.dataset.panelKey;if(!e)continue;let o=r.offsetLeft;t.set(e,o);let s=i.current.get(e);if(s===void 0)continue;let c=rw(r);for(let e of r.getAnimations())e.cancel();let l=s+c-o;!n&&Math.abs(l)>.5&&r.animate([{transform:`translate3d(${l}px, 0, 0)`},{transform:`translate3d(0, 0, 0)`}],{duration:tw,easing:`cubic-bezier(0.2, 0, 0, 1)`})}i.current=t},[o]),(0,Q.jsx)(`div`,{ref:r,className:t,children:n})}var aw=`pop-agent:big-modal-pos:v1`,ow=4,sw=()=>({width:window.innerWidth,height:window.innerHeight}),cw=(e,t,n)=>Math.min(Math.max(e,t),n);function lw(e,t,n,r){let i=(n-t)/2;return(r&&t<=n?cw(e,-i,n-t-i):cw(e,140-t-i,n-140-i))+0}function uw(e,t,n){return{x:lw(e.x,t.width,n.width,!0),y:lw(e.y,t.height,n.height,!0)}}function dw(e,t,n){return{x:lw(e.x,t.width,n.width,!1),y:lw(e.y,t.height,n.height,!1)}}function fw(e){if(!e)return{x:0,y:0};try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return{x:0,y:0};let n=t;return{x:typeof n.x==`number`&&Number.isFinite(n.x)?n.x:0,y:typeof n.y==`number`&&Number.isFinite(n.y)?n.y:0}}catch{return{x:0,y:0}}}function pw(e){let[t,n]=(0,C.useState)(Tf),[r,i]=(0,C.useState)(()=>fw(localStorage.getItem(aw))),a=(0,C.useRef)(r);a.current=r,(0,C.useEffect)(()=>{let t=()=>{n(Tf()),e.size&&i(t=>uw(t,e.size,sw()))};return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[e.size]),(0,C.useEffect)(()=>{e.size&&i(t=>uw(t,e.size,sw()))},[e.size]);let o=(0,C.useCallback)(t=>{if(t.button!==0||!e.size)return;let n=e.size,r=t.clientX,o=t.clientY,s=a.current,c=!1,l=e=>{let t=e.clientX-r,a=e.clientY-o;!c&&Math.abs(t)<ow&&Math.abs(a)<ow||(c||(c=!0,document.body.style.userSelect=`none`,document.documentElement.classList.add(`is-modal-moving`)),e.preventDefault(),i(dw({x:s.x+t,y:s.y+a},n,sw())))},u=()=>{if(document.removeEventListener(`pointermove`,l),document.removeEventListener(`pointerup`,u),document.body.style.userSelect=``,document.documentElement.classList.remove(`is-modal-moving`),!c)return;let e=e=>{e.stopPropagation(),e.preventDefault()};document.addEventListener(`click`,e,{capture:!0,once:!0}),window.setTimeout(()=>document.removeEventListener(`click`,e,{capture:!0}),400);try{localStorage.setItem(aw,JSON.stringify(a.current))}catch{}};document.addEventListener(`pointermove`,l),document.addEventListener(`pointerup`,u)},[e.size]),s=(0,C.useCallback)(()=>{try{localStorage.removeItem(aw)}catch{}i({x:0,y:0})},[]),c=(0,C.useCallback)(()=>{let t=e.size;if(!t)return;let n=uw(a.current,t,sw());a.current=n,i(n)},[e.size]),l=(0,C.useRef)(r),u=(0,C.useCallback)(()=>(l.current=a.current,l.current),[]),d=(0,C.useCallback)(e=>{let t={x:l.current.x+e.x,y:l.current.y+e.y};a.current=t,i(t)},[]),f=(0,C.useCallback)(()=>{try{localStorage.setItem(aw,JSON.stringify(a.current))}catch{}},[]);return{style:t?void 0:{transform:`translate(${Math.round(r.x)}px, ${Math.round(r.y)}px)`},start:o,reset:s,reclamp:c,beginResize:u,shiftBy:d,commitResize:f}}var mw=`pop-agent:big-modal-size:v4`,hw=[`pop-agent:big-modal-size`,`pop-agent:big-modal-size:v2`,`pop-agent:big-modal-size:v3`],gw=620,_w=340,vw=()=>({width:window.innerWidth,height:window.innerHeight}),yw=(e,t,n)=>Math.min(Math.max(e,t),n);function bw(e){return{minWidth:gw,minHeight:_w,maxWidth:Math.max(gw,e.width-32),maxHeight:Math.max(_w,e.height-32)}}function xw(e){let t=bw(e);return{width:Math.round(t.maxWidth),height:Math.round(t.maxHeight)}}function Sw(e,t){let n=bw(t),r=Number.isFinite(e.width)?e.width:xw(t).width,i=Number.isFinite(e.height)?e.height:xw(t).height;return{width:Math.round(yw(r,n.minWidth,n.maxWidth)),height:Math.round(yw(i,n.minHeight,n.maxHeight))}}function Cw(e){let t=e.corner===`se`||e.corner===`ne`?1:-1,n=e.corner===`se`||e.corner===`sw`?1:-1,r=Sw({width:e.start.width+t*e.dx,height:e.start.height+n*e.dy},e.view),i=uw({x:e.pos.x+t*(r.width-e.start.width)/2,y:e.pos.y+n*(r.height-e.start.height)/2},r,e.view),a=Math.round(i.x-e.pos.x),o=Math.round(i.y-e.pos.y);return{size:r,shift:{x:a===0?0:a,y:o===0?0:o}}}function ww(e,t){if(!e)return xw(t);try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return xw(t);let r=n;return typeof r.width!=`number`||typeof r.height!=`number`||!Number.isFinite(r.width)||!Number.isFinite(r.height)?xw(t):Sw({width:r.width,height:r.height},t)}catch{return xw(t)}}function Tw(e){let t=e?.anchor,[n,r]=(0,C.useState)(()=>{for(let e of hw)localStorage.removeItem(e);return ww(localStorage.getItem(mw),vw())}),[i,a]=(0,C.useState)(Tf),[o,s]=(0,C.useState)(()=>localStorage.getItem(mw)!==null);(0,C.useEffect)(()=>{o&&localStorage.setItem(mw,JSON.stringify(n))},[o,n]),(0,C.useEffect)(()=>{let e=()=>{a(Tf()),r(e=>o?Sw(e,vw()):xw(vw()))};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[o]);let c=(0,C.useCallback)((e,i=`se`)=>{e.preventDefault(),s(!0);let a=t?.current??null,o=a?.begin()??{x:0,y:0},c=e.clientX,l=e.clientY,u=n,d=e=>{let{size:t,shift:n}=Cw({start:u,pos:o,dx:e.clientX-c,dy:e.clientY-l,corner:i,view:vw()});r(t),a?.shift(n)},f=()=>{document.removeEventListener(`pointermove`,d),document.removeEventListener(`pointerup`,f),a?.commit()};document.addEventListener(`pointermove`,d),document.addEventListener(`pointerup`,f)},[n,t]),l=(0,C.useCallback)(()=>{localStorage.removeItem(mw),s(!1),r(xw(vw()))},[]);return{size:n,style:i?void 0:{width:`${n.width}px`,height:`${n.height}px`},start:c,reset:l}}var Ew={models:`模型`,skills:`技能`,push:`推送`,plugins:`插件`,mcp:`MCP`,voice:`语音`,agents:`子代理`,cron:`定时任务`,computer:`电脑控制`,settings:`设置`},Dw={models:`Models`,skills:`Skills`,push:`Push`,plugins:`Plugins`,mcp:`MCP`,voice:`Voice`,agents:`Subagents`,cron:`Cron`,computer:`Computer`,settings:`Settings`},Ow=[`nw`,`ne`,`sw`,`se`],kw=e=>e===`error`?12e3:e===`warn`?8e3:5e3;function Aw({initialPanel:e=null,variant:t=`full`,placement:n=`footer`,items:r,panel:i,onPanelChange:a,leadingAction:o}={}){let s=J(),[c,l]=XC(),[u,d]=(0,C.useState)(e),f=i===void 0?u:i,p=e=>{a&&a(e),i===void 0&&d(e)},m=(0,C.useRef)(null),h=Tw({anchor:m}),g=pw({size:h.size});m.current={begin:g.beginResize,shift:g.shiftBy,commit:g.commitResize};let _=g.reclamp;(0,C.useEffect)(()=>{f&&_()},[f,_]);let v=Ro(e=>e.snapshot),y=Ro(e=>e.lastError),b=(0,C.useRef)(new Set),x=(0,C.useRef)(y?.text??null),[S,w]=(0,C.useState)(null);(0,C.useEffect)(()=>{b.current=new Set((v?.notices??[]).map(e=>e.id)),x.current=y?.text??null,w(null)},[f]),(0,C.useEffect)(()=>{let e=(v?.notices??[]).filter(e=>!b.current.has(e.id));if(e.length===0)return;for(let t of e)b.current.add(t.id);let t=e[e.length-1];t&&w({key:`notice-${t.id}`,text:t.text,level:t.level,at:Date.now()})},[v?.notices]),(0,C.useEffect)(()=>{let e=y?.text??null;e&&e!==x.current&&(x.current=e,w({key:`error-${Date.now()}`,text:e,level:`error`,at:Date.now()}))},[y]),(0,C.useEffect)(()=>{if(!S)return;let e=setTimeout(()=>{w(e=>e&&Date.now()-e.at>=kw(e.level)?null:e)},kw(S.level));return()=>clearTimeout(e)},[S]);let T=c.filter(e=>!r||r.includes(e)),[E]=bp(Dr,Or),D=n===`appbar`,O=!D||E.label,k=!D||E.icon||!E.label,A=(e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-panel-key":e,title:t,className:`side-foot-btn side-foot-btn-${e}${f===e?` side-foot-btn-on`:``}`,onClick:()=>p(f===e?null:e),children:[k?(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:e})}):null,O?(0,Q.jsx)(`span`,{className:`side-foot-label`,children:t}):null]},e),j=(0,C.useRef)(!1);return(0,Q.jsxs)(`div`,{className:n===`appbar`?`appbar-menu`:`side-foot`,children:[t===`full`?(0,Q.jsxs)(iw,{className:`side-foot-row`,order:T,children:[o?.({showIcon:k,showLabel:O}),T.map(e=>A(e,s(Ew[e],Dw[e])))]}):null,f?(0,Ko.createPortal)((0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":s(`工作台面板`),onMouseDown:e=>{j.current=e.target===e.currentTarget},onClick:e=>{let t=j.current;j.current=!1,t&&e.target===e.currentTarget&&p(null)},children:(0,Q.jsxs)(`div`,{className:`modal big-modal`,style:{...h.style,...g.style},onPointerDown:e=>{e.target===e.currentTarget&&g.start(e)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny big-modal-close`,onClick:()=>p(null),title:s(`关闭`,`Close`),children:`✕`}),(0,Q.jsx)(ew,{order:c,active:f,label:e=>s(Ew[e],Dw[e]),onSelect:p,onOrderChange:l,onHeadPointerDown:g.start,onHeadDoubleClick:g.reset,headTitle:s(`拖动 Tab 排序;拖动空白处移动面板(双击复位)`,`Drag tabs to reorder; drag empty space to move the panel (double-click to reset)`)}),S?(0,Q.jsx)(`div`,{className:`modal-notices`,children:(0,Q.jsx)(`div`,{className:`notice${S.level===`error`?` notice-error`:S.level===`warn`?` notice-warn`:``}`,children:S.text},S.key)}):null,(0,Q.jsxs)(`div`,{className:`big-modal-body`,children:[f===`models`?(0,Q.jsx)(Cy,{}):null,f===`skills`?(0,Q.jsx)(fS,{}):null,f===`push`?(0,Q.jsx)(ZS,{}):null,f===`plugins`?(v?.engine??`pi`)===`pi`?(0,Q.jsx)(PS,{}):(0,Q.jsx)(ES,{engine:v?.engine??``}):null,f===`mcp`?(v?.engine??`pi`)===`pi`?(0,Q.jsx)(KS,{}):(0,Q.jsx)(wS,{engine:v?.engine??``}):null,f===`voice`?(0,Q.jsx)(eC,{}):null,f===`agents`?(0,Q.jsx)(cC,{}):null,f===`cron`?(0,Q.jsx)(OC,{}):null,f===`computer`?(0,Q.jsx)(zC,{}):null,f===`settings`?(0,Q.jsx)(Mx,{}):null]}),Ow.map(e=>(0,Q.jsx)(`div`,{className:`modal-resize modal-resize-${e}`,role:`separator`,"aria-label":s(`调整面板大小`),title:s(`拖动调整窗口大小(双击复位)`),onPointerDown:t=>h.start(t,e),onDoubleClick:()=>{h.reset(),g.reset()}},e))]})}),document.body):null]})}function jw({variant:e=`appbar`}){let t=J();return e===`icon`?(0,Q.jsx)(`button`,{type:`button`,className:`newchat-icon-btn`,onClick:()=>Mo(),title:t(`新建会话`,`New session`),"aria-label":t(`新建会话`,`New session`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`💬`})}):(0,Q.jsxs)(`button`,{type:`button`,className:`newchat-pill newchat-pill-${e}`,onClick:()=>Mo(),title:t(`新建会话`,`New session`),children:[(0,Q.jsx)(`span`,{className:`newchat-pill-icon`,"aria-hidden":`true`,children:`💬`}),(0,Q.jsx)(`span`,{className:`newchat-pill-label`,children:t(`新会话`,`New session`)})]})}function Mw({onClick:e,showIcon:t=!0,showLabel:n=!0}){let r=J();return(0,Q.jsxs)(`button`,{type:`button`,className:`side-foot-btn tempchat-btn`,onClick:e,title:r(`临时会话:在右侧新开一条聊天(不落盘,关掉就没了)`,`Temp session: start a separate chat on the right (not saved, gone on close)`),children:[t?(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:`💬`}):null,n?(0,Q.jsx)(`span`,{className:`side-foot-label`,children:r(`临时会话`,`Temp session`)}):null]})}function Nw(){let e=J(),t=yc(),[n]=xc(),r=oc();if((0,C.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),_c())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[t]),!t)return null;let i=bc(n,r),a=cc(n.cheatSheet,r);return(0,Q.jsx)(`div`,{className:`shortcut-sheet-backdrop`,onClick:e=>{e.target===e.currentTarget&&_c()},children:(0,Q.jsxs)(`div`,{className:`shortcut-sheet`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`快捷键速查表`,`Shortcuts`),children:[(0,Q.jsxs)(`div`,{className:`shortcut-sheet-head`,children:[(0,Q.jsx)(`span`,{className:`shortcut-sheet-title`,children:e(`快捷键`,`Shortcuts`)}),(0,Q.jsx)(`span`,{className:`shortcut-sheet-sub`,children:e(`设置 → 快捷键 里可以改;留空就是不用`,`Change them in Settings → Shortcuts; leave one empty to disable it`)}),(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-sheet-close`,onClick:_c,"aria-label":e(`关闭速查表`,`Close the cheat sheet`),title:e(`关闭(Esc)`,`Close (Esc)`),children:`✕`})]}),(0,Q.jsx)(`div`,{className:`shortcut-sheet-grid`,children:i.map(t=>(0,Q.jsxs)(`div`,{className:`sheet-row${t.combo?``:` sheet-row-off`}`,children:[(0,Q.jsx)(`span`,{className:`sheet-label`,children:e(t.label,t.labelEn)}),t.combo?(0,Q.jsx)(`kbd`,{className:`sheet-kbd`,children:t.combo}):(0,Q.jsx)(`span`,{className:`sheet-unbound`,children:e(`未设置`,`Unbound`)})]},t.id))}),(0,Q.jsxs)(`div`,{className:`shortcut-sheet-foot`,children:[e(`Esc 关闭`,`Esc to close`),a?e(`;再按一次 ${a} 也可以关`,`; press ${a} again to close`):``]})]})})}var Pw=[{id:`deepseek`,label:`DeepSeek`,labelEn:`DeepSeek`,provider:`deepseek`,baseUrl:`https://api.deepseek.com`,api:`openai-completions`,model:`deepseek-chat`},{id:`openai`,label:`OpenAI`,labelEn:`OpenAI`,provider:`openai`,baseUrl:`https://api.openai.com/v1`,api:`openai-completions`,model:`gpt-4o-mini`},{id:`anthropic`,label:`Anthropic`,labelEn:`Anthropic`,provider:`anthropic`,baseUrl:`https://api.anthropic.com`,api:`anthropic-messages`,model:`claude-opus-4-6`},{id:`custom`,label:`自定义`,labelEn:`Custom`,provider:``,baseUrl:``,api:`openai-completions`,model:``}],Fw=/^[a-z0-9][a-z0-9-]{1,30}$/,Iw=8,Lw=[];function Rw(e,t){if(e.name===`pi`)return`builtin`;if(t===null)return`checking`;let n=t[e.name];return!n||n.installed?`installed`:n.installable?`missing`:`manual`}function zw({onDone:e}){let t=J(),n=Zv(),r=Ro(e=>e.snapshot),i=r?.engines??Lw,[a,o]=(0,C.useState)(1),[s,c]=(0,C.useState)(`pi`),[l,u]=(0,C.useState)(`deepseek`),[d,f]=(0,C.useState)(`deepseek`),[p,m]=(0,C.useState)(`https://api.deepseek.com`),[h,g]=(0,C.useState)(``),[_,v]=(0,C.useState)(`deepseek-chat`),[y,b]=(0,C.useState)(r?.files?.root??``),[x,S]=(0,C.useState)(null),[w,T]=(0,C.useState)(null);(0,C.useEffect)(()=>{let e=!1;return fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(t=>{if(e)return;let n={};for(let e of t?.engines??[])n[e.name]={installed:e.installed,installable:e.installable!==!1};T(n)}).catch(()=>{e||T({})}),()=>{e=!0}},[]),(0,C.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let E=[t(`选择引擎`,`Choose engine`),t(`配置模型`,`Configure model`),t(`开始会话`,`Start a session`)],D=e=>e===`builtin`?t(`内置`,`Built-in`):e===`checking`?t(`检测中…`,`Checking…`):e===`installed`?t(`已安装`,`Installed`):e===`missing`?t(`未安装`,`Not installed`):t(`需要安装`,`Needs install`),O=()=>{S(null),tu(s),o(2)},k=e=>{let t=Pw.find(t=>t.id===e);t&&(u(e),f(t.provider),m(t.baseUrl),v(t.model),g(``),S(null))},A=()=>{let e=d.trim(),n=p.trim(),i=_.trim(),a=h.trim();a===``?S(t(`先填 API Key:空 key 提交上去也用不了。`,`Add an API key first — an empty one will not work.`)):a.length<Iw?S(t(`API Key 至少 ${Iw} 位。`,`The API key needs at least ${Iw} characters.`)):Fw.test(e)?n===``||!/^https?:\/\//i.test(n)?S(t(`baseUrl 要以 http:// 或 https:// 开头。`,`baseUrl must start with http:// or https://.`)):i===``?S(t(`填一个模型 id,例如 deepseek-chat。`,`Enter a model id, e.g. deepseek-chat.`)):(yu({provider:e,baseUrl:n,api:Pw.find(e=>e.id===l)?.api??`openai-completions`,apiKey:a,models:[{id:i}]}),lu(`${e}/${i}`,r?.active.conversationId??null),S(null),o(3)):S(t(`provider id 只能用小写字母、数字和 -,2–31 位(会作为 provider/model 的前缀)。`,`The provider id must be 2–31 chars of lowercase letters, digits or “-” (it prefixes provider/model).`))},j=()=>{let t=y.trim();Mo(t===``?null:t),e()},M=Pw.find(e=>e.id===l)?.api??`openai-completions`;return(0,Q.jsx)(`div`,{className:`first-run-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`first-run-title`,children:(0,Q.jsxs)(`div`,{className:`first-run-card`,children:[(0,Q.jsxs)(`div`,{className:`first-run-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{className:`first-run-title`,id:`first-run-title`,children:t(`欢迎使用 ${n.name}`,`Welcome to ${n.name}`)}),(0,Q.jsx)(`p`,{className:`first-run-subtitle`,children:t(`三步就能开始:选引擎、配一个模型、建第一条会话。`,`Three steps to get going: pick an engine, configure a model, start your first session.`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny first-run-skip`,onClick:e,children:t(`跳过`,`Skip`)})]}),(0,Q.jsx)(`ol`,{className:`first-run-steps`,children:E.map((e,t)=>{let n=t+1;return(0,Q.jsxs)(`li`,{className:`first-run-step${a===n?` first-run-step-on`:``}${a>n?` first-run-step-done`:``}`,children:[(0,Q.jsx)(`span`,{className:`first-run-step-index`,"aria-hidden":`true`,children:n}),(0,Q.jsx)(`span`,{children:e})]},e)})}),(0,Q.jsx)(`div`,{className:`first-run-body`,children:a===1?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`引擎决定谁来干活。没装的也能选:切过去之后界面会给你安装入口。`,`Pick the agent that does the work. You can choose one that is not installed — the app will offer to install it.`)}),(0,Q.jsx)(`div`,{className:`first-run-engines`,children:i.length===0?(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`引擎清单还没到,稍等一下。`,`The engine list has not arrived yet — one moment.`)}):i.map(e=>{let n=s===e.name,r=Rw(e,w),i=r===`installed`||r===`builtin`?` first-run-engine-state-on`:r===`missing`||r===`manual`?` first-run-engine-state-warn`:``;return(0,Q.jsxs)(`button`,{type:`button`,className:`first-run-engine${n?` first-run-engine-on`:``}`,"aria-pressed":n,onClick:()=>{c(e.name),S(null)},children:[(0,Q.jsxs)(`span`,{className:`first-run-engine-top`,children:[(0,Q.jsx)(`span`,{className:`first-run-engine-name`,children:t(e.label)}),(0,Q.jsx)(`span`,{className:`first-run-engine-state${i}`,children:D(r)})]}),e.description?(0,Q.jsx)(`span`,{className:`first-run-engine-desc`,children:t(e.description)}):null,r===`missing`?(0,Q.jsx)(`span`,{className:`first-run-engine-hint`,children:t(`还没装:可以继续,切过去后按提示一键安装。`,`Not installed: continue, then install it with one click when prompted.`)}):r===`manual`?(0,Q.jsx)(`span`,{className:`first-run-engine-hint`,children:t(`还没装且没有一键安装包:要先自己把它装好。`,`Not installed and no one-click package: install it yourself first.`)}):null]},e.name)})})]}):a===2?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`first-run-presets`,role:`group`,"aria-label":t(`服务商`,`Provider`),children:Pw.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`first-run-preset${l===e.id?` first-run-preset-on`:``}`,"aria-pressed":l===e.id,onClick:()=>k(e.id),children:t(e.label,e.labelEn)},e.id))}),s===`pi`?null:(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`当前选的不是 pi:它的模型由引擎自己管理。这里填的 provider 会写进 pi 的配置,之后切回 pi 时直接可用。`,`The selected engine is not pi: it manages its own models. This provider is written to pi's config and will be ready when you switch back.`)}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`provider(作为 provider/model 前缀)`,`provider (prefix of provider/model)`)}),(0,Q.jsx)(`input`,{value:d,readOnly:l!==`custom`,onChange:e=>f(e.target.value),placeholder:`my-endpoint`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:`base url`}),(0,Q.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),placeholder:`https://api.example.com/v1`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:`API Key`}),(0,Q.jsx)(`input`,{type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:`sk-…`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`模型 id`,`Model id`)}),(0,Q.jsx)(`input`,{value:_,onChange:e=>v(e.target.value),placeholder:t(`例如 deepseek-chat`,`e.g. deepseek-chat`),autoComplete:`off`})]}),(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`接口形态:${M}(自定义也按这个开局,之后可在设置里改)。key 只写进本机配置,不会回显。`,`API shape: ${M} (custom starts with this too; change it later in Settings). The key is stored locally and never shown again.`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`工作区路径`,`Workspace path`)}),(0,Q.jsx)(`input`,{value:y,onChange:e=>b(e.target.value),placeholder:t(`留空用默认工作区`,`Leave empty for the default workspace`),autoComplete:`off`})]}),(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`留空用默认工作区。填了的话,这条会话就在那个目录里跑。`,`Leave it empty to use the default workspace. Otherwise the session runs in the directory you enter.`)})]})}),x?(0,Q.jsx)(`div`,{className:`first-run-error`,role:`alert`,children:x}):null,(0,Q.jsxs)(`div`,{className:`first-run-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:a===1,onClick:()=>{S(null),o(e=>e>1?e-1:e)},children:t(`上一步`,`Back`)}),(0,Q.jsx)(`span`,{className:`first-run-actions-grow`}),a===3?(0,Q.jsx)(`button`,{type:`button`,className:`btn first-run-primary`,onClick:j,children:t(`开始`,`Start`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn first-run-primary`,onClick:a===1?O:A,children:t(`下一步`,`Next`)})]})]})})}var Bw={ts:`typescript`,tsx:`typescript`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`javascript`,json:`json`,css:`css`,scss:`scss`,html:`xml`,xml:`xml`,svg:`xml`,md:`markdown`,markdown:`markdown`,sh:`bash`,bash:`bash`,zsh:`bash`,py:`python`,rb:`ruby`,go:`go`,rs:`rust`,java:`java`,kt:`kotlin`,sql:`sql`,yml:`yaml`,yaml:`yaml`,toml:`ini`,ini:`ini`,dockerfile:`dockerfile`};function Vw(e){let t=D(e).toLowerCase();return t===`dockerfile`?`dockerfile`:t===`makefile`?`makefile`:Bw[t.includes(`.`)?t.split(`.`).pop()??``:``]??``}function Hw(e,t){return{start:Math.min(e,t)+1,end:Math.max(e,t)+1}}function Uw(e,t){return t?t.start===t.end?`@${e}:${t.start}`:`@${e}:${t.start}-${t.end}`:`@${e}`}function Ww(e){let t=e.filter(e=>e.end>=e.start).map(e=>({start:e.start,end:e.end})).sort((e,t)=>e.start-t.start),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=t.end+1?t.end=Math.max(t.end,e.end):n.push({...e})}return n}function Gw(e){return e.reduce((e,t)=>e+(t.end-t.start+1),0)}function Kw(e,t){return t.length===0?`@${e}`:t.map(t=>Uw(e,t)).join(` `)}function qw(e){let t=e[0];return t?e.filter(e=>e!==t).map(e=>e.start):[]}function Jw(e,t,n){let r=new Set(t);if(r.has(n)){r.delete(n);let t=e.find(e=>e.start===n);if(t)for(let n of e)n.start>t.start&&n.end<=t.end&&r.add(n.start);return r}return r.add(n),r}function Yw(e,t){let n=null;for(let r of e)(r.start===t||t>r.start&&t<=r.end)&&(!n||r.end-r.start<n.end-n.start)&&(n=r);return n}function Xw(e,t,n){return t.has(n.start)?`collapsed`:e.some(e=>e.start>n.start&&e.end<=n.end&&t.has(e.start))?`partial`:`open`}function Zw(e,t,n){let r=new Set(t);for(let t of e)t.start>=n.start&&t.end<=n.end&&r.delete(t.start);return r}function Qw(e,t,n){let r=new Set(t);for(let t of e)t.start>=n.start&&t.end<=n.end&&r.add(t.start);return r}function $w(e){let t=[],n=[],r=0,i=null,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(s===`
69
+ `)),c(``),f(!1)},D=e=>T(async()=>{i(await FC(e))}),O=()=>T(async()=>{n(await RC(!(t?.skill.enabled??!1)))}),k=()=>{let t=Number(h);!Number.isFinite(t)||t<kC.min||t>kC.max?S(e(`指针速度必须在 ${kC.min}–${kC.max} 之间`,`Pointer speed must be between ${kC.min} and ${kC.max}`)):D({pointerSpeed:t})},A=()=>{let t=Number(_);!Number.isInteger(t)||t<AC.min||t>AC.max?S(e(`逐键间隔必须是 ${AC.min}–${AC.max} 之间的整数`,`Key delay must be a whole number between ${AC.min} and ${AC.max}`)):D({typingKeyDelayMs:t})},j=()=>{let e=a.split(/[\n,]/).map(e=>e.trim()).filter(Boolean);D({unprotectedApps:e})},M=t?.skill.enabled??!1,N=t?.permissions?.accessibility===!0&&t?.permissions?.screenRecording===!0;return(0,Q.jsxs)(`div`,{className:`computer-panel`,children:[(0,Q.jsxs)(`header`,{className:`computer-head`,children:[(0,Q.jsx)(`h2`,{children:e(`电脑控制`,`Computer control`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void w(),disabled:y,children:e(`刷新`,`Refresh`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`让 agent 在你的电脑上操作真实应用:读取界面、点击、输入、按快捷键。需要一个单独安装的 macOS 小工具 Agent Computer.app 在跑(还要授权辅助功能与屏幕录制)。`,`Lets the agent operate real apps on your computer: read the UI, click, type, press keys. Needs the separately installed macOS helper Agent Computer.app (plus Accessibility and Screen Recording grants).`)}),x?(0,Q.jsx)(`div`,{className:`computer-error`,role:`alert`,children:x}):null,t&&t.comingSoon?(0,Q.jsx)(`div`,{className:`computer-notice`,role:`status`,children:e(`Windows 版的电脑控制敬请期待:macOS 上已经可用,Windows 还在做。`,`Computer control on Windows is coming soon — it already works on macOS.`)}):t&&!t.supported&&t.platform!==`darwin`?(0,Q.jsx)(`div`,{className:`computer-error`,role:`alert`,children:e(`这台机器上电脑控制不可用:目前只支持 macOS。`,`Computer control is unavailable on this machine: macOS only for now.`)}):null,(0,Q.jsx)(`section`,{className:`computer-section`,"aria-label":e(`总开关`,`Master switch`),children:(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsxs)(`span`,{className:`computer-row-label`,children:[(0,Q.jsx)(`strong`,{children:e(`启用电脑控制`,`Enable computer control`)}),(0,Q.jsx)(`span`,{className:`computer-hint`,children:e(`开启后会在 ~/.agents/skills/agent-computer 写入技能,所有能用 bash 的引擎都可以调用。关闭则把它改名为禁用。`,`Writes the agent-computer skill to ~/.agents/skills. Any engine with bash can use it. Turning it off renames the skill to disabled.`)})]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:M,disabled:y||!t||!t.supported,onChange:()=>void O()})]})}),t?.install?(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`安装 helper`,`Install the helper`),children:[(0,Q.jsx)(`h3`,{children:e(`还差一个本机 helper`,`One local helper left`)}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`操作桌面应用需要一个独立的 macOS 小工具。它不在 npm 包里(要单独分发),装好之后回到这一页就能看到「运行中」。`,`This needs a small macOS helper. It ships separately from the npm package; once installed, come back and this page shows Running.`)}),(0,Q.jsx)(`ol`,{className:`computer-install-steps`,children:t.install.steps.map(e=>(0,Q.jsx)(`li`,{children:e},e))}),(0,Q.jsxs)(`div`,{className:`computer-install-actions`,children:[(0,Q.jsx)(`a`,{className:`computer-btn`,href:t.install.downloadUrl,target:`_blank`,rel:`noreferrer`,children:e(`下载 Agent Computer.app`,`Download Agent Computer.app`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(w),children:e(`装好了,重新检测`,`Installed — check again`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`已经装到别的位置?启动工作台时设置 AGENT_COMPUTER_APP=/路径/Agent Computer.app 即可。`,`Installed somewhere else? Start the workbench with AGENT_COMPUTER_APP=/path/to/Agent Computer.app`)})]}):null,(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`helper 状态`,`Helper status`),children:[(0,Q.jsx)(`h3`,{children:e(`helper 状态`,`Helper status`)}),(0,Q.jsxs)(`ul`,{className:`computer-status`,children:[(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`安装`,`Installed`)}),(0,Q.jsx)(`span`,{className:t?.helper.installed?`computer-ok`:`computer-bad`,children:t?.helper.installed?t.helper.path:e(`未安装(先下载 Agent Computer.app)`,`Not installed (download Agent Computer.app first)`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`运行`,`Running`)}),(0,Q.jsx)(`span`,{className:t?.running?`computer-ok`:`computer-bad`,children:t?.running?`${e(`已连接`,`Connected`)}${t.helperVersion?` · ${t.helperVersion}`:``}`:t?.error??e(`未连接`,`Not connected`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`辅助功能权限`,`Accessibility`)}),(0,Q.jsx)(`span`,{className:t?.permissions?.accessibility?`computer-ok`:`computer-bad`,children:t?.permissions?.accessibility?e(`已授予`,`Granted`):e(`未授予`,`Not granted`)})]}),(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`span`,{children:e(`屏幕录制权限`,`Screen recording`)}),(0,Q.jsx)(`span`,{className:t?.permissions?.screenRecording?`computer-ok`:`computer-bad`,children:t?.permissions?.screenRecording?e(`已授予`,`Granted`):e(`未授予`,`Not granted`)})]})]}),t&&t.running&&!N?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`还缺权限。点下面的按钮会直接跳到系统设置里对应的那一页;勾上之后回到这里点「刷新」。`,`Some permissions are missing. The buttons below open the right pane in System Settings; tick the app, then hit Refresh here.`)}),(0,Q.jsxs)(`div`,{className:`computer-install-actions`,children:[t.permissions?.accessibility?null:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(async()=>{await IC(),await LC(`accessibility`),await w()}),children:e(`打开辅助功能设置`,`Open Accessibility settings`)}),t.permissions?.screenRecording?null:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(async()=>{await IC(),await LC(`screen`),await w()}),children:e(`打开屏幕录制设置`,`Open Screen Recording settings`)}),(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,onClick:()=>void T(w),children:e(`刷新`,`Refresh`)})]}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`屏幕录制勾上后如果仍显示未授予,把 PopAgent 完全退出再打开(macOS 要重启负责录屏的那个进程才认)。`,`If Screen Recording still shows as not granted, quit PopAgent completely and reopen it (macOS re-reads that grant on process start).`)})]}):null]}),r?(0,Q.jsxs)(`section`,{className:`computer-section`,"aria-label":e(`设置`,`Settings`),children:[(0,Q.jsx)(`h3`,{children:e(`设置`,`Settings`)}),(0,Q.jsxs)(`div`,{className:`computer-block`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:(0,Q.jsx)(`strong`,{children:e(`屏幕上显示什么`,`What shows on screen`)})}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`AI 操作时可以显示三种提示,都可以单独关掉:右下角的小浮窗、屏幕边缘的水印、跟随光标的蓝色指针。`,`Three optional indicators while the AI works: the preview window, an edge watermark, and a pointer ring following the cursor.`)})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`实时预览浮窗(能看到它在操作什么)`,`Live preview window`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.previewEnabled,disabled:y,onChange:()=>void D({previewEnabled:!r.previewEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`AI 操作水印(屏幕边缘 + 顶部提示)`,`AI activity watermark`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.watermarkEnabled,disabled:y,onChange:()=>void D({watermarkEnabled:!r.watermarkEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`agent 的指针动画(跟随光标的蓝圈)`,`Agent pointer ring`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.pointerEnabled,disabled:y,onChange:()=>void D({pointerEnabled:!r.pointerEnabled})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`需要前台的步骤可以短暂借用前台`,`Briefly borrow the foreground when needed`)}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.borrowFront,disabled:y,onChange:()=>void D({borrowFront:!r.borrowFront})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsxs)(`span`,{className:`computer-row-label`,children:[(0,Q.jsx)(`strong`,{children:e(`允许在你空闲时激活目标应用`,`Allow activating the target app while you are idle`)}),(0,Q.jsx)(`span`,{className:`computer-hint`,children:e(`默认关。开启后 agent 可能把窗口切到最前面。`,`Off by default. When on, the agent may bring the window to the front.`)})]}),(0,Q.jsx)(`input`,{type:`checkbox`,checked:r.activateTarget,disabled:y,onChange:()=>void D({activateTarget:!r.activateTarget})})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`指针速度`,`Pointer speed`)}),(0,Q.jsx)(`input`,{type:`number`,className:`computer-num`,min:kC.min,max:kC.max,step:.25,value:h,disabled:y,onChange:e=>g(e.target.value),onBlur:k,onKeyDown:e=>e.key===`Enter`&&k()})]}),(0,Q.jsxs)(`label`,{className:`computer-row`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:e(`逐键输入间隔(毫秒)`,`Delay between typed keys (ms)`)}),(0,Q.jsx)(`input`,{type:`number`,className:`computer-num`,min:AC.min,max:AC.max,step:1,value:_,disabled:y,onChange:e=>v(e.target.value),onBlur:A,onKeyDown:e=>e.key===`Enter`&&A()})]}),(0,Q.jsxs)(`div`,{className:`computer-block`,children:[(0,Q.jsx)(`span`,{className:`computer-row-label`,children:(0,Q.jsx)(`strong`,{children:e(`解除保护的应用(bundle id,一行一个)`,`Unprotected apps (bundle id, one per line)`)})}),(0,Q.jsx)(`p`,{className:`computer-hint`,children:e(`默认保护系统认证、系统设置等。这里加入的应用会被允许操作。密码管理器始终需要你在 helper 里确认,不受此处影响。`,`System authentication and System Settings stay protected by default. Apps listed here become allowed. Password managers still need your confirmation in the helper.`)}),(0,Q.jsxs)(`div`,{className:`computer-app-search`,children:[(0,Q.jsx)(`input`,{type:`text`,className:`computer-app-input`,value:s,disabled:y,placeholder:e(`搜索应用名,比如「微信」,点候选直接加进去`,`Search an app, e.g. "WeChat"`),onChange:e=>{c(e.target.value),f(!0)},onFocus:()=>f(!0),onBlur:()=>setTimeout(()=>f(!1),150),onKeyDown:e=>{if(e.key===`ArrowDown`)e.preventDefault(),f(!0),m(e=>Math.min(e+1,l.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),m(e=>Math.max(e-1,0));else if(e.key===`Enter`){let t=l[p];t&&(e.preventDefault(),E(t.bundleId))}else e.key===`Escape`&&f(!1)}}),d&&l.length>0?(0,Q.jsx)(`ul`,{className:`computer-app-options`,role:`listbox`,children:l.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{type:`button`,className:`computer-app-option${t===p?` is-active`:``}`,role:`option`,"aria-selected":t===p,onMouseDown:t=>{t.preventDefault(),E(e.bundleId)},children:[(0,Q.jsx)(`span`,{className:`computer-app-name`,children:e.name}),(0,Q.jsx)(`small`,{children:e.bundleId})]})},e.bundleId))}):null]}),(0,Q.jsx)(`textarea`,{className:`computer-apps`,rows:4,value:a,disabled:y,placeholder:`com.apple.Notes`,onChange:e=>o(e.target.value)}),(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`computer-btn`,disabled:y,onClick:j,children:e(`保存名单`,`Save list`)})})]})]}):null]})}function BC(e,t,n,r){let i=e.filter(e=>e!==t),a=i.length;for(let e=0;e<i.length;e+=1){let t=r.get(i[e]);if(t&&n<t.left+t.width/2){a=e;break}}return a}function VC(e,t,n){let r=new Map,i=1/0;for(let n of e){let e=t.get(n);e&&(i=Math.min(i,e.left))}if(!Number.isFinite(i))return r;for(let a of e){let e=t.get(a);e&&(r.set(a,i),i+=e.width+n)}return r}var HC=`pop-agent.panel-order.v1`,UC=`pop-agent:panel-order`,WC=[`voice`,`skills`,`push`,`plugins`,`mcp`,`models`,`agents`,`cron`,`computer`,`settings`],GC=new Set(WC);function KC(e){let t=Array.isArray(e)?e:[],n=t.filter((e,n)=>typeof e==`string`&&GC.has(e)&&t.indexOf(e)===n);return[...n,...WC.filter(e=>!n.includes(e))]}function qC(e){if(!e)return[...WC];try{return KC(JSON.parse(e))}catch{return[...WC]}}function JC(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function YC(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(Math.round(n),r.length)),a=[...r];return a.splice(i,0,t),a}function XC(){let[e,t]=(0,C.useState)(()=>qC(Yr(HC)));return(0,C.useEffect)(()=>{let e=e=>{let n=KC(e);t(e=>JC(e,n)?e:n)},n=t=>e(t.detail),r=t=>{t.key===HC&&e(qC(t.newValue))};return window.addEventListener(UC,n),window.addEventListener(`storage`,r),()=>{window.removeEventListener(UC,n),window.removeEventListener(`storage`,r)}},[]),[e,(0,C.useCallback)(e=>{let n=KC(e);t(e=>JC(e,n)?e:n),Xr(HC,JSON.stringify(n)),window.dispatchEvent(new CustomEvent(UC,{detail:n}))},[])]}var ZC=5,QC=180,$C=`is-panel-tab-dragging`;function ew({order:e,active:t,label:n,onSelect:r,onOrderChange:i,onHeadPointerDown:a,onHeadDoubleClick:o,headTitle:s}){let c=Y(),l=(0,C.useRef)(null),[u,d]=(0,C.useState)(null),f=(0,C.useRef)(null),p=(0,C.useRef)(null),m=(0,C.useRef)(null),h=(0,C.useRef)(!1),g=(0,C.useRef)(null),_=e=>{f.current=e,d(e)};(0,C.useEffect)(()=>()=>{p.current?.(),m.current!==null&&window.clearTimeout(m.current),g.current!==null&&window.clearTimeout(g.current),document.documentElement.classList.remove($C)},[]);let v=(t,n)=>{if(t.stopPropagation(),t.button!==0||f.current||Tf())return;let r=t.pointerId,a=t.currentTarget,o=[...e],s=t.clientX,c=t.clientY,u=s,d=c,v=!1,y=!1,b=null,x=o,S=e=>{JC(x,e)||(x=e,i(e))},C=()=>{if(!v||y)return;let e=f.current,t=e?.boxes.get(n);if(!e||!t)return;let r=u-s,i=t.left+t.width/2+r,a=BC(o,n,i,e.boxes),c=YC(o,n,a);_({...e,dx:r,previewOrder:c,phase:`dragging`}),S(c)},w=e=>{if(y)return;y=!0,A();let t=f.current;if(!t)return;let n=e?t.baseOrder:t.previewOrder;S(n),_({...t,previewOrder:n,phase:`settling`}),h.current=!0,g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{h.current=!1},400);let r=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;m.current=window.setTimeout(()=>{m.current=null,_(null)},r?0:QC)},T=e=>{if(!(e.pointerId!==r||y)){if(u=e.clientX,d=e.clientY,!v){let e=u-s,t=d-c;if(Math.max(Math.abs(e),Math.abs(t))<ZC)return;if(Math.abs(t)>Math.abs(e)){A();return}let i=l.current;if(!i)return;let f=new Map;for(let e of o){let t=i.querySelector(`[data-panel-key="${e}"]`);if(!t)continue;let n=t.getBoundingClientRect();f.set(e,{left:n.left,width:n.width})}if(f.size!==o.length){A();return}v=!0;try{a.setPointerCapture(r)}catch{}document.documentElement.classList.add($C);let p=Number.parseFloat(window.getComputedStyle(i).columnGap)||0;_({key:n,baseOrder:o,previewOrder:o,boxes:f,gap:p,dx:e,phase:`dragging`})}e.preventDefault(),b===null&&(b=window.requestAnimationFrame(()=>{b=null,C()}))}},E=e=>{e.pointerId!==r||y||(v?(e.preventDefault(),b!==null&&window.cancelAnimationFrame(b),b=null,C(),w(!1)):A())},D=e=>{e.pointerId!==r||y||(v?w(!0):A())},O=e=>{e.key===`Escape`&&(v?(e.preventDefault(),w(!0)):A())},k=()=>{v?w(!0):A()};function A(){document.removeEventListener(`pointermove`,T),document.removeEventListener(`pointerup`,E),document.removeEventListener(`pointercancel`,D),document.removeEventListener(`keydown`,O),window.removeEventListener(`blur`,k),b!==null&&window.cancelAnimationFrame(b),b=null,document.documentElement.classList.remove($C);try{a.hasPointerCapture(r)&&a.releasePointerCapture(r)}catch{}p.current===A&&(p.current=null)}p.current?.(),p.current=A,document.addEventListener(`pointermove`,T,{passive:!1}),document.addEventListener(`pointerup`,E),document.addEventListener(`pointercancel`,D),document.addEventListener(`keydown`,O),window.addEventListener(`blur`,k)},y=u?.baseOrder??e,b=u?VC(u.previewOrder,u.boxes,u.gap):null,x=e=>{if(!u||!b)return;let t=u.boxes.get(e),n=b.get(e);if(t&&n!==void 0)return`translate3d(${e===u.key&&u.phase===`dragging`?u.dx:n-t.left}px, 0, 0)`};return(0,Q.jsx)(`div`,{ref:l,className:`big-modal-head`,role:`tablist`,"aria-label":c(`工作台面板`),onPointerDown:a,onDoubleClick:o,title:s,children:y.map(e=>{let i=u?.key===e,a=[`big-tab`,t===e?`big-tab-on`:``,u?`big-tab-reordering`:``,i&&u.phase===`dragging`?`big-tab-dragging`:``,i&&u.phase===`settling`?`big-tab-settling`:``].filter(Boolean).join(` `);return(0,Q.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":t===e,"data-panel-key":e,className:a,style:{transform:x(e)},draggable:!1,title:`${n(e)} · ${c(`拖动排序`,`Drag to reorder`)}`,onPointerDown:t=>v(t,e),onClick:()=>{h.current||r(e)},children:[(0,Q.jsx)(`span`,{className:`big-tab-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:e})}),n(e)]},e)})})}var tw=180;function nw(e){let t=new Map;for(let n of Array.from(e.children)){if(!(n instanceof HTMLElement))continue;let e=n.dataset.panelKey;e&&t.set(e,n.offsetLeft)}return t}function rw(e){let t=window.getComputedStyle(e).transform;if(!t||t===`none`)return 0;try{return new DOMMatrixReadOnly(t).m41}catch{return 0}}function iw({order:e,className:t,children:n}){let r=(0,C.useRef)(null),i=(0,C.useRef)(new Map),a=(0,C.useRef)(null),o=e.join(`|`);return(0,C.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let t=new ResizeObserver(()=>{i.current=nw(e)});a.current=t,t.observe(e);for(let n of Array.from(e.children))t.observe(n);return()=>{t.disconnect(),a.current=null}},[]),(0,C.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let t=new Map,n=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;for(let r of Array.from(e.children)){if(!(r instanceof HTMLElement))continue;a.current?.observe(r);let e=r.dataset.panelKey;if(!e)continue;let o=r.offsetLeft;t.set(e,o);let s=i.current.get(e);if(s===void 0)continue;let c=rw(r);for(let e of r.getAnimations())e.cancel();let l=s+c-o;!n&&Math.abs(l)>.5&&r.animate([{transform:`translate3d(${l}px, 0, 0)`},{transform:`translate3d(0, 0, 0)`}],{duration:tw,easing:`cubic-bezier(0.2, 0, 0, 1)`})}i.current=t},[o]),(0,Q.jsx)(`div`,{ref:r,className:t,children:n})}var aw=`pop-agent:big-modal-pos:v1`,ow=4,sw=()=>({width:window.innerWidth,height:window.innerHeight}),cw=(e,t,n)=>Math.min(Math.max(e,t),n);function lw(e,t,n,r){let i=(n-t)/2;return(r&&t<=n?cw(e,-i,n-t-i):cw(e,140-t-i,n-140-i))+0}function uw(e,t,n){return{x:lw(e.x,t.width,n.width,!0),y:lw(e.y,t.height,n.height,!0)}}function dw(e,t,n){return{x:lw(e.x,t.width,n.width,!1),y:lw(e.y,t.height,n.height,!1)}}function fw(e){if(!e)return{x:0,y:0};try{let t=JSON.parse(e);if(typeof t!=`object`||!t)return{x:0,y:0};let n=t;return{x:typeof n.x==`number`&&Number.isFinite(n.x)?n.x:0,y:typeof n.y==`number`&&Number.isFinite(n.y)?n.y:0}}catch{return{x:0,y:0}}}function pw(e){let[t,n]=(0,C.useState)(Tf),[r,i]=(0,C.useState)(()=>fw(localStorage.getItem(aw))),a=(0,C.useRef)(r);a.current=r,(0,C.useEffect)(()=>{let t=()=>{n(Tf()),e.size&&i(t=>uw(t,e.size,sw()))};return window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[e.size]),(0,C.useEffect)(()=>{e.size&&i(t=>uw(t,e.size,sw()))},[e.size]);let o=(0,C.useCallback)(t=>{if(t.button!==0||!e.size)return;let n=e.size,r=t.clientX,o=t.clientY,s=a.current,c=!1,l=e=>{let t=e.clientX-r,a=e.clientY-o;!c&&Math.abs(t)<ow&&Math.abs(a)<ow||(c||(c=!0,document.body.style.userSelect=`none`,document.documentElement.classList.add(`is-modal-moving`)),e.preventDefault(),i(dw({x:s.x+t,y:s.y+a},n,sw())))},u=()=>{if(document.removeEventListener(`pointermove`,l),document.removeEventListener(`pointerup`,u),document.body.style.userSelect=``,document.documentElement.classList.remove(`is-modal-moving`),!c)return;let e=e=>{e.stopPropagation(),e.preventDefault()};document.addEventListener(`click`,e,{capture:!0,once:!0}),window.setTimeout(()=>document.removeEventListener(`click`,e,{capture:!0}),400);try{localStorage.setItem(aw,JSON.stringify(a.current))}catch{}};document.addEventListener(`pointermove`,l),document.addEventListener(`pointerup`,u)},[e.size]),s=(0,C.useCallback)(()=>{try{localStorage.removeItem(aw)}catch{}i({x:0,y:0})},[]),c=(0,C.useCallback)(()=>{let t=e.size;if(!t)return;let n=uw(a.current,t,sw());a.current=n,i(n)},[e.size]),l=(0,C.useRef)(r),u=(0,C.useCallback)(()=>(l.current=a.current,l.current),[]),d=(0,C.useCallback)(e=>{let t={x:l.current.x+e.x,y:l.current.y+e.y};a.current=t,i(t)},[]),f=(0,C.useCallback)(()=>{try{localStorage.setItem(aw,JSON.stringify(a.current))}catch{}},[]);return{style:t?void 0:{transform:`translate(${Math.round(r.x)}px, ${Math.round(r.y)}px)`},start:o,reset:s,reclamp:c,beginResize:u,shiftBy:d,commitResize:f}}var mw=`pop-agent:big-modal-size:v4`,hw=[`pop-agent:big-modal-size`,`pop-agent:big-modal-size:v2`,`pop-agent:big-modal-size:v3`],gw=620,_w=340,vw=()=>({width:window.innerWidth,height:window.innerHeight}),yw=(e,t,n)=>Math.min(Math.max(e,t),n);function bw(e){return{minWidth:gw,minHeight:_w,maxWidth:Math.max(gw,e.width-32),maxHeight:Math.max(_w,e.height-32)}}function xw(e){let t=bw(e);return{width:Math.round(t.maxWidth),height:Math.round(t.maxHeight)}}function Sw(e,t){let n=bw(t),r=Number.isFinite(e.width)?e.width:xw(t).width,i=Number.isFinite(e.height)?e.height:xw(t).height;return{width:Math.round(yw(r,n.minWidth,n.maxWidth)),height:Math.round(yw(i,n.minHeight,n.maxHeight))}}function Cw(e){let t=e.corner===`se`||e.corner===`ne`?1:-1,n=e.corner===`se`||e.corner===`sw`?1:-1,r=Sw({width:e.start.width+t*e.dx,height:e.start.height+n*e.dy},e.view),i=uw({x:e.pos.x+t*(r.width-e.start.width)/2,y:e.pos.y+n*(r.height-e.start.height)/2},r,e.view),a=Math.round(i.x-e.pos.x),o=Math.round(i.y-e.pos.y);return{size:r,shift:{x:a===0?0:a,y:o===0?0:o}}}function ww(e,t){if(!e)return xw(t);try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return xw(t);let r=n;return typeof r.width!=`number`||typeof r.height!=`number`||!Number.isFinite(r.width)||!Number.isFinite(r.height)?xw(t):Sw({width:r.width,height:r.height},t)}catch{return xw(t)}}function Tw(e){let t=e?.anchor,[n,r]=(0,C.useState)(()=>{for(let e of hw)localStorage.removeItem(e);return ww(localStorage.getItem(mw),vw())}),[i,a]=(0,C.useState)(Tf),[o,s]=(0,C.useState)(()=>localStorage.getItem(mw)!==null);(0,C.useEffect)(()=>{o&&localStorage.setItem(mw,JSON.stringify(n))},[o,n]),(0,C.useEffect)(()=>{let e=()=>{a(Tf()),r(e=>o?Sw(e,vw()):xw(vw()))};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[o]);let c=(0,C.useCallback)((e,i=`se`)=>{e.preventDefault(),s(!0);let a=t?.current??null,o=a?.begin()??{x:0,y:0},c=e.clientX,l=e.clientY,u=n,d=e=>{let{size:t,shift:n}=Cw({start:u,pos:o,dx:e.clientX-c,dy:e.clientY-l,corner:i,view:vw()});r(t),a?.shift(n)},f=()=>{document.removeEventListener(`pointermove`,d),document.removeEventListener(`pointerup`,f),a?.commit()};document.addEventListener(`pointermove`,d),document.addEventListener(`pointerup`,f)},[n,t]),l=(0,C.useCallback)(()=>{localStorage.removeItem(mw),s(!1),r(xw(vw()))},[]);return{size:n,style:i?void 0:{width:`${n.width}px`,height:`${n.height}px`},start:c,reset:l}}var Ew={models:`模型`,skills:`技能`,push:`推送`,plugins:`插件`,mcp:`MCP`,voice:`语音`,agents:`子代理`,cron:`定时任务`,computer:`电脑控制`,settings:`设置`},Dw={models:`Models`,skills:`Skills`,push:`Push`,plugins:`Plugins`,mcp:`MCP`,voice:`Voice`,agents:`Subagents`,cron:`Cron`,computer:`Computer`,settings:`Settings`},Ow=[`nw`,`ne`,`sw`,`se`],kw=e=>e===`error`?12e3:e===`warn`?8e3:5e3;function Aw({initialPanel:e=null,variant:t=`full`,placement:n=`footer`,items:r,panel:i,onPanelChange:a,leadingAction:o}={}){let s=Y(),[c,l]=XC(),[u,d]=(0,C.useState)(e),f=i===void 0?u:i,p=e=>{a&&a(e),i===void 0&&d(e)},m=(0,C.useRef)(null),h=Tw({anchor:m}),g=pw({size:h.size});m.current={begin:g.beginResize,shift:g.shiftBy,commit:g.commitResize};let _=g.reclamp;(0,C.useEffect)(()=>{f&&_()},[f,_]);let v=Ro(e=>e.snapshot),y=Ro(e=>e.lastError),b=(0,C.useRef)(new Set),x=(0,C.useRef)(y?.text??null),[S,w]=(0,C.useState)(null);(0,C.useEffect)(()=>{b.current=new Set((v?.notices??[]).map(e=>e.id)),x.current=y?.text??null,w(null)},[f]),(0,C.useEffect)(()=>{let e=(v?.notices??[]).filter(e=>!b.current.has(e.id));if(e.length===0)return;for(let t of e)b.current.add(t.id);let t=e[e.length-1];t&&w({key:`notice-${t.id}`,text:t.text,level:t.level,at:Date.now()})},[v?.notices]),(0,C.useEffect)(()=>{let e=y?.text??null;e&&e!==x.current&&(x.current=e,w({key:`error-${Date.now()}`,text:e,level:`error`,at:Date.now()}))},[y]),(0,C.useEffect)(()=>{if(!S)return;let e=setTimeout(()=>{w(e=>e&&Date.now()-e.at>=kw(e.level)?null:e)},kw(S.level));return()=>clearTimeout(e)},[S]);let T=c.filter(e=>!r||r.includes(e)),[E]=bp(Dr,Or),D=n===`appbar`,O=!D||E.label,k=!D||E.icon||!E.label,A=(e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-panel-key":e,title:t,className:`side-foot-btn side-foot-btn-${e}${f===e?` side-foot-btn-on`:``}`,onClick:()=>p(f===e?null:e),children:[k?(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(nx,{name:e})}):null,O?(0,Q.jsx)(`span`,{className:`side-foot-label`,children:t}):null]},e),j=(0,C.useRef)(!1);return(0,Q.jsxs)(`div`,{className:n===`appbar`?`appbar-menu`:`side-foot`,children:[t===`full`?(0,Q.jsxs)(iw,{className:`side-foot-row`,order:T,children:[o?.({showIcon:k,showLabel:O}),T.map(e=>A(e,s(Ew[e],Dw[e])))]}):null,f?(0,Ko.createPortal)((0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":s(`工作台面板`),onMouseDown:e=>{j.current=e.target===e.currentTarget},onClick:e=>{let t=j.current;j.current=!1,t&&e.target===e.currentTarget&&p(null)},children:(0,Q.jsxs)(`div`,{className:`modal big-modal`,style:{...h.style,...g.style},onPointerDown:e=>{e.target===e.currentTarget&&g.start(e)},children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny big-modal-close`,onClick:()=>p(null),title:s(`关闭`,`Close`),children:`✕`}),(0,Q.jsx)(ew,{order:c,active:f,label:e=>s(Ew[e],Dw[e]),onSelect:p,onOrderChange:l,onHeadPointerDown:g.start,onHeadDoubleClick:g.reset,headTitle:s(`拖动 Tab 排序;拖动空白处移动面板(双击复位)`,`Drag tabs to reorder; drag empty space to move the panel (double-click to reset)`)}),S?(0,Q.jsx)(`div`,{className:`modal-notices`,children:(0,Q.jsx)(`div`,{className:`notice${S.level===`error`?` notice-error`:S.level===`warn`?` notice-warn`:``}`,children:S.text},S.key)}):null,(0,Q.jsxs)(`div`,{className:`big-modal-body`,children:[f===`models`?(0,Q.jsx)(Cy,{}):null,f===`skills`?(0,Q.jsx)(fS,{}):null,f===`push`?(0,Q.jsx)(ZS,{}):null,f===`plugins`?(v?.engine??`pi`)===`pi`?(0,Q.jsx)(PS,{}):(0,Q.jsx)(ES,{engine:v?.engine??``}):null,f===`mcp`?(v?.engine??`pi`)===`pi`?(0,Q.jsx)(KS,{}):(0,Q.jsx)(wS,{engine:v?.engine??``}):null,f===`voice`?(0,Q.jsx)(eC,{}):null,f===`agents`?(0,Q.jsx)(cC,{}):null,f===`cron`?(0,Q.jsx)(OC,{}):null,f===`computer`?(0,Q.jsx)(zC,{}):null,f===`settings`?(0,Q.jsx)(Mx,{}):null]}),Ow.map(e=>(0,Q.jsx)(`div`,{className:`modal-resize modal-resize-${e}`,role:`separator`,"aria-label":s(`调整面板大小`),title:s(`拖动调整窗口大小(双击复位)`),onPointerDown:t=>h.start(t,e),onDoubleClick:()=>{h.reset(),g.reset()}},e))]})}),document.body):null]})}function jw({variant:e=`appbar`}){let t=Y();return e===`icon`?(0,Q.jsx)(`button`,{type:`button`,className:`newchat-icon-btn`,onClick:()=>Mo(),title:t(`新建会话`,`New session`),"aria-label":t(`新建会话`,`New session`),children:(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`💬`})}):(0,Q.jsxs)(`button`,{type:`button`,className:`newchat-pill newchat-pill-${e}`,onClick:()=>Mo(),title:t(`新建会话`,`New session`),children:[(0,Q.jsx)(`span`,{className:`newchat-pill-icon`,"aria-hidden":`true`,children:`💬`}),(0,Q.jsx)(`span`,{className:`newchat-pill-label`,children:t(`新会话`,`New session`)})]})}function Mw({onClick:e,showIcon:t=!0,showLabel:n=!0}){let r=Y();return(0,Q.jsxs)(`button`,{type:`button`,className:`side-foot-btn tempchat-btn`,onClick:e,title:r(`临时会话:在右侧新开一条聊天(不落盘,关掉就没了)`,`Temp session: start a separate chat on the right (not saved, gone on close)`),children:[t?(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:`💬`}):null,n?(0,Q.jsx)(`span`,{className:`side-foot-label`,children:r(`临时会话`,`Temp session`)}):null]})}function Nw(){let e=Y(),t=yc(),[n]=xc(),r=oc();if((0,C.useEffect)(()=>{if(!t)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),_c())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[t]),!t)return null;let i=bc(n,r),a=cc(n.cheatSheet,r);return(0,Q.jsx)(`div`,{className:`shortcut-sheet-backdrop`,onClick:e=>{e.target===e.currentTarget&&_c()},children:(0,Q.jsxs)(`div`,{className:`shortcut-sheet`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`快捷键速查表`,`Shortcuts`),children:[(0,Q.jsxs)(`div`,{className:`shortcut-sheet-head`,children:[(0,Q.jsx)(`span`,{className:`shortcut-sheet-title`,children:e(`快捷键`,`Shortcuts`)}),(0,Q.jsx)(`span`,{className:`shortcut-sheet-sub`,children:e(`设置 → 快捷键 里可以改;留空就是不用`,`Change them in Settings → Shortcuts; leave one empty to disable it`)}),(0,Q.jsx)(`button`,{type:`button`,className:`shortcut-sheet-close`,onClick:_c,"aria-label":e(`关闭速查表`,`Close the cheat sheet`),title:e(`关闭(Esc)`,`Close (Esc)`),children:`✕`})]}),(0,Q.jsx)(`div`,{className:`shortcut-sheet-grid`,children:i.map(t=>(0,Q.jsxs)(`div`,{className:`sheet-row${t.combo?``:` sheet-row-off`}`,children:[(0,Q.jsx)(`span`,{className:`sheet-label`,children:e(t.label,t.labelEn)}),t.combo?(0,Q.jsx)(`kbd`,{className:`sheet-kbd`,children:t.combo}):(0,Q.jsx)(`span`,{className:`sheet-unbound`,children:e(`未设置`,`Unbound`)})]},t.id))}),(0,Q.jsxs)(`div`,{className:`shortcut-sheet-foot`,children:[e(`Esc 关闭`,`Esc to close`),a?e(`;再按一次 ${a} 也可以关`,`; press ${a} again to close`):``]})]})})}var Pw=[{id:`deepseek`,label:`DeepSeek`,labelEn:`DeepSeek`,provider:`deepseek`,baseUrl:`https://api.deepseek.com`,api:`openai-completions`,model:`deepseek-chat`},{id:`openai`,label:`OpenAI`,labelEn:`OpenAI`,provider:`openai`,baseUrl:`https://api.openai.com/v1`,api:`openai-completions`,model:`gpt-4o-mini`},{id:`anthropic`,label:`Anthropic`,labelEn:`Anthropic`,provider:`anthropic`,baseUrl:`https://api.anthropic.com`,api:`anthropic-messages`,model:`claude-opus-4-6`},{id:`custom`,label:`自定义`,labelEn:`Custom`,provider:``,baseUrl:``,api:`openai-completions`,model:``}],Fw=/^[a-z0-9][a-z0-9-]{1,30}$/,Iw=8,Lw=[];function Rw(e,t){if(e.name===`pi`)return`builtin`;if(t===null)return`checking`;let n=t[e.name];return!n||n.installed?`installed`:n.installable?`missing`:`manual`}function zw({onDone:e}){let t=Y(),n=Zv(),r=Ro(e=>e.snapshot),i=r?.engines??Lw,[a,o]=(0,C.useState)(1),[s,c]=(0,C.useState)(`pi`),[l,u]=(0,C.useState)(`deepseek`),[d,f]=(0,C.useState)(`deepseek`),[p,m]=(0,C.useState)(`https://api.deepseek.com`),[h,g]=(0,C.useState)(``),[_,v]=(0,C.useState)(`deepseek-chat`),[y,b]=(0,C.useState)(r?.files?.root??``),[x,S]=(0,C.useState)(null),[w,T]=(0,C.useState)(null);(0,C.useEffect)(()=>{let e=!1;return fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(t=>{if(e)return;let n={};for(let e of t?.engines??[])n[e.name]={installed:e.installed,installable:e.installable!==!1};T(n)}).catch(()=>{e||T({})}),()=>{e=!0}},[]),(0,C.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let E=[t(`选择引擎`,`Choose engine`),t(`配置模型`,`Configure model`),t(`开始会话`,`Start a session`)],D=e=>e===`builtin`?t(`内置`,`Built-in`):e===`checking`?t(`检测中…`,`Checking…`):e===`installed`?t(`已安装`,`Installed`):e===`missing`?t(`未安装`,`Not installed`):t(`需要安装`,`Needs install`),O=()=>{S(null),tu(s),o(2)},k=e=>{let t=Pw.find(t=>t.id===e);t&&(u(e),f(t.provider),m(t.baseUrl),v(t.model),g(``),S(null))},A=()=>{let e=d.trim(),n=p.trim(),i=_.trim(),a=h.trim();a===``?S(t(`先填 API Key:空 key 提交上去也用不了。`,`Add an API key first — an empty one will not work.`)):a.length<Iw?S(t(`API Key 至少 ${Iw} 位。`,`The API key needs at least ${Iw} characters.`)):Fw.test(e)?n===``||!/^https?:\/\//i.test(n)?S(t(`baseUrl 要以 http:// 或 https:// 开头。`,`baseUrl must start with http:// or https://.`)):i===``?S(t(`填一个模型 id,例如 deepseek-chat。`,`Enter a model id, e.g. deepseek-chat.`)):(yu({provider:e,baseUrl:n,api:Pw.find(e=>e.id===l)?.api??`openai-completions`,apiKey:a,models:[{id:i}]}),lu(`${e}/${i}`,r?.active.conversationId??null),S(null),o(3)):S(t(`provider id 只能用小写字母、数字和 -,2–31 位(会作为 provider/model 的前缀)。`,`The provider id must be 2–31 chars of lowercase letters, digits or “-” (it prefixes provider/model).`))},j=()=>{let t=y.trim();Mo(t===``?null:t),e()},M=Pw.find(e=>e.id===l)?.api??`openai-completions`;return(0,Q.jsx)(`div`,{className:`first-run-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`first-run-title`,children:(0,Q.jsxs)(`div`,{className:`first-run-card`,children:[(0,Q.jsxs)(`div`,{className:`first-run-head`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{className:`first-run-title`,id:`first-run-title`,children:t(`欢迎使用 ${n.name}`,`Welcome to ${n.name}`)}),(0,Q.jsx)(`p`,{className:`first-run-subtitle`,children:t(`三步就能开始:选引擎、配一个模型、建第一条会话。`,`Three steps to get going: pick an engine, configure a model, start your first session.`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny first-run-skip`,onClick:e,children:t(`跳过`,`Skip`)})]}),(0,Q.jsx)(`ol`,{className:`first-run-steps`,children:E.map((e,t)=>{let n=t+1;return(0,Q.jsxs)(`li`,{className:`first-run-step${a===n?` first-run-step-on`:``}${a>n?` first-run-step-done`:``}`,children:[(0,Q.jsx)(`span`,{className:`first-run-step-index`,"aria-hidden":`true`,children:n}),(0,Q.jsx)(`span`,{children:e})]},e)})}),(0,Q.jsx)(`div`,{className:`first-run-body`,children:a===1?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`引擎决定谁来干活。没装的也能选:切过去之后界面会给你安装入口。`,`Pick the agent that does the work. You can choose one that is not installed — the app will offer to install it.`)}),(0,Q.jsx)(`div`,{className:`first-run-engines`,children:i.length===0?(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`引擎清单还没到,稍等一下。`,`The engine list has not arrived yet — one moment.`)}):i.map(e=>{let n=s===e.name,r=Rw(e,w),i=r===`installed`||r===`builtin`?` first-run-engine-state-on`:r===`missing`||r===`manual`?` first-run-engine-state-warn`:``;return(0,Q.jsxs)(`button`,{type:`button`,className:`first-run-engine${n?` first-run-engine-on`:``}`,"aria-pressed":n,onClick:()=>{c(e.name),S(null)},children:[(0,Q.jsxs)(`span`,{className:`first-run-engine-top`,children:[(0,Q.jsx)(`span`,{className:`first-run-engine-name`,children:t(e.label)}),(0,Q.jsx)(`span`,{className:`first-run-engine-state${i}`,children:D(r)})]}),e.description?(0,Q.jsx)(`span`,{className:`first-run-engine-desc`,children:t(e.description)}):null,r===`missing`?(0,Q.jsx)(`span`,{className:`first-run-engine-hint`,children:t(`还没装:可以继续,切过去后按提示一键安装。`,`Not installed: continue, then install it with one click when prompted.`)}):r===`manual`?(0,Q.jsx)(`span`,{className:`first-run-engine-hint`,children:t(`还没装且没有一键安装包:要先自己把它装好。`,`Not installed and no one-click package: install it yourself first.`)}):null]},e.name)})})]}):a===2?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`first-run-presets`,role:`group`,"aria-label":t(`服务商`,`Provider`),children:Pw.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`first-run-preset${l===e.id?` first-run-preset-on`:``}`,"aria-pressed":l===e.id,onClick:()=>k(e.id),children:t(e.label,e.labelEn)},e.id))}),s===`pi`?null:(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`当前选的不是 pi:它的模型由引擎自己管理。这里填的 provider 会写进 pi 的配置,之后切回 pi 时直接可用。`,`The selected engine is not pi: it manages its own models. This provider is written to pi's config and will be ready when you switch back.`)}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`provider(作为 provider/model 前缀)`,`provider (prefix of provider/model)`)}),(0,Q.jsx)(`input`,{value:d,readOnly:l!==`custom`,onChange:e=>f(e.target.value),placeholder:`my-endpoint`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:`base url`}),(0,Q.jsx)(`input`,{value:p,onChange:e=>m(e.target.value),placeholder:`https://api.example.com/v1`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:`API Key`}),(0,Q.jsx)(`input`,{type:`password`,value:h,onChange:e=>g(e.target.value),placeholder:`sk-…`,autoComplete:`off`})]}),(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`模型 id`,`Model id`)}),(0,Q.jsx)(`input`,{value:_,onChange:e=>v(e.target.value),placeholder:t(`例如 deepseek-chat`,`e.g. deepseek-chat`),autoComplete:`off`})]}),(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`接口形态:${M}(自定义也按这个开局,之后可在设置里改)。key 只写进本机配置,不会回显。`,`API shape: ${M} (custom starts with this too; change it later in Settings). The key is stored locally and never shown again.`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`first-run-field`,children:[(0,Q.jsx)(`span`,{children:t(`工作区路径`,`Workspace path`)}),(0,Q.jsx)(`input`,{value:y,onChange:e=>b(e.target.value),placeholder:t(`留空用默认工作区`,`Leave empty for the default workspace`),autoComplete:`off`})]}),(0,Q.jsx)(`div`,{className:`first-run-hint`,children:t(`留空用默认工作区。填了的话,这条会话就在那个目录里跑。`,`Leave it empty to use the default workspace. Otherwise the session runs in the directory you enter.`)})]})}),x?(0,Q.jsx)(`div`,{className:`first-run-error`,role:`alert`,children:x}):null,(0,Q.jsxs)(`div`,{className:`first-run-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn`,disabled:a===1,onClick:()=>{S(null),o(e=>e>1?e-1:e)},children:t(`上一步`,`Back`)}),(0,Q.jsx)(`span`,{className:`first-run-actions-grow`}),a===3?(0,Q.jsx)(`button`,{type:`button`,className:`btn first-run-primary`,onClick:j,children:t(`开始`,`Start`)}):(0,Q.jsx)(`button`,{type:`button`,className:`btn first-run-primary`,onClick:a===1?O:A,children:t(`下一步`,`Next`)})]})]})})}var Bw={ts:`typescript`,tsx:`typescript`,js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`javascript`,json:`json`,css:`css`,scss:`scss`,html:`xml`,xml:`xml`,svg:`xml`,md:`markdown`,markdown:`markdown`,sh:`bash`,bash:`bash`,zsh:`bash`,py:`python`,rb:`ruby`,go:`go`,rs:`rust`,java:`java`,kt:`kotlin`,sql:`sql`,yml:`yaml`,yaml:`yaml`,toml:`ini`,ini:`ini`,dockerfile:`dockerfile`};function Vw(e){let t=D(e).toLowerCase();return t===`dockerfile`?`dockerfile`:t===`makefile`?`makefile`:Bw[t.includes(`.`)?t.split(`.`).pop()??``:``]??``}function Hw(e,t){return{start:Math.min(e,t)+1,end:Math.max(e,t)+1}}function Uw(e,t){return t?t.start===t.end?`@${e}:${t.start}`:`@${e}:${t.start}-${t.end}`:`@${e}`}function Ww(e){let t=e.filter(e=>e.end>=e.start).map(e=>({start:e.start,end:e.end})).sort((e,t)=>e.start-t.start),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=t.end+1?t.end=Math.max(t.end,e.end):n.push({...e})}return n}function Gw(e){return e.reduce((e,t)=>e+(t.end-t.start+1),0)}function Kw(e,t){return t.length===0?`@${e}`:t.map(t=>Uw(e,t)).join(` `)}function qw(e){let t=e[0];return t?e.filter(e=>e!==t).map(e=>e.start):[]}function Jw(e,t,n){let r=new Set(t);if(r.has(n)){r.delete(n);let t=e.find(e=>e.start===n);if(t)for(let n of e)n.start>t.start&&n.end<=t.end&&r.add(n.start);return r}return r.add(n),r}function Yw(e,t){let n=null;for(let r of e)(r.start===t||t>r.start&&t<=r.end)&&(!n||r.end-r.start<n.end-n.start)&&(n=r);return n}function Xw(e,t,n){return t.has(n.start)?`collapsed`:e.some(e=>e.start>n.start&&e.end<=n.end&&t.has(e.start))?`partial`:`open`}function Zw(e,t,n){let r=new Set(t);for(let t of e)t.start>=n.start&&t.end<=n.end&&r.delete(t.start);return r}function Qw(e,t,n){let r=new Set(t);for(let t of e)t.start>=n.start&&t.end<=n.end&&r.add(t.start);return r}function $w(e){let t=[],n=[],r=0,i=null,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(s===`
70
70
  `)r+=1,i!=="`"&&(i=null);else if(a)s===`*`&&e[o+1]===`/`&&(a=!1,o+=1);else if(i){if(s===`\\`){o+=1;continue}s===i&&(i=null)}else if(s===`/`&&e[o+1]===`/`){let t=e.indexOf(`
71
- `,o);if(t===-1)break;o=t-1}else if(s===`/`&&e[o+1]===`*`)a=!0,o+=1;else if(s===`"`||s===`'`||s==="`")i=s;else if(s===`{`||s===`[`)n.push(r);else if(s===`}`||s===`]`){let e=n.pop();e!==void 0&&r>e&&t.push({start:e,end:r})}}return t.sort((e,t)=>e.start-t.start)}function eT(e,t,n,r){let i=n.includes("```")?"````":"```";return`${Uw(e,t)}\n${i}${r}\n${n}\n${i}`}function tT(e,t,n=5e3){let r=t.toLowerCase();if(r===``)return[];let i=[];for(let t=0;t<e.length;t+=1){let a=(e[t]??``).toLowerCase(),o=0;for(;;){let e=a.indexOf(r,o);if(e<0)break;if(i.push({line:t,offset:e}),i.length>=n)return i;o=e+r.length}}return i}function nT(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function rT(e,t,n){let r=t.toLowerCase();if(r===``)return e;let i=0;return e.split(/(<[^>]*>)/).map(e=>{if(e.startsWith(`<`))return e;let t=sT(e),a=t.map(e=>e.char.toLowerCase());if(a.some(e=>e.length!==1))return e;let o=a.join(``);if(!o.includes(r))return e;let s=``,c=0;for(;;){let e=o.indexOf(r,c);if(e<0)break;let a=e+r.length;s+=aT(t,c,e);let l=aT(t,e,a);s+=`<mark class="file-find-hit${i===n?` file-find-hit-on`:``}">${l}</mark>`,i+=1,c=a}return s+=aT(t,c,t.length),s}).join(``)}function iT(e,t,n){let r=new Set(t);for(let t of e)t.start<n&&n<=t.end&&r.delete(t.start);return r}function aT(e,t,n){let r=``;for(let i=t;i<n;i+=1)r+=e[i]?.raw??``;return r}function oT(e){let t={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `};if(e.startsWith(`#`)){let t=e.startsWith(`#x`)||e.startsWith(`#X`)?Number.parseInt(e.slice(2),16):Number(e.slice(1));if(!Number.isFinite(t)||t<0||t>1114111)return null;try{return String.fromCodePoint(t)}catch{return null}}return t[e]??null}function sT(e){let t=[];for(let n=0;n<e.length;){let r=e[n]??``;if(r===`&`){let r=e.indexOf(`;`,n+1);if(r>n&&r-n<=12){let i=oT(e.slice(n+1,r));if(i!==null&&i.length===1){t.push({char:i,raw:e.slice(n,r+1)}),n=r+1;continue}}}t.push({char:r,raw:r}),n+=1}return t}var cT=300,lT=600;function uT(e){let t=globalThis.requestIdleCallback;return typeof t==`function`?{kind:`idle`,id:t(e,{timeout:500})}:{kind:`timer`,id:setTimeout(e,16)}}function dT(e){let t=globalThis.cancelIdleCallback;e.kind===`idle`?typeof t==`function`&&t(e.id):clearTimeout(e.id)}function fT(e,t,n){let[r,i]=(0,C.useState)({html:[],done:!0,total:0});return(0,C.useEffect)(()=>{let r=e.length;if(r===0||t===``){i({html:[],done:!0,total:r});return}let a=Array.from({length:r},()=>void 0),o=Math.min(cT,r);for(let r=0;r<o;r+=1)a[r]=n(e[r]??``,t);if(o>=r){i({html:a,done:!0,total:r});return}let s=o,c=null,l=!1;i({html:[...a],done:!1,total:r});let u=()=>{if(l)return;let o=Math.min(s+lT,r);for(let r=s;r<o;r+=1)a[r]=n(e[r]??``,t);s=o;let d=s>=r;i({html:[...a],done:d,total:r}),d||(c=uT(u))};return c=uT(u),()=>{l=!0,c&&dT(c)}},[e,t,n]),r}function pT(e){let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0)return{range:null,text:``};let n=t.getRangeAt(0);if(!e.contains(n.commonAncestorContainer))return{range:null,text:``};let r=e=>{let t=(e instanceof Element?e:e?.parentElement??null)?.closest(`[data-line]`),n=Number(t?.getAttribute(`data-line`));return Number.isFinite(n)?n+1:null},i=r(n.startContainer),a=r(n.endContainer),o=t.toString();return i===null||a===null?{range:null,text:o}:{range:{start:Math.min(i,a),end:Math.max(i,a)},text:o}}function mT(e){let[t,n]=(0,C.useState)([]),r=(0,C.useRef)(null),i=(0,C.useRef)(e);return i.current!==e&&(i.current=e,r.current=null,n([])),{selection:t,has:e=>t.some(t=>e>=t.start&&e<=t.end),click:(0,C.useCallback)((e,t)=>{let i=e+1;if(t.toggle)n(e=>{let t=e.find(e=>e.start===i&&e.end===i);return t?e.filter(e=>e!==t):Ww([...e,{start:i,end:i}])}),r.current=e;else if(t.shift&&r.current!==null){let t=r.current;n(n=>{let r=t+1;return Ww([...n.filter(e=>!(e.start<=r&&r<=e.end)),Hw(t,e)])})}else r.current=e,n([{start:i,end:i}])},[]),clear:(0,C.useCallback)(()=>{r.current=null,n([])},[]),set:(0,C.useCallback)(e=>{r.current=e.start-1,n([{...e}])},[])}}var hT=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function gT(e){let t=[],n=0,r=0,i=!1;for(let a of e.split(/\r?\n/)){if(a===``)continue;let e=hT.exec(a);if(e){n=Number(e[1]),r=Number(e[2]),i=!0,t.push({kind:`hunk`,text:a});continue}if(a.startsWith(`\\`)){t.push({kind:`note`,text:a});continue}if(!i){t.push({kind:`meta`,text:a});continue}if(a.startsWith(`+`)){t.push({kind:`add`,text:a.slice(1),newNo:r}),r+=1;continue}if(a.startsWith(`-`)){t.push({kind:`del`,text:a.slice(1),oldNo:n}),n+=1;continue}let o=a.startsWith(` `)?a.slice(1):a;t.push({kind:`ctx`,text:o,oldNo:n,newNo:r}),n+=1,r+=1}return t}function _T({payload:e}){let t=J(),n=(0,C.useMemo)(()=>gT(e.diff),[e.diff]);return e.error?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:e.error}):e.diff.trim()===``?(0,Q.jsx)(`div`,{className:`file-diff-empty`,children:e.isRepo?t(`这个文件相对上次提交没有改动`,`This file has no changes since the last commit`):t(`这里不是 git 仓库,看不到改动`,`Not a git repository — no diff available`)}):(0,Q.jsxs)(`div`,{className:`file-diff`,children:[(0,Q.jsxs)(`div`,{className:`file-diff-summary`,children:[(0,Q.jsxs)(`span`,{className:`file-diff-added mono`,children:[`+`,e.added]}),(0,Q.jsxs)(`span`,{className:`file-diff-removed mono`,children:[`−`,e.removed]}),(0,Q.jsx)(`span`,{className:`file-diff-base`,children:e.untracked?t(`新文件(整份都是新增)`,`New file (everything is added)`):t(`对照上次提交(HEAD),含已暂存`,`Against the last commit (HEAD), including staged changes`)})]}),(0,Q.jsx)(`pre`,{className:`file-diff-body mono`,children:n.map((e,t)=>{if(e.kind===`meta`&&/^(diff --git |index |--- |\+\+\+ |new file mode )/.test(e.text))return null;if(e.kind===`hunk`)return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-hunk`,children:[(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-sign`}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text})]},t);if(e.kind===`meta`||e.kind===`note`)return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-${e.kind}`,children:[(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-sign`}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text})]},t);let n=e.kind===`add`?`+`:e.kind===`del`?`−`:` `;return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-${e.kind}`,children:[(0,Q.jsx)(`span`,{className:`diff-no`,children:e.kind===`add`?``:e.oldNo}),(0,Q.jsx)(`span`,{className:`diff-no`,children:e.kind===`del`?``:e.newNo}),(0,Q.jsx)(`span`,{className:`diff-sign`,children:n}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text||` `})]},t)})}),e.truncated?(0,Q.jsx)(`div`,{className:`file-diff-note`,children:t(`改动太长,只显示前一部分`,`The diff is long — only the first part is shown`)}):null]})}function vT({lines:e,highlighted:t,folds:n,folded:r,isSelected:i,flashLine:a,onToggleFold:o,onPick:s,find:c=null}){let l=J(),u=new Map(n.map(e=>[e.start,e.end])),d=-1;return(0,Q.jsx)(Q.Fragment,{children:e.map((e,n)=>{if(n<=d)return null;let f=u.get(n),p=f!==void 0&&f>n,m=p&&r.has(n);m&&(d=f);let h=i(n+1),g=(c!==null&&c.lines.has(n)?rT(t[n]??nT(e),c.needle,n===c.line?c.occurrence:null):void 0)??t[n];return(0,Q.jsxs)(`div`,{className:`file-preview-line file-preview-line-clickable${h?` file-preview-line-on`:``}${a===n+1?` file-preview-line-focus`:``}`,"data-line":n,title:l(`点选中这一行 · Shift+点连选 · Ctrl(Cmd)+点加选 · 双击折叠/展开这一层 · 右键追加到对话`,`Click to select · Shift+click to extend · Ctrl/Cmd+click to add · Double-click to fold/unfold this block · Right-click to add to chat`),onClick:e=>{if(e.detail>1)return;let t={shift:e.shiftKey,toggle:e.ctrlKey||e.metaKey};(t.shift||window.getSelection()?.isCollapsed)&&(t.shift&&window.getSelection()?.removeAllRanges(),s(n,t))},onDoubleClick:()=>{p&&o(n)},children:[p?(0,Q.jsx)(`button`,{type:`button`,className:`file-fold${m?` file-fold-collapsed`:``}`,title:m?l(`展开这一段(只展开一层)`,`Expand this block (one level)`):l(`折叠这一段`,`Collapse this block`),onClick:e=>{e.stopPropagation(),o(n)},children:m?`▸`:`▾`}):(0,Q.jsx)(`span`,{className:`file-fold file-fold-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`file-preview-no`,title:l(`点选这一行(Shift+点连选,Ctrl/Cmd+点加选)`),onClick:e=>{e.stopPropagation(),s(n,{shift:e.shiftKey,toggle:e.ctrlKey||e.metaKey})},children:n+1}),g===void 0?(0,Q.jsx)(`span`,{className:`file-preview-text`,children:e||` `}):(0,Q.jsx)(`span`,{className:`file-preview-text`,dangerouslySetInnerHTML:{__html:g||` `}}),m&&f!==void 0?(0,Q.jsx)(`span`,{className:`file-fold-summary`,children:l(`⋯ ${f-n} 行已折叠`,`⋯ ${f-n} lines folded`)}):null]},n)})})}function yT({state:e,appSelection:t,onAddSelection:n,onAddRange:r,onClearSelection:i,block:a,blockState:o,onExpandBlock:s,onCollapseBlock:c,onFind:l,blockText:u,blockFolded:d,onAddBlock:f,onClose:p}){let m=J(),h=e.dragRange,g=t.length>0;return(0,Q.jsxs)(qd,{point:e.point,className:`proj-menu ctx-menu`,onClose:p,children:[a&&o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{o===`open`?c(a):s(a),p()},children:[o===`open`?`⌃ `:`⌄ `,o===`open`?m(`收起这一块`,`Collapse this block`):o===`partial`?m(`展开里面全部`,`Expand everything inside`):m(`展开这一块`,`Expand this block`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),m(`)`,`)`)]}),(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`})]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{l(h&&h.start!==h.end?e.dragText.trim():``),p()},children:[`⌕`,` `,h&&h.start!==h.end&&e.dragText.trim()!==``?m(`查找选中的文字`,`Find the selected text`):m(`查找…`,`Find…`)]}),a&&u.trim()!==``?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{xp(u),p()},children:[`⧉ `,m(`复制这一块代码`,`Copy this block`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),d?m(`,含收起的部分`,`, including the collapsed part`):``,m(`)`,`)`)]}):null,a&&o?(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`}):null,a&&u.trim()!==``?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{f(),p()},children:[`⤴ `,m(`添加这一块代码到对话`,`Add this block to the conversation`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),d?m(`,含收起的部分`,`, including the collapsed part`):``,m(`)`,`)`)]}):null,g?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{n(),p()},children:[`⤴ `,m(`追加选中的`,`Append the selected`),` `,Gw(t),` `,m(`行到对话`,`lines to the conversation`)]}):null,h&&h.start!==h.end?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{r(h),p()},children:[`⤴ `,m(`追加鼠标选中的第`,`Append the dragged`),` `,h.start,`–`,h.end,` `,m(`行`,`lines`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{r({start:e.line,end:e.line}),p()},children:[`⤴ `,m(`追加第`,`Append line`),` `,e.line,` `,m(`行到对话`,`to the conversation`)]}),e.dragText===``?null:(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{xp(e.dragText),p()},children:[`⧉ `,m(`复制选中的文字`,`Copy the selected text`)]}),g?(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{i(),p()},children:m(`清空选中`,`Clear selection`)}):null]})}function bT({query:e,onQuery:t,total:n,index:r,onPrev:i,onNext:a,onClose:o}){let s=J(),c=(0,C.useRef)(null);(0,C.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let l=e===``;return(0,Q.jsxs)(`div`,{className:`file-find`,role:`search`,children:[(0,Q.jsxs)(`svg`,{className:`file-find-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.3`}),(0,Q.jsx)(`path`,{d:`m10.4 10.4 3.1 3.1`})]}),(0,Q.jsx)(`input`,{ref:c,className:`file-find-input`,value:e,placeholder:s(`查找内容(Enter 下一个,Shift+Enter 上一个)`,`Find (Enter next, Shift+Enter previous)`),onChange:e=>t(e.target.value),onKeyDown:e=>{if(e.key===`Escape`)e.preventDefault(),o();else if(e.key===`Enter`){if(e.preventDefault(),n===0)return;e.shiftKey?i():a()}}}),(0,Q.jsx)(`span`,{className:`file-find-count${l||n>0?``:` file-find-count-none`}`,children:l?``:n===0?s(`无匹配`,`No matches`):`${r+1} / ${n}`}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,disabled:n===0,title:s(`上一个(Shift+Enter)`,`Previous (Shift+Enter)`),"aria-label":s(`上一个`,`Previous`),onClick:i,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 12.4V3.8`}),(0,Q.jsx)(`path`,{d:`M4.2 7.2 8 3.6l3.8 3.6`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,disabled:n===0,title:s(`下一个(Enter)`,`Next (Enter)`),"aria-label":s(`下一个`,`Next`),onClick:a,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 3.6v8.8`}),(0,Q.jsx)(`path`,{d:`M4.2 9.2 8 12.8l3.8-3.6`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,title:s(`关闭(Esc)`,`Close (Esc)`),"aria-label":s(`关闭`,`Close`),onClick:o,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`m4 4 8 8`}),(0,Q.jsx)(`path`,{d:`m12 4-8 8`})]})})]})}var xT=60,ST=200,CT=10,wT=100;function TT(e){return!e.ctrlKey&&!e.metaKey||e.altKey?null:e.key===`+`||e.key===`=`||e.code===`NumpadAdd`?`in`:e.key===`-`||e.key===`_`||e.code===`NumpadSubtract`?`out`:e.key===`0`||e.code===`Numpad0`||e.code===`NumpadInsert`?`reset`:null}function ET(e){let[t,n]=Eh(e,wT,xT,ST),[r,i]=(0,C.useState)(!1),a=(0,C.useRef)(null),o=(0,C.useRef)(n);o.current=n;let s=(0,C.useRef)(t);return s.current=t,(0,C.useEffect)(()=>{let e=e=>{let t=a.current;if(!t)return;let n=TT(e);if(!n)return;let i=t.contains(document.activeElement);if(!i&&!r)return;let c=document.activeElement;!i&&(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement)||(e.preventDefault(),e.stopPropagation(),n===`reset`?o.current(wT):o.current(s.current+(n===`in`?CT:-10)))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]),{percent:t,ref:a,pointerHandlers:{onPointerEnter:()=>i(!0),onPointerLeave:()=>i(!1)}}}function DT(e){return e<1024?{value:String(Math.round(e)),unit:`B`}:e<1048576?{value:(e/1024).toFixed(1),unit:`KB`}:{value:(e/1048576).toFixed(1),unit:`MB`}}var OT=[];p.registerLanguage(`typescript`,m),p.registerLanguage(`javascript`,s),p.registerLanguage(`json`,o),p.registerLanguage(`xml`,i),p.registerLanguage(`css`,l),p.registerLanguage(`markdown`,_),p.registerLanguage(`bash`,c),p.registerLanguage(`yaml`,u),p.registerLanguage(`ini`,h),p.registerLanguage(`python`,d),p.registerLanguage(`go`,f),p.registerLanguage(`rust`,a),p.registerLanguage(`sql`,g);function kT({path:e,root:t,toolbar:n,initialMode:r,focusLine:i,onOpenPath:a}){let o=J(),[s,c]=(0,C.useState)(null),l=/\.(md|markdown)$/i.test(e),u=/\.(html?|xhtml)$/i.test(e),d=/\.json$/i.test(e),f=/\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i.test(e),m=`path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}`,h=f?`/api/files/raw?${m}`:null,g=/\.(mp4|m4v|webm|ogv|mov|mkv)$/i.test(e),_=/\.(mp3|m4a|aac|wav|ogg|opus|flac)$/i.test(e),v=g||_?`/api/files/media?${m}`:null,[y,b]=(0,C.useState)(r===`diff`?`diff`:l||u?`preview`:`source`),x=e=>b(e),[S,w]=(0,C.useState)(null),[T,E]=(0,C.useState)(new Set),[D,O]=uf(mr,!0),[k,A]=Eh(hr,15,10,32),j=(0,C.useRef)(k);j.current=k;let M=mT(e),[N,P]=(0,C.useState)(null),F=(0,C.useRef)(null),[I,L]=(0,C.useState)(null),[R,z]=(0,C.useState)(!1),[B,V]=(0,C.useState)(``),[H,U]=(0,C.useState)(0),W=(0,C.useRef)(null),[ee,G]=(0,C.useState)(!1);(0,C.useEffect)(()=>{b(r===`diff`?`diff`:l||u?`preview`:`source`)},[e,r,l,u]),(0,C.useEffect)(()=>{if(v||h){w(null);return}let e=!1;return(async()=>{let t=await fetch(`/api/files/diff?${m}`);e||(t.ok?w(await t.json()):w(null))})(),()=>{e=!0}},[m,v,h]),(0,C.useEffect)(()=>{let n=!1;return M.clear(),v?(c({text:``,bytes:0,truncated:!1,binary:!1}),()=>{n=!0}):((async()=>{let r=await fetch(`/api/files/read?path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}`),i=await r.json();n||(r.ok?c({text:i.text??``,bytes:i.bytes??0,truncated:i.truncated===!0,binary:i.binary===!0,...i.matchedBy===`suffix`&&i.path?{notedPath:i.path}:{}}):c({text:``,bytes:0,truncated:!1,binary:!1,error:i.error?.message??`HTTP ${r.status}`,...i.error?.candidates?{candidates:i.error.candidates}:{}}))})(),()=>{n=!0})},[e,t,h,v]);let K=(0,C.useMemo)(()=>s&&!s.binary&&!s.error?$w(s.text):[],[s]);(0,C.useEffect)(()=>{E(new Set(d?qw(K):[]))},[e,d,K]);let te=Vw(e),ne=S!==null,re=ne&&S.isRepo&&S.error===void 0&&S.diff!==``;(0,C.useEffect)(()=>{y===`diff`&&ne&&!re&&b(l||u?`preview`:`source`)},[y,ne,re,l,u]);let ie=(0,C.useMemo)(()=>s&&!s.binary&&!s.error?s.text.split(/\r?\n/):OT,[s]),ae=I?Yw(K,I.line-1):null,oe=ae?ie.slice(ae.start,ae.end+1).join(`
72
- `):``,se=(0,C.useMemo)(()=>R&&y===`source`?tT(ie,B):[],[R,y,ie,B]),ce=se.length===0?null:se[Math.min(H,se.length-1)],le=(0,C.useMemo)(()=>{if(!ce)return 0;let e=0;for(let t of se)if(t.line===ce.line){if(t.offset===ce.offset)return e;e+=1}return 0},[se,ce]),ue=(0,C.useMemo)(()=>new Set(se.map(e=>e.line)),[se]);(0,C.useEffect)(()=>{if(!i||y!==`source`||ie.length===0)return;let e=F.current,t=e?.querySelector(`[data-line="${i-1}"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();e.scrollTop+=r.top-n.top-e.clientHeight/2+r.height/2,P(i);let a=setTimeout(()=>P(null),1400);return()=>clearTimeout(a)},[i,y,ie.length,e]),(0,C.useEffect)(()=>{ce&&y===`source`&&E(e=>{let t=iT(K,e,ce.line);return t.size===e.size?e:t})},[ce,K,y]),(0,C.useEffect)(()=>{if(!ce||y!==`source`)return;let e=F.current,t=e?.querySelector(`[data-line="${ce.line}"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();e.scrollTop+=r.top-n.top-e.clientHeight/2+r.height/2},[ce,T,y]),(0,C.useEffect)(()=>{let e=e=>{let t=W.current;if(!t)return;let n=t.contains(document.activeElement);if(!n&&!ee)return;let r=document.activeElement;if(!n&&(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return;let i=TT(e);if(i){if(y!==`source`)return;e.preventDefault(),e.stopPropagation(),A(i===`reset`?15:j.current+(i===`in`?2:-2))}else(e.key===`f`||e.key===`F`)&&(e.metaKey||e.ctrlKey)&&y===`source`&&(e.preventDefault(),z(!0))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[ee,y,A]),(0,C.useEffect)(()=>{z(!1),V(``),U(0)},[e]);let de=e=>{let t=xo().draft;So(`${t}${t===``||t.endsWith(` `)?``:` `}${e} `)},fe=()=>{if(!ae)return;let t=ie.slice(ae.start,ae.end+1).join(`
71
+ `,o);if(t===-1)break;o=t-1}else if(s===`/`&&e[o+1]===`*`)a=!0,o+=1;else if(s===`"`||s===`'`||s==="`")i=s;else if(s===`{`||s===`[`)n.push(r);else if(s===`}`||s===`]`){let e=n.pop();e!==void 0&&r>e&&t.push({start:e,end:r})}}return t.sort((e,t)=>e.start-t.start)}function eT(e,t,n,r){let i=n.includes("```")?"````":"```";return`${Uw(e,t)}\n${i}${r}\n${n}\n${i}`}function tT(e,t,n=5e3){let r=t.toLowerCase();if(r===``)return[];let i=[];for(let t=0;t<e.length;t+=1){let a=(e[t]??``).toLowerCase(),o=0;for(;;){let e=a.indexOf(r,o);if(e<0)break;if(i.push({line:t,offset:e}),i.length>=n)return i;o=e+r.length}}return i}function nT(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function rT(e,t,n){let r=t.toLowerCase();if(r===``)return e;let i=0;return e.split(/(<[^>]*>)/).map(e=>{if(e.startsWith(`<`))return e;let t=sT(e),a=t.map(e=>e.char.toLowerCase());if(a.some(e=>e.length!==1))return e;let o=a.join(``);if(!o.includes(r))return e;let s=``,c=0;for(;;){let e=o.indexOf(r,c);if(e<0)break;let a=e+r.length;s+=aT(t,c,e);let l=aT(t,e,a);s+=`<mark class="file-find-hit${i===n?` file-find-hit-on`:``}">${l}</mark>`,i+=1,c=a}return s+=aT(t,c,t.length),s}).join(``)}function iT(e,t,n){let r=new Set(t);for(let t of e)t.start<n&&n<=t.end&&r.delete(t.start);return r}function aT(e,t,n){let r=``;for(let i=t;i<n;i+=1)r+=e[i]?.raw??``;return r}function oT(e){let t={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `};if(e.startsWith(`#`)){let t=e.startsWith(`#x`)||e.startsWith(`#X`)?Number.parseInt(e.slice(2),16):Number(e.slice(1));if(!Number.isFinite(t)||t<0||t>1114111)return null;try{return String.fromCodePoint(t)}catch{return null}}return t[e]??null}function sT(e){let t=[];for(let n=0;n<e.length;){let r=e[n]??``;if(r===`&`){let r=e.indexOf(`;`,n+1);if(r>n&&r-n<=12){let i=oT(e.slice(n+1,r));if(i!==null&&i.length===1){t.push({char:i,raw:e.slice(n,r+1)}),n=r+1;continue}}}t.push({char:r,raw:r}),n+=1}return t}var cT=300,lT=600;function uT(e){let t=globalThis.requestIdleCallback;return typeof t==`function`?{kind:`idle`,id:t(e,{timeout:500})}:{kind:`timer`,id:setTimeout(e,16)}}function dT(e){let t=globalThis.cancelIdleCallback;e.kind===`idle`?typeof t==`function`&&t(e.id):clearTimeout(e.id)}function fT(e,t,n){let[r,i]=(0,C.useState)({html:[],done:!0,total:0});return(0,C.useEffect)(()=>{let r=e.length;if(r===0||t===``){i({html:[],done:!0,total:r});return}let a=Array.from({length:r},()=>void 0),o=Math.min(cT,r);for(let r=0;r<o;r+=1)a[r]=n(e[r]??``,t);if(o>=r){i({html:a,done:!0,total:r});return}let s=o,c=null,l=!1;i({html:[...a],done:!1,total:r});let u=()=>{if(l)return;let o=Math.min(s+lT,r);for(let r=s;r<o;r+=1)a[r]=n(e[r]??``,t);s=o;let d=s>=r;i({html:[...a],done:d,total:r}),d||(c=uT(u))};return c=uT(u),()=>{l=!0,c&&dT(c)}},[e,t,n]),r}function pT(e){let t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0)return{range:null,text:``};let n=t.getRangeAt(0);if(!e.contains(n.commonAncestorContainer))return{range:null,text:``};let r=e=>{let t=(e instanceof Element?e:e?.parentElement??null)?.closest(`[data-line]`),n=Number(t?.getAttribute(`data-line`));return Number.isFinite(n)?n+1:null},i=r(n.startContainer),a=r(n.endContainer),o=t.toString();return i===null||a===null?{range:null,text:o}:{range:{start:Math.min(i,a),end:Math.max(i,a)},text:o}}function mT(e){let[t,n]=(0,C.useState)([]),r=(0,C.useRef)(null),i=(0,C.useRef)(e);return i.current!==e&&(i.current=e,r.current=null,n([])),{selection:t,has:e=>t.some(t=>e>=t.start&&e<=t.end),click:(0,C.useCallback)((e,t)=>{let i=e+1;if(t.toggle)n(e=>{let t=e.find(e=>e.start===i&&e.end===i);return t?e.filter(e=>e!==t):Ww([...e,{start:i,end:i}])}),r.current=e;else if(t.shift&&r.current!==null){let t=r.current;n(n=>{let r=t+1;return Ww([...n.filter(e=>!(e.start<=r&&r<=e.end)),Hw(t,e)])})}else r.current=e,n([{start:i,end:i}])},[]),clear:(0,C.useCallback)(()=>{r.current=null,n([])},[]),set:(0,C.useCallback)(e=>{r.current=e.start-1,n([{...e}])},[])}}var hT=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function gT(e){let t=[],n=0,r=0,i=!1;for(let a of e.split(/\r?\n/)){if(a===``)continue;let e=hT.exec(a);if(e){n=Number(e[1]),r=Number(e[2]),i=!0,t.push({kind:`hunk`,text:a});continue}if(a.startsWith(`\\`)){t.push({kind:`note`,text:a});continue}if(!i){t.push({kind:`meta`,text:a});continue}if(a.startsWith(`+`)){t.push({kind:`add`,text:a.slice(1),newNo:r}),r+=1;continue}if(a.startsWith(`-`)){t.push({kind:`del`,text:a.slice(1),oldNo:n}),n+=1;continue}let o=a.startsWith(` `)?a.slice(1):a;t.push({kind:`ctx`,text:o,oldNo:n,newNo:r}),n+=1,r+=1}return t}function _T({payload:e}){let t=Y(),n=(0,C.useMemo)(()=>gT(e.diff),[e.diff]);return e.error?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:e.error}):e.diff.trim()===``?(0,Q.jsx)(`div`,{className:`file-diff-empty`,children:e.isRepo?t(`这个文件相对上次提交没有改动`,`This file has no changes since the last commit`):t(`这里不是 git 仓库,看不到改动`,`Not a git repository — no diff available`)}):(0,Q.jsxs)(`div`,{className:`file-diff`,children:[(0,Q.jsxs)(`div`,{className:`file-diff-summary`,children:[(0,Q.jsxs)(`span`,{className:`file-diff-added mono`,children:[`+`,e.added]}),(0,Q.jsxs)(`span`,{className:`file-diff-removed mono`,children:[`−`,e.removed]}),(0,Q.jsx)(`span`,{className:`file-diff-base`,children:e.untracked?t(`新文件(整份都是新增)`,`New file (everything is added)`):t(`对照上次提交(HEAD),含已暂存`,`Against the last commit (HEAD), including staged changes`)})]}),(0,Q.jsx)(`pre`,{className:`file-diff-body mono`,children:n.map((e,t)=>{if(e.kind===`meta`&&/^(diff --git |index |--- |\+\+\+ |new file mode )/.test(e.text))return null;if(e.kind===`hunk`)return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-hunk`,children:[(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-sign`}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text})]},t);if(e.kind===`meta`||e.kind===`note`)return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-${e.kind}`,children:[(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-no diff-no-empty`}),(0,Q.jsx)(`span`,{className:`diff-sign`}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text})]},t);let n=e.kind===`add`?`+`:e.kind===`del`?`−`:` `;return(0,Q.jsxs)(`div`,{className:`diff-line diff-line-${e.kind}`,children:[(0,Q.jsx)(`span`,{className:`diff-no`,children:e.kind===`add`?``:e.oldNo}),(0,Q.jsx)(`span`,{className:`diff-no`,children:e.kind===`del`?``:e.newNo}),(0,Q.jsx)(`span`,{className:`diff-sign`,children:n}),(0,Q.jsx)(`span`,{className:`diff-text`,children:e.text||` `})]},t)})}),e.truncated?(0,Q.jsx)(`div`,{className:`file-diff-note`,children:t(`改动太长,只显示前一部分`,`The diff is long — only the first part is shown`)}):null]})}function vT({lines:e,highlighted:t,folds:n,folded:r,isSelected:i,flashLine:a,onToggleFold:o,onPick:s,find:c=null}){let l=Y(),u=new Map(n.map(e=>[e.start,e.end])),d=-1;return(0,Q.jsx)(Q.Fragment,{children:e.map((e,n)=>{if(n<=d)return null;let f=u.get(n),p=f!==void 0&&f>n,m=p&&r.has(n);m&&(d=f);let h=i(n+1),g=(c!==null&&c.lines.has(n)?rT(t[n]??nT(e),c.needle,n===c.line?c.occurrence:null):void 0)??t[n];return(0,Q.jsxs)(`div`,{className:`file-preview-line file-preview-line-clickable${h?` file-preview-line-on`:``}${a===n+1?` file-preview-line-focus`:``}`,"data-line":n,title:l(`点选中这一行 · Shift+点连选 · Ctrl(Cmd)+点加选 · 双击折叠/展开这一层 · 右键追加到对话`,`Click to select · Shift+click to extend · Ctrl/Cmd+click to add · Double-click to fold/unfold this block · Right-click to add to chat`),onClick:e=>{if(e.detail>1)return;let t={shift:e.shiftKey,toggle:e.ctrlKey||e.metaKey};(t.shift||window.getSelection()?.isCollapsed)&&(t.shift&&window.getSelection()?.removeAllRanges(),s(n,t))},onDoubleClick:()=>{p&&o(n)},children:[p?(0,Q.jsx)(`button`,{type:`button`,className:`file-fold${m?` file-fold-collapsed`:``}`,title:m?l(`展开这一段(只展开一层)`,`Expand this block (one level)`):l(`折叠这一段`,`Collapse this block`),onClick:e=>{e.stopPropagation(),o(n)},children:m?`▸`:`▾`}):(0,Q.jsx)(`span`,{className:`file-fold file-fold-empty`,"aria-hidden":`true`}),(0,Q.jsx)(`button`,{type:`button`,className:`file-preview-no`,title:l(`点选这一行(Shift+点连选,Ctrl/Cmd+点加选)`),onClick:e=>{e.stopPropagation(),s(n,{shift:e.shiftKey,toggle:e.ctrlKey||e.metaKey})},children:n+1}),g===void 0?(0,Q.jsx)(`span`,{className:`file-preview-text`,children:e||` `}):(0,Q.jsx)(`span`,{className:`file-preview-text`,dangerouslySetInnerHTML:{__html:g||` `}}),m&&f!==void 0?(0,Q.jsx)(`span`,{className:`file-fold-summary`,children:l(`⋯ ${f-n} 行已折叠`,`⋯ ${f-n} lines folded`)}):null]},n)})})}function yT({state:e,appSelection:t,onAddSelection:n,onAddRange:r,onClearSelection:i,block:a,blockState:o,onExpandBlock:s,onCollapseBlock:c,onFind:l,blockText:u,blockFolded:d,onAddBlock:f,onClose:p}){let m=Y(),h=e.dragRange,g=t.length>0;return(0,Q.jsxs)(qd,{point:e.point,className:`proj-menu ctx-menu`,onClose:p,children:[a&&o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{o===`open`?c(a):s(a),p()},children:[o===`open`?`⌃ `:`⌄ `,o===`open`?m(`收起这一块`,`Collapse this block`):o===`partial`?m(`展开里面全部`,`Expand everything inside`):m(`展开这一块`,`Expand this block`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),m(`)`,`)`)]}),(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`})]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{l(h&&h.start!==h.end?e.dragText.trim():``),p()},children:[`⌕`,` `,h&&h.start!==h.end&&e.dragText.trim()!==``?m(`查找选中的文字`,`Find the selected text`):m(`查找…`,`Find…`)]}),a&&u.trim()!==``?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{xp(u),p()},children:[`⧉ `,m(`复制这一块代码`,`Copy this block`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),d?m(`,含收起的部分`,`, including the collapsed part`):``,m(`)`,`)`)]}):null,a&&o?(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`}):null,a&&u.trim()!==``?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{f(),p()},children:[`⤴ `,m(`添加这一块代码到对话`,`Add this block to the conversation`),m(`(`,` (`),m(`第 ${a.start+1}–${a.end+1} 行`,`lines ${a.start+1}–${a.end+1}`),d?m(`,含收起的部分`,`, including the collapsed part`):``,m(`)`,`)`)]}):null,g?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{n(),p()},children:[`⤴ `,m(`追加选中的`,`Append the selected`),` `,Gw(t),` `,m(`行到对话`,`lines to the conversation`)]}):null,h&&h.start!==h.end?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{r(h),p()},children:[`⤴ `,m(`追加鼠标选中的第`,`Append the dragged`),` `,h.start,`–`,h.end,` `,m(`行`,`lines`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{r({start:e.line,end:e.line}),p()},children:[`⤴ `,m(`追加第`,`Append line`),` `,e.line,` `,m(`行到对话`,`to the conversation`)]}),e.dragText===``?null:(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{xp(e.dragText),p()},children:[`⧉ `,m(`复制选中的文字`,`Copy the selected text`)]}),g?(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:()=>{i(),p()},children:m(`清空选中`,`Clear selection`)}):null]})}function bT({query:e,onQuery:t,total:n,index:r,onPrev:i,onNext:a,onClose:o}){let s=Y(),c=(0,C.useRef)(null);(0,C.useEffect)(()=>{let e=c.current;e&&(e.focus(),e.select())},[]);let l=e===``;return(0,Q.jsxs)(`div`,{className:`file-find`,role:`search`,children:[(0,Q.jsxs)(`svg`,{className:`file-find-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.3`}),(0,Q.jsx)(`path`,{d:`m10.4 10.4 3.1 3.1`})]}),(0,Q.jsx)(`input`,{ref:c,className:`file-find-input`,value:e,placeholder:s(`查找内容(Enter 下一个,Shift+Enter 上一个)`,`Find (Enter next, Shift+Enter previous)`),onChange:e=>t(e.target.value),onKeyDown:e=>{if(e.key===`Escape`)e.preventDefault(),o();else if(e.key===`Enter`){if(e.preventDefault(),n===0)return;e.shiftKey?i():a()}}}),(0,Q.jsx)(`span`,{className:`file-find-count${l||n>0?``:` file-find-count-none`}`,children:l?``:n===0?s(`无匹配`,`No matches`):`${r+1} / ${n}`}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,disabled:n===0,title:s(`上一个(Shift+Enter)`,`Previous (Shift+Enter)`),"aria-label":s(`上一个`,`Previous`),onClick:i,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 12.4V3.8`}),(0,Q.jsx)(`path`,{d:`M4.2 7.2 8 3.6l3.8 3.6`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,disabled:n===0,title:s(`下一个(Enter)`,`Next (Enter)`),"aria-label":s(`下一个`,`Next`),onClick:a,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 3.6v8.8`}),(0,Q.jsx)(`path`,{d:`M4.2 9.2 8 12.8l3.8-3.6`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`file-find-btn`,title:s(`关闭(Esc)`,`Close (Esc)`),"aria-label":s(`关闭`,`Close`),onClick:o,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`m4 4 8 8`}),(0,Q.jsx)(`path`,{d:`m12 4-8 8`})]})})]})}var xT=60,ST=200,CT=10,wT=100;function TT(e){return!e.ctrlKey&&!e.metaKey||e.altKey?null:e.key===`+`||e.key===`=`||e.code===`NumpadAdd`?`in`:e.key===`-`||e.key===`_`||e.code===`NumpadSubtract`?`out`:e.key===`0`||e.code===`Numpad0`||e.code===`NumpadInsert`?`reset`:null}function ET(e){let[t,n]=Eh(e,wT,xT,ST),[r,i]=(0,C.useState)(!1),a=(0,C.useRef)(null),o=(0,C.useRef)(n);o.current=n;let s=(0,C.useRef)(t);return s.current=t,(0,C.useEffect)(()=>{let e=e=>{let t=a.current;if(!t)return;let n=TT(e);if(!n)return;let i=t.contains(document.activeElement);if(!i&&!r)return;let c=document.activeElement;!i&&(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement)||(e.preventDefault(),e.stopPropagation(),n===`reset`?o.current(wT):o.current(s.current+(n===`in`?CT:-10)))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]),{percent:t,ref:a,pointerHandlers:{onPointerEnter:()=>i(!0),onPointerLeave:()=>i(!1)}}}function DT(e){return e<1024?{value:String(Math.round(e)),unit:`B`}:e<1048576?{value:(e/1024).toFixed(1),unit:`KB`}:{value:(e/1048576).toFixed(1),unit:`MB`}}var OT=[];p.registerLanguage(`typescript`,m),p.registerLanguage(`javascript`,s),p.registerLanguage(`json`,o),p.registerLanguage(`xml`,i),p.registerLanguage(`css`,l),p.registerLanguage(`markdown`,_),p.registerLanguage(`bash`,c),p.registerLanguage(`yaml`,u),p.registerLanguage(`ini`,h),p.registerLanguage(`python`,d),p.registerLanguage(`go`,f),p.registerLanguage(`rust`,a),p.registerLanguage(`sql`,g);function kT({path:e,root:t,toolbar:n,initialMode:r,focusLine:i,onOpenPath:a}){let o=Y(),[s,c]=(0,C.useState)(null),l=/\.(md|markdown)$/i.test(e),u=/\.(html?|xhtml)$/i.test(e),d=/\.json$/i.test(e),f=/\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i.test(e),m=`path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}`,h=f?`/api/files/raw?${m}`:null,g=/\.(mp4|m4v|webm|ogv|mov|mkv)$/i.test(e),_=/\.(mp3|m4a|aac|wav|ogg|opus|flac)$/i.test(e),v=g||_?`/api/files/media?${m}`:null,[y,b]=(0,C.useState)(r===`diff`?`diff`:l||u?`preview`:`source`),x=e=>b(e),[S,w]=(0,C.useState)(null),[T,E]=(0,C.useState)(new Set),[D,O]=uf(mr,!0),[k,A]=Eh(hr,15,10,32),j=(0,C.useRef)(k);j.current=k;let M=mT(e),[N,P]=(0,C.useState)(null),F=(0,C.useRef)(null),[I,L]=(0,C.useState)(null),[R,z]=(0,C.useState)(!1),[B,V]=(0,C.useState)(``),[H,U]=(0,C.useState)(0),W=(0,C.useRef)(null),[ee,G]=(0,C.useState)(!1);(0,C.useEffect)(()=>{b(r===`diff`?`diff`:l||u?`preview`:`source`)},[e,r,l,u]),(0,C.useEffect)(()=>{if(v||h){w(null);return}let e=!1;return(async()=>{let t=await fetch(`/api/files/diff?${m}`);e||(t.ok?w(await t.json()):w(null))})(),()=>{e=!0}},[m,v,h]),(0,C.useEffect)(()=>{let n=!1;return M.clear(),v?(c({text:``,bytes:0,truncated:!1,binary:!1}),()=>{n=!0}):((async()=>{let r=await fetch(`/api/files/read?path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}`),i=await r.json();n||(r.ok?c({text:i.text??``,bytes:i.bytes??0,truncated:i.truncated===!0,binary:i.binary===!0,...i.matchedBy===`suffix`&&i.path?{notedPath:i.path}:{}}):c({text:``,bytes:0,truncated:!1,binary:!1,error:i.error?.message??`HTTP ${r.status}`,...i.error?.candidates?{candidates:i.error.candidates}:{}}))})(),()=>{n=!0})},[e,t,h,v]);let K=(0,C.useMemo)(()=>s&&!s.binary&&!s.error?$w(s.text):[],[s]);(0,C.useEffect)(()=>{E(new Set(d?qw(K):[]))},[e,d,K]);let te=Vw(e),ne=S!==null,re=ne&&S.isRepo&&S.error===void 0&&S.diff!==``;(0,C.useEffect)(()=>{y===`diff`&&ne&&!re&&b(l||u?`preview`:`source`)},[y,ne,re,l,u]);let ie=(0,C.useMemo)(()=>s&&!s.binary&&!s.error?s.text.split(/\r?\n/):OT,[s]),ae=I?Yw(K,I.line-1):null,oe=ae?ie.slice(ae.start,ae.end+1).join(`
72
+ `):``,se=(0,C.useMemo)(()=>R&&y===`source`?tT(ie,B):[],[R,y,ie,B]),ce=se.length===0?null:se[Math.min(H,se.length-1)],le=(0,C.useMemo)(()=>{if(!ce)return 0;let e=0;for(let t of se)if(t.line===ce.line){if(t.offset===ce.offset)return e;e+=1}return 0},[se,ce]),ue=(0,C.useMemo)(()=>new Set(se.map(e=>e.line)),[se]);(0,C.useEffect)(()=>{if(!i||y!==`source`||ie.length===0)return;let e=F.current,t=e?.querySelector(`[data-line="${i-1}"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();e.scrollTop+=r.top-n.top-e.clientHeight/2+r.height/2,P(i);let a=setTimeout(()=>P(null),1400);return()=>clearTimeout(a)},[i,y,ie.length,e]),(0,C.useEffect)(()=>{ce&&y===`source`&&E(e=>{let t=iT(K,e,ce.line);return t.size===e.size?e:t})},[ce,K,y]),(0,C.useEffect)(()=>{if(!ce||y!==`source`)return;let e=F.current,t=e?.querySelector(`[data-line="${ce.line}"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();e.scrollTop+=r.top-n.top-e.clientHeight/2+r.height/2},[ce,T,y]),(0,C.useEffect)(()=>{let e=e=>{let t=W.current;if(!t)return;let n=t.contains(document.activeElement);if(!n&&!ee)return;let r=document.activeElement;if(!n&&(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return;let i=TT(e);if(i){if(y!==`source`)return;e.preventDefault(),e.stopPropagation(),A(i===`reset`?15:j.current+(i===`in`?2:-2))}else(e.key===`f`||e.key===`F`)&&(e.metaKey||e.ctrlKey)&&y===`source`&&(e.preventDefault(),z(!0))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[ee,y,A]),(0,C.useEffect)(()=>{z(!1),V(``),U(0)},[e]);let de=e=>{let t=xo().draft;So(`${t}${t===``||t.endsWith(` `)?``:` `}${e} `)},q=()=>{if(!ae)return;let t=ie.slice(ae.start,ae.end+1).join(`
73
73
  `);if(t.trim()===``)return;let n=eT(e,{start:ae.start+1,end:ae.end+1},t,te),r=xo().draft;So(`${r}${r===``||r.endsWith(`
74
74
  `)?``:`
75
- `}${n}\n`)},pe=(0,C.useCallback)((e,t)=>{try{return p.highlight(e,{language:t,ignoreIllegals:!0}).value}catch{return``}},[]),{html:me,done:he,total:ge}=fT(ie,te!==``&&p.getLanguage(te)?te:``,pe),_e=e.startsWith(`/`)||!t?e:`${t.replace(/\/+$/,``)}/${e}`,ve=zp(e.split(`/`).pop()??e)?.tone??null;return(0,Q.jsxs)(`div`,{className:`file-viewer`,ref:W,onPointerEnter:()=>G(!0),onPointerLeave:()=>G(!1),children:[(0,Q.jsxs)(`div`,{className:`file-preview-head`,children:[(0,Q.jsxs)(`span`,{className:`file-preview-meta`,children:[(0,Q.jsxs)(`span`,{className:`file-preview-size${ve?` filetype-${ve}`:``}`,children:[v?g?o(`视频`,`Video`):o(`音频`,`Audio`):s?(e=>{let t=DT(e);return t.unit===`B`?o(`${t.value} 字节`,`${t.value} bytes`):`${t.value} ${t.unit}`})(s.bytes):o(`读取中…`,`Loading…`),s?.truncated?o(`(已截断)`,`(truncated)`):``]}),(0,Q.jsx)(`span`,{className:`file-preview-path`,title:_e,children:_e})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),v||h?null:(0,Q.jsxs)(`span`,{className:`preview-mode`,children:[(0,Q.jsx)(`button`,{type:`button`,className:y===`source`?`preview-mode-on`:``,onClick:()=>x(`source`),children:o(`源码`,`Source`)}),l||u?(0,Q.jsx)(`button`,{type:`button`,className:y===`preview`?`preview-mode-on`:``,onClick:()=>x(`preview`),children:u?o(`页面`,`Page`):o(`预览`,`Preview`)}):null,re?(0,Q.jsxs)(`button`,{type:`button`,className:y===`diff`?`preview-mode-on`:``,onClick:()=>x(`diff`),title:o(`相对上次提交(HEAD)改了什么`,`What changed since the last commit (HEAD)`),children:[o(`改动`,`Diff`),S?(0,Q.jsxs)(`span`,{className:`preview-mode-diff`,children:[(0,Q.jsxs)(`span`,{className:`preview-mode-plus`,children:[`+`,S.added]}),(0,Q.jsxs)(`span`,{className:`preview-mode-minus`,children:[`−`,S.removed]})]}):null]}):null]}),v||h?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-wrap${D?` preview-wrap-on`:``}`,onClick:()=>O(!D),title:D?o(`自动换行:开(长行折行显示)`,`Word wrap: on (long lines wrap)`):o(`自动换行:关(长行横向滚动)`,`Word wrap: off (long lines scroll sideways)`),"aria-pressed":D,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2 3.6h12M2 7.2h8.6a2.4 2.4 0 1 1 0 4.8H8.4`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`m9.6 10.4-1.6 1.6 1.6 1.6`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,transform:`translate(0,-1.2)`}),(0,Q.jsx)(`path`,{d:`M2 10.8h4`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`})]})}),n]}),s?.notedPath?(0,Q.jsx)(`div`,{className:`file-preview-note`,children:o(`按文件名匹配到 ${s.notedPath}`,`Matched by file name: ${s.notedPath}`)}):null,s?.error?(0,Q.jsxs)(`div`,{className:`file-preview-error`,children:[(0,Q.jsx)(`span`,{children:s.error}),s.candidates&&s.candidates.length>0?(0,Q.jsx)(`ul`,{className:`file-preview-candidates`,children:s.candidates.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`button`,{type:`button`,title:e,onClick:()=>a?.(e),children:e})},e))}):null]}):null,h?(0,Q.jsx)(`div`,{className:`file-image-wrap`,children:(0,Q.jsx)(`img`,{className:`file-image`,src:h,alt:e})}):null,g&&v?(0,Q.jsx)(`div`,{className:`file-media`,children:(0,Q.jsx)(`video`,{className:`file-video`,src:v,controls:!0,playsInline:!0,preload:`metadata`})}):null,_&&v?(0,Q.jsx)(`div`,{className:`file-media`,children:(0,Q.jsx)(`audio`,{className:`file-audio`,src:v,controls:!0,preload:`metadata`})}):null,s?.binary&&h===null&&v===null?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:o(`这是二进制文件,不能预览`,`This is a binary file and cannot be previewed`)}):null,s&&!s.binary&&!s.error&&l&&y===`preview`?(0,Q.jsx)(`div`,{className:`file-preview-md`,children:(0,Q.jsx)(bg,{text:s.text})}):null,u&&y===`preview`?(0,Q.jsx)(`div`,{className:`file-html-wrap`,children:(0,Q.jsx)(`iframe`,{className:`file-html-frame`,title:e,src:`/api/files/raw?${m}`,sandbox:`allow-scripts allow-popups allow-forms allow-modals`,referrerPolicy:`no-referrer`})}):null,y===`diff`&&S?(0,Q.jsx)(_T,{payload:S}):null,y===`diff`&&S===null?(0,Q.jsx)(`div`,{className:`file-diff-empty`,children:o(`正在读取改动…`,`Reading the diff…`)}):null,s&&!s.binary&&!s.error&&v===null&&y===`source`?(0,Q.jsx)(`pre`,{ref:F,className:`file-preview-body mono${D?` file-preview-body-wrap`:``}`,style:{"--ln-w":`${Math.max(2,String(ie.length).length)}ch`,fontSize:`${k}px`},onContextMenu:e=>{let t=e.target.closest(`[data-line]`);if(!t)return;let n=Number(t.getAttribute(`data-line`))+1;if(!Number.isFinite(n))return;e.preventDefault();let r=pT(e.currentTarget);L({point:{x:e.clientX,y:e.clientY},line:n,dragRange:r.range,dragText:r.text})},children:(0,Q.jsx)(vT,{lines:ie,highlighted:me,folds:K,folded:T,isSelected:e=>M.has(e),flashLine:N,onToggleFold:e=>E(t=>Jw(K,t,e)),onPick:(e,t)=>M.click(e,t),find:R&&B!==``?{needle:B,line:ce?.line??-1,occurrence:le,lines:ue}:null})}):null,R&&y===`source`&&v===null?(0,Q.jsx)(bT,{query:B,onQuery:e=>{V(e),U(0)},total:se.length,index:se.length===0?0:Math.min(H,se.length-1),onPrev:()=>U(e=>se.length===0?0:(e-1+se.length)%se.length),onNext:()=>U(e=>se.length===0?0:(e+1)%se.length),onClose:()=>{z(!1),V(``)}}):null,!he&&ge>0?(0,Q.jsxs)(`div`,{className:`file-preview-hint`,children:[`文件较大(`,ge.toLocaleString(),` 行),正在分批上色…(可以边看边滚,不影响滚动)`]}):null,I?(0,Q.jsx)(yT,{state:I,appSelection:M.selection,onAddSelection:()=>{de(Kw(e,M.selection)),M.clear()},onAddRange:t=>de(Uw(e,t)),onClearSelection:M.clear,block:ae,blockState:ae?Xw(K,T,ae):null,onExpandBlock:e=>E(t=>Zw(K,t,e)),onCollapseBlock:e=>E(t=>Qw(K,t,e)),blockText:oe,blockFolded:ae!==null&&T.has(ae.start),onAddBlock:fe,onFind:e=>{V(e),U(0),z(!0)},onClose:()=>L(null)}):null]})}function AT({termId:e,cwd:t,initialCommand:n=null,standalone:r=!1,active:i=!0,onClose:a}){let o=J(),s=(0,C.useRef)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(!1),[f,p]=(0,C.useState)(null),[m,h]=Eh(br,14,8,24),g=(0,C.useRef)(null),_=(0,C.useRef)(null),v=(0,C.useRef)(m);v.current=m;let y=(0,C.useRef)(null);return(0,C.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>y.current?.(),30);return()=>clearTimeout(e)},[i]),(0,C.useEffect)(()=>{let r=s.current;if(!r)return;let i=new S({fontSize:v.current,fontFamily:`"Cascadia Mono", Consolas, ui-monospace, SFMono-Regular, Menlo, "Courier New", monospace`,lineHeight:1.2,theme:{background:`#ffffff`,foreground:`#24292f`,cursor:`#24292f`,cursorAccent:`#ffffff`,selectionBackground:`rgb(9 105 218 / 22%)`,black:`#24292f`,red:`#cf222e`,green:`#116329`,yellow:`#7d4e00`,blue:`#0969da`,magenta:`#8250df`,cyan:`#1b7c83`,white:`#6e7781`,brightBlack:`#57606a`,brightRed:`#a40e26`,brightGreen:`#1a7f37`,brightYellow:`#633c01`,brightBlue:`#218bff`,brightMagenta:`#a475f9`,brightCyan:`#3192aa`,brightWhite:`#8c959f`},cursorBlink:!0,scrollback:2e3}),a=new x;i.loadAddon(a),i.open(r),a.fit(),g.current=i,_.current=a;let o=e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault();let t=e.deltaY<0?2:-2;h(v.current+t)};r.addEventListener(`wheel`,o,{passive:!1});let c=e=>{if(!e.ctrlKey&&!e.metaKey||e.altKey)return;let t=e.key===`+`||e.key===`=`||e.code===`NumpadAdd`,n=e.key===`-`||e.key===`_`||e.code===`NumpadSubtract`,r=e.key===`0`||e.code===`Numpad0`;(t||n||r)&&(e.preventDefault(),e.stopPropagation(),h(t?v.current+2:n?v.current-2:14))};r.addEventListener(`keydown`,c,!0);let u=null,f=null,m=!1,b=!1,C=[],w=t=>{fetch(`/api/terminal/input`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,data:t})})},T=e=>{b?w(e):C.push(e)},E=e=>{if(!e)return!1;for(let t of e){let e=t.codePointAt(0)??0;if(e<32||e===127)return!1}return!0},D=``,O=e=>{if(!e){p(null);return}let t=r.querySelector(`.xterm-screen`),n=r.parentElement;if(!t||!n||i.cols<=0||i.rows<=0){p({text:e,left:0,top:0,cellH:16,fontSize:i.options.fontSize??12,fontFamily:String(i.options.fontFamily??`monospace`)});return}let a=t.clientWidth/i.cols,o=t.clientHeight/i.rows,s=n.getBoundingClientRect(),c=t.getBoundingClientRect(),l=i.buffer.active;p({text:e,left:c.left-s.left+l.cursorX*a,top:c.top-s.top+l.cursorY*o,cellH:o,fontSize:i.options.fontSize??12,fontFamily:String(i.options.fontFamily??`monospace`)})};return i.onCursorMove(()=>{D&&O(D)}),i.onResize(()=>{D&&O(D)}),i.onData(e=>{if(i.buffer.active.type===`alternate`){let t=D;D=``,p(null),T(t+e);return}if(E(e)){D+=e,O(D);return}if(e===``&&D){D=Array.from(D).slice(0,-1).join(``),O(D);return}let t=D+e;D=``,O(``),T(t)}),i.onResize(({cols:t,rows:n})=>void fetch(`/api/terminal/resize`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,cols:t,rows:n})})),(async()=>{let o=await fetch(`/api/terminal/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,cols:i.cols,rows:i.rows,...t?{cwd:t}:{}})}),s=await o.json();if(m)return;if(!o.ok){l(s.error?.message??`HTTP ${o.status}`);return}d(!0),b=!0;for(let e of C.splice(0))w(e);n&&fetch(`/api/terminal/input`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,data:`${n}\r`})});let c=0,p=()=>{u=al({wsPath:`/ws?terminal=${encodeURIComponent(e)}`,sseUrl:`/api/terminal/stream?id=${encodeURIComponent(e)}`,handlers:{onOpen:()=>{c=0},onMessage:e=>{try{i.write(JSON.parse(e))}catch{i.write(e)}},onClose:()=>{u=null,!(m||c>=5)&&(c+=1,setTimeout(()=>{m||p()},Math.min(500*2**c,8e3)))}}})};p(),f=new ResizeObserver(()=>a.fit()),f.observe(r),y.current=()=>{a.fit(),i.focus()},i.focus()})(),()=>{m=!0,r.removeEventListener(`wheel`,o),r.removeEventListener(`keydown`,c,!0),g.current=null,_.current=null,f?.disconnect(),u?.close(),fetch(`/api/terminal/stop`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e})}),i.dispose()}},[t,e,n]),(0,C.useEffect)(()=>{let e=g.current;e&&e.options.fontSize!==m&&(e.options.fontSize=m,_.current?.fit())},[m]),(0,Q.jsxs)(`aside`,{className:`terminal-panel${r?``:` terminal-panel-embedded`}`,children:[r?(0,Q.jsxs)(`div`,{className:`terminal-head`,children:[(0,Q.jsxs)(`span`,{children:[`⌨ `,o(`终端`,`Terminal`),t?` · ${D(t)}`:``]}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:u?o(`PTY 已启动`,`PTY running`):o(`启动中…`,`Starting…`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:a,children:o(`关闭`,`Close`)})]}):null,c?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:c}):null,(0,Q.jsx)(`div`,{className:`terminal-host`,ref:s}),f?(0,Q.jsx)(`div`,{className:`terminal-pending`,"aria-live":`polite`,style:{left:f.left,top:f.top,fontSize:f.fontSize,fontFamily:f.fontFamily,lineHeight:`${f.cellH}px`,maxWidth:`calc(100% - ${Math.round(f.left)}px)`},children:f.text}):null]})}var jT={snapshot:null,error:null,draft:``};function MT(e,t){if(typeof t!=`object`||!t)return e;let n=t;if(n.type===`reply`&&n.ok===!1){let t=n.error;return{...e,error:t?`${t.code??`error`}: ${t.message??``}`:q(`请求失败`,`Request failed`)}}if(n.type!==`event`)return e;if(n.event===`snapshot`&&typeof n.snapshot==`object`&&n.snapshot!==null)return{...e,snapshot:n.snapshot,error:null};if(n.event===`message_delta`){let t=e.snapshot,{conversationId:r,messageId:i,text:a}=n;if(!t||!i||typeof a!=`string`||!r||t.active.conversationId!==r)return e;let o=t.active.messages.map(e=>e.id===i?Wc(e,a):e);return{...e,snapshot:{...t,active:{...t.active,messages:o}}}}return e}var NT=0;function PT(){let e=`side-${rl()}`,t=jT,n=new Set,r=null,i=!1,a=e=>{if(e===t)return;t=e;let r=t.snapshot?.active.conversationId;r&&IT.add(r);for(let e of n)e(t)},o=n=>{(async()=>{try{let r=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":e},body:JSON.stringify({id:`side-req-${++NT}`,...n})});if(!r.ok){a({...t,error:q(`请求失败:HTTP ${r.status}`,`Request failed: HTTP ${r.status}`)});return}let i=await r.json();for(let e of i.frames??[])try{a(MT(t,JSON.parse(e)))}catch{}}catch(e){a({...t,error:e instanceof Error?e.message:String(e)})}})()},s=()=>{if(i||r)return;let n=`client=${encodeURIComponent(e)}&slim=1`,o=0,s=()=>{r=al({wsPath:`/ws?${n}`,sseUrl:`/api/events?${n}`,handlers:{onOpen:()=>{o=0},onMessage:e=>{try{a(MT(t,JSON.parse(e)))}catch{}},onClose:()=>{r=null,!(i||o>=5)&&(o+=1,setTimeout(s,Math.min(500*2**o,8e3)))}}})};s()};return{id:e,get:()=>t,subscribe:e=>(n.add(e),e(t),()=>n.delete(e)),newChat:()=>{s(),o({type:`new_chat`,payload:{ephemeral:!0}})},send:(e,t,n)=>{let r=e.trim();r&&(s(),o({type:`send_message`,payload:{text:r,...t&&t.length>0?{attachments:t}:{},...n&&n!==`now`?{mode:n}:{}}}))},setModel:e=>o({type:`set_model`,payload:{modelId:e}}),setDraft:e=>a({...t,draft:e}),interrupt:e=>o({type:`interrupt`,payload:{conversationId:e}}),persist:e=>o({type:`persist_conversation`,payload:{conversationId:e}}),closeEphemeral:e=>o({type:`close_ephemeral`,payload:{conversationId:e}}),shutdown:()=>{let e=t.snapshot?.active.conversationId;e&&o({type:`close_ephemeral`,payload:{conversationId:e}}),i=!0,r?.close(),r=null,n.clear()},dispose:()=>{i=!0,r?.close(),r=null,n.clear()}}}var FT=new Map,IT=new Set;function LT(e){let t=FT.get(e);return t||(t=PT(),FT.set(e,t)),t}function RT(e){let t=FT.get(e);t&&(FT.delete(e),t.shutdown())}function zT(e){return IT.has(e)}function BT({itemId:e}){let t=J(),n=LT(e),r=(0,C.useSyncExternalStore)(e=>n.subscribe(()=>e()),n.get,n.get);(0,C.useEffect)(()=>{n.get().snapshot===null&&n.newChat()},[n]);let i=r.snapshot,a=i?.active.conversationId??null,[o,s]=(0,C.useState)(!1),c=i?.conversations?.find(e=>e.id===a),l=a!==null&&(c?c.ephemeral===!0:!o),u=i?.engineCapabilities.ephemeralChat===!0,d=i?.active.messages??[],f=i!==null&&i.running.status!==`idle`&&i.running.conversationId===a,p=(0,C.useMemo)(()=>Object.fromEntries((i?.models??[]).map(e=>[e.id,e.label])),[i?.models]),m=(0,C.useMemo)(()=>({draft:r.draft??``,setDraft:n.setDraft,snapshot:i,send:(e,t,r)=>{n.send(e,t,r),n.setDraft(``)},interrupt:e=>n.interrupt(e),switchModel:e=>n.setModel(e),hostCommands:!1}),[r.draft,i,n]),h=ET(gr);return(0,Q.jsxs)(`div`,{className:`work-chat work-chat-main`,ref:h.ref,...h.pointerHandlers,style:{zoom:h.percent/100},children:[(0,Q.jsx)(Af,{notices:(i?.notices??[]).filter(e=>e.conversationId===a),activeConversationId:a}),(0,Q.jsx)(`div`,{className:`work-chat-stream`,children:d.length===0?(0,Q.jsx)(`div`,{className:`work-chat-empty`,children:t(`问一句就走:这条聊天不落盘,关掉即消失。`)}):(0,Q.jsx)(hv,{messages:d,hasMoreBefore:!1,modelLabels:p,workspaceRoot:i?.files?.root??null,running:f,activeTool:f?i?.running.activeTool??null:null})}),l?(0,Q.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,Q.jsx)(`span`,{className:`ephemeral-banner-text`,title:u?t(`消息只保存在内存里,不落盘、不进历史;关掉标签或重启服务后就没了。`,`Messages live in memory only: nothing is written to disk, nothing shows up in history, and it is gone once the tab closes or the server restarts.`):t(`这条聊天不写进本工作台的会话文件、也不进历史,关掉标签或重启服务后就没了。当前引擎没有「转正」能力,所以不提供保存(引擎自己的会话记录由它管理)。`,`This chat is never written to a workbench session file and never shows up in history; it is gone once the tab closes or the server restarts. The current engine cannot promote it to a saved session, so no save button is offered (the engine keeps its own record).`),children:u?t(`💬 临时会话:仅存内存,关掉即销毁。`,`💬 Temp session: in-memory only, gone on close.`):t(`💬 临时会话:不落盘,关掉即消失。`,`💬 Temp session: never saved, gone on close.`)}),u?(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>{a&&(n.persist(a),s(!0),Z({text:t(`已保存为正式对话`,`Saved as a regular chat`),actions:[]}))},title:t(`把这条聊天写成真正的会话文件(之后就能在历史里找到)`,`Write this chat to a real session file`),children:[`💾 `,t(`保存为正式对话`,`Save as a regular chat`)]}):null]}):null,(0,Q.jsx)(_m,{running:f,conversationId:a,surface:m,tempChat:!0})]})}var VT=/^([a-z][a-z0-9+.-]*):/i,HT=/^\d+(\/|$|\?|#)/;function UT(e){let t=e.trim();if(!t)return null;let n=VT.exec(t);if(n){let e=n[1].toLowerCase(),r=t.slice(n[0].length);if(r.startsWith(`//`)||!HT.test(r)){if(e!==`http`&&e!==`https`)return null;try{return new URL(t).toString()}catch{return null}}}let r=WT(t)?`http://`:`https://`;try{return new URL(`${r}${t}`).toString()}catch{return null}}function WT(e){return/^(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(e)}function GT(e){try{return new URL(e).host.replace(/^www\./i,``)||e}catch{return e}}function KT(e){let t=e.toLowerCase();return t===`127.0.0.1`?`localhost`:t===`localhost`||t===`::1`||t===`[::1]`?`127.0.0.1`:null}function qT(e,t,n={}){if(t.protocol!==`http:`)return null;let r=KT(t.hostname);if(r===null||XT(e)===null)return null;let i=t.port===``?``:`:${t.port}`,a=n.mobile===!0?`&m=1`:``;return`${t.protocol}//${r}${i}/web/w?u=${encodeURIComponent(e)}${a}`}var JT=`/web/p/`,YT=`/web/m/`;function XT(e,t={}){try{let n=new URL(e);return n.protocol!==`http:`&&n.protocol!==`https:`?null:`${t.mobile===!0?YT:JT}${n.protocol.slice(0,-1)}/${n.host}${n.pathname}${n.search}`}catch{return null}}function ZT(e){let t;try{t=new URL(e)}catch{return null}let n=t.pathname.startsWith(`/web/m/`)?YT:JT;if(!t.pathname.startsWith(n))return null;let r=t.pathname.slice(n.length),i=r.indexOf(`/`);if(i<0)return null;let a=r.slice(0,i).toLowerCase(),o=r.slice(i+1),s=o.indexOf(`/`),c=s<0?o:o.slice(0,s),l=s<0?`/`:o.slice(s);return a!==`http`&&a!==`https`||!c?null:`${a}://${c}${l}${t.search}${t.hash}`}var QT=[{id:`se`,label:`iPhone SE 375×667`,width:375,height:667},{id:`iphone14`,label:`iPhone 14 390×844`,width:390,height:844},{id:`promax`,label:`iPhone 15 Pro Max 430×932`,width:430,height:932},{id:`android`,label:`Android 360×800`,width:360,height:800},{id:`tablet`,label:`平板 768×1024`,width:768,height:1024}];function $T(e){return QT.find(t=>t.id===e)??QT.find(e=>e.id===`iphone14`)??QT[0]}function eE(e,t,n=12){if(e.width<=0||e.height<=0)return 1;let r=Math.min((e.width-n*2)/t.width,(e.height-n*2)/t.height,1);return Number.isFinite(r)?Math.max(.25,Math.round(r*100)/100):1}var tE=[`http://localhost:3000`,`https://www.baidu.com`,`https://developer.mozilla.org`],nE=`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals`,rE=`${nE} allow-same-origin`;function iE(e){return ZT(e)??e}function aE(){try{return window.localStorage}catch{return null}}function oE({initialUrl:e=``,onAddNote:t}){let n=J(),[r,i]=(0,C.useState)(e?[e]:[]),[a,o]=(0,C.useState)(e?0:-1),[s,c]=(0,C.useState)(e),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(0),p=(0,C.useRef)(null),m=ET(_r),[h,g]=uf(vr,!1),[_,v]=(0,C.useState)(()=>Yr(yr)),y=(0,C.useMemo)(()=>$T(_),[_]),[b,x]=(0,C.useState)(!1),S=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!b)return;let e=e=>{S.current?.contains(e.target)||x(!1)},t=e=>{e.key===`Escape`&&x(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[b]);let w=(0,C.useRef)(null),[T,E]=(0,C.useState)({width:0,height:0});(0,C.useEffect)(()=>{let e=w.current;if(e===null)return;let t=()=>E({width:e.clientWidth,height:e.clientHeight});t();let n=new ResizeObserver(t);return n.observe(e,{box:`content-box`}),()=>n.disconnect()},[]);let D=h?eE(T,y):1,O=a>=0?r[a]:``,k=(0,C.useMemo)(()=>O?qT(O,{protocol:window.location.protocol,hostname:window.location.hostname,port:window.location.port},{mobile:h}):null,[O,h]),A=k??XT(O,{mobile:h})??O,j=k===null?nE:rE,M=t!==void 0,N=(0,C.useRef)(t);(0,C.useEffect)(()=>{N.current=t},[t]);let[P,F]=(0,C.useState)(!1),[I,L]=(0,C.useState)(()=>(cd(aE(),[]),[])),R=(0,C.useRef)(I);(0,C.useEffect)(()=>{R.current=I},[I]),(0,C.useEffect)(()=>sd(()=>{let e=ad(aE());R.current=e,L(e)}),[]);let z=(0,C.useMemo)(()=>ud(I,iE(O)),[I,O]),B=(0,C.useCallback)(e=>{p.current?.contentWindow?.postMessage({__aw:`picker`,...e},`*`)},[]),V=(0,C.useCallback)(e=>{let t=iE(e.url),n=fd(R.current,{url:t,selector:e.selector,comment:e.comment}),r=n.find(n=>n.url===t&&n.selector===e.selector);R.current=n,L(n),cd(aE(),n),N.current?.({...e,url:t,number:r?.number??1})},[]),H=()=>{let e=md(R.current,iE(O));R.current=e,L(e),cd(aE(),e)},U=(0,C.useCallback)(()=>{B({type:`marks`,list:z.map(e=>({selector:e.selector,number:e.number,comment:e.comment}))})},[z,B]);(0,C.useEffect)(U,[U]),(0,C.useEffect)(()=>{F(!1)},[O,d]),(0,C.useEffect)(()=>{if(!P)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),B({type:`off`}),F(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[P,B]),(0,C.useEffect)(()=>{let e=e=>{let t=p.current;if(t===null||e.source!==t.contentWindow)return;let n=Mu(e.data);n!==null&&(n.kind===`ready`?(U(),F(e=>(e&&B({type:`on`}),e))):n.kind!==`blank`&&(n.kind===`exit`?F(!1):n.kind===`note`?V(n.note):V({...n.pick,comment:``})))};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[U,V,B]);let W=e=>{let t=UT(e);t?(u(null),c(t),i(e=>[...e.slice(0,a+1),t]),o(e=>e+1)):u(n(`这不像是个网址(只支持 http / https)`,`That does not look like a URL (http / https only)`))},ee=()=>{P?(B({type:`off`}),F(!1)):(B({type:`on`}),F(!0))};return(0,Q.jsxs)(`div`,{className:`work-web`,ref:m.ref,...m.pointerHandlers,children:[(0,Q.jsxs)(`div`,{className:`work-web-bar`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>Math.max(0,e-1)),disabled:a<=0,title:n(`后退`,`Back`),children:`←`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>Math.min(r.length-1,e+1)),disabled:a>=r.length-1,title:n(`前进`,`Forward`),children:`→`}),M?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny work-web-pick${P?` work-web-pick-on`:``}`,onClick:ee,disabled:!O,"aria-pressed":P,title:P?n(`退出标注`,`Stop annotating`):n(`标注网页:点页面上要改的那一处,收进输入框那颗「N 条注释」`,`Annotate the page: click the spot to change; it joins the notes in the input`),children:[`📍`,z.length>0?` ${z.length}`:``]}):null,(0,Q.jsxs)(`div`,{className:`work-web-phone-wrap`,ref:S,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny work-web-phone-btn${h?` work-web-phone-on`:``}`,onClick:()=>x(e=>!e),"aria-pressed":h,"aria-haspopup":`menu`,"aria-expanded":b,title:h?n(`手机预览:${y.label}(点开换机型或关闭)`,`Phone preview: ${y.label} (open to change or turn off)`):n(`手机尺寸预览:点开选机型`,`Phone-size preview: open to pick a device`),children:`📱`}),b?(0,Q.jsxs)(`div`,{className:`work-web-phone-menu`,role:`menu`,children:[(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`work-web-phone-item${h?``:` work-web-phone-item-on`}`,onClick:()=>{g(!1),x(!1)},children:n(`关闭手机预览`,`Turn off the phone preview`)}),QT.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`work-web-phone-item${h&&e.id===y.id?` work-web-phone-item-on`:``}`,onClick:()=>{v(e.id),Xr(yr,e.id),g(!0),x(!1)},children:e.label},e.id))]}):null]}),M&&O&&z.length>0?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:H,title:n(`清空这一页的 ${z.length} 处标记`,`Clear the ${z.length} mark(s) on this page`),"aria-label":n(`清空这一页的标记`,`Clear the marks on this page`),children:`⌫`}):null,(0,Q.jsx)(`input`,{className:`work-web-input`,value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&W(s)},placeholder:n(`输入网址后回车(例:localhost:3000)`,`Type a URL and press Enter (e.g. localhost:3000)`),spellCheck:!1}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{M&&O&&z.length>0&&H(),f(e=>e+1)},disabled:!O,title:n(`刷新(同时清空这一页的标记)`,`Reload (also clears the marks on this page)`),children:`↻`}),O?(0,Q.jsx)(`a`,{className:`btn btn-tiny`,href:O,target:`_blank`,rel:`noopener noreferrer`,title:n(`在系统浏览器打开`),children:`⧉`}):null]}),l?(0,Q.jsx)(`div`,{className:`work-web-note work-web-note-error`,children:l}):null,P?(0,Q.jsx)(`div`,{className:`work-web-note work-web-pick-hint`,children:n(`点页面上要改的那一处,就地写一句;可以接着标多处(Esc 退出)`,`Click the spot to change and type right there; keep going for more (Esc to stop)`)}):null,O?(0,Q.jsx)(`div`,{className:`work-web-stage${h?` work-web-stage-phone`:``}`,ref:w,children:(0,Q.jsx)(`div`,{className:`work-web-body${h?` work-web-body-phone`:``}`,style:h?{width:`${y.width}px`,height:`${y.height}px`,zoom:D*m.percent/100}:{zoom:m.percent/100},children:(0,Q.jsx)(`iframe`,{ref:p,className:`work-web-frame`,src:A,title:O,sandbox:j,referrerPolicy:`no-referrer`},`${O}#${d}#${h?`m`:`d`}`)})}):(0,Q.jsxs)(`div`,{className:`work-web-start`,children:[(0,Q.jsx)(`p`,{className:`side-panel-hint`,children:n(`输入网址就能在这儿打开(经本机代理,拒绝被嵌入的站点也能显示)`,`Enter a URL to open it here (served through the local proxy, so sites that refuse embedding still work)`)}),(0,Q.jsx)(`p`,{className:`side-panel-hint work-web-caveat`,children:n(`代理不带 cookie、跑在隔离沙箱里:要重登录的站点(GitHub、后台系统)可能是一片空白;面板里跑不起来的页面会提示你『在新窗口打开』。`,`The proxy carries no cookies and runs in an isolated sandbox: sites that need a session (GitHub, admin consoles) may stay blank, and pages that cannot run in a panel will offer “Open in a window”.`)}),(0,Q.jsx)(`div`,{className:`work-web-suggestions`,children:tE.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`tpl-card`,onClick:()=>W(e),children:(0,Q.jsx)(`span`,{className:`tpl-card-title`,children:e.replace(/^https?:\/\//,``)})},e))})]})]})}function sE({point:e,isDir:t,onReveal:n,onTerminal:r,onAddToConversation:i,onChanges:a,changesOnly:o=!1,onFind:s,onClose:c}){let l=J(),u=e=>()=>{e(),c()};return(0,Q.jsxs)(qd,{point:e,pointerTail:!0,className:`proj-menu ctx-menu`,onClose:c,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(n),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`📂`}),l(`打开`,`Open`)]}),t&&r?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(r),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`⌨️`}),l(`在集成终端中打开`,`Open in integrated terminal`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(i),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`💬`}),l(`添加到对话`,`Add to conversation`)]}),a?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(a),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:o?`📄`:`📝`}),o?l(`所有文件`,`All files`):l(`改动过的文件`,`Changed files`)]}):null,s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(s),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`🔍`}),t?l(`在文件夹中查找…`,`Find in folder…`):l(`在所在文件夹中查找…`,`Find in its folder…`)]})]}):null]})}var cE={modified:`M`,added:`A`,deleted:`D`,untracked:`U`,renamed:`R`,conflicted:`!`},lE=[`conflicted`,`deleted`,`modified`,`renamed`,`added`,`untracked`];function uE(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=n.split(`/`);for(let n=e.length-1;n>=1;--n){let i=e.slice(0,n).join(`/`),a=t.get(i);(a===void 0||lE.indexOf(r.status)<lE.indexOf(a))&&t.set(i,r.status)}}return t}function dE(e,t,n){let[r,i]=(0,C.useState)({isRepo:!1,entries:{}}),[a,o]=(0,C.useState)(0),[s,c]=(0,C.useState)(n);return s!==n&&(c(n),s&&o(e=>e+1)),(0,C.useEffect)(()=>{if(!e){i({isRepo:!1,entries:{}});return}let t=!1;return(async()=>{try{let n=await fetch(`/api/files/git/status?root=${encodeURIComponent(e)}`);if(t)return;if(!n.ok){console.warn(`[git status] ${n.status} — 服务端可能还在跑旧版本,重启一次即可`),i({isRepo:!1,entries:{}});return}i(await n.json())}catch{t||i({isRepo:!1,entries:{}})}})(),()=>{t=!0}},[e,t,a]),r}async function fE(e,t,n=!1){try{let r=await fetch(`/api/files/list?path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}${n?`&hidden=1`:``}`),i=await r.json();return r.ok?{entries:i.entries??[]}:{error:i.error?.message??`HTTP ${r.status}`}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}function pE({root:e,showHidden:t=!1,statusRevision:n=``,running:r=!1,activePath:i=null,revealSeq:a=0,revealPath:o=null,onNeedHidden:s,onOpenFile:c,onOpenTerminalAt:l,onFindInFolder:u,changesOnly:d=!1,onToggleChangesOnly:f,onOpenChangedFile:p}){let m=J(),[h,g]=(0,C.useState)(null),_=t=>e?`${e.replace(/[\\/]+$/,``)}/${t}`:t,v=e=>{fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:_(e)})})},y=dE(e,n,r),b=(0,C.useMemo)(()=>uE(y.entries),[y.entries]),[x,S]=(0,C.useState)([]),[w,T]=(0,C.useState)(null),E=(0,C.useRef)([]),k=e=>{let t=e(E.current);E.current=t,S(t)},A=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(k(()=>[]),T(null),!e)return;let n=!1;return fE(``,e,t).then(({entries:e,error:t})=>{n||(t?T(t):k(()=>(e??[]).map(e=>({entry:e,depth:0,expanded:!1,loading:!1,children:null,error:null}))))}),()=>{n=!0}},[e,t]);let j=async n=>{let r=E.current.find(e=>e.entry.path===n);if(!r||r.expanded&&r.children!==null)return;k(e=>e.map(e=>e.entry.path===n?{...e,expanded:!0,loading:!0}:e));let{entries:i,error:a}=await fE(n,e,t);k(e=>{let t=e.findIndex(e=>e.entry.path===n&&e.expanded),r=t<0?void 0:e[t];if(!r)return e;let o=e.slice(0,t+1).map((e,n)=>n===t?{...e,loading:!1,children:i??null,error:a??null}:e);if(a||!i)return[...o,...e.slice(t+1)];let s=i.map(e=>({entry:e,depth:r.depth+1,expanded:!1,loading:!1,children:null,error:null}));return[...o,...s,...e.slice(t+1)]})},M=async e=>{let t=E.current.find(t=>t.entry.path===e);t&&(t.expanded?k(t=>{let n=t.findIndex(t=>t.entry.path===e);return n<0?t:yd(t,n)}):await j(e))},[N,P]=(0,C.useState)(null),F=(0,C.useRef)(-1);(0,C.useEffect)(()=>{if(F.current===a)return;F.current=a;let e=o??i;a!==0&&e&&P(e)},[a,o,i]);let I=x.length>0;return(0,C.useEffect)(()=>{if(N===null||!I)return;let e=!1;return(async()=>{for(let n of bd(N)){let r=E.current.find(e=>e.entry.path===n);if(!r){!t&&Sd(N)!==null&&s?.();return}if(r.expanded||await j(n),e)return}let n=E.current.find(e=>e.entry.path===N);n?.entry.isDir&&!n.expanded&&await j(N),!e&&(P(null),requestAnimationFrame(()=>{(A.current?.querySelector(`[data-path="${CSS.escape(N)}"]`))?.scrollIntoView({block:`nearest`})}))})(),()=>{e=!0}},[N,I]),e?(0,Q.jsxs)(`div`,{className:`filetree`,ref:A,children:[w?(0,Q.jsx)(`div`,{className:`filetree-error`,children:w}):null,d?(()=>{let e=Object.keys(y.entries).sort((e,t)=>e.localeCompare(t));return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`filetree-changes-head`,children:[(0,Q.jsxs)(`span`,{className:`filetree-changes-title`,children:[m(`改动过的文件`,`Changed files`),` · `,e.length]}),f?(0,Q.jsx)(`button`,{type:`button`,className:`filetree-changes-exit`,onClick:f,title:m(`回到普通的文件树`,`Back to the file tree`),children:m(`所有文件`,`All files`)}):null]}),y.isRepo?e.length===0?(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`没有改动过的文件。`,`No changed files.`)}):e.map(e=>{let t=y.entries[e],n=D(e),r=zp(n);return(0,Q.jsx)(`div`,{className:`filetree-item`,children:(0,Q.jsxs)(`button`,{type:`button`,"data-path":e,className:`filetree-row filetree-file filetree-${t.status}${e===i?` filetree-row-on`:``}`,style:{paddingLeft:8},title:e,onClick:()=>(p??c)(e),onContextMenu:t=>{t.preventDefault(),g({entry:{name:n,path:e,isDir:!1},point:{x:t.clientX,y:t.clientY}})},children:[(0,Q.jsx)(`span`,{className:`filetree-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`filetree-type${r?` filetype-${r.tone}`:``}`,"aria-hidden":`true`,children:r?r.label:`▤`}),(0,Q.jsx)(`span`,{className:`filetree-name`,children:n}),O(e)?(0,Q.jsx)(`span`,{className:`filetree-changes-dir`,children:O(e)}):null,(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${t.status}`,"aria-hidden":`true`,children:cE[t.status]})]})},e)}):(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`这个目录不是 git 仓库。`,`Not a git repository.`)})]})})():x.map((e,t)=>{let n=y.entries[e.entry.path],r=b.get(e.entry.path),a=e.entry.isDir?r:n?.status,o=e.entry.isDir?null:zp(e.entry.name),s=e.entry.isDir?e.entry.path:n?`${e.entry.path}\n${cE[n.status]}${n.added||n.removed?` · +${n.added} −${n.removed}`:``}`:e.entry.path;return(0,Q.jsxs)(`div`,{className:`filetree-item`,children:[(0,Q.jsxs)(`button`,{type:`button`,"data-path":e.entry.path,className:`filetree-row filetree-${e.entry.isDir?`dir`:`file`}${a?` filetree-${a}`:``}${!e.entry.isDir&&e.entry.path===i?` filetree-row-on`:``}`,style:{paddingLeft:8+e.depth*14},onClick:()=>e.entry.isDir?void M(e.entry.path):c(e.entry.path),title:s,onContextMenu:t=>{t.preventDefault(),g({entry:e.entry,point:{x:t.clientX,y:t.clientY}})},children:[(0,Q.jsx)(`span`,{className:`filetree-icon`,"aria-hidden":`true`,children:e.entry.isDir?e.expanded?`▾`:`▸`:null}),e.entry.isDir?(0,Q.jsx)(ap,{open:e.expanded,className:`filetree-folder${e.expanded?` filetree-folder-open`:``}`}):(0,Q.jsx)(`span`,{className:`filetree-type${o?` filetype-${o.tone}`:``}`,"aria-hidden":`true`,children:o?o.label:`▤`}),(0,Q.jsx)(`span`,{className:`filetree-name`,children:e.entry.name}),e.loading?(0,Q.jsx)(`span`,{className:`filetree-hint`,children:`…`}):null,e.entry.isDir?a?(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${a} filetree-status-dot`,"aria-hidden":`true`}):null:a?(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${a}`,"aria-hidden":`true`,children:cE[a]}):null]}),e.entry.isDir?null:(0,Q.jsxs)(`button`,{type:`button`,className:`filetree-mention`,title:m(`把 @${e.entry.path} 加到对话`,`Add @${e.entry.path} to the conversation`),onClick:()=>So(`${Uw(e.entry.path,null)} `),children:[`@ `,m(`提及`,`mention`)]}),e.error?(0,Q.jsx)(`div`,{className:`filetree-error`,children:e.error}):null]},e.entry.path||t)}),h?(0,Q.jsx)(sE,{point:h.point,isDir:h.entry.isDir,onReveal:()=>v(h.entry.path),onTerminal:l&&h.entry.isDir?()=>l(_(h.entry.path)):void 0,onAddToConversation:()=>So(`${Uw(h.entry.path,null)} `),onFind:u?()=>u(h.entry.isDir?h.entry.path:O(h.entry.path)):void 0,changesOnly:d,onChanges:f&&(d||y.isRepo&&Object.keys(y.entries).length>0)?f:void 0,onClose:()=>g(null)}):null]}):(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`还没有打开会话,不知道是哪个项目。`)})}function mE({text:e,keys:t,children:n}){return(0,Q.jsx)(`span`,{className:`files-tool-tip`,"data-tip":e,...t?{"data-key":t}:{},children:n})}function hE(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`4.5`,cy:`3.6`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`circle`,{cx:`4.5`,cy:`12.4`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`circle`,{cx:`11.5`,cy:`6.2`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`path`,{d:`M4.5 5.3v5.4M11.5 7.9c0 2-2.4 2-4.4 2.4`,stroke:`currentColor`,strokeWidth:`1.2`,fill:`none`,strokeLinecap:`round`})]})}function gE({git:e}){let t=J(),[n,r]=(0,C.useState)(!1),[i,a]=(0,C.useState)(null);if(!e.isRepo)return null;let o=e.branch??`detached`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,ref:a,className:`files-branch${n?` files-branch-open`:``}`,title:t(`当前 git 分支:${o}(点开切换)`,`Current git branch: ${o} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>{n||e.refresh(),r(e=>!e)},children:[(0,Q.jsx)(hE,{}),(0,Q.jsx)(`span`,{className:`files-branch-name`,children:o})]}),n&&i?(0,Q.jsx)(sp,{anchor:i,git:e,onClose:()=>r(!1)}):null]})}function _E({root:e,showHidden:t,onToggleHidden:n,onOpenTerminal:r,onReveal:i,onRefresh:a,onSearchContents:o,search:s,changesOnly:c=!1,changedCount:l=0,onShowChanges:u}){let d=J(),[f]=xc(),p=cc(f.contentSearch,oc()),m=p?{zh:`搜索文件内容(${p})`,en:`Search file contents (${p})`}:{zh:`搜索文件内容`,en:`Search file contents`};return(0,Q.jsxs)(`div`,{className:`files-toolbar`,children:[(0,Q.jsx)(mE,{text:d(`刷新文件列表`,`Refresh the file list`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool`,"aria-label":d(`刷新文件列表`,`Refresh the file list`),onClick:a,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M12.9 8a5.2 5.2 0 1 1-5.2-5.2c1.46 0 2.85.58 3.89 1.59L12.9 5.3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`M12.9 2.1v3.2h-3.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})}),(0,Q.jsx)(mE,{text:t?d(`隐藏点开头的文件`,`Hide dot-prefixed files`):d(`显示隐藏文件(.env 等)`,`Show hidden files (.env etc.)`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool${t?` files-tool-on`:``}`,"aria-label":d(`显示 / 隐藏以点开头的文件`,`Show / hide dot-prefixed files`),"aria-pressed":t,onClick:n,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M1.6 8s2.3-4 6.4-4 6.4 4 6.4 4-2.3 4-6.4 4S1.6 8 1.6 8Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinejoin:`round`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.9`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`})]})})}),(0,Q.jsx)(mE,{text:d(`按文件名搜索`,`Search by file name`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool${s.active?` files-tool-on`:``}`,"aria-label":d(`按文件名搜索`,`Search by file name`),"aria-pressed":s.active,onClick:s.toggle,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`path`,{d:`m10.2 10.2 3.2 3.2`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`})]})})}),(0,Q.jsx)(mE,{text:d(`搜索文件内容`,`Search file contents`),keys:p||void 0,children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool`,"aria-label":d(m.zh,m.en),onClick:o,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2.4 3.2h8.2M2.4 6.1h8.2M2.4 9h4.6`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.25`,strokeLinecap:`round`}),(0,Q.jsx)(`circle`,{cx:`10.3`,cy:`10.1`,r:`2.5`,fill:`var(--bg-elev)`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`path`,{d:`m12.2 12 2 2`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`})]})})}),u&&l>0?(0,Q.jsx)(mE,{text:d(`改动过的文件(${l} 个):点一下看最新的改动`,`Changed files (${l}): click to list the latest`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-diff${c?` files-tool-on`:``}`,"aria-label":d(`查看改动过的文件`,`Show changed files`),"aria-pressed":c,onClick:u,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`1.7`,y:`2.7`,width:`12.6`,height:`10.6`,rx:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.15`}),(0,Q.jsx)(`path`,{d:`M8 3v10`,stroke:`currentColor`,strokeWidth:`1`,opacity:`0.45`}),(0,Q.jsx)(`path`,{d:`M3.4 6.1h3.1M3.4 9.3h2.2`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`M9.5 6.1h2.9M10.95 4.65v2.9M9.5 9.3h2.9`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})]})})}):null,(0,Q.jsx)(mE,{text:d(`在底部终端中打开`,`Open in the bottom terminal`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-terminal`,"aria-label":d(`在底部终端中打开`,`Open in the bottom terminal`),onClick:r,children:`>_`})}),(0,Q.jsx)(mE,{text:d(`在 Finder 中显示这个目录`,`Reveal this folder in Finder`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-reveal`,"aria-label":d(`在 Finder 中显示这个目录`,`Reveal this folder in Finder`),onClick:i,disabled:!e,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M1.8 4.3c0-.6.5-1.1 1.1-1.1h2.7l1.3 1.5h5.2c.6 0 1.1.5 1.1 1.1v5.5c0 .6-.5 1.1-1.1 1.1H2.9c-.6 0-1.1-.5-1.1-1.1V4.3Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinejoin:`round`})})})})]})}function vE({search:e,placeholder:t}){let n=J();return(0,Q.jsx)(`input`,{ref:e.inputRef,className:`files-search`,value:e.query,placeholder:t??n(`搜索文件名…`),onChange:t=>e.setQuery(t.target.value),onKeyDown:t=>{t.key===`Escape`&&e.close()}})}function yE({entries:e,truncated:t,onPick:n}){let r=J(),i=e.slice(0,60);return e.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有匹配的文件名`)}):(0,Q.jsxs)(`div`,{className:`files-search-list`,children:[i.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`files-search-row`,title:e.path,onClick:()=>n(e),children:[(0,Q.jsx)(`span`,{className:`files-search-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`files-search-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)})]},e.path)),t?(0,Q.jsx)(`div`,{className:`files-search-more`,children:r(`结果太多,只显示前 200 个`)}):null]})}function bE({value:e,options:t,onChange:n}){let r=J(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),c=t.find(t=>t.cwd===e)?.label??(e===``?r(`跟随当前会话`,`Follow the current session`):D(e)||e),l=e=>{n(e),s(!1)};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,ref:a,className:`side-files-root${o?` side-files-root-open`:``}`,title:e===``?r(`文件树跟着当前会话走(点一下可换项目)`,`The tree follows the current session (click to pick another project)`):r(`文件树根目录:${e}`,`Tree root: ${e}`),"aria-haspopup":`listbox`,"aria-expanded":o,onClick:()=>s(e=>!e),children:[(0,Q.jsx)(`span`,{className:`side-files-root-label`,children:c}),(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,className:`side-files-root-caret`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4.4 6.4 3.6 3.6 3.6-3.6`})})]}),o&&i?(0,Q.jsxs)(qd,{anchor:i,className:`proj-menu files-root-menu`,style:{width:Math.min(320,Math.max(200,i.getBoundingClientRect().width))},onClose:()=>s(!1),children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${e===``?` files-root-option-on`:``}`,onClick:()=>l(null),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:e===``?`✓`:``}),r(`跟随当前会话`,`Follow the current session`)]}),t.length>0?(0,Q.jsx)(`div`,{className:`files-root-sep`}):null,t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${e===t.cwd?` files-root-option-on`:``}`,title:t.cwd,onClick:()=>l(t.cwd),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:e===t.cwd?`✓`:``}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:t.label})]},t.cwd))]}):null]})}var xE=[];function SE(e,t){let[n,r]=(0,C.useState)(!1),i=t?.always===!0,[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(xE),[l,u]=(0,C.useState)(!1),d=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!(i||n)||!e)return;let t=a.trim();if(t===``){c(xE),u(!1);return}let r=!1,o=setTimeout(()=>{(async()=>{try{let n=await(await fetch(`/api/files/search?q=${encodeURIComponent(t)}&root=${encodeURIComponent(e)}`)).json();if(r)return;c(n.entries??xE),u(n.truncated===!0)}catch{if(r)return;c(xE)}})()},250);return()=>{r=!0,clearTimeout(o)}},[n,a,e]),(0,C.useEffect)(()=>{e||c(xE)},[e]),(0,C.useEffect)(()=>{n&&d.current?.focus()},[n]);let f=(0,C.useCallback)(()=>{r(!1),o(``),c(xE),u(!1)},[]);return{active:n,query:a,results:s,truncated:l,inputRef:d,setQuery:o,toggle:(0,C.useCallback)(()=>{r(e=>!e),o(``),c(xE),u(!1)},[]),close:f}}function CE({variant:e=`sidebar`,open:t,onToggle:n,height:r,fill:i=!1,root:a,onRootChange:o,options:s,onOpenFile:c,onOpenChangedFile:l,onOpenTerminal:u,onOpenBottomTerminal:d,onFindInFolder:f,onReveal:p,onSearchContents:m,activePath:h,revealSeq:g,revealPath:_,onRevealPath:v}){let y=J(),[b,x]=(0,C.useState)(!1),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(0),D=SE(a),O=ep(a),k=Ro(e=>e.snapshot),A=k!==null&&k.running.status!==`idle`&&k.running.conversationId===k.active.conversationId,{active:j,close:M}=D;(0,C.useEffect)(()=>{!t&&j&&M()},[t,j,M]);let N=j&&D.query.trim()!==``,P=dE(a,`${O.branch??``}:${T}`,A),F=Object.keys(P.entries).length,I=()=>{t||n(),w(!0),E(e=>e+1),O.refresh()};(0,C.useEffect)(()=>{S&&P.isRepo&&F===0&&w(!1)},[S,P.isRepo,F]);let L=e===`panel`;return(0,Q.jsxs)(`section`,{className:`side-files${t?``:` side-files-closed`}${i&&t?` side-files-fill`:``}${L?` side-files-panel`:``}`,style:{height:t&&!i&&!L?r:void 0},children:[(0,Q.jsxs)(`div`,{className:`side-files-head`,children:[L?null:(0,Q.jsxs)(`button`,{type:`button`,className:`side-files-title`,onClick:n,title:t?y(`收起文件`,`Collapse files`):y(`展开文件`,`Expand files`),"aria-expanded":t,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${t?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:y(`文件`,`Files`)})]}),(0,Q.jsx)(_E,{root:a,showHidden:b,onToggleHidden:()=>x(e=>!e),onOpenTerminal:u,onReveal:()=>a&&p?.(a),onRefresh:()=>{E(e=>e+1),O.refresh()},onSearchContents:()=>m?.(),search:D,changesOnly:S,changedCount:F,onShowChanges:I}),L?null:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-row-fill`,"aria-hidden":`true`,tabIndex:-1,onClick:n})]}),t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`side-files-select-row`,children:[(0,Q.jsx)(bE,{value:a??``,options:s,onChange:o}),(0,Q.jsx)(gE,{git:O})]}),j?(0,Q.jsx)(vE,{search:D}):null,(0,Q.jsx)(`div`,{className:`side-files-body`,children:N?(0,Q.jsx)(yE,{entries:D.results,truncated:D.truncated,onPick:e=>{e.isDir?v?.(e.path):c(e.path),D.setQuery(``)}}):(0,Q.jsx)(pE,{root:a,showHidden:b,statusRevision:`${O.branch??``}:${T}`,running:A,activePath:h??null,revealSeq:g??0,revealPath:_??null,onNeedHidden:()=>x(!0),onOpenTerminalAt:d,onFindInFolder:f,changesOnly:S,onToggleChangesOnly:()=>w(e=>!e),onOpenFile:c,onOpenChangedFile:l},`${a??``}:${O.branch??``}:${T}`)})]}):null]})}function wE(e){return(0,Q.jsx)(CE,{variant:`panel`,open:!0,height:0,onToggle:()=>{},...e})}function TE({root:e,activePath:t,onOpenFile:n,width:r,revealSeq:i=0}){let a=J(),o=SE(e,{always:!0}),[s,c]=(0,C.useState)(!1),[l,u]=(0,C.useState)(0),d=o.query.trim()!==``,f=e?D(e):a(`文件`,`Files`);return(0,Q.jsxs)(`aside`,{className:`preview-files`,"aria-label":a(`文件列表`,`File list`),style:r?{width:r}:void 0,children:[(0,Q.jsxs)(`div`,{className:`preview-files-head`,children:[(0,Q.jsxs)(`span`,{className:`preview-files-title`,children:[(0,Q.jsx)(`span`,{className:`preview-files-label`,children:a(`文件列表`,`Files`)}),e?(0,Q.jsx)(`span`,{className:`preview-files-root`,title:e,children:` · ${f}`}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${s?` btn-wide-on`:``}`,onClick:()=>c(e=>!e),title:a(`显示隐藏文件`,`Show hidden files`),children:`👁`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>u(e=>e+1),title:a(`刷新(重新拉一次改动状态)`,`Refresh (re-read the changes)`),children:`↻`})]}),(0,Q.jsx)(vE,{search:o,placeholder:a(`筛选文件…`,`Filter files…`)}),(0,Q.jsx)(`div`,{className:`preview-files-body`,children:d?(0,Q.jsx)(yE,{entries:o.results,truncated:o.truncated,onPick:e=>{e.isDir||n(e.path)}}):(0,Q.jsx)(pE,{root:e,showHidden:s,statusRevision:String(l),activePath:t,revealSeq:i,onNeedHidden:()=>c(!0),onOpenFile:n})})]})}function EE({conversationId:e}){let t=J();return e?(0,Q.jsx)(`div`,{className:`session-history`,children:(0,Q.jsx)(`iframe`,{className:`session-history-frame`,title:t(`完整历史`,`Full history`),src:`/api/sessions/${encodeURIComponent(e)}/history`},e)}):(0,Q.jsx)(`div`,{className:`session-view-empty`,children:t(`先打开一条会话。`,`Open a session first.`)})}function DE({conversationId:e,active:t=!0}){let n=J(),[r,i]=(0,C.useState)({status:`loading`}),[a,o]=(0,C.useState)(0);if((0,C.useEffect)(()=>{if(!e){i({status:`error`,message:n(`先打开一条会话。`,`Open a session first.`)});return}if(!t)return;let r=!1;return i({status:`loading`}),fetch(`/api/sessions/${encodeURIComponent(e)}/system-prompt`).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok){let n=typeof t?.error?.message==`string`?t.error.message:`HTTP ${e.status}`;throw Error(n)}return typeof t?.prompt==`string`?t.prompt:``}).then(e=>{r||i({status:`ready`,prompt:e})}).catch(e=>{r||i({status:`error`,message:e instanceof Error?e.message:String(e)})}),()=>{r=!0}},[e,a,t,n]),r.status===`loading`)return(0,Q.jsx)(`div`,{className:`session-view-empty`,children:n(`正在读取系统提示词…`,`Reading the system prompt…`)});if(r.status===`error`)return(0,Q.jsxs)(`div`,{className:`session-view-empty session-view-error`,children:[(0,Q.jsx)(`div`,{children:r.message}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>e+1),children:n(`重读`,`Retry`)})]});let s=r.prompt,c=s===``?0:s.split(`
76
- `).length;return(0,Q.jsxs)(`div`,{className:`session-prompt`,children:[(0,Q.jsxs)(`div`,{className:`session-prompt-head`,children:[(0,Q.jsx)(`span`,{className:`session-prompt-meta`,children:c>0?n(`${c} 行 · ${s.length.toLocaleString()} 字符`,`${c} lines · ${s.length.toLocaleString()} chars`):n(`这段是空的`,`This is empty`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,title:n(`重新读取`,`Read again`),onClick:()=>o(e=>e+1),children:`↻`}),(0,Q.jsx)(ah,{text:s,className:`btn btn-tiny`,title:`复制系统提示词`})]}),(0,Q.jsx)(`pre`,{className:`session-prompt-body`,children:s})]})}var OE=.2,kE=2.5,AE=5,jE=6,ME=240,NE=`pop-agent.canvas.style.v1`,PE={task:{icon:`•`,zh:`待办项`,en:`Task`},milestone:{icon:`▲`,zh:`里程碑`,en:`Milestone`},risk:{icon:`!`,zh:`风险`,en:`Risk`},doc:{icon:`▤`,zh:`参考`,en:`Doc`},decision:{icon:`◆`,zh:`决策`,en:`Decision`}};function FE(e){return e.kind&&PE[e.kind]?e.kind:`task`}function IE(e,t){let n=new Map;for(let t of e)n.set(t.id,[]);for(let e of t)n.get(e.to)?.push(e.from);let r=new Map,i=new Set,a=e=>{let t=r.get(e);if(t!==void 0)return t;if(i.has(e))return 0;i.add(e);let o=0;for(let t of n.get(e)??[])o=Math.max(o,a(t)+1);return i.delete(e),r.set(e,o),o},o=new Map;for(let t of e)o.set(t.id,a(t.id));return o}function LE(e,t,n){let r=new Map;if(e.length===0)return r;let i=new Map;for(let t of e)i.set(t.id,0);let a=new Map;for(let e of t){i.set(e.to,(i.get(e.to)??0)+1);let t=a.get(e.from)??[];t.push(e.to),a.set(e.from,t)}let o=new Set,s=64,c=(e,t,i)=>{if(o.has(e))return r.get(e)?.y??s;if(i.has(e))return s;i.add(e),o.add(e);let l=(a.get(e)??[]).filter(e=>!o.has(e)&&!i.has(e)),u;if(l.length===0)u=s,s+=n(e)+20;else{let r=l.map(e=>c(e,t+1,i)),a=r[0]+n(l[0])/2,o=l[l.length-1];u=(a+(r[r.length-1]+n(o)/2))/2-n(e)/2}return i.delete(e),r.set(e,{x:40+t*340,y:u}),u},l=e.filter(e=>(i.get(e.id)??0)===0).map(e=>e.id);l.length===0&&e[0]!==void 0&&l.push(e[0].id);for(let e of l)c(e,0,new Set);let u=e.filter(e=>!o.has(e.id));for(let e of u)r.set(e.id,{x:40,y:s}),s+=n(e.id)+20;return r}function RE(e,t,n){let r=new Map,i=[];if(e.length===0)return{positions:r,bands:i};let a=new Map,o=new Map;for(let t of e)o.set(t.id,0);for(let e of t)a.set(e.from,[...a.get(e.from)??[],e.to]),o.set(e.to,(o.get(e.to)??0)+1);let s=e.find(e=>(o.get(e.id)??0)===0)??e[0],c=(a.get(s.id)??[]).filter(t=>e.some(e=>e.id===t)),l=e=>{let t=[],n=[e],r=new Set;for(;n.length>0;){let e=n.pop();if(!(r.has(e)||e===s.id)){r.add(e),t.push(e);for(let t of a.get(e)??[])n.push(t)}}return t},u=64,d=(e,t,a)=>{if(t.length===0)return;let o=new Map;for(let e of t){let t=a.get(e)??0;o.set(t,[...o.get(t)??[],e])}let s=[...o.keys()].sort((e,t)=>e-t),c=0,l=u+26+8,d=new Map;for(let e of s){let t=o.get(e),r=l,i=0;for(let e of t)d.set(e,r),r+=n(e)+18,i=Math.max(i,n(e));l=r,c=Math.max(c,l-u)}c=Math.max(c,82)+16;let f=s[s.length-1]??0,p=s[0]??0;i.push({x:24,y:u,w:(f-p+1)*320+32,h:c,label:e});for(let e of t)r.set(e,{x:40+((a.get(e)??0)-p)*320,y:d.get(e)??u+26+8});u+=c+26},f=IE(e,t);if(c.length===0)d(s.title,e.filter(e=>e.id!==s.id).map(e=>e.id),f);else{let t=new Set;for(let n of c){let r=e.find(e=>e.id===n)?.title??n,i=l(n);for(let e of i)t.add(e);d(r,i,f)}d(`其他`,e.filter(e=>e.id!==s.id&&!t.has(e.id)).map(e=>e.id),f)}let p=n(s.id);r.set(s.id,{x:40,y:64});for(let e of i)e.y+=p+26;for(let[e,t]of r)e!==s.id&&r.set(e,{x:t.x,y:t.y+p+26});return{positions:r,bands:i}}var zE=`pop-agent.canvas.moves.v1`;function BE(){try{let e=localStorage.getItem(zE);if(e===null)return{};let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function VE(e){try{localStorage.setItem(zE,JSON.stringify(e))}catch{}}function HE(e){try{let t=localStorage.getItem(NE);if(t===null||e===null)return`card`;let n=JSON.parse(t)?.[e];return n===`timeline`||n===`checklist`||n===`mindmap`||n===`swimlane`?n:`card`}catch{return`card`}}function UE(e,t){if(e!==null)try{let n=localStorage.getItem(NE),r=n===null?{}:JSON.parse(n);r[e]=t,localStorage.setItem(NE,JSON.stringify(r))}catch{}}function WE(e){return e.status===`doing`?{tone:`doing`,zh:`正在做`,en:`Doing`}:e.status===`done`?{tone:`done`,zh:`已完成`,en:`Done`}:e.status===`blocked`?{tone:`blocked`,zh:`卡住了`,en:`Blocked`}:{tone:`todo`,zh:`待办`,en:`To do`}}function GE(e,t){let n=typeof e.turnStartedAt==`number`&&e.turnStartedAt>0?`${Math.max(0,Math.floor((Date.now()-e.turnStartedAt)/1e3))}s`:``,r=e.activeTool?.name;if(r){let t=(e.activeTool?.argsSummary??``).replace(/\s+/g,` `).trim(),i=t.length>26?`${t.slice(0,26)}…`:t;return[i===``?`正在 ${r}`:`正在 ${r} · ${i}`,n].filter(Boolean).join(` · `)}return e.retrying?[t(`等模型重试…`,`Retrying…`),n].filter(Boolean).join(` · `):e.status===`awaiting_approval`?t(`等你确认`,`Waiting for you`):[t(`正在输出…`,`Writing…`),n].filter(Boolean).join(` · `)}function KE(e,t,n){let r=null;for(let i of e)for(let e of t){let t=e-i;Math.abs(t)>n||(r===null||Math.abs(t)<Math.abs(r.delta))&&(r={delta:t,at:e})}return r}function qE({onOpenFile:e}){let t=J(),{snapshot:n,newSession:r,pendingNewChat:i}=Lo(),a=r!==null||i,o=a?null:n?.canvas??null,s=a?null:n?.active.conversationId??null,[c,l]=(0,C.useState)([]),u=c.length===0?null:c[c.length-1]??null;(0,C.useEffect)(()=>{l([])},[s]);let d=(0,C.useMemo)(()=>{if(o===null)return{nodes:[],edges:[],host:null};if(u===null)return{nodes:o.nodes,edges:o.edges,host:null};let e=o.nodes.find(e=>e.id===u)??null;return{nodes:e?.sub?.nodes??[],edges:e?.sub?.edges??[],host:e}},[o,u]);(0,C.useEffect)(()=>{u!==null&&d.host===null&&l([])},[u,d.host]);let f=(0,C.useRef)(null),p=(0,C.useRef)(null),m=(0,C.useRef)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(null),_=(0,C.useRef)(null),v=(0,C.useRef)(null),y=(0,C.useRef)({x:0,y:0,k:1}),[b,x]=(0,C.useState)({}),[S,w]=(0,C.useState)(null),[T,E]=(0,C.useState)(null),[D,O]=(0,C.useState)([]),[k,A]=(0,C.useState)(!1),[j,M]=(0,C.useState)(null),[N,P]=(0,C.useState)(null),F=(0,C.useCallback)((e,t=null)=>{let n=p.current?.getBoundingClientRect();return{x:e.clientX-(n?.left??0),y:e.clientY-(n?.top??0),nodeId:t}},[]),I=S?.nodeId===null?9:13,L=(0,C.useCallback)(()=>w(null),[]),[R,z]=(0,C.useState)([]),B=(0,C.useRef)(new Set);(0,C.useLayoutEffect)(()=>{B.current=new Set(R)},[R]);let V=n?.canvasRunningNodeId??null,H=s===null?void 0:n?.runningByConversation?.[s],[,U]=(0,C.useState)(0);(0,C.useEffect)(()=>{if(V===null)return;let e=window.setInterval(()=>U(e=>e+1),1e3);return()=>window.clearInterval(e)},[V]);let[W,ee]=(0,C.useState)({}),G=(0,C.useRef)(new Map),[K,te]=(0,C.useState)(()=>HE(s)),ne=(0,C.useRef)(K);(0,C.useLayoutEffect)(()=>{ne.current=K},[K]),(0,C.useEffect)(()=>{te(HE(s))},[s,u]);let re=(0,C.useCallback)(e=>{te(e),UE(s,e)},[s]),ie=(0,C.useMemo)(()=>{if(K===`card`||o===null)return{positions:null,bands:[]};if(K===`swimlane`)return RE(d.nodes,d.edges,e=>W[e]??128);let e=IE(d.nodes,d.edges),t=[...d.nodes].sort((t,n)=>(e.get(t.id)??0)-(e.get(n.id)??0)||(t.order??0)-(n.order??0)),n=e=>W[e]??128,r=new Map;if(K===`mindmap`)return{positions:LE(d.nodes,d.edges,e=>W[e]??128),bands:[]};if(K===`timeline`){let i=new Map;for(let a of t){let t=e.get(a.id)??0,o=i.get(t)??64;r.set(a.id,{x:40+t*300,y:o}),i.set(t,o+n(a.id)+22)}return{positions:r,bands:[]}}{let e=64;for(let i of t)r.set(i.id,{x:40,y:e}),e+=n(i.id)+22}return{positions:r,bands:[]}},[d,K,W]),ae=ie.positions,oe=ie.bands,[se,ce]=(0,C.useState)(BE),le=K===`card`?void 0:se[s??``]?.[K],ue=(0,C.useCallback)(e=>le?.[e.id]??ae?.get(e.id)??b[e.id]??{x:e.x,y:e.y},[ae,b,le]);(0,C.useEffect)(()=>{let e=e=>{if(!ye.current)return;let t=e.target;(t===null||!t.isContentEditable&&!/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))&&(e.key===`Escape`?(L(),P(null),z([])):(e.metaKey||e.ctrlKey)&&(e.key===`a`||e.key===`A`)?(e.preventDefault(),z((o?.nodes??[]).map(e=>e.id))):(e.key===`Delete`||e.key===`Backspace`)&&R.length>0&&s!==null&&(e.preventDefault(),su(s,R),z([])))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[L,s,o,R]);let de=o?.rev??0;(0,C.useEffect)(()=>{x({})},[de]),(0,C.useLayoutEffect)(()=>{let e={};for(let[t,n]of G.current)e[t]=n.offsetHeight;Object.keys(e).length!==0&&ee(t=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n)?t:e)},[de,b,V,H?.status,H?.activeTool?.name,K]);let fe=(0,C.useCallback)(()=>{let e=y.current,t=m.current,n=f.current;if(!t||!n)return;t.style.transform=`translate3d(${e.x}px, ${e.y}px, 0) scale(${e.k})`;let r=24*e.k;n.style.backgroundSize=`${r}px ${r}px`,n.style.backgroundPosition=`${e.x}px ${e.y}px`,p.current?.classList.toggle(`is-far`,e.k<.5),h.current&&(h.current.textContent=`${e.k.toFixed(2)}×`,h.current.title=`x ${Math.round(e.x)} · y ${Math.round(e.y)} · ${e.k.toFixed(2)}×`)},[]);(0,C.useEffect)(()=>{fe()},[fe]);let pe=e=>Math.min(kE,Math.max(OE,e)),me=(0,C.useCallback)((e,t,n)=>{let r=y.current,i=pe(n),a=(e-r.x)/r.k,o=(t-r.y)/r.k;r.k=i,r.x=e-a*i,r.y=t-o*i,fe()},[fe]),he=(0,C.useCallback)(e=>{let t=f.current;t&&me(t.clientWidth/2,t.clientHeight/2,y.current.k*e)},[me]),ge=(0,C.useCallback)(()=>{for(let e of[_,v])e.current&&(e.current.style.display=`none`)},[]),_e=(0,C.useCallback)((e,t)=>{let n=y.current;_.current&&(e===null?_.current.style.display=`none`:(_.current.style.display=`block`,_.current.style.transform=`translateX(${e*n.k+n.x}px)`)),v.current&&(t===null?v.current.style.display=`none`:(v.current.style.display=`block`,v.current.style.transform=`translateY(${t*n.k+n.y}px)`))},[]),ve=(0,C.useRef)(null),ye=(0,C.useRef)(!1),be=(0,C.useRef)(null),xe=(0,C.useRef)(null),Se=(e,t)=>{if(e.button!==0||De.current||Ee.current||e.target.closest(`button, select`))return;e.stopPropagation();let n=e.shiftKey||e.metaKey||e.ctrlKey,r;if(n){let e=new Set(B.current);if(e.has(t)){e.delete(t),z([...e]);return}e.add(t),z([...e]),r=[...e]}else B.current.has(t)?r=[...B.current]:(z([t]),r=[t]);let i=new Map;for(let e of r){let t=o?.nodes.find(t=>t.id===e);t&&i.set(e,ue(t))}xe.current={pointerId:e.pointerId,ids:[...i.keys()],sx:e.clientX,sy:e.clientY,origins:i,moved:!1},e.currentTarget.setPointerCapture(e.pointerId)},Ce=(0,C.useCallback)((e,t)=>{let n=xe.current;if(n===null)return;let r=jE/y.current.k,i=1/0,a=1/0,s=-1/0,c=-1/0;for(let[e,t]of n.origins){let n=G.current.get(e)?.offsetHeight??W[e]??84;i=Math.min(i,t.x),a=Math.min(a,t.y),s=Math.max(s,t.x+ME),c=Math.max(c,t.y+n)}if(!Number.isFinite(i))return;let l=[],u=[];for(let e of o?.nodes??[]){if(n.origins.has(e.id))continue;let t=ue(e),r=G.current.get(e.id)?.offsetHeight??W[e.id]??84;l.push(t.x,t.x+ME/2,t.x+ME),u.push(t.y,t.y+r/2,t.y+r)}let d=KE([i+e,(i+s)/2+e,s+e],l,r),f=KE([a+t,(a+c)/2+t,c+t],u,r),p=e+(d?.delta??0),m=t+(f?.delta??0);for(let e of n.ids){let t=G.current.get(e);t&&(t.style.setProperty(`--card-dx`,`${p}px`),t.style.setProperty(`--card-dy`,`${m}px`))}_e(d?.at??null,f?.at??null)},[o?.nodes,W,ue,_e]),[we,Te]=(0,C.useState)(!1),Ee=(0,C.useRef)(!1);(0,C.useLayoutEffect)(()=>{Ee.current=we,f.current?.classList.toggle(`can-zoom`,we||De.current)},[we]);let De=(0,C.useRef)(!1),Oe=(0,C.useRef)(null),ke=e=>{let t=e.target;if(t.closest(`.canvas-bar`))return;if(e.button===0&&(De.current||Ee.current)){Oe.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,moved:!1},f.current?.classList.add(`is-zooming`),f.current?.setPointerCapture(e.pointerId);return}if(t.closest(`.canvas-node`))return;let n=e.shiftKey||e.altKey;e.button===1||e.button===0&&!n?(ve.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,ox:y.current.x,oy:y.current.y},f.current?.classList.add(`is-panning`),f.current?.setPointerCapture(e.pointerId)):e.button===0&&(be.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,additive:e.metaKey||e.ctrlKey,moved:!1},f.current?.setPointerCapture(e.pointerId))},Ae=e=>{let t=Oe.current;if(t!==null&&e.pointerId===t.id){let n=f.current,r=g.current;if(!n||!r)return;let i=n.getBoundingClientRect(),a=t.sx-i.left,o=t.sy-i.top,s=e.clientX-i.left,c=e.clientY-i.top;if(!t.moved&&Math.hypot(s-a,c-o)<4)return;t.moved=!0,r.classList.add(`is-zoom`),r.style.display=`block`,r.style.left=`${Math.min(a,s)}px`,r.style.top=`${Math.min(o,c)}px`,r.style.width=`${Math.abs(s-a)}px`,r.style.height=`${Math.abs(c-o)}px`;return}let n=ve.current;if(n!==null&&e.pointerId===n.id){y.current.x=n.ox+(e.clientX-n.sx),y.current.y=n.oy+(e.clientY-n.sy),fe();return}let r=xe.current;if(r!==null&&e.pointerId===r.pointerId){let t=e.clientX-r.sx,n=e.clientY-r.sy;if(!r.moved&&Math.hypot(t,n)<AE)return;if(!r.moved){r.moved=!0;for(let e of r.ids)G.current.get(e)?.classList.add(`is-dragging`)}Ce(t/y.current.k,n/y.current.k);return}let i=be.current;if(i!==null&&e.pointerId===i.id){let t=f.current,n=g.current;if(!t||!n)return;let r=t.getBoundingClientRect(),a=i.sx-r.left,o=i.sy-r.top,s=e.clientX-r.left,c=e.clientY-r.top;if(!i.moved&&Math.hypot(s-a,c-o)<AE)return;i.moved=!0,n.style.display=`block`,n.style.left=`${Math.min(a,s)}px`,n.style.top=`${Math.min(o,c)}px`,n.style.width=`${Math.abs(s-a)}px`,n.style.height=`${Math.abs(c-o)}px`}},je=(0,C.useCallback)(e=>{let t=f.current,n=g.current;if(!t||!n)return;let r=y.current,i=Number.parseFloat(n.style.left),a=Number.parseFloat(n.style.top),s=Number.parseFloat(n.style.width),c=Number.parseFloat(n.style.height),l=(i-r.x)/r.k,u=(a-r.y)/r.k,d=(i+s-r.x)/r.k,p=(a+c-r.y)/r.k,m=[];for(let e of o?.nodes??[]){let t=ue(e),n=G.current.get(e.id)?.offsetHeight??W[e.id]??84;t.x<d&&t.x+ME>l&&t.y<p&&t.y+n>u&&m.push(e.id)}z(t=>e?[...new Set([...t,...m])]:m)},[o?.nodes,W,ue]),Me=(0,C.useCallback)(()=>{let e=f.current,t=g.current;if(!e||!t)return;let n=y.current,r=Number.parseFloat(t.style.left)||0,i=Number.parseFloat(t.style.top)||0,a=Number.parseFloat(t.style.width)||0,o=Number.parseFloat(t.style.height)||0;if(a<8||o<8)return;let s=a/n.k,c=o/n.k,l=(r-n.x)/n.k,u=(i-n.y)/n.k,d=pe(Math.min(e.clientWidth/s,e.clientHeight/c));n.k=d,n.x=(e.clientWidth-s*d)/2-l*d,n.y=(e.clientHeight-c*d)/2-u*d,fe()},[fe]),q=e=>{let t=ve.current;t!==null&&e.pointerId===t.id&&(ve.current=null,f.current?.classList.remove(`is-panning`));let n=Oe.current;if(n!==null&&e.pointerId===n.id){Oe.current=null,f.current?.classList.remove(`is-zooming`),n.moved&&Me(),g.current&&(g.current.style.display=`none`,g.current.classList.remove(`is-zoom`)),Ee.current&&Te(!1);return}let r=be.current;r!==null&&e.pointerId===r.id&&(be.current=null,r.moved?je(r.additive):r.additive||z([]),g.current&&(g.current.style.display=`none`));let i=xe.current;if(i===null||e.pointerId!==i.pointerId)return;xe.current=null,ge();for(let e of i.ids)G.current.get(e)?.classList.remove(`is-dragging`);if(!i.moved){for(let e of i.ids){let t=G.current.get(e);t?.style.removeProperty(`--card-dx`),t?.style.removeProperty(`--card-dy`)}return}let a=new Map;for(let e of i.ids){let t=G.current.get(e);t&&(a.set(e,{x:Number.parseFloat(t.style.getPropertyValue(`--card-dx`))||0,y:Number.parseFloat(t.style.getPropertyValue(`--card-dy`))||0}),t.style.removeProperty(`--card-dx`),t.style.removeProperty(`--card-dy`))}let o={},c=[];for(let[e,t]of a){let n=i.origins.get(e);if(!n)continue;let r={x:n.x+t.x,y:n.y+t.y};o[e]=r,c.push({id:e,...r})}K===`card`?(x(e=>({...e,...o})),s!==null&&cu(s,c,u??void 0)):ce(e=>{let t=s??``,n={...e[t]?.[K],...o},r={...e,[t]:{...e[t],[K]:n}};return VE(r),r})};(0,C.useEffect)(()=>{let e=p.current;if(!e)return;let t=t=>{if(t.preventDefault(),t.ctrlKey||t.metaKey){let n=e.getBoundingClientRect(),r=Math.exp(-t.deltaY*.0025);me(t.clientX-n.left,t.clientY-n.top,y.current.k*r)}else f.current!==null&&(y.current.x-=t.deltaX,y.current.y-=t.deltaY,fe())};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[fe,me]),(0,C.useEffect)(()=>{let e=e=>{if(!ye.current)return;let t=e.target;if(t!==null&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))return;let n=f.current;if(!n)return;let r=e.key===`+`||e.key===`=`?1.15:e.key===`-`||e.key===`_`?1/1.15:null;r===null?e.key===`0`&&(e.preventDefault(),me(n.clientWidth/2,n.clientHeight/2,1)):(e.preventDefault(),he(r))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[he,me]),(0,C.useEffect)(()=>{let e=e=>{let t=e;return t!==null&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))},t=e=>{De.current=e,f.current?.classList.toggle(`can-zoom`,e||Ee.current)},n=n=>{if(!e(n.target)){if((n.key===`z`||n.key===`Z`)&&!n.metaKey&&!n.ctrlKey&&!n.altKey){if(!ye.current)return;t(!0)}else n.key===`Escape`&&(Te(!1),t(!1))}},r=e=>{(e.key===`z`||e.key===`Z`)&&t(!1)},i=()=>t(!1);return window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r),window.addEventListener(`blur`,i),()=>{window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),window.removeEventListener(`blur`,i)}},[]);let Ne=(0,C.useCallback)(()=>{let e=f.current;if(!e||e.clientWidth===0||e.clientHeight===0)return;let t=d.nodes;if(t.length===0)return;let n=1/0,r=1/0,i=-1/0,a=-1/0;for(let e of t){let t=ue(e),o=G.current.get(e.id)?.offsetHeight??W[e.id]??84;n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+ME),a=Math.max(a,t.y+o)}let o=Math.min(1,pe(Math.min((e.clientWidth-80)/Math.max(1,i-n),(e.clientHeight-80)/Math.max(1,a-r))));y.current.k=o;let s=(e.clientWidth-(i-n)*o)/2-n*o,c=(e.clientHeight-(a-r)*o)/2-r*o;y.current.x=Math.max(s,40-n*o),y.current.y=Math.max(c,40-r*o),fe()},[o?.nodes,W,fe,ue]),Y=(0,C.useCallback)(()=>{y.current={x:0,y:0,k:1},fe()},[fe]),Pe=(0,C.useCallback)(()=>{let e=Fe.current;if(P(null),e===null||s===null)return;let t=o?.nodes.find(t=>t.id===e.id);if(t===void 0)return;let n=e.title.trim(),r=e.detail.trim(),i={};n!==``&&n!==t.title&&(i.title=n),r!==(t.detail??``)&&(i.detail=r),(i.title!==void 0||i.detail!==void 0)&&au(s,e.id,i,u??void 0)},[s,o]),Fe=(0,C.useRef)(null);(0,C.useLayoutEffect)(()=>{Fe.current=N},[N]);let Ie=(0,C.useCallback)(async()=>{if(j!==null&&s!==null){A(!0);try{let e=await iu(s,j.nodeIds,u??void 0);O(e)}finally{A(!1)}}},[j,s,u]);(0,C.useEffect)(()=>{j===null?O([]):Ie()},[j?.nodeIds.join(`,`),j!==null]);let Le=(0,C.useCallback)(()=>{if(j===null||s===null)return;let e=j.nodeIds.map(e=>o?.nodes.find(t=>t.id===e)).filter(e=>e!==void 0),t=j.text.trim();if(e.length===0||t===``)return;let n=[`【画布选区】针对这 ${e.length} 个节点:`,...e.map(e=>`- ${e.id}(${e.status}${e.kind?`,${e.kind}`:``}):${e.title}${e.detail?` —— ${e.detail}`:``}`),``,`我的要求:${t}`,``,`只改这几个节点(用 canvas 工具的 update / status / add 定位到上面的 id),别动其他节点;改完一句话说改了什么。`];an(),Al(n.join(`
77
- `)),M(null)},[j,s,o]),Re=(0,C.useCallback)((e,t)=>{s!==null&&t!==e.status&&ou(s,e.id,t,u??void 0)},[s,u]),ze=(0,C.useCallback)(e=>{s!==null&&(su(s,[e.id],u??void 0),z(t=>t.filter(t=>t!==e.id)),Ge(t=>t?.id===e.id?null:t))},[s]),Be=(0,C.useCallback)(n=>{let r=n.artifacts??[];return r.length===0?null:(0,Q.jsxs)(`div`,{className:`canvas-preview-artifacts`,children:[(0,Q.jsx)(`div`,{className:`canvas-preview-artifacts-head`,children:t(`这一步的产出`,`Artifacts`)}),r.map((t,n)=>{let r=t.kind===`file`&&t.detail!==`工作区外`;return(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-artifact is-${t.kind}${r?` can-open`:``}`,title:t.detail??t.label,onClick:()=>{r&&(e(t.label),E(null))},children:[(0,Q.jsx)(`span`,{className:`canvas-artifact-icon`,children:t.kind===`file`?`▤`:t.kind===`command`?`>_`:`✎`}),(0,Q.jsx)(`span`,{className:`canvas-artifact-label`,children:t.label}),t.detail?(0,Q.jsx)(`span`,{className:`canvas-artifact-detail`,children:t.detail}):null]},`${t.kind}-${n}-${t.label}`)})]})},[t,e]),Ve=(0,C.useCallback)(e=>{s!==null&&ru(s,e.id,u??void 0)},[s]),He=d.nodes,Ue=(0,C.useMemo)(()=>new Set(R),[R]),[We,Ge]=(0,C.useState)(null),Ke=We===null?null:He.find(e=>e.id===We.id)??null,qe=(0,C.useRef)(null),Je=(0,C.useCallback)(()=>{qe.current!==null&&(window.clearTimeout(qe.current),qe.current=null)},[]),Ye=(0,C.useCallback)(()=>{Je(),Ge(null)},[Je]),Xe=(0,C.useCallback)(()=>{Je(),qe.current=window.setTimeout(()=>{qe.current=null,Ge(null)},160)},[Je]),Ze=(0,C.useCallback)(e=>{let t=f.current;if(!t)return;let n=ue(e),r=G.current.get(e.id)?.offsetHeight??W[e.id]??84,i=pe(Math.min((t.clientWidth-120)/ME,(t.clientHeight-120)/Math.max(1,r)));y.current.k=i,y.current.x=t.clientWidth/2-(n.x+ME/2)*i,y.current.y=t.clientHeight/2-(n.y+r/2)*i,fe(),Ge(null)},[W,fe,ue]),Qe=(0,C.useMemo)(()=>{if(We===null)return null;let e=f.current?.clientWidth??600,t=f.current?.clientHeight??600;return{left:We.x+We.w+12+300>e?Math.max(8,We.x-300-12):We.x+We.w+12,top:Math.max(8,Math.min(We.y,t-170)),width:300}},[We]),$e=(0,C.useMemo)(()=>{if(o===null||d.edges.length===0)return[];let e=new Map(d.nodes.map(e=>[e.id,ue(e)])),t=new Map(d.nodes.map(e=>[e.id,W[e.id]??84]));return d.edges.map(n=>{let r=e.get(n.from),i=e.get(n.to);if(!r||!i)return null;let a=r.x+ME,o=r.y+(t.get(n.from)??84)/2,s=i.x,c=i.y+(t.get(n.to)??84)/2,l=s<a,u=l?r.x:a,d=l?i.x+ME:s,f=Math.max(48,Math.abs(d-u)*.45)*(l?-1:1),p=`M ${u} ${o} C ${u+f} ${o}, ${d-f} ${c}, ${d} ${c}`;return{key:`${n.from}->${n.to}`,d:p,label:n.label,mid:{x:(u+d)/2,y:(o+c)/2}}}).filter(e=>e!==null)},[o,d,W,ue]);return o===null||He.length===0?(0,Q.jsx)(`div`,{className:`canvas-view canvas-empty`,ref:p,onPointerEnter:()=>{ye.current=!0},onPointerLeave:()=>{ye.current=!1},children:(0,Q.jsxs)(`div`,{className:`canvas-empty-card`,children:[(0,Q.jsx)(`div`,{className:`canvas-empty-title`,children:t(`画布还空着`,`The canvas is empty`)}),(0,Q.jsx)(`div`,{className:`canvas-empty-body`,children:t(`在左边对话里说一句你要做什么,比如「我要做一个签到活动,帮我把要做的事画出来」,agent 会把它拆成一张图放到这里。`,`Tell the agent what you want to build (e.g. “I'm shipping a check-in campaign — map out what needs to happen”), and it will lay the work out here.`)})]})}):(0,Q.jsxs)(`div`,{className:`canvas-view`,ref:p,children:[(0,Q.jsxs)(`div`,{className:`canvas-viewport`,ref:f,onPointerDown:ke,onContextMenu:e=>{e.preventDefault(),w(F(e))},onPointerMove:Ae,onPointerUp:q,onPointerCancel:q,onPointerEnter:()=>{ye.current=!0},onPointerLeave:()=>{ye.current=!1,f.current?.classList.remove(`can-pan`)},children:[(0,Q.jsxs)(`div`,{className:`canvas-world`,ref:m,children:[oe.map(e=>(0,Q.jsx)(`div`,{className:`canvas-lane`,style:{left:e.x,top:e.y,width:e.w,height:e.h},children:(0,Q.jsx)(`span`,{className:`canvas-lane-label`,children:e.label})},`${e.label}-${e.y}`)),$e.length>0?(0,Q.jsx)(`svg`,{className:`canvas-edges`,children:$e.map(e=>(0,Q.jsx)(`path`,{d:e.d},e.key))}):null,He.map((e,n)=>{let r=ue(e),i=WE(e),a=Ue.has(e.id),o=V===e.id&&H!==void 0&&H.status!==`idle`,s=o?GE(H,t):null;return(0,Q.jsxs)(`div`,{className:`canvas-node is-${i.tone} kind-${FE(e)}${a?` is-selected`:``}${o?` is-live`:``}`,ref:t=>{t?G.current.set(e.id,t):G.current.delete(e.id)},style:{left:r.x,top:r.y},onPointerDown:t=>Se(t,e.id),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),w(F(t,e.id))},onPointerEnter:()=>{if(y.current.k>=.7){Ge(null);return}let t=y.current,n=G.current.get(e.id)?.offsetHeight??84;Ge({id:e.id,x:r.x*t.k+t.x,y:r.y*t.k+t.y,w:ME*t.k,h:n*t.k})},onPointerLeave:Xe,onDoubleClick:()=>{e.sub===void 0?Ve(e):l([e.id])},title:t(`双击让 agent 开始做这一步`,`Double-click to have the agent start this step`),children:[(0,Q.jsx)(`span`,{className:`canvas-node-index`,children:n+1}),N!==null&&N.id===e.id?(0,Q.jsxs)(`div`,{className:`canvas-node-edit`,children:[(0,Q.jsx)(`input`,{className:`canvas-node-edit-title`,value:N.title,autoFocus:!0,onChange:e=>P({...N,title:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Pe()),e.key===`Escape`&&P(null)}}),(0,Q.jsx)(`textarea`,{className:`canvas-node-edit-detail`,value:N.detail,rows:2,placeholder:t(`说明(可留空)`,`Detail (optional)`),onChange:e=>P({...N,detail:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),Pe()),e.key===`Escape`&&P(null)}}),(0,Q.jsxs)(`div`,{className:`canvas-node-edit-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:Pe,children:t(`保存`,`Save`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>P(null),children:t(`取消`,`Cancel`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`canvas-node-head`,children:[(0,Q.jsx)(`span`,{className:`canvas-dot is-${i.tone}`}),(0,Q.jsx)(`span`,{className:`canvas-node-kind kind-${FE(e)}`,title:t(PE[FE(e)].zh,PE[FE(e)].en),children:PE[FE(e)].icon}),(0,Q.jsx)(`span`,{className:`canvas-node-title`,children:e.title})]}),e.detail?(0,Q.jsx)(`div`,{className:`canvas-node-detail`,children:e.detail}):null]}),o&&s!==null?(0,Q.jsxs)(`div`,{className:`canvas-node-live`,children:[(0,Q.jsx)(`span`,{className:`canvas-live-dot`}),(0,Q.jsx)(`span`,{className:`canvas-live-text`,children:s})]}):null,(0,Q.jsxs)(`div`,{className:`canvas-node-state is-${i.tone}`,children:[t(i.zh,i.en),e.sub!==void 0&&e.sub.nodes.length>0?(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-node-sub`,title:t(`看这一步的子计划`,`Open its sub-plan`),onPointerDown:e=>e.stopPropagation(),onClick:()=>l([e.id]),children:[`· `,e.sub.nodes.filter(e=>e.status===`done`).length,`/`,e.sub.nodes.length,` `,t(`子步`,`sub`)]}):null,e.artifacts!==void 0&&e.artifacts.length>0?(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-node-artifacts`,title:t(`看这一步的产出`,`See artifacts`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let t=y.current;E({id:e.id,x:r.x*t.k+t.x,y:(r.y+40)*t.k+t.y})},children:[`· `,e.artifacts.length,` `,t(`项产出`,`artifacts`)]}):null]}),(0,Q.jsxs)(`div`,{className:`canvas-node-actions`,children:[(0,Q.jsxs)(`select`,{className:`canvas-node-status`,value:e.status,"aria-label":t(`改状态`,`Change status`),onPointerDown:e=>e.stopPropagation(),onChange:t=>Re(e,t.target.value),children:[(0,Q.jsx)(`option`,{value:`todo`,children:t(`待办`,`To do`)}),(0,Q.jsx)(`option`,{value:`doing`,children:t(`正在做`,`Doing`)}),(0,Q.jsx)(`option`,{value:`done`,children:t(`已完成`,`Done`)}),(0,Q.jsx)(`option`,{value:`blocked`,children:t(`卡住了`,`Blocked`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-node-delete`,title:t(`删掉这一步`,`Delete this step`),"aria-label":t(`删掉这一步`,`Delete this step`),onClick:()=>ze(e),children:`×`})]})]},e.id)})]}),(0,Q.jsx)(`div`,{className:`canvas-marquee`,ref:g}),(0,Q.jsx)(`div`,{className:`canvas-guide canvas-guide-x`,ref:_}),(0,Q.jsx)(`div`,{className:`canvas-guide canvas-guide-y`,ref:v})]}),We!==null&&Ke!==null&&Qe!==null?(0,Q.jsxs)(`div`,{className:`canvas-preview is-${WE(Ke).tone}`,style:{left:Qe.left,top:Qe.top,width:Qe.width},onPointerEnter:Je,onPointerLeave:Ye,children:[(0,Q.jsxs)(`div`,{className:`canvas-preview-head`,children:[(0,Q.jsx)(`span`,{className:`canvas-dot is-${WE(Ke).tone}`}),(0,Q.jsx)(`span`,{className:`canvas-preview-title`,children:Ke.title})]}),Ke.detail?(0,Q.jsx)(`div`,{className:`canvas-preview-detail`,children:Ke.detail}):null,Be(Ke),(0,Q.jsxs)(`div`,{className:`canvas-preview-foot`,children:[(0,Q.jsx)(`span`,{className:`canvas-node-state is-${WE(Ke).tone}`,children:t(WE(Ke).zh,WE(Ke).en)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-preview-zoom`,onClick:()=>Ze(Ke),children:t(`放大看`,`Zoom in`)})]})]}):null,T===null?null:(()=>{let e=He.find(e=>e.id===T.id);return e===void 0?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:()=>E(null)}),(0,Q.jsxs)(`div`,{className:`canvas-ask`,style:{left:Math.min(T.x,(f.current?.clientWidth??600)-300),top:Math.min(T.y,(f.current?.clientHeight??600)-160)},children:[(0,Q.jsx)(`div`,{className:`canvas-ask-head`,children:e.title}),Be(e)]})]})})(),j===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:()=>M(null)}),(0,Q.jsxs)(`div`,{className:`canvas-ask`,style:{left:Math.min(j.x,(f.current?.clientWidth??600)-300),top:Math.min(j.y,(f.current?.clientHeight??600)-150)},children:[(0,Q.jsxs)(`div`,{className:`canvas-ask-head`,children:[(0,Q.jsx)(`span`,{children:t(`对这 ${j.nodeIds.length} 步说:`,`About these ${j.nodeIds.length}:`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-ask-refresh`,disabled:k,onClick:()=>void Ie(),children:k?t(`正在想…`,`Thinking…`):t(`换一批`,`Shuffle`)})]}),D.length>0?(0,Q.jsx)(`div`,{className:`canvas-ask-chips`,children:D.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`canvas-ask-chip`,onClick:()=>M(t=>t===null?t:{...t,text:e}),children:e},e))}):null,(0,Q.jsx)(`textarea`,{className:`canvas-ask-input`,value:j.text,autoFocus:!0,rows:3,placeholder:t(`比如:这几步太粗,拆细一点 / 合并成一步 / 顺序不对`,`e.g. too coarse — split them / merge / wrong order`),onChange:e=>M({...j,text:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Le()),e.key===`Escape`&&M(null)}}),(0,Q.jsxs)(`div`,{className:`canvas-ask-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`is-primary`,onClick:Le,children:t(`发给 agent`,`Send`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>M(null),children:t(`取消`,`Cancel`)})]})]})]}),S===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:L,onContextMenu:e=>{e.preventDefault(),L()}}),(0,Q.jsx)(`span`,{className:`canvas-rt-marker`,style:{left:S.x,top:S.y},"aria-hidden":`true`},`${S.x}-${S.y}`),(0,Q.jsxs)(`div`,{className:`canvas-menu`,style:{left:Math.min(S.x+8,(f.current?.clientWidth??600)-200),top:Math.min(S.y+8,(f.current?.clientHeight??600)-40-I*26)},children:[S.nodeId===null?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Ne()},children:t(`看全局`,`Fit all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Y()},children:t(`回到 100%`,`Back to 100%`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${we?` is-on`:``}`,onClick:()=>{L(),Te(e=>!e)},children:[we?`✓ `:``,t(`框选放大`,`Zoom to area`)]}),R.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-accent`,onClick:()=>{M({x:S.x,y:S.y,nodeIds:[...R],text:``}),L()},children:t(`就这 ${R.length} 步说两句…`,`Ask about these ${R.length}…`)})]}):null,(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`div`,{className:`canvas-menu-label`,children:t(`布局`,`Layout`)}),[[`card`,t(`卡片`,`Cards`)],[`timeline`,t(`时间线`,`Timeline`)],[`checklist`,t(`清单`,`Checklist`)],[`mindmap`,t(`导图`,`Mind map`)],[`swimlane`,t(`泳道`,`Swimlanes`)]].map(([e,t])=>(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${K===e?` is-on`:``}`,onClick:()=>{L(),re(e)},children:[K===e?`✓ `:``,t]},e))]}):null,S.nodeId===null?null:(()=>{let e=He.find(e=>e.id===S.nodeId);if(e===void 0)return null;let n=(()=>{let n=d.edges.filter(t=>t.to===e.id).map(e=>e.from);if(n.length===0)return null;let r=n.filter(e=>(He.find(t=>t.id===e)?.status??`todo`)!==`done`);return r.length===0?null:t(`前置还有 ${r.length} 步没完成`,`${r.length} earlier step(s) not done yet`)})();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-accent`,onClick:()=>{let t=R.includes(e.id)&&R.length>0?R:[e.id];M({x:S.x,y:S.y,nodeIds:t,text:``}),L()},children:R.includes(e.id)&&R.length>1?t(`就这 ${R.length} 步说两句…`,`Ask about these ${R.length}…`):t(`就这一步说两句…`,`Ask about this step…`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Ve(e)},children:e.status===`done`?t(`重新做一遍`,`Run it again`):e.status===`doing`?t(`重新开始这一步`,`Restart this step`):e.status===`blocked`?t(`重试这一步`,`Retry this step`):t(`开始做这一步`,`Start this step`)}),e.status===`doing`?(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),s!==null&&jl(s)},children:t(`停下来`,`Stop it`)}):null,n===null?null:(0,Q.jsx)(`div`,{className:`canvas-menu-hint`,children:n}),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`div`,{className:`canvas-menu-label`,children:t(`状态`,`Status`)}),[[`todo`,t(`待办`,`To do`)],[`doing`,t(`正在做`,`Doing`)],[`done`,t(`已完成`,`Done`)],[`blocked`,t(`卡住了`,`Blocked`)]].map(([t,n])=>(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${e.status===t?` is-on`:``}`,onClick:()=>{L(),Re(e,t)},children:[e.status===t?`✓ `:``,n]},t)),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),P({id:e.id,title:e.title,detail:e.detail??``})},children:t(`重命名 / 改说明`,`Rename`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Ze(e)},children:t(`放大看这一步`,`Zoom in`)}),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-danger`,onClick:()=>{L(),ze(e)},children:t(`删除这一步`,`Delete`)})]})})()]})]}),(0,Q.jsxs)(`div`,{className:`canvas-bar`,children:[u===null?null:(0,Q.jsxs)(`span`,{className:`canvas-crumbs`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>l([]),title:t(`回到全部`,`Back to all`),children:[`‹ `,t(`全部`,`All`)]}),(0,Q.jsx)(`span`,{className:`canvas-crumbs-sep`,children:`›`}),(0,Q.jsx)(`span`,{className:`canvas-crumbs-current`,children:d.host?.title??u})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn`,onClick:Ne,title:t(`看全局(缩到能看见全部)`,`Fit all`),"aria-label":t(`看全局`,`Fit all`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2 6V2h4M14 6V2h-4M2 10v4h4M14 10v4h-4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn canvas-icon-text`,onClick:Y,title:t(`回到 100%(重置视角)`,`Back to 100%`),"aria-label":t(`重置视角`,`Reset view`),children:`1:1`}),(0,Q.jsxs)(`select`,{className:`canvas-style`,value:K,"aria-label":t(`画布布局`,`Canvas layout`),title:t(`画布布局`,`Canvas layout`),onChange:e=>re(e.target.value),children:[(0,Q.jsx)(`option`,{value:`card`,children:t(`卡片`,`Cards`)}),(0,Q.jsx)(`option`,{value:`timeline`,children:t(`时间线`,`Timeline`)}),(0,Q.jsx)(`option`,{value:`checklist`,children:t(`清单`,`Checklist`)}),(0,Q.jsx)(`option`,{value:`mindmap`,children:t(`导图`,`Mind map`)}),(0,Q.jsx)(`option`,{value:`swimlane`,children:t(`泳道`,`Swimlanes`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn${we?` is-on`:``}`,"aria-pressed":we,onClick:()=>Te(e=>!e),title:t(`框选放大(也可以按住 Z 拖)`,`Zoom to area`),"aria-label":t(`框选放大`,`Zoom to area`),children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`1.5`,y:`1.5`,width:`8`,height:`8`,rx:`1`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeDasharray:`2 1.6`}),(0,Q.jsx)(`circle`,{cx:`10.6`,cy:`10.6`,r:`3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,Q.jsx)(`path`,{d:`M12.9 12.9 15 15`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})]})}),(0,Q.jsxs)(`span`,{className:`canvas-zoom`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>he(1/1.15),title:t(`缩小`,`Zoom out`),"aria-label":t(`缩小`,`Zoom out`),children:`−`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>he(1.15),title:t(`放大`,`Zoom in`),"aria-label":t(`放大`,`Zoom in`),children:`+`})]}),(0,Q.jsx)(`span`,{ref:h,className:`canvas-readout`,title:t(`当前缩放`,`Current zoom`)}),(0,Q.jsx)(`span`,{className:`canvas-count`,title:t(`${He.length} 个节点`,`${He.length} steps`),children:He.length}),R.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`canvas-bar-sel`,title:t(`已选 ${R.length} 个`,`${R.length} selected`),children:R.length}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn`,onClick:()=>z([]),title:t(`取消选择`,`Clear selection`),"aria-label":t(`取消选择`,`Clear selection`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`12`,height:`12`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M4 4l8 8M12 4l-8 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})})})]}):null]}),o.goal?(0,Q.jsx)(`div`,{className:`canvas-goal`,children:o.goal}):null,(0,Q.jsx)(`div`,{className:`canvas-hint`,children:t(`拖空白平移 · Shift+拖框选 · Z+拖框选放大 · +/- 缩放 · 双击节点开工`,`Drag to pan · Shift+drag to box-select · Z+drag to zoom · +/- to zoom · double-click to start`)})]})}var JE=`pop-agent.preview.width.v2`,YE=360,XE=1200,ZE=`pop-agent.preview.files-rail-w`,QE=140,$E=520,eD=224,tD=260;function nD(){let e=Number(localStorage.getItem(ZE));return!Number.isFinite(e)||e<=0?eD:Math.min(Math.max(e,QE),$E)}function rD(){let e=Number(localStorage.getItem(JE));return Number.isFinite(e)&&e>=YE?Math.min(e,XE):null}function iD(e,t){return e.kind===`terminal`?{icon:`>_`,label:e.label??(e.cwd&&D(e.cwd)||t(`终端`,`Terminal`)),title:e.cwd??t(`终端`,`Terminal`)}:e.kind===`files`?{icon:`🗂`,label:t(`文件`,`Files`),title:t(`文件树`,`File tree`)}:e.kind===`side`?{icon:`💬`,label:e.label??t(`临时聊天`,`Side chat`),title:t(`临时聊天(不落盘)`,`Side chat (not saved)`)}:e.kind===`web`?{icon:`🌐`,label:e.url?GT(e.url):t(`新网页`,`New page`),title:e.url||t(`网页`,`Web page`)}:e.kind===`history`?{icon:`📜`,label:t(`完整历史`,`Full history`),title:t(`完整历史(pi 的会话导出页)`,`Full history (pi session export)`)}:e.kind===`prompt`?{icon:`🧾`,label:t(`系统提示词`,`System prompt`),title:t(`这次运行实际在用的系统提示词`,`The system prompt this run actually uses`)}:e.kind===`canvas`?{icon:`◎`,label:t(`画布`,`Canvas`),title:t(`画布:把会话摊在一块平面上`,`Canvas: sessions laid out on a plane`)}:{icon:/\.[jt]sx?$/i.test(e.path)?`TS`:/\.json$/i.test(e.path)?`{}`:/\.md$/i.test(e.path)?`M↓`:/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(e.path)?`IMG`:`▤`,label:D(e.path)||e.path,title:e.path}}var aD=[{tool:`side`,icon:`💬`,zh:`临时聊天`,en:`Side chat`,hintZh:`另开一条对话问一句就走,不落盘、不影响主会话`,hintEn:`A separate throwaway chat: nothing saved, main session untouched`},{tool:`terminal`,icon:`>_`,zh:`终端`,en:`Terminal`,hintZh:`在对话框下面开一个 shell(底部终端)`,hintEn:`Open a shell under the chat (bottom panel)`},{tool:`files`,icon:`🗂`,zh:`文件`,en:`Files`,hintZh:`在当前工作区里翻文件,点开就在右边多一个标签`,hintEn:`Browse the workspace; opened files land in a new tab`},{tool:`web`,icon:`🌐`,zh:`网页`,en:`Web`,hintZh:`输入网址直接在这儿看(有些站点拒绝被嵌入)`,hintEn:`Open a URL right here (some sites refuse embedding)`},{tool:`canvas`,icon:`◎`,zh:`画布`,en:`Canvas`,hintZh:`把会话摊在一块可平移缩放的平面上,一眼看全谁在跑`,hintEn:`Lay your sessions out on a pannable, zoomable plane`}];function oD({items:e,activeId:t,landing:n,onActivate:r,onCloseTabs:i,onReorder:a,onShowLanding:o,onPickTool:s,onToggleSplit:c,onWideChange:l,root:u,files:d,onOpenFile:f,onOpenFilePath:p,revealSeq:m=0,onRevealFile:h,chatOnRight:g=!1,showSplitButton:_=!0,onWebNote:v,conversationId:y=null}){let b=J(),[x,S]=(0,C.useState)(()=>rD()??620),w=(0,C.useRef)(null),T=(0,C.useRef)(rD()===null);(0,C.useLayoutEffect)(()=>{if(!T.current)return;T.current=!1;let e=w.current?.parentElement?.clientWidth??0;if(e<=0)return;let t=Math.round((e-6)/2);S(Math.min(Math.max(t,YE),XE))},[]);let[E,D]=(0,C.useState)(!1),O=e=>{D(e),l?.(e)},k=(0,C.useRef)(!1),A=(0,C.useCallback)(e=>{e.preventDefault(),k.current=!0;let t=e.clientX,n=x,r=e.currentTarget,i=e.pointerId;try{r.setPointerCapture(i)}catch{}document.documentElement.classList.add(`is-resizing`);let a=e=>{if(!k.current)return;let r=e.clientX-t,i=Math.min(Math.max(n+(g?r:-r),YE),XE);S(Math.round(i))},o=()=>{k.current=!1,document.documentElement.classList.remove(`is-resizing`),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),document.removeEventListener(`pointercancel`,o);try{r.hasPointerCapture(i)&&r.releasePointerCapture(i)}catch{}};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o),document.addEventListener(`pointercancel`,o)},[x,g]);(0,C.useEffect)(()=>{localStorage.setItem(JE,String(x))},[x]);let j=e.find(e=>e.id===t)??e[0],M=n||e.length===0,[N,P]=uf(`pop-agent.preview.files-rail.v3`,!1),[F,I]=(0,C.useState)(nD);(0,C.useEffect)(()=>{localStorage.setItem(ZE,String(F))},[F]);let L=(0,C.useCallback)(e=>{e.preventDefault();let t=e.clientX,n=F,r=Math.max(QE,Math.min($E,x-tD)),i=e=>{let i=Math.min(Math.max(n+(t-e.clientX),QE),r);I(Math.round(i))},a=()=>{document.removeEventListener(`pointermove`,i),document.removeEventListener(`pointerup`,a)};document.addEventListener(`pointermove`,i),document.addEventListener(`pointerup`,a)},[F,x]),R=!M&&j?.kind===`file`?j:null,z=!M&&j?.kind===`terminal`,B=(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn${N?` btn-wide-on`:``}`,onClick:()=>{let e=!N;P(e),e&&R&&h?.(R.path,R.root||u||``)},"aria-pressed":N,title:N?b(`隐藏右边那排文件列表`,`Hide the file list on the right`):b(`显示文件列表(常驻在内容右边,点文件另开标签)`,`Show the file list (opens files as new tabs)`),children:(0,Q.jsx)(`svg`,{className:`preview-tool-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2 4.4c0-.66.54-1.2 1.2-1.2h2.7l1.4 1.6h5.5c.66 0 1.2.54 1.2 1.2v6.4c0 .66-.54 1.2-1.2 1.2H3.2c-.66 0-1.2-.54-1.2-1.2z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinejoin:`round`})})}),V=(0,C.useRef)(null),H=(0,C.useRef)(null),[U,W]=(0,C.useState)(null);(0,C.useEffect)(()=>{let e=V.current;if(!e)return;let t=t=>{e.scrollWidth<=e.clientWidth+1||Math.abs(t.deltaX)>=Math.abs(t.deltaY)||(e.scrollLeft+=t.deltaY,t.preventDefault())};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,C.useEffect)(()=>{let e=V.current;if(!e||!j)return;let t=e.querySelector(`[data-tab-id="${CSS.escape(j.id)}"]`);if(!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.left<n.left?e.scrollLeft-=n.left-r.left+6:r.right>n.right&&(e.scrollLeft+=r.right-n.right+6)},[j?.id,e.length]);let ee=e=>{let t=H.current;if(H.current=null,W(null),e===void 0)return;let n=V.current;for(let t of n?.querySelectorAll(`[data-tab-id]`)??[])t.hasPointerCapture?.(e)&&t.releasePointerCapture(e);return t},G=t=>{let n=V.current;if(!n)return e.length-1;let r=Array.from(n.querySelectorAll(`[data-tab-id]`));for(let e=0;e<r.length;e+=1){let n=r[e].getBoundingClientRect();if(t<n.left+n.width/2)return e}return r.length-1},K=(e,t)=>{e.button===0&&(e.target.closest(`.preview-tab-x`)||e.pointerType!==`touch`&&(H.current={id:t,startX:e.clientX,moved:!1},e.currentTarget.setPointerCapture?.(e.pointerId)))},te=t=>{let n=H.current;if(!n)return;if(!n.moved){if(Math.abs(t.clientX-n.startX)<5)return;n.moved=!0,W(n.id)}let r=e.map(e=>e.id),i=r.indexOf(n.id),o=G(t.clientX);if(i<0)return;let s=o>i?o-1:o;if(s===i)return;let c=[...r];c.splice(i,1),c.splice(s,0,n.id),a(c)},ne=(e,t)=>{let n=H.current?.moved===!0;ee(e.pointerId),n||r(t)},[re,ie]=(0,C.useState)(null);(0,C.useEffect)(()=>{if(!re)return;let e=e=>{e.target?.closest?.(`.preview-tab-menu`)||ie(null)},t=e=>{e.key===`Escape`&&ie(null)};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t),window.addEventListener(`blur`,e),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t),window.removeEventListener(`blur`,e)}},[re]);let ae=re?e.findIndex(e=>e.id===re.id):-1,oe=ae<0?[]:[{key:`one`,zh:`关闭`,en:`Close`,ids:[e[ae].id],disabled:!1},{key:`left`,zh:`关闭左侧标签`,en:`Close tabs to the left`,ids:e.slice(0,ae).map(e=>e.id),disabled:ae===0},{key:`right`,zh:`关闭右侧标签`,en:`Close tabs to the right`,ids:e.slice(ae+1).map(e=>e.id),disabled:ae===e.length-1},{key:`all`,zh:`关闭全部标签`,en:`Close all tabs`,ids:e.map(e=>e.id),disabled:!1}];return(0,Q.jsxs)(`aside`,{ref:w,className:`preview-panel${E?` preview-panel-wide`:``}${z?` preview-panel-term`:``}`,style:E?void 0:{width:x},children:[(0,Q.jsx)(`div`,{className:`preview-resizer`,onPointerDown:A,title:b(`拖动调整宽度`,`Drag to resize`)}),(0,Q.jsxs)(`div`,{className:`preview-tabs`,children:[(0,Q.jsx)(`div`,{className:`preview-tabs-strip`,ref:V,children:e.map(e=>{let{icon:t,label:n,title:a}=iD(e,b);return(0,Q.jsxs)(`span`,{className:`preview-tab${e.id===j?.id&&!M?` preview-tab-on`:``}${U===e.id?` preview-tab-dragging`:``}`,"data-tab-id":e.id,onPointerDown:t=>K(t,e.id),onPointerMove:te,onPointerUp:t=>ne(t,e.id),onPointerCancel:e=>ee(e.pointerId),onContextMenu:t=>{t.preventDefault(),ie({x:t.clientX,y:t.clientY,id:e.id})},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`preview-tab-name`,title:a,onClick:t=>{t.detail===0&&r(e.id)},children:[(0,Q.jsx)(`span`,{className:`preview-tab-icon`,children:t}),n]}),(0,Q.jsx)(`button`,{type:`button`,className:`preview-tab-x`,onClick:()=>i([e.id]),title:b(`关闭`,`Close`),children:`×`})]},e.id)})}),(0,Q.jsx)(`button`,{type:`button`,className:`preview-tab-add`,onClick:o,title:b(`新标签(文件 / 终端 / 临时聊天 / 网页)`,`New tab (files / terminal / side chat / web)`),children:(0,Q.jsx)(`svg`,{className:`preview-tab-add-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M8 2.4v11.2M2.4 8h11.2`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn${E?` btn-wide-on`:``}`,onClick:()=>O(!E),title:E?b(`收回右侧(恢复对话区)`,`Collapse the right panel (brings the chat back)`):b(`铺开:占满对话 + 预览两块区域(左侧栏保留)`,`Spread out: fill the chat + preview area (left sidebar stays)`),"aria-pressed":E,children:(0,Q.jsxs)(`svg`,{className:`preview-wide-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2.2 4v8`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`M6.2 8h7.2`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`m10.6 5.5 2.8 2.5-2.8 2.5`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`m7.8 5.5-2.8 2.5 2.8 2.5`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),c&&_?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn`,onClick:c,title:g?b(`收起左侧工作区(分栏)`,`Collapse the left work area (split)`):b(`收起右侧工作区(分栏)`,`Collapse the right work area (split)`),children:(0,Q.jsxs)(`svg`,{className:`preview-tool-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:g?`6`:`10`,y1:`4`,x2:g?`6`:`10`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})}):null]}),re?(0,Q.jsx)(`div`,{className:`preview-tab-menu`,role:`menu`,style:{left:Math.max(8,Math.min(re.x,window.innerWidth-200)),top:Math.max(8,Math.min(re.y,window.innerHeight-160))},children:oe.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`preview-tab-menu-item`,disabled:e.disabled,onClick:()=>{ie(null),i(e.ids)},children:b(e.zh,e.en)},e.key))}):null,(0,Q.jsxs)(`div`,{className:`preview-body`,children:[M?(0,Q.jsxs)(`div`,{className:`work-landing`,children:[(0,Q.jsx)(`div`,{className:`work-landing-head`,children:b(`工具`,`Tools`)}),(0,Q.jsx)(`div`,{className:`work-landing-grid`,children:aD.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`work-tool-card`,onClick:()=>s(e.tool),title:b(e.hintZh,e.hintEn),children:[(0,Q.jsx)(`span`,{className:`work-tool-icon`,children:e.icon}),(0,Q.jsx)(`span`,{className:`work-tool-label`,children:b(e.zh,e.en)}),(0,Q.jsx)(`span`,{className:`work-tool-hint`,children:b(e.hintZh,e.hintEn)})]},e.tool))})]}):null,e.map(e=>(0,Q.jsx)(`div`,{className:`preview-slot${e.id===j?.id&&!M?``:` preview-slot-hidden`}`,children:e.kind===`file`?(0,Q.jsx)(kT,{path:e.path,root:e.root,initialMode:e.mode??null,focusLine:e.line,toolbar:B,onOpenPath:p?t=>p(t,e.root):void 0}):e.kind===`terminal`?(0,Q.jsx)(AT,{termId:e.id,cwd:e.cwd,initialCommand:e.initialCommand??null,active:e.id===j?.id&&!M,onClose:()=>i([e.id])}):e.kind===`files`?(0,Q.jsx)(wE,{...d}):e.kind===`web`?(0,Q.jsx)(oE,{initialUrl:e.url,onAddNote:v}):e.kind===`history`?(0,Q.jsx)(EE,{conversationId:y}):e.kind===`prompt`?(0,Q.jsx)(DE,{conversationId:y,active:e.id===j?.id&&!M}):e.kind===`canvas`?(0,Q.jsx)(qE,{root:u,onOpenFile:f}):(0,Q.jsx)(BT,{itemId:e.id})},e.id)),R&&N?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`preview-files-resizer`,role:`separator`,"aria-orientation":`vertical`,title:b(`拖动调整文件列表宽度(双击复位)`,`Drag to resize the file list (double-click to reset)`),onPointerDown:L,onDoubleClick:()=>I(eD)}),(0,Q.jsx)(TE,{root:R.root||u,activePath:R.path,revealSeq:m,onOpenFile:f,width:F})]}):null]})]})}function sD(e){e.kind===`side`&&RT(e.id)}function cD({className:e}){return(0,Q.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M4.7 3.3h7.9a2.3 2.3 0 0 1 2.3 2.3v6a2.3 2.3 0 0 1-2.3 2.3H8.1L5.4 16.6v-2.7h-.7a2.3 2.3 0 0 1-2.3-2.3v-6a2.3 2.3 0 0 1 2.3-2.3Z`}),(0,Q.jsx)(`path`,{d:`M16.9 9.1h.8a2.3 2.3 0 0 1 2.3 2.3v6a2.3 2.3 0 0 1-2.3 2.3h-6.1`})]})}function lD(e,t,n){let r=new Map,i=[],a=(e,t,n)=>{let a={cwd:t,name:n,sessions:[]};return r.set(e,a),i.push(a),a};for(let t of e){let e=j(t.cwd),n=r.get(e)??a(e,t.cwd,t.name);for(let e of t.sessions)n.sessions.some(t=>t.id===e.id)||n.sessions.push(e)}let o=new Map;for(let e of t){let t=j(e.workspace);t!==``&&o.set(e.id,{conversation:e,key:t})}for(let e of i)e.sessions=e.sessions.filter(t=>{let n=o.get(t.id);return!n||n.key===j(e.cwd)});let s=new Set(i.flatMap(e=>e.sessions.map(e=>e.id)));for(let e of t){if(s.has(e.id))continue;let t=j(e.workspace),i=r.get(t)??a(t,e.workspace,e.workspace===``?n:D(e.workspace)),o={id:e.id,title:e.title||q(`新对话`,`New chat`),startedAt:e.createdAt,updatedAt:e.updatedAt,cwd:e.workspace,model:null,sessionPath:``};i.sessions.unshift(o),s.add(o.id)}return i.filter(e=>e.sessions.length>0)}function uD(e,t){let n=new Set(t.map(j).filter(e=>e!==``)),r=[],i=[];for(let t of e)n.has(j(t.cwd))?i.push(t):r.push(t);return{visible:r,hidden:i}}var dD={fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`};function fD({className:e}){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:e,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`3.8`,width:`17.6`,height:`4.8`,rx:`1.4`,...dD}),(0,Q.jsx)(`path`,{d:`M4.9 8.6v9.6a1.8 1.8 0 0 0 1.8 1.8h10.6a1.8 1.8 0 0 0 1.8-1.8V8.6`,...dD}),(0,Q.jsx)(`path`,{d:`M9.4 13.2h5.2`,...dD})]})}function pD({total:e,open:t,onToggle:n}){let r=J();return e<=0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-row-entry`,"aria-expanded":t,title:t?r(`收起归档的会话`,`Collapse archived sessions`):r(`已归档 · ${e}(点一下展开,可恢复 / 删除)`,`Archived · ${e} (click to expand; restore or delete)`),onClick:n,children:[(0,Q.jsx)(`span`,{className:`proj-chevron`,"aria-hidden":`true`,children:(0,Q.jsx)(fD,{className:`archived-row-entry-icon`})}),(0,Q.jsxs)(`span`,{className:`archived-row-entry-name`,children:[r(`已归档`,`Archived`),` · `,e]})]})}function mD(e,t,n){let r=e.indexOf(n),i=t===null?-1:e.indexOf(t);if(r<0||i<0)return[n];let[a,o]=i<=r?[i,r]:[r,i];return e.slice(a,o+1)}function hD(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function gD(e,t){if(e.length===0)return[];let n=new Set(t);return e.filter(e=>n.has(e))}function _D({open:e}){return(0,Q.jsx)(`span`,{className:`proj-chevron${e?` proj-chevron-open`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:e,className:`proj-folder`})})}function vD({groups:e,onOpen:t,onRestore:n,onRestoreMany:r}){let i=J(),a=e.reduce((e,t)=>e+t.items.length,0),[o,s]=(0,C.useState)([]),c=(0,C.useRef)(null),[l,u]=(0,C.useState)(new Set),d=(e,t)=>u(n=>{let r=new Set(n);if(r.has(e)){r.delete(e);let n=new Set(t);s(e=>e.filter(e=>!n.has(e)))}else r.add(e);return r}),f=e=>l.has(e),p=e.flatMap(e=>f(e.name)?e.items.map(e=>e.id):[]),m=Yd();return(0,Q.jsxs)(`div`,{className:`archived-inline`,children:[o.length>0?(0,Q.jsxs)(`div`,{className:`archived-inline-bar sidebar-selection`,children:[(0,Q.jsx)(`span`,{className:`sidebar-selection-count`,"aria-live":`polite`,children:i(`已选 ${o.length} 条`,`${o.length} selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn`,title:i(`把这些恢复回主列表`,`Restore these back to the main list`),onClick:()=>{let e=[...o];e.length!==0&&(e.length===1?n(e[0]):r(e),s([]),c.current=null)},children:i(`恢复`,`Restore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn sidebar-selbtn-danger${m.armed?` sidebar-selbtn-armed`:``}`,title:m.armed?i(`再点一次就真删这些会话文件:不可恢复`,`Click again to permanently delete these session files`):i(`把选中的这些连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected sessions including their files — first click only arms it`),onClick:()=>{let e=[...o];e.length!==0&&m.run(()=>{Ud(e,`选中的归档会话`),s([]),c.current=null})},children:m.armed?i(`确认彻底删除`,`Confirm purge`):i(`彻底删除`,`Purge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon`,title:i(`取消选择`,`Clear selection`),"aria-label":i(`取消选择`,`Clear selection`),onClick:()=>{s([]),c.current=null},children:`✕`})]}):null,(0,Q.jsxs)(`div`,{className:`archived-view-list archived-inline-list`,children:[e.map(e=>(0,Q.jsxs)(`div`,{className:`archived-group`,children:[(0,Q.jsx)(`div`,{className:`archived-group-title`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-group-toggle`,onClick:()=>d(e.name,e.items.map(e=>e.id)),"aria-expanded":f(e.name),title:f(e.name)?i(`收起这个项目的归档`,`Collapse this project's archive`):i(`展开这个项目的归档`,`Expand this project's archive`),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${f(e.name)?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(_D,{open:!1}),(0,Q.jsxs)(`span`,{className:`archived-group-name`,children:[e.name,` · `,e.items.length]})]})}),(f(e.name)?e.items:[]).map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`archived-open${o.includes(e.id)?` archived-row-on`:``}`,title:i(`点一下选中 · Shift 连选 · Ctrl/⌘ 加减选 · 双击打开\n${e.id}`,`Click to select · Shift for a range · Ctrl/⌘ to add or remove · Double-click to open\n${e.id}`),onClick:t=>{t.shiftKey?s(mD(p,c.current,e.id)):t.ctrlKey||t.metaKey?(s(hD(o,e.id)),c.current=e.id):(s([e.id]),c.current=e.id)},onDoubleClick:()=>t(e.id),children:(0,Q.jsx)(`span`,{className:`archived-title`,children:e.title})},e.id))]},e.name)),a===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:i(`没有归档的会话`)}):null]})]})}function yD({point:e,anchor:t,count:n,onArchive:r,onDelete:i,onClear:a,onClose:o}){let s=J(),c=e=>()=>{o(),e()},l=Yd();return(0,Q.jsxs)(qd,{point:e,anchor:t,className:`pi-menu`,closeOnLeave:!0,onClose:o,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:s(`把这 ${n} 条一起隐藏,可在「已归档」里找回或撤销`,`Hide all ${n}; find them under Archived or undo`),onClick:c(r),children:[`🗄 `,s(`归档这 ${n} 条`,`Archive ${n}`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${l.armed?` proj-menu-item-armed`:``}`,title:l.armed?s(`再点一次就真删这 ${n} 个会话文件:不可恢复`,`Click again to permanently delete these ${n} session file(s) — not recoverable`):s(`把选中的 ${n} 条连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected ${n} including their files — first click only arms it`),"aria-label":l.armed?s(`再点一次确认彻底删除`,`Click again to delete permanently`):s(`彻底删除选中的会话`,`Permanently delete selected sessions`),onClick:()=>l.run(()=>{o(),i()}),children:l.armed?s(`🧨 再点一次彻底删除这 ${n} 条`,`🧨 Click again to purge ${n}`):s(`🧨 彻底删除这 ${n} 条`,`🧨 Purge ${n}`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:c(a),children:[`✕ `,s(`取消选择`,`Clear selection`)]})]})}function bD({count:e,onArchive:t,onDelete:n,onClear:r}){let i=J(),a=Yd();return(0,Q.jsxs)(`span`,{className:`sidebar-selection`,children:[(0,Q.jsx)(`span`,{className:`sidebar-selection-count`,title:i(`已选中 ${e} 条会话(Shift 连选 · Ctrl/⌘ 加减选)`,`${e} session(s) selected (Shift for a range · Ctrl/⌘ to add or remove)`),"aria-label":i(`已选中 ${e} 条会话`,`${e} session(s) selected`),"aria-live":`polite`,children:i(`已选 ${e} 条`,`${e} selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn`,title:i(`把这 ${e} 条一起隐藏,可在「已归档」里找回或撤销`,`Hide all ${e}; find them under Archived or undo`),onClick:t,children:i(`归档`,`Archive`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn sidebar-selbtn-danger${a.armed?` sidebar-selbtn-armed`:``}`,title:a.armed?i(`再点一次就真删这 ${e} 个会话文件:不可恢复`,`Click again to permanently delete these ${e} session file(s) — not recoverable`):i(`把选中的 ${e} 条连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected ${e} including their files — first click only arms it`),"aria-label":a.armed?i(`再点一次确认彻底删除`,`Click again to delete permanently`):i(`彻底删除选中的会话`,`Permanently delete selected sessions`),onClick:()=>a.run(n),children:a.armed?i(`确认彻底删除`,`Confirm purge`):i(`彻底删除`,`Purge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon`,title:i(`取消选择`,`Clear selection`),"aria-label":i(`取消选择`,`Clear selection`),onClick:r,children:`✕`})]})}function xD(e,t){return e.map(e=>({name:e.name||e.cwd,items:e.sessions.filter(e=>t.archived.includes(e.id)).map(e=>({id:e.id,title:e.title||q(`(无标题)`,`(untitled)`)}))})).filter(e=>e.items.length>0)}function SD(e,t,n,r){return n[e.cwd]??(t===0||e.sessions.some(e=>e.id===r))}function CD(e,t=Date.now()){let n=Math.max(0,t-e),r=6e4;if(n<r)return q(`刚刚`,`just now`);if(n<60*r)return q(`${Math.floor(n/r)}分`,`${Math.floor(n/r)}m`);if(n<1440*r)return q(`${Math.floor(n/(60*r))}小时`,`${Math.floor(n/(60*r))}h`);let i=Math.floor(n/(1440*r));if(i<30)return q(`${i}天`,`${i}d`);let a=Math.floor(i/30);return a<12?q(`${a}个月`,`${a}mo`):q(`${Math.floor(a/12)}年`,`${Math.floor(a/12)}y`)}function wD({session:e,active:t,running:n,unseen:r=!1,title:i,pinned:a,selected:o=!1,menuPoint:s,onOpenMenu:c,onSwitch:l,onPin:u,onRename:d,onAiRename:f,onArchive:p,onDelete:m,onOpenInNewTab:h,onFork:g,canFork:_=!1,onCloseMenu:v,draggable:y,onDragStart:b,onDragEnd:x,dragOver:S,onDragOver:w,onDragLeave:T,onDrop:E}){let D=J(),[O,k]=(0,C.useState)(!1),[A,j]=(0,C.useState)(!1),M=()=>{f&&!A&&(j(!0),Promise.resolve(f()).finally(()=>j(!1)))},[N,P]=(0,C.useState)(i),F=(0,C.useRef)(null);(0,C.useEffect)(()=>{O&&(P(i),requestAnimationFrame(()=>{F.current?.focus(),F.current?.select()}))},[O,i]);let I=(0,C.useRef)(null),L=(0,C.useRef)(null),R=(0,C.useRef)(null),z=()=>{let e=L.current,t=R.current;if(!e||!t)return;let r=n?0:64,i=Math.ceil(t.getBoundingClientRect().width-(e.clientWidth-r));if(i<=0){e.style.removeProperty(`--pi-title-shift`),e.style.removeProperty(`--pi-title-dur`);return}e.style.setProperty(`--pi-title-shift`,`-${i}px`);let a=Math.min(12e3,Math.max(1500,Math.round(i/25*1e3)));e.style.setProperty(`--pi-title-dur`,`${a}ms`)},B=()=>{let e=N.replace(/\s+/g,` `).trim().slice(0,60);k(!1),e!==``&&e!==i&&d(e)},V=o||s!==null;return(0,Q.jsxs)(`div`,{ref:I,className:`pi-row-wrap${t?` pi-row-wrap-active`:``}${V?` pi-row-wrap-selected`:``}${n?` pi-row-wrap-running`:``}${S?` pi-row-drag-over`:``}`,draggable:y,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e.id),t.dataTransfer.effectAllowed=`move`,b?.()},onDragEnd:x,onDragOver:w?e=>{e.dataTransfer?.types.includes(`text/plain`)&&(e.preventDefault(),w())}:void 0,onDragLeave:T,onDrop:E?e=>{e.preventDefault(),e.stopPropagation(),E()}:void 0,onContextMenu:e=>{e.preventDefault(),e.ctrlKey?l({shift:!1,toggle:!0}):c({x:e.clientX,y:e.clientY})},onMouseEnter:z,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pi-row${t?` pi-row-active`:``}${V?` pi-row-selected`:``}${a?` pi-row-pinned`:``}`,onClick:e=>l({shift:e.shiftKey,toggle:e.metaKey||e.ctrlKey}),title:`${e.cwd}\n${e.id}\n${D(`最后活动:`,`Last activity: `)}${CD(e.updatedAt)}`,children:[O?(0,Q.jsx)(`input`,{ref:F,className:`pi-row-title pi-row-title-input`,...wu,value:N,onChange:e=>P(e.target.value),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),B()):e.key===`Escape`&&(e.preventDefault(),k(!1))},onBlur:B}):(0,Q.jsx)(`span`,{ref:L,className:`pi-row-title`,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),k(!0)},title:D(`双击改名`),children:(0,Q.jsx)(`span`,{ref:R,className:`pi-row-title-text`,children:i})}),n?(0,Q.jsx)(`span`,{className:`pi-running`,role:`img`,"aria-label":D(`这个会话正在运行`,`This session is running`),title:D(`这个会话正在运行`,`This session is running`),children:(0,Q.jsx)(`span`,{className:`pi-ring`,"aria-hidden":`true`})}):r?(0,Q.jsx)(`span`,{className:`pi-unseen`,role:`img`,"aria-label":D(`已跑完,还没看`,`Finished, not reviewed`),title:D(`跑完了、你还没看(点开这条会话就消失)`,`Finished and not reviewed — open it to clear`)}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`pi-more`,title:D(`更多操作(置顶 / 重命名 / 归档…)`),onClick:e=>{e.stopPropagation();let t=e.currentTarget.getBoundingClientRect();c({x:t.left,y:t.bottom+2})},children:`⋯`}),s?(0,Q.jsx)(Xd,{anchor:I.current,title:i,pinned:a,onClose:v,onPin:u,onRename:()=>k(!0),onAiRename:f?M:void 0,aiRenaming:A,onOpenInNewTab:h,fork:g?{enabled:_,reason:_?void 0:D(`当前引擎不支持分叉`,`The current engine does not support forking`),onFork:g}:void 0,onArchive:p,onDelete:m}):null]})}function TD({count:e,open:t,onToggle:n}){let r=J();return e<=0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-row-entry hidden-row-entry`,title:t?r(`收起隐藏的项目`,`Collapse hidden projects`):r(`已隐藏 ${e} 个项目(点一下展开,里面跟「项目」那一栏一样能点开项目、打开会话)`,`${e} hidden project(s) — click to expand; projects and sessions work like the main list`),"aria-expanded":t,onClick:n,children:[(0,Q.jsx)(`span`,{className:`proj-chevron`,"aria-hidden":`true`,children:`🙈`}),(0,Q.jsxs)(`span`,{className:`hidden-row-name`,children:[r(`已隐藏`,`Hidden`),` · `,e]})]})}function ED({value:e,onChange:t,onCommit:n,onCancel:r}){let i=J();return(0,Q.jsx)(`input`,{className:`proj-name proj-name-input`,...wu,value:e,autoFocus:!0,onFocus:e=>e.currentTarget.select(),onChange:e=>t(e.target.value),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),n()):e.key===`Escape`&&(e.preventDefault(),r())},onBlur:n,title:i(`回车保存 · Esc 取消(只改显示名,不动目录)`)})}function DD({point:e,anchor:t,onClose:n,pinned:r,onTogglePin:i,onNewSession:a,onMoveUp:o,onMoveDown:s,onRename:c,onOpenFiles:l,onOpenTerminal:u,onReveal:d,onHide:f,hidden:p=!1,onUnhide:m,onDeleteAll:h,sessionCount:g}){let _=J(),v=Yd(),y=e=>()=>{e(),n()};return(0,Q.jsxs)(qd,{point:e,anchor:t,closeOnLeave:!0,onClose:n,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在这个项目下开一条新会话`,`Start a new session under this project`),onClick:y(a),children:[`💬 `,_(`新建会话`,`New session`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(i),children:r?`📌 ${_(`取消置顶`,`Unpin`)}`:`📌 ${_(`置顶项目`,`Pin project`)}`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在同组内上移一格`,`Move up one slot within this group`),onClick:y(o),children:[`↑ `,_(`上移`,`Move up`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在同组内下移一格`,`Move down one slot within this group`),onClick:y(s),children:[`↓ `,_(`下移`,`Move down`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(c),children:[`✏️ `,_(`重命名`,`Rename`),`…`]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(l),children:[`📁 `,_(`在文件列表中定位`,`Reveal in the file list`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(u),children:[`⌨ `,_(`在终端中打开`,`Open in terminal`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在系统文件管理器里定位这个目录(只定位,不执行任何文件)`),onClick:y(d),children:[`🔍 `,_(`在文件夹中打开`,`Open in folder`)]}),p?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`把它放回主列表(会话都在,位置也还是原来的)`,`Put it back in the main list (sessions and position are kept)`),onClick:y(()=>m?.()),children:[`👁 `,_(`取消隐藏`,`Unhide`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`把这个项目从侧栏收起来(会话都还在;可撤销,也可在「已隐藏」里放回来)`,`Hide this project from the sidebar (sessions stay; undoable, or unhide from “Hidden”)`),onClick:y(f),children:[`🙈 `,_(`隐藏项目`,`Hide project`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${v.armed?` proj-menu-item-armed`:``}`,title:v.armed?_(`再点一次就真删这些会话文件:不可恢复`):_(`彻底删除这个项目下的全部会话(不可恢复);第一下只是确认`),onClick:()=>v.run(()=>{n(),h()}),children:v.armed?_(`🗑 再点一次确认删除 · ${g}`,`🗑 Click again to delete · ${g}`):_(`🗑 删除全部会话… · ${g}`,`🗑 Delete all sessions… · ${g}`)})]})}function OD({conversations:e,activeId:t,piProjects:n,runningIds:r=[],onOpenTerminal:i,onFork:a,canFork:o,onOpenFiles:s,onNewProject:c}){let l=J(),u=Zv(),d=Ro(e=>e.snapshot?.settings.projectPrefs??null),f=Ro(e=>e.snapshot?.settings.sessionPrefs??null),[p]=Eh(qr,10,1,50),m=Ho(),h=d??{order:[],pinned:[],aliases:{},hidden:[]},g={order:h.order.map(j),pinned:h.pinned.map(j),aliases:Object.fromEntries(Object.entries(h.aliases).map(([e,t])=>[j(e),t])),hidden:(h.hidden??[]).map(j)},_=g.pinned,v=()=>{let e=xo().snapshot?.settings.projectPrefs;return e?{order:e.order.map(j),pinned:e.pinned.map(j),aliases:Object.fromEntries(Object.entries(e.aliases).map(([e,t])=>[j(e),t])),hidden:(e.hidden??[]).map(j)}:g},[y,b]=(0,C.useState)({}),x=(0,C.useRef)(0),S=(0,C.useRef)(null),w=(0,C.useRef)(!1),T=()=>{S.current!==null&&(window.clearTimeout(S.current.timer),S.current=null)},[E,D]=(0,C.useState)(null),[O,k]=(0,C.useState)(!0);(0,C.useEffect)(()=>uc(()=>k(e=>!e)),[]);let[A,M]=(0,C.useState)(!1),[N,P]=(0,C.useState)(!1),F=(0,C.useRef)(null),I=()=>{P(!0),requestAnimationFrame(()=>F.current?.scrollIntoView({block:`nearest`}))},L=f??{pinned:[],archived:[],order:[]},[R,z]=(0,C.useState)(!0),[B,V]=(0,C.useState)(null),[H,U]=(0,C.useState)([]),W=(0,C.useRef)(null),[ee,G]=(0,C.useState)(null),[K,te]=(0,C.useState)(null),[ne,re]=(0,C.useState)(null),[ie,ae]=(0,C.useState)(null),[oe,se]=(0,C.useState)(null),[ce,le]=(0,C.useState)(null),ue=()=>xo().snapshot?.settings.sessionPrefs??L,de=e=>bu({sessionPrefs:{...ue(),...e}}),fe=(e,t)=>{let n=ue();n.archived.includes(e)||(bu({sessionPrefs:{...n,archived:[...n.archived,e]}}),Z({text:l(`已归档「${t||`未命名会话`}」`,`Archived "${t||`Untitled session`}"`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>pe(e)},{label:l(`查看`,`View`),onClick:I}]}))},pe=e=>{let t=ue();t.archived.includes(e)&&bu({sessionPrefs:{...t,archived:t.archived.filter(t=>t!==e)}})},me=xD(n,L),he=me.reduce((e,t)=>e+t.items.length,0),[ge,_e]=(0,C.useState)({}),ve=g.aliases,[ye,be]=(0,C.useState)(null),xe=()=>{if(!ye)return;let e=ye.draft.replace(/\s+/g,` `).trim(),t={...g.aliases};e===``?delete t[ye.cwd]:t[ye.cwd]=e,bu({projectPrefs:{...g,aliases:t}}),be(null)},Se=(e,t)=>{let n=_.includes(e),r=g.order.filter(e=>!_.includes(e)),i=r.length>0?r:Me.filter(e=>!_.includes(e.cwd)).map(e=>e.cwd),a=n?_:i,o=a.indexOf(e),s=o+t;if(o<0||s<0||s>=a.length)return;let c=[...a];c.splice(o,1),c.splice(s,0,e),bu({projectPrefs:n?{...g,pinned:c}:{...g,order:c}})},Ce=(e,t)=>{let n=[...e.querySelectorAll(`details.proj[data-cwd]`)],r=null;for(let e of n){if(e.classList.contains(`proj-hidden`))continue;let n=e.dataset.cwd??``;if(n===``||n===oe)continue;let i=(e.querySelector(`.proj-head`)??e).getBoundingClientRect();if(r={cwd:n,after:!0},t<i.top+i.height/2)return{cwd:n,after:!1}}return r},we=(e,t,n)=>{let r=lm({visible:Ae.map(e=>e.cwd),pinned:_,from:e,target:t,after:n});r&&bu({projectPrefs:{...g,...r}})},Te=e=>{let t=_.includes(e)?_.filter(t=>t!==e):[e,..._];bu({projectPrefs:{...g,pinned:t}})},Ee=e=>{let t=v(),n=j(e),r=t.hidden.filter(e=>j(e)!==n);r.length!==t.hidden.length&&(bu({projectPrefs:{...t,hidden:r}}),r.length===0&&M(!1))},De=(e,t,n)=>{let r=v(),i=j(e);r.hidden.some(e=>j(e)===i)||(bu({projectPrefs:{...r,hidden:[...r.hidden,e]}}),D(null),Z({text:l(`已隐藏项目「${t}」(${n} 条会话)`,`Hid project "${t}" (${n} session(s))`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>Ee(e)},{label:l(`查看`,`View`),onClick:()=>M(!0)}]}))};new Set(n.map(e=>e.cwd));let Oe=new Map(e.filter(e=>e.title!==``).map(e=>[e.id,e.title])),ke=e=>Oe.get(e.id)||e.title,Ae=lD(n,e,l(`未分组`,`Ungrouped`));Ae.splice(0,Ae.length,...cm(Ae,g));let je=uD(Ae,g.hidden),Me=je.visible,q=je.hidden,Ne=(e,n)=>SD(e,n,y,t),Y=Me.every((e,t)=>Ne(e,t)),Pe=Me.flatMap(e=>e.sessions.filter(e=>L.pinned.includes(e.id)&&!L.archived.includes(e.id))).sort((e,t)=>L.pinned.indexOf(e.id)-L.pinned.indexOf(t.id)),Fe=new Map;for(let e of Ae){let t=Qc(e.sessions.filter(e=>!L.archived.includes(e.id)&&!L.pinned.includes(e.id)),L.order),n=ge[e.cwd]===!0;Fe.set(e.cwd,{expanded:n,visibleSessions:t,shown:n?t:t.slice(0,p)})}let Ie=[];Pe.length>0&&R&&Ie.push(...Pe.map(e=>e.id)),O&&Me.forEach((e,t)=>{let n=Fe.get(e.cwd);n&&Ne(e,t)&&Ie.push(...n.shown.map(e=>e.id))}),O&&A&&q.forEach(e=>{let t=Fe.get(e.cwd);t&&y[e.cwd]===!0&&Ie.push(...t.shown.map(e=>e.id))});let Le=()=>{U([]),G(null),W.current=null},Re=e=>{let t=mD(Ie,W.current,e);U(t),t.length===1&&(W.current=e)},ze=e=>{U(t=>hD(t,e)),W.current=e},Be=()=>{let e=H;if(e.length===0)return;let t=new Set(e),n=ue();de({archived:[...n.archived.filter(e=>!t.has(e)),...e]}),Le(),Z({text:l(`已归档 ${e.length} 条会话`,`Archived ${e.length} session(s)`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>{de({archived:ue().archived.filter(e=>!t.has(e))})}},{label:l(`查看`,`View`),onClick:I}]})},Ve=()=>{let e=H;e.length!==0&&(Le(),Ud(e,l(`选中的 ${e.length} 条会话`,`${e.length} selected session(s)`)))};(0,C.useEffect)(()=>{if(H.length===0)return;let e=gD(H,Ie);e.length!==H.length&&U(e)});let He=()=>{b(Object.fromEntries([...Me,...q].map(e=>[e.cwd,!Y]))),z(!Y)},Ue=e=>{te({id:e.id,cwd:e.cwd})},We=()=>{te(null),re(null),ae(null)},Ge=e=>{if(!K||K.id===e)return;let t=[...ue().pinned],n=t.indexOf(K.id),r=t.indexOf(e);n<0||r<0||(t.splice(n,1),t.splice(r,0,K.id),de({pinned:t}))},Ke=!!K&&L.pinned.includes(K.id),qe=e=>{if(!K)return;K.cwd!==e.cwd&&ql(K.id,e.cwd);let t=ue();bu({sessionPrefs:{...t,order:tl(t.order,K.id)}})},Je=(e,t)=>{if(!K||K.id===t||K.cwd!==e.cwd)return;let n=ue(),r=Qc(e.sessions,n.order).map(e=>e.id),i=$c(r,K.id,t);i!==r&&bu({sessionPrefs:{...n,order:el(n.order,r,i)}})},Ye=(e,n={})=>(0,Q.jsx)(wD,{session:e,active:e.id===t,selected:H.includes(e.id),running:r.includes(e.id),unseen:m[e.id]!==void 0,title:ke(e)||l(`(无标题)`,`(untitled)`),pinned:L.pinned.includes(e.id),menuPoint:B?.id===e.id?B.point:null,onOpenMenu:t=>{H.length>1&&H.includes(e.id)?(V(null),G({point:t})):(G(null),H.length>0&&Le(),W.current=e.id,V({id:e.id,point:t}))},onSwitch:({shift:t,toggle:n})=>{t?Re(e.id):n?ze(e.id):(U([]),G(null),W.current=e.id,ho(e.id),Yl(e.id))},onPin:()=>{let t=ue().pinned;de({pinned:t.includes(e.id)?t.filter(t=>t!==e.id):[...t,e.id]})},onAiRename:async()=>{await Kl(e.id)||Z({text:xo().lastError?.text??l(`AI 重命名失败,稍后再试`)})},onRename:t=>{Gl(e.id,t)},onArchive:()=>fe(e.id,ke(e)),onOpenInNewTab:()=>window.open(kc(window.location.href,e.id),`_blank`,`noopener`),onFork:a?()=>a(e.id):void 0,canFork:o,onDelete:()=>Hd(e.id,ke(e)||e.id),onCloseMenu:()=>V(null),draggable:!n.noDrag,onDragStart:()=>Ue(e),onDragEnd:We,...(()=>{if(oe||n.noDrag)return{};let t={dragOver:ie===e.id,onDragOver:()=>ae(e.id),onDragLeave:()=>ae(t=>t===e.id?null:t)};if(n.pinnedGroup)return Ke?{...t,onDrop:()=>Ge(e.id)}:{};let r=n.project;return!r||!K||K.cwd!==r.cwd||K.id===e.id?{}:{...t,onDrop:()=>Je(r,e.id)}})()},e.id);return(0,Q.jsxs)(`aside`,{className:`sidebar`,children:[(0,Q.jsx)(`div`,{className:`sidebar-drag`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`sidebar-head sidebar-brand`,children:[(0,Q.jsxs)(`span`,{className:`brand`,children:[u.logoShown?(0,Q.jsx)(`img`,{className:`brand-icon`,src:u.logo||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}):null,u.shown?(0,Q.jsx)(`span`,{className:`brand-name`,children:u.name}):null]}),(0,Q.jsx)(jw,{variant:`sidebar`})]}),Pe.length>0?(0,Q.jsxs)(`section`,{className:`pin-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pin-group-head sidebar-title`,title:R?l(`收起置顶`,`Collapse pinned`):l(`展开置顶`,`Expand pinned`),"aria-expanded":R,onClick:()=>z(e=>!e),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${R?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:l(`置顶会话`,`Pinned sessions`)})]}),R?(0,Q.jsx)(`div`,{className:`pin-group-body`,children:Pe.map(e=>Ye(e,{pinnedGroup:!0}))}):null]}):null,(0,Q.jsxs)(`div`,{className:`sidebar-head${H.length>0?` sidebar-head-selecting`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-title`,title:O?l(`收起项目`,`Collapse projects`):l(`展开项目`,`Expand projects`),"aria-expanded":O,onClick:()=>k(e=>!e),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${O?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:l(`项目`,`Projects`)})]}),H.length>0?(0,Q.jsx)(bD,{count:H.length,onArchive:Be,onDelete:Ve,onClear:Le}):null,(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon sidebar-icon-inline${H.length>0?` sidebar-icon-away`:``}`,title:l(`新建项目(选择一个本地目录)`,`New project (pick a local folder)`),"aria-label":l(`新建项目`,`New project`),onClick:c,children:(0,Q.jsx)(op,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon sidebar-icon-inline${H.length>0?` sidebar-icon-away`:``}`,title:Y?l(`全部收起(只留项目名)`,`Collapse all (project names only)`):l(`全部展开(显示各项目的会话)`,`Expand all (show each project's sessions)`),"aria-label":Y?l(`全部收起`,`Collapse all`):l(`全部展开`,`Expand all`),"aria-pressed":Y,onClick:()=>{O?He():(k(!0),b(Object.fromEntries(Me.map(e=>[e.cwd,!0]))),z(!0))},children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M5.4 2.4 8 5.2 10.6 2.4`}),(0,Q.jsx)(`path`,{d:`M5.4 13.6 8 10.8 10.6 13.6`}),(0,Q.jsx)(`path`,{d:`M2.8 8h10.4`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-row-fill`,"aria-hidden":`true`,tabIndex:-1,onClick:()=>k(e=>!e)})]}),(0,Q.jsxs)(`div`,{className:`sidebar-list${O?``:` sidebar-list-hidden`}`,onDragOver:e=>{if(!oe)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=Ce(e.currentTarget,e.clientY);t&&le(t)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||le(null)},onDrop:e=>{if(!oe)return;e.preventDefault(),e.stopPropagation();let t=Ce(e.currentTarget,e.clientY);t&&we(oe,t.cwd,t.after),se(null),le(null)},children:[Me.length===0&&q.length===0?(0,Q.jsx)(`div`,{className:`sidebar-empty`,children:l(`还没有会话。发一条消息就会自动建一个;「临时会话(不保存)」不会留在这里。`,`No sessions yet. Sending a message creates one — but a “temporary session (not saved)” never shows up here.`)}):null,(A?[...Me,...q]:Me).map((e,t)=>{let n=q.some(t=>t.cwd===e.cwd),{expanded:a,visibleSessions:o,shown:c}=Fe.get(e.cwd),u=o.length-c.length,d=ve[e.cwd]||e.name||l(`未分组`,`Ungrouped`),f=n?y[e.cwd]===!0:Ne(e,t),h=e.sessions.some(e=>r.includes(e.id)),g=e.sessions.filter(e=>m[e.id]!==void 0&&!L.archived.includes(e.id));return(0,Q.jsxs)(Q.Fragment,{children:[n&&q[0]?.cwd===e.cwd?(0,Q.jsx)(TD,{count:q.length,open:!0,onToggle:()=>M(!1)}):null,(0,Q.jsxs)(`details`,{"data-cwd":e.cwd,"data-hidden":n?`true`:void 0,className:`proj${n?` proj-hidden`:``}${ne===e.cwd?` proj-drag-over`:``}${oe===e.cwd?` proj-dragging`:``}${ce?.cwd===e.cwd?ce.after?` proj-drop-after`:` proj-drop-before`:``}`,open:f,onMouseDown:e=>{e.button!==0&&(x.current=performance.now())},onToggle:t=>{let n=t.currentTarget,r=n.open;w.current?(w.current=!1,n.open=f):performance.now()-x.current<400?n.open=f:b(t=>({...t,[e.cwd]:r}))},onDragOver:t=>{n||!oe&&K&&(t.preventDefault(),K.cwd!==e.cwd&&re(e.cwd))},onDragLeave:()=>{n||re(t=>t===e.cwd?null:t)},onDrop:t=>{n||oe||(t.preventDefault(),K&&qe(e),We())},children:[(0,Q.jsxs)(`summary`,{className:`proj-head`,title:`${e.cwd||l(`未分组`,`Ungrouped`)}\n${n?l(`右键:项目菜单(可取消隐藏)`,`Right-click for the project menu (unhide)`):l(`拖动可换项目顺序 右键:项目菜单`,`Drag to reorder projects · Right-click for the project menu`)}`,draggable:!n&&ye?.cwd!==e.cwd,onDragStart:t=>{n||(t.dataTransfer.setData(`text/plain`,e.cwd),t.dataTransfer.effectAllowed=`move`,se(e.cwd))},onDragEnd:()=>{se(null),le(null)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),T(),D({cwd:e.cwd,point:{x:t.clientX,y:t.clientY},anchor:t.currentTarget})},onPointerDown:t=>{if(w.current=!1,T(),t.pointerType!==`touch`||ye?.cwd===e.cwd)return;let n=t.currentTarget,r={x:t.clientX,y:t.clientY},i=window.setTimeout(()=>{S.current=null,w.current=!0,D({cwd:e.cwd,point:r,anchor:n})},450);S.current={timer:i,x:r.x,y:r.y}},onPointerMove:e=>{let t=S.current;t&&(Math.abs(e.clientX-t.x)>10||Math.abs(e.clientY-t.y)>10)&&T()},onPointerUp:T,onPointerCancel:T,onPointerLeave:T,onClick:t=>{w.current||(ye?.cwd===e.cwd&&t.preventDefault(),go(e.sessions.map(e=>e.id)))},children:[(0,Q.jsx)(_D,{open:f}),ye?.cwd===e.cwd?(0,Q.jsx)(ED,{value:ye.draft,onChange:t=>be({cwd:e.cwd,draft:t}),onCommit:xe,onCancel:()=>be(null)}):(0,Q.jsx)(`span`,{className:`proj-name`,children:d}),(()=>{let t=!f&&h,n=!f&&!h&&g.length>0,r=_.includes(e.cwd);return!t&&!n&&!r?null:(0,Q.jsxs)(Q.Fragment,{children:[t?(0,Q.jsx)(`span`,{className:`proj-busy`,role:`img`,"aria-label":l(`这个项目里有会话正在跑`,`A session in this project is running`),title:l(`这个项目里有会话正在跑(展开就能看到是哪一条)`,`A session in this project is running (expand to see which)`),children:(0,Q.jsx)(`span`,{className:`proj-busy-ring`,"aria-hidden":`true`})}):n?(0,Q.jsx)(`span`,{className:`proj-unseen`,role:`img`,"aria-label":l(`有会话跑完了、你还没看`,`A session finished and is not reviewed yet`),title:l(`有 ${g.length} 条会话跑完了、你还没看(点一下这个项目就消失)`,`${g.length} session(s) finished and unreviewed (click the project to clear)`)}):(0,Q.jsx)(`span`,{className:`proj-ind-slot`,"aria-hidden":`true`}),r?(0,Q.jsx)(`span`,{className:`proj-pin`,title:l(`已置顶`),"aria-label":l(`已置顶`),children:`📌`}):(0,Q.jsx)(`span`,{className:`proj-ind-slot`,"aria-hidden":`true`})]})})(),(0,Q.jsx)(`button`,{type:`button`,className:`proj-more`,title:l(`项目菜单(新建会话 / 重命名 / 定位…)`),onClick:t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();D({cwd:e.cwd,point:{x:n.left,y:n.bottom+2},anchor:t.currentTarget.closest(`.proj-head`)})},children:`⋯`})]}),E?.cwd===e.cwd?(0,Q.jsx)(DD,{anchor:E.anchor,onClose:()=>D(null),pinned:_.includes(e.cwd),onTogglePin:()=>Te(e.cwd),onNewSession:()=>Mo(e.cwd),onMoveUp:()=>Se(e.cwd,-1),onMoveDown:()=>Se(e.cwd,1),onRename:()=>be({cwd:e.cwd,draft:d}),onOpenFiles:()=>{s?.(e.cwd)},onOpenTerminal:()=>i?.(e.cwd),onReveal:()=>void fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:e.cwd})}),onDeleteAll:()=>Ud(e.sessions.map(e=>e.id),`「${d}」下的全部会话`),onHide:()=>De(e.cwd,d,e.sessions.length),hidden:n,onUnhide:()=>Ee(e.cwd),sessionCount:e.sessions.length}):null,(0,Q.jsxs)(`div`,{className:`proj-body`,children:[c.map(t=>Ye(t,{project:e,noDrag:n})),u>0?(0,Q.jsx)(`button`,{type:`button`,className:`pi-row pi-row-more`,title:a?l(`收起,只显示前几个`,`Collapse back to the first few`):l(`展开,显示全部 ${o.length} 个会话`,`Expand to show all ${o.length} sessions`),onClick:()=>_e(t=>({...t,[e.cwd]:!a})),children:a?l(`收起`,`Collapse`):l(`还有 ${u} 个…`,`and ${u} more…`)}):a&&o.length>p?(0,Q.jsx)(`button`,{type:`button`,className:`pi-row pi-row-more`,onClick:()=>_e(t=>({...t,[e.cwd]:!1})),children:l(`收起`,`Collapse`)}):null]})]},e.cwd||d)]})}),q.length>0&&!A?(0,Q.jsx)(TD,{count:q.length,open:!1,onToggle:()=>M(!0)}):null,(0,Q.jsxs)(`div`,{className:`archived-block`,ref:F,children:[(0,Q.jsx)(pD,{total:he,open:N,onToggle:()=>P(e=>!e)}),N&&he>0?(0,Q.jsx)(vD,{groups:me,onOpen:e=>{Le(),Yl(e),P(!1)},onRestore:pe,onRestoreMany:e=>{let t=new Set(e);de({archived:ue().archived.filter(e=>!t.has(e))})}}):null]})]}),ee?(0,Q.jsx)(yD,{point:ee.point,count:H.length,onArchive:Be,onDelete:Ve,onClear:Le,onClose:()=>G(null)}):null]})}var kD=(0,C.memo)(OD),AD=`pop-agent.contentSearch.size`,jD=32,MD=96;function ND(e,t,n,r){return PD({w:e.w+t*2,h:e.h+n},r)}function PD(e,t){let n=Math.max(420,t.width-jD),r=Math.max(240,t.height-MD-jD/2),i=Number.isFinite(e.w)?e.w:920,a=Number.isFinite(e.h)?e.h:r;return{w:Math.round(Math.min(Math.max(i,420),n)),h:Math.round(Math.min(Math.max(a,240),r))}}function FD(e){if(e===null)return null;try{let t=JSON.parse(e),n=Number(t?.w),r=Number(t?.h);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?null:{w:n,h:r}}catch{return null}}function ID(e){try{let t=JSON.parse(e);return typeof t==`object`&&t?t:null}catch{return null}}var LD=250;function RD({open:e,root:t,onClose:n,onOpen:r,presetGlob:i=null}){let a=J(),[o,s]=(0,C.useState)(``),[c,l]=(0,C.useState)(``);(0,C.useEffect)(()=>{i&&l(i.value)},[i]);let[u,d]=(0,C.useState)([]),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)(!1),[v,y]=(0,C.useState)(0),[b,x]=(0,C.useState)(!1),S=(0,C.useRef)(null),w=(0,C.useRef)(null),[T,E]=(0,C.useState)(()=>{try{return FD(localStorage.getItem(AD))}catch{return null}}),D=(0,C.useRef)(null),O=(0,C.useRef)(T),[k,A]=(0,C.useState)(!1),j=(0,C.useRef)(null),M=e=>{O.current=e,E(e)};if((0,C.useEffect)(()=>{e&&(S.current?.focus(),S.current?.select())},[e]),(0,C.useEffect)(()=>{if(!e||!t||b)return;let n=o.trim();if(n===``){d([]),p(!1),h(null),_(!1);return}let r=!1;_(!0);let i=setTimeout(()=>{(async()=>{try{let e=new URLSearchParams({q:n,root:t,glob:c}),i=await fetch(`/api/files/grep?${e}`),o=ID(await i.text());if(r)return;if(o===null){d([]),p(!1),y(0),h(a(`搜索接口没有返回数据(服务端大概是旧进程):重启一次 pop-agent 再试`,`The search endpoint returned no JSON (the server is probably an older build): restart pop-agent and retry`));return}d(o.matches??[]),p(o.truncated===!0),h(i.ok?null:o.error?.message??a(`搜索失败`,`Search failed`)),y(0)}catch(e){if(r)return;d([]),p(!1),h(e instanceof Error?e.message:a(`搜索失败`,`Search failed`))}finally{r||_(!1)}})()},LD);return()=>{r=!0,clearTimeout(i)}},[e,o,c,t,a,b]),(0,C.useEffect)(()=>{d([]),p(!1),h(null),y(0)},[t]),(0,C.useEffect)(()=>{e&&(w.current?.querySelector(`[data-hit="${v}"]`))?.scrollIntoView({block:`nearest`})},[v,e,u]),!e)return null;let N=e=>{e&&(r(e.path,e.line),n())},P=e=>{if(!(b||e.nativeEvent.isComposing)){if(e.key===`Escape`)e.preventDefault(),n();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(u.length===0)return;e.preventDefault();let t=e.key===`ArrowDown`?1:-1;y(e=>(e+t+u.length)%u.length)}else e.key===`Enter`&&(e.preventDefault(),N(u[v]))}},F=o.trim(),I=e=>{let t=j.current;if(!t)return;e.preventDefault();let n=t.getBoundingClientRect();D.current={x:e.clientX,y:e.clientY,w:n.width,h:n.height},A(!0),e.currentTarget.setPointerCapture?.(e.pointerId)},L=e=>{let t=D.current;t&&M(ND({w:t.w,h:t.h},e.clientX-t.x,e.clientY-t.y,{width:window.innerWidth,height:window.innerHeight}))},R=()=>{if(D.current){D.current=null,A(!1);try{let e=O.current;e?localStorage.setItem(AD,JSON.stringify(e)):localStorage.removeItem(AD)}catch{}}},z=T===null?null:PD(T,{width:window.innerWidth,height:window.innerHeight}),B=z===null?void 0:{width:z.w,height:z.h,maxHeight:`none`},V=F===``?a(`输入关键字,搜工作区里的文件内容`,`Type to search file contents in the workspace`):m?``:g?a(`搜索中…`,`Searching…`):u.length===0?a(`没有匹配的行`,`No matching lines`):`${a(`${u.length} 条结果`,`${u.length} results`)}${f?a(`(只显示前若干条,换个更具体的关键字)`,` (first results only — narrow the query)`):``}`;return(0,Q.jsx)(`div`,{className:`content-search-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":a(`搜索文件内容`,`Search file contents`),onKeyDown:P,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,Q.jsxs)(`div`,{className:`content-search${k?` content-search-resizing`:``}`,ref:j,style:B,children:[(0,Q.jsxs)(`div`,{className:`content-search-head`,children:[(0,Q.jsx)(`input`,{ref:S,className:`content-search-input`,value:o,onChange:e=>s(e.target.value),onCompositionStart:()=>x(!0),onCompositionEnd:e=>{x(!1),s(e.currentTarget.value)},placeholder:a(`搜索文件内容…`,`Search file contents…`),"aria-label":a(`关键字`,`Query`),spellCheck:!1}),(0,Q.jsx)(`input`,{className:`content-search-glob mono`,value:c,onChange:e=>l(e.target.value),placeholder:a(`文件掩码,如 *.ts`,`File mask, e.g. *.ts`),"aria-label":a(`文件掩码`,`File mask`),title:a("只看匹配的文件:`*.ts` 看文件名,`src/**/*.go` 看路径,留空则搜全部","Limit to matching files: `*.ts` matches names, `src/**/*.go` matches paths, empty = all"),spellCheck:!1}),(0,Q.jsx)(`kbd`,{className:`content-search-esc`,children:`Esc`})]}),m?(0,Q.jsx)(`div`,{className:`content-search-error`,children:m}):null,(0,Q.jsx)(`div`,{className:`content-search-list`,ref:w,children:u.map((e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-hit":t,className:`content-search-row${t===v?` content-search-row-on`:``}`,onClick:()=>N(e),title:`${e.path}:${e.line}`,onMouseMove:()=>{t!==v&&y(t)},children:[(0,Q.jsx)(`span`,{className:`content-search-line mono`,children:zD(e,F)}),(0,Q.jsxs)(`span`,{className:`content-search-where mono`,children:[e.path,`:`,e.line]})]},`${e.path}:${e.line}`))}),(0,Q.jsxs)(`div`,{className:`content-search-foot`,children:[(0,Q.jsx)(`span`,{className:`content-search-status`,children:V}),(0,Q.jsxs)(`span`,{className:`content-search-keys`,children:[(0,Q.jsx)(`kbd`,{children:`↑`}),(0,Q.jsx)(`kbd`,{children:`↓`}),` `,a(`切换结果`,`switch`),(0,Q.jsx)(`kbd`,{children:`⏎`}),` `,a(`打开`,`open`)]})]}),(0,Q.jsx)(`div`,{className:`content-search-grip`,"aria-hidden":`true`,title:a(`拖动调整大小(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:I,onPointerMove:L,onPointerUp:R,onPointerCancel:R,onDoubleClick:()=>M(null)})]})})}function zD(e,t){if(t===``||e.column<0)return e.text;let n=e.column+t.length;return(0,Q.jsxs)(Q.Fragment,{children:[e.text.slice(0,e.column),(0,Q.jsx)(`mark`,{className:`content-search-mark`,children:e.text.slice(e.column,n)}),e.text.slice(n)]})}function BD({engine:e,onClose:t,onInstalled:n}){let r=J(),[i,a]=(0,C.useState)(!1),[o,s]=(0,C.useState)(null),c=(0,C.useRef)(null),[l,u]=(0,C.useState)(null);(0,C.useEffect)(()=>{fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(t=>{let n=t?.engines.find(t=>t.name===e.name)??null;u(n)}).catch(()=>void 0)},[e.name]),(0,C.useEffect)(()=>{c.current?.focus()},[]),(0,C.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!i&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i,t]);let d=async()=>{a(!0),s(null);try{let t=await fetch(`/api/engines/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e.name})}),i=await t.json(),a=t.ok&&i.ok===!0;s({ok:a,message:i.message??(a?r(`装好了`,`Installed`):r(`安装失败`,`Install failed`)),restartRequired:i.restartRequired===!0}),a&&n()}catch(e){s({ok:!1,restartRequired:!1,message:r(`安装请求失败:${e instanceof Error?e.message:String(e)}`,`Install request failed: ${e instanceof Error?e.message:String(e)}`)})}finally{a(!1)}},f=o?.ok===!0&&o.restartRequired;return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`engine-install-title`,onMouseDown:e=>{e.target===e.currentTarget&&!i&&t()},children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,id:`engine-install-title`,children:r(`还没装 ${e.label}`,`${e.label} is not installed`)}),(0,Q.jsx)(`p`,{className:`modal-risk`,children:r(`切到 ${e.label} 需要它自己的命令行程序,这台机器上没找到。`,`Switching to ${e.label} needs its own CLI, and it is not on this machine.`)}),(0,Q.jsx)(`p`,{children:r(`装了才会启动它;不装的话继续用 pi 就行,什么时候想用再装。`,`Installing lets it start. If you skip it, keep using pi and install whenever you want.`)}),o?(0,Q.jsx)(`p`,{className:o.ok?`modal-ok`:`modal-risk`,children:o.message}):l&&l.guide.length>0?(0,Q.jsxs)(`p`,{className:`modal-hint`,children:[r(`装到 ~/.pop-agent(你自己的 npm 目录,不碰系统、不用 sudo)。`,`Installs into ~/.pop-agent (your own npm prefix — no system changes, no sudo).`),l.afterInstall?` ${r(l.afterInstall)}`:``]}):null,(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn`,onClick:t,disabled:i,children:f?r(`关闭`,`Close`):r(`以后再装`,`Not now`)}),l?.installable===!1?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:i||o?.ok===!0,children:i?r(`正在安装…`,`Installing…`):r(`安装 ${e.label}`,`Install ${e.label}`)})]}),l?.installable===!1?(0,Q.jsxs)(`p`,{className:`modal-hint`,children:[r(`这个引擎没有公开的 npm 包,只能你自己装:`,`This engine has no public npm package — install it yourself:`),l.guide.join(`;`)]}):null]})})}function VD(){return(0,Q.jsxs)(`svg`,{className:`engine-picker-icon`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.6`,y:`5.2`,width:`10.8`,height:`7.6`,rx:`2.3`}),(0,Q.jsx)(`path`,{d:`M8 5.2V3.3`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.4`,r:`0.85`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`9`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`9`,r:`0.8`,fill:`currentColor`,stroke:`none`})]})}function HD(){return(0,Q.jsx)(`svg`,{className:`engine-picker-chevron`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M4.4 6.2 8 9.8l3.6-3.6`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function UD(){return(0,Q.jsx)(`svg`,{className:`engine-picker-check`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M3.4 8.4 6.6 11.6 12.6 4.8`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function WD(e){return e?/^\d/.test(e)?`v${e}`:e:``}function GD(e,t,n){return WD((t?n:null)??e.version??null)}function KD({placement:e=`appbar`}={}){let t=J(),n=Ro(e=>e.snapshot),[r,i]=(0,C.useState)(!1),a=(0,C.useRef)(null),o=(0,C.useRef)(null),s=(0,C.useRef)(null),[c,l]=(0,C.useState)(null),u=n?.engines??[],d=n?.engine??``,f=u.find(e=>e.name===d),p=n?n.running.status!==`idle`:!1,[m,h]=(0,C.useState)({}),[g,_]=(0,C.useState)(null),v=()=>{fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(e=>{if(!e)return;let t={};for(let n of e.engines)n.installed||(t[n.name]=!0);h(t)}).catch(()=>void 0)};if((0,C.useEffect)(()=>{r&&v()},[r]),(0,C.useLayoutEffect)(()=>{if(!r){l(null);return}let t=()=>{let t=o.current?.getBoundingClientRect(),n=s.current?.getBoundingClientRect();if(!t||!n)return;if(e===`statusbar`){let{left:e,bottom:r,arrow:i}=Rf({trigger:{left:t.left,top:t.top,width:t.width,height:t.height},popover:{width:n.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8});l({left:e,top:Math.max(8,window.innerHeight-r-n.height),arrow:i});return}let r=o.current?.closest(`.appbar`)?.getBoundingClientRect().bottom??0,i=Math.max(t.top+t.height,r);l(zf({trigger:{left:t.left,top:i-t.height,width:t.width,height:t.height},popover:{width:n.width},viewport:{width:window.innerWidth,height:window.innerHeight}}))};return t(),window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[r,e]),(0,C.useEffect)(()=>{if(!r)return;let e=e=>{a.current&&!a.current.contains(e.target)&&i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]),u.length===0)return null;let y=t(f?.label??d),b=f?.badge??d.toUpperCase();return(0,Q.jsxs)(`div`,{className:`engine-picker${e===`statusbar`?` engine-picker-in-statusbar`:``}`,ref:a,children:[(0,Q.jsxs)(`button`,{ref:o,type:`button`,className:`side-foot-btn engine-picker-btn${r?` side-foot-btn-on`:``}`,onClick:()=>i(e=>!e),title:p?t(`切换智能体引擎(回合进行中,先等它结束)`,`Switch agent engine (a turn is running — wait for it to end)`):t(`切换智能体引擎`,`Switch agent engine`),"aria-haspopup":`listbox`,"aria-expanded":r,"aria-label":t(`智能体引擎:${y}`,`Agent engine: ${y}`),children:[(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(VD,{})}),(0,Q.jsx)(`span`,{className:`engine-picker-badge`,children:b}),(0,Q.jsx)(HD,{})]}),r?(0,Q.jsxs)(`div`,{ref:s,className:`engine-pop`,role:`listbox`,"aria-label":t(`智能体引擎`),style:c?{left:c.left,top:c.top}:{visibility:`hidden`},children:[c?(0,Q.jsx)(`span`,{className:`engine-pop-arrow`,style:{left:c.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`div`,{className:`engine-pop-scroll`,children:[(0,Q.jsxs)(`div`,{className:`engine-pop-head`,children:[(0,Q.jsx)(`span`,{className:`engine-pop-title`,children:t(`智能体引擎`)}),(0,Q.jsx)(`span`,{className:`engine-pop-note`,children:t(`切换后项目与会话跟着新引擎`)})]}),u.map(e=>{let r=e.name===d,a=GD(e,r,n?.versions.engine);return(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":r,disabled:p&&!r,className:`engine-option${r?` engine-option-on`:``}`,onClick:()=>{i(!1),!r&&(m[e.name]?_(e):tu(e.name))},title:p&&!r?t(`回合进行中,先中断或等它结束`,`A turn is running — interrupt it or wait for it to end`):void 0,children:[(0,Q.jsxs)(`span`,{className:`engine-option-top`,children:[(0,Q.jsx)(`span`,{className:`engine-option-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(VD,{})}),(0,Q.jsx)(`span`,{className:`engine-option-badge`,children:e.badge}),(0,Q.jsx)(`span`,{className:`engine-option-label`,children:t(e.label)}),m[e.name]?(0,Q.jsx)(`span`,{className:`engine-option-version`,children:t(`未安装`,`not installed`)}):a?(0,Q.jsx)(`span`,{className:`engine-option-version`,children:a}):null,(0,Q.jsx)(`span`,{className:`engine-option-tail`,children:r?(0,Q.jsx)(UD,{}):null})]}),e.description?(0,Q.jsx)(`span`,{className:`engine-option-desc`,children:t(e.description)}):null,(0,Q.jsxs)(`span`,{className:`engine-option-caps`,children:[e.capabilities.approvals?t(`审批拦截`,`Approval gate`):t(`自行授权`,`Self-approved`),e.capabilities.modelSwitch?` · ${t(`模型可切`,`switchable models`)}`:``,e.capabilities.thinkingLevel?` · ${t(`思考强度`,`thinking level`)}`:``,e.capabilities.resume?` · ${t(`可续历史`,`resumable history`)}`:``]})]},e.name)}),p?(0,Q.jsx)(`div`,{className:`engine-pop-hint`,children:t(`有回合在跑:先中断或等结束再切`)}):null]})]}):null,g?(0,Q.jsx)(BD,{engine:{name:g.name,label:g.label},onClose:()=>_(null),onInstalled:v}):null]})}function qD(e){return e.replace(/\.?0+$/,``)}function JD(e){return e<1e3?String(e):e<1e6?`${qD((e/1e3).toFixed(1))}K`:`${qD((e/1e6).toFixed(2))}M`}function YD({snapshot:e,appbarHidden:t,onToggleAppbar:n,terminalOpen:r,onToggleTerminal:i,onOpenHistory:a,onOpenPrompt:o,onOpenSettings:s}){let c=J(),{language:l}=je(),u=e?Object.values(e.runningByConversation??{}).filter(e=>e.status!==`idle`).length:0,d=(e?.queued??[]).length,[f]=bp(Br,Wr,Hr),[p]=tx(),m=e=>({order:p.indexOf(e)}),h=e?.sessionStats??null,[g,..._]=String(e?.model??``).split(`/`),v=(e?.providers??[]).find(e=>e.provider===g)?.models.find(e=>e.id===_.join(`/`)),y=v?.contextWindow&&v.contextWindow>0?v.contextWindow:null,b=h?.contextTokens??0,x=y?Math.min(1,b/y):0,S=y?Math.round(x*100):null,w=37.7,[T,E]=(0,C.useState)(!1),[D,O]=(0,C.useState)(null),k=(0,C.useRef)(null),A=(0,C.useRef)(null);return(0,C.useLayoutEffect)(()=>{if(!T){O(null);return}let e=()=>{let e=k.current?.getBoundingClientRect(),t=A.current?.getBoundingClientRect();e&&t&&O(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight}}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[T]),(0,C.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.target;t&&(A.current?.contains(t)||k.current?.contains(t)||E(!1))},t=e=>{e.key===`Escape`&&E(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[T]),(0,Q.jsxs)(`footer`,{className:`statusbar`,children:[s?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`settings`),onClick:s,title:c(`设置`,`Settings`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:(0,Q.jsx)(nx,{name:`settings`})}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`设置`,`Settings`)})]}):null,(0,Q.jsxs)(`span`,{className:`status-controls`,children:[e?.engineCapabilities.approvals===!1?(0,Q.jsx)(`span`,{className:`tool-chip tool-static`,style:{...m(`approval`),display:f.approval?void 0:`none`},title:c(`该引擎自行决定授权,本工作台拦不住它的危险操作`,`This engine decides approvals itself; the workbench cannot block its risky operations`),children:c(`🔒 审批:引擎自理`,`🔒 Approvals: engine-managed`)}):(0,Q.jsx)(`button`,{type:`button`,className:`tool-chip${e?.approvalMode===`allow`?` tool-chip-warn`:``}`,style:{...m(`approval`),display:f.approval?void 0:`none`},onClick:()=>nu(e?.approvalMode===`allow`?`ask`:`allow`,e?.active.conversationId??null),title:c(`审批模式(全局生效,重启回到默认:全部放行)——点一下在「全部放行 / 询问」之间切换`,`Approval mode (global; resets to allow-all on restart) — click to switch between allow-all and ask`),children:e?.approvalMode===`allow`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`🔓`}),(0,Q.jsx)(`span`,{children:c(`全部放行`,`Allow all`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`🔒`}),(0,Q.jsx)(`span`,{children:c(`询问`,`Ask`)})]})}),f.engine?(0,Q.jsx)(`span`,{className:`statusbar-slot`,style:m(`engine`),children:(0,Q.jsx)(KD,{placement:`statusbar`})}):null]}),f.queued?(0,Q.jsxs)(`span`,{className:`status-item status-queued`,style:m(`queued`),title:c(`所有项目 / 所有会话的待发队列合计`,`Queued messages across all sessions and projects`),children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`⏳`}),` `,c(`排队`,`Queued`),` `,d]}):null,f.running?(0,Q.jsxs)(`span`,{className:`status-item status-running${u>0?` is-working`:``}`,style:m(`running`),title:c(`所有项目 / 所有会话里正在跑的回合数`,`Turns currently running across all sessions and projects`),children:[(0,Q.jsx)(`span`,{className:`status-spinner`,"aria-hidden":`true`}),c(`工作中`,`Running`),` `,u]}):null,f.context?(0,Q.jsxs)(`span`,{className:`status-context-wrap`,style:m(`context`),children:[(0,Q.jsxs)(`button`,{ref:k,type:`button`,className:`status-context`,title:y?c(`当前会话上下文:已用 ${b.toLocaleString()} / 窗口 ${y.toLocaleString()}(${S}%)· 点开看整段会话累计(每条回复底部的 I/O/C 只算那一轮)`,`Context of this session: ${b.toLocaleString()} used / ${y.toLocaleString()} window (${S}%) · click for the whole-session total (the I/O/C line under each reply covers that turn only)`):c(`当前会话上下文(模型窗口未知)`,`Context of this conversation (model window unknown)`),onClick:()=>E(e=>!e),children:[(0,Q.jsxs)(`svg`,{className:`status-ring`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{className:`status-ring-bg`,cx:`8`,cy:`8`,r:`6`}),(0,Q.jsx)(`circle`,{className:`status-ring-fg`,cx:`8`,cy:`8`,r:`6`,style:{strokeDasharray:`${(x*w).toFixed(2)} ${w}`}})]}),(0,Q.jsx)(`span`,{className:`status-context-used`,children:JD(b)}),(0,Q.jsxs)(`span`,{className:`status-context-total`,children:[`/`,y?JD(y):`—`]})]}),T?(0,Q.jsxs)(`div`,{ref:A,className:`status-usage-pop`,role:`dialog`,"aria-label":c(`会话信息`,`Session info`),style:D?{left:D.left,bottom:D.bottom}:{visibility:`hidden`},children:[D?(0,Q.jsx)(`span`,{className:`status-usage-arrow`,style:{left:D.arrow},"aria-hidden":`true`}):null,(0,Q.jsx)(`div`,{className:`status-usage-title`,children:c(`会话信息(整段会话)`,`Session info (whole session)`)}),[[c(`用户消息`,`User messages`),String(h?.userMessages??0)],[c(`助手消息`,`Assistant messages`),String(h?.assistantMessages??0)],[c(`工具调用`,`Tool calls`),String(h?.toolCalls??0)],[c(`输入(未命中缓存)`,`Input (cache misses)`),JD(h?.inputTokens??0)],[c(`输出`,`Output`),JD(h?.outputTokens??0)],[c(`缓存读(命中)`,`Cache read (hits)`),JD(h?.cacheRead??0)],[c(`缓存写`,`Cache write`),JD(h?.cacheWrite??0)],[c(`总花费`,`Total cost`),h?.cost?z_(h.cost):`—`],[c(`上下文(最后一次)`,`Context (last call)`),y?`${JD(b)} / ${JD(y)}`:JD(b)]].map(([e,t])=>(0,Q.jsxs)(`div`,{className:`status-usage-row`,children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsx)(`span`,{className:`mono`,children:t})]},e)),(0,Q.jsx)(`div`,{className:`status-usage-note`,children:l===`en`?(0,Q.jsxs)(Q.Fragment,{children:[`The numbers above are cumulative for `,(0,Q.jsx)(`b`,{children:`the whole session`}),`; the I / O / C line under each reply is `,(0,Q.jsx)(`b`,{children:`that turn's own`}),` usage. “Input” `,(0,Q.jsx)(`b`,{children:`excludes`}),` cache hits (hits are counted under cache read — the whole prefix is re-read every turn, so that number is large). “Context” counts only`,` `,(0,Q.jsx)(`b`,{children:`the last`}),` call: input + cache read + cache write, which is why it is usually much larger than the cumulative input.`,(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`b`,{children:`Subagents`}),` are separate sessions billed separately, so they are `,(0,Q.jsx)(`b`,{children:`not`}),` part of the numbers above (open the subagent cards in the conversation for their own usage).`]}):(0,Q.jsxs)(Q.Fragment,{children:[`上面这些是`,(0,Q.jsx)(`b`,{children:c(`整段会话`)}),c(`的累计值;每条回复底部那行`),` `,(0,Q.jsx)(`b`,{children:`I / O / C`}),` `,c(`是`),(0,Q.jsx)(`b`,{children:c(`那一轮自己的`)}),`用量。 「输入」`,(0,Q.jsx)(`b`,{children:c(`不含`)}),`缓存命中部分(命中单列在缓存读里,每一轮都重新读一遍整个前缀,所以会很大)。 「上下文」只算`,(0,Q.jsx)(`b`,{children:c(`最后一次`)}),`调用:输入 + 缓存读 + 缓存写,所以它常比累计输入大得多。`,(0,Q.jsx)(`br`,{}),`另外,`,(0,Q.jsx)(`b`,{children:c(`子代理`)}),`是独立会话、单独计费,`,(0,Q.jsx)(`b`,{children:c(`不在`)}),`上面的统计里(去对话里的子代理卡片看它们各自的用量)。`]})})]}):null]}):null,a&&f.history?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle status-view`,style:m(`history`),onClick:a,title:c(`完整历史:整份会话(含工具调用、思考与分支)在右侧面板展开`,`Full history: the whole session (tools, thinking, branches) in the side panel`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`📜`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`完整历史`,`History`)})]}):null,o&&f.prompt?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle status-view`,style:m(`prompt`),onClick:o,title:c(`系统提示词:这次运行实际在用的那段(AGENTS.md / 技能都拼好了)`,`System prompt: the text this run actually uses (context files and skills included)`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`🧾`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`系统提示词`,`Prompt`)})]}):null,f.terminal?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`terminal`),"aria-pressed":r,onClick:i,title:r?c(`隐藏终端`,`Hide terminal`):c(`显示终端`,`Show terminal`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`🖥️`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`终端`,`Terminal`)})]}):null,f.top?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`top`),onClick:n,title:t?c(`显示顶部栏`,`Show the top bar`):c(`隐藏顶部栏`,`Hide the top bar`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:t?`⬇️`:`⬆️`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:t?c(`显示顶部`,`Show top`):c(`隐藏顶部`,`Hide top`)})]}):null]})}var XD=`pop-agent.bottom-term.height`,ZD=240,QD=120,$D=900,eO=.7,tO=0;function nO(e){return tO+=1,`${e}:${tO}`}function rO({open:e,cwd:t,onHide:n,request:r=null,onOpenSettings:i}){let a=J(),[o,s]=Eh(XD,ZD,QD,$D),[c,l]=(0,C.useState)([]),[u,d]=(0,C.useState)(null),f=(0,C.useCallback)((e,t=null)=>{let n={id:nO(`bterm`),cwd:e,initialCommand:t},r={id:nO(`bgroup`),panes:[n],activePaneId:n.id};l(e=>[...e,r]),d(r.id)},[]),p=(0,C.useRef)(0);(0,C.useEffect)(()=>{e&&(r&&r.seq!==p.current?(p.current=r.seq,f(r.cwd,r.initialCommand??null)):c.length===0&&f(t))},[e,c.length,r,t,f]),(0,C.useEffect)(()=>{c.length!==0&&(u&&c.some(e=>e.id===u)||d(c[c.length-1].id))},[c,u]);let m=e=>{let t=c.filter(t=>t.id!==e);l(t),t.length===0&&n()},h=(e,t)=>{let n=c.find(t=>t.id===e);if(!n)return;if(n.panes.length<=1){m(e);return}let r=n.panes.findIndex(e=>e.id===t),i=n.panes.filter(e=>e.id!==t);l(n=>n.map(n=>n.id===e?{...n,panes:i,activePaneId:n.activePaneId===t?i[Math.min(Math.max(r,0),i.length-1)].id:n.activePaneId}:n))},g=(e,t)=>{let n=c.find(t=>t.id===e);n&&u===e&&n.activePaneId===t||(d(e),l(n=>n.map(n=>n.id===e?{...n,activePaneId:t}:n)))};return(0,Q.jsxs)(`section`,{className:`bottom-term`,style:{height:o},hidden:!e,"aria-label":a(`终端`,`Terminal`),children:[(0,Q.jsx)(`div`,{className:`bottom-term-handle`,role:`separator`,"aria-orientation":`horizontal`,title:a(`拖动调整高度`,`Drag to resize`),onPointerDown:e=>{e.preventDefault();let t=e.clientY,n=o,r=e=>{let r=Math.min($D,Math.round(window.innerHeight*eO)),i=n+(t-e.clientY);s(Math.max(QD,Math.min(r,i)))},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i)};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)}}),(0,Q.jsxs)(`div`,{className:`bottom-term-bar`,children:[(0,Q.jsx)(`div`,{className:`bottom-term-tabs`,role:`tablist`,children:c.map((e,t)=>{let n=e.id===u;return(0,Q.jsxs)(`div`,{role:`tab`,"aria-selected":n,className:`bottom-term-tab${n?` is-active`:``}`,title:e.panes[0]?.cwd??void 0,onClick:()=>d(e.id),children:[(0,Q.jsxs)(`span`,{children:[a(`终端`,`Terminal`),` `,t+1,e.panes.length>1?` · ${e.panes.length}`:``]}),(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-tab-x`,title:a(`关闭这个终端(含所有分屏)`,`Kill this terminal (all splits)`),"aria-label":a(`关闭这个终端`,`Kill this terminal`),onClick:t=>{t.stopPropagation(),m(e.id)},children:`×`})]},e.id)})}),(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn`,title:a(`新建终端`,`New terminal`),"aria-label":a(`新建终端`,`New terminal`),onClick:()=>f(t),children:`+`}),(0,Q.jsx)(`span`,{className:`bottom-term-spacer`}),i?(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn bottom-term-settings`,title:a(`设置`,`Settings`),"aria-label":a(`设置`,`Settings`),onClick:i,children:(0,Q.jsx)(nx,{name:`settings`})}):null,(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn`,title:a(`隐藏终端(进程保留)`,`Hide terminal (shells keep running)`),"aria-label":a(`隐藏终端`,`Hide terminal`),onClick:n,children:`⌄`})]}),(0,Q.jsx)(`div`,{className:`bottom-term-body`,children:c.map(t=>(0,Q.jsx)(`div`,{className:`bottom-term-group`,hidden:t.id!==u,children:t.panes.map(n=>{let r=t.activePaneId===n.id;return(0,Q.jsx)(`div`,{className:`bottom-term-pane${r?` is-focused`:``}`,onPointerDown:()=>g(t.id,n.id),children:(0,Q.jsx)(AT,{termId:n.id,cwd:n.cwd,initialCommand:n.initialCommand,active:e&&t.id===u&&r,onClose:()=>h(t.id,n.id)})},n.id)})},t.id))})]})}function iO(){let e=navigator.userAgent;if(!e.includes(`Electron/`))return;let t=/Macintosh|Mac OS X/.test(e);document.documentElement.dataset.shell=t?`electron-mac`:`electron`}function aO(){return(document.documentElement.dataset.shell??``).startsWith(`electron`)}function oO(e){return Number.isFinite(e.chatPx)&&Number.isFinite(e.projectPx)&&Number.isFinite(e.sessionPx)}function sO(e){return`${e.chatPx}/${e.projectPx}/${e.sessionPx}`}function cO(e,t){if(!t||!oO(t))return null;let n=sO(t);return n===e?null:n}var lO=null;function uO(e){let t=cO(lO,e);t===null?e||(lO=null):(lO=t,e&&(nb(e.chatPx),Ib(e.projectPx),Lb(e.sessionPx)))}var dO=[],fO=[];function pO(){let e=J(),t=Zv(),n=t.name,r=aO(),[i,a]=(0,C.useState)(()=>Ss({stored:Yr(vs),tablet:typeof window<`u`&&Cs(e=>window.matchMedia(e).matches)})),[o,s]=(0,C.useState)(()=>Tf());(0,C.useEffect)(()=>{let e=()=>s(Tf());return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]);let[c,l]=(0,C.useState)(()=>Yr(`pop-agent:appbar-hidden`)===`1`),u=(0,C.useRef)(Tc(Yr(`pop-agent.preview.tabs.v1`))??{tabs:[],active:null,open:!1}),[d,f]=(0,C.useState)(()=>u.current?.open??!1),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(!1),[y,b]=(0,C.useState)(``),x=(0,C.useRef)(null),S=(0,C.useRef)(null),[w,T]=(0,C.useState)(0),[O,k]=(0,C.useState)(null),A=(0,C.useRef)(null),j=(0,C.useRef)(null),M=(0,C.useRef)(null),[N,P]=(0,C.useState)(!1),[F,I]=(0,C.useState)(!1),[L,B]=(0,C.useState)(()=>localStorage.getItem(`pop-agent.onboarded`)===`1`),[V,H]=(0,C.useState)(null),[U,W]=(0,C.useState)(()=>Yr(`pop-agent.split.chatSide`)===`right`?`right`:`left`),ee=()=>{let e=U===`right`?`left`:`right`;W(e),Xr(lr,e)},[G,K]=(0,C.useState)(null),[te,ne]=(0,C.useState)({path:``,seq:0}),re=d&&!p&&!o,ie=d&&p&&!o;(0,C.useEffect)(()=>{let e=document.documentElement;if(!re){e.style.setProperty(`--split-w`,`0px`),e.style.setProperty(`--top-lane`,`0px`);return}let t=()=>{let t=document.querySelector(`.appbar`),n=document.querySelector(`.preview-panel`);if(!t||!n){e.style.setProperty(`--split-w`,`0px`);return}let r=t.getBoundingClientRect(),a=n.getBoundingClientRect(),o=Math.round(a.width);e.style.setProperty(`--split-w`,`${Math.max(0,Math.round(o))}px`);let s=document.querySelector(`.appbar > .appbar-side`),c=U===`right`&&i&&s?Math.round(s.getBoundingClientRect().right-r.left):0;e.style.setProperty(`--top-lane`,`${Math.max(0,c)}px`)};t();let n=new ResizeObserver(t);for(let e of[document.querySelector(`.appbar`),document.querySelector(`.preview-panel`),document.querySelector(`.appbar > .appbar-side`)])e&&n.observe(e,{box:`border-box`});return window.addEventListener(`resize`,t),()=>{n.disconnect(),window.removeEventListener(`resize`,t)}},[re,U,i]);let[ae,oe]=(0,C.useState)(()=>(u.current?.tabs.length??0)===0),[se,ce]=(0,C.useState)(()=>xs(Yr(_s))),le=(0,C.useRef)(!1);(0,C.useEffect)(()=>{Xr(vs,i?`1`:`0`)},[i]),(0,C.useEffect)(()=>{document.documentElement.style.setProperty(`--side-w`,i||o?`0px`:`${se}px`)},[se,i,o]),(0,C.useEffect)(()=>{Xr(`pop-agent:appbar-hidden`,c?`1`:`0`)},[c]),(0,C.useEffect)(()=>{Xr(_s,String(se))},[se]),(0,C.useEffect)(()=>{let e=document.querySelector(`.appbar`);if(!e)return;let t=()=>{document.documentElement.style.setProperty(`--appbar-h`,`${e.offsetHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e,{box:`border-box`}),()=>n.disconnect()},[]);let ue=e=>{e.preventDefault(),le.current=!0,document.documentElement.classList.add(`is-resizing`);let t=e.clientX,n=Math.min(se,bs(window.innerWidth)),r=e.currentTarget,i=e.pointerId;try{r.setPointerCapture(i)}catch{}let a=e=>{le.current&&ce(ys(n+(e.clientX-t),bs(window.innerWidth)))},o=()=>{le.current=!1,document.documentElement.classList.remove(`is-resizing`),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),document.removeEventListener(`pointercancel`,o);try{r.hasPointerCapture(i)&&r.releasePointerCapture(i)}catch{}};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o),document.addEventListener(`pointercancel`,o)},[de,fe]=(0,C.useState)(()=>wc(u.current?.tabs??[])),pe=(0,C.useCallback)(()=>{let e=!d;f(e),e&&oe(de.length===0),e||m(!1)},[d,de.length]),me=(0,C.useRef)(null),he=(0,C.useCallback)((e,t,n,r)=>{let i=`file:${t}:${e}`;fe(a=>{let o=a.find(e=>e.id===i);return o?o.kind!==`file`||o.mode===n&&o.line===r?a:a.map(e=>e.id===i?{...e,mode:n,line:r}:e):[...a,{id:i,kind:`file`,path:e,root:t,...n?{mode:n}:{},...r?{line:r}:{}}]}),ye(i),oe(!1),f(!0),K(e=>xd(e,me.current,t)),ne(t=>({path:e,seq:t.seq+1}))},[]),ge=(0,C.useCallback)((e,t)=>he(e,t??``,`diff`),[he]),_e=d,[ve,ye]=(0,C.useState)(()=>u.current?.active??null);(0,C.useEffect)(()=>{Xr(Sc,Dc(de,ve,d))},[de,ve,d]);let[be,xe]=(0,C.useState)(!1),[Se,Ce]=(0,C.useState)(null),[we,Te]=(0,C.useState)(null),[Ee,De]=(0,C.useState)(0),Oe=(0,C.useCallback)(e=>{if(e.length===0)return;let t=new Set(e);fe(e=>{for(let n of e)t.has(n.id)&&sD(n);let n=e.filter(e=>!t.has(e.id));return n.length===0&&oe(!0),n}),ye(e=>e&&t.has(e)?null:e)},[]),ke=(0,C.useCallback)(e=>{fe(t=>{let n=new Map(t.map(e=>[e.id,e])),r=e.map(e=>n.get(e)).filter(e=>e!==void 0);return r.length===t.length?r:t})},[]),[Ae,je]=(0,C.useState)(null),[Me]=Bb();(0,C.useEffect)(()=>$d(e=>je(e)),[]);let[q]=uf(Nr,!1),Ne=[...xr.filter(e=>Me[e]),...Me.settings?[`settings`]:[]],Y=Ro(e=>e.snapshot),Pe=Y?.settings.appearance;(0,C.useEffect)(()=>{uO(Pe)},[Pe?.chatPx,Pe?.projectPx,Pe?.sessionPx]);let Fe=Ro(e=>e.creating),Ie=Ro(e=>e.newSession),Le=Ro(e=>e.pendingActive),Re=Ro(e=>e.pendingNewChat),ze=Ro(e=>e.lastError),Be=Ro(e=>e.connection),Ve=Ro(e=>e.preview),He=(0,C.useRef)([]),Ue=(0,C.useCallback)(e=>{let t=Nd(e,Md(He.current))??e;he(t,Y?.files?.root??``)},[he,Y?.files?.root]),We=Y?.active.conversationId??null,Ge=Y?.files?.root??null;me.current=Ge;let Ke=G??Ge,qe=(()=>{let e=de.find(e=>e.id===(ve??de[0]?.id??``));return e!==void 0&&e.kind===`file`?e:null})(),Je=(0,C.useMemo)(()=>(Y?.conversations??[]).filter(e=>!zT(e.id)),[Y?.conversations]),Ye=(0,C.useMemo)(()=>Y?.piProjects??[],[Y?.piProjects]),Xe=(0,C.useMemo)(()=>Object.keys(Y?.runningByConversation??{}),[Y?.runningByConversation]),Ze=(0,C.useCallback)(()=>P(!0),[]),Qe=(0,C.useCallback)(e=>{f(!0),oe(!1),fe(t=>t.some(t=>t.id===e)?t:[...t,{id:e,kind:e}]),ye(e)},[]),$e=(0,C.useCallback)(()=>{f(!0),oe(!1),fe(e=>e.some(e=>e.kind===`files`)?e:[...e,{id:`files`,kind:`files`}]),ye(`files`)},[]),et=(0,C.useCallback)(()=>{if(!d||ae)return!1;let e=de.find(e=>e.id===(ve??de[0]?.id??``));return e!==void 0&&e.kind===`files`},[d,ae,de,ve]),tt=(0,C.useCallback)(e=>{Ce(t=>({cwd:e,seq:(t?.seq??0)+1})),xe(!0)},[]),nt=(0,C.useCallback)(e=>{Te(t=>({value:e?`${e}/**`:``,seq:(t?.seq??0)+1})),P(!0)},[]),rt=(0,C.useCallback)(()=>I(!0),[]),it=(0,C.useCallback)(e=>{ne(t=>({path:e,seq:t.seq+1}))},[]),at=(0,C.useMemo)(()=>{let e=Y?.settings.projectPrefs?.aliases??{};return(Y?.piProjects??[]).map(t=>({cwd:t.cwd,label:e[t.cwd]||t.name||t.cwd}))},[Y?.piProjects,Y?.settings.projectPrefs?.aliases]),ot=(0,C.useMemo)(()=>{let e=G??Ge??null;return{root:e,onRootChange:K,options:at,onOpenFile:t=>he(t,e??``),onOpenChangedFile:t=>he(t,e??``,`diff`),onOpenTerminal:()=>{e&&tt(e)},onReveal:e=>{fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:e})})},onSearchContents:Ze,onOpenBottomTerminal:tt,onFindInFolder:nt,activePath:qe?.path??null,revealSeq:te.seq,revealPath:te.path||null,onRevealPath:it}},[G,Ge,at,he,tt,Ze,nt,qe,te,it]),st=(0,C.useCallback)(e=>{if(e===`files`){$e();return}if(e===`terminal`){Ge?tt(Ge):xe(!0);return}if(f(!0),oe(!1),e===`canvas`){fe(e=>e.some(e=>e.id===`canvas`)?e:[...e,{id:`canvas`,kind:`canvas`}]),ye(`canvas`);return}if(e===`side`){let e=`side:${Ee}`;fe(t=>[...t,{id:e,kind:`side`}]),ye(e),De(e=>e+1);return}let t=`${e}:${Ee}`;De(e=>e+1),fe(e=>[...e,{id:t,kind:`web`,url:``}]),ye(t)},[Ee,Ge,tt]),ct=(0,C.useCallback)(()=>{de.some(e=>e.id===`canvas`)?(fe(e=>e.filter(e=>e.id!==`canvas`)),f(!1)):(f(!0),oe(!1),fe(e=>e.some(e=>e.id===`canvas`)?e:[...e,{id:`canvas`,kind:`canvas`}]),ye(`canvas`))},[de]),[lt]=xc(),ut=(0,C.useRef)(lt);ut.current=lt;let dt=(0,C.useCallback)(e=>{switch(e){case`newChat`:Mo();return;case`newProject`:I(!0);return;case`tempChat`:st(`side`);return;case`settings`:je(`settings`);return;case`toggleRight`:pe();return;case`toggleLeft`:a(e=>!e);return;case`projects`:(i||!dc())&&a(!1);return;case`files`:d&&et()?f(!1):$e();return;case`canvas`:ct();return;case`terminal`:xe(e=>!e);return;case`contentSearch`:P(!0);return;case`toggleMic`:Ea();return;case`pauseSpeech`:hn(!mn());return;case`stopSpeech`:nn();return;case`cheatSheet`:vc();return}},[i,d,st,$e,et,ct,pe]),ft=(0,C.useRef)(dt);ft.current=dt;let pt=(0,C.useRef)(null),mt=(0,C.useCallback)(e=>{if(pt.current)return;let t={at:Date.now(),timer:null,key:e};pt.current=t,!na()&&(t.timer=setTimeout(()=>{pt.current===t&&rc(350,na())===`startHold`&&wa()},350))},[]),ht=(0,C.useCallback)(()=>{let e=pt.current;if(!e)return;pt.current=null,e.timer&&clearTimeout(e.timer);let t=rc(Date.now()-e.at,na());t===`stop`?Ta():t===`start`&&Ea()},[]),gt=(0,C.useRef)(mt);gt.current=mt;let _t=(0,C.useRef)(ht);_t.current=ht;let vt=(0,C.useCallback)(()=>{let e=pt.current;e&&(pt.current=null,e.timer&&clearTimeout(e.timer))},[]),yt=(0,C.useRef)(vt);yt.current=vt;let bt=(0,C.useRef)(null);(0,C.useEffect)(()=>{let e=e=>{if(zs(e),e.repeat||e.defaultPrevented)return;let t=Ys(ut.current,e);if(t){t===`toggleMic`?gt.current(null):bt.current={id:t};return}bt.current=null,yt.current();let n=Ws(ut.current,e);n&&(e.preventDefault(),n===`toggleMic`?gt.current(js(e)):ft.current(n))},t=e=>{zs(e);let t=bt.current;if(t&&(bt.current=null,qs(e))){ft.current(t.id);return}let n=pt.current;if(!n)return;let r=js(e);(r===null||r===n.key)&&_t.current()},n=()=>{Bs(),bt.current=null,pt.current&&_t.current()};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,t),window.addEventListener(`blur`,n),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,t),window.removeEventListener(`blur`,n)}},[]);let xt=(0,C.useCallback)(e=>{f(!0),oe(!1);let t=de.filter(e=>e.kind===`side`),n=t.length>0?t[t.length-1]?.id??`side:0`:`side:${Ee}`;t.length===0&&(De(e=>e+1),fe(e=>[...e,{id:n,kind:`side`}])),ye(n),LT(n).setDraft(`${Tu(e)}
75
+ `}${n}\n`)},fe=(0,C.useCallback)((e,t)=>{try{return p.highlight(e,{language:t,ignoreIllegals:!0}).value}catch{return``}},[]),{html:pe,done:me,total:he}=fT(ie,te!==``&&p.getLanguage(te)?te:``,fe),ge=e.startsWith(`/`)||!t?e:`${t.replace(/\/+$/,``)}/${e}`,_e=zp(e.split(`/`).pop()??e)?.tone??null;return(0,Q.jsxs)(`div`,{className:`file-viewer`,ref:W,onPointerEnter:()=>G(!0),onPointerLeave:()=>G(!1),children:[(0,Q.jsxs)(`div`,{className:`file-preview-head`,children:[(0,Q.jsxs)(`span`,{className:`file-preview-meta`,children:[(0,Q.jsxs)(`span`,{className:`file-preview-size${_e?` filetype-${_e}`:``}`,children:[v?g?o(`视频`,`Video`):o(`音频`,`Audio`):s?(e=>{let t=DT(e);return t.unit===`B`?o(`${t.value} 字节`,`${t.value} bytes`):`${t.value} ${t.unit}`})(s.bytes):o(`读取中…`,`Loading…`),s?.truncated?o(`(已截断)`,`(truncated)`):``]}),(0,Q.jsx)(`span`,{className:`file-preview-path`,title:ge,children:ge})]}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),v||h?null:(0,Q.jsxs)(`span`,{className:`preview-mode`,children:[(0,Q.jsx)(`button`,{type:`button`,className:y===`source`?`preview-mode-on`:``,onClick:()=>x(`source`),children:o(`源码`,`Source`)}),l||u?(0,Q.jsx)(`button`,{type:`button`,className:y===`preview`?`preview-mode-on`:``,onClick:()=>x(`preview`),children:u?o(`页面`,`Page`):o(`预览`,`Preview`)}):null,re?(0,Q.jsxs)(`button`,{type:`button`,className:y===`diff`?`preview-mode-on`:``,onClick:()=>x(`diff`),title:o(`相对上次提交(HEAD)改了什么`,`What changed since the last commit (HEAD)`),children:[o(`改动`,`Diff`),S?(0,Q.jsxs)(`span`,{className:`preview-mode-diff`,children:[(0,Q.jsxs)(`span`,{className:`preview-mode-plus`,children:[`+`,S.added]}),(0,Q.jsxs)(`span`,{className:`preview-mode-minus`,children:[`−`,S.removed]})]}):null]}):null]}),v||h?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-wrap${D?` preview-wrap-on`:``}`,onClick:()=>O(!D),title:D?o(`自动换行:开(长行折行显示)`,`Word wrap: on (long lines wrap)`):o(`自动换行:关(长行横向滚动)`,`Word wrap: off (long lines scroll sideways)`),"aria-pressed":D,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2 3.6h12M2 7.2h8.6a2.4 2.4 0 1 1 0 4.8H8.4`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`m9.6 10.4-1.6 1.6 1.6 1.6`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`,transform:`translate(0,-1.2)`}),(0,Q.jsx)(`path`,{d:`M2 10.8h4`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`})]})}),n]}),s?.notedPath?(0,Q.jsx)(`div`,{className:`file-preview-note`,children:o(`按文件名匹配到 ${s.notedPath}`,`Matched by file name: ${s.notedPath}`)}):null,s?.error?(0,Q.jsxs)(`div`,{className:`file-preview-error`,children:[(0,Q.jsx)(`span`,{children:s.error}),s.candidates&&s.candidates.length>0?(0,Q.jsx)(`ul`,{className:`file-preview-candidates`,children:s.candidates.map(e=>(0,Q.jsx)(`li`,{children:(0,Q.jsx)(`button`,{type:`button`,title:e,onClick:()=>a?.(e),children:e})},e))}):null]}):null,h?(0,Q.jsx)(`div`,{className:`file-image-wrap`,children:(0,Q.jsx)(`img`,{className:`file-image`,src:h,alt:e})}):null,g&&v?(0,Q.jsx)(`div`,{className:`file-media`,children:(0,Q.jsx)(`video`,{className:`file-video`,src:v,controls:!0,playsInline:!0,preload:`metadata`})}):null,_&&v?(0,Q.jsx)(`div`,{className:`file-media`,children:(0,Q.jsx)(`audio`,{className:`file-audio`,src:v,controls:!0,preload:`metadata`})}):null,s?.binary&&h===null&&v===null?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:o(`这是二进制文件,不能预览`,`This is a binary file and cannot be previewed`)}):null,s&&!s.binary&&!s.error&&l&&y===`preview`?(0,Q.jsx)(`div`,{className:`file-preview-md`,children:(0,Q.jsx)(bg,{text:s.text})}):null,u&&y===`preview`?(0,Q.jsx)(`div`,{className:`file-html-wrap`,children:(0,Q.jsx)(`iframe`,{className:`file-html-frame`,title:e,src:`/api/files/raw?${m}`,sandbox:`allow-scripts allow-popups allow-forms allow-modals`,referrerPolicy:`no-referrer`})}):null,y===`diff`&&S?(0,Q.jsx)(_T,{payload:S}):null,y===`diff`&&S===null?(0,Q.jsx)(`div`,{className:`file-diff-empty`,children:o(`正在读取改动…`,`Reading the diff…`)}):null,s&&!s.binary&&!s.error&&v===null&&y===`source`?(0,Q.jsx)(`pre`,{ref:F,className:`file-preview-body mono${D?` file-preview-body-wrap`:``}`,style:{"--ln-w":`${Math.max(2,String(ie.length).length)}ch`,fontSize:`${k}px`},onContextMenu:e=>{let t=e.target.closest(`[data-line]`);if(!t)return;let n=Number(t.getAttribute(`data-line`))+1;if(!Number.isFinite(n))return;e.preventDefault();let r=pT(e.currentTarget);L({point:{x:e.clientX,y:e.clientY},line:n,dragRange:r.range,dragText:r.text})},children:(0,Q.jsx)(vT,{lines:ie,highlighted:pe,folds:K,folded:T,isSelected:e=>M.has(e),flashLine:N,onToggleFold:e=>E(t=>Jw(K,t,e)),onPick:(e,t)=>M.click(e,t),find:R&&B!==``?{needle:B,line:ce?.line??-1,occurrence:le,lines:ue}:null})}):null,R&&y===`source`&&v===null?(0,Q.jsx)(bT,{query:B,onQuery:e=>{V(e),U(0)},total:se.length,index:se.length===0?0:Math.min(H,se.length-1),onPrev:()=>U(e=>se.length===0?0:(e-1+se.length)%se.length),onNext:()=>U(e=>se.length===0?0:(e+1)%se.length),onClose:()=>{z(!1),V(``)}}):null,!me&&he>0?(0,Q.jsxs)(`div`,{className:`file-preview-hint`,children:[`文件较大(`,he.toLocaleString(),` 行),正在分批上色…(可以边看边滚,不影响滚动)`]}):null,I?(0,Q.jsx)(yT,{state:I,appSelection:M.selection,onAddSelection:()=>{de(Kw(e,M.selection)),M.clear()},onAddRange:t=>de(Uw(e,t)),onClearSelection:M.clear,block:ae,blockState:ae?Xw(K,T,ae):null,onExpandBlock:e=>E(t=>Zw(K,t,e)),onCollapseBlock:e=>E(t=>Qw(K,t,e)),blockText:oe,blockFolded:ae!==null&&T.has(ae.start),onAddBlock:q,onFind:e=>{V(e),U(0),z(!0)},onClose:()=>L(null)}):null]})}function AT({termId:e,cwd:t,initialCommand:n=null,standalone:r=!1,active:i=!0,onClose:a}){let o=Y(),s=(0,C.useRef)(null),[c,l]=(0,C.useState)(null),[u,d]=(0,C.useState)(!1),[f,p]=(0,C.useState)(null),[m,h]=Eh(br,14,8,24),g=(0,C.useRef)(null),_=(0,C.useRef)(null),v=(0,C.useRef)(m);v.current=m;let y=(0,C.useRef)(null);return(0,C.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>y.current?.(),30);return()=>clearTimeout(e)},[i]),(0,C.useEffect)(()=>{let r=s.current;if(!r)return;let i=new S({fontSize:v.current,fontFamily:`"Cascadia Mono", Consolas, ui-monospace, SFMono-Regular, Menlo, "Courier New", monospace`,lineHeight:1.2,theme:{background:`#ffffff`,foreground:`#24292f`,cursor:`#24292f`,cursorAccent:`#ffffff`,selectionBackground:`rgb(9 105 218 / 22%)`,black:`#24292f`,red:`#cf222e`,green:`#116329`,yellow:`#7d4e00`,blue:`#0969da`,magenta:`#8250df`,cyan:`#1b7c83`,white:`#6e7781`,brightBlack:`#57606a`,brightRed:`#a40e26`,brightGreen:`#1a7f37`,brightYellow:`#633c01`,brightBlue:`#218bff`,brightMagenta:`#a475f9`,brightCyan:`#3192aa`,brightWhite:`#8c959f`},cursorBlink:!0,scrollback:2e3}),a=new x;i.loadAddon(a),i.open(r),a.fit(),g.current=i,_.current=a;let o=e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault();let t=e.deltaY<0?2:-2;h(v.current+t)};r.addEventListener(`wheel`,o,{passive:!1});let c=e=>{if(!e.ctrlKey&&!e.metaKey||e.altKey)return;let t=e.key===`+`||e.key===`=`||e.code===`NumpadAdd`,n=e.key===`-`||e.key===`_`||e.code===`NumpadSubtract`,r=e.key===`0`||e.code===`Numpad0`;(t||n||r)&&(e.preventDefault(),e.stopPropagation(),h(t?v.current+2:n?v.current-2:14))};r.addEventListener(`keydown`,c,!0);let u=null,f=null,m=!1,b=!1,C=[],w=t=>{fetch(`/api/terminal/input`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,data:t})})},T=e=>{b?w(e):C.push(e)},E=e=>{if(!e)return!1;for(let t of e){let e=t.codePointAt(0)??0;if(e<32||e===127)return!1}return!0},D=``,O=e=>{if(!e){p(null);return}let t=r.querySelector(`.xterm-screen`),n=r.parentElement;if(!t||!n||i.cols<=0||i.rows<=0){p({text:e,left:0,top:0,cellH:16,fontSize:i.options.fontSize??12,fontFamily:String(i.options.fontFamily??`monospace`)});return}let a=t.clientWidth/i.cols,o=t.clientHeight/i.rows,s=n.getBoundingClientRect(),c=t.getBoundingClientRect(),l=i.buffer.active;p({text:e,left:c.left-s.left+l.cursorX*a,top:c.top-s.top+l.cursorY*o,cellH:o,fontSize:i.options.fontSize??12,fontFamily:String(i.options.fontFamily??`monospace`)})};return i.onCursorMove(()=>{D&&O(D)}),i.onResize(()=>{D&&O(D)}),i.onData(e=>{if(i.buffer.active.type===`alternate`){let t=D;D=``,p(null),T(t+e);return}if(E(e)){D+=e,O(D);return}if(e===``&&D){D=Array.from(D).slice(0,-1).join(``),O(D);return}let t=D+e;D=``,O(``),T(t)}),i.onResize(({cols:t,rows:n})=>void fetch(`/api/terminal/resize`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,cols:t,rows:n})})),(async()=>{let o=await fetch(`/api/terminal/start`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,cols:i.cols,rows:i.rows,...t?{cwd:t}:{}})}),s=await o.json();if(m)return;if(!o.ok){l(s.error?.message??`HTTP ${o.status}`);return}d(!0),b=!0;for(let e of C.splice(0))w(e);n&&fetch(`/api/terminal/input`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e,data:`${n}\r`})});let c=0,p=()=>{u=al({wsPath:`/ws?terminal=${encodeURIComponent(e)}`,sseUrl:`/api/terminal/stream?id=${encodeURIComponent(e)}`,handlers:{onOpen:()=>{c=0},onMessage:e=>{try{i.write(JSON.parse(e))}catch{i.write(e)}},onClose:()=>{u=null,!(m||c>=5)&&(c+=1,setTimeout(()=>{m||p()},Math.min(500*2**c,8e3)))}}})};p(),f=new ResizeObserver(()=>a.fit()),f.observe(r),y.current=()=>{a.fit(),i.focus()},i.focus()})(),()=>{m=!0,r.removeEventListener(`wheel`,o),r.removeEventListener(`keydown`,c,!0),g.current=null,_.current=null,f?.disconnect(),u?.close(),fetch(`/api/terminal/stop`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({id:e})}),i.dispose()}},[t,e,n]),(0,C.useEffect)(()=>{let e=g.current;e&&e.options.fontSize!==m&&(e.options.fontSize=m,_.current?.fit())},[m]),(0,Q.jsxs)(`aside`,{className:`terminal-panel${r?``:` terminal-panel-embedded`}`,children:[r?(0,Q.jsxs)(`div`,{className:`terminal-head`,children:[(0,Q.jsxs)(`span`,{children:[`⌨ `,o(`终端`,`Terminal`),t?` · ${D(t)}`:``]}),(0,Q.jsx)(`span`,{className:`side-panel-count`,children:u?o(`PTY 已启动`,`PTY running`):o(`启动中…`,`Starting…`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:a,children:o(`关闭`,`Close`)})]}):null,c?(0,Q.jsx)(`div`,{className:`file-preview-error`,children:c}):null,(0,Q.jsx)(`div`,{className:`terminal-host`,ref:s}),f?(0,Q.jsx)(`div`,{className:`terminal-pending`,"aria-live":`polite`,style:{left:f.left,top:f.top,fontSize:f.fontSize,fontFamily:f.fontFamily,lineHeight:`${f.cellH}px`,maxWidth:`calc(100% - ${Math.round(f.left)}px)`},children:f.text}):null]})}var jT={snapshot:null,error:null,draft:``};function MT(e,t){if(typeof t!=`object`||!t)return e;let n=t;if(n.type===`reply`&&n.ok===!1){let t=n.error;return{...e,error:t?`${t.code??`error`}: ${t.message??``}`:J(`请求失败`,`Request failed`)}}if(n.type!==`event`)return e;if(n.event===`snapshot`&&typeof n.snapshot==`object`&&n.snapshot!==null)return{...e,snapshot:n.snapshot,error:null};if(n.event===`message_delta`){let t=e.snapshot,{conversationId:r,messageId:i,text:a}=n;if(!t||!i||typeof a!=`string`||!r||t.active.conversationId!==r)return e;let o=t.active.messages.map(e=>e.id===i?Wc(e,a):e);return{...e,snapshot:{...t,active:{...t.active,messages:o}}}}return e}var NT=0;function PT(){let e=`side-${rl()}`,t=jT,n=new Set,r=null,i=!1,a=e=>{if(e===t)return;t=e;let r=t.snapshot?.active.conversationId;r&&IT.add(r);for(let e of n)e(t)},o=n=>{(async()=>{try{let r=await fetch(`/api/rpc`,{method:`POST`,headers:{"content-type":`application/json`,"x-agent-client":e},body:JSON.stringify({id:`side-req-${++NT}`,...n})});if(!r.ok){a({...t,error:J(`请求失败:HTTP ${r.status}`,`Request failed: HTTP ${r.status}`)});return}let i=await r.json();for(let e of i.frames??[])try{a(MT(t,JSON.parse(e)))}catch{}}catch(e){a({...t,error:e instanceof Error?e.message:String(e)})}})()},s=()=>{if(i||r)return;let n=`client=${encodeURIComponent(e)}&slim=1`,o=0,s=()=>{r=al({wsPath:`/ws?${n}`,sseUrl:`/api/events?${n}`,handlers:{onOpen:()=>{o=0},onMessage:e=>{try{a(MT(t,JSON.parse(e)))}catch{}},onClose:()=>{r=null,!(i||o>=5)&&(o+=1,setTimeout(s,Math.min(500*2**o,8e3)))}}})};s()};return{id:e,get:()=>t,subscribe:e=>(n.add(e),e(t),()=>n.delete(e)),newChat:()=>{s(),o({type:`new_chat`,payload:{ephemeral:!0}})},send:(e,t,n)=>{let r=e.trim();r&&(s(),o({type:`send_message`,payload:{text:r,...t&&t.length>0?{attachments:t}:{},...n&&n!==`now`?{mode:n}:{}}}))},setModel:e=>o({type:`set_model`,payload:{modelId:e}}),setDraft:e=>a({...t,draft:e}),interrupt:e=>o({type:`interrupt`,payload:{conversationId:e}}),persist:e=>o({type:`persist_conversation`,payload:{conversationId:e}}),closeEphemeral:e=>o({type:`close_ephemeral`,payload:{conversationId:e}}),shutdown:()=>{let e=t.snapshot?.active.conversationId;e&&o({type:`close_ephemeral`,payload:{conversationId:e}}),i=!0,r?.close(),r=null,n.clear()},dispose:()=>{i=!0,r?.close(),r=null,n.clear()}}}var FT=new Map,IT=new Set;function LT(e){let t=FT.get(e);return t||(t=PT(),FT.set(e,t)),t}function RT(e){let t=FT.get(e);t&&(FT.delete(e),t.shutdown())}function zT(e){return IT.has(e)}function BT({itemId:e}){let t=Y(),n=LT(e),r=(0,C.useSyncExternalStore)(e=>n.subscribe(()=>e()),n.get,n.get);(0,C.useEffect)(()=>{n.get().snapshot===null&&n.newChat()},[n]);let i=r.snapshot,a=i?.active.conversationId??null,[o,s]=(0,C.useState)(!1),c=i?.conversations?.find(e=>e.id===a),l=a!==null&&(c?c.ephemeral===!0:!o),u=i?.engineCapabilities.ephemeralChat===!0,d=i?.active.messages??[],f=i!==null&&i.running.status!==`idle`&&i.running.conversationId===a,p=(0,C.useMemo)(()=>Object.fromEntries((i?.models??[]).map(e=>[e.id,e.label])),[i?.models]),m=(0,C.useMemo)(()=>({draft:r.draft??``,setDraft:n.setDraft,snapshot:i,send:(e,t,r)=>{n.send(e,t,r),n.setDraft(``)},interrupt:e=>n.interrupt(e),switchModel:e=>n.setModel(e),hostCommands:!1}),[r.draft,i,n]),h=ET(gr);return(0,Q.jsxs)(`div`,{className:`work-chat work-chat-main`,ref:h.ref,...h.pointerHandlers,style:{zoom:h.percent/100},children:[(0,Q.jsx)(Af,{notices:(i?.notices??[]).filter(e=>e.conversationId===a),activeConversationId:a}),(0,Q.jsx)(`div`,{className:`work-chat-stream`,children:d.length===0?(0,Q.jsx)(`div`,{className:`work-chat-empty`,children:t(`问一句就走:这条聊天不落盘,关掉即消失。`)}):(0,Q.jsx)(hv,{messages:d,hasMoreBefore:!1,modelLabels:p,workspaceRoot:i?.files?.root??null,running:f,activeTool:f?i?.running.activeTool??null:null})}),l?(0,Q.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,Q.jsx)(`span`,{className:`ephemeral-banner-text`,title:u?t(`消息只保存在内存里,不落盘、不进历史;关掉标签或重启服务后就没了。`,`Messages live in memory only: nothing is written to disk, nothing shows up in history, and it is gone once the tab closes or the server restarts.`):t(`这条聊天不写进本工作台的会话文件、也不进历史,关掉标签或重启服务后就没了。当前引擎没有「转正」能力,所以不提供保存(引擎自己的会话记录由它管理)。`,`This chat is never written to a workbench session file and never shows up in history; it is gone once the tab closes or the server restarts. The current engine cannot promote it to a saved session, so no save button is offered (the engine keeps its own record).`),children:u?t(`💬 临时会话:仅存内存,关掉即销毁。`,`💬 Temp session: in-memory only, gone on close.`):t(`💬 临时会话:不落盘,关掉即消失。`,`💬 Temp session: never saved, gone on close.`)}),u?(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>{a&&(n.persist(a),s(!0),Z({text:t(`已保存为正式对话`,`Saved as a regular chat`),actions:[]}))},title:t(`把这条聊天写成真正的会话文件(之后就能在历史里找到)`,`Write this chat to a real session file`),children:[`💾 `,t(`保存为正式对话`,`Save as a regular chat`)]}):null]}):null,(0,Q.jsx)(_m,{running:f,conversationId:a,surface:m,tempChat:!0})]})}var VT=/^([a-z][a-z0-9+.-]*):/i,HT=/^\d+(\/|$|\?|#)/;function UT(e){let t=e.trim();if(!t)return null;let n=VT.exec(t);if(n){let e=n[1].toLowerCase(),r=t.slice(n[0].length);if(r.startsWith(`//`)||!HT.test(r)){if(e!==`http`&&e!==`https`)return null;try{return new URL(t).toString()}catch{return null}}}let r=WT(t)?`http://`:`https://`;try{return new URL(`${r}${t}`).toString()}catch{return null}}function WT(e){return/^(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/i.test(e)}function GT(e){try{return new URL(e).host.replace(/^www\./i,``)||e}catch{return e}}function KT(e){let t=e.toLowerCase();return t===`127.0.0.1`?`localhost`:t===`localhost`||t===`::1`||t===`[::1]`?`127.0.0.1`:null}function qT(e,t,n={}){if(t.protocol!==`http:`)return null;let r=KT(t.hostname);if(r===null||XT(e)===null)return null;let i=t.port===``?``:`:${t.port}`,a=n.mobile===!0?`&m=1`:``;return`${t.protocol}//${r}${i}/web/w?u=${encodeURIComponent(e)}${a}`}var JT=`/web/p/`,YT=`/web/m/`;function XT(e,t={}){try{let n=new URL(e);return n.protocol!==`http:`&&n.protocol!==`https:`?null:`${t.mobile===!0?YT:JT}${n.protocol.slice(0,-1)}/${n.host}${n.pathname}${n.search}`}catch{return null}}function ZT(e){let t;try{t=new URL(e)}catch{return null}let n=t.pathname.startsWith(`/web/m/`)?YT:JT;if(!t.pathname.startsWith(n))return null;let r=t.pathname.slice(n.length),i=r.indexOf(`/`);if(i<0)return null;let a=r.slice(0,i).toLowerCase(),o=r.slice(i+1),s=o.indexOf(`/`),c=s<0?o:o.slice(0,s),l=s<0?`/`:o.slice(s);return a!==`http`&&a!==`https`||!c?null:`${a}://${c}${l}${t.search}${t.hash}`}var QT=[{id:`se`,label:`iPhone SE 375×667`,width:375,height:667},{id:`iphone14`,label:`iPhone 14 390×844`,width:390,height:844},{id:`promax`,label:`iPhone 15 Pro Max 430×932`,width:430,height:932},{id:`android`,label:`Android 360×800`,width:360,height:800},{id:`tablet`,label:`平板 768×1024`,width:768,height:1024}];function $T(e){return QT.find(t=>t.id===e)??QT.find(e=>e.id===`iphone14`)??QT[0]}function eE(e,t,n=12){if(e.width<=0||e.height<=0)return 1;let r=Math.min((e.width-n*2)/t.width,(e.height-n*2)/t.height,1);return Number.isFinite(r)?Math.max(.25,Math.round(r*100)/100):1}var tE=[`http://localhost:3000`,`https://www.baidu.com`,`https://developer.mozilla.org`],nE=`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals`,rE=`${nE} allow-same-origin`;function iE(e){return ZT(e)??e}function aE(){try{return window.localStorage}catch{return null}}function oE({initialUrl:e=``,onAddNote:t}){let n=Y(),[r,i]=(0,C.useState)(e?[e]:[]),[a,o]=(0,C.useState)(e?0:-1),[s,c]=(0,C.useState)(e),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(0),p=(0,C.useRef)(null),m=ET(_r),[h,g]=uf(vr,!1),[_,v]=(0,C.useState)(()=>Yr(yr)),y=(0,C.useMemo)(()=>$T(_),[_]),[b,x]=(0,C.useState)(!1),S=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!b)return;let e=e=>{S.current?.contains(e.target)||x(!1)},t=e=>{e.key===`Escape`&&x(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[b]);let w=(0,C.useRef)(null),[T,E]=(0,C.useState)({width:0,height:0});(0,C.useEffect)(()=>{let e=w.current;if(e===null)return;let t=()=>E({width:e.clientWidth,height:e.clientHeight});t();let n=new ResizeObserver(t);return n.observe(e,{box:`content-box`}),()=>n.disconnect()},[]);let D=h?eE(T,y):1,O=a>=0?r[a]:``,k=(0,C.useMemo)(()=>O?qT(O,{protocol:window.location.protocol,hostname:window.location.hostname,port:window.location.port},{mobile:h}):null,[O,h]),A=k??XT(O,{mobile:h})??O,j=k===null?nE:rE,M=t!==void 0,N=(0,C.useRef)(t);(0,C.useEffect)(()=>{N.current=t},[t]);let[P,F]=(0,C.useState)(!1),[I,L]=(0,C.useState)(()=>(cd(aE(),[]),[])),R=(0,C.useRef)(I);(0,C.useEffect)(()=>{R.current=I},[I]),(0,C.useEffect)(()=>sd(()=>{let e=ad(aE());R.current=e,L(e)}),[]);let z=(0,C.useMemo)(()=>ud(I,iE(O)),[I,O]),B=(0,C.useCallback)(e=>{p.current?.contentWindow?.postMessage({__aw:`picker`,...e},`*`)},[]),V=(0,C.useCallback)(e=>{let t=iE(e.url),n=fd(R.current,{url:t,selector:e.selector,comment:e.comment}),r=n.find(n=>n.url===t&&n.selector===e.selector);R.current=n,L(n),cd(aE(),n),N.current?.({...e,url:t,number:r?.number??1})},[]),H=()=>{let e=md(R.current,iE(O));R.current=e,L(e),cd(aE(),e)},U=(0,C.useCallback)(()=>{B({type:`marks`,list:z.map(e=>({selector:e.selector,number:e.number,comment:e.comment}))})},[z,B]);(0,C.useEffect)(U,[U]),(0,C.useEffect)(()=>{F(!1)},[O,d]),(0,C.useEffect)(()=>{if(!P)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),B({type:`off`}),F(!1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[P,B]),(0,C.useEffect)(()=>{let e=e=>{let t=p.current;if(t===null||e.source!==t.contentWindow)return;let n=Mu(e.data);n!==null&&(n.kind===`ready`?(U(),F(e=>(e&&B({type:`on`}),e))):n.kind!==`blank`&&(n.kind===`exit`?F(!1):n.kind===`note`?V(n.note):V({...n.pick,comment:``})))};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[U,V,B]);let W=e=>{let t=UT(e);t?(u(null),c(t),i(e=>[...e.slice(0,a+1),t]),o(e=>e+1)):u(n(`这不像是个网址(只支持 http / https)`,`That does not look like a URL (http / https only)`))},ee=()=>{P?(B({type:`off`}),F(!1)):(B({type:`on`}),F(!0))};return(0,Q.jsxs)(`div`,{className:`work-web`,ref:m.ref,...m.pointerHandlers,children:[(0,Q.jsxs)(`div`,{className:`work-web-bar`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>Math.max(0,e-1)),disabled:a<=0,title:n(`后退`,`Back`),children:`←`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>Math.min(r.length-1,e+1)),disabled:a>=r.length-1,title:n(`前进`,`Forward`),children:`→`}),M?(0,Q.jsxs)(`button`,{type:`button`,className:`btn btn-tiny work-web-pick${P?` work-web-pick-on`:``}`,onClick:ee,disabled:!O,"aria-pressed":P,title:P?n(`退出标注`,`Stop annotating`):n(`标注网页:点页面上要改的那一处,收进输入框那颗「N 条注释」`,`Annotate the page: click the spot to change; it joins the notes in the input`),children:[`📍`,z.length>0?` ${z.length}`:``]}):null,(0,Q.jsxs)(`div`,{className:`work-web-phone-wrap`,ref:S,children:[(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny work-web-phone-btn${h?` work-web-phone-on`:``}`,onClick:()=>x(e=>!e),"aria-pressed":h,"aria-haspopup":`menu`,"aria-expanded":b,title:h?n(`手机预览:${y.label}(点开换机型或关闭)`,`Phone preview: ${y.label} (open to change or turn off)`):n(`手机尺寸预览:点开选机型`,`Phone-size preview: open to pick a device`),children:`📱`}),b?(0,Q.jsxs)(`div`,{className:`work-web-phone-menu`,role:`menu`,children:[(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`work-web-phone-item${h?``:` work-web-phone-item-on`}`,onClick:()=>{g(!1),x(!1)},children:n(`关闭手机预览`,`Turn off the phone preview`)}),QT.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`work-web-phone-item${h&&e.id===y.id?` work-web-phone-item-on`:``}`,onClick:()=>{v(e.id),Xr(yr,e.id),g(!0),x(!1)},children:e.label},e.id))]}):null]}),M&&O&&z.length>0?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:H,title:n(`清空这一页的 ${z.length} 处标记`,`Clear the ${z.length} mark(s) on this page`),"aria-label":n(`清空这一页的标记`,`Clear the marks on this page`),children:`⌫`}):null,(0,Q.jsx)(`input`,{className:`work-web-input`,value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&W(s)},placeholder:n(`输入网址后回车(例:localhost:3000)`,`Type a URL and press Enter (e.g. localhost:3000)`),spellCheck:!1}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>{M&&O&&z.length>0&&H(),f(e=>e+1)},disabled:!O,title:n(`刷新(同时清空这一页的标记)`,`Reload (also clears the marks on this page)`),children:`↻`}),O?(0,Q.jsx)(`a`,{className:`btn btn-tiny`,href:O,target:`_blank`,rel:`noopener noreferrer`,title:n(`在系统浏览器打开`),children:`⧉`}):null]}),l?(0,Q.jsx)(`div`,{className:`work-web-note work-web-note-error`,children:l}):null,P?(0,Q.jsx)(`div`,{className:`work-web-note work-web-pick-hint`,children:n(`点页面上要改的那一处,就地写一句;可以接着标多处(Esc 退出)`,`Click the spot to change and type right there; keep going for more (Esc to stop)`)}):null,O?(0,Q.jsx)(`div`,{className:`work-web-stage${h?` work-web-stage-phone`:``}`,ref:w,children:(0,Q.jsx)(`div`,{className:`work-web-body${h?` work-web-body-phone`:``}`,style:h?{width:`${y.width}px`,height:`${y.height}px`,zoom:D*m.percent/100}:{zoom:m.percent/100},children:(0,Q.jsx)(`iframe`,{ref:p,className:`work-web-frame`,src:A,title:O,sandbox:j,referrerPolicy:`no-referrer`},`${O}#${d}#${h?`m`:`d`}`)})}):(0,Q.jsxs)(`div`,{className:`work-web-start`,children:[(0,Q.jsx)(`p`,{className:`side-panel-hint`,children:n(`输入网址就能在这儿打开(经本机代理,拒绝被嵌入的站点也能显示)`,`Enter a URL to open it here (served through the local proxy, so sites that refuse embedding still work)`)}),(0,Q.jsx)(`p`,{className:`side-panel-hint work-web-caveat`,children:n(`代理不带 cookie、跑在隔离沙箱里:要重登录的站点(GitHub、后台系统)可能是一片空白;面板里跑不起来的页面会提示你『在新窗口打开』。`,`The proxy carries no cookies and runs in an isolated sandbox: sites that need a session (GitHub, admin consoles) may stay blank, and pages that cannot run in a panel will offer “Open in a window”.`)}),(0,Q.jsx)(`div`,{className:`work-web-suggestions`,children:tE.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`tpl-card`,onClick:()=>W(e),children:(0,Q.jsx)(`span`,{className:`tpl-card-title`,children:e.replace(/^https?:\/\//,``)})},e))})]})]})}function sE({point:e,isDir:t,onReveal:n,onTerminal:r,onAddToConversation:i,onChanges:a,changesOnly:o=!1,onFind:s,onClose:c}){let l=Y(),u=e=>()=>{e(),c()};return(0,Q.jsxs)(qd,{point:e,pointerTail:!0,className:`proj-menu ctx-menu`,onClose:c,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(n),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`📂`}),l(`打开`,`Open`)]}),t&&r?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(r),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`⌨️`}),l(`在集成终端中打开`,`Open in integrated terminal`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(i),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`💬`}),l(`添加到对话`,`Add to conversation`)]}),a?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(a),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:o?`📄`:`📝`}),o?l(`所有文件`,`All files`):l(`改动过的文件`,`Changed files`)]}):null,s?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`proj-menu-sep`,"aria-hidden":`true`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:u(s),children:[(0,Q.jsx)(`span`,{className:`proj-menu-ico`,"aria-hidden":`true`,children:`🔍`}),t?l(`在文件夹中查找…`,`Find in folder…`):l(`在所在文件夹中查找…`,`Find in its folder…`)]})]}):null]})}var cE={modified:`M`,added:`A`,deleted:`D`,untracked:`U`,renamed:`R`,conflicted:`!`},lE=[`conflicted`,`deleted`,`modified`,`renamed`,`added`,`untracked`];function uE(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=n.split(`/`);for(let n=e.length-1;n>=1;--n){let i=e.slice(0,n).join(`/`),a=t.get(i);(a===void 0||lE.indexOf(r.status)<lE.indexOf(a))&&t.set(i,r.status)}}return t}function dE(e,t,n){let[r,i]=(0,C.useState)({isRepo:!1,entries:{}}),[a,o]=(0,C.useState)(0),[s,c]=(0,C.useState)(n);return s!==n&&(c(n),s&&o(e=>e+1)),(0,C.useEffect)(()=>{if(!e){i({isRepo:!1,entries:{}});return}let t=!1;return(async()=>{try{let n=await fetch(`/api/files/git/status?root=${encodeURIComponent(e)}`);if(t)return;if(!n.ok){console.warn(`[git status] ${n.status} — 服务端可能还在跑旧版本,重启一次即可`),i({isRepo:!1,entries:{}});return}i(await n.json())}catch{t||i({isRepo:!1,entries:{}})}})(),()=>{t=!0}},[e,t,a]),r}async function fE(e,t,n=!1){try{let r=await fetch(`/api/files/list?path=${encodeURIComponent(e)}${t?`&root=${encodeURIComponent(t)}`:``}${n?`&hidden=1`:``}`),i=await r.json();return r.ok?{entries:i.entries??[]}:{error:i.error?.message??`HTTP ${r.status}`}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}function pE({root:e,showHidden:t=!1,statusRevision:n=``,running:r=!1,activePath:i=null,revealSeq:a=0,revealPath:o=null,onNeedHidden:s,onOpenFile:c,onOpenTerminalAt:l,onFindInFolder:u,changesOnly:d=!1,onToggleChangesOnly:f,onOpenChangedFile:p}){let m=Y(),[h,g]=(0,C.useState)(null),_=t=>e?`${e.replace(/[\\/]+$/,``)}/${t}`:t,v=e=>{fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:_(e)})})},y=dE(e,n,r),b=(0,C.useMemo)(()=>uE(y.entries),[y.entries]),[x,S]=(0,C.useState)([]),[w,T]=(0,C.useState)(null),E=(0,C.useRef)([]),k=e=>{let t=e(E.current);E.current=t,S(t)},A=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(k(()=>[]),T(null),!e)return;let n=!1;return fE(``,e,t).then(({entries:e,error:t})=>{n||(t?T(t):k(()=>(e??[]).map(e=>({entry:e,depth:0,expanded:!1,loading:!1,children:null,error:null}))))}),()=>{n=!0}},[e,t]);let j=async n=>{let r=E.current.find(e=>e.entry.path===n);if(!r||r.expanded&&r.children!==null)return;k(e=>e.map(e=>e.entry.path===n?{...e,expanded:!0,loading:!0}:e));let{entries:i,error:a}=await fE(n,e,t);k(e=>{let t=e.findIndex(e=>e.entry.path===n&&e.expanded),r=t<0?void 0:e[t];if(!r)return e;let o=e.slice(0,t+1).map((e,n)=>n===t?{...e,loading:!1,children:i??null,error:a??null}:e);if(a||!i)return[...o,...e.slice(t+1)];let s=i.map(e=>({entry:e,depth:r.depth+1,expanded:!1,loading:!1,children:null,error:null}));return[...o,...s,...e.slice(t+1)]})},M=async e=>{let t=E.current.find(t=>t.entry.path===e);t&&(t.expanded?k(t=>{let n=t.findIndex(t=>t.entry.path===e);return n<0?t:yd(t,n)}):await j(e))},[N,P]=(0,C.useState)(null),F=(0,C.useRef)(-1);(0,C.useEffect)(()=>{if(F.current===a)return;F.current=a;let e=o??i;a!==0&&e&&P(e)},[a,o,i]);let I=x.length>0;return(0,C.useEffect)(()=>{if(N===null||!I)return;let e=!1;return(async()=>{for(let n of bd(N)){let r=E.current.find(e=>e.entry.path===n);if(!r){!t&&Sd(N)!==null&&s?.();return}if(r.expanded||await j(n),e)return}let n=E.current.find(e=>e.entry.path===N);n?.entry.isDir&&!n.expanded&&await j(N),!e&&(P(null),requestAnimationFrame(()=>{(A.current?.querySelector(`[data-path="${CSS.escape(N)}"]`))?.scrollIntoView({block:`nearest`})}))})(),()=>{e=!0}},[N,I]),e?(0,Q.jsxs)(`div`,{className:`filetree`,ref:A,children:[w?(0,Q.jsx)(`div`,{className:`filetree-error`,children:w}):null,d?(()=>{let e=Object.keys(y.entries).sort((e,t)=>e.localeCompare(t));return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`filetree-changes-head`,children:[(0,Q.jsxs)(`span`,{className:`filetree-changes-title`,children:[m(`改动过的文件`,`Changed files`),` · `,e.length]}),f?(0,Q.jsx)(`button`,{type:`button`,className:`filetree-changes-exit`,onClick:f,title:m(`回到普通的文件树`,`Back to the file tree`),children:m(`所有文件`,`All files`)}):null]}),y.isRepo?e.length===0?(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`没有改动过的文件。`,`No changed files.`)}):e.map(e=>{let t=y.entries[e],n=D(e),r=zp(n);return(0,Q.jsx)(`div`,{className:`filetree-item`,children:(0,Q.jsxs)(`button`,{type:`button`,"data-path":e,className:`filetree-row filetree-file filetree-${t.status}${e===i?` filetree-row-on`:``}`,style:{paddingLeft:8},title:e,onClick:()=>(p??c)(e),onContextMenu:t=>{t.preventDefault(),g({entry:{name:n,path:e,isDir:!1},point:{x:t.clientX,y:t.clientY}})},children:[(0,Q.jsx)(`span`,{className:`filetree-icon`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`filetree-type${r?` filetype-${r.tone}`:``}`,"aria-hidden":`true`,children:r?r.label:`▤`}),(0,Q.jsx)(`span`,{className:`filetree-name`,children:n}),O(e)?(0,Q.jsx)(`span`,{className:`filetree-changes-dir`,children:O(e)}):null,(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${t.status}`,"aria-hidden":`true`,children:cE[t.status]})]})},e)}):(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`这个目录不是 git 仓库。`,`Not a git repository.`)})]})})():x.map((e,t)=>{let n=y.entries[e.entry.path],r=b.get(e.entry.path),a=e.entry.isDir?r:n?.status,o=e.entry.isDir?null:zp(e.entry.name),s=e.entry.isDir?e.entry.path:n?`${e.entry.path}\n${cE[n.status]}${n.added||n.removed?` · +${n.added} −${n.removed}`:``}`:e.entry.path;return(0,Q.jsxs)(`div`,{className:`filetree-item`,children:[(0,Q.jsxs)(`button`,{type:`button`,"data-path":e.entry.path,className:`filetree-row filetree-${e.entry.isDir?`dir`:`file`}${a?` filetree-${a}`:``}${!e.entry.isDir&&e.entry.path===i?` filetree-row-on`:``}`,style:{paddingLeft:8+e.depth*14},onClick:()=>e.entry.isDir?void M(e.entry.path):c(e.entry.path),title:s,onContextMenu:t=>{t.preventDefault(),g({entry:e.entry,point:{x:t.clientX,y:t.clientY}})},children:[(0,Q.jsx)(`span`,{className:`filetree-icon`,"aria-hidden":`true`,children:e.entry.isDir?e.expanded?`▾`:`▸`:null}),e.entry.isDir?(0,Q.jsx)(ap,{open:e.expanded,className:`filetree-folder${e.expanded?` filetree-folder-open`:``}`}):(0,Q.jsx)(`span`,{className:`filetree-type${o?` filetype-${o.tone}`:``}`,"aria-hidden":`true`,children:o?o.label:`▤`}),(0,Q.jsx)(`span`,{className:`filetree-name`,children:e.entry.name}),e.loading?(0,Q.jsx)(`span`,{className:`filetree-hint`,children:`…`}):null,e.entry.isDir?a?(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${a} filetree-status-dot`,"aria-hidden":`true`}):null:a?(0,Q.jsx)(`span`,{className:`filetree-status filetree-status-${a}`,"aria-hidden":`true`,children:cE[a]}):null]}),e.entry.isDir?null:(0,Q.jsxs)(`button`,{type:`button`,className:`filetree-mention`,title:m(`把 @${e.entry.path} 加到对话`,`Add @${e.entry.path} to the conversation`),onClick:()=>So(`${Uw(e.entry.path,null)} `),children:[`@ `,m(`提及`,`mention`)]}),e.error?(0,Q.jsx)(`div`,{className:`filetree-error`,children:e.error}):null]},e.entry.path||t)}),h?(0,Q.jsx)(sE,{point:h.point,isDir:h.entry.isDir,onReveal:()=>v(h.entry.path),onTerminal:l&&h.entry.isDir?()=>l(_(h.entry.path)):void 0,onAddToConversation:()=>So(`${Uw(h.entry.path,null)} `),onFind:u?()=>u(h.entry.isDir?h.entry.path:O(h.entry.path)):void 0,changesOnly:d,onChanges:f&&(d||y.isRepo&&Object.keys(y.entries).length>0)?f:void 0,onClose:()=>g(null)}):null]}):(0,Q.jsx)(`div`,{className:`filetree-empty`,children:m(`还没有打开会话,不知道是哪个项目。`)})}function mE({text:e,keys:t,children:n}){return(0,Q.jsx)(`span`,{className:`files-tool-tip`,"data-tip":e,...t?{"data-key":t}:{},children:n})}function hE(){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`4.5`,cy:`3.6`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`circle`,{cx:`4.5`,cy:`12.4`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`circle`,{cx:`11.5`,cy:`6.2`,r:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`}),(0,Q.jsx)(`path`,{d:`M4.5 5.3v5.4M11.5 7.9c0 2-2.4 2-4.4 2.4`,stroke:`currentColor`,strokeWidth:`1.2`,fill:`none`,strokeLinecap:`round`})]})}function gE({git:e}){let t=Y(),[n,r]=(0,C.useState)(!1),[i,a]=(0,C.useState)(null);if(!e.isRepo)return null;let o=e.branch??`detached`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,ref:a,className:`files-branch${n?` files-branch-open`:``}`,title:t(`当前 git 分支:${o}(点开切换)`,`Current git branch: ${o} (click to switch)`),"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>{n||e.refresh(),r(e=>!e)},children:[(0,Q.jsx)(hE,{}),(0,Q.jsx)(`span`,{className:`files-branch-name`,children:o})]}),n&&i?(0,Q.jsx)(sp,{anchor:i,git:e,onClose:()=>r(!1)}):null]})}function _E({root:e,showHidden:t,onToggleHidden:n,onOpenTerminal:r,onReveal:i,onRefresh:a,onSearchContents:o,search:s,changesOnly:c=!1,changedCount:l=0,onShowChanges:u}){let d=Y(),[f]=xc(),p=cc(f.contentSearch,oc()),m=p?{zh:`搜索文件内容(${p})`,en:`Search file contents (${p})`}:{zh:`搜索文件内容`,en:`Search file contents`};return(0,Q.jsxs)(`div`,{className:`files-toolbar`,children:[(0,Q.jsx)(mE,{text:d(`刷新文件列表`,`Refresh the file list`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool`,"aria-label":d(`刷新文件列表`,`Refresh the file list`),onClick:a,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M12.9 8a5.2 5.2 0 1 1-5.2-5.2c1.46 0 2.85.58 3.89 1.59L12.9 5.3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`M12.9 2.1v3.2h-3.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`,strokeLinejoin:`round`})]})})}),(0,Q.jsx)(mE,{text:t?d(`隐藏点开头的文件`,`Hide dot-prefixed files`):d(`显示隐藏文件(.env 等)`,`Show hidden files (.env etc.)`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool${t?` files-tool-on`:``}`,"aria-label":d(`显示 / 隐藏以点开头的文件`,`Show / hide dot-prefixed files`),"aria-pressed":t,onClick:n,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M1.6 8s2.3-4 6.4-4 6.4 4 6.4 4-2.3 4-6.4 4S1.6 8 1.6 8Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinejoin:`round`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`8`,r:`1.9`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`})]})})}),(0,Q.jsx)(mE,{text:d(`按文件名搜索`,`Search by file name`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool${s.active?` files-tool-on`:``}`,"aria-label":d(`按文件名搜索`,`Search by file name`),"aria-pressed":s.active,onClick:s.toggle,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`path`,{d:`m10.2 10.2 3.2 3.2`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`})]})})}),(0,Q.jsx)(mE,{text:d(`搜索文件内容`,`Search file contents`),keys:p||void 0,children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool`,"aria-label":d(m.zh,m.en),onClick:o,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2.4 3.2h8.2M2.4 6.1h8.2M2.4 9h4.6`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.25`,strokeLinecap:`round`}),(0,Q.jsx)(`circle`,{cx:`10.3`,cy:`10.1`,r:`2.5`,fill:`var(--bg-elev)`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`path`,{d:`m12.2 12 2 2`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinecap:`round`})]})})}),u&&l>0?(0,Q.jsx)(mE,{text:d(`改动过的文件(${l} 个):点一下看最新的改动`,`Changed files (${l}): click to list the latest`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-diff${c?` files-tool-on`:``}`,"aria-label":d(`查看改动过的文件`,`Show changed files`),"aria-pressed":c,onClick:u,disabled:!e,children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`1.7`,y:`2.7`,width:`12.6`,height:`10.6`,rx:`1.7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.15`}),(0,Q.jsx)(`path`,{d:`M8 3v10`,stroke:`currentColor`,strokeWidth:`1`,opacity:`0.45`}),(0,Q.jsx)(`path`,{d:`M3.4 6.1h3.1M3.4 9.3h2.2`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`M9.5 6.1h2.9M10.95 4.65v2.9M9.5 9.3h2.9`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})]})})}):null,(0,Q.jsx)(mE,{text:d(`在底部终端中打开`,`Open in the bottom terminal`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-terminal`,"aria-label":d(`在底部终端中打开`,`Open in the bottom terminal`),onClick:r,children:`>_`})}),(0,Q.jsx)(mE,{text:d(`在 Finder 中显示这个目录`,`Reveal this folder in Finder`),children:(0,Q.jsx)(`button`,{type:`button`,className:`files-tool files-tool-reveal`,"aria-label":d(`在 Finder 中显示这个目录`,`Reveal this folder in Finder`),onClick:i,disabled:!e,children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M1.8 4.3c0-.6.5-1.1 1.1-1.1h2.7l1.3 1.5h5.2c.6 0 1.1.5 1.1 1.1v5.5c0 .6-.5 1.1-1.1 1.1H2.9c-.6 0-1.1-.5-1.1-1.1V4.3Z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinejoin:`round`})})})})]})}function vE({search:e,placeholder:t}){let n=Y();return(0,Q.jsx)(`input`,{ref:e.inputRef,className:`files-search`,value:e.query,placeholder:t??n(`搜索文件名…`),onChange:t=>e.setQuery(t.target.value),onKeyDown:t=>{t.key===`Escape`&&e.close()}})}function yE({entries:e,truncated:t,onPick:n}){let r=Y(),i=e.slice(0,60);return e.length===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:r(`没有匹配的文件名`)}):(0,Q.jsxs)(`div`,{className:`files-search-list`,children:[i.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`files-search-row`,title:e.path,onClick:()=>n(e),children:[(0,Q.jsx)(`span`,{className:`files-search-name`,children:e.name}),(0,Q.jsx)(`span`,{className:`files-search-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)})]},e.path)),t?(0,Q.jsx)(`div`,{className:`files-search-more`,children:r(`结果太多,只显示前 200 个`)}):null]})}function bE({value:e,options:t,onChange:n}){let r=Y(),[i,a]=(0,C.useState)(null),[o,s]=(0,C.useState)(!1),c=t.find(t=>t.cwd===e)?.label??(e===``?r(`跟随当前会话`,`Follow the current session`):D(e)||e),l=e=>{n(e),s(!1)};return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`button`,{type:`button`,ref:a,className:`side-files-root${o?` side-files-root-open`:``}`,title:e===``?r(`文件树跟着当前会话走(点一下可换项目)`,`The tree follows the current session (click to pick another project)`):r(`文件树根目录:${e}`,`Tree root: ${e}`),"aria-haspopup":`listbox`,"aria-expanded":o,onClick:()=>s(e=>!e),children:[(0,Q.jsx)(`span`,{className:`side-files-root-label`,children:c}),(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,className:`side-files-root-caret`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`m4.4 6.4 3.6 3.6 3.6-3.6`})})]}),o&&i?(0,Q.jsxs)(qd,{anchor:i,className:`proj-menu files-root-menu`,style:{width:Math.min(320,Math.max(200,i.getBoundingClientRect().width))},onClose:()=>s(!1),children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${e===``?` files-root-option-on`:``}`,onClick:()=>l(null),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:e===``?`✓`:``}),r(`跟随当前会话`,`Follow the current session`)]}),t.length>0?(0,Q.jsx)(`div`,{className:`files-root-sep`}):null,t.map(t=>(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item files-root-option${e===t.cwd?` files-root-option-on`:``}`,title:t.cwd,onClick:()=>l(t.cwd),children:[(0,Q.jsx)(`span`,{className:`files-root-check`,"aria-hidden":`true`,children:e===t.cwd?`✓`:``}),(0,Q.jsx)(`span`,{className:`files-root-option-label`,children:t.label})]},t.cwd))]}):null]})}var xE=[];function SE(e,t){let[n,r]=(0,C.useState)(!1),i=t?.always===!0,[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)(xE),[l,u]=(0,C.useState)(!1),d=(0,C.useRef)(null);(0,C.useEffect)(()=>{if(!(i||n)||!e)return;let t=a.trim();if(t===``){c(xE),u(!1);return}let r=!1,o=setTimeout(()=>{(async()=>{try{let n=await(await fetch(`/api/files/search?q=${encodeURIComponent(t)}&root=${encodeURIComponent(e)}`)).json();if(r)return;c(n.entries??xE),u(n.truncated===!0)}catch{if(r)return;c(xE)}})()},250);return()=>{r=!0,clearTimeout(o)}},[n,a,e]),(0,C.useEffect)(()=>{e||c(xE)},[e]),(0,C.useEffect)(()=>{n&&d.current?.focus()},[n]);let f=(0,C.useCallback)(()=>{r(!1),o(``),c(xE),u(!1)},[]);return{active:n,query:a,results:s,truncated:l,inputRef:d,setQuery:o,toggle:(0,C.useCallback)(()=>{r(e=>!e),o(``),c(xE),u(!1)},[]),close:f}}function CE({variant:e=`sidebar`,open:t,onToggle:n,height:r,fill:i=!1,root:a,onRootChange:o,options:s,onOpenFile:c,onOpenChangedFile:l,onOpenTerminal:u,onOpenBottomTerminal:d,onFindInFolder:f,onReveal:p,onSearchContents:m,activePath:h,revealSeq:g,revealPath:_,onRevealPath:v}){let y=Y(),[b,x]=(0,C.useState)(!1),[S,w]=(0,C.useState)(!1),[T,E]=(0,C.useState)(0),D=SE(a),O=ep(a),k=Ro(e=>e.snapshot),A=k!==null&&k.running.status!==`idle`&&k.running.conversationId===k.active.conversationId,{active:j,close:M}=D;(0,C.useEffect)(()=>{!t&&j&&M()},[t,j,M]);let N=j&&D.query.trim()!==``,P=dE(a,`${O.branch??``}:${T}`,A),F=Object.keys(P.entries).length,I=()=>{t||n(),w(!0),E(e=>e+1),O.refresh()};(0,C.useEffect)(()=>{S&&P.isRepo&&F===0&&w(!1)},[S,P.isRepo,F]);let L=e===`panel`;return(0,Q.jsxs)(`section`,{className:`side-files${t?``:` side-files-closed`}${i&&t?` side-files-fill`:``}${L?` side-files-panel`:``}`,style:{height:t&&!i&&!L?r:void 0},children:[(0,Q.jsxs)(`div`,{className:`side-files-head`,children:[L?null:(0,Q.jsxs)(`button`,{type:`button`,className:`side-files-title`,onClick:n,title:t?y(`收起文件`,`Collapse files`):y(`展开文件`,`Expand files`),"aria-expanded":t,children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${t?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:y(`文件`,`Files`)})]}),(0,Q.jsx)(_E,{root:a,showHidden:b,onToggleHidden:()=>x(e=>!e),onOpenTerminal:u,onReveal:()=>a&&p?.(a),onRefresh:()=>{E(e=>e+1),O.refresh()},onSearchContents:()=>m?.(),search:D,changesOnly:S,changedCount:F,onShowChanges:I}),L?null:(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-row-fill`,"aria-hidden":`true`,tabIndex:-1,onClick:n})]}),t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`side-files-select-row`,children:[(0,Q.jsx)(bE,{value:a??``,options:s,onChange:o}),(0,Q.jsx)(gE,{git:O})]}),j?(0,Q.jsx)(vE,{search:D}):null,(0,Q.jsx)(`div`,{className:`side-files-body`,children:N?(0,Q.jsx)(yE,{entries:D.results,truncated:D.truncated,onPick:e=>{e.isDir?v?.(e.path):c(e.path),D.setQuery(``)}}):(0,Q.jsx)(pE,{root:a,showHidden:b,statusRevision:`${O.branch??``}:${T}`,running:A,activePath:h??null,revealSeq:g??0,revealPath:_??null,onNeedHidden:()=>x(!0),onOpenTerminalAt:d,onFindInFolder:f,changesOnly:S,onToggleChangesOnly:()=>w(e=>!e),onOpenFile:c,onOpenChangedFile:l},`${a??``}:${O.branch??``}:${T}`)})]}):null]})}function wE(e){return(0,Q.jsx)(CE,{variant:`panel`,open:!0,height:0,onToggle:()=>{},...e})}function TE({root:e,activePath:t,onOpenFile:n,width:r,revealSeq:i=0}){let a=Y(),o=SE(e,{always:!0}),[s,c]=(0,C.useState)(!1),[l,u]=(0,C.useState)(0),d=o.query.trim()!==``,f=e?D(e):a(`文件`,`Files`);return(0,Q.jsxs)(`aside`,{className:`preview-files`,"aria-label":a(`文件列表`,`File list`),style:r?{width:r}:void 0,children:[(0,Q.jsxs)(`div`,{className:`preview-files-head`,children:[(0,Q.jsxs)(`span`,{className:`preview-files-title`,children:[(0,Q.jsx)(`span`,{className:`preview-files-label`,children:a(`文件列表`,`Files`)}),e?(0,Q.jsx)(`span`,{className:`preview-files-root`,title:e,children:` · ${f}`}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny${s?` btn-wide-on`:``}`,onClick:()=>c(e=>!e),title:a(`显示隐藏文件`,`Show hidden files`),children:`👁`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>u(e=>e+1),title:a(`刷新(重新拉一次改动状态)`,`Refresh (re-read the changes)`),children:`↻`})]}),(0,Q.jsx)(vE,{search:o,placeholder:a(`筛选文件…`,`Filter files…`)}),(0,Q.jsx)(`div`,{className:`preview-files-body`,children:d?(0,Q.jsx)(yE,{entries:o.results,truncated:o.truncated,onPick:e=>{e.isDir||n(e.path)}}):(0,Q.jsx)(pE,{root:e,showHidden:s,statusRevision:String(l),activePath:t,revealSeq:i,onNeedHidden:()=>c(!0),onOpenFile:n})})]})}function EE({conversationId:e}){let t=Y();return e?(0,Q.jsx)(`div`,{className:`session-history`,children:(0,Q.jsx)(`iframe`,{className:`session-history-frame`,title:t(`完整历史`,`Full history`),src:`/api/sessions/${encodeURIComponent(e)}/history`},e)}):(0,Q.jsx)(`div`,{className:`session-view-empty`,children:t(`先打开一条会话。`,`Open a session first.`)})}function DE({conversationId:e,active:t=!0}){let n=Y(),[r,i]=(0,C.useState)({status:`loading`}),[a,o]=(0,C.useState)(0);if((0,C.useEffect)(()=>{if(!e){i({status:`error`,message:n(`先打开一条会话。`,`Open a session first.`)});return}if(!t)return;let r=!1;return i({status:`loading`}),fetch(`/api/sessions/${encodeURIComponent(e)}/system-prompt`).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok){let n=typeof t?.error?.message==`string`?t.error.message:`HTTP ${e.status}`;throw Error(n)}return typeof t?.prompt==`string`?t.prompt:``}).then(e=>{r||i({status:`ready`,prompt:e})}).catch(e=>{r||i({status:`error`,message:e instanceof Error?e.message:String(e)})}),()=>{r=!0}},[e,a,t,n]),r.status===`loading`)return(0,Q.jsx)(`div`,{className:`session-view-empty`,children:n(`正在读取系统提示词…`,`Reading the system prompt…`)});if(r.status===`error`)return(0,Q.jsxs)(`div`,{className:`session-view-empty session-view-error`,children:[(0,Q.jsx)(`div`,{children:r.message}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,onClick:()=>o(e=>e+1),children:n(`重读`,`Retry`)})]});let s=r.prompt,c=s===``?0:s.split(`
76
+ `).length;return(0,Q.jsxs)(`div`,{className:`session-prompt`,children:[(0,Q.jsxs)(`div`,{className:`session-prompt-head`,children:[(0,Q.jsx)(`span`,{className:`session-prompt-meta`,children:c>0?n(`${c} 行 · ${s.length.toLocaleString()} 字符`,`${c} lines · ${s.length.toLocaleString()} chars`):n(`这段是空的`,`This is empty`)}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny`,title:n(`重新读取`,`Read again`),onClick:()=>o(e=>e+1),children:`↻`}),(0,Q.jsx)(ah,{text:s,className:`btn btn-tiny`,title:`复制系统提示词`})]}),(0,Q.jsx)(`pre`,{className:`session-prompt-body`,children:s})]})}var OE=.2,kE=2.5,AE=5,jE=6,ME=240,NE=`pop-agent.canvas.style.v1`,PE={task:{icon:`•`,zh:`待办项`,en:`Task`},milestone:{icon:`▲`,zh:`里程碑`,en:`Milestone`},risk:{icon:`!`,zh:`风险`,en:`Risk`},doc:{icon:`▤`,zh:`参考`,en:`Doc`},decision:{icon:`◆`,zh:`决策`,en:`Decision`}};function FE(e){return e.kind&&PE[e.kind]?e.kind:`task`}function IE(e,t){let n=new Map;for(let t of e)n.set(t.id,[]);for(let e of t)n.get(e.to)?.push(e.from);let r=new Map,i=new Set,a=e=>{let t=r.get(e);if(t!==void 0)return t;if(i.has(e))return 0;i.add(e);let o=0;for(let t of n.get(e)??[])o=Math.max(o,a(t)+1);return i.delete(e),r.set(e,o),o},o=new Map;for(let t of e)o.set(t.id,a(t.id));return o}function LE(e,t,n){let r=new Map;if(e.length===0)return r;let i=new Map;for(let t of e)i.set(t.id,0);let a=new Map;for(let e of t){i.set(e.to,(i.get(e.to)??0)+1);let t=a.get(e.from)??[];t.push(e.to),a.set(e.from,t)}let o=new Set,s=64,c=(e,t,i)=>{if(o.has(e))return r.get(e)?.y??s;if(i.has(e))return s;i.add(e),o.add(e);let l=(a.get(e)??[]).filter(e=>!o.has(e)&&!i.has(e)),u;if(l.length===0)u=s,s+=n(e)+20;else{let r=l.map(e=>c(e,t+1,i)),a=r[0]+n(l[0])/2,o=l[l.length-1];u=(a+(r[r.length-1]+n(o)/2))/2-n(e)/2}return i.delete(e),r.set(e,{x:40+t*340,y:u}),u},l=e.filter(e=>(i.get(e.id)??0)===0).map(e=>e.id);l.length===0&&e[0]!==void 0&&l.push(e[0].id);for(let e of l)c(e,0,new Set);let u=e.filter(e=>!o.has(e.id));for(let e of u)r.set(e.id,{x:40,y:s}),s+=n(e.id)+20;return r}function RE(e,t,n){let r=new Map,i=[];if(e.length===0)return{positions:r,bands:i};let a=new Map,o=new Map;for(let t of e)o.set(t.id,0);for(let e of t)a.set(e.from,[...a.get(e.from)??[],e.to]),o.set(e.to,(o.get(e.to)??0)+1);let s=e.find(e=>(o.get(e.id)??0)===0)??e[0],c=(a.get(s.id)??[]).filter(t=>e.some(e=>e.id===t)),l=e=>{let t=[],n=[e],r=new Set;for(;n.length>0;){let e=n.pop();if(!(r.has(e)||e===s.id)){r.add(e),t.push(e);for(let t of a.get(e)??[])n.push(t)}}return t},u=64,d=(e,t,a)=>{if(t.length===0)return;let o=new Map;for(let e of t){let t=a.get(e)??0;o.set(t,[...o.get(t)??[],e])}let s=[...o.keys()].sort((e,t)=>e-t),c=0,l=u+26+8,d=new Map;for(let e of s){let t=o.get(e),r=l,i=0;for(let e of t)d.set(e,r),r+=n(e)+18,i=Math.max(i,n(e));l=r,c=Math.max(c,l-u)}c=Math.max(c,82)+16;let f=s[s.length-1]??0,p=s[0]??0;i.push({x:24,y:u,w:(f-p+1)*320+32,h:c,label:e});for(let e of t)r.set(e,{x:40+((a.get(e)??0)-p)*320,y:d.get(e)??u+26+8});u+=c+26},f=IE(e,t);if(c.length===0)d(s.title,e.filter(e=>e.id!==s.id).map(e=>e.id),f);else{let t=new Set;for(let n of c){let r=e.find(e=>e.id===n)?.title??n,i=l(n);for(let e of i)t.add(e);d(r,i,f)}d(`其他`,e.filter(e=>e.id!==s.id&&!t.has(e.id)).map(e=>e.id),f)}let p=n(s.id);r.set(s.id,{x:40,y:64});for(let e of i)e.y+=p+26;for(let[e,t]of r)e!==s.id&&r.set(e,{x:t.x,y:t.y+p+26});return{positions:r,bands:i}}var zE=`pop-agent.canvas.moves.v1`;function BE(){try{let e=localStorage.getItem(zE);if(e===null)return{};let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function VE(e){try{localStorage.setItem(zE,JSON.stringify(e))}catch{}}function HE(e){try{let t=localStorage.getItem(NE);if(t===null||e===null)return`card`;let n=JSON.parse(t)?.[e];return n===`timeline`||n===`checklist`||n===`mindmap`||n===`swimlane`?n:`card`}catch{return`card`}}function UE(e,t){if(e!==null)try{let n=localStorage.getItem(NE),r=n===null?{}:JSON.parse(n);r[e]=t,localStorage.setItem(NE,JSON.stringify(r))}catch{}}function WE(e){return e.status===`doing`?{tone:`doing`,zh:`正在做`,en:`Doing`}:e.status===`done`?{tone:`done`,zh:`已完成`,en:`Done`}:e.status===`blocked`?{tone:`blocked`,zh:`卡住了`,en:`Blocked`}:{tone:`todo`,zh:`待办`,en:`To do`}}function GE(e,t){let n=typeof e.turnStartedAt==`number`&&e.turnStartedAt>0?`${Math.max(0,Math.floor((Date.now()-e.turnStartedAt)/1e3))}s`:``,r=e.activeTool?.name;if(r){let t=(e.activeTool?.argsSummary??``).replace(/\s+/g,` `).trim(),i=t.length>26?`${t.slice(0,26)}…`:t;return[i===``?`正在 ${r}`:`正在 ${r} · ${i}`,n].filter(Boolean).join(` · `)}return e.retrying?[t(`等模型重试…`,`Retrying…`),n].filter(Boolean).join(` · `):e.status===`awaiting_approval`?t(`等你确认`,`Waiting for you`):[t(`正在输出…`,`Writing…`),n].filter(Boolean).join(` · `)}function KE(e,t,n){let r=null;for(let i of e)for(let e of t){let t=e-i;Math.abs(t)>n||(r===null||Math.abs(t)<Math.abs(r.delta))&&(r={delta:t,at:e})}return r}function qE({onOpenFile:e}){let t=Y(),{snapshot:n,newSession:r,pendingNewChat:i}=Lo(),a=r!==null||i,o=a?null:n?.canvas??null,s=a?null:n?.active.conversationId??null,[c,l]=(0,C.useState)([]),u=c.length===0?null:c[c.length-1]??null;(0,C.useEffect)(()=>{l([])},[s]);let d=(0,C.useMemo)(()=>{if(o===null)return{nodes:[],edges:[],host:null};if(u===null)return{nodes:o.nodes,edges:o.edges,host:null};let e=o.nodes.find(e=>e.id===u)??null;return{nodes:e?.sub?.nodes??[],edges:e?.sub?.edges??[],host:e}},[o,u]);(0,C.useEffect)(()=>{u!==null&&d.host===null&&l([])},[u,d.host]);let f=(0,C.useRef)(null),p=(0,C.useRef)(null),m=(0,C.useRef)(null),h=(0,C.useRef)(null),g=(0,C.useRef)(null),_=(0,C.useRef)(null),v=(0,C.useRef)(null),y=(0,C.useRef)({x:0,y:0,k:1}),[b,x]=(0,C.useState)({}),[S,w]=(0,C.useState)(null),[T,E]=(0,C.useState)(null),[D,O]=(0,C.useState)([]),[k,A]=(0,C.useState)(!1),[j,M]=(0,C.useState)(null),[N,P]=(0,C.useState)(null),F=(0,C.useCallback)((e,t=null)=>{let n=p.current?.getBoundingClientRect();return{x:e.clientX-(n?.left??0),y:e.clientY-(n?.top??0),nodeId:t}},[]),I=S?.nodeId===null?9:13,L=(0,C.useCallback)(()=>w(null),[]),[R,z]=(0,C.useState)([]),B=(0,C.useRef)(new Set);(0,C.useLayoutEffect)(()=>{B.current=new Set(R)},[R]);let V=n?.canvasRunningNodeId??null,H=s===null?void 0:n?.runningByConversation?.[s],[,U]=(0,C.useState)(0);(0,C.useEffect)(()=>{if(V===null)return;let e=window.setInterval(()=>U(e=>e+1),1e3);return()=>window.clearInterval(e)},[V]);let[W,ee]=(0,C.useState)({}),G=(0,C.useRef)(new Map),[K,te]=(0,C.useState)(()=>HE(s)),ne=(0,C.useRef)(K);(0,C.useLayoutEffect)(()=>{ne.current=K},[K]),(0,C.useEffect)(()=>{te(HE(s))},[s,u]);let re=(0,C.useCallback)(e=>{te(e),UE(s,e)},[s]),ie=(0,C.useMemo)(()=>{if(K===`card`||o===null)return{positions:null,bands:[]};if(K===`swimlane`)return RE(d.nodes,d.edges,e=>W[e]??128);let e=IE(d.nodes,d.edges),t=[...d.nodes].sort((t,n)=>(e.get(t.id)??0)-(e.get(n.id)??0)||(t.order??0)-(n.order??0)),n=e=>W[e]??128,r=new Map;if(K===`mindmap`)return{positions:LE(d.nodes,d.edges,e=>W[e]??128),bands:[]};if(K===`timeline`){let i=new Map;for(let a of t){let t=e.get(a.id)??0,o=i.get(t)??64;r.set(a.id,{x:40+t*300,y:o}),i.set(t,o+n(a.id)+22)}return{positions:r,bands:[]}}{let e=64;for(let i of t)r.set(i.id,{x:40,y:e}),e+=n(i.id)+22}return{positions:r,bands:[]}},[d,K,W]),ae=ie.positions,oe=ie.bands,[se,ce]=(0,C.useState)(BE),le=K===`card`?void 0:se[s??``]?.[K],ue=(0,C.useCallback)(e=>le?.[e.id]??ae?.get(e.id)??b[e.id]??{x:e.x,y:e.y},[ae,b,le]);(0,C.useEffect)(()=>{let e=e=>{if(!ve.current)return;let t=e.target;(t===null||!t.isContentEditable&&!/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))&&(e.key===`Escape`?(L(),P(null),z([])):(e.metaKey||e.ctrlKey)&&(e.key===`a`||e.key===`A`)?(e.preventDefault(),z((o?.nodes??[]).map(e=>e.id))):(e.key===`Delete`||e.key===`Backspace`)&&R.length>0&&s!==null&&(e.preventDefault(),su(s,R),z([])))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[L,s,o,R]);let de=o?.rev??0;(0,C.useEffect)(()=>{x({})},[de]),(0,C.useLayoutEffect)(()=>{let e={};for(let[t,n]of G.current)e[t]=n.offsetHeight;Object.keys(e).length!==0&&ee(t=>Object.keys(e).length===Object.keys(t).length&&Object.entries(e).every(([e,n])=>t[e]===n)?t:e)},[de,b,V,H?.status,H?.activeTool?.name,K]);let q=(0,C.useCallback)(()=>{let e=y.current,t=m.current,n=f.current;if(!t||!n)return;t.style.transform=`translate3d(${e.x}px, ${e.y}px, 0) scale(${e.k})`;let r=24*e.k;n.style.backgroundSize=`${r}px ${r}px`,n.style.backgroundPosition=`${e.x}px ${e.y}px`,p.current?.classList.toggle(`is-far`,e.k<.5),h.current&&(h.current.textContent=`${e.k.toFixed(2)}×`,h.current.title=`x ${Math.round(e.x)} · y ${Math.round(e.y)} · ${e.k.toFixed(2)}×`)},[]);(0,C.useEffect)(()=>{q()},[q]);let fe=e=>Math.min(kE,Math.max(OE,e)),pe=(0,C.useCallback)((e,t,n)=>{let r=y.current,i=fe(n),a=(e-r.x)/r.k,o=(t-r.y)/r.k;r.k=i,r.x=e-a*i,r.y=t-o*i,q()},[q]),me=(0,C.useCallback)(e=>{let t=f.current;t&&pe(t.clientWidth/2,t.clientHeight/2,y.current.k*e)},[pe]),he=(0,C.useCallback)(()=>{for(let e of[_,v])e.current&&(e.current.style.display=`none`)},[]),ge=(0,C.useCallback)((e,t)=>{let n=y.current;_.current&&(e===null?_.current.style.display=`none`:(_.current.style.display=`block`,_.current.style.transform=`translateX(${e*n.k+n.x}px)`)),v.current&&(t===null?v.current.style.display=`none`:(v.current.style.display=`block`,v.current.style.transform=`translateY(${t*n.k+n.y}px)`))},[]),_e=(0,C.useRef)(null),ve=(0,C.useRef)(!1),ye=(0,C.useRef)(null),be=(0,C.useRef)(null),xe=(e,t)=>{if(e.button!==0||Ee.current||Te.current||e.target.closest(`button, select`))return;e.stopPropagation();let n=e.shiftKey||e.metaKey||e.ctrlKey,r;if(n){let e=new Set(B.current);if(e.has(t)){e.delete(t),z([...e]);return}e.add(t),z([...e]),r=[...e]}else B.current.has(t)?r=[...B.current]:(z([t]),r=[t]);let i=new Map;for(let e of r){let t=o?.nodes.find(t=>t.id===e);t&&i.set(e,ue(t))}be.current={pointerId:e.pointerId,ids:[...i.keys()],sx:e.clientX,sy:e.clientY,origins:i,moved:!1},e.currentTarget.setPointerCapture(e.pointerId)},Se=(0,C.useCallback)((e,t)=>{let n=be.current;if(n===null)return;let r=jE/y.current.k,i=1/0,a=1/0,s=-1/0,c=-1/0;for(let[e,t]of n.origins){let n=G.current.get(e)?.offsetHeight??W[e]??84;i=Math.min(i,t.x),a=Math.min(a,t.y),s=Math.max(s,t.x+ME),c=Math.max(c,t.y+n)}if(!Number.isFinite(i))return;let l=[],u=[];for(let e of o?.nodes??[]){if(n.origins.has(e.id))continue;let t=ue(e),r=G.current.get(e.id)?.offsetHeight??W[e.id]??84;l.push(t.x,t.x+ME/2,t.x+ME),u.push(t.y,t.y+r/2,t.y+r)}let d=KE([i+e,(i+s)/2+e,s+e],l,r),f=KE([a+t,(a+c)/2+t,c+t],u,r),p=e+(d?.delta??0),m=t+(f?.delta??0);for(let e of n.ids){let t=G.current.get(e);t&&(t.style.setProperty(`--card-dx`,`${p}px`),t.style.setProperty(`--card-dy`,`${m}px`))}ge(d?.at??null,f?.at??null)},[o?.nodes,W,ue,ge]),[Ce,we]=(0,C.useState)(!1),Te=(0,C.useRef)(!1);(0,C.useLayoutEffect)(()=>{Te.current=Ce,f.current?.classList.toggle(`can-zoom`,Ce||Ee.current)},[Ce]);let Ee=(0,C.useRef)(!1),De=(0,C.useRef)(null),Oe=e=>{let t=e.target;if(t.closest(`.canvas-bar`))return;if(e.button===0&&(Ee.current||Te.current)){De.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,moved:!1},f.current?.classList.add(`is-zooming`),f.current?.setPointerCapture(e.pointerId);return}if(t.closest(`.canvas-node`))return;let n=e.shiftKey||e.altKey;e.button===1||e.button===0&&!n?(_e.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,ox:y.current.x,oy:y.current.y},f.current?.classList.add(`is-panning`),f.current?.setPointerCapture(e.pointerId)):e.button===0&&(ye.current={id:e.pointerId,sx:e.clientX,sy:e.clientY,additive:e.metaKey||e.ctrlKey,moved:!1},f.current?.setPointerCapture(e.pointerId))},ke=e=>{let t=De.current;if(t!==null&&e.pointerId===t.id){let n=f.current,r=g.current;if(!n||!r)return;let i=n.getBoundingClientRect(),a=t.sx-i.left,o=t.sy-i.top,s=e.clientX-i.left,c=e.clientY-i.top;if(!t.moved&&Math.hypot(s-a,c-o)<4)return;t.moved=!0,r.classList.add(`is-zoom`),r.style.display=`block`,r.style.left=`${Math.min(a,s)}px`,r.style.top=`${Math.min(o,c)}px`,r.style.width=`${Math.abs(s-a)}px`,r.style.height=`${Math.abs(c-o)}px`;return}let n=_e.current;if(n!==null&&e.pointerId===n.id){y.current.x=n.ox+(e.clientX-n.sx),y.current.y=n.oy+(e.clientY-n.sy),q();return}let r=be.current;if(r!==null&&e.pointerId===r.pointerId){let t=e.clientX-r.sx,n=e.clientY-r.sy;if(!r.moved&&Math.hypot(t,n)<AE)return;if(!r.moved){r.moved=!0;for(let e of r.ids)G.current.get(e)?.classList.add(`is-dragging`)}Se(t/y.current.k,n/y.current.k);return}let i=ye.current;if(i!==null&&e.pointerId===i.id){let t=f.current,n=g.current;if(!t||!n)return;let r=t.getBoundingClientRect(),a=i.sx-r.left,o=i.sy-r.top,s=e.clientX-r.left,c=e.clientY-r.top;if(!i.moved&&Math.hypot(s-a,c-o)<AE)return;i.moved=!0,n.style.display=`block`,n.style.left=`${Math.min(a,s)}px`,n.style.top=`${Math.min(o,c)}px`,n.style.width=`${Math.abs(s-a)}px`,n.style.height=`${Math.abs(c-o)}px`}},Ae=(0,C.useCallback)(e=>{let t=f.current,n=g.current;if(!t||!n)return;let r=y.current,i=Number.parseFloat(n.style.left),a=Number.parseFloat(n.style.top),s=Number.parseFloat(n.style.width),c=Number.parseFloat(n.style.height),l=(i-r.x)/r.k,u=(a-r.y)/r.k,d=(i+s-r.x)/r.k,p=(a+c-r.y)/r.k,m=[];for(let e of o?.nodes??[]){let t=ue(e),n=G.current.get(e.id)?.offsetHeight??W[e.id]??84;t.x<d&&t.x+ME>l&&t.y<p&&t.y+n>u&&m.push(e.id)}z(t=>e?[...new Set([...t,...m])]:m)},[o?.nodes,W,ue]),je=(0,C.useCallback)(()=>{let e=f.current,t=g.current;if(!e||!t)return;let n=y.current,r=Number.parseFloat(t.style.left)||0,i=Number.parseFloat(t.style.top)||0,a=Number.parseFloat(t.style.width)||0,o=Number.parseFloat(t.style.height)||0;if(a<8||o<8)return;let s=a/n.k,c=o/n.k,l=(r-n.x)/n.k,u=(i-n.y)/n.k,d=fe(Math.min(e.clientWidth/s,e.clientHeight/c));n.k=d,n.x=(e.clientWidth-s*d)/2-l*d,n.y=(e.clientHeight-c*d)/2-u*d,q()},[q]),J=e=>{let t=_e.current;t!==null&&e.pointerId===t.id&&(_e.current=null,f.current?.classList.remove(`is-panning`));let n=De.current;if(n!==null&&e.pointerId===n.id){De.current=null,f.current?.classList.remove(`is-zooming`),n.moved&&je(),g.current&&(g.current.style.display=`none`,g.current.classList.remove(`is-zoom`)),Te.current&&we(!1);return}let r=ye.current;r!==null&&e.pointerId===r.id&&(ye.current=null,r.moved?Ae(r.additive):r.additive||z([]),g.current&&(g.current.style.display=`none`));let i=be.current;if(i===null||e.pointerId!==i.pointerId)return;be.current=null,he();for(let e of i.ids)G.current.get(e)?.classList.remove(`is-dragging`);if(!i.moved){for(let e of i.ids){let t=G.current.get(e);t?.style.removeProperty(`--card-dx`),t?.style.removeProperty(`--card-dy`)}return}let a=new Map;for(let e of i.ids){let t=G.current.get(e);t&&(a.set(e,{x:Number.parseFloat(t.style.getPropertyValue(`--card-dx`))||0,y:Number.parseFloat(t.style.getPropertyValue(`--card-dy`))||0}),t.style.removeProperty(`--card-dx`),t.style.removeProperty(`--card-dy`))}let o={},c=[];for(let[e,t]of a){let n=i.origins.get(e);if(!n)continue;let r={x:n.x+t.x,y:n.y+t.y};o[e]=r,c.push({id:e,...r})}K===`card`?(x(e=>({...e,...o})),s!==null&&cu(s,c,u??void 0)):ce(e=>{let t=s??``,n={...e[t]?.[K],...o},r={...e,[t]:{...e[t],[K]:n}};return VE(r),r})};(0,C.useEffect)(()=>{let e=p.current;if(!e)return;let t=t=>{if(t.preventDefault(),t.ctrlKey||t.metaKey){let n=e.getBoundingClientRect(),r=Math.exp(-t.deltaY*.0025);pe(t.clientX-n.left,t.clientY-n.top,y.current.k*r)}else f.current!==null&&(y.current.x-=t.deltaX,y.current.y-=t.deltaY,q())};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[q,pe]),(0,C.useEffect)(()=>{let e=e=>{if(!ve.current)return;let t=e.target;if(t!==null&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))return;let n=f.current;if(!n)return;let r=e.key===`+`||e.key===`=`?1.15:e.key===`-`||e.key===`_`?1/1.15:null;r===null?e.key===`0`&&(e.preventDefault(),pe(n.clientWidth/2,n.clientHeight/2,1)):(e.preventDefault(),me(r))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[me,pe]),(0,C.useEffect)(()=>{let e=e=>{let t=e;return t!==null&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))},t=e=>{Ee.current=e,f.current?.classList.toggle(`can-zoom`,e||Te.current)},n=n=>{if(!e(n.target)){if((n.key===`z`||n.key===`Z`)&&!n.metaKey&&!n.ctrlKey&&!n.altKey){if(!ve.current)return;t(!0)}else n.key===`Escape`&&(we(!1),t(!1))}},r=e=>{(e.key===`z`||e.key===`Z`)&&t(!1)},i=()=>t(!1);return window.addEventListener(`keydown`,n),window.addEventListener(`keyup`,r),window.addEventListener(`blur`,i),()=>{window.removeEventListener(`keydown`,n),window.removeEventListener(`keyup`,r),window.removeEventListener(`blur`,i)}},[]);let Me=(0,C.useCallback)(()=>{let e=f.current;if(!e||e.clientWidth===0||e.clientHeight===0)return;let t=d.nodes;if(t.length===0)return;let n=1/0,r=1/0,i=-1/0,a=-1/0;for(let e of t){let t=ue(e),o=G.current.get(e.id)?.offsetHeight??W[e.id]??84;n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+ME),a=Math.max(a,t.y+o)}let o=Math.min(1,fe(Math.min((e.clientWidth-80)/Math.max(1,i-n),(e.clientHeight-80)/Math.max(1,a-r))));y.current.k=o;let s=(e.clientWidth-(i-n)*o)/2-n*o,c=(e.clientHeight-(a-r)*o)/2-r*o;y.current.x=Math.max(s,40-n*o),y.current.y=Math.max(c,40-r*o),q()},[o?.nodes,W,q,ue]),Ne=(0,C.useCallback)(()=>{y.current={x:0,y:0,k:1},q()},[q]),X=(0,C.useCallback)(()=>{let e=Pe.current;if(P(null),e===null||s===null)return;let t=o?.nodes.find(t=>t.id===e.id);if(t===void 0)return;let n=e.title.trim(),r=e.detail.trim(),i={};n!==``&&n!==t.title&&(i.title=n),r!==(t.detail??``)&&(i.detail=r),(i.title!==void 0||i.detail!==void 0)&&au(s,e.id,i,u??void 0)},[s,o]),Pe=(0,C.useRef)(null);(0,C.useLayoutEffect)(()=>{Pe.current=N},[N]);let Fe=(0,C.useCallback)(async()=>{if(j!==null&&s!==null){A(!0);try{let e=await iu(s,j.nodeIds,u??void 0);O(e)}finally{A(!1)}}},[j,s,u]);(0,C.useEffect)(()=>{j===null?O([]):Fe()},[j?.nodeIds.join(`,`),j!==null]);let Ie=(0,C.useCallback)(()=>{if(j===null||s===null)return;let e=j.nodeIds.map(e=>o?.nodes.find(t=>t.id===e)).filter(e=>e!==void 0),t=j.text.trim();if(e.length===0||t===``)return;let n=[`【画布选区】针对这 ${e.length} 个节点:`,...e.map(e=>`- ${e.id}(${e.status}${e.kind?`,${e.kind}`:``}):${e.title}${e.detail?` —— ${e.detail}`:``}`),``,`我的要求:${t}`,``,`只改这几个节点(用 canvas 工具的 update / status / add 定位到上面的 id),别动其他节点;改完一句话说改了什么。`];an(),Al(n.join(`
77
+ `)),M(null)},[j,s,o]),Le=(0,C.useCallback)((e,t)=>{s!==null&&t!==e.status&&ou(s,e.id,t,u??void 0)},[s,u]),Re=(0,C.useCallback)(e=>{s!==null&&(su(s,[e.id],u??void 0),z(t=>t.filter(t=>t!==e.id)),We(t=>t?.id===e.id?null:t))},[s]),ze=(0,C.useCallback)(n=>{let r=n.artifacts??[];return r.length===0?null:(0,Q.jsxs)(`div`,{className:`canvas-preview-artifacts`,children:[(0,Q.jsx)(`div`,{className:`canvas-preview-artifacts-head`,children:t(`这一步的产出`,`Artifacts`)}),r.map((t,n)=>{let r=t.kind===`file`&&t.detail!==`工作区外`;return(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-artifact is-${t.kind}${r?` can-open`:``}`,title:t.detail??t.label,onClick:()=>{r&&(e(t.label),E(null))},children:[(0,Q.jsx)(`span`,{className:`canvas-artifact-icon`,children:t.kind===`file`?`▤`:t.kind===`command`?`>_`:`✎`}),(0,Q.jsx)(`span`,{className:`canvas-artifact-label`,children:t.label}),t.detail?(0,Q.jsx)(`span`,{className:`canvas-artifact-detail`,children:t.detail}):null]},`${t.kind}-${n}-${t.label}`)})]})},[t,e]),Be=(0,C.useCallback)(e=>{s!==null&&ru(s,e.id,u??void 0)},[s]),Ve=d.nodes,He=(0,C.useMemo)(()=>new Set(R),[R]),[Ue,We]=(0,C.useState)(null),Ge=Ue===null?null:Ve.find(e=>e.id===Ue.id)??null,Ke=(0,C.useRef)(null),qe=(0,C.useCallback)(()=>{Ke.current!==null&&(window.clearTimeout(Ke.current),Ke.current=null)},[]),Je=(0,C.useCallback)(()=>{qe(),We(null)},[qe]),Ye=(0,C.useCallback)(()=>{qe(),Ke.current=window.setTimeout(()=>{Ke.current=null,We(null)},160)},[qe]),Xe=(0,C.useCallback)(e=>{let t=f.current;if(!t)return;let n=ue(e),r=G.current.get(e.id)?.offsetHeight??W[e.id]??84,i=fe(Math.min((t.clientWidth-120)/ME,(t.clientHeight-120)/Math.max(1,r)));y.current.k=i,y.current.x=t.clientWidth/2-(n.x+ME/2)*i,y.current.y=t.clientHeight/2-(n.y+r/2)*i,q(),We(null)},[W,q,ue]),Ze=(0,C.useMemo)(()=>{if(Ue===null)return null;let e=f.current?.clientWidth??600,t=f.current?.clientHeight??600;return{left:Ue.x+Ue.w+12+300>e?Math.max(8,Ue.x-300-12):Ue.x+Ue.w+12,top:Math.max(8,Math.min(Ue.y,t-170)),width:300}},[Ue]),Qe=(0,C.useMemo)(()=>{if(o===null||d.edges.length===0)return[];let e=new Map(d.nodes.map(e=>[e.id,ue(e)])),t=new Map(d.nodes.map(e=>[e.id,W[e.id]??84]));return d.edges.map(n=>{let r=e.get(n.from),i=e.get(n.to);if(!r||!i)return null;let a=r.x+ME,o=r.y+(t.get(n.from)??84)/2,s=i.x,c=i.y+(t.get(n.to)??84)/2,l=s<a,u=l?r.x:a,d=l?i.x+ME:s,f=Math.max(48,Math.abs(d-u)*.45)*(l?-1:1),p=`M ${u} ${o} C ${u+f} ${o}, ${d-f} ${c}, ${d} ${c}`;return{key:`${n.from}->${n.to}`,d:p,label:n.label,mid:{x:(u+d)/2,y:(o+c)/2}}}).filter(e=>e!==null)},[o,d,W,ue]);return o===null||Ve.length===0?(0,Q.jsx)(`div`,{className:`canvas-view canvas-empty`,ref:p,onPointerEnter:()=>{ve.current=!0},onPointerLeave:()=>{ve.current=!1},children:(0,Q.jsxs)(`div`,{className:`canvas-empty-card`,children:[(0,Q.jsx)(`div`,{className:`canvas-empty-title`,children:t(`画布还空着`,`The canvas is empty`)}),(0,Q.jsx)(`div`,{className:`canvas-empty-body`,children:t(`在左边对话里说一句你要做什么,比如「我要做一个签到活动,帮我把要做的事画出来」,agent 会把它拆成一张图放到这里。`,`Tell the agent what you want to build (e.g. “I'm shipping a check-in campaign — map out what needs to happen”), and it will lay the work out here.`)})]})}):(0,Q.jsxs)(`div`,{className:`canvas-view`,ref:p,children:[(0,Q.jsxs)(`div`,{className:`canvas-viewport`,ref:f,onPointerDown:Oe,onContextMenu:e=>{e.preventDefault(),w(F(e))},onPointerMove:ke,onPointerUp:J,onPointerCancel:J,onPointerEnter:()=>{ve.current=!0},onPointerLeave:()=>{ve.current=!1,f.current?.classList.remove(`can-pan`)},children:[(0,Q.jsxs)(`div`,{className:`canvas-world`,ref:m,children:[oe.map(e=>(0,Q.jsx)(`div`,{className:`canvas-lane`,style:{left:e.x,top:e.y,width:e.w,height:e.h},children:(0,Q.jsx)(`span`,{className:`canvas-lane-label`,children:e.label})},`${e.label}-${e.y}`)),Qe.length>0?(0,Q.jsx)(`svg`,{className:`canvas-edges`,children:Qe.map(e=>(0,Q.jsx)(`path`,{d:e.d},e.key))}):null,Ve.map((e,n)=>{let r=ue(e),i=WE(e),a=He.has(e.id),o=V===e.id&&H!==void 0&&H.status!==`idle`,s=o?GE(H,t):null;return(0,Q.jsxs)(`div`,{className:`canvas-node is-${i.tone} kind-${FE(e)}${a?` is-selected`:``}${o?` is-live`:``}`,ref:t=>{t?G.current.set(e.id,t):G.current.delete(e.id)},style:{left:r.x,top:r.y},onPointerDown:t=>xe(t,e.id),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),w(F(t,e.id))},onPointerEnter:()=>{if(y.current.k>=.7){We(null);return}let t=y.current,n=G.current.get(e.id)?.offsetHeight??84;We({id:e.id,x:r.x*t.k+t.x,y:r.y*t.k+t.y,w:ME*t.k,h:n*t.k})},onPointerLeave:Ye,onDoubleClick:()=>{e.sub===void 0?Be(e):l([e.id])},title:t(`双击让 agent 开始做这一步`,`Double-click to have the agent start this step`),children:[(0,Q.jsx)(`span`,{className:`canvas-node-index`,children:n+1}),N!==null&&N.id===e.id?(0,Q.jsxs)(`div`,{className:`canvas-node-edit`,children:[(0,Q.jsx)(`input`,{className:`canvas-node-edit-title`,value:N.title,autoFocus:!0,onChange:e=>P({...N,title:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),X()),e.key===`Escape`&&P(null)}}),(0,Q.jsx)(`textarea`,{className:`canvas-node-edit-detail`,value:N.detail,rows:2,placeholder:t(`说明(可留空)`,`Detail (optional)`),onChange:e=>P({...N,detail:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),X()),e.key===`Escape`&&P(null)}}),(0,Q.jsxs)(`div`,{className:`canvas-node-edit-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:X,children:t(`保存`,`Save`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>P(null),children:t(`取消`,`Cancel`)})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`canvas-node-head`,children:[(0,Q.jsx)(`span`,{className:`canvas-dot is-${i.tone}`}),(0,Q.jsx)(`span`,{className:`canvas-node-kind kind-${FE(e)}`,title:t(PE[FE(e)].zh,PE[FE(e)].en),children:PE[FE(e)].icon}),(0,Q.jsx)(`span`,{className:`canvas-node-title`,children:e.title})]}),e.detail?(0,Q.jsx)(`div`,{className:`canvas-node-detail`,children:e.detail}):null]}),o&&s!==null?(0,Q.jsxs)(`div`,{className:`canvas-node-live`,children:[(0,Q.jsx)(`span`,{className:`canvas-live-dot`}),(0,Q.jsx)(`span`,{className:`canvas-live-text`,children:s})]}):null,(0,Q.jsxs)(`div`,{className:`canvas-node-state is-${i.tone}`,children:[t(i.zh,i.en),e.sub!==void 0&&e.sub.nodes.length>0?(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-node-sub`,title:t(`看这一步的子计划`,`Open its sub-plan`),onPointerDown:e=>e.stopPropagation(),onClick:()=>l([e.id]),children:[`· `,e.sub.nodes.filter(e=>e.status===`done`).length,`/`,e.sub.nodes.length,` `,t(`子步`,`sub`)]}):null,e.artifacts!==void 0&&e.artifacts.length>0?(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-node-artifacts`,title:t(`看这一步的产出`,`See artifacts`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let t=y.current;E({id:e.id,x:r.x*t.k+t.x,y:(r.y+40)*t.k+t.y})},children:[`· `,e.artifacts.length,` `,t(`项产出`,`artifacts`)]}):null]}),(0,Q.jsxs)(`div`,{className:`canvas-node-actions`,children:[(0,Q.jsxs)(`select`,{className:`canvas-node-status`,value:e.status,"aria-label":t(`改状态`,`Change status`),onPointerDown:e=>e.stopPropagation(),onChange:t=>Le(e,t.target.value),children:[(0,Q.jsx)(`option`,{value:`todo`,children:t(`待办`,`To do`)}),(0,Q.jsx)(`option`,{value:`doing`,children:t(`正在做`,`Doing`)}),(0,Q.jsx)(`option`,{value:`done`,children:t(`已完成`,`Done`)}),(0,Q.jsx)(`option`,{value:`blocked`,children:t(`卡住了`,`Blocked`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-node-delete`,title:t(`删掉这一步`,`Delete this step`),"aria-label":t(`删掉这一步`,`Delete this step`),onClick:()=>Re(e),children:`×`})]})]},e.id)})]}),(0,Q.jsx)(`div`,{className:`canvas-marquee`,ref:g}),(0,Q.jsx)(`div`,{className:`canvas-guide canvas-guide-x`,ref:_}),(0,Q.jsx)(`div`,{className:`canvas-guide canvas-guide-y`,ref:v})]}),Ue!==null&&Ge!==null&&Ze!==null?(0,Q.jsxs)(`div`,{className:`canvas-preview is-${WE(Ge).tone}`,style:{left:Ze.left,top:Ze.top,width:Ze.width},onPointerEnter:qe,onPointerLeave:Je,children:[(0,Q.jsxs)(`div`,{className:`canvas-preview-head`,children:[(0,Q.jsx)(`span`,{className:`canvas-dot is-${WE(Ge).tone}`}),(0,Q.jsx)(`span`,{className:`canvas-preview-title`,children:Ge.title})]}),Ge.detail?(0,Q.jsx)(`div`,{className:`canvas-preview-detail`,children:Ge.detail}):null,ze(Ge),(0,Q.jsxs)(`div`,{className:`canvas-preview-foot`,children:[(0,Q.jsx)(`span`,{className:`canvas-node-state is-${WE(Ge).tone}`,children:t(WE(Ge).zh,WE(Ge).en)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-preview-zoom`,onClick:()=>Xe(Ge),children:t(`放大看`,`Zoom in`)})]})]}):null,T===null?null:(()=>{let e=Ve.find(e=>e.id===T.id);return e===void 0?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:()=>E(null)}),(0,Q.jsxs)(`div`,{className:`canvas-ask`,style:{left:Math.min(T.x,(f.current?.clientWidth??600)-300),top:Math.min(T.y,(f.current?.clientHeight??600)-160)},children:[(0,Q.jsx)(`div`,{className:`canvas-ask-head`,children:e.title}),ze(e)]})]})})(),j===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:()=>M(null)}),(0,Q.jsxs)(`div`,{className:`canvas-ask`,style:{left:Math.min(j.x,(f.current?.clientWidth??600)-300),top:Math.min(j.y,(f.current?.clientHeight??600)-150)},children:[(0,Q.jsxs)(`div`,{className:`canvas-ask-head`,children:[(0,Q.jsx)(`span`,{children:t(`对这 ${j.nodeIds.length} 步说:`,`About these ${j.nodeIds.length}:`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-ask-refresh`,disabled:k,onClick:()=>void Fe(),children:k?t(`正在想…`,`Thinking…`):t(`换一批`,`Shuffle`)})]}),D.length>0?(0,Q.jsx)(`div`,{className:`canvas-ask-chips`,children:D.map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`canvas-ask-chip`,onClick:()=>M(t=>t===null?t:{...t,text:e}),children:e},e))}):null,(0,Q.jsx)(`textarea`,{className:`canvas-ask-input`,value:j.text,autoFocus:!0,rows:3,placeholder:t(`比如:这几步太粗,拆细一点 / 合并成一步 / 顺序不对`,`e.g. too coarse — split them / merge / wrong order`),onChange:e=>M({...j,text:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Ie()),e.key===`Escape`&&M(null)}}),(0,Q.jsxs)(`div`,{className:`canvas-ask-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`is-primary`,onClick:Ie,children:t(`发给 agent`,`Send`)}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>M(null),children:t(`取消`,`Cancel`)})]})]})]}),S===null?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-backdrop`,onPointerDown:L,onContextMenu:e=>{e.preventDefault(),L()}}),(0,Q.jsx)(`span`,{className:`canvas-rt-marker`,style:{left:S.x,top:S.y},"aria-hidden":`true`},`${S.x}-${S.y}`),(0,Q.jsxs)(`div`,{className:`canvas-menu`,style:{left:Math.min(S.x+8,(f.current?.clientWidth??600)-200),top:Math.min(S.y+8,(f.current?.clientHeight??600)-40-I*26)},children:[S.nodeId===null?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Me()},children:t(`看全局`,`Fit all`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Ne()},children:t(`回到 100%`,`Back to 100%`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${Ce?` is-on`:``}`,onClick:()=>{L(),we(e=>!e)},children:[Ce?`✓ `:``,t(`框选放大`,`Zoom to area`)]}),R.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-accent`,onClick:()=>{M({x:S.x,y:S.y,nodeIds:[...R],text:``}),L()},children:t(`就这 ${R.length} 步说两句…`,`Ask about these ${R.length}…`)})]}):null,(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`div`,{className:`canvas-menu-label`,children:t(`布局`,`Layout`)}),[[`card`,t(`卡片`,`Cards`)],[`timeline`,t(`时间线`,`Timeline`)],[`checklist`,t(`清单`,`Checklist`)],[`mindmap`,t(`导图`,`Mind map`)],[`swimlane`,t(`泳道`,`Swimlanes`)]].map(([e,t])=>(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${K===e?` is-on`:``}`,onClick:()=>{L(),re(e)},children:[K===e?`✓ `:``,t]},e))]}):null,S.nodeId===null?null:(()=>{let e=Ve.find(e=>e.id===S.nodeId);if(e===void 0)return null;let n=(()=>{let n=d.edges.filter(t=>t.to===e.id).map(e=>e.from);if(n.length===0)return null;let r=n.filter(e=>(Ve.find(t=>t.id===e)?.status??`todo`)!==`done`);return r.length===0?null:t(`前置还有 ${r.length} 步没完成`,`${r.length} earlier step(s) not done yet`)})();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-accent`,onClick:()=>{let t=R.includes(e.id)&&R.length>0?R:[e.id];M({x:S.x,y:S.y,nodeIds:t,text:``}),L()},children:R.includes(e.id)&&R.length>1?t(`就这 ${R.length} 步说两句…`,`Ask about these ${R.length}…`):t(`就这一步说两句…`,`Ask about this step…`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Be(e)},children:e.status===`done`?t(`重新做一遍`,`Run it again`):e.status===`doing`?t(`重新开始这一步`,`Restart this step`):e.status===`blocked`?t(`重试这一步`,`Retry this step`):t(`开始做这一步`,`Start this step`)}),e.status===`doing`?(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),s!==null&&jl(s)},children:t(`停下来`,`Stop it`)}):null,n===null?null:(0,Q.jsx)(`div`,{className:`canvas-menu-hint`,children:n}),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`div`,{className:`canvas-menu-label`,children:t(`状态`,`Status`)}),[[`todo`,t(`待办`,`To do`)],[`doing`,t(`正在做`,`Doing`)],[`done`,t(`已完成`,`Done`)],[`blocked`,t(`卡住了`,`Blocked`)]].map(([t,n])=>(0,Q.jsxs)(`button`,{type:`button`,className:`canvas-menu-item${e.status===t?` is-on`:``}`,onClick:()=>{L(),Le(e,t)},children:[e.status===t?`✓ `:``,n]},t)),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),P({id:e.id,title:e.title,detail:e.detail??``})},children:t(`重命名 / 改说明`,`Rename`)}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item`,onClick:()=>{L(),Xe(e)},children:t(`放大看这一步`,`Zoom in`)}),(0,Q.jsx)(`div`,{className:`canvas-menu-sep`}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-menu-item is-danger`,onClick:()=>{L(),Re(e)},children:t(`删除这一步`,`Delete`)})]})})()]})]}),(0,Q.jsxs)(`div`,{className:`canvas-bar`,children:[u===null?null:(0,Q.jsxs)(`span`,{className:`canvas-crumbs`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>l([]),title:t(`回到全部`,`Back to all`),children:[`‹ `,t(`全部`,`All`)]}),(0,Q.jsx)(`span`,{className:`canvas-crumbs-sep`,children:`›`}),(0,Q.jsx)(`span`,{className:`canvas-crumbs-current`,children:d.host?.title??u})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn`,onClick:Me,title:t(`看全局(缩到能看见全部)`,`Fit all`),"aria-label":t(`看全局`,`Fit all`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2 6V2h4M14 6V2h-4M2 10v4h4M14 10v4h-4`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn canvas-icon-text`,onClick:Ne,title:t(`回到 100%(重置视角)`,`Back to 100%`),"aria-label":t(`重置视角`,`Reset view`),children:`1:1`}),(0,Q.jsxs)(`select`,{className:`canvas-style`,value:K,"aria-label":t(`画布布局`,`Canvas layout`),title:t(`画布布局`,`Canvas layout`),onChange:e=>re(e.target.value),children:[(0,Q.jsx)(`option`,{value:`card`,children:t(`卡片`,`Cards`)}),(0,Q.jsx)(`option`,{value:`timeline`,children:t(`时间线`,`Timeline`)}),(0,Q.jsx)(`option`,{value:`checklist`,children:t(`清单`,`Checklist`)}),(0,Q.jsx)(`option`,{value:`mindmap`,children:t(`导图`,`Mind map`)}),(0,Q.jsx)(`option`,{value:`swimlane`,children:t(`泳道`,`Swimlanes`)})]}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn${Ce?` is-on`:``}`,"aria-pressed":Ce,onClick:()=>we(e=>!e),title:t(`框选放大(也可以按住 Z 拖)`,`Zoom to area`),"aria-label":t(`框选放大`,`Zoom to area`),children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`1.5`,y:`1.5`,width:`8`,height:`8`,rx:`1`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeDasharray:`2 1.6`}),(0,Q.jsx)(`circle`,{cx:`10.6`,cy:`10.6`,r:`3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,Q.jsx)(`path`,{d:`M12.9 12.9 15 15`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})]})}),(0,Q.jsxs)(`span`,{className:`canvas-zoom`,children:[(0,Q.jsx)(`button`,{type:`button`,onClick:()=>me(1/1.15),title:t(`缩小`,`Zoom out`),"aria-label":t(`缩小`,`Zoom out`),children:`−`}),(0,Q.jsx)(`button`,{type:`button`,onClick:()=>me(1.15),title:t(`放大`,`Zoom in`),"aria-label":t(`放大`,`Zoom in`),children:`+`})]}),(0,Q.jsx)(`span`,{ref:h,className:`canvas-readout`,title:t(`当前缩放`,`Current zoom`)}),(0,Q.jsx)(`span`,{className:`canvas-count`,title:t(`${Ve.length} 个节点`,`${Ve.length} steps`),children:Ve.length}),R.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`canvas-bar-sel`,title:t(`已选 ${R.length} 个`,`${R.length} selected`),children:R.length}),(0,Q.jsx)(`button`,{type:`button`,className:`canvas-icon-btn`,onClick:()=>z([]),title:t(`取消选择`,`Clear selection`),"aria-label":t(`取消选择`,`Clear selection`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,width:`12`,height:`12`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M4 4l8 8M12 4l-8 8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.6`,strokeLinecap:`round`})})})]}):null]}),o.goal?(0,Q.jsx)(`div`,{className:`canvas-goal`,children:o.goal}):null,(0,Q.jsx)(`div`,{className:`canvas-hint`,children:t(`拖空白平移 · Shift+拖框选 · Z+拖框选放大 · +/- 缩放 · 双击节点开工`,`Drag to pan · Shift+drag to box-select · Z+drag to zoom · +/- to zoom · double-click to start`)})]})}var JE=`pop-agent.preview.width.v2`,YE=360,XE=1200,ZE=`pop-agent.preview.files-rail-w`,QE=140,$E=520,eD=224,tD=260;function nD(){let e=Number(localStorage.getItem(ZE));return!Number.isFinite(e)||e<=0?eD:Math.min(Math.max(e,QE),$E)}function rD(){let e=Number(localStorage.getItem(JE));return Number.isFinite(e)&&e>=YE?Math.min(e,XE):null}function iD(e,t){return e.kind===`terminal`?{icon:`>_`,label:e.label??(e.cwd&&D(e.cwd)||t(`终端`,`Terminal`)),title:e.cwd??t(`终端`,`Terminal`)}:e.kind===`files`?{icon:`🗂`,label:t(`文件`,`Files`),title:t(`文件树`,`File tree`)}:e.kind===`side`?{icon:`💬`,label:e.label??t(`临时聊天`,`Side chat`),title:t(`临时聊天(不落盘)`,`Side chat (not saved)`)}:e.kind===`web`?{icon:`🌐`,label:e.url?GT(e.url):t(`新网页`,`New page`),title:e.url||t(`网页`,`Web page`)}:e.kind===`history`?{icon:`📜`,label:t(`完整历史`,`Full history`),title:t(`完整历史(pi 的会话导出页)`,`Full history (pi session export)`)}:e.kind===`prompt`?{icon:`🧾`,label:t(`系统提示词`,`System prompt`),title:t(`这次运行实际在用的系统提示词`,`The system prompt this run actually uses`)}:e.kind===`canvas`?{icon:`◎`,label:t(`画布`,`Canvas`),title:t(`画布:把会话摊在一块平面上`,`Canvas: sessions laid out on a plane`)}:{icon:/\.[jt]sx?$/i.test(e.path)?`TS`:/\.json$/i.test(e.path)?`{}`:/\.md$/i.test(e.path)?`M↓`:/\.(png|jpe?g|gif|webp|avif|svg)$/i.test(e.path)?`IMG`:`▤`,label:D(e.path)||e.path,title:e.path}}var aD=[{tool:`side`,icon:`💬`,zh:`临时聊天`,en:`Side chat`,hintZh:`另开一条对话问一句就走,不落盘、不影响主会话`,hintEn:`A separate throwaway chat: nothing saved, main session untouched`},{tool:`terminal`,icon:`>_`,zh:`终端`,en:`Terminal`,hintZh:`在对话框下面开一个 shell(底部终端)`,hintEn:`Open a shell under the chat (bottom panel)`},{tool:`files`,icon:`🗂`,zh:`文件`,en:`Files`,hintZh:`在当前工作区里翻文件,点开就在右边多一个标签`,hintEn:`Browse the workspace; opened files land in a new tab`},{tool:`web`,icon:`🌐`,zh:`网页`,en:`Web`,hintZh:`输入网址直接在这儿看(有些站点拒绝被嵌入)`,hintEn:`Open a URL right here (some sites refuse embedding)`},{tool:`canvas`,icon:`◎`,zh:`画布`,en:`Canvas`,hintZh:`把会话摊在一块可平移缩放的平面上,一眼看全谁在跑`,hintEn:`Lay your sessions out on a pannable, zoomable plane`}];function oD({items:e,activeId:t,landing:n,onActivate:r,onCloseTabs:i,onReorder:a,onShowLanding:o,onPickTool:s,onToggleSplit:c,onWideChange:l,root:u,files:d,onOpenFile:f,onOpenFilePath:p,revealSeq:m=0,onRevealFile:h,chatOnRight:g=!1,showSplitButton:_=!0,onWebNote:v,conversationId:y=null}){let b=Y(),[x,S]=(0,C.useState)(()=>rD()??620),w=(0,C.useRef)(null),T=(0,C.useRef)(rD()===null);(0,C.useLayoutEffect)(()=>{if(!T.current)return;T.current=!1;let e=w.current?.parentElement?.clientWidth??0;if(e<=0)return;let t=Math.round((e-6)/2);S(Math.min(Math.max(t,YE),XE))},[]);let[E,D]=(0,C.useState)(!1),O=e=>{D(e),l?.(e)},k=(0,C.useRef)(!1),A=(0,C.useCallback)(e=>{e.preventDefault(),k.current=!0;let t=e.clientX,n=x,r=e.currentTarget,i=e.pointerId;try{r.setPointerCapture(i)}catch{}document.documentElement.classList.add(`is-resizing`);let a=e=>{if(!k.current)return;let r=e.clientX-t,i=Math.min(Math.max(n+(g?r:-r),YE),XE);S(Math.round(i))},o=()=>{k.current=!1,document.documentElement.classList.remove(`is-resizing`),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),document.removeEventListener(`pointercancel`,o);try{r.hasPointerCapture(i)&&r.releasePointerCapture(i)}catch{}};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o),document.addEventListener(`pointercancel`,o)},[x,g]);(0,C.useEffect)(()=>{localStorage.setItem(JE,String(x))},[x]);let j=e.find(e=>e.id===t)??e[0],M=n||e.length===0,[N,P]=uf(`pop-agent.preview.files-rail.v3`,!1),[F,I]=(0,C.useState)(nD);(0,C.useEffect)(()=>{localStorage.setItem(ZE,String(F))},[F]);let L=(0,C.useCallback)(e=>{e.preventDefault();let t=e.clientX,n=F,r=Math.max(QE,Math.min($E,x-tD)),i=e=>{let i=Math.min(Math.max(n+(t-e.clientX),QE),r);I(Math.round(i))},a=()=>{document.removeEventListener(`pointermove`,i),document.removeEventListener(`pointerup`,a)};document.addEventListener(`pointermove`,i),document.addEventListener(`pointerup`,a)},[F,x]),R=!M&&j?.kind===`file`?j:null,z=!M&&j?.kind===`terminal`,B=(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn${N?` btn-wide-on`:``}`,onClick:()=>{let e=!N;P(e),e&&R&&h?.(R.path,R.root||u||``)},"aria-pressed":N,title:N?b(`隐藏右边那排文件列表`,`Hide the file list on the right`):b(`显示文件列表(常驻在内容右边,点文件另开标签)`,`Show the file list (opens files as new tabs)`),children:(0,Q.jsx)(`svg`,{className:`preview-tool-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M2 4.4c0-.66.54-1.2 1.2-1.2h2.7l1.4 1.6h5.5c.66 0 1.2.54 1.2 1.2v6.4c0 .66-.54 1.2-1.2 1.2H3.2c-.66 0-1.2-.54-1.2-1.2z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`,strokeLinejoin:`round`})})}),V=(0,C.useRef)(null),H=(0,C.useRef)(null),[U,W]=(0,C.useState)(null);(0,C.useEffect)(()=>{let e=V.current;if(!e)return;let t=t=>{e.scrollWidth<=e.clientWidth+1||Math.abs(t.deltaX)>=Math.abs(t.deltaY)||(e.scrollLeft+=t.deltaY,t.preventDefault())};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,C.useEffect)(()=>{let e=V.current;if(!e||!j)return;let t=e.querySelector(`[data-tab-id="${CSS.escape(j.id)}"]`);if(!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.left<n.left?e.scrollLeft-=n.left-r.left+6:r.right>n.right&&(e.scrollLeft+=r.right-n.right+6)},[j?.id,e.length]);let ee=e=>{let t=H.current;if(H.current=null,W(null),e===void 0)return;let n=V.current;for(let t of n?.querySelectorAll(`[data-tab-id]`)??[])t.hasPointerCapture?.(e)&&t.releasePointerCapture(e);return t},G=t=>{let n=V.current;if(!n)return e.length-1;let r=Array.from(n.querySelectorAll(`[data-tab-id]`));for(let e=0;e<r.length;e+=1){let n=r[e].getBoundingClientRect();if(t<n.left+n.width/2)return e}return r.length-1},K=(e,t)=>{e.button===0&&(e.target.closest(`.preview-tab-x`)||e.pointerType!==`touch`&&(H.current={id:t,startX:e.clientX,moved:!1},e.currentTarget.setPointerCapture?.(e.pointerId)))},te=t=>{let n=H.current;if(!n)return;if(!n.moved){if(Math.abs(t.clientX-n.startX)<5)return;n.moved=!0,W(n.id)}let r=e.map(e=>e.id),i=r.indexOf(n.id),o=G(t.clientX);if(i<0)return;let s=o>i?o-1:o;if(s===i)return;let c=[...r];c.splice(i,1),c.splice(s,0,n.id),a(c)},ne=(e,t)=>{let n=H.current?.moved===!0;ee(e.pointerId),n||r(t)},[re,ie]=(0,C.useState)(null);(0,C.useEffect)(()=>{if(!re)return;let e=e=>{e.target?.closest?.(`.preview-tab-menu`)||ie(null)},t=e=>{e.key===`Escape`&&ie(null)};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t),window.addEventListener(`blur`,e),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t),window.removeEventListener(`blur`,e)}},[re]);let ae=re?e.findIndex(e=>e.id===re.id):-1,oe=ae<0?[]:[{key:`one`,zh:`关闭`,en:`Close`,ids:[e[ae].id],disabled:!1},{key:`left`,zh:`关闭左侧标签`,en:`Close tabs to the left`,ids:e.slice(0,ae).map(e=>e.id),disabled:ae===0},{key:`right`,zh:`关闭右侧标签`,en:`Close tabs to the right`,ids:e.slice(ae+1).map(e=>e.id),disabled:ae===e.length-1},{key:`all`,zh:`关闭全部标签`,en:`Close all tabs`,ids:e.map(e=>e.id),disabled:!1}];return(0,Q.jsxs)(`aside`,{ref:w,className:`preview-panel${E?` preview-panel-wide`:``}${z?` preview-panel-term`:``}`,style:E?void 0:{width:x},children:[(0,Q.jsx)(`div`,{className:`preview-resizer`,onPointerDown:A,title:b(`拖动调整宽度`,`Drag to resize`)}),(0,Q.jsxs)(`div`,{className:`preview-tabs`,children:[(0,Q.jsx)(`div`,{className:`preview-tabs-strip`,ref:V,children:e.map(e=>{let{icon:t,label:n,title:a}=iD(e,b);return(0,Q.jsxs)(`span`,{className:`preview-tab${e.id===j?.id&&!M?` preview-tab-on`:``}${U===e.id?` preview-tab-dragging`:``}`,"data-tab-id":e.id,onPointerDown:t=>K(t,e.id),onPointerMove:te,onPointerUp:t=>ne(t,e.id),onPointerCancel:e=>ee(e.pointerId),onContextMenu:t=>{t.preventDefault(),ie({x:t.clientX,y:t.clientY,id:e.id})},children:[(0,Q.jsxs)(`button`,{type:`button`,className:`preview-tab-name`,title:a,onClick:t=>{t.detail===0&&r(e.id)},children:[(0,Q.jsx)(`span`,{className:`preview-tab-icon`,children:t}),n]}),(0,Q.jsx)(`button`,{type:`button`,className:`preview-tab-x`,onClick:()=>i([e.id]),title:b(`关闭`,`Close`),children:`×`})]},e.id)})}),(0,Q.jsx)(`button`,{type:`button`,className:`preview-tab-add`,onClick:o,title:b(`新标签(文件 / 终端 / 临时聊天 / 网页)`,`New tab (files / terminal / side chat / web)`),children:(0,Q.jsx)(`svg`,{className:`preview-tab-add-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M8 2.4v11.2M2.4 8h11.2`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})})}),(0,Q.jsx)(`span`,{className:`topbar-spacer`}),(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn${E?` btn-wide-on`:``}`,onClick:()=>O(!E),title:E?b(`收回右侧(恢复对话区)`,`Collapse the right panel (brings the chat back)`):b(`铺开:占满对话 + 预览两块区域(左侧栏保留)`,`Spread out: fill the chat + preview area (left sidebar stays)`),"aria-pressed":E,children:(0,Q.jsxs)(`svg`,{className:`preview-wide-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M2.2 4v8`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`M6.2 8h7.2`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`}),(0,Q.jsx)(`path`,{d:`m10.6 5.5 2.8 2.5-2.8 2.5`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`}),(0,Q.jsx)(`path`,{d:`m7.8 5.5-2.8 2.5 2.8 2.5`,stroke:`currentColor`,strokeWidth:`1.4`,fill:`none`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),c&&_?(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-tiny preview-tool-btn`,onClick:c,title:g?b(`收起左侧工作区(分栏)`,`Collapse the left work area (split)`):b(`收起右侧工作区(分栏)`,`Collapse the right work area (split)`),children:(0,Q.jsxs)(`svg`,{className:`preview-tool-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:g?`6`:`10`,y1:`4`,x2:g?`6`:`10`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})}):null]}),re?(0,Q.jsx)(`div`,{className:`preview-tab-menu`,role:`menu`,style:{left:Math.max(8,Math.min(re.x,window.innerWidth-200)),top:Math.max(8,Math.min(re.y,window.innerHeight-160))},children:oe.map(e=>(0,Q.jsx)(`button`,{type:`button`,role:`menuitem`,className:`preview-tab-menu-item`,disabled:e.disabled,onClick:()=>{ie(null),i(e.ids)},children:b(e.zh,e.en)},e.key))}):null,(0,Q.jsxs)(`div`,{className:`preview-body`,children:[M?(0,Q.jsxs)(`div`,{className:`work-landing`,children:[(0,Q.jsx)(`div`,{className:`work-landing-head`,children:b(`工具`,`Tools`)}),(0,Q.jsx)(`div`,{className:`work-landing-grid`,children:aD.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`work-tool-card`,onClick:()=>s(e.tool),title:b(e.hintZh,e.hintEn),children:[(0,Q.jsx)(`span`,{className:`work-tool-icon`,children:e.icon}),(0,Q.jsx)(`span`,{className:`work-tool-label`,children:b(e.zh,e.en)}),(0,Q.jsx)(`span`,{className:`work-tool-hint`,children:b(e.hintZh,e.hintEn)})]},e.tool))})]}):null,e.map(e=>(0,Q.jsx)(`div`,{className:`preview-slot${e.id===j?.id&&!M?``:` preview-slot-hidden`}`,children:e.kind===`file`?(0,Q.jsx)(kT,{path:e.path,root:e.root,initialMode:e.mode??null,focusLine:e.line,toolbar:B,onOpenPath:p?t=>p(t,e.root):void 0}):e.kind===`terminal`?(0,Q.jsx)(AT,{termId:e.id,cwd:e.cwd,initialCommand:e.initialCommand??null,active:e.id===j?.id&&!M,onClose:()=>i([e.id])}):e.kind===`files`?(0,Q.jsx)(wE,{...d}):e.kind===`web`?(0,Q.jsx)(oE,{initialUrl:e.url,onAddNote:v}):e.kind===`history`?(0,Q.jsx)(EE,{conversationId:y}):e.kind===`prompt`?(0,Q.jsx)(DE,{conversationId:y,active:e.id===j?.id&&!M}):e.kind===`canvas`?(0,Q.jsx)(qE,{root:u,onOpenFile:f}):(0,Q.jsx)(BT,{itemId:e.id})},e.id)),R&&N?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`preview-files-resizer`,role:`separator`,"aria-orientation":`vertical`,title:b(`拖动调整文件列表宽度(双击复位)`,`Drag to resize the file list (double-click to reset)`),onPointerDown:L,onDoubleClick:()=>I(eD)}),(0,Q.jsx)(TE,{root:R.root||u,activePath:R.path,revealSeq:m,onOpenFile:f,width:F})]}):null]})]})}function sD(e){e.kind===`side`&&RT(e.id)}function cD({className:e}){return(0,Q.jsxs)(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M4.7 3.3h7.9a2.3 2.3 0 0 1 2.3 2.3v6a2.3 2.3 0 0 1-2.3 2.3H8.1L5.4 16.6v-2.7h-.7a2.3 2.3 0 0 1-2.3-2.3v-6a2.3 2.3 0 0 1 2.3-2.3Z`}),(0,Q.jsx)(`path`,{d:`M16.9 9.1h.8a2.3 2.3 0 0 1 2.3 2.3v6a2.3 2.3 0 0 1-2.3 2.3h-6.1`})]})}function lD(e,t,n){let r=new Map,i=[],a=(e,t,n)=>{let a={cwd:t,name:n,sessions:[]};return r.set(e,a),i.push(a),a};for(let t of e){let e=j(t.cwd),n=r.get(e)??a(e,t.cwd,t.name);for(let e of t.sessions)n.sessions.some(t=>t.id===e.id)||n.sessions.push(e)}let o=new Map;for(let e of t){let t=j(e.workspace);t!==``&&o.set(e.id,{conversation:e,key:t})}for(let e of i)e.sessions=e.sessions.filter(t=>{let n=o.get(t.id);return!n||n.key===j(e.cwd)});let s=new Set(i.flatMap(e=>e.sessions.map(e=>e.id)));for(let e of t){if(s.has(e.id))continue;let t=j(e.workspace),i=r.get(t)??a(t,e.workspace,e.workspace===``?n:D(e.workspace)),o={id:e.id,title:e.title||J(`新对话`,`New chat`),startedAt:e.createdAt,updatedAt:e.updatedAt,cwd:e.workspace,model:null,sessionPath:``};i.sessions.unshift(o),s.add(o.id)}return i.filter(e=>e.sessions.length>0)}function uD(e,t){let n=new Set(t.map(j).filter(e=>e!==``)),r=[],i=[];for(let t of e)n.has(j(t.cwd))?i.push(t):r.push(t);return{visible:r,hidden:i}}var dD={fill:`none`,stroke:`currentColor`,strokeWidth:1.8,strokeLinecap:`round`,strokeLinejoin:`round`};function fD({className:e}){return(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:e,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`3.2`,y:`3.8`,width:`17.6`,height:`4.8`,rx:`1.4`,...dD}),(0,Q.jsx)(`path`,{d:`M4.9 8.6v9.6a1.8 1.8 0 0 0 1.8 1.8h10.6a1.8 1.8 0 0 0 1.8-1.8V8.6`,...dD}),(0,Q.jsx)(`path`,{d:`M9.4 13.2h5.2`,...dD})]})}function pD({total:e,open:t,onToggle:n}){let r=Y();return e<=0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-row-entry`,"aria-expanded":t,title:t?r(`收起归档的会话`,`Collapse archived sessions`):r(`已归档 · ${e}(点一下展开,可恢复 / 删除)`,`Archived · ${e} (click to expand; restore or delete)`),onClick:n,children:[(0,Q.jsx)(`span`,{className:`proj-chevron`,"aria-hidden":`true`,children:(0,Q.jsx)(fD,{className:`archived-row-entry-icon`})}),(0,Q.jsxs)(`span`,{className:`archived-row-entry-name`,children:[r(`已归档`,`Archived`),` · `,e]})]})}function mD(e,t,n){let r=e.indexOf(n),i=t===null?-1:e.indexOf(t);if(r<0||i<0)return[n];let[a,o]=i<=r?[i,r]:[r,i];return e.slice(a,o+1)}function hD(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function gD(e,t){if(e.length===0)return[];let n=new Set(t);return e.filter(e=>n.has(e))}function _D({open:e}){return(0,Q.jsx)(`span`,{className:`proj-chevron${e?` proj-chevron-open`:``}`,"aria-hidden":`true`,children:(0,Q.jsx)(ap,{open:e,className:`proj-folder`})})}function vD({groups:e,onOpen:t,onRestore:n,onRestoreMany:r}){let i=Y(),a=e.reduce((e,t)=>e+t.items.length,0),[o,s]=(0,C.useState)([]),c=(0,C.useRef)(null),[l,u]=(0,C.useState)(new Set),d=(e,t)=>u(n=>{let r=new Set(n);if(r.has(e)){r.delete(e);let n=new Set(t);s(e=>e.filter(e=>!n.has(e)))}else r.add(e);return r}),f=e=>l.has(e),p=e.flatMap(e=>f(e.name)?e.items.map(e=>e.id):[]),m=Yd();return(0,Q.jsxs)(`div`,{className:`archived-inline`,children:[o.length>0?(0,Q.jsxs)(`div`,{className:`archived-inline-bar sidebar-selection`,children:[(0,Q.jsx)(`span`,{className:`sidebar-selection-count`,"aria-live":`polite`,children:i(`已选 ${o.length} 条`,`${o.length} selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn`,title:i(`把这些恢复回主列表`,`Restore these back to the main list`),onClick:()=>{let e=[...o];e.length!==0&&(e.length===1?n(e[0]):r(e),s([]),c.current=null)},children:i(`恢复`,`Restore`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn sidebar-selbtn-danger${m.armed?` sidebar-selbtn-armed`:``}`,title:m.armed?i(`再点一次就真删这些会话文件:不可恢复`,`Click again to permanently delete these session files`):i(`把选中的这些连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected sessions including their files — first click only arms it`),onClick:()=>{let e=[...o];e.length!==0&&m.run(()=>{Ud(e,`选中的归档会话`),s([]),c.current=null})},children:m.armed?i(`确认彻底删除`,`Confirm purge`):i(`彻底删除`,`Purge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon`,title:i(`取消选择`,`Clear selection`),"aria-label":i(`取消选择`,`Clear selection`),onClick:()=>{s([]),c.current=null},children:`✕`})]}):null,(0,Q.jsxs)(`div`,{className:`archived-view-list archived-inline-list`,children:[e.map(e=>(0,Q.jsxs)(`div`,{className:`archived-group`,children:[(0,Q.jsx)(`div`,{className:`archived-group-title`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-group-toggle`,onClick:()=>d(e.name,e.items.map(e=>e.id)),"aria-expanded":f(e.name),title:f(e.name)?i(`收起这个项目的归档`,`Collapse this project's archive`):i(`展开这个项目的归档`,`Expand this project's archive`),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${f(e.name)?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(_D,{open:!1}),(0,Q.jsxs)(`span`,{className:`archived-group-name`,children:[e.name,` · `,e.items.length]})]})}),(f(e.name)?e.items:[]).map(e=>(0,Q.jsx)(`button`,{type:`button`,className:`archived-open${o.includes(e.id)?` archived-row-on`:``}`,title:i(`点一下选中 · Shift 连选 · Ctrl/⌘ 加减选 · 双击打开\n${e.id}`,`Click to select · Shift for a range · Ctrl/⌘ to add or remove · Double-click to open\n${e.id}`),onClick:t=>{t.shiftKey?s(mD(p,c.current,e.id)):t.ctrlKey||t.metaKey?(s(hD(o,e.id)),c.current=e.id):(s([e.id]),c.current=e.id)},onDoubleClick:()=>t(e.id),children:(0,Q.jsx)(`span`,{className:`archived-title`,children:e.title})},e.id))]},e.name)),a===0?(0,Q.jsx)(`div`,{className:`side-panel-hint`,children:i(`没有归档的会话`)}):null]})]})}function yD({point:e,anchor:t,count:n,onArchive:r,onDelete:i,onClear:a,onClose:o}){let s=Y(),c=e=>()=>{o(),e()},l=Yd();return(0,Q.jsxs)(qd,{point:e,anchor:t,className:`pi-menu`,closeOnLeave:!0,onClose:o,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:s(`把这 ${n} 条一起隐藏,可在「已归档」里找回或撤销`,`Hide all ${n}; find them under Archived or undo`),onClick:c(r),children:[`🗄 `,s(`归档这 ${n} 条`,`Archive ${n}`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${l.armed?` proj-menu-item-armed`:``}`,title:l.armed?s(`再点一次就真删这 ${n} 个会话文件:不可恢复`,`Click again to permanently delete these ${n} session file(s) — not recoverable`):s(`把选中的 ${n} 条连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected ${n} including their files — first click only arms it`),"aria-label":l.armed?s(`再点一次确认彻底删除`,`Click again to delete permanently`):s(`彻底删除选中的会话`,`Permanently delete selected sessions`),onClick:()=>l.run(()=>{o(),i()}),children:l.armed?s(`🧨 再点一次彻底删除这 ${n} 条`,`🧨 Click again to purge ${n}`):s(`🧨 彻底删除这 ${n} 条`,`🧨 Purge ${n}`)}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:c(a),children:[`✕ `,s(`取消选择`,`Clear selection`)]})]})}function bD({count:e,onArchive:t,onDelete:n,onClear:r}){let i=Y(),a=Yd();return(0,Q.jsxs)(`span`,{className:`sidebar-selection`,children:[(0,Q.jsx)(`span`,{className:`sidebar-selection-count`,title:i(`已选中 ${e} 条会话(Shift 连选 · Ctrl/⌘ 加减选)`,`${e} session(s) selected (Shift for a range · Ctrl/⌘ to add or remove)`),"aria-label":i(`已选中 ${e} 条会话`,`${e} session(s) selected`),"aria-live":`polite`,children:i(`已选 ${e} 条`,`${e} selected`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn`,title:i(`把这 ${e} 条一起隐藏,可在「已归档」里找回或撤销`,`Hide all ${e}; find them under Archived or undo`),onClick:t,children:i(`归档`,`Archive`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-selbtn sidebar-selbtn-danger${a.armed?` sidebar-selbtn-armed`:``}`,title:a.armed?i(`再点一次就真删这 ${e} 个会话文件:不可恢复`,`Click again to permanently delete these ${e} session file(s) — not recoverable`):i(`把选中的 ${e} 条连同磁盘上的文件一起删掉(不可恢复);第一下只是确认`,`Permanently delete the selected ${e} including their files — first click only arms it`),"aria-label":a.armed?i(`再点一次确认彻底删除`,`Click again to delete permanently`):i(`彻底删除选中的会话`,`Permanently delete selected sessions`),onClick:()=>a.run(n),children:a.armed?i(`确认彻底删除`,`Confirm purge`):i(`彻底删除`,`Purge`)}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon`,title:i(`取消选择`,`Clear selection`),"aria-label":i(`取消选择`,`Clear selection`),onClick:r,children:`✕`})]})}function xD(e,t){return e.map(e=>({name:e.name||e.cwd,items:e.sessions.filter(e=>t.archived.includes(e.id)).map(e=>({id:e.id,title:e.title||J(`(无标题)`,`(untitled)`)}))})).filter(e=>e.items.length>0)}function SD(e,t,n,r){return n[e.cwd]??(t===0||e.sessions.some(e=>e.id===r))}function CD(e,t=Date.now()){let n=Math.max(0,t-e),r=6e4;if(n<r)return J(`刚刚`,`just now`);if(n<60*r)return J(`${Math.floor(n/r)}分`,`${Math.floor(n/r)}m`);if(n<1440*r)return J(`${Math.floor(n/(60*r))}小时`,`${Math.floor(n/(60*r))}h`);let i=Math.floor(n/(1440*r));if(i<30)return J(`${i}天`,`${i}d`);let a=Math.floor(i/30);return a<12?J(`${a}个月`,`${a}mo`):J(`${Math.floor(a/12)}年`,`${Math.floor(a/12)}y`)}function wD({session:e,active:t,running:n,unseen:r=!1,title:i,pinned:a,selected:o=!1,menuPoint:s,onOpenMenu:c,onSwitch:l,onPin:u,onRename:d,onAiRename:f,onArchive:p,onDelete:m,onOpenInNewTab:h,onFork:g,canFork:_=!1,onCloseMenu:v,draggable:y,onDragStart:b,onDragEnd:x,dragOver:S,onDragOver:w,onDragLeave:T,onDrop:E}){let D=Y(),[O,k]=(0,C.useState)(!1),[A,j]=(0,C.useState)(!1),M=()=>{f&&!A&&(j(!0),Promise.resolve(f()).finally(()=>j(!1)))},[N,P]=(0,C.useState)(i),F=(0,C.useRef)(null);(0,C.useEffect)(()=>{O&&(P(i),requestAnimationFrame(()=>{F.current?.focus(),F.current?.select()}))},[O,i]);let I=(0,C.useRef)(null),L=(0,C.useRef)(null),R=(0,C.useRef)(null),z=()=>{let e=L.current,t=R.current;if(!e||!t)return;let r=n?0:64,i=Math.ceil(t.getBoundingClientRect().width-(e.clientWidth-r));if(i<=0){e.style.removeProperty(`--pi-title-shift`),e.style.removeProperty(`--pi-title-dur`);return}e.style.setProperty(`--pi-title-shift`,`-${i}px`);let a=Math.min(12e3,Math.max(1500,Math.round(i/25*1e3)));e.style.setProperty(`--pi-title-dur`,`${a}ms`)},B=()=>{let e=N.replace(/\s+/g,` `).trim().slice(0,60);k(!1),e!==``&&e!==i&&d(e)},V=o||s!==null;return(0,Q.jsxs)(`div`,{ref:I,className:`pi-row-wrap${t?` pi-row-wrap-active`:``}${V?` pi-row-wrap-selected`:``}${n?` pi-row-wrap-running`:``}${S?` pi-row-drag-over`:``}`,draggable:y,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e.id),t.dataTransfer.effectAllowed=`move`,b?.()},onDragEnd:x,onDragOver:w?e=>{e.dataTransfer?.types.includes(`text/plain`)&&(e.preventDefault(),w())}:void 0,onDragLeave:T,onDrop:E?e=>{e.preventDefault(),e.stopPropagation(),E()}:void 0,onContextMenu:e=>{e.preventDefault(),e.ctrlKey?l({shift:!1,toggle:!0}):c({x:e.clientX,y:e.clientY})},onMouseEnter:z,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pi-row${t?` pi-row-active`:``}${V?` pi-row-selected`:``}${a?` pi-row-pinned`:``}`,onClick:e=>l({shift:e.shiftKey,toggle:e.metaKey||e.ctrlKey}),title:`${e.cwd}\n${e.id}\n${D(`最后活动:`,`Last activity: `)}${CD(e.updatedAt)}`,children:[O?(0,Q.jsx)(`input`,{ref:F,className:`pi-row-title pi-row-title-input`,...wu,value:N,onChange:e=>P(e.target.value),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),B()):e.key===`Escape`&&(e.preventDefault(),k(!1))},onBlur:B}):(0,Q.jsx)(`span`,{ref:L,className:`pi-row-title`,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),k(!0)},title:D(`双击改名`),children:(0,Q.jsx)(`span`,{ref:R,className:`pi-row-title-text`,children:i})}),n?(0,Q.jsx)(`span`,{className:`pi-running`,role:`img`,"aria-label":D(`这个会话正在运行`,`This session is running`),title:D(`这个会话正在运行`,`This session is running`),children:(0,Q.jsx)(`span`,{className:`pi-ring`,"aria-hidden":`true`})}):r?(0,Q.jsx)(`span`,{className:`pi-unseen`,role:`img`,"aria-label":D(`已跑完,还没看`,`Finished, not reviewed`),title:D(`跑完了、你还没看(点开这条会话就消失)`,`Finished and not reviewed — open it to clear`)}):null]}),(0,Q.jsx)(`button`,{type:`button`,className:`pi-more`,title:D(`更多操作(置顶 / 重命名 / 归档…)`),onClick:e=>{e.stopPropagation();let t=e.currentTarget.getBoundingClientRect();c({x:t.left,y:t.bottom+2})},children:`⋯`}),s?(0,Q.jsx)(Xd,{anchor:I.current,title:i,pinned:a,onClose:v,onPin:u,onRename:()=>k(!0),onAiRename:f?M:void 0,aiRenaming:A,onOpenInNewTab:h,fork:g?{enabled:_,reason:_?void 0:D(`当前引擎不支持分叉`,`The current engine does not support forking`),onFork:g}:void 0,onArchive:p,onDelete:m}):null]})}function TD({count:e,open:t,onToggle:n}){let r=Y();return e<=0?null:(0,Q.jsxs)(`button`,{type:`button`,className:`archived-row-entry hidden-row-entry`,title:t?r(`收起隐藏的项目`,`Collapse hidden projects`):r(`已隐藏 ${e} 个项目(点一下展开,里面跟「项目」那一栏一样能点开项目、打开会话)`,`${e} hidden project(s) — click to expand; projects and sessions work like the main list`),"aria-expanded":t,onClick:n,children:[(0,Q.jsx)(`span`,{className:`proj-chevron`,"aria-hidden":`true`,children:`🙈`}),(0,Q.jsxs)(`span`,{className:`hidden-row-name`,children:[r(`已隐藏`,`Hidden`),` · `,e]})]})}function ED({value:e,onChange:t,onCommit:n,onCancel:r}){let i=Y();return(0,Q.jsx)(`input`,{className:`proj-name proj-name-input`,...wu,value:e,autoFocus:!0,onFocus:e=>e.currentTarget.select(),onChange:e=>t(e.target.value),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),n()):e.key===`Escape`&&(e.preventDefault(),r())},onBlur:n,title:i(`回车保存 · Esc 取消(只改显示名,不动目录)`)})}function DD({point:e,anchor:t,onClose:n,pinned:r,onTogglePin:i,onNewSession:a,onMoveUp:o,onMoveDown:s,onRename:c,onOpenFiles:l,onOpenTerminal:u,onReveal:d,onHide:f,hidden:p=!1,onUnhide:m,onDeleteAll:h,sessionCount:g}){let _=Y(),v=Yd(),y=e=>()=>{e(),n()};return(0,Q.jsxs)(qd,{point:e,anchor:t,closeOnLeave:!0,onClose:n,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在这个项目下开一条新会话`,`Start a new session under this project`),onClick:y(a),children:[`💬 `,_(`新建会话`,`New session`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(i),children:r?`📌 ${_(`取消置顶`,`Unpin`)}`:`📌 ${_(`置顶项目`,`Pin project`)}`}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在同组内上移一格`,`Move up one slot within this group`),onClick:y(o),children:[`↑ `,_(`上移`,`Move up`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在同组内下移一格`,`Move down one slot within this group`),onClick:y(s),children:[`↓ `,_(`下移`,`Move down`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(c),children:[`✏️ `,_(`重命名`,`Rename`),`…`]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(l),children:[`📁 `,_(`在文件列表中定位`,`Reveal in the file list`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,onClick:y(u),children:[`⌨ `,_(`在终端中打开`,`Open in terminal`)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`在系统文件管理器里定位这个目录(只定位,不执行任何文件)`),onClick:y(d),children:[`🔍 `,_(`在文件夹中打开`,`Open in folder`)]}),p?(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`把它放回主列表(会话都在,位置也还是原来的)`,`Put it back in the main list (sessions and position are kept)`),onClick:y(()=>m?.()),children:[`👁 `,_(`取消隐藏`,`Unhide`)]}):(0,Q.jsxs)(`button`,{type:`button`,className:`proj-menu-item`,title:_(`把这个项目从侧栏收起来(会话都还在;可撤销,也可在「已隐藏」里放回来)`,`Hide this project from the sidebar (sessions stay; undoable, or unhide from “Hidden”)`),onClick:y(f),children:[`🙈 `,_(`隐藏项目`,`Hide project`)]}),(0,Q.jsx)(`button`,{type:`button`,className:`proj-menu-item proj-menu-danger${v.armed?` proj-menu-item-armed`:``}`,title:v.armed?_(`再点一次就真删这些会话文件:不可恢复`):_(`彻底删除这个项目下的全部会话(不可恢复);第一下只是确认`),onClick:()=>v.run(()=>{n(),h()}),children:v.armed?_(`🗑 再点一次确认删除 · ${g}`,`🗑 Click again to delete · ${g}`):_(`🗑 删除全部会话… · ${g}`,`🗑 Delete all sessions… · ${g}`)})]})}function OD({conversations:e,activeId:t,piProjects:n,runningIds:r=[],onOpenTerminal:i,onFork:a,canFork:o,onOpenFiles:s,onNewProject:c}){let l=Y(),u=Zv(),d=Ro(e=>e.snapshot?.settings.projectPrefs??null),f=Ro(e=>e.snapshot?.settings.sessionPrefs??null),[p]=Eh(qr,10,1,50),m=Ho(),h=d??{order:[],pinned:[],aliases:{},hidden:[]},g={order:h.order.map(j),pinned:h.pinned.map(j),aliases:Object.fromEntries(Object.entries(h.aliases).map(([e,t])=>[j(e),t])),hidden:(h.hidden??[]).map(j)},_=g.pinned,v=()=>{let e=xo().snapshot?.settings.projectPrefs;return e?{order:e.order.map(j),pinned:e.pinned.map(j),aliases:Object.fromEntries(Object.entries(e.aliases).map(([e,t])=>[j(e),t])),hidden:(e.hidden??[]).map(j)}:g},[y,b]=(0,C.useState)({}),x=(0,C.useRef)(0),S=(0,C.useRef)(null),w=(0,C.useRef)(!1),T=()=>{S.current!==null&&(window.clearTimeout(S.current.timer),S.current=null)},[E,D]=(0,C.useState)(null),[O,k]=(0,C.useState)(!0);(0,C.useEffect)(()=>uc(()=>k(e=>!e)),[]);let[A,M]=(0,C.useState)(!1),[N,P]=(0,C.useState)(!1),F=(0,C.useRef)(null),I=()=>{P(!0),requestAnimationFrame(()=>F.current?.scrollIntoView({block:`nearest`}))},L=f??{pinned:[],archived:[],order:[]},[R,z]=(0,C.useState)(!0),[B,V]=(0,C.useState)(null),[H,U]=(0,C.useState)([]),W=(0,C.useRef)(null),[ee,G]=(0,C.useState)(null),[K,te]=(0,C.useState)(null),[ne,re]=(0,C.useState)(null),[ie,ae]=(0,C.useState)(null),[oe,se]=(0,C.useState)(null),[ce,le]=(0,C.useState)(null),ue=()=>xo().snapshot?.settings.sessionPrefs??L,de=e=>bu({sessionPrefs:{...ue(),...e}}),q=(e,t)=>{let n=ue();n.archived.includes(e)||(bu({sessionPrefs:{...n,archived:[...n.archived,e]}}),Z({text:l(`已归档「${t||`未命名会话`}」`,`Archived "${t||`Untitled session`}"`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>fe(e)},{label:l(`查看`,`View`),onClick:I}]}))},fe=e=>{let t=ue();t.archived.includes(e)&&bu({sessionPrefs:{...t,archived:t.archived.filter(t=>t!==e)}})},pe=xD(n,L),me=pe.reduce((e,t)=>e+t.items.length,0),[he,ge]=(0,C.useState)({}),_e=g.aliases,[ve,ye]=(0,C.useState)(null),be=()=>{if(!ve)return;let e=ve.draft.replace(/\s+/g,` `).trim(),t={...g.aliases};e===``?delete t[ve.cwd]:t[ve.cwd]=e,bu({projectPrefs:{...g,aliases:t}}),ye(null)},xe=(e,t)=>{let n=_.includes(e),r=g.order.filter(e=>!_.includes(e)),i=r.length>0?r:je.filter(e=>!_.includes(e.cwd)).map(e=>e.cwd),a=n?_:i,o=a.indexOf(e),s=o+t;if(o<0||s<0||s>=a.length)return;let c=[...a];c.splice(o,1),c.splice(s,0,e),bu({projectPrefs:n?{...g,pinned:c}:{...g,order:c}})},Se=(e,t)=>{let n=[...e.querySelectorAll(`details.proj[data-cwd]`)],r=null;for(let e of n){if(e.classList.contains(`proj-hidden`))continue;let n=e.dataset.cwd??``;if(n===``||n===oe)continue;let i=(e.querySelector(`.proj-head`)??e).getBoundingClientRect();if(r={cwd:n,after:!0},t<i.top+i.height/2)return{cwd:n,after:!1}}return r},Ce=(e,t,n)=>{let r=lm({visible:ke.map(e=>e.cwd),pinned:_,from:e,target:t,after:n});r&&bu({projectPrefs:{...g,...r}})},we=e=>{let t=_.includes(e)?_.filter(t=>t!==e):[e,..._];bu({projectPrefs:{...g,pinned:t}})},Te=e=>{let t=v(),n=j(e),r=t.hidden.filter(e=>j(e)!==n);r.length!==t.hidden.length&&(bu({projectPrefs:{...t,hidden:r}}),r.length===0&&M(!1))},Ee=(e,t,n)=>{let r=v(),i=j(e);r.hidden.some(e=>j(e)===i)||(bu({projectPrefs:{...r,hidden:[...r.hidden,e]}}),D(null),Z({text:l(`已隐藏项目「${t}」(${n} 条会话)`,`Hid project "${t}" (${n} session(s))`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>Te(e)},{label:l(`查看`,`View`),onClick:()=>M(!0)}]}))};new Set(n.map(e=>e.cwd));let De=new Map(e.filter(e=>e.title!==``).map(e=>[e.id,e.title])),Oe=e=>De.get(e.id)||e.title,ke=lD(n,e,l(`未分组`,`Ungrouped`));ke.splice(0,ke.length,...cm(ke,g));let Ae=uD(ke,g.hidden),je=Ae.visible,J=Ae.hidden,Me=(e,n)=>SD(e,n,y,t),Ne=je.every((e,t)=>Me(e,t)),X=je.flatMap(e=>e.sessions.filter(e=>L.pinned.includes(e.id)&&!L.archived.includes(e.id))).sort((e,t)=>L.pinned.indexOf(e.id)-L.pinned.indexOf(t.id)),Pe=new Map;for(let e of ke){let t=Qc(e.sessions.filter(e=>!L.archived.includes(e.id)&&!L.pinned.includes(e.id)),L.order),n=he[e.cwd]===!0;Pe.set(e.cwd,{expanded:n,visibleSessions:t,shown:n?t:t.slice(0,p)})}let Fe=[];X.length>0&&R&&Fe.push(...X.map(e=>e.id)),O&&je.forEach((e,t)=>{let n=Pe.get(e.cwd);n&&Me(e,t)&&Fe.push(...n.shown.map(e=>e.id))}),O&&A&&J.forEach(e=>{let t=Pe.get(e.cwd);t&&y[e.cwd]===!0&&Fe.push(...t.shown.map(e=>e.id))});let Ie=()=>{U([]),G(null),W.current=null},Le=e=>{let t=mD(Fe,W.current,e);U(t),t.length===1&&(W.current=e)},Re=e=>{U(t=>hD(t,e)),W.current=e},ze=()=>{let e=H;if(e.length===0)return;let t=new Set(e),n=ue();de({archived:[...n.archived.filter(e=>!t.has(e)),...e]}),Ie(),Z({text:l(`已归档 ${e.length} 条会话`,`Archived ${e.length} session(s)`),actions:[{label:l(`撤销`,`Undo`),onClick:()=>{de({archived:ue().archived.filter(e=>!t.has(e))})}},{label:l(`查看`,`View`),onClick:I}]})},Be=()=>{let e=H;e.length!==0&&(Ie(),Ud(e,l(`选中的 ${e.length} 条会话`,`${e.length} selected session(s)`)))};(0,C.useEffect)(()=>{if(H.length===0)return;let e=gD(H,Fe);e.length!==H.length&&U(e)});let Ve=()=>{b(Object.fromEntries([...je,...J].map(e=>[e.cwd,!Ne]))),z(!Ne)},He=e=>{te({id:e.id,cwd:e.cwd})},Ue=()=>{te(null),re(null),ae(null)},We=e=>{if(!K||K.id===e)return;let t=[...ue().pinned],n=t.indexOf(K.id),r=t.indexOf(e);n<0||r<0||(t.splice(n,1),t.splice(r,0,K.id),de({pinned:t}))},Ge=!!K&&L.pinned.includes(K.id),Ke=e=>{if(!K)return;K.cwd!==e.cwd&&ql(K.id,e.cwd);let t=ue();bu({sessionPrefs:{...t,order:tl(t.order,K.id)}})},qe=(e,t)=>{if(!K||K.id===t||K.cwd!==e.cwd)return;let n=ue(),r=Qc(e.sessions,n.order).map(e=>e.id),i=$c(r,K.id,t);i!==r&&bu({sessionPrefs:{...n,order:el(n.order,r,i)}})},Je=(e,n={})=>(0,Q.jsx)(wD,{session:e,active:e.id===t,selected:H.includes(e.id),running:r.includes(e.id),unseen:m[e.id]!==void 0,title:Oe(e)||l(`(无标题)`,`(untitled)`),pinned:L.pinned.includes(e.id),menuPoint:B?.id===e.id?B.point:null,onOpenMenu:t=>{H.length>1&&H.includes(e.id)?(V(null),G({point:t})):(G(null),H.length>0&&Ie(),W.current=e.id,V({id:e.id,point:t}))},onSwitch:({shift:t,toggle:n})=>{t?Le(e.id):n?Re(e.id):(U([]),G(null),W.current=e.id,ho(e.id),Yl(e.id))},onPin:()=>{let t=ue().pinned;de({pinned:t.includes(e.id)?t.filter(t=>t!==e.id):[...t,e.id]})},onAiRename:async()=>{await Kl(e.id)||Z({text:xo().lastError?.text??l(`AI 重命名失败,稍后再试`)})},onRename:t=>{Gl(e.id,t)},onArchive:()=>q(e.id,Oe(e)),onOpenInNewTab:()=>window.open(kc(window.location.href,e.id),`_blank`,`noopener`),onFork:a?()=>a(e.id):void 0,canFork:o,onDelete:()=>Hd(e.id,Oe(e)||e.id),onCloseMenu:()=>V(null),draggable:!n.noDrag,onDragStart:()=>He(e),onDragEnd:Ue,...(()=>{if(oe||n.noDrag)return{};let t={dragOver:ie===e.id,onDragOver:()=>ae(e.id),onDragLeave:()=>ae(t=>t===e.id?null:t)};if(n.pinnedGroup)return Ge?{...t,onDrop:()=>We(e.id)}:{};let r=n.project;return!r||!K||K.cwd!==r.cwd||K.id===e.id?{}:{...t,onDrop:()=>qe(r,e.id)}})()},e.id);return(0,Q.jsxs)(`aside`,{className:`sidebar`,children:[(0,Q.jsx)(`div`,{className:`sidebar-drag`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`sidebar-head sidebar-brand`,children:[(0,Q.jsxs)(`span`,{className:`brand`,children:[u.logoShown?(0,Q.jsx)(`img`,{className:`brand-icon`,src:u.logo||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}):null,u.shown?(0,Q.jsx)(`span`,{className:`brand-name`,children:u.name}):null]}),(0,Q.jsx)(jw,{variant:`sidebar`})]}),X.length>0?(0,Q.jsxs)(`section`,{className:`pin-group`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`pin-group-head sidebar-title`,title:R?l(`收起置顶`,`Collapse pinned`):l(`展开置顶`,`Expand pinned`),"aria-expanded":R,onClick:()=>z(e=>!e),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${R?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:l(`置顶会话`,`Pinned sessions`)})]}),R?(0,Q.jsx)(`div`,{className:`pin-group-body`,children:X.map(e=>Je(e,{pinnedGroup:!0}))}):null]}):null,(0,Q.jsxs)(`div`,{className:`sidebar-head${H.length>0?` sidebar-head-selecting`:``}`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`sidebar-title`,title:O?l(`收起项目`,`Collapse projects`):l(`展开项目`,`Expand projects`),"aria-expanded":O,onClick:()=>k(e=>!e),children:[(0,Q.jsx)(`span`,{className:`sidebar-title-caret${O?` sidebar-title-caret-open`:``}`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`sidebar-title-label`,children:l(`项目`,`Projects`)})]}),H.length>0?(0,Q.jsx)(bD,{count:H.length,onArchive:ze,onDelete:Be,onClear:Ie}):null,(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon sidebar-icon-inline${H.length>0?` sidebar-icon-away`:``}`,title:l(`新建项目(选择一个本地目录)`,`New project (pick a local folder)`),"aria-label":l(`新建项目`,`New project`),onClick:c,children:(0,Q.jsx)(op,{})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-icon sidebar-icon-inline${H.length>0?` sidebar-icon-away`:``}`,title:Ne?l(`全部收起(只留项目名)`,`Collapse all (project names only)`):l(`全部展开(显示各项目的会话)`,`Expand all (show each project's sessions)`),"aria-label":Ne?l(`全部收起`,`Collapse all`):l(`全部展开`,`Expand all`),"aria-pressed":Ne,onClick:()=>{O?Ve():(k(!0),b(Object.fromEntries(je.map(e=>[e.cwd,!0]))),z(!0))},children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M5.4 2.4 8 5.2 10.6 2.4`}),(0,Q.jsx)(`path`,{d:`M5.4 13.6 8 10.8 10.6 13.6`}),(0,Q.jsx)(`path`,{d:`M2.8 8h10.4`})]})}),(0,Q.jsx)(`button`,{type:`button`,className:`sidebar-row-fill`,"aria-hidden":`true`,tabIndex:-1,onClick:()=>k(e=>!e)})]}),(0,Q.jsxs)(`div`,{className:`sidebar-list${O?``:` sidebar-list-hidden`}`,onDragOver:e=>{if(!oe)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=Se(e.currentTarget,e.clientY);t&&le(t)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||le(null)},onDrop:e=>{if(!oe)return;e.preventDefault(),e.stopPropagation();let t=Se(e.currentTarget,e.clientY);t&&Ce(oe,t.cwd,t.after),se(null),le(null)},children:[je.length===0&&J.length===0?(0,Q.jsx)(`div`,{className:`sidebar-empty`,children:l(`还没有会话。发一条消息就会自动建一个;「临时会话(不保存)」不会留在这里。`,`No sessions yet. Sending a message creates one — but a “temporary session (not saved)” never shows up here.`)}):null,(A?[...je,...J]:je).map((e,t)=>{let n=J.some(t=>t.cwd===e.cwd),{expanded:a,visibleSessions:o,shown:c}=Pe.get(e.cwd),u=o.length-c.length,d=_e[e.cwd]||e.name||l(`未分组`,`Ungrouped`),f=n?y[e.cwd]===!0:Me(e,t),h=e.sessions.some(e=>r.includes(e.id)),g=e.sessions.filter(e=>m[e.id]!==void 0&&!L.archived.includes(e.id));return(0,Q.jsxs)(Q.Fragment,{children:[n&&J[0]?.cwd===e.cwd?(0,Q.jsx)(TD,{count:J.length,open:!0,onToggle:()=>M(!1)}):null,(0,Q.jsxs)(`details`,{"data-cwd":e.cwd,"data-hidden":n?`true`:void 0,className:`proj${n?` proj-hidden`:``}${ne===e.cwd?` proj-drag-over`:``}${oe===e.cwd?` proj-dragging`:``}${ce?.cwd===e.cwd?ce.after?` proj-drop-after`:` proj-drop-before`:``}`,open:f,onMouseDown:e=>{e.button!==0&&(x.current=performance.now())},onToggle:t=>{let n=t.currentTarget,r=n.open;w.current?(w.current=!1,n.open=f):performance.now()-x.current<400?n.open=f:b(t=>({...t,[e.cwd]:r}))},onDragOver:t=>{n||!oe&&K&&(t.preventDefault(),K.cwd!==e.cwd&&re(e.cwd))},onDragLeave:()=>{n||re(t=>t===e.cwd?null:t)},onDrop:t=>{n||oe||(t.preventDefault(),K&&Ke(e),Ue())},children:[(0,Q.jsxs)(`summary`,{className:`proj-head`,title:`${e.cwd||l(`未分组`,`Ungrouped`)}\n${n?l(`右键:项目菜单(可取消隐藏)`,`Right-click for the project menu (unhide)`):l(`拖动可换项目顺序 右键:项目菜单`,`Drag to reorder projects · Right-click for the project menu`)}`,draggable:!n&&ve?.cwd!==e.cwd,onDragStart:t=>{n||(t.dataTransfer.setData(`text/plain`,e.cwd),t.dataTransfer.effectAllowed=`move`,se(e.cwd))},onDragEnd:()=>{se(null),le(null)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),T(),D({cwd:e.cwd,point:{x:t.clientX,y:t.clientY},anchor:t.currentTarget})},onPointerDown:t=>{if(w.current=!1,T(),t.pointerType!==`touch`||ve?.cwd===e.cwd)return;let n=t.currentTarget,r={x:t.clientX,y:t.clientY},i=window.setTimeout(()=>{S.current=null,w.current=!0,D({cwd:e.cwd,point:r,anchor:n})},450);S.current={timer:i,x:r.x,y:r.y}},onPointerMove:e=>{let t=S.current;t&&(Math.abs(e.clientX-t.x)>10||Math.abs(e.clientY-t.y)>10)&&T()},onPointerUp:T,onPointerCancel:T,onPointerLeave:T,onClick:t=>{w.current||(ve?.cwd===e.cwd&&t.preventDefault(),go(e.sessions.map(e=>e.id)))},children:[(0,Q.jsx)(_D,{open:f}),ve?.cwd===e.cwd?(0,Q.jsx)(ED,{value:ve.draft,onChange:t=>ye({cwd:e.cwd,draft:t}),onCommit:be,onCancel:()=>ye(null)}):(0,Q.jsx)(`span`,{className:`proj-name`,children:d}),(()=>{let t=!f&&h,n=!f&&!h&&g.length>0,r=_.includes(e.cwd);return!t&&!n&&!r?null:(0,Q.jsxs)(Q.Fragment,{children:[t?(0,Q.jsx)(`span`,{className:`proj-busy`,role:`img`,"aria-label":l(`这个项目里有会话正在跑`,`A session in this project is running`),title:l(`这个项目里有会话正在跑(展开就能看到是哪一条)`,`A session in this project is running (expand to see which)`),children:(0,Q.jsx)(`span`,{className:`proj-busy-ring`,"aria-hidden":`true`})}):n?(0,Q.jsx)(`span`,{className:`proj-unseen`,role:`img`,"aria-label":l(`有会话跑完了、你还没看`,`A session finished and is not reviewed yet`),title:l(`有 ${g.length} 条会话跑完了、你还没看(点一下这个项目就消失)`,`${g.length} session(s) finished and unreviewed (click the project to clear)`)}):(0,Q.jsx)(`span`,{className:`proj-ind-slot`,"aria-hidden":`true`}),r?(0,Q.jsx)(`span`,{className:`proj-pin`,title:l(`已置顶`),"aria-label":l(`已置顶`),children:`📌`}):(0,Q.jsx)(`span`,{className:`proj-ind-slot`,"aria-hidden":`true`})]})})(),(0,Q.jsx)(`button`,{type:`button`,className:`proj-more`,title:l(`项目菜单(新建会话 / 重命名 / 定位…)`),onClick:t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect();D({cwd:e.cwd,point:{x:n.left,y:n.bottom+2},anchor:t.currentTarget.closest(`.proj-head`)})},children:`⋯`})]}),E?.cwd===e.cwd?(0,Q.jsx)(DD,{anchor:E.anchor,onClose:()=>D(null),pinned:_.includes(e.cwd),onTogglePin:()=>we(e.cwd),onNewSession:()=>Mo(e.cwd),onMoveUp:()=>xe(e.cwd,-1),onMoveDown:()=>xe(e.cwd,1),onRename:()=>ye({cwd:e.cwd,draft:d}),onOpenFiles:()=>{s?.(e.cwd)},onOpenTerminal:()=>i?.(e.cwd),onReveal:()=>void fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:e.cwd})}),onDeleteAll:()=>Ud(e.sessions.map(e=>e.id),`「${d}」下的全部会话`),onHide:()=>Ee(e.cwd,d,e.sessions.length),hidden:n,onUnhide:()=>Te(e.cwd),sessionCount:e.sessions.length}):null,(0,Q.jsxs)(`div`,{className:`proj-body`,children:[c.map(t=>Je(t,{project:e,noDrag:n})),u>0?(0,Q.jsx)(`button`,{type:`button`,className:`pi-row pi-row-more`,title:a?l(`收起,只显示前几个`,`Collapse back to the first few`):l(`展开,显示全部 ${o.length} 个会话`,`Expand to show all ${o.length} sessions`),onClick:()=>ge(t=>({...t,[e.cwd]:!a})),children:a?l(`收起`,`Collapse`):l(`还有 ${u} 个…`,`and ${u} more…`)}):a&&o.length>p?(0,Q.jsx)(`button`,{type:`button`,className:`pi-row pi-row-more`,onClick:()=>ge(t=>({...t,[e.cwd]:!1})),children:l(`收起`,`Collapse`)}):null]})]},e.cwd||d)]})}),J.length>0&&!A?(0,Q.jsx)(TD,{count:J.length,open:!1,onToggle:()=>M(!0)}):null,(0,Q.jsxs)(`div`,{className:`archived-block`,ref:F,children:[(0,Q.jsx)(pD,{total:me,open:N,onToggle:()=>P(e=>!e)}),N&&me>0?(0,Q.jsx)(vD,{groups:pe,onOpen:e=>{Ie(),Yl(e),P(!1)},onRestore:fe,onRestoreMany:e=>{let t=new Set(e);de({archived:ue().archived.filter(e=>!t.has(e))})}}):null]})]}),ee?(0,Q.jsx)(yD,{point:ee.point,count:H.length,onArchive:ze,onDelete:Be,onClear:Ie,onClose:()=>G(null)}):null]})}var kD=(0,C.memo)(OD),AD=`pop-agent.contentSearch.size`,jD=32,MD=96;function ND(e,t,n,r){return PD({w:e.w+t*2,h:e.h+n},r)}function PD(e,t){let n=Math.max(420,t.width-jD),r=Math.max(240,t.height-MD-jD/2),i=Number.isFinite(e.w)?e.w:920,a=Number.isFinite(e.h)?e.h:r;return{w:Math.round(Math.min(Math.max(i,420),n)),h:Math.round(Math.min(Math.max(a,240),r))}}function FD(e){if(e===null)return null;try{let t=JSON.parse(e),n=Number(t?.w),r=Number(t?.h);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?null:{w:n,h:r}}catch{return null}}function ID(e){try{let t=JSON.parse(e);return typeof t==`object`&&t?t:null}catch{return null}}var LD=250;function RD({open:e,root:t,onClose:n,onOpen:r,presetGlob:i=null}){let a=Y(),[o,s]=(0,C.useState)(``),[c,l]=(0,C.useState)(``);(0,C.useEffect)(()=>{i&&l(i.value)},[i]);let[u,d]=(0,C.useState)([]),[f,p]=(0,C.useState)(!1),[m,h]=(0,C.useState)(null),[g,_]=(0,C.useState)(!1),[v,y]=(0,C.useState)(0),[b,x]=(0,C.useState)(!1),S=(0,C.useRef)(null),w=(0,C.useRef)(null),[T,E]=(0,C.useState)(()=>{try{return FD(localStorage.getItem(AD))}catch{return null}}),D=(0,C.useRef)(null),O=(0,C.useRef)(T),[k,A]=(0,C.useState)(!1),j=(0,C.useRef)(null),M=e=>{O.current=e,E(e)};if((0,C.useEffect)(()=>{e&&(S.current?.focus(),S.current?.select())},[e]),(0,C.useEffect)(()=>{if(!e||!t||b)return;let n=o.trim();if(n===``){d([]),p(!1),h(null),_(!1);return}let r=!1;_(!0);let i=setTimeout(()=>{(async()=>{try{let e=new URLSearchParams({q:n,root:t,glob:c}),i=await fetch(`/api/files/grep?${e}`),o=ID(await i.text());if(r)return;if(o===null){d([]),p(!1),y(0),h(a(`搜索接口没有返回数据(服务端大概是旧进程):重启一次 pop-agent 再试`,`The search endpoint returned no JSON (the server is probably an older build): restart pop-agent and retry`));return}d(o.matches??[]),p(o.truncated===!0),h(i.ok?null:o.error?.message??a(`搜索失败`,`Search failed`)),y(0)}catch(e){if(r)return;d([]),p(!1),h(e instanceof Error?e.message:a(`搜索失败`,`Search failed`))}finally{r||_(!1)}})()},LD);return()=>{r=!0,clearTimeout(i)}},[e,o,c,t,a,b]),(0,C.useEffect)(()=>{d([]),p(!1),h(null),y(0)},[t]),(0,C.useEffect)(()=>{e&&(w.current?.querySelector(`[data-hit="${v}"]`))?.scrollIntoView({block:`nearest`})},[v,e,u]),!e)return null;let N=e=>{e&&(r(e.path,e.line),n())},P=e=>{if(!(b||e.nativeEvent.isComposing)){if(e.key===`Escape`)e.preventDefault(),n();else if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(u.length===0)return;e.preventDefault();let t=e.key===`ArrowDown`?1:-1;y(e=>(e+t+u.length)%u.length)}else e.key===`Enter`&&(e.preventDefault(),N(u[v]))}},F=o.trim(),I=e=>{let t=j.current;if(!t)return;e.preventDefault();let n=t.getBoundingClientRect();D.current={x:e.clientX,y:e.clientY,w:n.width,h:n.height},A(!0),e.currentTarget.setPointerCapture?.(e.pointerId)},L=e=>{let t=D.current;t&&M(ND({w:t.w,h:t.h},e.clientX-t.x,e.clientY-t.y,{width:window.innerWidth,height:window.innerHeight}))},R=()=>{if(D.current){D.current=null,A(!1);try{let e=O.current;e?localStorage.setItem(AD,JSON.stringify(e)):localStorage.removeItem(AD)}catch{}}},z=T===null?null:PD(T,{width:window.innerWidth,height:window.innerHeight}),B=z===null?void 0:{width:z.w,height:z.h,maxHeight:`none`},V=F===``?a(`输入关键字,搜工作区里的文件内容`,`Type to search file contents in the workspace`):m?``:g?a(`搜索中…`,`Searching…`):u.length===0?a(`没有匹配的行`,`No matching lines`):`${a(`${u.length} 条结果`,`${u.length} results`)}${f?a(`(只显示前若干条,换个更具体的关键字)`,` (first results only — narrow the query)`):``}`;return(0,Q.jsx)(`div`,{className:`content-search-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":a(`搜索文件内容`,`Search file contents`),onKeyDown:P,onMouseDown:e=>{e.target===e.currentTarget&&n()},children:(0,Q.jsxs)(`div`,{className:`content-search${k?` content-search-resizing`:``}`,ref:j,style:B,children:[(0,Q.jsxs)(`div`,{className:`content-search-head`,children:[(0,Q.jsx)(`input`,{ref:S,className:`content-search-input`,value:o,onChange:e=>s(e.target.value),onCompositionStart:()=>x(!0),onCompositionEnd:e=>{x(!1),s(e.currentTarget.value)},placeholder:a(`搜索文件内容…`,`Search file contents…`),"aria-label":a(`关键字`,`Query`),spellCheck:!1}),(0,Q.jsx)(`input`,{className:`content-search-glob mono`,value:c,onChange:e=>l(e.target.value),placeholder:a(`文件掩码,如 *.ts`,`File mask, e.g. *.ts`),"aria-label":a(`文件掩码`,`File mask`),title:a("只看匹配的文件:`*.ts` 看文件名,`src/**/*.go` 看路径,留空则搜全部","Limit to matching files: `*.ts` matches names, `src/**/*.go` matches paths, empty = all"),spellCheck:!1}),(0,Q.jsx)(`kbd`,{className:`content-search-esc`,children:`Esc`})]}),m?(0,Q.jsx)(`div`,{className:`content-search-error`,children:m}):null,(0,Q.jsx)(`div`,{className:`content-search-list`,ref:w,children:u.map((e,t)=>(0,Q.jsxs)(`button`,{type:`button`,"data-hit":t,className:`content-search-row${t===v?` content-search-row-on`:``}`,onClick:()=>N(e),title:`${e.path}:${e.line}`,onMouseMove:()=>{t!==v&&y(t)},children:[(0,Q.jsx)(`span`,{className:`content-search-line mono`,children:zD(e,F)}),(0,Q.jsxs)(`span`,{className:`content-search-where mono`,children:[e.path,`:`,e.line]})]},`${e.path}:${e.line}`))}),(0,Q.jsxs)(`div`,{className:`content-search-foot`,children:[(0,Q.jsx)(`span`,{className:`content-search-status`,children:V}),(0,Q.jsxs)(`span`,{className:`content-search-keys`,children:[(0,Q.jsx)(`kbd`,{children:`↑`}),(0,Q.jsx)(`kbd`,{children:`↓`}),` `,a(`切换结果`,`switch`),(0,Q.jsx)(`kbd`,{children:`⏎`}),` `,a(`打开`,`open`)]})]}),(0,Q.jsx)(`div`,{className:`content-search-grip`,"aria-hidden":`true`,title:a(`拖动调整大小(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:I,onPointerMove:L,onPointerUp:R,onPointerCancel:R,onDoubleClick:()=>M(null)})]})})}function zD(e,t){if(t===``||e.column<0)return e.text;let n=e.column+t.length;return(0,Q.jsxs)(Q.Fragment,{children:[e.text.slice(0,e.column),(0,Q.jsx)(`mark`,{className:`content-search-mark`,children:e.text.slice(e.column,n)}),e.text.slice(n)]})}function BD({engine:e,onClose:t,onInstalled:n}){let r=Y(),[i,a]=(0,C.useState)(!1),[o,s]=(0,C.useState)(null),c=(0,C.useRef)(null),[l,u]=(0,C.useState)(null);(0,C.useEffect)(()=>{fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(t=>{let n=t?.engines.find(t=>t.name===e.name)??null;u(n)}).catch(()=>void 0)},[e.name]),(0,C.useEffect)(()=>{c.current?.focus()},[]),(0,C.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!i&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i,t]);let d=async()=>{a(!0),s(null);try{let t=await fetch(`/api/engines/install`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:e.name})}),i=await t.json(),a=t.ok&&i.ok===!0;s({ok:a,message:i.message??(a?r(`装好了`,`Installed`):r(`安装失败`,`Install failed`)),restartRequired:i.restartRequired===!0}),a&&n()}catch(e){s({ok:!1,restartRequired:!1,message:r(`安装请求失败:${e instanceof Error?e.message:String(e)}`,`Install request failed: ${e instanceof Error?e.message:String(e)}`)})}finally{a(!1)}},f=o?.ok===!0&&o.restartRequired;return(0,Q.jsx)(`div`,{className:`modal-backdrop`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`engine-install-title`,onMouseDown:e=>{e.target===e.currentTarget&&!i&&t()},children:(0,Q.jsxs)(`div`,{className:`modal`,children:[(0,Q.jsx)(`h2`,{className:`modal-title`,id:`engine-install-title`,children:r(`还没装 ${e.label}`,`${e.label} is not installed`)}),(0,Q.jsx)(`p`,{className:`modal-risk`,children:r(`切到 ${e.label} 需要它自己的命令行程序,这台机器上没找到。`,`Switching to ${e.label} needs its own CLI, and it is not on this machine.`)}),(0,Q.jsx)(`p`,{children:r(`装了才会启动它;不装的话继续用 pi 就行,什么时候想用再装。`,`Installing lets it start. If you skip it, keep using pi and install whenever you want.`)}),o?(0,Q.jsx)(`p`,{className:o.ok?`modal-ok`:`modal-risk`,children:o.message}):l&&l.guide.length>0?(0,Q.jsxs)(`p`,{className:`modal-hint`,children:[r(`装到 ~/.pop-agent(你自己的 npm 目录,不碰系统、不用 sudo)。`,`Installs into ~/.pop-agent (your own npm prefix — no system changes, no sudo).`),l.afterInstall?` ${r(l.afterInstall)}`:``]}):null,(0,Q.jsxs)(`div`,{className:`modal-actions`,children:[(0,Q.jsx)(`button`,{ref:c,type:`button`,className:`btn`,onClick:t,disabled:i,children:f?r(`关闭`,`Close`):r(`以后再装`,`Not now`)}),l?.installable===!1?null:(0,Q.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:i||o?.ok===!0,children:i?r(`正在安装…`,`Installing…`):r(`安装 ${e.label}`,`Install ${e.label}`)})]}),l?.installable===!1?(0,Q.jsxs)(`p`,{className:`modal-hint`,children:[r(`这个引擎没有公开的 npm 包,只能你自己装:`,`This engine has no public npm package — install it yourself:`),l.guide.join(`;`)]}):null]})})}function VD(){return(0,Q.jsxs)(`svg`,{className:`engine-picker-icon`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.3,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.6`,y:`5.2`,width:`10.8`,height:`7.6`,rx:`2.3`}),(0,Q.jsx)(`path`,{d:`M8 5.2V3.3`}),(0,Q.jsx)(`circle`,{cx:`8`,cy:`2.4`,r:`0.85`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`6`,cy:`9`,r:`0.8`,fill:`currentColor`,stroke:`none`}),(0,Q.jsx)(`circle`,{cx:`10`,cy:`9`,r:`0.8`,fill:`currentColor`,stroke:`none`})]})}function HD(){return(0,Q.jsx)(`svg`,{className:`engine-picker-chevron`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M4.4 6.2 8 9.8l3.6-3.6`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function UD(){return(0,Q.jsx)(`svg`,{className:`engine-picker-check`,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.8,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M3.4 8.4 6.6 11.6 12.6 4.8`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function WD(e){return e?/^\d/.test(e)?`v${e}`:e:``}function GD(e,t,n){return WD((t?n:null)??e.version??null)}function KD({placement:e=`appbar`}={}){let t=Y(),n=Ro(e=>e.snapshot),[r,i]=(0,C.useState)(!1),a=(0,C.useRef)(null),o=(0,C.useRef)(null),s=(0,C.useRef)(null),[c,l]=(0,C.useState)(null),u=n?.engines??[],d=n?.engine??``,f=u.find(e=>e.name===d),p=n?n.running.status!==`idle`:!1,[m,h]=(0,C.useState)({}),[g,_]=(0,C.useState)(null),v=()=>{fetch(`/api/engines`).then(async e=>e.ok?await e.json():null).then(e=>{if(!e)return;let t={};for(let n of e.engines)n.installed||(t[n.name]=!0);h(t)}).catch(()=>void 0)};if((0,C.useEffect)(()=>{r&&v()},[r]),(0,C.useLayoutEffect)(()=>{if(!r){l(null);return}let t=()=>{let t=o.current?.getBoundingClientRect(),n=s.current?.getBoundingClientRect();if(!t||!n)return;if(e===`statusbar`){let{left:e,bottom:r,arrow:i}=Rf({trigger:{left:t.left,top:t.top,width:t.width,height:t.height},popover:{width:n.width},viewport:{width:window.innerWidth,height:window.innerHeight},gap:8});l({left:e,top:Math.max(8,window.innerHeight-r-n.height),arrow:i});return}let r=o.current?.closest(`.appbar`)?.getBoundingClientRect().bottom??0,i=Math.max(t.top+t.height,r);l(zf({trigger:{left:t.left,top:i-t.height,width:t.width,height:t.height},popover:{width:n.width},viewport:{width:window.innerWidth,height:window.innerHeight}}))};return t(),window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[r,e]),(0,C.useEffect)(()=>{if(!r)return;let e=e=>{a.current&&!a.current.contains(e.target)&&i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]),u.length===0)return null;let y=t(f?.label??d),b=f?.badge??d.toUpperCase();return(0,Q.jsxs)(`div`,{className:`engine-picker${e===`statusbar`?` engine-picker-in-statusbar`:``}`,ref:a,children:[(0,Q.jsxs)(`button`,{ref:o,type:`button`,className:`side-foot-btn engine-picker-btn${r?` side-foot-btn-on`:``}`,onClick:()=>i(e=>!e),title:p?t(`切换智能体引擎(回合进行中,先等它结束)`,`Switch agent engine (a turn is running — wait for it to end)`):t(`切换智能体引擎`,`Switch agent engine`),"aria-haspopup":`listbox`,"aria-expanded":r,"aria-label":t(`智能体引擎:${y}`,`Agent engine: ${y}`),children:[(0,Q.jsx)(`span`,{className:`side-foot-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(VD,{})}),(0,Q.jsx)(`span`,{className:`engine-picker-badge`,children:b}),(0,Q.jsx)(HD,{})]}),r?(0,Q.jsxs)(`div`,{ref:s,className:`engine-pop`,role:`listbox`,"aria-label":t(`智能体引擎`),style:c?{left:c.left,top:c.top}:{visibility:`hidden`},children:[c?(0,Q.jsx)(`span`,{className:`engine-pop-arrow`,style:{left:c.arrow},"aria-hidden":`true`}):null,(0,Q.jsxs)(`div`,{className:`engine-pop-scroll`,children:[(0,Q.jsxs)(`div`,{className:`engine-pop-head`,children:[(0,Q.jsx)(`span`,{className:`engine-pop-title`,children:t(`智能体引擎`)}),(0,Q.jsx)(`span`,{className:`engine-pop-note`,children:t(`切换后项目与会话跟着新引擎`)})]}),u.map(e=>{let r=e.name===d,a=GD(e,r,n?.versions.engine);return(0,Q.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":r,disabled:p&&!r,className:`engine-option${r?` engine-option-on`:``}`,onClick:()=>{i(!1),!r&&(m[e.name]?_(e):tu(e.name))},title:p&&!r?t(`回合进行中,先中断或等它结束`,`A turn is running — interrupt it or wait for it to end`):void 0,children:[(0,Q.jsxs)(`span`,{className:`engine-option-top`,children:[(0,Q.jsx)(`span`,{className:`engine-option-icon`,"aria-hidden":`true`,children:(0,Q.jsx)(VD,{})}),(0,Q.jsx)(`span`,{className:`engine-option-badge`,children:e.badge}),(0,Q.jsx)(`span`,{className:`engine-option-label`,children:t(e.label)}),m[e.name]?(0,Q.jsx)(`span`,{className:`engine-option-version`,children:t(`未安装`,`not installed`)}):a?(0,Q.jsx)(`span`,{className:`engine-option-version`,children:a}):null,(0,Q.jsx)(`span`,{className:`engine-option-tail`,children:r?(0,Q.jsx)(UD,{}):null})]}),e.description?(0,Q.jsx)(`span`,{className:`engine-option-desc`,children:t(e.description)}):null,(0,Q.jsxs)(`span`,{className:`engine-option-caps`,children:[e.capabilities.approvals?t(`审批拦截`,`Approval gate`):t(`自行授权`,`Self-approved`),e.capabilities.modelSwitch?` · ${t(`模型可切`,`switchable models`)}`:``,e.capabilities.thinkingLevel?` · ${t(`思考强度`,`thinking level`)}`:``,e.capabilities.resume?` · ${t(`可续历史`,`resumable history`)}`:``]})]},e.name)}),p?(0,Q.jsx)(`div`,{className:`engine-pop-hint`,children:t(`有回合在跑:先中断或等结束再切`)}):null]})]}):null,g?(0,Q.jsx)(BD,{engine:{name:g.name,label:g.label},onClose:()=>_(null),onInstalled:v}):null]})}function qD(e){return e.replace(/\.?0+$/,``)}function JD(e){return e<1e3?String(e):e<1e6?`${qD((e/1e3).toFixed(1))}K`:`${qD((e/1e6).toFixed(2))}M`}function YD({snapshot:e,appbarHidden:t,onToggleAppbar:n,terminalOpen:r,onToggleTerminal:i,onOpenHistory:a,onOpenPrompt:o,onOpenSettings:s}){let c=Y(),{language:l}=Ae(),u=e?Object.values(e.runningByConversation??{}).filter(e=>e.status!==`idle`).length:0,d=(e?.queued??[]).length,[f]=bp(Br,Wr,Hr),[p]=tx(),m=e=>({order:p.indexOf(e)}),h=e?.sessionStats??null,[g,..._]=String(e?.model??``).split(`/`),v=(e?.providers??[]).find(e=>e.provider===g)?.models.find(e=>e.id===_.join(`/`)),y=v?.contextWindow&&v.contextWindow>0?v.contextWindow:null,b=h?.contextTokens??0,x=y?Math.min(1,b/y):0,S=y?Math.round(x*100):null,w=37.7,[T,E]=(0,C.useState)(!1),[D,O]=(0,C.useState)(null),k=(0,C.useRef)(null),A=(0,C.useRef)(null);return(0,C.useLayoutEffect)(()=>{if(!T){O(null);return}let e=()=>{let e=k.current?.getBoundingClientRect(),t=A.current?.getBoundingClientRect();e&&t&&O(Rf({trigger:{left:e.left,top:e.top,width:e.width,height:e.height},popover:{width:t.width},viewport:{width:window.innerWidth,height:window.innerHeight}}))};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[T]),(0,C.useEffect)(()=>{if(!T)return;let e=e=>{let t=e.target;t&&(A.current?.contains(t)||k.current?.contains(t)||E(!1))},t=e=>{e.key===`Escape`&&E(!1)};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[T]),(0,Q.jsxs)(`footer`,{className:`statusbar`,children:[s?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`settings`),onClick:s,title:c(`设置`,`Settings`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:(0,Q.jsx)(nx,{name:`settings`})}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`设置`,`Settings`)})]}):null,(0,Q.jsxs)(`span`,{className:`status-controls`,children:[e?.engineCapabilities.approvals===!1?(0,Q.jsx)(`span`,{className:`tool-chip tool-static`,style:{...m(`approval`),display:f.approval?void 0:`none`},title:c(`该引擎自行决定授权,本工作台拦不住它的危险操作`,`This engine decides approvals itself; the workbench cannot block its risky operations`),children:c(`🔒 审批:引擎自理`,`🔒 Approvals: engine-managed`)}):(0,Q.jsx)(`button`,{type:`button`,className:`tool-chip${e?.approvalMode===`allow`?` tool-chip-warn`:``}`,style:{...m(`approval`),display:f.approval?void 0:`none`},onClick:()=>nu(e?.approvalMode===`allow`?`ask`:`allow`,e?.active.conversationId??null),title:c(`审批模式(全局生效,重启回到默认:全部放行)——点一下在「全部放行 / 询问」之间切换`,`Approval mode (global; resets to allow-all on restart) — click to switch between allow-all and ask`),children:e?.approvalMode===`allow`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`🔓`}),(0,Q.jsx)(`span`,{children:c(`全部放行`,`Allow all`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`🔒`}),(0,Q.jsx)(`span`,{children:c(`询问`,`Ask`)})]})}),f.engine?(0,Q.jsx)(`span`,{className:`statusbar-slot`,style:m(`engine`),children:(0,Q.jsx)(KD,{placement:`statusbar`})}):null]}),f.queued?(0,Q.jsxs)(`span`,{className:`status-item status-queued`,style:m(`queued`),title:c(`所有项目 / 所有会话的待发队列合计`,`Queued messages across all sessions and projects`),children:[(0,Q.jsx)(`span`,{className:`status-ico`,children:`⏳`}),` `,c(`排队`,`Queued`),` `,d]}):null,f.running?(0,Q.jsxs)(`span`,{className:`status-item status-running${u>0?` is-working`:``}`,style:m(`running`),title:c(`所有项目 / 所有会话里正在跑的回合数`,`Turns currently running across all sessions and projects`),children:[(0,Q.jsx)(`span`,{className:`status-spinner`,"aria-hidden":`true`}),c(`工作中`,`Running`),` `,u]}):null,f.context?(0,Q.jsxs)(`span`,{className:`status-context-wrap`,style:m(`context`),children:[(0,Q.jsxs)(`button`,{ref:k,type:`button`,className:`status-context`,title:y?c(`当前会话上下文:已用 ${b.toLocaleString()} / 窗口 ${y.toLocaleString()}(${S}%)· 点开看整段会话累计(每条回复底部的 I/O/C 只算那一轮)`,`Context of this session: ${b.toLocaleString()} used / ${y.toLocaleString()} window (${S}%) · click for the whole-session total (the I/O/C line under each reply covers that turn only)`):c(`当前会话上下文(模型窗口未知)`,`Context of this conversation (model window unknown)`),onClick:()=>E(e=>!e),children:[(0,Q.jsxs)(`svg`,{className:`status-ring`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`circle`,{className:`status-ring-bg`,cx:`8`,cy:`8`,r:`6`}),(0,Q.jsx)(`circle`,{className:`status-ring-fg`,cx:`8`,cy:`8`,r:`6`,style:{strokeDasharray:`${(x*w).toFixed(2)} ${w}`}})]}),(0,Q.jsx)(`span`,{className:`status-context-used`,children:JD(b)}),(0,Q.jsxs)(`span`,{className:`status-context-total`,children:[`/`,y?JD(y):`—`]})]}),T?(0,Q.jsxs)(`div`,{ref:A,className:`status-usage-pop`,role:`dialog`,"aria-label":c(`会话信息`,`Session info`),style:D?{left:D.left,bottom:D.bottom}:{visibility:`hidden`},children:[D?(0,Q.jsx)(`span`,{className:`status-usage-arrow`,style:{left:D.arrow},"aria-hidden":`true`}):null,(0,Q.jsx)(`div`,{className:`status-usage-title`,children:c(`会话信息(整段会话)`,`Session info (whole session)`)}),[[c(`用户消息`,`User messages`),String(h?.userMessages??0)],[c(`助手消息`,`Assistant messages`),String(h?.assistantMessages??0)],[c(`工具调用`,`Tool calls`),String(h?.toolCalls??0)],[c(`输入(未命中缓存)`,`Input (cache misses)`),JD(h?.inputTokens??0)],[c(`输出`,`Output`),JD(h?.outputTokens??0)],[c(`缓存读(命中)`,`Cache read (hits)`),JD(h?.cacheRead??0)],[c(`缓存写`,`Cache write`),JD(h?.cacheWrite??0)],[c(`总花费`,`Total cost`),h?.cost?z_(h.cost):`—`],[c(`上下文(最后一次)`,`Context (last call)`),y?`${JD(b)} / ${JD(y)}`:JD(b)]].map(([e,t])=>(0,Q.jsxs)(`div`,{className:`status-usage-row`,children:[(0,Q.jsx)(`span`,{children:e}),(0,Q.jsx)(`span`,{className:`mono`,children:t})]},e)),(0,Q.jsx)(`div`,{className:`status-usage-note`,children:l===`en`?(0,Q.jsxs)(Q.Fragment,{children:[`The numbers above are cumulative for `,(0,Q.jsx)(`b`,{children:`the whole session`}),`; the I / O / C line under each reply is `,(0,Q.jsx)(`b`,{children:`that turn's own`}),` usage. “Input” `,(0,Q.jsx)(`b`,{children:`excludes`}),` cache hits (hits are counted under cache read — the whole prefix is re-read every turn, so that number is large). “Context” counts only`,` `,(0,Q.jsx)(`b`,{children:`the last`}),` call: input + cache read + cache write, which is why it is usually much larger than the cumulative input.`,(0,Q.jsx)(`br`,{}),(0,Q.jsx)(`b`,{children:`Subagents`}),` are separate sessions billed separately, so they are `,(0,Q.jsx)(`b`,{children:`not`}),` part of the numbers above (open the subagent cards in the conversation for their own usage).`]}):(0,Q.jsxs)(Q.Fragment,{children:[`上面这些是`,(0,Q.jsx)(`b`,{children:c(`整段会话`)}),c(`的累计值;每条回复底部那行`),` `,(0,Q.jsx)(`b`,{children:`I / O / C`}),` `,c(`是`),(0,Q.jsx)(`b`,{children:c(`那一轮自己的`)}),`用量。 「输入」`,(0,Q.jsx)(`b`,{children:c(`不含`)}),`缓存命中部分(命中单列在缓存读里,每一轮都重新读一遍整个前缀,所以会很大)。 「上下文」只算`,(0,Q.jsx)(`b`,{children:c(`最后一次`)}),`调用:输入 + 缓存读 + 缓存写,所以它常比累计输入大得多。`,(0,Q.jsx)(`br`,{}),`另外,`,(0,Q.jsx)(`b`,{children:c(`子代理`)}),`是独立会话、单独计费,`,(0,Q.jsx)(`b`,{children:c(`不在`)}),`上面的统计里(去对话里的子代理卡片看它们各自的用量)。`]})})]}):null]}):null,a&&f.history?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle status-view`,style:m(`history`),onClick:a,title:c(`完整历史:整份会话(含工具调用、思考与分支)在右侧面板展开`,`Full history: the whole session (tools, thinking, branches) in the side panel`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`📜`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`完整历史`,`History`)})]}):null,o&&f.prompt?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle status-view`,style:m(`prompt`),onClick:o,title:c(`系统提示词:这次运行实际在用的那段(AGENTS.md / 技能都拼好了)`,`System prompt: the text this run actually uses (context files and skills included)`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`🧾`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`系统提示词`,`Prompt`)})]}):null,f.terminal?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`terminal`),"aria-pressed":r,onClick:i,title:r?c(`隐藏终端`,`Hide terminal`):c(`显示终端`,`Show terminal`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:`🖥️`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:c(`终端`,`Terminal`)})]}):null,f.top?(0,Q.jsxs)(`button`,{type:`button`,className:`status-toggle`,style:m(`top`),onClick:n,title:t?c(`显示顶部栏`,`Show the top bar`):c(`隐藏顶部栏`,`Hide the top bar`),children:[(0,Q.jsx)(`span`,{className:`status-toggle-icon`,children:t?`⬇️`:`⬆️`}),(0,Q.jsx)(`span`,{className:`status-toggle-label`,children:t?c(`显示顶部`,`Show top`):c(`隐藏顶部`,`Hide top`)})]}):null]})}var XD=`pop-agent.bottom-term.height`,ZD=240,QD=120,$D=900,eO=.7,tO=0;function nO(e){return tO+=1,`${e}:${tO}`}function rO({open:e,cwd:t,onHide:n,request:r=null,onOpenSettings:i}){let a=Y(),[o,s]=Eh(XD,ZD,QD,$D),[c,l]=(0,C.useState)([]),[u,d]=(0,C.useState)(null),f=(0,C.useCallback)((e,t=null)=>{let n={id:nO(`bterm`),cwd:e,initialCommand:t},r={id:nO(`bgroup`),panes:[n],activePaneId:n.id};l(e=>[...e,r]),d(r.id)},[]),p=(0,C.useRef)(0);(0,C.useEffect)(()=>{e&&(r&&r.seq!==p.current?(p.current=r.seq,f(r.cwd,r.initialCommand??null)):c.length===0&&f(t))},[e,c.length,r,t,f]),(0,C.useEffect)(()=>{c.length!==0&&(u&&c.some(e=>e.id===u)||d(c[c.length-1].id))},[c,u]);let m=e=>{let t=c.filter(t=>t.id!==e);l(t),t.length===0&&n()},h=(e,t)=>{let n=c.find(t=>t.id===e);if(!n)return;if(n.panes.length<=1){m(e);return}let r=n.panes.findIndex(e=>e.id===t),i=n.panes.filter(e=>e.id!==t);l(n=>n.map(n=>n.id===e?{...n,panes:i,activePaneId:n.activePaneId===t?i[Math.min(Math.max(r,0),i.length-1)].id:n.activePaneId}:n))},g=(e,t)=>{let n=c.find(t=>t.id===e);n&&u===e&&n.activePaneId===t||(d(e),l(n=>n.map(n=>n.id===e?{...n,activePaneId:t}:n)))};return(0,Q.jsxs)(`section`,{className:`bottom-term`,style:{height:o},hidden:!e,"aria-label":a(`终端`,`Terminal`),children:[(0,Q.jsx)(`div`,{className:`bottom-term-handle`,role:`separator`,"aria-orientation":`horizontal`,title:a(`拖动调整高度`,`Drag to resize`),onPointerDown:e=>{e.preventDefault();let t=e.clientY,n=o,r=e=>{let r=Math.min($D,Math.round(window.innerHeight*eO)),i=n+(t-e.clientY);s(Math.max(QD,Math.min(r,i)))},i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i)};window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i)}}),(0,Q.jsxs)(`div`,{className:`bottom-term-bar`,children:[(0,Q.jsx)(`div`,{className:`bottom-term-tabs`,role:`tablist`,children:c.map((e,t)=>{let n=e.id===u;return(0,Q.jsxs)(`div`,{role:`tab`,"aria-selected":n,className:`bottom-term-tab${n?` is-active`:``}`,title:e.panes[0]?.cwd??void 0,onClick:()=>d(e.id),children:[(0,Q.jsxs)(`span`,{children:[a(`终端`,`Terminal`),` `,t+1,e.panes.length>1?` · ${e.panes.length}`:``]}),(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-tab-x`,title:a(`关闭这个终端(含所有分屏)`,`Kill this terminal (all splits)`),"aria-label":a(`关闭这个终端`,`Kill this terminal`),onClick:t=>{t.stopPropagation(),m(e.id)},children:`×`})]},e.id)})}),(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn`,title:a(`新建终端`,`New terminal`),"aria-label":a(`新建终端`,`New terminal`),onClick:()=>f(t),children:`+`}),(0,Q.jsx)(`span`,{className:`bottom-term-spacer`}),i?(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn bottom-term-settings`,title:a(`设置`,`Settings`),"aria-label":a(`设置`,`Settings`),onClick:i,children:(0,Q.jsx)(nx,{name:`settings`})}):null,(0,Q.jsx)(`button`,{type:`button`,className:`bottom-term-btn`,title:a(`隐藏终端(进程保留)`,`Hide terminal (shells keep running)`),"aria-label":a(`隐藏终端`,`Hide terminal`),onClick:n,children:`⌄`})]}),(0,Q.jsx)(`div`,{className:`bottom-term-body`,children:c.map(t=>(0,Q.jsx)(`div`,{className:`bottom-term-group`,hidden:t.id!==u,children:t.panes.map(n=>{let r=t.activePaneId===n.id;return(0,Q.jsx)(`div`,{className:`bottom-term-pane${r?` is-focused`:``}`,onPointerDown:()=>g(t.id,n.id),children:(0,Q.jsx)(AT,{termId:n.id,cwd:n.cwd,initialCommand:n.initialCommand,active:e&&t.id===u&&r,onClose:()=>h(t.id,n.id)})},n.id)})},t.id))})]})}function iO(){let e=navigator.userAgent;if(!e.includes(`Electron/`))return;let t=/Macintosh|Mac OS X/.test(e);document.documentElement.dataset.shell=t?`electron-mac`:`electron`}function aO(){return(document.documentElement.dataset.shell??``).startsWith(`electron`)}function oO(e){return Number.isFinite(e.chatPx)&&Number.isFinite(e.projectPx)&&Number.isFinite(e.sessionPx)}function sO(e){return`${e.chatPx}/${e.projectPx}/${e.sessionPx}`}function cO(e,t){if(!t||!oO(t))return null;let n=sO(t);return n===e?null:n}var lO=null;function uO(e){let t=cO(lO,e);t===null?e||(lO=null):(lO=t,e&&(nb(e.chatPx),Ib(e.projectPx),Lb(e.sessionPx)))}var dO=[],fO=[];function pO(){let e=Y(),t=Zv(),n=t.name,r=aO(),[i,a]=(0,C.useState)(()=>Ss({stored:Yr(vs),tablet:typeof window<`u`&&Cs(e=>window.matchMedia(e).matches)})),[o,s]=(0,C.useState)(()=>Tf());(0,C.useEffect)(()=>{let e=()=>s(Tf());return window.addEventListener(`resize`,e),window.addEventListener(`orientationchange`,e),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`orientationchange`,e)}},[]);let[c,l]=(0,C.useState)(()=>Yr(`pop-agent:appbar-hidden`)===`1`),u=(0,C.useRef)(Tc(Yr(`pop-agent.preview.tabs.v1`))??{tabs:[],active:null,open:!1}),[d,f]=(0,C.useState)(()=>u.current?.open??!1),[p,m]=(0,C.useState)(!1),[h,g]=(0,C.useState)(!1),[_,v]=(0,C.useState)(!1),[y,b]=(0,C.useState)(``),x=(0,C.useRef)(null),S=(0,C.useRef)(null),[w,O]=(0,C.useState)(0),[k,A]=(0,C.useState)(null),j=(0,C.useRef)(null),M=(0,C.useRef)(null),N=(0,C.useRef)(null),[P,F]=(0,C.useState)(!1),[I,L]=(0,C.useState)(!1),[B,V]=(0,C.useState)(()=>localStorage.getItem(`pop-agent.onboarded`)===`1`),[H,U]=(0,C.useState)(null),[W,ee]=(0,C.useState)(()=>Yr(`pop-agent.split.chatSide`)===`right`?`right`:`left`),G=()=>{let e=W===`right`?`left`:`right`;ee(e),Xr(lr,e)},[K,te]=(0,C.useState)(null),[ne,re]=(0,C.useState)({path:``,seq:0}),ie=d&&!p&&!o,ae=d&&p&&!o;(0,C.useEffect)(()=>{let e=document.documentElement;if(!ie){e.style.setProperty(`--split-w`,`0px`),e.style.setProperty(`--top-lane`,`0px`);return}let t=()=>{let t=document.querySelector(`.appbar`),n=document.querySelector(`.preview-panel`);if(!t||!n){e.style.setProperty(`--split-w`,`0px`);return}let r=t.getBoundingClientRect(),a=n.getBoundingClientRect(),o=Math.round(a.width);e.style.setProperty(`--split-w`,`${Math.max(0,Math.round(o))}px`);let s=document.querySelector(`.appbar > .appbar-side`),c=W===`right`&&i&&s?Math.round(s.getBoundingClientRect().right-r.left):0;e.style.setProperty(`--top-lane`,`${Math.max(0,c)}px`)};t();let n=new ResizeObserver(t);for(let e of[document.querySelector(`.appbar`),document.querySelector(`.preview-panel`),document.querySelector(`.appbar > .appbar-side`)])e&&n.observe(e,{box:`border-box`});return window.addEventListener(`resize`,t),()=>{n.disconnect(),window.removeEventListener(`resize`,t)}},[ie,W,i]);let[oe,se]=(0,C.useState)(()=>(u.current?.tabs.length??0)===0),[ce,le]=(0,C.useState)(()=>xs(Yr(_s))),ue=(0,C.useRef)(!1);(0,C.useEffect)(()=>{Xr(vs,i?`1`:`0`)},[i]),(0,C.useEffect)(()=>{document.documentElement.style.setProperty(`--side-w`,i||o?`0px`:`${ce}px`)},[ce,i,o]),(0,C.useEffect)(()=>{Xr(`pop-agent:appbar-hidden`,c?`1`:`0`)},[c]),(0,C.useEffect)(()=>{Xr(_s,String(ce))},[ce]),(0,C.useEffect)(()=>{let e=document.querySelector(`.appbar`);if(!e)return;let t=()=>{document.documentElement.style.setProperty(`--appbar-h`,`${e.offsetHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e,{box:`border-box`}),()=>n.disconnect()},[]);let de=e=>{e.preventDefault(),ue.current=!0,document.documentElement.classList.add(`is-resizing`);let t=e.clientX,n=Math.min(ce,bs(window.innerWidth)),r=e.currentTarget,i=e.pointerId;try{r.setPointerCapture(i)}catch{}let a=e=>{ue.current&&le(ys(n+(e.clientX-t),bs(window.innerWidth)))},o=()=>{ue.current=!1,document.documentElement.classList.remove(`is-resizing`),document.removeEventListener(`pointermove`,a),document.removeEventListener(`pointerup`,o),document.removeEventListener(`pointercancel`,o);try{r.hasPointerCapture(i)&&r.releasePointerCapture(i)}catch{}};document.addEventListener(`pointermove`,a),document.addEventListener(`pointerup`,o),document.addEventListener(`pointercancel`,o)},[q,fe]=(0,C.useState)(()=>wc(u.current?.tabs??[])),pe=(0,C.useCallback)(()=>{let e=!d;f(e),e&&se(q.length===0),e||m(!1)},[d,q.length]),me=(0,C.useRef)(null),he=(0,C.useCallback)((e,t,n,r)=>{let i=`file:${t}:${e}`;fe(a=>{let o=a.find(e=>e.id===i);return o?o.kind!==`file`||o.mode===n&&o.line===r?a:a.map(e=>e.id===i?{...e,mode:n,line:r}:e):[...a,{id:i,kind:`file`,path:e,root:t,...n?{mode:n}:{},...r?{line:r}:{}}]}),ye(i),se(!1),f(!0),te(e=>xd(e,me.current,t)),re(t=>({path:e,seq:t.seq+1}))},[]),ge=(0,C.useCallback)((e,t)=>he(e,t??``,`diff`),[he]),_e=d,[ve,ye]=(0,C.useState)(()=>u.current?.active??null);(0,C.useEffect)(()=>{Xr(Sc,Dc(q,ve,d))},[q,ve,d]);let[be,xe]=(0,C.useState)(!1),[Se,Ce]=(0,C.useState)(null),[we,Te]=(0,C.useState)(null),[Ee,De]=(0,C.useState)(0),Oe=(0,C.useCallback)(e=>{if(e.length===0)return;let t=new Set(e);fe(e=>{for(let n of e)t.has(n.id)&&sD(n);let n=e.filter(e=>!t.has(e.id));return n.length===0&&se(!0),n}),ye(e=>e&&t.has(e)?null:e)},[]),ke=(0,C.useCallback)(e=>{fe(t=>{let n=new Map(t.map(e=>[e.id,e])),r=e.map(e=>n.get(e)).filter(e=>e!==void 0);return r.length===t.length?r:t})},[]),[Ae,je]=(0,C.useState)(null),[J]=Bb();(0,C.useEffect)(()=>$d(e=>je(e)),[]);let[Me]=uf(Nr,!1),Ne=[...xr.filter(e=>J[e]),...J.settings?[`settings`]:[]],X=Ro(e=>e.snapshot),Pe=X?.settings.appearance;(0,C.useEffect)(()=>{uO(Pe)},[Pe?.chatPx,Pe?.projectPx,Pe?.sessionPx]);let Fe=Ro(e=>e.creating),Ie=Ro(e=>e.newSession),Le=Ro(e=>e.pendingActive),Re=Ro(e=>e.pendingNewChat),ze=Ro(e=>e.lastError),Be=Ro(e=>e.connection),Ve=Ro(e=>e.preview),He=(0,C.useRef)([]),Ue=(0,C.useCallback)(e=>{let t=Nd(e,Md(He.current))??e;he(t,X?.files?.root??``)},[he,X?.files?.root]),We=X?.active.conversationId??null,Ge=X?.files?.root??null;me.current=Ge;let Ke=K??Ge,qe=(()=>{let e=q.find(e=>e.id===(ve??q[0]?.id??``));return e!==void 0&&e.kind===`file`?e:null})(),Je=(0,C.useMemo)(()=>(X?.conversations??[]).filter(e=>!zT(e.id)),[X?.conversations]),Ye=(0,C.useMemo)(()=>X?.piProjects??[],[X?.piProjects]),Xe=(0,C.useMemo)(()=>Object.keys(X?.runningByConversation??{}),[X?.runningByConversation]),Ze=(0,C.useCallback)(()=>F(!0),[]),Qe=(0,C.useCallback)(e=>{f(!0),se(!1),fe(t=>t.some(t=>t.id===e)?t:[...t,{id:e,kind:e}]),ye(e)},[]),$e=(0,C.useCallback)(()=>{f(!0),se(!1),fe(e=>e.some(e=>e.kind===`files`)?e:[...e,{id:`files`,kind:`files`}]),ye(`files`)},[]),et=(0,C.useCallback)(()=>{if(!d||oe)return!1;let e=q.find(e=>e.id===(ve??q[0]?.id??``));return e!==void 0&&e.kind===`files`},[d,oe,q,ve]),tt=(0,C.useCallback)(e=>{Ce(t=>({cwd:e,seq:(t?.seq??0)+1})),xe(!0)},[]),nt=(0,C.useCallback)(e=>{Te(t=>({value:e?`${e}/**`:``,seq:(t?.seq??0)+1})),F(!0)},[]),rt=(0,C.useCallback)(()=>L(!0),[]),it=(0,C.useCallback)(e=>{re(t=>({path:e,seq:t.seq+1}))},[]),at=(0,C.useMemo)(()=>{let e=X?.settings.projectPrefs?.aliases??{};return(X?.piProjects??[]).map(t=>({cwd:t.cwd,label:e[t.cwd]||t.name||t.cwd}))},[X?.piProjects,X?.settings.projectPrefs?.aliases]),ot=(0,C.useMemo)(()=>{let e=K??Ge??null;return{root:e,onRootChange:te,options:at,onOpenFile:t=>he(t,e??``),onOpenChangedFile:t=>he(t,e??``,`diff`),onOpenTerminal:()=>{e&&tt(e)},onReveal:e=>{fetch(`/api/projects/reveal`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({cwd:e})})},onSearchContents:Ze,onOpenBottomTerminal:tt,onFindInFolder:nt,activePath:qe?.path??null,revealSeq:ne.seq,revealPath:ne.path||null,onRevealPath:it}},[K,Ge,at,he,tt,Ze,nt,qe,ne,it]),st=(0,C.useCallback)(e=>{if(e===`files`){$e();return}if(e===`terminal`){Ge?tt(Ge):xe(!0);return}if(f(!0),se(!1),e===`canvas`){fe(e=>e.some(e=>e.id===`canvas`)?e:[...e,{id:`canvas`,kind:`canvas`}]),ye(`canvas`);return}if(e===`side`){let e=`side:${Ee}`;fe(t=>[...t,{id:e,kind:`side`}]),ye(e),De(e=>e+1);return}let t=`${e}:${Ee}`;De(e=>e+1),fe(e=>[...e,{id:t,kind:`web`,url:``}]),ye(t)},[Ee,Ge,tt]),ct=(0,C.useCallback)(()=>{q.some(e=>e.id===`canvas`)?(fe(e=>e.filter(e=>e.id!==`canvas`)),f(!1)):(f(!0),se(!1),fe(e=>e.some(e=>e.id===`canvas`)?e:[...e,{id:`canvas`,kind:`canvas`}]),ye(`canvas`))},[q]),[lt]=xc(),ut=(0,C.useRef)(lt);ut.current=lt;let dt=(0,C.useCallback)(e=>{switch(e){case`newChat`:Mo();return;case`newProject`:L(!0);return;case`tempChat`:st(`side`);return;case`settings`:je(`settings`);return;case`toggleRight`:pe();return;case`toggleLeft`:a(e=>!e);return;case`projects`:(i||!dc())&&a(!1);return;case`files`:d&&et()?f(!1):$e();return;case`canvas`:ct();return;case`terminal`:xe(e=>!e);return;case`contentSearch`:F(!0);return;case`toggleMic`:Ea();return;case`pauseSpeech`:hn(!mn());return;case`stopSpeech`:nn();return;case`cheatSheet`:vc();return}},[i,d,st,$e,et,ct,pe]),ft=(0,C.useRef)(dt);ft.current=dt;let pt=(0,C.useRef)(null),mt=(0,C.useCallback)(e=>{if(pt.current)return;let t={at:Date.now(),timer:null,key:e};pt.current=t,!na()&&(t.timer=setTimeout(()=>{pt.current===t&&rc(350,na())===`startHold`&&wa()},350))},[]),ht=(0,C.useCallback)(()=>{let e=pt.current;if(!e)return;pt.current=null,e.timer&&clearTimeout(e.timer);let t=rc(Date.now()-e.at,na());t===`stop`?Ta():t===`start`&&Ea()},[]),gt=(0,C.useRef)(mt);gt.current=mt;let _t=(0,C.useRef)(ht);_t.current=ht;let vt=(0,C.useCallback)(()=>{let e=pt.current;e&&(pt.current=null,e.timer&&clearTimeout(e.timer))},[]),yt=(0,C.useRef)(vt);yt.current=vt;let bt=(0,C.useRef)(null);(0,C.useEffect)(()=>{let e=e=>{if(zs(e),e.repeat||e.defaultPrevented)return;let t=Ys(ut.current,e);if(t){t===`toggleMic`?gt.current(null):bt.current={id:t};return}bt.current=null,yt.current();let n=Ws(ut.current,e);n&&(e.preventDefault(),n===`toggleMic`?gt.current(js(e)):ft.current(n))},t=e=>{zs(e);let t=bt.current;if(t&&(bt.current=null,qs(e))){ft.current(t.id);return}let n=pt.current;if(!n)return;let r=js(e);(r===null||r===n.key)&&_t.current()},n=()=>{Bs(),bt.current=null,pt.current&&_t.current()};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,t),window.addEventListener(`blur`,n),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,t),window.removeEventListener(`blur`,n)}},[]);let xt=(0,C.useCallback)(e=>{f(!0),se(!1);let t=q.filter(e=>e.kind===`side`),n=t.length>0?t[t.length-1]?.id??`side:0`:`side:${Ee}`;t.length===0&&(De(e=>e+1),fe(e=>[...e,{id:n,kind:`side`}])),ye(n),LT(n).setDraft(`${Tu(e)}
78
78
 
79
- `)},[de,Ee]),St=(0,C.useCallback)(e=>{Ce(t=>({cwd:Ge??``,initialCommand:e,seq:(t?.seq??0)+1})),xe(!0)},[Ge]),Ct=Ve&&Ve.conversationId!==We?Ve:null,wt=Ie||Re?dO:Ct?.messages??Y?.active.messages??dO;He.current=wt;let Tt=Y?.conversations.find(e=>e.id===Y.active.conversationId)??null,Et=Ie||Re?!1:Tt?.ephemeral===!0,Dt=(()=>{if(Ie||Re){let t=Ie?Ie.workspace:Y?.files?.root??null;return{project:t?D(t):``,title:e(`新对话`,`New chat`),unnamed:!0}}let t=Y?.active.conversationId??null;if(!Y||!t)return{project:``,title:``,unnamed:!0};let n=Y.conversations.find(e=>e.id===t),r=(Y.piProjects??[]).find(e=>e.sessions.some(e=>e.id===t)),i=r?.sessions.find(e=>e.id===t);return{project:D(n?.workspace??r?.cwd??Y.files?.root??``),title:n?.title??i?.title??``,unnamed:!(n?.title??i?.title??``)}})(),[Ot,kt]=(0,C.useState)(!1),[At,jt]=(0,C.useState)(null),X=Y?.active.conversationId??null,[Mt,Nt]=(0,C.useState)([]),[Pt,Ft]=(0,C.useState)(!1),[It,Lt]=(0,C.useState)(null);(0,C.useEffect)(()=>{Nt(Bu(window.localStorage,X)),Ft(!1),Lt(null)},[X]);let Rt=Ie||Re?[]:Mt,zt=(0,C.useCallback)(t=>{if(t.anchor!==null&&Hu(Mt,t.messageId,t.anchor)>=0){Z({text:e(`这一处已经在会话里了`,`That spot is already in this session`),ttl:2e3});return}if(t.anchor===null||t.messageId===``){Z({text:e(`这一段量不出位置,试一下重新选中`,`Could not locate that passage — try selecting it again`)});return}let n=Date.now(),r=Wu(Mt,{id:`${t.messageId}:${n}:${Mt.length}`,messageId:t.messageId,anchor:t.anchor,comment:t.comment,createdAt:n});Nt(r),Vu(window.localStorage,X,r),Lt(null),Z({text:e(`已添加到会话`,`Added to this session`),ttl:2e3})},[Mt,X,e]),Bt=(0,C.useCallback)(e=>{let t=Mt.find(t=>t.id===e),n=Gu(Mt,e);if(Nt(n),Vu(window.localStorage,X,n),It===e&&Lt(null),t!==void 0&&Fu(t)){let e=window.localStorage;cd(e,pd(ad(e),t.spot.url,t.spot.selector))}},[Mt,X,It]),Vt=(0,C.useCallback)(()=>{Nt([]),Vu(window.localStorage,X,[]),Ft(!1),Lt(null)},[X]),Ht=(0,C.useCallback)(()=>{let e=window.localStorage,t=ad(e);for(let e of Mt)Fu(e)&&(t=pd(t,e.spot.url,e.spot.selector));cd(e,t),Nt([]),Vu(e,X,[]),Ft(!1),Lt(null)},[Mt,X]),Ut=(0,C.useCallback)(t=>{let n=Qu(Mt,t.id),r=Ju(t,n>0?n:1);So(Du(xo().draft,r));let i=qu(Mt,t.id);Nt(i),Vu(window.localStorage,X,i),window.setTimeout(vo,0),Z({text:e(`已放进输入框`,`Added to the input`),ttl:2200})},[e,Mt,X]),Wt=(0,C.useCallback)(t=>{let n=Date.now(),r=Wu(Mt,{id:`web:${n}:${Mt.length}`,kind:`web`,number:t.number,spot:{url:t.url,selector:t.selector,tag:t.tag,label:t.label,text:t.text},comment:t.comment,createdAt:n});Nt(r),Vu(window.localStorage,X,r),Z({text:e(`已加入注释`,`Added to the notes`),ttl:1800})},[e,Mt,X]),Gt=(0,C.useCallback)((e,t)=>{let n=Ku(Mt,e,t);Nt(n),Vu(window.localStorage,X,n)},[Mt,X]),Kt=(0,C.useCallback)(e=>{if(Fu(e))return;let t=document.getElementById(`msg-${e.messageId}`);t!==null&&(t.scrollIntoView({block:`center`,behavior:`smooth`}),t.classList.remove(`annot-flash`),t.offsetWidth,t.classList.add(`annot-flash`),window.setTimeout(()=>t.classList.remove(`annot-flash`),1300))},[]),qt=(0,C.useCallback)(e=>{Ft(!0),Lt(e),window.setTimeout(()=>document.getElementById(`annot-row-${e}`)?.scrollIntoView({block:`nearest`}),0)},[]),Jt=X?(Y?.settings.sessionPrefs.pinned??[]).includes(X):!1;(0,C.useEffect)(()=>{h&&(b(Dt.title),requestAnimationFrame(()=>{x.current?.focus(),x.current?.select()}))},[h,Dt.title]);let Yt=()=>{let e=Y?.active.conversationId??null,t=y.replace(/\s+/g,` `).trim().slice(0,60);g(!1),e&&t!==``&&t!==Dt.title&&Gl(e,t)},Xt=(Y?.engineCapabilities.forkChat??!1)&&!Et,Zt=(0,C.useCallback)(e=>{X&&Hl(X,e)},[X]),Qt=Y?.engineCapabilities.ephemeralChat===!0,$t=ze&&(ze.conversationId===null||ze.conversationId===(Y?.active.conversationId??null))?ze.text:null,en=Le!==null&&Le!==We&&Ct===null,tn=(0,C.useRef)(Oc(window.location.search)),rn=(0,C.useRef)(!1),an=(0,C.useRef)(tn.current);(0,C.useEffect)(()=>{let e=Y?.active.conversationId??null;e&&(an.current=e)},[Y?.active.conversationId]),(0,C.useEffect)(()=>{if(Be!==`open`)return;if(!rn.current){rn.current=!0,tn.current&&(Yl(tn.current),Jl(tn.current,{force:!0}));return}if(xo().newSession)return;let e=an.current;e&&(Yl(e),Jl(e))},[Be]),(0,C.useEffect)(()=>{if(!Y||xo().newSession||tn.current!==null&&Oc(window.location.search)===tn.current&&Y.active.conversationId!==tn.current)return;tn.current=null;let e=kc(window.location.href,Y.active.conversationId);e!==`${window.location.pathname}${window.location.search}${window.location.hash}`&&window.history.replaceState(null,``,e)},[Y?.active.conversationId,Ie]);let on=Ct===null&&Y!==null&&Y.running.status!==`idle`&&Y.running.conversationId===Y.active.conversationId;(0,C.useEffect)(()=>{let{project:t,title:r}=Dt,i=r?t?`${r} · ${t}`:`${r} · ${n}`:`${e(`新会话`,`New session`)} · ${n}`;if(!on){document.title=i;return}let a=!0;document.title=`● ${i}`;let o=window.setInterval(()=>{a=!a,document.title=`${a?`●`:`○`} ${i}`},900);return()=>{window.clearInterval(o),document.title=i}},[Dt.project,Dt.title,n,on,e]);let sn=wt.at(-1)?.blocks.reduce((e,t)=>e+(t.kind===`text`?t.text.length:0),0)??0,cn=Ct===null&&Y!==null&&Y.running.status!==`idle`&&Y.running.conversationId===Y.active.conversationId?Y.running:null;Qa(Y),Go();let ln=R(`${wt.length}:${sn}:${Y?.running.streamingText?.length??0}:${Y?.active.conversationId??``}`,Y?.active.conversationId??null),un=wt.at(-1)?.id??null,dn=(()=>{for(let e=wt.length-1;e>=0;--e){let t=wt[e];if(t&&t.role===`user`&&!t.steer)return t.id}return null})(),fn=(0,C.useRef)({conversation:null,messageId:null,queuedId:null});return(0,C.useLayoutEffect)(()=>{let e=(t,n=performance.now()+3e3)=>{let r=document.getElementById(`msg-${t}`);r?ln.anchorTo(r):performance.now()<n&&requestAnimationFrame(()=>e(t,n))},t=z(fn.current,{conversation:Y?.active.conversationId??null,messageId:dn,queuedId:null});fn.current=t.seen,t.target!==null&&e(t.target)},[dn,Y?.active.conversationId,ln.anchorTo]),(0,C.useLayoutEffect)(()=>{let e=A.current,t=j.current??M.current;if(!e||!t)return;let n=()=>{let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(n.width===0||r.width===0)return;let i=Math.max(0,Math.round(r.left-n.left)),a=Math.round(r.width);T(e=>e===i?e:i),k(e=>e===a?e:a)};n();let r=new ResizeObserver(n);return r.observe(e),r.observe(t),window.addEventListener(`resize`,n),()=>{r.disconnect(),window.removeEventListener(`resize`,n)}},[i,o,se,d,p,U,c]),(0,Q.jsxs)(`div`,{className:`app${re?` app-split`:``}${ie?` app-wide-lift`:``}${U===`right`?` app-flip`:``}${i?` app-collapsed`:``}`,children:[en||Fe?(0,Q.jsx)(`div`,{className:`switch-hint`,role:`status`,children:Fe?e(`正在新建会话…`,`Creating session…`):e(`正在打开会话…`,`Opening session…`)}):null,(0,Q.jsxs)(`div`,{className:`appbar`,hidden:c,children:[(0,Q.jsx)(`div`,{className:`appbar-drag`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`appbar-side`,children:r?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`brand`,children:[t.logoShown?(0,Q.jsx)(`img`,{className:`brand-icon`,src:t.logo||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}):null,t.shown?(0,Q.jsx)(`span`,{className:`brand-name`,children:t.name}):null]}),(0,Q.jsx)(jw,{})]})}),(0,Q.jsxs)(`div`,{className:`appbar-main`,ref:A,children:[(0,Q.jsxs)(`span`,{ref:S,className:`appbar-slot`,style:{marginLeft:w,maxWidth:O??void 0},onContextMenu:X?e=>{e.preventDefault();let t=e.currentTarget.querySelector(`.appbar-title, .appbar-title-input`);jt(t??e.currentTarget),kt(!0)}:void 0,children:[Dt.title&&!Dt.unnamed?h?(0,Q.jsx)(`input`,{ref:x,className:`appbar-title-input`,...wu,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),Yt()):e.key===`Escape`&&(e.preventDefault(),g(!1))},onBlur:Yt}):(0,Q.jsxs)(`span`,{className:`appbar-title`,title:Dt.project?`${Dt.project}\n${e(`双击改会话名`,`Double-click to rename`)}`:e(`双击改会话名`,`Double-click to rename`),onDoubleClick:e=>{e.preventDefault(),g(!0)},children:[Dt.project?(0,Q.jsx)(`button`,{type:`button`,className:`appbar-title-badge${_?` appbar-title-badge-busy`:``}`,disabled:_,title:e(`让 AI 按当前会话内容重新起名`,`Let AI rename this session from its content`),"aria-label":e(`让 AI 按当前会话内容重新起名`,`Let AI rename this session from its content`),onClick:e=>{e.preventDefault(),e.stopPropagation(),X&&!_&&(v(!0),Kl(X).finally(()=>v(!1)))},children:(0,Q.jsx)(cD,{className:`appbar-title-badge-icon`})}):null,(0,Q.jsx)(`span`,{className:`appbar-title-name`,children:Dt.title})]}):null,Ot&&X?(0,Q.jsx)(Xd,{anchor:At,title:Dt.title,pinned:Jt,fork:{enabled:Xt&&un!==null,reason:Et?e(`临时会话不能派生分支,先「保存为正式对话」`):Y?.engineCapabilities.forkChat??!1?e(`这条会话还没有消息,没有可分叉的点`):e(`当前引擎不支持分叉`),onFork:()=>{X&&un&&Hl(X,un)}},splitSide:_e&&!p?{chatOnRight:U===`right`,onMove:ee}:void 0,onClose:()=>kt(!1),onPin:()=>Id(X),onRename:()=>g(!0),aiRenaming:_,onAiRename:()=>{X&&!_&&(v(!0),Kl(X).finally(()=>v(!1)))},onOpenInNewTab:()=>window.open(kc(window.location.href,X),`_blank`,`noopener`),onArchive:()=>Rd(X,Dt.title,e),onDelete:()=>Hd(X,Dt.title||X)}):null]}),(0,Q.jsx)(Aw,{variant:`full`,placement:`appbar`,items:Ne,panel:Ae,onPanelChange:je,leadingAction:q?({showIcon:e,showLabel:t})=>(0,Q.jsx)(Mw,{showIcon:e,showLabel:t,onClick:()=>{st(`side`),Tf()&&a(!0)}}):void 0}),re||ie?null:(0,Q.jsx)(`button`,{type:`button`,className:`side-foot-btn appbar-panel-btn${d?` side-foot-btn-on`:``}`,onClick:pe,"aria-pressed":d,title:d?U===`right`?e(`收起左侧工作区`,`Collapse the left work area`):e(`收起右侧工作区`,`Collapse the right work area`):U===`right`?e(`分栏:左边开一个工作区(文件 / 终端 / 临时聊天 / 网页)`,`Split view: a work area on the left (files / terminal / side chat / web)`):e(`分栏:右边开一个工作区(文件 / 终端 / 临时聊天 / 网页)`,`Split view: a work area on the right (files / terminal / side chat / web)`),children:(0,Q.jsxs)(`svg`,{className:`appbar-panel-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:U===`right`?`6`:`10`,y1:`4`,x2:U===`right`?`6`:`10`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})}),re?(0,Q.jsx)(`span`,{className:`appbar-split-divider`,"aria-hidden":`true`}):null,re&&U===`right`?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`button`,{type:`button`,className:`side-foot-btn appbar-panel-btn side-foot-btn-on`,onClick:pe,"aria-pressed":d,title:e(`收起左侧工作区`,`Collapse the left work area`),children:(0,Q.jsxs)(`svg`,{className:`appbar-panel-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:`6`,y1:`4`,x2:`6`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})})}):null]})]}),(0,Q.jsxs)(`div`,{className:`app-main`,children:[i?(0,Q.jsx)(`button`,{type:`button`,className:`side-expand`,onClick:()=>a(!1),title:e(`展开项目列表`,`Expand project list`),"aria-label":e(`展开项目列表`,`Expand project list`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M6 3.6 10.4 8 6 12.4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}):null,i?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`side-backdrop`,onClick:()=>a(!0),"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`side-host`,style:{width:se},onClick:e=>{if(!Tf())return;let t=e.target;t.closest(`.pi-menu, .proj-more, .proj-menu`)||t.closest(`.pi-row-wrap, .session-row, .newchat-pill, .archived-view-list *`)&&setTimeout(()=>a(!0),0)},children:[(0,Q.jsx)(kD,{conversations:Je,activeId:Ie?null:Le??Y?.active.conversationId??null,piProjects:Ye,runningIds:Xe,onOpenTerminal:e=>tt(e),onOpenFiles:e=>{K(e),$e()},canFork:Y?.engineCapabilities.forkChat??!1,onFork:e=>Hl(e),onNewProject:rt}),(0,Q.jsx)(`button`,{type:`button`,className:`side-collapse`,title:e(`收起项目列表`,`Collapse project list`),"aria-label":e(`收起项目列表`,`Collapse project list`),onPointerDown:e=>e.stopPropagation(),onClick:()=>a(!0),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M10 3.6 5.6 8 10 12.4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Q.jsx)(`div`,{className:`side-resizer`,role:`separator`,"aria-orientation":`vertical`,title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:ue,onDoubleClick:()=>ce(xs(null))})]})]}),(0,Q.jsx)(`div`,{className:`right-col`,ref:M,children:(0,Q.jsxs)(`div`,{className:`right-upper${p?` right-upper-wide`:``}${U===`right`?` right-upper-flip`:``}`,children:[p&&_e?null:(0,Q.jsxs)(`div`,{className:`workspace`,ref:j,children:[(0,Q.jsxs)(`main`,{className:`main`,ref:ln.ref,children:[Y&&wt.length===0?(0,Q.jsxs)(`div`,{className:`newchat-hero`,children:[(0,Q.jsx)($v,{webVersion:Y.versions.web,latestVersion:Y.versions.latest,outdated:Y.versions.outdated,onUpgrade:()=>St(E)}),(0,Q.jsx)(ey,{templates:Y.settings.templates??[],conversationId:Y.active.conversationId})]}):Y?(0,Q.jsx)(hv,{messages:wt,hasMoreBefore:Y.active.hasMoreBefore,running:cn!==null,activeTool:cn?.activeTool??null,retrying:cn?.retrying??null,modelLabels:Object.fromEntries(Y.models.map(e=>[e.id,e.label])),workspaceRoot:Y.files?.root??null,onOpenFile:ge,onOpenPath:Ue,pending:(Y.queued??[]).filter(e=>e.conversationId===Y.active.conversationId),onRecallPending:e=>{let t=Y.queued.find(t=>t.id===e);t&&So(t.text),wl(e)},onCancelPending:e=>wl(e),actions:Y.actions??[],subagentRuns:Y.subagents??fO,onFork:Xt&&X?Zt:void 0,onAddSelectionToSession:zt,onAskSelectionInSideChat:xt,annotations:Rt,onFocusAnnotation:qt}):(0,Q.jsx)(`div`,{className:`empty`,children:e(`等待服务端快照…(后端没起来的话看终端日志)`)}),ln.pad>0?(0,Q.jsx)(`div`,{className:`scroll-anchor-tail`,style:{height:ln.pad},"aria-hidden":`true`}):null]}),(0,Q.jsx)(ny,{messages:wt}),$t?(0,Q.jsx)(`div`,{className:`error-bar`,children:$t}):null,(0,Q.jsx)(Af,{notices:Y?.notices??[],activeConversationId:Y?.active.conversationId??null}),Et&&Y?.active.conversationId?(0,Q.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,Q.jsx)(`span`,{className:`ephemeral-banner-text`,title:Qt?e(`消息只保存在内存里,不落盘、不进历史;关闭或退出服务后就没了。想留就点右边「保存为正式对话」。`,`Messages live in memory only: nothing is written to disk, nothing shows up in history, and it is gone once closed or the server restarts. Use “Save as a regular chat” to keep it.`):e(`这条对话不写进本工作台的会话文件、也不进历史,关闭或退出服务后就没了。当前引擎没有「转正」能力,所以不提供保存。`,`This chat is never written to a workbench session file and never shows up in history; it is gone once closed or the server restarts. The current engine cannot promote it to a saved session, so no save button is offered.`),children:Qt?e(`💬 临时会话:仅存内存,关闭即销毁。`,`💬 Temp session: in-memory only, gone on close.`):e(`💬 临时会话:不落盘,关闭即消失。`,`💬 Temp session: never saved, gone on close.`)}),Qt?(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>Bl(Y.active.conversationId),title:e(`把这条对话写成真正的会话文件`,`Write this chat to a real session file`),children:[`💾 `,e(`保存为正式对话`,`Save as a regular chat`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-close`,onClick:()=>H({conversationId:Y.active.conversationId,title:Tt?.title??``}),title:Qt?e(`关闭这条临时会话(内容直接丢弃,不可恢复;想留先「保存为正式对话」)`,`Close this temp session (content is discarded, not recoverable; use “Save as a regular chat” to keep it)`):e(`关闭这条临时会话(内容直接丢弃,不可恢复)`,`Close this temp session (content is discarded, not recoverable)`),children:[`✕ `,e(`关闭`,`Close`)]})]}):null,ln.stuck?null:(0,Q.jsx)(`div`,{className:`composer-wrap jump-bottom-host`,children:(0,Q.jsx)(`button`,{type:`button`,className:`jump-bottom`,onClick:ln.toBottom,title:e(`回到最新`,`Jump to latest`),"aria-label":e(`回到最新`,`Jump to latest`),children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 3.6v8.8`}),(0,Q.jsx)(`path`,{d:`M4.3 9 8 12.7 11.7 9`})]})})}),(0,Q.jsx)(_m,{annotationSummary:(0,Q.jsx)(hd,{annotations:Rt,open:Pt,focusedId:It,onToggle:()=>Ft(e=>!e),onRemove:Bt,onClear:Ht,onQuote:Ut,onJump:Kt,onComment:Gt}),running:!Ie&&!Re&&Y?.running.status!==`idle`&&Y?.running.conversationId===(Y?.active.conversationId??null),conversationId:Ie||Re?null:Y?.active.conversationId??null,annotations:Rt,onAnnotationsSent:Vt,onOpenFile:(e,t)=>he(e,t??Ge??``),newSession:Ie?{workspace:Ie.workspace,ephemeral:Ie.ephemeral,onWorkspaceChange:No,onEphemeralChange:Po}:null}),(0,Q.jsx)(rO,{open:be,cwd:Ge,request:Se,onHide:()=>xe(!1),onOpenSettings:()=>je(`settings`)})]}),_e?(0,Q.jsx)(oD,{items:de,activeId:ve??de[0]?.id??``,landing:ae,onActivate:e=>{ye(e),oe(!1)},onCloseTabs:Oe,onReorder:ke,onShowLanding:()=>oe(!0),onPickTool:st,onWideChange:m,onToggleSplit:pe,root:Ge,files:ot,chatOnRight:U===`right`,showSplitButton:!(re&&U===`right`),revealSeq:te.seq,onRevealFile:(e,t)=>{K(e=>xd(e,Ge,t)),ne(t=>({path:e,seq:t.seq+1}))},onOpenFile:e=>he(e,Ge??``),onWebNote:Wt,onOpenFilePath:he,conversationId:Y?.active.conversationId??null}):null]})})]}),(0,Q.jsx)(bf,{}),(0,Q.jsx)(YD,{snapshot:Y,terminalOpen:be,onToggleTerminal:()=>xe(e=>!e),onOpenSettings:()=>je(`settings`),onOpenHistory:Y?.engineCapabilities.historyExport?()=>Qe(`history`):void 0,onOpenPrompt:Y?.engineCapabilities.systemPrompt?()=>Qe(`prompt`):void 0,appbarHidden:c,onToggleAppbar:()=>l(e=>!e)}),(0,Q.jsx)(Nw,{}),F?(0,Q.jsx)(fm,{onClose:()=>I(!1)}):null,V?(0,Q.jsx)(_d,{title:V.title,onCancel:()=>H(null),onConfirm:()=>{gd(V.conversationId),H(null)}}):null,(0,Q.jsx)(RD,{open:N,root:Ke,onClose:()=>P(!1),onOpen:(e,t)=>he(e,Ke??``,void 0,t),presetGlob:we}),Y?.pendingApproval?(0,Q.jsx)(Of,{approval:Y.pendingApproval}):null,!L&&Y?(0,Q.jsx)(zw,{onDone:()=>{localStorage.setItem(`pop-agent.onboarded`,`1`),B(!0)}}):null,(0,Q.jsx)(Zo,{}),(0,Q.jsx)(hs,{})]})}var mO=`pop-agent.prefs-reset.v1`,hO=[`pop-agent.appbar.`,`pop-agent.statusbar.`,`pop-agent.composer.`],gO=[`pop-agent.statusbar-order.v1`,`pop-agent.chat-width`,`pop-agent.chat-font.v2`,`pop-agent.chat-font`,`pop-agent.sidebar-project-font.v2`,`pop-agent.sidebar-project-font`,`pop-agent.sidebar-session-font.v2`,`pop-agent.sidebar-session-font`,`pop-agent.appbar-scale.v2`,`pop-agent.appbar-scale`];function _O(){try{if(localStorage.getItem(mO)===`1`)return;let e=[];for(let t=0;t<localStorage.length;t+=1){let n=localStorage.key(t);n!==null&&n!==mO&&(gO.includes(n)||hO.some(e=>n.startsWith(e)))&&e.push(n)}for(let t of e)localStorage.removeItem(t);localStorage.setItem(mO,`1`)}catch{}}function vO(){if(typeof window>`u`||!window.visualViewport)return()=>{};let e=document.documentElement,t=window.visualViewport,n=()=>{e.style.setProperty(`--vvh`,`${Math.round(t.height)}px`),e.style.setProperty(`--vvtop`,`${Math.round(t.offsetTop)}px`)};return n(),t.addEventListener(`resize`,n),t.addEventListener(`scroll`,n),()=>{t.removeEventListener(`resize`,n),t.removeEventListener(`scroll`,n)}}_O(),Ih(),eb(),Pb(),bb(),iO(),Df(),vO();var yO=document.getElementById(`root`);if(!yO)throw Error(`缺少 #root 容器`);var bO=(0,w.createRoot)(yO),xO=()=>bO.render((0,Q.jsx)(C.StrictMode,{children:(0,Q.jsx)(pO,{})}));xe(ye()),ye()===`en`?Ae().finally(xO):xO(),Oc(window.location.search)===null&&dl(),yl(),Sl();export{De as t};
79
+ `)},[q,Ee]),St=(0,C.useCallback)(e=>{Ce(t=>({cwd:Ge??``,initialCommand:e,seq:(t?.seq??0)+1})),xe(!0)},[Ge]),Ct=Ve&&Ve.conversationId!==We?Ve:null,wt=Ie||Re?dO:Ct?.messages??X?.active.messages??dO;He.current=wt;let Tt=X?.conversations.find(e=>e.id===X.active.conversationId)??null,Et=Ie||Re?!1:Tt?.ephemeral===!0,Dt=(()=>{if(Ie||Re){let t=Ie?Ie.workspace:X?.files?.root??null;return{project:t?D(t):``,title:e(`新对话`,`New chat`),unnamed:!0}}let t=X?.active.conversationId??null;if(!X||!t)return{project:``,title:``,unnamed:!0};let n=X.conversations.find(e=>e.id===t),r=(X.piProjects??[]).find(e=>e.sessions.some(e=>e.id===t)),i=r?.sessions.find(e=>e.id===t);return{project:D(n?.workspace??r?.cwd??X.files?.root??``),title:n?.title??i?.title??``,unnamed:!(n?.title??i?.title??``)}})(),[Ot,kt]=(0,C.useState)(!1),[At,jt]=(0,C.useState)(null),Mt=X?.active.conversationId??null,[Nt,Pt]=(0,C.useState)([]),[Ft,It]=(0,C.useState)(!1),[Lt,Rt]=(0,C.useState)(null);(0,C.useEffect)(()=>{Pt(Bu(window.localStorage,Mt)),It(!1),Rt(null)},[Mt]);let zt=Ie||Re?[]:Nt,Bt=(0,C.useCallback)(t=>{if(t.anchor!==null&&Hu(Nt,t.messageId,t.anchor)>=0){Z({text:e(`这一处已经在会话里了`,`That spot is already in this session`),ttl:2e3});return}if(t.anchor===null||t.messageId===``){Z({text:e(`这一段量不出位置,试一下重新选中`,`Could not locate that passage — try selecting it again`)});return}let n=Date.now(),r=Wu(Nt,{id:`${t.messageId}:${n}:${Nt.length}`,messageId:t.messageId,anchor:t.anchor,comment:t.comment,createdAt:n});Pt(r),Vu(window.localStorage,Mt,r),Rt(null),Z({text:e(`已添加到会话`,`Added to this session`),ttl:2e3})},[Nt,Mt,e]),Vt=(0,C.useCallback)(e=>{let t=Nt.find(t=>t.id===e),n=Gu(Nt,e);if(Pt(n),Vu(window.localStorage,Mt,n),Lt===e&&Rt(null),t!==void 0&&Fu(t)){let e=window.localStorage;cd(e,pd(ad(e),t.spot.url,t.spot.selector))}},[Nt,Mt,Lt]),Ht=(0,C.useCallback)(()=>{Pt([]),Vu(window.localStorage,Mt,[]),It(!1),Rt(null)},[Mt]),Ut=(0,C.useCallback)(()=>{let e=window.localStorage,t=ad(e);for(let e of Nt)Fu(e)&&(t=pd(t,e.spot.url,e.spot.selector));cd(e,t),Pt([]),Vu(e,Mt,[]),It(!1),Rt(null)},[Nt,Mt]),Wt=(0,C.useCallback)(t=>{let n=Qu(Nt,t.id),r=Ju(t,n>0?n:1);So(Du(xo().draft,r));let i=qu(Nt,t.id);Pt(i),Vu(window.localStorage,Mt,i),window.setTimeout(vo,0),Z({text:e(`已放进输入框`,`Added to the input`),ttl:2200})},[e,Nt,Mt]),Gt=(0,C.useCallback)(t=>{let n=Date.now(),r=Wu(Nt,{id:`web:${n}:${Nt.length}`,kind:`web`,number:t.number,spot:{url:t.url,selector:t.selector,tag:t.tag,label:t.label,text:t.text},comment:t.comment,createdAt:n});Pt(r),Vu(window.localStorage,Mt,r),Z({text:e(`已加入注释`,`Added to the notes`),ttl:1800})},[e,Nt,Mt]),Kt=(0,C.useCallback)((e,t)=>{let n=Ku(Nt,e,t);Pt(n),Vu(window.localStorage,Mt,n)},[Nt,Mt]),qt=(0,C.useCallback)(e=>{if(Fu(e))return;let t=document.getElementById(`msg-${e.messageId}`);t!==null&&(t.scrollIntoView({block:`center`,behavior:`smooth`}),t.classList.remove(`annot-flash`),t.offsetWidth,t.classList.add(`annot-flash`),window.setTimeout(()=>t.classList.remove(`annot-flash`),1300))},[]),Jt=(0,C.useCallback)(e=>{It(!0),Rt(e),window.setTimeout(()=>document.getElementById(`annot-row-${e}`)?.scrollIntoView({block:`nearest`}),0)},[]),Yt=Mt?(X?.settings.sessionPrefs.pinned??[]).includes(Mt):!1;(0,C.useEffect)(()=>{h&&(b(Dt.title),requestAnimationFrame(()=>{x.current?.focus(),x.current?.select()}))},[h,Dt.title]);let Xt=()=>{let e=X?.active.conversationId??null,t=y.replace(/\s+/g,` `).trim().slice(0,60);g(!1),e&&t!==``&&t!==Dt.title&&Gl(e,t)},Zt=(X?.engineCapabilities.forkChat??!1)&&!Et,Qt=(0,C.useCallback)(e=>{Mt&&Hl(Mt,e)},[Mt]),$t=X?.engineCapabilities.ephemeralChat===!0,en=ze&&(ze.conversationId===null||ze.conversationId===(X?.active.conversationId??null))?ze.text:null,tn=Le!==null&&Le!==We&&Ct===null,rn=(0,C.useRef)(Oc(window.location.search)),an=(0,C.useRef)(!1),on=(0,C.useRef)(rn.current);(0,C.useEffect)(()=>{let e=X?.active.conversationId??null;e&&(on.current=e)},[X?.active.conversationId]),(0,C.useEffect)(()=>{if(Be!==`open`)return;if(!an.current){an.current=!0,rn.current&&(Yl(rn.current),Jl(rn.current,{force:!0}));return}if(xo().newSession)return;let e=on.current;e&&(Yl(e),Jl(e))},[Be]),(0,C.useEffect)(()=>{if(!X||xo().newSession||rn.current!==null&&Oc(window.location.search)===rn.current&&X.active.conversationId!==rn.current)return;rn.current=null;let e=kc(window.location.href,X.active.conversationId);e!==`${window.location.pathname}${window.location.search}${window.location.hash}`&&window.history.replaceState(null,``,e)},[X?.active.conversationId,Ie]);let sn=Ct===null&&X!==null&&X.running.status!==`idle`&&X.running.conversationId===X.active.conversationId;(0,C.useEffect)(()=>{let{project:t,title:r}=Dt,i=r?t?`${r} · ${t}`:`${r} · ${n}`:`${e(`新会话`,`New session`)} · ${n}`;if(!sn){document.title=i;return}let a=!0;document.title=`● ${i}`;let o=window.setInterval(()=>{a=!a,document.title=`${a?`●`:`○`} ${i}`},900);return()=>{window.clearInterval(o),document.title=i}},[Dt.project,Dt.title,n,sn,e]);let cn=wt.at(-1)?.blocks.reduce((e,t)=>e+(t.kind===`text`?t.text.length:0),0)??0,ln=Ct===null&&X!==null&&X.running.status!==`idle`&&X.running.conversationId===X.active.conversationId?X.running:null;Qa(X),Go();let un=R(`${wt.length}:${cn}:${X?.running.streamingText?.length??0}:${X?.active.conversationId??``}`,X?.active.conversationId??null),dn=wt.at(-1)?.id??null,fn=(()=>{for(let e=wt.length-1;e>=0;--e){let t=wt[e];if(t&&t.role===`user`&&!t.steer)return t.id}return null})(),pn=(0,C.useRef)({conversation:null,messageId:null,queuedId:null});return(0,C.useLayoutEffect)(()=>{let e=(t,n=performance.now()+3e3)=>{let r=document.getElementById(`msg-${t}`);r?un.anchorTo(r):performance.now()<n&&requestAnimationFrame(()=>e(t,n))},t=z(pn.current,{conversation:X?.active.conversationId??null,messageId:fn,queuedId:null});pn.current=t.seen,t.target!==null&&e(t.target)},[fn,X?.active.conversationId,un.anchorTo]),(0,C.useLayoutEffect)(()=>{let e=j.current,t=M.current??N.current;if(!e||!t)return;let n=()=>{let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(n.width===0||r.width===0)return;let i=Math.max(0,Math.round(r.left-n.left)),a=Math.round(r.width);O(e=>e===i?e:i),A(e=>e===a?e:a)};n();let r=new ResizeObserver(n);return r.observe(e),r.observe(t),window.addEventListener(`resize`,n),()=>{r.disconnect(),window.removeEventListener(`resize`,n)}},[i,o,ce,d,p,W,c]),(0,Q.jsxs)(`div`,{className:`app${ie?` app-split`:``}${ae?` app-wide-lift`:``}${W===`right`?` app-flip`:``}${i?` app-collapsed`:``}`,children:[tn||Fe?(0,Q.jsx)(`div`,{className:`switch-hint`,role:`status`,children:Fe?e(`正在新建会话…`,`Creating session…`):e(`正在打开会话…`,`Opening session…`)}):null,(0,Q.jsxs)(`div`,{className:`appbar`,hidden:c,children:[(0,Q.jsx)(`div`,{className:`appbar-drag`,"aria-hidden":`true`}),(0,Q.jsx)(`div`,{className:`appbar-side`,children:r?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`brand`,children:[t.logoShown?(0,Q.jsx)(`img`,{className:`brand-icon`,src:t.logo||`/favicon.svg?v=9`,alt:``,"aria-hidden":`true`}):null,t.shown?(0,Q.jsx)(`span`,{className:`brand-name`,children:t.name}):null]}),(0,Q.jsx)(jw,{})]})}),(0,Q.jsxs)(`div`,{className:`appbar-main`,ref:j,children:[(0,Q.jsxs)(`span`,{ref:S,className:`appbar-slot`,style:{marginLeft:w,maxWidth:k??void 0},onContextMenu:Mt?e=>{e.preventDefault();let t=e.currentTarget.querySelector(`.appbar-title, .appbar-title-input`);jt(t??e.currentTarget),kt(!0)}:void 0,children:[Dt.title&&!Dt.unnamed?h?(0,Q.jsx)(`input`,{ref:x,className:`appbar-title-input`,...wu,value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),Xt()):e.key===`Escape`&&(e.preventDefault(),g(!1))},onBlur:Xt}):(0,Q.jsxs)(`span`,{className:`appbar-title`,title:Dt.project?`${Dt.project}\n${e(`双击改会话名`,`Double-click to rename`)}`:e(`双击改会话名`,`Double-click to rename`),onDoubleClick:e=>{e.preventDefault(),g(!0)},children:[Dt.project?(0,Q.jsx)(`button`,{type:`button`,className:`appbar-title-badge${_?` appbar-title-badge-busy`:``}`,disabled:_,title:e(`让 AI 按当前会话内容重新起名`,`Let AI rename this session from its content`),"aria-label":e(`让 AI 按当前会话内容重新起名`,`Let AI rename this session from its content`),onClick:e=>{e.preventDefault(),e.stopPropagation(),Mt&&!_&&(v(!0),Kl(Mt).finally(()=>v(!1)))},children:(0,Q.jsx)(cD,{className:`appbar-title-badge-icon`})}):null,(0,Q.jsx)(`span`,{className:`appbar-title-name`,children:Dt.title})]}):null,Ot&&Mt?(0,Q.jsx)(Xd,{anchor:At,title:Dt.title,pinned:Yt,fork:{enabled:Zt&&dn!==null,reason:Et?e(`临时会话不能派生分支,先「保存为正式对话」`):X?.engineCapabilities.forkChat??!1?e(`这条会话还没有消息,没有可分叉的点`):e(`当前引擎不支持分叉`),onFork:()=>{Mt&&dn&&Hl(Mt,dn)}},splitSide:_e&&!p?{chatOnRight:W===`right`,onMove:G}:void 0,onClose:()=>kt(!1),onPin:()=>Id(Mt),onRename:()=>g(!0),aiRenaming:_,onAiRename:()=>{Mt&&!_&&(v(!0),Kl(Mt).finally(()=>v(!1)))},onOpenInNewTab:()=>window.open(kc(window.location.href,Mt),`_blank`,`noopener`),onArchive:()=>Rd(Mt,Dt.title,e),onDelete:()=>Hd(Mt,Dt.title||Mt)}):null]}),(0,Q.jsx)(Aw,{variant:`full`,placement:`appbar`,items:Ne,panel:Ae,onPanelChange:je,leadingAction:Me?({showIcon:e,showLabel:t})=>(0,Q.jsx)(Mw,{showIcon:e,showLabel:t,onClick:()=>{st(`side`),Tf()&&a(!0)}}):void 0}),ie||ae?null:(0,Q.jsx)(`button`,{type:`button`,className:`side-foot-btn appbar-panel-btn${d?` side-foot-btn-on`:``}`,onClick:pe,"aria-pressed":d,title:d?W===`right`?e(`收起左侧工作区`,`Collapse the left work area`):e(`收起右侧工作区`,`Collapse the right work area`):W===`right`?e(`分栏:左边开一个工作区(文件 / 终端 / 临时聊天 / 网页)`,`Split view: a work area on the left (files / terminal / side chat / web)`):e(`分栏:右边开一个工作区(文件 / 终端 / 临时聊天 / 网页)`,`Split view: a work area on the right (files / terminal / side chat / web)`),children:(0,Q.jsxs)(`svg`,{className:`appbar-panel-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:W===`right`?`6`:`10`,y1:`4`,x2:W===`right`?`6`:`10`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})}),ie?(0,Q.jsx)(`span`,{className:`appbar-split-divider`,"aria-hidden":`true`}):null,ie&&W===`right`?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(`button`,{type:`button`,className:`side-foot-btn appbar-panel-btn side-foot-btn-on`,onClick:pe,"aria-pressed":d,title:e(`收起左侧工作区`,`Collapse the left work area`),children:(0,Q.jsxs)(`svg`,{className:`appbar-panel-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:[(0,Q.jsx)(`rect`,{x:`2.2`,y:`4`,width:`11.6`,height:`8.2`,rx:`1.8`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.3`}),(0,Q.jsx)(`line`,{x1:`6`,y1:`4`,x2:`6`,y2:`12.2`,stroke:`currentColor`,strokeWidth:`1.3`})]})})}):null]})]}),(0,Q.jsxs)(`div`,{className:`app-main`,children:[i?(0,Q.jsx)(`button`,{type:`button`,className:`side-expand`,onClick:()=>a(!1),title:e(`展开项目列表`,`Expand project list`),"aria-label":e(`展开项目列表`,`Expand project list`),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M6 3.6 10.4 8 6 12.4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}):null,i?null:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`side-backdrop`,onClick:()=>a(!0),"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`side-host`,style:{width:ce},onClick:e=>{if(!Tf())return;let t=e.target;t.closest(`.pi-menu, .proj-more, .proj-menu`)||t.closest(`.pi-row-wrap, .session-row, .newchat-pill, .archived-view-list *`)&&setTimeout(()=>a(!0),0)},children:[(0,Q.jsx)(kD,{conversations:Je,activeId:Ie?null:Le??X?.active.conversationId??null,piProjects:Ye,runningIds:Xe,onOpenTerminal:e=>tt(e),onOpenFiles:e=>{te(e),$e()},canFork:X?.engineCapabilities.forkChat??!1,onFork:e=>Hl(e),onNewProject:rt}),(0,Q.jsx)(`button`,{type:`button`,className:`side-collapse`,title:e(`收起项目列表`,`Collapse project list`),"aria-label":e(`收起项目列表`,`Collapse project list`),onPointerDown:e=>e.stopPropagation(),onClick:()=>a(!0),children:(0,Q.jsx)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M10 3.6 5.6 8 10 12.4`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Q.jsx)(`div`,{className:`side-resizer`,role:`separator`,"aria-orientation":`vertical`,title:e(`拖动调整宽度(双击复位)`,`Drag to resize (double-click to reset)`),onPointerDown:de,onDoubleClick:()=>le(xs(null))})]})]}),(0,Q.jsx)(`div`,{className:`right-col`,ref:N,children:(0,Q.jsxs)(`div`,{className:`right-upper${p?` right-upper-wide`:``}${W===`right`?` right-upper-flip`:``}`,children:[p&&_e?null:(0,Q.jsxs)(`div`,{className:`workspace`,ref:M,children:[(0,Q.jsxs)(`main`,{className:`main`,ref:un.ref,children:[X&&wt.length===0?(0,Q.jsxs)(`div`,{className:`newchat-hero`,children:[(0,Q.jsx)($v,{webVersion:X.versions.web,latestVersion:X.versions.latest,outdated:X.versions.outdated,desktop:X.desktop,onUpgrade:()=>X.desktop?window.open(`${T}/releases`,`_blank`,`noopener,noreferrer`):St(E)}),(0,Q.jsx)(ey,{templates:X.settings.templates??[],conversationId:X.active.conversationId})]}):X?(0,Q.jsx)(hv,{messages:wt,hasMoreBefore:X.active.hasMoreBefore,running:ln!==null,activeTool:ln?.activeTool??null,retrying:ln?.retrying??null,modelLabels:Object.fromEntries(X.models.map(e=>[e.id,e.label])),workspaceRoot:X.files?.root??null,onOpenFile:ge,onOpenPath:Ue,pending:(X.queued??[]).filter(e=>e.conversationId===X.active.conversationId),onRecallPending:e=>{let t=X.queued.find(t=>t.id===e);t&&So(t.text),wl(e)},onCancelPending:e=>wl(e),actions:X.actions??[],subagentRuns:X.subagents??fO,onFork:Zt&&Mt?Qt:void 0,onAddSelectionToSession:Bt,onAskSelectionInSideChat:xt,annotations:zt,onFocusAnnotation:Jt}):(0,Q.jsx)(`div`,{className:`empty`,children:e(`等待服务端快照…(后端没起来的话看终端日志)`)}),un.pad>0?(0,Q.jsx)(`div`,{className:`scroll-anchor-tail`,style:{height:un.pad},"aria-hidden":`true`}):null]}),(0,Q.jsx)(ny,{messages:wt}),en?(0,Q.jsx)(`div`,{className:`error-bar`,children:en}):null,(0,Q.jsx)(Af,{notices:X?.notices??[],activeConversationId:X?.active.conversationId??null}),Et&&X?.active.conversationId?(0,Q.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,Q.jsx)(`span`,{className:`ephemeral-banner-text`,title:$t?e(`消息只保存在内存里,不落盘、不进历史;关闭或退出服务后就没了。想留就点右边「保存为正式对话」。`,`Messages live in memory only: nothing is written to disk, nothing shows up in history, and it is gone once closed or the server restarts. Use “Save as a regular chat” to keep it.`):e(`这条对话不写进本工作台的会话文件、也不进历史,关闭或退出服务后就没了。当前引擎没有「转正」能力,所以不提供保存。`,`This chat is never written to a workbench session file and never shows up in history; it is gone once closed or the server restarts. The current engine cannot promote it to a saved session, so no save button is offered.`),children:$t?e(`💬 临时会话:仅存内存,关闭即销毁。`,`💬 Temp session: in-memory only, gone on close.`):e(`💬 临时会话:不落盘,关闭即消失。`,`💬 Temp session: never saved, gone on close.`)}),$t?(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>Bl(X.active.conversationId),title:e(`把这条对话写成真正的会话文件`,`Write this chat to a real session file`),children:[`💾 `,e(`保存为正式对话`,`Save as a regular chat`)]}):null,(0,Q.jsxs)(`button`,{type:`button`,className:`ephemeral-close`,onClick:()=>U({conversationId:X.active.conversationId,title:Tt?.title??``}),title:$t?e(`关闭这条临时会话(内容直接丢弃,不可恢复;想留先「保存为正式对话」)`,`Close this temp session (content is discarded, not recoverable; use “Save as a regular chat” to keep it)`):e(`关闭这条临时会话(内容直接丢弃,不可恢复)`,`Close this temp session (content is discarded, not recoverable)`),children:[`✕ `,e(`关闭`,`Close`)]})]}):null,un.stuck?null:(0,Q.jsx)(`div`,{className:`composer-wrap jump-bottom-host`,children:(0,Q.jsx)(`button`,{type:`button`,className:`jump-bottom`,onClick:un.toBottom,title:e(`回到最新`,`Jump to latest`),"aria-label":e(`回到最新`,`Jump to latest`),children:(0,Q.jsxs)(`svg`,{viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{d:`M8 3.6v8.8`}),(0,Q.jsx)(`path`,{d:`M4.3 9 8 12.7 11.7 9`})]})})}),(0,Q.jsx)(_m,{annotationSummary:(0,Q.jsx)(hd,{annotations:zt,open:Ft,focusedId:Lt,onToggle:()=>It(e=>!e),onRemove:Vt,onClear:Ut,onQuote:Wt,onJump:qt,onComment:Kt}),running:!Ie&&!Re&&X?.running.status!==`idle`&&X?.running.conversationId===(X?.active.conversationId??null),conversationId:Ie||Re?null:X?.active.conversationId??null,annotations:zt,onAnnotationsSent:Ht,onOpenFile:(e,t)=>he(e,t??Ge??``),newSession:Ie?{workspace:Ie.workspace,ephemeral:Ie.ephemeral,onWorkspaceChange:No,onEphemeralChange:Po}:null}),(0,Q.jsx)(rO,{open:be,cwd:Ge,request:Se,onHide:()=>xe(!1),onOpenSettings:()=>je(`settings`)})]}),_e?(0,Q.jsx)(oD,{items:q,activeId:ve??q[0]?.id??``,landing:oe,onActivate:e=>{ye(e),se(!1)},onCloseTabs:Oe,onReorder:ke,onShowLanding:()=>se(!0),onPickTool:st,onWideChange:m,onToggleSplit:pe,root:Ge,files:ot,chatOnRight:W===`right`,showSplitButton:!(ie&&W===`right`),revealSeq:ne.seq,onRevealFile:(e,t)=>{te(e=>xd(e,Ge,t)),re(t=>({path:e,seq:t.seq+1}))},onOpenFile:e=>he(e,Ge??``),onWebNote:Gt,onOpenFilePath:he,conversationId:X?.active.conversationId??null}):null]})})]}),(0,Q.jsx)(bf,{}),(0,Q.jsx)(YD,{snapshot:X,terminalOpen:be,onToggleTerminal:()=>xe(e=>!e),onOpenSettings:()=>je(`settings`),onOpenHistory:X?.engineCapabilities.historyExport?()=>Qe(`history`):void 0,onOpenPrompt:X?.engineCapabilities.systemPrompt?()=>Qe(`prompt`):void 0,appbarHidden:c,onToggleAppbar:()=>l(e=>!e)}),(0,Q.jsx)(Nw,{}),I?(0,Q.jsx)(fm,{onClose:()=>L(!1)}):null,H?(0,Q.jsx)(_d,{title:H.title,onCancel:()=>U(null),onConfirm:()=>{gd(H.conversationId),U(null)}}):null,(0,Q.jsx)(RD,{open:P,root:Ke,onClose:()=>F(!1),onOpen:(e,t)=>he(e,Ke??``,void 0,t),presetGlob:we}),X?.pendingApproval?(0,Q.jsx)(Of,{approval:X.pendingApproval}):null,!B&&X?(0,Q.jsx)(zw,{onDone:()=>{localStorage.setItem(`pop-agent.onboarded`,`1`),V(!0)}}):null,(0,Q.jsx)(Zo,{}),(0,Q.jsx)(hs,{})]})}var mO=`pop-agent.prefs-reset.v1`,hO=[`pop-agent.appbar.`,`pop-agent.statusbar.`,`pop-agent.composer.`],gO=[`pop-agent.statusbar-order.v1`,`pop-agent.chat-width`,`pop-agent.chat-font.v2`,`pop-agent.chat-font`,`pop-agent.sidebar-project-font.v2`,`pop-agent.sidebar-project-font`,`pop-agent.sidebar-session-font.v2`,`pop-agent.sidebar-session-font`,`pop-agent.appbar-scale.v2`,`pop-agent.appbar-scale`];function _O(){try{if(localStorage.getItem(mO)===`1`)return;let e=[];for(let t=0;t<localStorage.length;t+=1){let n=localStorage.key(t);n!==null&&n!==mO&&(gO.includes(n)||hO.some(e=>n.startsWith(e)))&&e.push(n)}for(let t of e)localStorage.removeItem(t);localStorage.setItem(mO,`1`)}catch{}}function vO(){if(typeof window>`u`||!window.visualViewport)return()=>{};let e=document.documentElement,t=window.visualViewport,n=()=>{e.style.setProperty(`--vvh`,`${Math.round(t.height)}px`),e.style.setProperty(`--vvtop`,`${Math.round(t.offsetTop)}px`)};return n(),t.addEventListener(`resize`,n),t.addEventListener(`scroll`,n),()=>{t.removeEventListener(`resize`,n),t.removeEventListener(`scroll`,n)}}_O(),Ih(),eb(),Pb(),bb(),iO(),Df(),vO();var yO=document.getElementById(`root`);if(!yO)throw Error(`缺少 #root 容器`);var bO=(0,w.createRoot)(yO),xO=()=>bO.render((0,Q.jsx)(C.StrictMode,{children:(0,Q.jsx)(pO,{})}));be(ve()),ve()===`en`?ke().finally(xO):xO(),Oc(window.location.search)===null&&dl(),yl(),Sl();export{Ee as t};