aitu-app 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +3 -3
  2. package/assets/{CanvasAudioPlayer-C_USx5uz.js → CanvasAudioPlayer-BKMfe-GO.js} +2 -2
  3. package/assets/{ComicCreator-qGQaXp7h.js → ComicCreator-D5HnnPYu.js} +3 -3
  4. package/assets/DeferredAIInputBar-CVXfAbVO.css +1 -0
  5. package/assets/DeferredAIInputBar-Ce250DxA.js +107 -0
  6. package/assets/{DrawnixDeferredFeatures-Hy_-quZ1.js → DrawnixDeferredFeatures-ue9KjDJ6.js} +2 -2
  7. package/assets/{KnowledgeBaseContent-DSKNA70H.js → KnowledgeBaseContent-YCNU2vP8.js} +5 -5
  8. package/assets/{MVCreator-C3iClDLU.js → MVCreator-uWWF5q7x.js} +4 -4
  9. package/assets/{ModelBenchmarkWorkbench-BxwdcZ0q.js → ModelBenchmarkWorkbench-Bm75hOT0.js} +2 -2
  10. package/assets/{MusicAnalyzer-f_T6_YPJ.js → MusicAnalyzer-BXe6y3_p.js} +1 -1
  11. package/assets/ParametersDropdown-BE58BbHs.css +1 -0
  12. package/assets/{ParametersDropdown-CTSN3ClD.js → ParametersDropdown-wKdOCk_p.js} +1 -1
  13. package/assets/{PromptHistoryTool-DV-8RSdz.js → PromptHistoryTool-BRMlnlE1.js} +2 -2
  14. package/assets/{ResizableDivider-CUQBmPpx.js → ResizableDivider-tAq9KErj.js} +1 -1
  15. package/assets/{TaskQueuePanel-CtjY1W4t.js → TaskQueuePanel-D4PA4azU.js} +1 -1
  16. package/assets/{VideoAnalyzer-BBVBSONO.js → VideoAnalyzer-CVqV3zd3.js} +3 -3
  17. package/assets/{VideoAnalyzer-BmAjGvN8.js → VideoAnalyzer-gVfFvd5A.js} +1 -1
  18. package/assets/{ai-chat-BO5vbKZW.js → ai-chat-D_s8vs6j.js} +45 -45
  19. package/assets/{ai-chat-DyV67c_f.css → ai-chat-_KImIteT.css} +1 -1
  20. package/assets/{ai-generation-preferences-service-ZmPTR-wz.js → ai-generation-preferences-service-rBqGBu1Z.js} +1 -1
  21. package/assets/{batch-image-generation-BLBSv-t6.js → batch-image-generation-BHunNwyR.js} +6 -6
  22. package/assets/{diagram-engines-CSzW_-6N.js → diagram-engines-y0JSIEUO.js} +3 -3
  23. package/assets/{editor-engines-C573k8UM.js → editor-engines-Cc9_gvTn.js} +1 -1
  24. package/assets/{index-BT-rxxI3.js → index-BECJnoIM.js} +1 -1
  25. package/assets/{index-jxwTv7c1.js → index-BOOKwIS8.js} +1 -1
  26. package/assets/{index-N8asYyaz.js → index-Co0sFz6V.js} +2 -2
  27. package/assets/{index-IHNaVKGH.js → index-CrsvRs42.js} +1 -1
  28. package/assets/{index-Dw_8lcIi.js → index-Dthb4yKS.js} +1 -1
  29. package/assets/{index.es-BLXvmueB.js → index.es-l6CUS7uC.js} +1 -1
  30. package/assets/{jspdf.es.min-DxWvbkh4.js → jspdf.es.min-vSonSXg8.js} +3 -3
  31. package/assets/{markdown-to-drawnix-BVFYnimo.js → markdown-to-drawnix-CkXxETO6.js} +3 -3
  32. package/assets/{mermaid-to-drawnix-nGs2aeZ7.js → mermaid-to-drawnix-CiiYHL53.js} +3 -3
  33. package/assets/{model-benchmark-launcher-DAWoSySc.js → model-benchmark-launcher-EfxZ9z3O.js} +1 -1
  34. package/assets/{photo-wall-splitter-CCUURzGk.js → photo-wall-splitter-BJ5RLX6n.js} +1 -1
  35. package/assets/{prompt-utils-MF_LILNU.js → prompt-utils-7NlWAivq.js} +1 -1
  36. package/assets/{settings-dialog-Ac7R-_CG.js → settings-dialog-CBNPo-wJ.js} +1 -1
  37. package/assets/{skill-dsl-parser-Do9iAYbB.js → skill-dsl-parser-9CW3IgX7.js} +1 -1
  38. package/assets/{startup-app-CKHrOmQ0.css → startup-app-BJH8E5sr.css} +1 -1
  39. package/assets/{startup-app-eD_rQhSh.js → startup-app-M6vjXkRC.js} +509 -504
  40. package/assets/{task-sync-BJVOunRa.js → task-sync-B01Tbv7m.js} +1 -1
  41. package/assets/{tool-windows-CmgL3thd.js → tool-windows-Cf62DjP-.js} +21 -21
  42. package/assets/ttd-dialog-O1oaoYry.js +6 -0
  43. package/assets/{ttd-dialog-submit-shortcut-C2lJygXA.js → ttd-dialog-submit-shortcut-rkvbdHF7.js} +1 -1
  44. package/assets/{useCharacters-BAKE4TeJ.js → useCharacters-BVPiqeuF.js} +1 -1
  45. package/assets/{useMediaViewer-BGw5RkSR.js → useMediaViewer-Be0fy5RZ.js} +1 -1
  46. package/assets/{useWorkflowSubmission-iAPmKke9.js → useWorkflowSubmission-BwYRubj-.js} +9 -9
  47. package/assets/{video-recovery-service-CW7bErP2.js → video-recovery-service-CUmfssNZ.js} +1 -1
  48. package/assets/{workflow-generation-utils-DhIVnOHO.js → workflow-generation-utils-362XEGgT.js} +3 -3
  49. package/assets/{workflow-submission-service-Ce0cpj8E.js → workflow-submission-service-Dk47OkGu.js} +2 -2
  50. package/changelog.json +18 -13
  51. package/idle-prefetch-manifest.json +286 -286
  52. package/manifest.json +3 -3
  53. package/package.json +1 -1
  54. package/precache-manifest.json +6 -6
  55. package/sw.js +1 -1
  56. package/version.json +3 -4
  57. package/assets/DeferredAIInputBar-CPykEFYX.css +0 -1
  58. package/assets/DeferredAIInputBar-LmZGQCLT.js +0 -107
  59. package/assets/ParametersDropdown-b2oWAycj.css +0 -1
  60. package/assets/ttd-dialog-B12v0SVY.js +0 -6
@@ -1,13 +1,13 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css","./editor-engines-B8u8agiX.css","./tool-windows-CegtMid1.css"])))=>i.map(i=>d[i]);
2
- import{r as a,n as ut,s as _s,j as s,P as Vo,i as ar,g as Bn,a as Gn,C as Ue,b as qt,c as Rn,d as cr,H as Bo,M as Ke,A as lr,R as Tt,G as Go,Z as dr,e as ur,f as Kt,h as mr,F as pr,k as hr,l as fr,D as gr,m as wr,o as yr,p as qo,q as Ko,t as Zo,u as cn,X as Mt,v as gn,w as xr,x as bs,y as it,z as Yo,B as Xo,L as Jo,U as Qo,S as ei,E as je,I as ti,J as ni,K as si,N as ri,O as oi,Q as ii,T as ai,V as ci,W as li,Y as di,_ as Rt,$ as ui,a0 as qn,a1 as _r,a2 as mi,a3 as vs,a4 as pi,a5 as hi,a6 as Fe,a7 as vn,a8 as fi,a9 as gi,aa as wi,ab as yi,ac as xi,ad as Ss,ae as Kn,af as _i,ag as bi,ah as se,ai as vi,aj as Si,ak as Zn,al as ht,am as ye,an as Ii,ao as ln,ap as ki,aq as br,ar as Dt,as as vr,at as Mi,au as Sr,av as zn,aw as Ci,ax as Ir,ay as Is,az as Dn,aA as ji,aB as ks,aC as Ht,aD as Ln,aE as Ti,aF as Sn,aG as Ni,aH as Ei,aI as Pi,aJ as Ai,aK as Ri,aL as zi,aM as kr,aN as Di,aO as Li,aP as Ms,aQ as $i,aR as Yn,aS as Oi,aT as Fi,aU as Mr,aV as Cr,aW as jr,aX as at,aY as Xn,aZ as Jn,a_ as Qn,a$ as Ui,b0 as Wi,b1 as Tr,b2 as Nr,b3 as Zt,b4 as Er,b5 as Pr,b6 as Hi,b7 as Vi,b8 as Cs,b9 as Bi,ba as Ar,bb as Yt,bc as Ct,bd as Gi,be as wn,bf as Rr,bg as xt,bh as yn,bi as qi,bj as Ki,bk as zr,bl as Zi,bm as Yi,bn as es,bo as Xi,bp as Dr,bq as $n,br as Ji,bs as Lr,bt as ts,bu as $r,bv as Qi,bw as ns,bx as ss,by as Or,bz as ft,bA as ea,bB as ta,bC as Fr,bD as na,bE as sa,bF as ra,bG as oa,bH as ia,bI as aa,bJ as ca,bK as Ur,bL as la,bM as da,bN as ua,bO as ma,bP as pa,bQ as ha,bR as js,bS as fa,bT as ga,bU as wa,bV as ya,bW as xa,bX as _a,bY as ba,bZ as va,b_ as Sa,b$ as Ia,c0 as Wr,c1 as ka,c2 as Ma,c3 as Ca,c4 as ja,c5 as Ts,c6 as Ta,c7 as Na,c8 as Ea,c9 as Pa,ca as Aa,cb as Ra,cc as za,cd as Da,ce as Hr,cf as La,cg as $a,ch as Oa,ci as Fa,cj as Ua,ck as Wa,cl as Ha,cm as Vr,cn as Va,co as Br,cp as In,cq as kn,cr as Ns,cs as Es,ct as Ba,cu as Ga}from"./startup-app-eD_rQhSh.js";import{_ as dt}from"./startup-runtime-DTmhLESk.js";const St=new Map,Gr=300*1e3,Ps=500,gt=new Set;let zt=!1,Mn=null,Cn=null;function qa(){return Mn||(Mn=caches.open("drawnix-images-thumb")),Mn}function Ka(){return Cn||(Cn=caches.open("drawnix-images")),Cn}function qr(t,e){return`${t}|${e}`}function Za(t,e){try{const n=new URL(t,window.location.origin);return n.searchParams.delete("thumbnail"),n.searchParams.set("_thumb",e),n.toString()}catch{const n=t.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/g,""),r=n.includes("?")?"&":"?";return`${n}${r}_thumb=${e}`}}function xn(t,e){return t.startsWith("data:")||t.startsWith("blob:")||e!=="video"&&(t.startsWith("http://")||t.startsWith("https://"))}function As(t,e="small",n){const r=ut(t);if(xn(r,n))return r;try{const i=new URL(r,window.location.origin);return i.searchParams.set("thumbnail",e),i.toString()}catch{const i=r.includes("?")?"&":"?";return`${r}${i}thumbnail=${e}`}}async function Vt(){if(!(zt||gt.size===0)){zt=!0;try{const t=Date.now();if(St.size>Ps)for(const[r,i]of St)(t-i>Gr||St.size>Ps)&&St.delete(r);const n=Array.from(gt).slice(0,5);for(const r of n){gt.delete(r);const[i,o,c="small"]=r.split("|");try{await Kr(i,o,c),St.set(qr(i,c),Date.now())}catch(l){console.warn("Failed to ensure thumbnail:",i,l)}}gt.size>0&&("requestIdleCallback"in window?window.requestIdleCallback(Vt):setTimeout(Vt,100))}finally{zt=!1}}}async function Kr(t,e,n){const r=ut(t);if(xn(r,e))return;const i=Za(r,n);if(await(await qa()).match(i))return;const l=await Ka();let m=await l.match(r);if(!m)try{const u=new URL(r,window.location.origin);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&(m=await l.match(u.pathname))}catch{}if(m){const u=await m.blob();if(_s.isInitialized()){const d=await u.arrayBuffer();await _s.generateThumbnail(r,e,d,u.type,[n])}}}function Ya(t,e,n,r=!1){const i=ut(t);if(xn(i,e))return;const o=qr(i,n),c=St.get(o);if(c&&Date.now()-c<Gr)return;const l=`${i}|${e}|${n}`;if(!gt.has(l)){if(gt.add(l),r){(async()=>{if(!zt)try{zt=!0,gt.delete(l),await Kr(i,e,n),St.set(o,Date.now())}catch(m){console.warn("Failed to ensure thumbnail immediately:",i,m)}finally{zt=!1,gt.size>0&&setTimeout(Vt,0)}})();return}"requestIdleCallback"in window?window.requestIdleCallback(Vt,{timeout:2e3}):setTimeout(Vt,200)}}function Xa(t,e,n="small"){const[r,i]=a.useState(t?As(t,n,e):void 0);return a.useEffect(()=>{if(!t){i(void 0);return}const o=ut(t),c=As(o,n,e);i(c),e&&!xn(t,e)&&Ya(t,e,n,e==="video")},[t,e,n]),r}const Rs=1,Ja=4,Zr=600*1e3,Yr=600*1e3,dn=new Map,un=new Map;function Xr(t){dn.forEach((e,n)=>{t-e>Zr&&dn.delete(n)})}function Qa(t){const e=Date.now();Xr(e),dn.set(t,e)}function ec(t){const e=Date.now();Xr(e);const n=dn.get(t);return typeof n=="number"&&e-n<=Zr}function Jr(t){un.forEach((e,n)=>{t-e.resolvedAt>Yr&&un.delete(n)})}function tc(t,e){const n=Date.now();Jr(n),un.set(t,{resolvedPoster:e,resolvedAt:n})}function zs(t){if(!t)return null;const e=Date.now();Jr(e);const n=un.get(t);return n&&e-n.resolvedAt<=Yr?n.resolvedPoster:null}function nc(t,e){if(e<=0||!t)return t;try{const n=new URL(t,window.location.origin);return n.searchParams.set("_poster_retry",String(e)),n.toString()}catch{const n=t.includes("?")?"&":"?";return`${t}${n}_poster_retry=${e}`}}function jn(t,e){return s.jsxs("div",{className:"video-poster-preview",children:[t,e&&s.jsx("div",{className:"video-poster-preview__play-overlay","aria-hidden":"true",children:s.jsx(Vo,{size:"32px"})})]})}const sc=({src:t,poster:e,alt:n="",className:r,thumbnailSize:i="small",imageLoading:o="lazy",activateVideoOnClick:c=!1,playOnActivate:l=!1,onClick:m,videoProps:u})=>{const d=a.useMemo(()=>typeof e=="string"&&e.trim()?e.trim():void 0,[e]),p=a.useMemo(()=>d?ec(d):!1,[d]),h=Xa(t,"video",i),[g,y]=a.useState(p),f=g?h:d||h,x=!!(d&&!g),z=!!(f&&f===h&&f!==t),N=a.useRef(null),O=a.useRef(!1),T=a.useRef(null),[I,b]=a.useState(()=>zs(f)),[S,C]=a.useState(0),[R,U]=a.useState(!1),P=c;a.useEffect(()=>{y(p)},[p]),a.useEffect(()=>{b(zs(f)),C(0),U(!1),O.current=!1,T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[t,f,c,h,d,i]),a.useEffect(()=>{if(R||I&&I===f)return;if(!f){P||U(!0);return}const Q=x?f:nc(f,S);let B=!1;const _=new Image,E=()=>{if(!z||S>=Ja){P||U(!0);return}T.current=window.setTimeout(()=>{C(M=>M+1)},180+S*220)};return _.onload=()=>{if(!B){if(x||_.naturalWidth>Rs||_.naturalHeight>Rs){tc(f,f),b(f);return}E()}},_.onerror=()=>{if(!B){if(x&&d){Qa(d),y(!0),b(null),C(0);return}E()}},_.src=Q,()=>{B=!0,_.onload=null,_.onerror=null,T.current!==null&&(window.clearTimeout(T.current),T.current=null)}},[t,f,S,x,z,R,d,I,P]),a.useEffect(()=>{var Q;!R||!l||!O.current||(O.current=!1,(Q=N.current)==null||Q.play().catch(()=>{}))},[R,l]),a.useEffect(()=>()=>{const Q=N.current;if(Q)try{Q.pause(),Q.removeAttribute("src"),Q.load()}catch{}},[]);const J=Q=>{c&&(O.current=!0,U(!0)),m==null||m(Q)},ee=Q=>{m==null||m(Q)},X=c&&!R;return!R&&I?jn(s.jsx("img",{src:I,alt:n,className:`video-poster-preview__media${r?` ${r}`:""}`,loading:o,decoding:"async",draggable:!1,referrerPolicy:"no-referrer",onClick:J}),X):!R&&!I?jn(s.jsx("div",{className:`video-poster-preview__placeholder${r?` ${r}`:""}`,"aria-hidden":"true",onClick:c?()=>{O.current=!0,U(!0)}:void 0}),X):jn(s.jsx("video",{ref:N,src:t,poster:I||d,className:`video-poster-preview__media${r?` ${r}`:""}`,playsInline:!0,...u,onClick:ee}),!1)},rc=.1,oc=5,Ds=t=>Math.max(rc,Math.min(oc,t));function ic(t){const{items:e,initialMode:n="single",initialIndex:r=0,maxCompareSlots:i=4,defaultCompareLayout:o="horizontal",visible:c,onModeChange:l}=t,m=a.useCallback(()=>{if(Array.isArray(r))return r.slice(0,i);const q=typeof r=="number"?r:0,ce=(q+1)%e.length;return e.length>1?[q,ce]:[q]},[r,i,e.length]),u=a.useCallback(()=>{const q=m().length;return q>=4?4:q===3?3:2},[m]),[d,p]=a.useState(n),[h,g]=a.useState(typeof r=="number"?r:0),[y,f]=a.useState(m),[x,z]=a.useState(o),[N,O]=a.useState(!1),[T,I]=a.useState(1),[b,S]=a.useState({x:0,y:0}),[C,R]=a.useState(0),[U,P]=a.useState(u);a.useEffect(()=>{if(c){const q=m();p(n),g(typeof r=="number"?r:0),f(q),P(q.length>=4?4:q.length===3?3:2),I(1),S({x:0,y:0}),R(0)}},[c,n,r,m]);const J=a.useRef(e);a.useEffect(()=>{if(!c||e===J.current){J.current=e;return}const q=J.current;J.current=e;const ce=q[h];if(!(ce!=null&&ce.id))return;const ve=e.findIndex(me=>me.id===ce.id);ve!==-1&&ve!==h&&g(ve)},[c,e,h]);const ee=a.useMemo(()=>({mode:d,currentIndex:h,compareIndices:y,compareLayout:x,syncMode:N,zoomLevel:T,panOffset:b,focusedSlot:C}),[d,h,y,x,N,T,b,C]),X=a.useCallback(q=>{if(q!==d){if(q==="compare"){const ce=(h+1)%e.length;f(e.length>1?[h,ce]:[h])}else{const ce=y[C]??y[0]??0;g(ce)}p(q),I(1),S({x:0,y:0}),l==null||l(q)}},[d,h,e.length,y,C,l]),Q=a.useCallback(q=>{q>=0&&q<e.length&&(g(q),I(1),S({x:0,y:0}))},[e.length]),B=a.useCallback(()=>{const q=h>0?h-1:e.length-1;Q(q)},[h,e.length,Q]),_=a.useCallback(()=>{const q=h<e.length-1?h+1:0;Q(q)},[h,e.length,Q]),E=a.useCallback((q,ce)=>{f(ve=>{const me=[...ve];return typeof ce=="number"&&ce<U?me[ce]=q:me.length<U?me.push(q):me[C]=q,me})},[U,C]),M=a.useCallback(q=>{f(ce=>{if(ce.length<=2)return ce;const ve=[...ce];return ve.splice(q,1),ve}),C>=q&&C>0&&R(C-1)},[C]),$=a.useCallback((q,ce)=>{f(ve=>{const me=[...ve],Re=me[q];return me[q]=me[ce],me[ce]=Re,me})},[]),re=a.useCallback(q=>{z(q)},[]),fe=a.useCallback(()=>{O(q=>!q)},[]),K=a.useCallback(q=>{I(ce=>{const ve=ce+q;return Ds(ve)})},[]),de=a.useCallback(q=>{I(Ds(q))},[]),ie=a.useCallback(()=>{I(1),S({x:0,y:0})},[]),ue=a.useCallback(q=>{S(q)},[]),xe=a.useCallback(q=>{R(q)},[]),pe=a.useCallback(q=>{P(q),f(ce=>{if(ce.length>q)return ce.slice(0,q);if(ce.length<q&&e.length>ce.length){const ve=[...ce];let me=(ce[ce.length-1]+1)%e.length;for(;ve.length<q&&ve.length<e.length;)ve.includes(me)||ve.push(me),me=(me+1)%e.length;return ve}return ce})},[e.length]),ae=a.useMemo(()=>({setMode:X,goTo:Q,goToPrev:B,goToNext:_,addToCompare:E,removeFromCompare:M,swapSlots:$,setCompareLayout:re,toggleSyncMode:fe,zoom:K,setZoomLevel:de,setPan:ue,resetView:ie,setFocusedSlot:xe,setSlotCount:pe}),[X,Q,B,_,E,M,$,re,fe,K,de,ue,ie,xe,pe]);return[ee,ae]}let Qr=null;function om(t){Qr=t}function ac(){return Qr}const Nt=400;function cc(t){return t==="video"?{width:Nt,height:Math.round(Nt*(9/16))}:{width:Nt,height:Nt}}async function lc(t,e,n,r,i){const o=i||cc(e);return e==="video"?(await Rn(t,n,r,!1,o,!0,!0),o):(await cr(t,n,r,!1,o,!0,!0),o)}async function dc(t,e,n,r){const i=ac();if(!i)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{if(!n){const u=await ar(i,e,t,r);if(u)return{success:!0,data:{insertedCount:1,items:[{type:t,point:u.point,elementId:u.elementId,size:u.size}],firstElementId:u.elementId,firstElementPosition:u.point,firstElementSize:u.size},type:"text"}}const o=n||Bn(i,{logPrefix:"MediaQuickInsert"})||Gn(i,{emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT,c=i.children.length,l=await lc(i,t,e,o,r),m=i.children[c];return requestAnimationFrame(()=>{qt(i,[o[0]+Nt/2,o[1]+Nt/2])}),{success:!0,data:{insertedCount:1,items:[{type:t,point:o,elementId:m==null?void 0:m.id,size:l}],firstElementId:m==null?void 0:m.id,firstElementPosition:o,firstElementSize:l},type:"text"}}catch(o){return console.error("[MediaQuickInsert] Failed to insert media:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const ke=({content:t,children:e,placement:n="bottom",sideOffset:r=8,crossAxisOffset:i=0,contentClassName:o,closeDelay:c=100})=>s.jsx(Bo,{content:t,placement:n,sideOffset:r,crossAxisOffset:i,contentClassName:o||"viewer-popover",closeDelay:c,children:e}),tn={x:0,y:0},uc=.1,mc=5,Ft=.001,Ls=.25,pc=.0025,$s=.08,hc=1,fc=2,gc=16,wc=800,yc=32,xc=88,_c=140,bc=t=>Math.max(uc,Math.min(mc,t)),vc=t=>t.deltaMode===hc?t.deltaY*gc:t.deltaMode===fc?t.deltaY*wc:t.deltaY,Sc=t=>Math.max(-$s,Math.min($s,t)),Ic=(t,e)=>{if(t.offsetWidth>0&&t.offsetHeight>0)return{width:t.offsetWidth,height:t.offsetHeight};const n=t.getBoundingClientRect(),r=Math.max(Math.abs(e),Ft);return{width:n.width/r,height:n.height/r}},eo="media-viewport-toolbar-state-single",kc=()=>{try{const t=localStorage.getItem(eo);if(t)return JSON.parse(t)}catch{}return{orientation:"horizontal",position:null}},Mc=t=>{try{localStorage.setItem(eo,JSON.stringify(t))}catch{}},On=a.forwardRef(({item:t,slotIndex:e,isFocused:n=!1,zoomLevel:r=1,panOffset:i,onClick:o,videoAutoPlay:c=!1,videoLoop:l=!0,onZoomChange:m,onPanChange:u,isCompareMode:d=!1,onInsertToCanvas:p,onDownload:h,onEdit:g,onVideoPlayStateChange:y,onVideoTimeUpdate:f,isSyncMode:x=!1},z)=>{var Ze;const N=a.useRef(null),O=a.useRef(null),T=a.useRef(null),[I,b]=a.useState(!1),[S,C]=a.useState(!0),[R,U]=a.useState(!1),[P,J]=a.useState({x:0,y:0}),[ee,X]=a.useState(i??tn),[Q,B]=a.useState(r),_=a.useRef(r),[E,M]=a.useState(0),[$,re]=a.useState(!1),[fe,K]=a.useState(!1),[de,ie]=a.useState(!1),[ue,xe]=a.useState(!1),[pe,ae]=a.useState(!1),q=a.useRef(null),ce=a.useRef(!1),ve=a.useRef(r),me=a.useRef(i);a.useImperativeHandle(z,()=>({resetVideo:()=>{O.current&&(O.current.currentTime=0,O.current.play().catch(()=>{}))},playVideo:()=>{O.current&&O.current.play().catch(()=>{})},pauseVideo:()=>{O.current&&O.current.pause()},toggleVideoPlayback:()=>{if(O.current){if(O.current.paused||O.current.ended){O.current.play().catch(()=>{});return}O.current.pause()}},setVideoTime:A=>{O.current&&(O.current.currentTime=A)},getVideoTime:()=>{var A;return((A=O.current)==null?void 0:A.currentTime)??0},isVideo:()=>(t==null?void 0:t.type)==="video"}),[t]);const[Re]=a.useState(()=>d?{orientation:"horizontal",position:null}:kc()),[Me,We]=a.useState(Re.orientation),[Ee,Te]=a.useState(Re.position),[Ye,$e]=a.useState(!1),be=a.useRef({x:0,y:0,posX:0,posY:0}),Ie=(t==null?void 0:t.type)==="video",he=(t==null?void 0:t.type)==="audio",ze=((Ze=t==null?void 0:t.prompt)==null?void 0:Ze.trim())||"",De=!!ze&&(de||ue)&&!pe,He=t?Ie||he?t.url:ut(t.url):"",Be=t!=null&&t.posterUrl?ut(t.posterUrl):"",Ge=t?`${t.type}:${t.id||t.url}`:"empty",Qe=!!(t!=null&&t.url&&!he&&!d&&!I),Ne=a.useCallback(()=>{q.current!==null&&(window.clearTimeout(q.current),q.current=null)},[]),L=a.useCallback(()=>{Ne(),ie(!0)},[Ne]),w=a.useCallback(()=>{ie(!1),Ne(),q.current=window.setTimeout(()=>{xe(!1),q.current=null},120)},[Ne]),V=a.useCallback(()=>{Ne(),xe(!0)},[Ne]),v=a.useCallback(()=>{xe(!1)},[]);a.useLayoutEffect(()=>{b(!1),C(!(t!=null&&t.url)||he||d),U(!1);const A=me.current??tn,ge=ve.current;X(A),_.current=ge,B(ge),M(0),re(!1),K(!1),ce.current=!1},[Ge,t==null?void 0:t.url,he,d]),a.useEffect(()=>()=>{Ne()},[Ne]),a.useEffect(()=>{d||Mc({orientation:Me,position:Ee})},[Me,Ee,d]),a.useLayoutEffect(()=>{const A=i??tn;me.current=i,X(ge=>ge.x===A.x&&ge.y===A.y?ge:A)},[i]),a.useLayoutEffect(()=>{ve.current=r,_.current=r,B(A=>A===r?A:r)},[r]);const D=a.useCallback((A,ge="manual")=>{const Le=bc(A);ge==="manual"&&(ce.current=!0),!(Math.abs(_.current-Le)<=Ft)&&(_.current=Le,B(tt=>Math.abs(tt-Le)<=Ft?tt:Le),m==null||m(Le))},[m]),W=a.useCallback(A=>{const ge=me.current??tn;Math.abs(ge.x-A.x)<=Ft&&Math.abs(ge.y-A.y)<=Ft||(me.current=A,X(A),u==null||u(A))},[u]),G=a.useCallback(()=>{if(d||he||!N.current)return;if(ce.current){C(!0);return}const A=Ie?O.current:T.current;if(!A||!N.current)return;const ge=N.current.getBoundingClientRect();if(ge.width<=0||ge.height<=0)return;const Le=Ie?A.videoWidth:A.naturalWidth,tt=Ie?A.videoHeight:A.naturalHeight;if(Le<=0||tt<=0)return;const Xe=Ic(A,_.current);if(Xe.width<=0||Xe.height<=0)return;const Je=Ie?_c:xc,rt=Math.max(ge.width-yc,0),mt=Math.max(ge.height-Je,0);if(rt<=0||mt<=0)return;const ct=Math.min(rt/Xe.width,mt/Xe.height);!Number.isFinite(ct)||ct<=0||(W({x:0,y:-Je/2}),D(ct,"auto"),C(!0))},[d,he,Ie,W,D]);a.useLayoutEffect(()=>{if(!(t!=null&&t.url)||he||d)return;const A=Ie?O.current:T.current;if(!A)return;if(Ie){A.readyState>=1&&G();return}const ge=A;ge.complete&&ge.naturalWidth>0&&G()},[t,he,d,Ie,G]),a.useEffect(()=>{if(!(t!=null&&t.url)||he||d||typeof ResizeObserver>"u"||!N.current)return;const A=new ResizeObserver(()=>{G()});return A.observe(N.current),()=>{A.disconnect()}},[t==null?void 0:t.url,he,d,G]);const Y=a.useCallback(A=>{A.button===0&&(A.preventDefault(),U(!0),J({x:A.clientX-ee.x,y:A.clientY-ee.y}))},[ee]),le=a.useCallback(A=>{if(!R)return;ce.current=!0;const ge={x:A.clientX-P.x,y:A.clientY-P.y};me.current=ge,X(ge),u==null||u(ge)},[R,P,u]),_e=a.useCallback(()=>{U(!1)},[]),k=a.useCallback(A=>{A.preventDefault();const ge=vc(A);if(!Number.isFinite(ge)||ge===0)return;const Le=Sc(-ge*pc);D(_.current+Le)},[D]),H=a.useCallback(()=>{D(_.current+Ls)},[D]),F=a.useCallback(()=>{D(_.current-Ls)},[D]),Z=a.useCallback(()=>{M(A=>A-90)},[]),oe=a.useCallback(()=>{M(A=>A+90)},[]),te=a.useCallback(()=>{re(A=>!A)},[]),Pe=a.useCallback(()=>{K(A=>!A)},[]),Ce=a.useCallback(async()=>{if(t)try{const A=t.type==="video"?"video":"image";if(t.type==="audio"){Ke.warning("音频暂不支持直接插入到画布");return}const ge=await dc(A,He);ge.success?Ke.success(t.type==="video"?"视频已插入到画布":"图片已插入到画布"):Ke.error(ge.error||"插入失败")}catch(A){console.error("Failed to insert to canvas:",A),Ke.error("插入失败")}},[t,He]),Ae=a.useCallback(()=>{We(A=>A==="horizontal"?"vertical":"horizontal")},[]),qe=a.useCallback(A=>{A.preventDefault(),A.stopPropagation(),$e(!0);const ge=Ee||{x:0,y:0};be.current={x:A.clientX,y:A.clientY,posX:ge.x,posY:ge.y};const Le=Xe=>{const Je=Xe.clientX-be.current.x,rt=Xe.clientY-be.current.y;Te({x:be.current.posX+Je,y:be.current.posY+rt})},tt=()=>{$e(!1),document.removeEventListener("mousemove",Le),document.removeEventListener("mouseup",tt)};document.addEventListener("mousemove",Le),document.addEventListener("mouseup",tt)},[Ee]),et=a.useCallback(A=>{if(A.stopPropagation(),A.touches.length!==1)return;const ge=A.touches[0];$e(!0);const Le=Ee||{x:0,y:0};be.current={x:ge.clientX,y:ge.clientY,posX:Le.x,posY:Le.y};const tt=Je=>{if(Je.touches.length!==1)return;Je.preventDefault();const rt=Je.touches[0],mt=rt.clientX-be.current.x,ct=rt.clientY-be.current.y;Te({x:be.current.posX+mt,y:be.current.posY+ct})},Xe=()=>{$e(!1),document.removeEventListener("touchmove",tt),document.removeEventListener("touchend",Xe),document.removeEventListener("touchcancel",Xe)};document.addEventListener("touchmove",tt,{passive:!1}),document.addEventListener("touchend",Xe),document.addEventListener("touchcancel",Xe)},[Ee]),Ve=a.useCallback(()=>{Te(null)},[]);if(!t)return s.jsx("div",{className:`media-viewport media-viewport--empty ${n?"media-viewport--focused":""}`,onClick:o,children:s.jsx("div",{className:"media-viewport__placeholder",children:s.jsx("span",{children:"点击底部缩略图添加媒体"})})});const j=$?-Q:Q,ne=fe?-Q:Q,we={transform:`translate(${ee.x}px, ${ee.y}px) scale(${j}, ${ne}) rotate(${E}deg)`},Oe=Qe&&!S;return s.jsxs("div",{ref:N,className:`media-viewport ${n?"media-viewport--focused":""} ${he?"media-viewport--audio":""} ${Ie?"media-viewport--video":""} ${d?"":"media-viewport--single"}`,onClick:o,onMouseDown:he?void 0:Y,onMouseMove:he?void 0:le,onMouseUp:he?void 0:_e,onWheel:he?void 0:k,onMouseLeave:()=>{he||_e(),ie(!1),xe(!1),ae(!1),Ne()},"data-slot":e,children:[s.jsx("div",{className:`media-viewport__content ${Oe?"media-viewport__content--auto-fitting":""}`,style:he?void 0:we,children:Ie?s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx("video",{ref:O,src:He,autoPlay:c,loop:l,controls:!0,className:"media-viewport__video",referrerPolicy:"no-referrer",onClick:A=>A.stopPropagation(),onPlay:()=>{x&&y&&y(!0)},onPause:()=>{x&&y&&y(!1)},onSeeked:()=>{x&&f&&O.current&&f(O.current.currentTime)},onLoadedMetadata:G})}):he?s.jsx("div",{className:"media-viewport__audio-shell",onClick:A=>A.stopPropagation(),children:s.jsxs("div",{className:"media-viewport__audio-card",children:[s.jsx(lr,{src:Be,alt:t.alt||t.title||"",imageClassName:"media-viewport__audio-poster",fallbackClassName:"media-viewport__audio-poster media-viewport__audio-poster--fallback",iconSize:56}),s.jsxs("div",{className:"media-viewport__audio-meta",children:[t.title&&s.jsx("div",{className:"media-viewport__audio-title",children:t.title}),typeof t.duration=="number"&&Number.isFinite(t.duration)&&t.duration>0&&s.jsxs("div",{className:"media-viewport__audio-duration",children:[Math.floor(t.duration/60),":",String(Math.round(t.duration%60)).padStart(2,"0")]})]}),s.jsx("audio",{src:He,controls:!0,preload:"metadata",className:"media-viewport__audio",referrerPolicy:"no-referrer"})]})}):I?s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx("div",{className:"media-viewport__image-fallback",children:s.jsx("span",{children:"图片加载失败"})})}):s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx(Tt,{ref:T,src:He,alt:t.alt||t.title||"",className:"media-viewport__image",draggable:!1,showSkeleton:!1,eager:!0,onLoad:G,onError:()=>{b(!0),C(!0)}})})}),s.jsxs("div",{className:`media-viewport__toolbar media-viewport__toolbar--${Me} ${Ye?"media-viewport__toolbar--dragging":""} ${d?"media-viewport__toolbar--compact":""}`,style:!d&&Ee?{transform:`translate(calc(-50% + ${Ee.x}px), ${Ee.y}px)`}:void 0,onMouseEnter:()=>ae(!0),onMouseLeave:()=>ae(!1),onMouseDown:A=>A.stopPropagation(),onClick:A=>A.stopPropagation(),children:[!he&&s.jsxs(s.Fragment,{children:[!d&&s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"拖拽移动工具栏,双击重置位置",placement:"top",contentClassName:"viewer-popover",children:s.jsx("div",{className:"media-viewport__toolbar-handle",onMouseDown:qe,onTouchStart:et,onDoubleClick:A=>{A.stopPropagation(),Ve()},children:s.jsx(Go,{size:14})})}),s.jsx(ke,{content:Me==="horizontal"?"切换为垂直布局":"切换为水平布局",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",className:"media-viewport__toolbar-orientation-btn",onClick:A=>{A.stopPropagation(),A.preventDefault(),Ae()},children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Me==="horizontal"?s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("polyline",{points:"8 7 12 3 16 7"}),s.jsx("polyline",{points:"8 17 12 21 16 17"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),s.jsx("polyline",{points:"7 8 3 12 7 16"}),s.jsx("polyline",{points:"17 8 21 12 17 16"})]})})})}),s.jsx("div",{className:"media-viewport__toolbar-divider"})]}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"缩小",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"缩小",onClick:A=>{A.stopPropagation(),A.preventDefault(),F()},children:s.jsx(dr,{size:16})})}),s.jsxs("span",{className:"media-viewport__zoom-level",children:[Math.round(Q*100),"%"]}),s.jsx(ke,{content:"放大",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"放大",onClick:A=>{A.stopPropagation(),A.preventDefault(),H()},children:s.jsx(ur,{size:16})})})]}),s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"向左旋转 90°",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"向左旋转 90°",onClick:A=>{A.stopPropagation(),A.preventDefault(),Z()},children:s.jsx(Kt,{size:16})})}),s.jsx(ke,{content:"向右旋转 90°",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"向右旋转 90°",onClick:A=>{A.stopPropagation(),A.preventDefault(),oe()},children:s.jsx(mr,{size:16})})})]}),s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"水平翻转",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"水平翻转",className:$?"active":"",onClick:A=>{A.stopPropagation(),A.preventDefault(),te()},children:s.jsx(pr,{size:16})})}),s.jsx(ke,{content:"垂直翻转",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"垂直翻转",className:fe?"active":"",onClick:A=>{A.stopPropagation(),A.preventDefault(),Pe()},children:s.jsx(hr,{size:16})})})]})]}),!d&&!he&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsx(ke,{content:"插入到画布",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),p?p():Ce()},children:s.jsx(fr,{size:16})})})]}),!d&&h&&s.jsxs(s.Fragment,{children:[he&&s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsx(ke,{content:"下载",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),h()},children:s.jsx(gr,{size:16})})})]}),!d&&g&&(t==null?void 0:t.type)==="image"&&s.jsx(ke,{content:"编辑图片",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),g()},children:s.jsx(wr,{size:16})})})]}),ze&&!he&&s.jsx(ke,{content:ze,placement:"bottom",sideOffset:10,contentClassName:"viewer-popover viewer-popover--prompt",children:s.jsx("div",{className:`media-viewport__prompt ${De?"media-viewport__prompt--visible":""} ${ue?"media-viewport__prompt--expanded":""}`,onMouseEnter:V,onMouseLeave:v,children:ze})})]})});On.displayName="MediaViewport";const Cc=({src:t,fallbackSrc:e,alt:n})=>{const[r,i]=a.useState(t),[o,c]=a.useState(!1);return a.useEffect(()=>{i(t),c(!1)},[t]),o?s.jsx("div",{className:"thumbnail-queue__image thumbnail-queue__image-fallback",children:s.jsx("span",{children:"加载失败"})}):s.jsx(Tt,{src:r,alt:n,className:"thumbnail-queue__image",showSkeleton:!1,onError:()=>{if(e&&r!==e){i(e);return}c(!0)}})};function jc(t,e="small"){const n=ut(t);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||Zo(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",e),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${e}`}}const Tc=({items:t,mode:e,currentIndex:n,compareIndices:r,onThumbnailClick:i,onDragStart:o})=>{const c=a.useRef(null),[l,m]=a.useState(null);a.useEffect(()=>{if(e==="single"&&c.current){const y=c.current.querySelector(".thumbnail-queue__item--active");y&&y.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}},[n,e]);const u=a.useCallback((y,f)=>{f.dataTransfer.setData("text/plain",String(y)),f.dataTransfer.effectAllowed="move",m(y),o==null||o(y)},[o]),d=a.useCallback(()=>{m(null)},[]),p=a.useCallback(y=>e==="single"?y===n:r.includes(y),[e,n,r]),h=a.useCallback(y=>{if(e!=="compare")return;const f=r.indexOf(y);return f>=0?f+1:void 0},[e,r]),g=a.useCallback((y,f)=>{const x=p(f),z=h(f),N=l===f,O=y.type==="video",T=y.type==="audio",I=ut(y.url),b=y.posterUrl?ut(y.posterUrl):"",S=jc(T&&b?b:I,"small");return s.jsxs("div",{className:`thumbnail-queue__item ${x?"thumbnail-queue__item--active":""} ${N?"thumbnail-queue__item--dragging":""}`,onClick:()=>i(f),draggable:e==="compare",onDragStart:C=>u(f,C),onDragEnd:d,role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),i(f))},children:[s.jsx("div",{className:"thumbnail-queue__thumb",children:O?s.jsxs(s.Fragment,{children:[s.jsx(sc,{src:I,poster:b||void 0,className:"thumbnail-queue__video",alt:y.alt||y.title||"",thumbnailSize:"small",videoProps:{muted:!0,preload:"metadata"}}),s.jsx("div",{className:"thumbnail-queue__video-icon",children:s.jsx(yr,{size:16})})]}):T?s.jsxs(s.Fragment,{children:[s.jsx(lr,{src:b?S:void 0,fallbackSrc:b,alt:y.alt||y.title||"",imageClassName:"thumbnail-queue__image",fallbackClassName:"thumbnail-queue__image thumbnail-queue__audio-fallback",iconSize:18,loading:"lazy"}),s.jsx("div",{className:"thumbnail-queue__video-icon",children:s.jsx(qo,{size:16})})]}):s.jsx(Cc,{src:S,alt:y.alt||y.title||"",fallbackSrc:I})}),x&&s.jsx("div",{className:"thumbnail-queue__check",children:z?s.jsx("span",{className:"thumbnail-queue__slot-number",children:z}):s.jsx(Ko,{size:18})})]},y.id||`${y.url}-${f}`)},[p,h,l,e,i,u,d]);return t.length===0?null:s.jsx("div",{className:"thumbnail-queue",ref:c,children:s.jsx("div",{className:"thumbnail-queue__list",children:t.map((y,f)=>g(y,f))})})},Nc=({mode:t,currentIndex:e,totalCount:n,slotCount:r,compareLayout:i,syncMode:o,onModeChange:c,onSlotCountChange:l,onLayoutChange:m,onSyncToggle:u,onResetView:d,onClose:p,onFullscreen:h,isImage:g=!1,showEditButton:y=!1,onBackToPreview:f,onResetEdit:x,onSaveEdit:z})=>{const N=a.useCallback(C=>{m(C),C==="grid"&&r<4&&l(4)},[m,l,r]),O=()=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"viewer-toolbar__indicator",children:[s.jsx("span",{className:"viewer-toolbar__current",children:e+1}),s.jsx("span",{className:"viewer-toolbar__separator",children:"/"}),s.jsx("span",{className:"viewer-toolbar__total",children:n})]}),n>1&&s.jsx(ke,{content:"对比模式",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>c("compare"),"aria-label":"对比模式",children:s.jsx(bs,{size:18})})}),y&&g&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx(ke,{content:"编辑图片",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>c("edit"),"aria-label":"编辑图片",children:s.jsx(wr,{size:18})})})]})]}),T=()=>s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__btn",onClick:f,"aria-label":"返回预览",children:[s.jsx(cn,{size:18}),s.jsx("span",{className:"viewer-toolbar__btn-text",children:"返回"})]})}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx("div",{className:"viewer-toolbar__title",children:"编辑图片"})]}),I=()=>s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"单图模式",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__btn",onClick:()=>c("single"),"aria-label":"单图模式",children:[s.jsx(cn,{size:18}),s.jsx("span",{className:"viewer-toolbar__btn-text",children:"单图"})]})}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsxs("div",{className:"viewer-toolbar__group",children:[s.jsx("span",{className:"viewer-toolbar__label",children:"分屏"}),[2,3,4].map(C=>s.jsx(it.Fragment,{children:s.jsx(ke,{content:`${C}分屏`,placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn viewer-toolbar__btn--small ${r===C?"viewer-toolbar__btn--active":""}`,onClick:()=>l(C),"aria-label":`${C}分屏`,children:C})})},C))]}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsxs("div",{className:"viewer-toolbar__group",children:[s.jsx(ke,{content:"水平布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="horizontal"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("horizontal"),"aria-label":"水平布局",children:s.jsx(bs,{size:18})})}),s.jsx(ke,{content:"垂直布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="vertical"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("vertical"),"aria-label":"垂直布局",children:s.jsx(Yo,{size:18})})}),s.jsx(ke,{content:"网格布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="grid"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("grid"),"aria-label":"网格布局",children:s.jsx(Xo,{size:18})})})]}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx(ke,{content:o?"取消联动(快捷键 S)":"联动缩放/拖拽(快捷键 S)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${o?"viewer-toolbar__btn--active":""}`,onClick:u,"aria-label":o?"取消联动":"联动缩放/拖拽",children:o?s.jsx(Jo,{size:18}):s.jsx(Qo,{size:18})})}),o&&s.jsx(ke,{content:"重置视图",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:d,children:s.jsx(Kt,{size:18})})})]}),b=()=>{switch(t){case"edit":return T();case"compare":return I();default:return O()}},S=()=>t==="edit"?s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"重置",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:x,children:s.jsx(Kt,{size:18})})}),s.jsx(ke,{content:"保存",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--primary",onClick:z,"aria-label":"保存",children:s.jsx(gn,{size:18})})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]}):s.jsxs(s.Fragment,{children:[h&&s.jsx(ke,{content:"全屏",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:h,children:s.jsx(xr,{size:18})})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]});return t==="edit"?s.jsxs("div",{className:"viewer-toolbar viewer-toolbar--edit-simplified",children:[s.jsx(ke,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--left",onClick:f,"aria-label":"返回预览",children:[s.jsx(cn,{size:20}),s.jsx("span",{children:"返回"})]})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--right",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]}):s.jsxs("div",{className:"viewer-toolbar",children:[s.jsx("div",{className:"viewer-toolbar__left",children:b()}),s.jsx("div",{className:"viewer-toolbar__right",children:S()})]})},_t={brightness:100,contrast:100,saturate:100,blur:0,grayscale:0,sepia:0,hueRotate:0,invert:0},Ec=[{label:"自由",value:null},{label:"1:1",value:1},{label:"4:3",value:4/3},{label:"3:4",value:3/4},{label:"16:9",value:16/9},{label:"9:16",value:9/16},{label:"3:2",value:3/2},{label:"2:3",value:2/3}],Os=[{label:"原图",type:"none",filter:"none"},{label:"黑白",type:"grayscale",filter:"grayscale(100%)"},{label:"怀旧",type:"sepia",filter:"sepia(80%)"},{label:"复古",type:"vintage",filter:"sepia(40%) contrast(110%) brightness(90%)"},{label:"冷色",type:"cold",filter:"saturate(80%) hue-rotate(180deg) brightness(105%)"},{label:"暖色",type:"warm",filter:"saturate(120%) sepia(20%) brightness(105%)"},{label:"高对比",type:"contrast",filter:"contrast(150%)"},{label:"高饱和",type:"saturate",filter:"saturate(180%)"},{label:"反转",type:"invert",filter:"invert(100%)"}],Pc=({aspectRatio:t,presets:e,onAspectRatioChange:n,rotation:r,flipH:i,flipV:o,onRotate:c,onFlipH:l,onFlipV:m,onConfirmCrop:u,hasCropArea:d=!1,onAutoTrimWhitespace:p,isDetectingWhitespace:h=!1})=>s.jsxs("div",{className:"crop-panel",children:[p&&s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"智能裁剪"}),s.jsxs("button",{type:"button",className:`crop-panel__auto-trim-btn ${h?"loading":""}`,onClick:p,disabled:h,children:[s.jsx(ei,{size:16}),s.jsx("span",{children:h?"检测中...":"智能去白边"})]}),s.jsx("div",{className:"crop-panel__auto-trim-hint",children:"自动检测并移除图片周围的白色边框"})]}),s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"裁剪比例"}),s.jsx("div",{className:"crop-panel__ratio-grid",children:e.map(g=>s.jsx("button",{type:"button",className:`crop-panel__ratio-btn ${t===g.value?"active":""}`,onClick:()=>n(g.value),children:g.label},g.label))})]}),s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"旋转和翻转"}),s.jsxs("div",{className:"crop-panel__transform-row",children:[s.jsx(je,{content:"向左旋转 90°",placement:"top",children:s.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>c(-90),children:s.jsx(Kt,{size:18})})}),s.jsx(je,{content:"向右旋转 90°",placement:"top",children:s.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>c(90),children:s.jsx(mr,{size:18})})}),s.jsx(je,{content:"水平翻转",placement:"top",children:s.jsx("button",{type:"button",className:`crop-panel__transform-btn ${i?"active":""}`,onClick:l,children:s.jsx(pr,{size:18})})}),s.jsx(je,{content:"垂直翻转",placement:"top",children:s.jsx("button",{type:"button",className:`crop-panel__transform-btn ${o?"active":""}`,onClick:m,children:s.jsx(hr,{size:18})})})]}),r!==0&&s.jsxs("div",{className:"crop-panel__rotation-info",children:["当前旋转: ",r,"°"]})]}),u&&s.jsxs("div",{className:"crop-panel__section",children:[s.jsxs("button",{type:"button",className:`crop-panel__confirm-btn ${d?"":"disabled"}`,onClick:u,disabled:!d,children:[s.jsx(gn,{size:16}),s.jsx("span",{children:"应用裁剪"})]}),s.jsx("div",{className:"crop-panel__confirm-hint",children:"按 Enter 键快速确认"})]}),s.jsxs("div",{className:"crop-panel__tips",children:[s.jsx("p",{children:"拖动裁剪框调整位置"}),s.jsx("p",{children:"拖动边角调整大小"})]})]}),Ac=({filterType:t,filterParams:e,presets:n,imageUrl:r,onPresetSelect:i,onParamChange:o})=>s.jsxs("div",{className:"filter-panel",children:[s.jsxs("div",{className:"filter-panel__section",children:[s.jsx("div",{className:"filter-panel__section-title",children:"滤镜预设"}),s.jsx("div",{className:"filter-panel__preset-grid",children:n.map(c=>s.jsxs("button",{type:"button",className:`filter-panel__preset-btn ${t===c.type?"active":""}`,onClick:()=>i(c.type),children:[s.jsx("div",{className:"filter-panel__preset-preview",style:{backgroundImage:`url(${r})`,filter:c.filter}}),s.jsx("span",{className:"filter-panel__preset-label",children:c.label})]},c.type))})]}),s.jsxs("div",{className:"filter-panel__section",children:[s.jsx("div",{className:"filter-panel__section-title",children:"参数调节"}),s.jsxs("div",{className:"filter-panel__sliders",children:[s.jsx(bt,{label:"亮度",value:e.brightness,min:0,max:200,defaultValue:100,onChange:c=>o("brightness",c)}),s.jsx(bt,{label:"对比度",value:e.contrast,min:0,max:200,defaultValue:100,onChange:c=>o("contrast",c)}),s.jsx(bt,{label:"饱和度",value:e.saturate,min:0,max:200,defaultValue:100,onChange:c=>o("saturate",c)}),s.jsx(bt,{label:"灰度",value:e.grayscale,min:0,max:100,defaultValue:0,onChange:c=>o("grayscale",c)}),s.jsx(bt,{label:"复古",value:e.sepia,min:0,max:100,defaultValue:0,onChange:c=>o("sepia",c)}),s.jsx(bt,{label:"色相",value:e.hueRotate,min:0,max:360,defaultValue:0,onChange:c=>o("hueRotate",c)}),s.jsx(bt,{label:"模糊",value:e.blur,min:0,max:10,defaultValue:0,step:.5,onChange:c=>o("blur",c)})]})]})]}),bt=({label:t,value:e,min:n,max:r,defaultValue:i,step:o=1,onChange:c})=>{const l=e===i;return s.jsxs("div",{className:"filter-slider",children:[s.jsxs("div",{className:"filter-slider__header",children:[s.jsx("span",{className:"filter-slider__label",children:t}),s.jsx("span",{className:`filter-slider__value ${l?"":"modified"}`,children:e})]}),s.jsx(ti,{value:e,min:n,max:r,step:o,onChange:m=>c(m)})]})},pt=10010;function Rc(t,e={}){const{threshold:n=250,tolerance:r=.02,minContentSize:i=50}=e,o=t.naturalWidth,c=t.naturalHeight,l=document.createElement("canvas");l.width=o,l.height=c;const m=l.getContext("2d");if(!m)return null;m.drawImage(t,0,0);const d=m.getImageData(0,0,o,c).data,p=b=>{const S=d[b],C=d[b+1],R=d[b+2];return d[b+3]<10?!0:S>=n&&C>=n&&R>=n},h=b=>{let S=0;for(let C=0;C<o;C++){const R=(b*o+C)*4;p(R)&&S++}return S/o>=1-r},g=b=>{let S=0;for(let C=0;C<c;C++){const R=(C*o+b)*4;p(R)&&S++}return S/c>=1-r};let y=0;for(;y<c&&h(y);)y++;let f=c-1;for(;f>y&&h(f);)f--;let x=0;for(;x<o&&g(x);)x++;let z=o-1;for(;z>x&&g(z);)z--;const N=z-x+1,O=f-y+1,T=y>0||x>0||z<o-1||f<c-1,I=N>=i&&O>=i;return!T||!I?null:{x,y,width:N,height:O}}const to=a.forwardRef(({imageUrl:t,showOverwrite:e=!1,onOverwrite:n,onInsert:r,onClose:i,onSave:o,className:c},l)=>{const[m,u]=a.useState("crop"),[d,p]=a.useState(null),[h,g]=a.useState(null),[y,f]=a.useState("none"),[x,z]=a.useState(_t),[N,O]=a.useState(0),[T,I]=a.useState(!1),[b,S]=a.useState(!1),[C,R]=a.useState({width:0,height:0}),[U,P]=a.useState(1),[J,ee]=a.useState(1),X=.1,Q=5,B=.1,[_,E]=a.useState({x:0,y:0}),[M,$]=a.useState(!1),[re,fe]=a.useState({x:0,y:0}),[K,de]=a.useState(!1),[ie,ue]=a.useState(null),[xe,pe]=a.useState(!1),[ae,q]=a.useState(null),[ce,ve]=a.useState(!1),[me,Re]=a.useState([]),[Me,We]=a.useState(-1),Ee=a.useRef(!1),Te=a.useRef(null),Ye=a.useRef(null),$e=a.useRef(null);a.useEffect(()=>{$e.current!==null&&$e.current!==t&&(p(null),q(null),g(null),f("none"),z(_t),O(0),I(!1),S(!1),ee(1),P(1),R({width:0,height:0}),E({x:0,y:0}),u("crop"),Re([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:_t,rotation:0,flipH:!1,flipV:!1}]),We(0)),$e.current=t},[t]),a.useEffect(()=>{if(!t)return;const j=new Image;return j.crossOrigin="anonymous",j.onload=()=>{Te.current=j,R({width:j.naturalWidth,height:j.naturalHeight})},j.onerror=()=>{Ke.error("图片加载失败")},j.src=t,()=>{Te.current=null}},[t]),a.useEffect(()=>{t&&me.length===0&&(Re([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:_t,rotation:0,flipH:!1,flipV:!1}]),We(0))},[t,me.length]),a.useEffect(()=>{if(!Ye.current||C.width===0)return;const j=()=>{const we=Ye.current;if(!we)return;const Oe=we.clientWidth-80,Ze=we.clientHeight-80;if(Oe<=0||Ze<=0)return;const A=Oe/C.width,ge=Ze/C.height,Le=Math.min(A,ge,1);Le>0&&isFinite(Le)&&P(Le)};requestAnimationFrame(j);const ne=new ResizeObserver(j);return ne.observe(Ye.current),()=>ne.disconnect()},[C]);const be=a.useRef(null);a.useEffect(()=>{if(!(Ee.current||me.length===0))return be.current&&clearTimeout(be.current),be.current=setTimeout(()=>{He()},300),()=>{be.current&&clearTimeout(be.current)}},[N,T,b,y,x,h,ae]);const Ie=a.useCallback(()=>{if(y!=="none"){const ne=Os.find(we=>we.type===y);if(ne)return ne.filter}const j=[];return x.brightness!==100&&j.push(`brightness(${x.brightness}%)`),x.contrast!==100&&j.push(`contrast(${x.contrast}%)`),x.saturate!==100&&j.push(`saturate(${x.saturate}%)`),x.blur>0&&j.push(`blur(${x.blur}px)`),x.grayscale>0&&j.push(`grayscale(${x.grayscale}%)`),x.sepia>0&&j.push(`sepia(${x.sepia}%)`),x.hueRotate!==0&&j.push(`hue-rotate(${x.hueRotate}deg)`),x.invert>0&&j.push(`invert(${x.invert}%)`),j.length>0?j.join(" "):"none"},[y,x]),he=a.useCallback(()=>{const j=[];return N!==0&&j.push(`rotate(${N}deg)`),T&&j.push("scaleX(-1)"),b&&j.push("scaleY(-1)"),j.length>0?j.join(" "):"none"},[N,T,b]),ze=a.useCallback(()=>({cropArea:d,confirmedCropArea:ae,aspectRatio:h,filterType:y,filterParams:x,rotation:N,flipH:T,flipV:b}),[d,ae,h,y,x,N,T,b]),De=a.useCallback(j=>{Ee.current=!0,p(j.cropArea),q(j.confirmedCropArea),g(j.aspectRatio),f(j.filterType),z(j.filterParams),O(j.rotation),I(j.flipH),S(j.flipV),requestAnimationFrame(()=>{Ee.current=!1})},[]),He=a.useCallback(()=>{if(Ee.current)return;const j=ze();Re(ne=>{const we=ne.slice(0,Me+1);return we.push(j),we.length>50&&we.shift(),we}),We(ne=>Math.min(ne+1,49))},[ze,Me]),Be=a.useCallback(()=>{if(Me<=0)return;const j=Me-1;We(j),De(me[j])},[Me,me,De]),Ge=a.useCallback(()=>{if(Me>=me.length-1)return;const j=Me+1;We(j),De(me[j])},[Me,me,De]),Qe=Me>0,Ne=Me<me.length-1,L=a.useCallback(()=>ae!==null||d!==null||N!==0||T||b||y!=="none"||Object.keys(x).some(j=>x[j]!==_t[j]),[ae,d,N,T,b,y,x]),w=a.useCallback(()=>{p(null),q(null),g(null),f("none"),z(_t),O(0),I(!1),S(!1),ee(1),E({x:0,y:0}),Re([]),We(-1)},[]),V=a.useCallback(async()=>{const j=Te.current;if(!j){Ke.error("图片未加载");return}const ne=Ke.loading("正在处理图片...",0);try{const we=document.createElement("canvas"),Oe=we.getContext("2d");if(!Oe)throw new Error("无法创建 Canvas 上下文");let Ze=j.naturalWidth,A=j.naturalHeight,ge=0,Le=0,tt=j.naturalWidth,Xe=j.naturalHeight;const Je=ae||d;Je&&(ge=Je.x,Le=Je.y,tt=Je.width,Xe=Je.height,Ze=Je.width,A=Je.height);const rt=(N%360+360)%360;(rt===90||rt===270)&&([Ze,A]=[A,Ze]),we.width=Ze,we.height=A,Oe.save(),Oe.translate(Ze/2,A/2),N!==0&&Oe.rotate(N*Math.PI/180),T&&Oe.scale(-1,1),b&&Oe.scale(1,-1);let mt=tt,ct=Xe;(rt===90||rt===270)&&([mt,ct]=[ct,mt]);const ys=Ie();ys!=="none"&&(Oe.filter=ys),Oe.drawImage(j,ge,Le,tt,Xe,-mt/2,-ct/2,mt,ct),Oe.restore();const xs=we.toDataURL("image/png");if(Ke.close(ne),o){o(xs);return}ue(xs),de(!0)}catch(we){Ke.close(ne),Ke.error(we instanceof Error?we.message:"图片处理失败")}},[ae,d,N,T,b,Ie,o]),v=a.useCallback(j=>{if(ie){switch(j){case"overwrite":n==null||n(ie);break;case"insert":r==null||r(ie);break;case"download":{const ne=document.createElement("a");ne.href=ie,ne.download=`edited-image-${Date.now()}.png`,ne.click(),Ke.success("图片已下载");break}}de(!1),ue(null),i==null||i()}},[ie,n,r,i]),D=a.useCallback(j=>{g(j),p(null),q(null)},[]),W=a.useCallback(j=>{f(j),j!=="none"&&z(_t)},[]),G=a.useCallback((j,ne)=>{z(we=>({...we,[j]:ne})),f("none")},[]),Y=a.useCallback(j=>{O(ne=>ne+j)},[]),le=a.useCallback(()=>{I(j=>!j)},[]),_e=a.useCallback(()=>{S(j=>!j)},[]),k=a.useCallback(()=>{!d||!Te.current||(q({...d}),u("filter"))},[d]),H=a.useCallback(()=>{const j=Te.current;if(!j){Ke.warning("图片未加载完成");return}ve(!0),requestAnimationFrame(()=>{try{const ne=Rc(j);ne?(g(null),p(ne),Ke.success("已检测到白边,裁剪框已自动调整")):Ke.info("未检测到明显的白边")}catch{Ke.error("检测白边失败")}finally{ve(!1)}})},[]);a.useEffect(()=>{const j=ne=>{ne.target instanceof HTMLInputElement||ne.target instanceof HTMLTextAreaElement||(ne.key==="Enter"&&m==="crop"&&d&&(ne.preventDefault(),k()),(ne.ctrlKey||ne.metaKey)&&ne.key==="z"&&!ne.shiftKey&&(ne.preventDefault(),Be()),(ne.ctrlKey||ne.metaKey)&&(ne.key==="y"||ne.key==="z"&&ne.shiftKey)&&(ne.preventDefault(),Ge()))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[m,d,k,Be,Ge]);const F=a.useCallback(()=>{ee(j=>Math.min(j+B,Q))},[]),Z=a.useCallback(()=>{ee(j=>Math.max(j-B,X))},[]),oe=a.useCallback(()=>{ee(1),E({x:0,y:0})},[]),te=a.useCallback(j=>{j.preventDefault();const ne=Math.abs(j.deltaY);let we;ne>50?we=j.deltaY>0?-.15:.15:we=-j.deltaY*.008,ee(Oe=>Math.max(X,Math.min(Q,Oe+we)))},[]);a.useEffect(()=>{const j=Ye.current;if(j)return j.addEventListener("wheel",te,{passive:!1}),()=>j.removeEventListener("wheel",te)},[te]);const Pe=a.useCallback(j=>{j==="crop"&&ae&&!d&&p({...ae}),u(j)},[ae,d]),Ce=a.useCallback(j=>{m!=="crop"&&($(!0),fe({x:j.clientX-_.x,y:j.clientY-_.y}))},[m,_]),Ae=a.useCallback(j=>{M&&E({x:j.clientX-re.x,y:j.clientY-re.y})},[M,re]),qe=a.useCallback(()=>{$(!1)},[]);a.useEffect(()=>{if(!M)return;const j=we=>{E({x:we.clientX-re.x,y:we.clientY-re.y})},ne=()=>{$(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",ne),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",ne)}},[M,re]),a.useEffect(()=>{ee(1),E({x:0,y:0})},[m]),a.useImperativeHandle(l,()=>({reset:w,save:V,hasChanges:L,getState:ze,setState:De}));const et=Ie(),Ve=he();return s.jsxs("div",{className:`image-editor-core ${c||""}`,children:[s.jsxs("div",{className:"image-editor-core__header",children:[s.jsx("div",{className:"image-editor-core__title",children:"编辑图片"}),s.jsxs("div",{className:"image-editor-core__actions",children:[s.jsx(je,{content:"撤销 (Ctrl+Z)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${Qe?"":"disabled"}`,onClick:Be,disabled:!Qe,children:s.jsx(ni,{size:18})})}),s.jsx(je,{content:"重做 (Ctrl+Y)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${Ne?"":"disabled"}`,onClick:Ge,disabled:!Ne,children:s.jsx(si,{size:18})})}),s.jsx("div",{className:"image-editor-core__divider"}),s.jsx(je,{content:"对比原图(按住查看)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${xe?"active":""}`,onMouseDown:()=>pe(!0),onMouseUp:()=>pe(!1),onMouseLeave:()=>pe(!1),children:s.jsx(ri,{size:18})})}),s.jsx(je,{content:"重置",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:w,children:s.jsx(Kt,{size:18})})}),i&&s.jsx(je,{content:"取消",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:i,children:s.jsx(Mt,{size:18})})}),(o||n||r)&&s.jsx(je,{content:"保存",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn image-editor-core__btn--primary",onClick:V,children:s.jsx(gn,{size:18})})})]})]}),s.jsxs("div",{className:"image-editor-core__main",children:[s.jsxs("div",{className:"image-editor-core__sidebar",children:[s.jsxs("div",{className:"image-editor-core__mode-tabs",children:[s.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${m==="crop"?"active":""}`,onClick:()=>Pe("crop"),children:[s.jsx(oi,{size:16}),s.jsx("span",{children:"裁剪"})]}),s.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${m==="filter"?"active":""}`,onClick:()=>Pe("filter"),children:[s.jsx(ii,{size:16}),s.jsx("span",{children:"滤镜"})]})]}),s.jsx("div",{className:"image-editor-core__panel",children:m==="crop"?s.jsx(Pc,{aspectRatio:h,presets:Ec,onAspectRatioChange:D,rotation:N,flipH:T,flipV:b,onRotate:Y,onFlipH:le,onFlipV:_e,onConfirmCrop:k,hasCropArea:!!d,onAutoTrimWhitespace:H,isDetectingWhitespace:ce}):s.jsx(Ac,{filterType:y,filterParams:x,presets:Os,imageUrl:t,onPresetSelect:W,onParamChange:G})})]}),s.jsxs("div",{className:"image-editor-core__preview",ref:Ye,onMouseDown:Ce,onMouseMove:Ae,onMouseUp:qe,onMouseLeave:qe,style:{cursor:M?"grabbing":"grab"},children:[s.jsx("div",{className:"image-editor-core__canvas-wrapper",style:{transform:`translate(${_.x}px, ${_.y}px)`},children:xe?ae?(()=>{const j=ae.y/C.height*100,ne=(C.width-ae.x-ae.width)/C.width*100,we=(C.height-ae.y-ae.height)/C.height*100,Oe=ae.x/C.width*100;return s.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ve} scale(${U*J})`.trim(),clipPath:`inset(${j}% ${ne}% ${we}% ${Oe}%)`},children:s.jsx("img",{src:t,alt:"Original",draggable:!1})})})():s.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ve} scale(${U*J})`.trim()},children:s.jsx("img",{src:t,alt:"Original",draggable:!1})}):m==="crop"?s.jsx(zc,{imageUrl:t,imageSize:C,cropArea:d,aspectRatio:h,rotation:N,displayScale:U,flipH:T,flipV:b,zoom:J,filterCSS:et,onCropChange:p},t):ae?(()=>{const j=ae.y/C.height*100,ne=(C.width-ae.x-ae.width)/C.width*100,we=(C.height-ae.y-ae.height)/C.height*100,Oe=ae.x/C.width*100;return s.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:et,transform:`${Ve} scale(${U*J})`.trim(),clipPath:`inset(${j}% ${ne}% ${we}% ${Oe}%)`},children:s.jsx("img",{src:t,alt:"Preview",draggable:!1})})})():s.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:et,transform:`${Ve} scale(${U*J})`.trim()},children:s.jsx("img",{src:t,alt:"Preview",draggable:!1})})}),s.jsxs("div",{className:"image-editor-core__zoom-controls",children:[s.jsx(je,{content:"缩小",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:Z,disabled:J<=X,children:s.jsx(dr,{size:16})})}),s.jsxs("span",{className:"image-editor-core__zoom-value",children:[Math.round(J*100),"%"]}),s.jsx(je,{content:"放大",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:F,disabled:J>=Q,children:s.jsx(ur,{size:16})})}),s.jsx(je,{content:"重置视图",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:oe,children:s.jsx(xr,{size:16})})})]})]})]}),K&&ie&&s.jsxs("div",{className:"image-editor-core__save-dialog",children:[s.jsx("div",{className:"image-editor-core__save-dialog-backdrop",onClick:()=>de(!1)}),s.jsxs("div",{className:"image-editor-core__save-dialog-content",children:[s.jsx("h3",{className:"image-editor-core__save-dialog-title",children:"保存图片"}),s.jsxs("div",{className:"image-editor-core__save-options",children:[e&&n&&s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>v("overwrite"),children:[s.jsx(ai,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"覆盖原图"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"替换画布中的原图片"})]})]}),r&&s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>v("insert"),children:[s.jsx(ci,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"插入新图片"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"在画布中插入编辑后的图片"})]})]}),s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>v("download"),children:[s.jsx(gr,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"下载到本地"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"保存编辑后的图片到本地"})]})]})]}),s.jsx("button",{type:"button",className:"image-editor-core__save-cancel",onClick:()=>de(!1),children:"取消"})]})]})]})});to.displayName="ImageEditorCore";const zc=({imageUrl:t,imageSize:e,cropArea:n,aspectRatio:r,rotation:i,flipH:o,flipV:c,zoom:l,displayScale:m,filterCSS:u,onCropChange:d})=>{const p=a.useRef(null),[h,g]=a.useState(!1),[y,f]=a.useState(null),[x,z]=a.useState(null),[N,O]=a.useState({x:0,y:0}),[T,I]=a.useState(null);a.useEffect(()=>{if(!n&&e.width>0){let P;if(r)if(e.width/e.height>r){const ee=e.height,X=ee*r;P={x:(e.width-X)/2,y:0,width:X,height:ee}}else{const ee=e.width,X=ee/r;P={x:0,y:(e.height-X)/2,width:ee,height:X}}else P={x:0,y:0,width:e.width,height:e.height};d(P)}},[r,e,n,d]);const b=a.useCallback((P,J,ee)=>{P.preventDefault(),P.stopPropagation(),g(!0),f(J),z(ee||null),O({x:P.clientX,y:P.clientY}),I(n)},[n]);a.useEffect(()=>{if(!h||!T)return;const P=ee=>{let X=(ee.clientX-N.x)/(m*l),Q=(ee.clientY-N.y)/(m*l);const B=(i%360+360)%360;let _,E;switch(B){case 90:_=Q,E=-X;break;case 180:_=-X,E=-Q;break;case 270:_=-Q,E=X;break;default:_=X,E=Q}o&&(_=-_),c&&(E=-E);const M={...T};if(y==="move")M.x=Math.max(0,Math.min(T.x+_,e.width-T.width)),M.y=Math.max(0,Math.min(T.y+E,e.height-T.height));else if(y==="resize"&&x){switch(x){case"nw":M.x=Math.min(T.x+_,T.x+T.width-20),M.y=Math.min(T.y+E,T.y+T.height-20),M.width=Math.max(20,T.width-_),M.height=Math.max(20,T.height-E);break;case"ne":M.y=Math.min(T.y+E,T.y+T.height-20),M.width=Math.max(20,T.width+_),M.height=Math.max(20,T.height-E);break;case"sw":M.x=Math.min(T.x+_,T.x+T.width-20),M.width=Math.max(20,T.width-_),M.height=Math.max(20,T.height+E);break;case"se":M.width=Math.max(20,T.width+_),M.height=Math.max(20,T.height+E);break;case"n":M.y=Math.min(T.y+E,T.y+T.height-20),M.height=Math.max(20,T.height-E);break;case"s":M.height=Math.max(20,T.height+E);break;case"w":M.x=Math.min(T.x+_,T.x+T.width-20),M.width=Math.max(20,T.width-_);break;case"e":M.width=Math.max(20,T.width+_);break}if(r&&(["e","w","ne","nw","se","sw"].includes(x)?M.height=M.width/r:["n","s"].includes(x)&&(M.width=M.height*r)),M.x<0&&(M.width+=M.x,M.x=0),M.y<0&&(M.height+=M.y,M.y=0),M.width=Math.min(M.width,e.width-M.x),M.height=Math.min(M.height,e.height-M.y),M.width=Math.max(20,M.width),M.height=Math.max(20,M.height),r){const re=M.height*r,fe=M.width/r;M.width>re?M.width=re:M.height>fe&&(M.height=fe)}}d(M)},J=()=>{g(!1),f(null),z(null)};return document.addEventListener("mousemove",P),document.addEventListener("mouseup",J),()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",J)}},[h,y,x,N,T,m,l,i,o,c,e,r,d]);const S=e.width*m*l,C=e.height*m*l,R={transform:`rotate(${i}deg) ${o?"scaleX(-1)":""} ${c?"scaleY(-1)":""}`.trim()},U=P=>{const J={nw:"nw-resize",ne:"ne-resize",sw:"sw-resize",se:"se-resize",n:"n-resize",s:"s-resize",w:"w-resize",e:"e-resize"},ee={nw:"ne",ne:"se",se:"sw",sw:"nw",n:"e",e:"s",s:"w",w:"n"};let X=P;const Q=(i%360+360)%360,B=Math.round(Q/90)%4;for(let _=0;_<B;_++)X=ee[X]||X;return o&&(X.includes("w")?X=X.replace("w","e"):X.includes("e")&&(X=X.replace("e","w"))),c&&(X.includes("n")?X=X.replace("n","s"):X.includes("s")&&(X=X.replace("s","n"))),J[X]||"pointer"};return s.jsx("div",{ref:p,className:"crop-canvas",children:s.jsxs("div",{className:"crop-canvas__image-container",style:{width:S,height:C,...R},children:[s.jsx("img",{src:t,alt:"Crop",draggable:!1,style:{filter:u||"none"}}),n&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"crop-canvas__overlay"}),s.jsxs("div",{className:"crop-canvas__crop-area",style:{left:n.x*m*l,top:n.y*m*l,width:n.width*m*l,height:n.height*m*l},onMouseDown:P=>b(P,"move"),children:[s.jsx("div",{className:"crop-canvas__crop-image",style:{backgroundImage:`url(${t})`,backgroundPosition:`-${n.x*m*l}px -${n.y*m*l}px`,backgroundSize:`${S}px ${C}px`,filter:u||"none"}}),s.jsxs("div",{className:"crop-canvas__grid",children:[s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h1"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h2"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v1"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v2"})]}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--nw",style:{cursor:U("nw")},onMouseDown:P=>b(P,"resize","nw")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--ne",style:{cursor:U("ne")},onMouseDown:P=>b(P,"resize","ne")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--sw",style:{cursor:U("sw")},onMouseDown:P=>b(P,"resize","sw")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--se",style:{cursor:U("se")},onMouseDown:P=>b(P,"resize","se")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--n",style:{cursor:U("n")},onMouseDown:P=>b(P,"resize","n")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--s",style:{cursor:U("s")},onMouseDown:P=>b(P,"resize","s")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--w",style:{cursor:U("w")},onMouseDown:P=>b(P,"resize","w")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--e",style:{cursor:U("e")},onMouseDown:P=>b(P,"resize","e")})]})]})]})})},no=a.forwardRef(({imageUrl:t,showOverwrite:e=!1,onOverwrite:n,onInsert:r},i)=>s.jsx(to,{ref:i,imageUrl:t,showOverwrite:e,onOverwrite:n,onInsert:r,className:"embedded-editor"}));no.displayName="ImageEditorContent";const mn=({visible:t,items:e,initialMode:n="single",initialIndex:r=0,onClose:i,onModeChange:o,showThumbnails:c=!0,maxCompareSlots:l=4,defaultCompareLayout:m="horizontal",className:u="",showTitle:d=!0,videoAutoPlay:p=!1,videoLoop:h=!0,onInsertToCanvas:g,onEdit:y,useBuiltInEditor:f=!1,onEditOverwrite:x,onEditInsert:z,showEditOverwrite:N=!1})=>{const O=a.useRef(null),T=a.useRef(null),[I,b]=a.useState(2),[S,C]=a.useState(!1),[R,U]=a.useState(null),P=a.useRef(null),J=a.useRef(new Map),ee=a.useRef([]),X=a.useRef(null),Q=a.useRef(!1),[B,_]=ic({items:e,initialMode:n,initialIndex:r,maxCompareSlots:l,defaultCompareLayout:m,visible:t,onModeChange:o}),{mode:E,currentIndex:M,compareIndices:$,compareLayout:re,syncMode:fe,zoomLevel:K,panOffset:de,focusedSlot:ie}=B,ue=a.useCallback(v=>{P.current=v,U(v)},[]);a.useEffect(()=>{t||(J.current.clear(),ue(null))},[t,ue]);const xe=a.useCallback(()=>{if(e.length<=I)return;const D=Math.max(...$)+1;if(D>=e.length){const W=[];for(let G=0;G<I&&G<e.length;G++)W.push(G);W.forEach((G,Y)=>_.addToCompare(G,Y))}else{const W=[];for(let G=0;G<I;G++){const Y=(D+G)%e.length;W.push(Y)}W.forEach((G,Y)=>_.addToCompare(G,Y))}},[e.length,I,$,_]),pe=a.useCallback(()=>{if(e.length<=I)return;const D=Math.min(...$)-I;if(D<0){const W=Math.max(0,e.length-I),G=[];for(let Y=0;Y<I&&W+Y<e.length;Y++)G.push(W+Y);G.forEach((Y,le)=>_.addToCompare(Y,le))}else{const W=[];for(let G=0;G<I;G++)W.push(D+G);W.forEach((G,Y)=>_.addToCompare(G,Y))}},[e.length,I,$,_]),ae=a.useCallback(v=>{const D=e[v];if(!D||D.type!=="image")return!1;const W=P.current;if(W&&T.current){const G=T.current.getState();J.current.set(W.url,G)}return _.goTo(v),ue(D),setTimeout(()=>{const G=J.current.get(D.url);G&&T.current&&T.current.setState(G)},50),!0},[e,_,ue]),q=a.useCallback(()=>{_.resetView(),ee.current.forEach(v=>{v!=null&&v.isVideo()&&v.resetVideo()})},[_]);a.useEffect(()=>{if(!t)return;const v=D=>{const W=D.target instanceof HTMLElement?D.target:null;if(W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement||W instanceof HTMLSelectElement||W instanceof HTMLButtonElement||W!=null&&W.isContentEditable)return;const G=E==="single"?X.current:ee.current[ie]||null;switch(D.key){case"Escape":D.preventDefault(),i();break;case"ArrowLeft":case"ArrowUp":if(D.preventDefault(),E==="edit"){const Y=(M-1+e.length)%e.length;ae(Y)}else E==="single"?_.goToPrev():pe();break;case"ArrowRight":case"ArrowDown":if(D.preventDefault(),E==="edit"){const Y=(M+1)%e.length;ae(Y)}else E==="single"?_.goToNext():xe();break;case"c":case"C":e.length>1&&(D.preventDefault(),_.setMode(E==="single"?"compare":"single"));break;case"1":case"2":case"3":case"4":if(E==="compare"){const Y=parseInt(D.key,10)-1;Y<I&&(D.preventDefault(),_.setFocusedSlot(Y))}break;case"+":case"=":D.preventDefault(),_.zoom(.25);break;case"-":case"_":D.preventDefault(),_.zoom(-.25);break;case"0":D.preventDefault(),E==="compare"?q():_.resetView();break;case" ":case"Spacebar":G!=null&&G.isVideo()&&(D.preventDefault(),G.toggleVideoPlayback());break;case"s":case"S":E==="compare"&&(D.preventDefault(),_.toggleSyncMode());break}};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[t,E,e.length,e,M,ie,_,i,I,xe,pe,ae,q]);const ce=a.useCallback(()=>{if(O.current)if(S){const v=di();v==null||v.catch(()=>{})}else{const v=li(O.current);v==null||v.catch(()=>{})}},[S]);a.useEffect(()=>{const v=()=>{C(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",v),()=>document.removeEventListener("fullscreenchange",v)},[]);const ve=a.useCallback(v=>{v.target===v.currentTarget&&i()},[i]),me=a.useCallback(v=>{E==="edit"?ae(v):E==="single"?_.goTo(v):_.addToCompare(v,ie)},[E,_,ie,ae]),Re=a.useCallback(v=>{b(v),_.setSlotCount(v)},[_]),Me=a.useCallback((v,D)=>v==="grid"?D<=2?"layout-horizontal":"layout-grid":`layout-${v}`,[]),We=a.useCallback(()=>{const v=e[M];v&&g&&g(v)},[e,M,g]),Ee=a.useCallback(async()=>{const v=e[M];if(!v)return;const D=v.type==="image"?ut(v.url):v.url;if(D.startsWith("blob:")){const{unifiedCacheService:Y}=await dt(async()=>{const{unifiedCacheService:H}=await import("./startup-app-eD_rQhSh.js").then(F=>F.nQ);return{unifiedCacheService:H}},__vite__mapDeps([0]),import.meta.url),{downloadFromBlob:le}=await dt(async()=>{const{downloadFromBlob:H}=await import("./startup-app-eD_rQhSh.js").then(F=>F.nO);return{downloadFromBlob:H}},__vite__mapDeps([0]),import.meta.url),_e=D.indexOf("#"),k=_e>0?D.substring(_e+1):null;if(k&&k.startsWith("merged-video-")){const H=await Y.getCachedBlob(k);if(H){const F=H.type||"video/webm",Z=F.startsWith("video/mp4")?"mp4":F.startsWith("video/webm")?"webm":"bin";le(H,`merged-video-${Date.now()}.${Z}`);return}}try{const F=await(await fetch(D)).blob(),Z=F.type.startsWith("video/mp4")?"mp4":F.type.startsWith("video/webm")?"webm":F.type.startsWith("audio/mpeg")?"mp3":F.type.startsWith("audio/wav")?"wav":F.type.startsWith("audio/")?"m4a":F.type.startsWith("image/")?"png":"bin";le(F,`${v.type}_${Date.now()}.${Z}`)}catch(H){console.error("[UnifiedMediaViewer] Failed to fetch blob URL:",H)}return}const{smartDownload:W,buildDownloadFilename:G}=await dt(async()=>{const{smartDownload:Y,buildDownloadFilename:le}=await import("./startup-app-eD_rQhSh.js").then(_e=>_e.o0);return{smartDownload:Y,buildDownloadFilename:le}},__vite__mapDeps([0]),import.meta.url);await W([{url:D,type:v.type,filename:v.type==="audio"?G(v.title,"audio","mp3"):void 0,audioMetadata:v.type==="audio"?{title:v.title,prompt:v.prompt,tags:v.tags,coverUrl:v.posterUrl,artist:v.artist,album:v.album}:void 0}])},[e,M]),Te=a.useCallback(()=>{const v=e[M];v&&v.type==="image"&&(f?(ue(v),_.setMode("edit")):y&&y(v))},[e,M,y,f,_,ue]),Ye=a.useCallback(v=>{if(v==="edit"){const D=e[M];D&&D.type==="image"&&ue(D)}_.setMode(v)},[e,M,_,ue]),$e=a.useCallback(()=>{J.current.clear(),ue(null),_.setMode("single")},[_,ue]),be=a.useCallback(()=>{var v;(v=T.current)==null||v.reset()},[]),Ie=a.useCallback(()=>{var v;(v=T.current)==null||v.save()},[]),he=a.useCallback(v=>{const D=P.current;x&&D&&x(v,D),$e()},[x,$e]),ze=a.useCallback(v=>{z&&z(v),$e()},[z,$e]),De=a.useCallback((v,D)=>{ee.current[v]=D},[]),He=a.useCallback((v,D)=>{Q.current||(Q.current=!0,ee.current.forEach((W,G)=>{G!==v&&(W!=null&&W.isVideo())&&(D?W.playVideo():W.pauseVideo())}),setTimeout(()=>{Q.current=!1},50))},[]),Be=a.useCallback((v,D)=>{Q.current||(Q.current=!0,ee.current.forEach((W,G)=>{G!==v&&(W!=null&&W.isVideo())&&W.setVideoTime(D)}),setTimeout(()=>{Q.current=!1},50))},[]),Ge=()=>{const v=e[M]||null;return s.jsxs("div",{className:"unified-viewer__single",children:[e.length>1&&s.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--prev",onClick:_.goToPrev,"aria-label":"上一个",children:s.jsx(cn,{size:32})}),s.jsx(On,{ref:X,item:v,zoomLevel:K,panOffset:de,videoAutoPlay:p,videoLoop:h,onZoomChange:_.setZoomLevel,onPanChange:()=>{},onInsertToCanvas:g?We:void 0,onDownload:Ee,onEdit:y?Te:void 0}),e.length>1&&s.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--next",onClick:_.goToNext,"aria-label":"下一个",children:s.jsx(ui,{size:32})})]})},Qe=()=>{const v=Me(re,I);return s.jsx("div",{className:`unified-viewer__compare ${v}`,children:Array.from({length:I}).map((D,W)=>{const G=$[W],Y=typeof G=="number"?e[G]:null;return s.jsx(On,{ref:le=>De(W,le),item:Y,slotIndex:W,isFocused:ie===W,zoomLevel:fe?K:void 0,panOffset:fe?de:void 0,onClick:()=>_.setFocusedSlot(W),onClose:I>2?()=>_.removeFromCompare(W):void 0,videoAutoPlay:p,videoLoop:h,onZoomChange:fe?_.setZoomLevel:void 0,onPanChange:fe?_.setPan:void 0,isCompareMode:!0,isSyncMode:fe,onVideoPlayStateChange:fe?le=>He(W,le):void 0,onVideoTimeUpdate:fe?le=>Be(W,le):void 0},W)})})},Ne=()=>{const v=R||e[M];return!v||v.type!=="image"?null:s.jsx("div",{className:"unified-viewer__edit",children:s.jsx(no,{ref:T,imageUrl:v.url,showOverwrite:N,onOverwrite:x?he:void 0,onInsert:z?ze:void 0})})},L=e[M]||null;if(!t||e.length===0)return null;const w=()=>{switch(E){case"edit":return Ne();case"compare":return Qe();default:return Ge()}},V=s.jsx("div",{ref:O,className:`unified-viewer ${u} ${S?"unified-viewer--fullscreen":""} ${E==="edit"?"unified-viewer--edit-mode":""}`,onClick:ve,children:s.jsxs("div",{className:"unified-viewer__container",children:[s.jsx(Nc,{mode:E,currentIndex:M,totalCount:e.length,slotCount:I,compareLayout:re,syncMode:fe,onModeChange:Ye,onSlotCountChange:Re,onLayoutChange:_.setCompareLayout,onSyncToggle:_.toggleSyncMode,onResetView:E==="compare"?q:_.resetView,onClose:i,onFullscreen:ce,isImage:(L==null?void 0:L.type)==="image",showEditButton:f||!!y,onBackToPreview:$e,onResetEdit:be,onSaveEdit:Ie}),s.jsx("div",{className:"unified-viewer__content",children:w()}),c&&e.length>1&&s.jsx(Tc,{items:e,mode:E==="edit"?"single":E,currentIndex:M,compareIndices:$,onThumbnailClick:me})]})});return Rt.createPortal(V,document.body)},im=Object.freeze(Object.defineProperty({__proto__:null,UnifiedMediaViewer:mn,default:mn},Symbol.toStringTag,{value:"Module"})),Dc=qn.DIALOG_AI_IMAGE;class Et{constructor(){this.windows=new Map,this.counter=0}static getInstance(){return Et.instance||(Et.instance=new Et),Et.instance}register(e,n){const r=this.windows.get(e);r?(r.element=n,r.activationOrder=++this.counter):this.windows.set(e,{windowId:e,activationOrder:++this.counter,element:n}),this.applyAllZIndexes()}unregister(e){this.windows.delete(e)&&this.applyAllZIndexes()}bringToFront(e){const n=this.windows.get(e);n&&(this.isTopWindow(e)||(n.activationOrder=++this.counter,this.applyAllZIndexes()))}updateElement(e,n){const r=this.windows.get(e);r&&(r.element=n,this.applyZIndex(r,this.getPositionIndex(e)))}getTopWindowId(){let e=null,n=-1;return this.windows.forEach(r=>{r.activationOrder>n&&(n=r.activationOrder,e=r.windowId)}),e}isTopWindow(e){return this.getTopWindowId()===e}getPositionIndex(e){return this.getSortedEntries().findIndex(r=>r.windowId===e)}getSortedEntries(){return Array.from(this.windows.values()).sort((e,n)=>e.activationOrder-n.activationOrder)}applyAllZIndexes(){this.getSortedEntries().forEach((n,r)=>{this.applyZIndex(n,r)})}applyZIndex(e,n){!e.element||n<0||e.element.style.setProperty("--aitu-winbox-z-index",String(Dc+n))}}const vt=Et.getInstance();let nt=null,nn=null;const Lc=async()=>nt||(typeof window<"u"&&window.WinBox?(nt=window.WinBox,nt):nn||(nn=(async()=>{try{if(await dt(()=>import("./winbox.bundle.min-CoRPjCs5.js"),[],import.meta.url),nt=window.WinBox,nt)return nt;throw new Error("WinBox not found after import")}catch(t){return console.warn("Dynamic import failed, falling back to CDN:",t),new Promise((e,n)=>{const r=document.createElement("script");r.src="https://cdn.jsdelivr.net/npm/winbox@0.2.82/dist/winbox.bundle.min.js",r.async=!0,r.onload=()=>{nt=window.WinBox,nt?e(nt):n(new Error("WinBox not found after CDN loading"))},r.onerror=n,document.head.appendChild(r)})}})(),nn)),$c=({visible:t,title:e,icon:n,onClose:r,children:i,width:o="80%",height:c="80%",minWidth:l=400,minHeight:m=300,x:u="center",y:d="center",maximizable:p=!0,minimizable:h=!0,resizable:g=!0,movable:y=!0,modal:f=!1,background:x="linear-gradient(135deg, #5A4FCF 0%, #7B68EE 50%, #E91E63 100%)",border:z=0,className:N,id:O,headerContent:T,container:I,onMaximize:b,onMinimize:S,onRestore:C,onFocus:R,onBlur:U,onMove:P,onResize:J,autoMaximize:ee=!1,minVisiblePixels:X=50,onInsertToCanvas:Q,keepAlive:B=!1,minimizeTargetSelector:_,onActivate:E})=>{var _e;const M=a.useRef(O||`winbox-${_r()}`),$=a.useRef(null),re=a.useRef(null),fe=a.useRef(r),K=a.useRef(E),de=a.useRef(!0),ie=a.useRef(!1),ue=a.useRef(null),xe=a.useRef([]);fe.current=r,K.current=E;const pe=a.useRef(null),ae=a.useRef(!1),[q,ce]=a.useState(null),[ve,me]=a.useState(null),[Re,Me]=a.useState(null),[We,Ee]=a.useState(!1),[Te,Ye]=a.useState(!!nt),[$e,be]=a.useState(null),Ie=a.useRef(null),he=a.useRef(null),ze=a.useCallback(()=>{xe.current.forEach(k=>{window.clearTimeout(k)}),xe.current=[]},[]),De=a.useCallback((k,H)=>{const F=window.setTimeout(()=>{xe.current=xe.current.filter(Z=>Z!==F),k()},H);return xe.current.push(F),F},[]),He=a.useCallback(()=>{de.current&&(ce(null),me(null),Me(null),Ee(!1))},[]),Be=a.useCallback((k,H=!0)=>{if(k){ze(),H&&(k.onclose=null);try{k.close(!0)}catch{}}},[ze]),Ge=a.useCallback(()=>{const k=ue.current;k&&(ue.current=null,Be(k))},[Be]),Qe=a.useCallback(k=>{if(k){ze(),ue.current=k;try{k.hide()}catch{}De(()=>{ie.current=!1,Ge()},800)}},[ze,Ge,De]),Ne=a.useCallback(k=>{be(k),Ie.current=k,k===null&&he.current!==null&&$.current&&($.current.minwidth=he.current,he.current=null)},[]),L=a.useCallback(()=>{const k={left:!1,right:!1};if(typeof window>"u"||!window.WinBox)return k;const F=window.WinBox.stack(),Z=window.innerWidth;return F.forEach(oe=>{if(oe===$.current)return;Math.abs(oe.width-Z/2)<20&&(oe.x<20&&(k.left=!0),Math.abs(oe.x+oe.width-Z)<20&&(k.right=!0))}),k},[]),w=a.useCallback(k=>{if(!k||!k.window)return;const H=window.innerWidth,F=window.innerHeight;he.current!==null&&(k.minwidth=he.current,he.current=null),k.left=0,k.right=0,k.top=0,k.bottom=0;let Z,oe;typeof o=="string"&&o.endsWith("%")?Z=Math.floor(H*parseInt(o)/100):Z=typeof o=="number"?o:Math.floor(H*.8),typeof c=="string"&&c.endsWith("%")?oe=Math.floor(F*parseInt(c)/100):oe=typeof c=="number"?c:Math.floor(F*.8),Z=Math.max(Z,l),oe=Math.max(oe,m);const te=Math.floor((H-Z)/2),Pe=Math.floor((F-oe)/2);k.resize(Z,oe).move(te,Pe),Ne(null)},[o,c,l,m,Ne]),V=a.useCallback((k,H,F,Z,oe)=>{!k||!k.window||(k.left=0,k.right=0,k.top=0,k.bottom=0,H==="left"?(k.resize(F,oe).move(0,0),Ne("left")):(k.resize(F,oe).move(Z-F,0),Ne("right")))},[Ne]),v=a.useCallback(()=>{const k=$.current,H=Ie.current;if(!k||!k.window)return;const F=window.innerWidth,Z=window.innerHeight,oe=L(),te=Math.floor(F/2),Pe=Ae=>{he.current===null&&(he.current=k.minwidth),k.minwidth=Math.min(200,te),k.max?(k.restore(),requestAnimationFrame(()=>{!k||!k.window||V(k,Ae,te,F,Z)})):V(k,Ae,te,F,Z)},Ce=()=>{k.max?(k.restore(),requestAnimationFrame(()=>{!k||!k.window||w(k)})):w(k)};if(H==="left"){Ce();return}if(H==="right"){oe.left?Ce():Pe("left");return}oe.right&&!oe.left?Pe("left"):Pe("right")},[L,w,V]),D=mi(re,{enablePositionTracking:!1,enableScaleCompensation:!$e&&!((_e=$.current)!=null&&_e.max)});a.useEffect(()=>{Te||Lc().then(()=>Ye(!0))},[Te]),a.useEffect(()=>(de.current=!0,()=>{de.current=!1}),[]);const W=a.useRef(!1),G=a.useCallback(()=>{var k;return vt.unregister(M.current),(k=fe.current)==null||k.call(fe),!1},[]),Y=a.useCallback(()=>{var k;vt.bringToFront(M.current),(k=K.current)==null||k.call(K)},[]);a.useEffect(()=>{if(!(!Te||!nt)){if(!t){if($.current)if(vt.unregister(M.current),ze(),B)try{$.current.hide()}catch{}else{const k=$.current;ie.current?Qe(k):Be(k),$.current=null,re.current=null,He()}return}if(t&&$.current){$.current.show(),$.current.focus(),vt.register(M.current,$.current.window);return}if(t&&!$.current){Ge();const k=["winbox-react"];p||k.push("no-max"),h||k.push("no-min"),g||k.push("no-resize"),y||k.push("no-move"),k.push("no-full"),N&&k.push(N);const H=new nt({id:O,title:e,width:o,height:c,minwidth:l,minheight:m,x:u,y:d,modal:f,background:x,border:z,overflow:!0,class:k,root:I||document.body,onclose:G,onmaximize:b,onminimize:function(){ae.current=!0;const F=pe.current,Z=F?{x:F.x,y:F.y}:{x:this.x||0,y:this.y||0},oe=F?{width:F.width,height:F.height}:{width:this.width||800,height:this.height||600},te=this.window;if(_&&te){const Pe=document.querySelector(_);if(Pe){te.style.transition="none",te.style.transform="",te.style.opacity="1",F&&(te.style.left=`${F.x}px`,te.style.top=`${F.y}px`,te.style.width=`${F.width}px`,te.style.height=`${F.height}px`),te.offsetHeight;const Ce=te.getBoundingClientRect(),Ae=Pe.getBoundingClientRect(),qe=Ae.left+Ae.width/2,et=Ae.top+Ae.height/2,Ve=Ce.left,j=Ce.top+Ce.height/2,ne=qe-Ve,we=et-j,Oe=Math.min(Ae.width/Ce.width,Ae.height/Ce.height,.06);te.style.transformOrigin="left center";const Ze=te.parentElement;Ze&&(Ze.style.perspective="1000px",Ze.style.perspectiveOrigin="left center"),te.offsetHeight;const A=400;return te.style.transition=`transform ${A}ms cubic-bezier(0.4, 0, 0.2, 1), opacity ${A}ms ease-out`,te.style.transform=`translate(${ne}px, ${we}px) scale(${Oe}) rotateY(-30deg)`,te.style.opacity="0",De(()=>{te.isConnected&&(te.style.transition="none",te.style.transform="",te.style.opacity="",Ze&&(Ze.style.perspective="",Ze.style.perspectiveOrigin=""),this.hide(),S==null||S(Z,oe))},A),!0}}return this.hide(),S==null||S(Z,oe),!0},onrestore:C,onfocus:function(){R==null||R(),Y()},onblur:U,onmove:function(F,Z){if(this.max||this.min||W.current)return;const oe=window.innerWidth,te=window.innerHeight,Pe=this.width;this.height;const Ce=X;if(Ie.current){const j=Ie.current==="left"?0:oe-Pe;Math.abs(F-j)>50&&Ne(null)}let Ae=F,qe=Z;F<Ce-Pe&&(Ae=Ce-Pe),F>oe-Ce&&(Ae=oe-Ce),Z<0&&(qe=0),Z>te-Ce&&(qe=te-Ce),(Ae!==F||qe!==Z)&&(W.current=!0,this.move(Ae,qe),W.current=!1);const et=pe.current,Ve=et&&qe-et.y>200;!this.min&&!this.max&&!ae.current&&!Ve&&(pe.current={x:Ae,y:qe,width:this.width,height:this.height}),P==null||P(Ae,qe)},onresize:function(F,Z){const oe=pe.current,te=oe&&(Z<100||oe.height-Z>200);!this.min&&!this.max&&!ae.current&&!te&&(pe.current={x:this.x,y:this.y,width:F,height:Z}),J==null||J(F,Z)}});if($.current=H,H.addControl({index:0,class:"wb-split",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PGxpbmUgeDE9IjEyIiB5MT0iMyIgeDI9IjEyIiB5Mj0iMjEiPjwvbGluZT48L3N2Zz4=",click:F=>{F.preventDefault(),F.stopPropagation(),v()}}),Q&&H.addControl({index:0,class:"wb-insert-canvas",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiLz48cGF0aCBkPSJNMTIgOHY4Ii8+PHBhdGggZD0iTTggMTJoOCIvPjwvc3ZnPg==",click:F=>{F.preventDefault(),F.stopPropagation();const Z=H.window;if(Z){const oe=Z.getBoundingClientRect(),te={x:oe.left,y:oe.top,width:oe.width,height:oe.height};Q(te)}else{const oe={x:H.x||0,y:H.y||0,width:H.width||800,height:H.height||600};Q(oe)}}}),H.window){re.current=H.window,vt.register(M.current,re.current),requestAnimationFrame(()=>{D()});const F=H.window.querySelector(".wb-body");if(F&&me(F),n){const Z=H.window.querySelector(".wb-drag"),oe=H.window.querySelector(".wb-title");if(Z&&oe){const te=document.createElement("div");te.className="wb-icon-container",Z.insertBefore(te,oe),Me(te)}}}if(T&&H.window){const F=H.window.querySelector(".wb-drag");if(F){const Z=document.createElement("div");Z.className="wb-header-custom";const oe=te=>{te.stopPropagation()};Z.addEventListener("mousedown",oe,!0),Z.addEventListener("touchstart",oe,!0),Z.addEventListener("pointerdown",oe,!0),F.appendChild(Z),ce(Z)}}H&&!H.min&&!H.max&&(pe.current={x:H.x,y:H.y,width:H.width,height:H.height}),Ee(!0),ee&&De(()=>{$.current&&$.current.maximize()},100)}}},[t,Te,ee,B,ze,Be,Qe,Ge,He,De]),a.useEffect(()=>{const k=M.current;return()=>{if(vt.unregister(k),$.current){const H=$.current;ie.current?Qe(H):Be(H),$.current=null,re.current=null}ue.current||ze()}},[ze,Be,Qe]),a.useEffect(()=>{$.current&&e&&$.current.setTitle(e)},[e]),a.useEffect(()=>{var k,H;if($.current&&n&&!Re){const F=$.current,Z=(k=F.window)==null?void 0:k.querySelector(".wb-drag"),oe=(H=F.window)==null?void 0:H.querySelector(".wb-title");if(Z&&oe&&!Z.querySelector(".wb-icon-container")){const Pe=document.createElement("div");Pe.className="wb-icon-container",Z.insertBefore(Pe,oe),Me(Pe)}}},[n,Re]),a.useEffect(()=>{if($.current){const k=pe.current;if(t){const H=$.current.min||$.current.hidden;$.current.min&&($.current.restore(),k&&($.current.move(k.x,k.y),$.current.resize(k.width,k.height)),ae.current=!1),$.current.show(),$.current.focus(),vt.bringToFront(M.current),H&&_&&requestAnimationFrame(()=>{le()})}else $.current.hide()}},[t]);const le=a.useCallback(()=>{if(!_||!$.current)return;const k=$.current.window,H=document.querySelector(_);if(!k||!H)return;const F=pe.current;if(!F)return;const Z=H.getBoundingClientRect(),oe=Z.left+Z.width/2,te=Z.top+Z.height/2,Pe=F.x,Ce=F.y+F.height/2,Ae=oe-Pe,qe=te-Ce,et=Math.min(Z.width/F.width,Z.height/F.height,.06),Ve=k.parentElement;Ve&&(Ve.style.perspective="1000px",Ve.style.perspectiveOrigin="left center"),k.style.transition="none",k.style.transformOrigin="left center",k.style.transform=`translate(${Ae}px, ${qe}px) scale(${et}) rotateY(-30deg)`,k.style.opacity="0",k.offsetHeight;const j=350;k.style.transition=`transform ${j}ms cubic-bezier(0.2, 0, 0.4, 1), opacity ${j*.6}ms ease-out`,k.style.transform="",k.style.opacity="1",De(()=>{k.isConnected&&(k.style.transition="none",k.style.transform="",k.style.transformOrigin="",Ve&&(Ve.style.perspective="",Ve.style.perspectiveOrigin=""))},j)},[_,De]);return a.useEffect(()=>{const k=re.current;if(!k)return;const H=[".wb-drag",".wb-n",".wb-s",".wb-e",".wb-w",".wb-ne",".wb-nw",".wb-se",".wb-sw"].join(", "),F=oe=>{const te=oe.target;te instanceof Element&&te.closest(H)&&(ie.current=!0)},Z=()=>{!ie.current&&!ue.current||(ie.current=!1,Ge())};return k.addEventListener("mousedown",F,!0),k.addEventListener("touchstart",F,!0),window.addEventListener("mouseup",Z,!0),window.addEventListener("touchend",Z,!0),window.addEventListener("touchcancel",Z,!0),window.addEventListener("blur",Z),()=>{k.removeEventListener("mousedown",F,!0),k.removeEventListener("touchstart",F,!0),window.removeEventListener("mouseup",Z,!0),window.removeEventListener("touchend",Z,!0),window.removeEventListener("touchcancel",Z,!0),window.removeEventListener("blur",Z)}},[We,Ge]),a.useEffect(()=>{$.current&&ee&&$.current.maximize()},[ee]),a.useEffect(()=>{const k=re.current;if(!k)return;const H=()=>{Y()},F=()=>{Y()};return k.addEventListener("pointerdown",H,!0),k.addEventListener("focusin",F,!0),()=>{k.removeEventListener("pointerdown",H,!0),k.removeEventListener("focusin",F,!0)}},[We,Y]),a.useEffect(()=>{if(!$.current||!t||Ie.current)return;const k=typeof o=="number"?o:$.current.width,H=typeof c=="number"?c:$.current.height;typeof k!="number"||typeof H!="number"||$.current.width===k&&$.current.height===H&&$.current.minwidth===l&&$.current.minheight===m||($.current.minwidth=l,$.current.minheight=m,$.current.resize(k,H))},[c,m,l,t,o]),s.jsxs(s.Fragment,{children:[We&&n&&Re&&Rt.createPortal(s.jsx("span",{className:"wb-icon-content",children:n}),Re),We&&ve&&Rt.createPortal(s.jsx("div",{className:"winbox-content-wrapper",children:i}),ve),We&&T&&q&&Rt.createPortal(T,q)]})},Oc={image:"prompt-list-item__tag--image",video:"prompt-list-item__tag--video",audio:"prompt-list-item__tag--audio",text:"prompt-list-item__tag--text",agent:"prompt-list-item__tag--agent","ppt-common":"prompt-list-item__tag--ppt-common","ppt-slide":"prompt-list-item__tag--ppt-slide"},Fc=({content:t,title:e,sentPrompt:n,tags:r,resultPreview:i,pinned:o=!1,isPreset:c=!1,modelType:l,scene:m,previewExamples:u,onClick:d,onTogglePin:p,onDelete:h,onPreviewExample:g,language:y="zh",disabled:f=!1})=>{const x=B=>{B.stopPropagation(),p==null||p()},z=B=>{B.stopPropagation(),h==null||h()},N=(u==null?void 0:u.slice(0,3))??[],O=N.length>0,T=(e==null?void 0:e.trim())||t,I=(r||[]).filter(Boolean).slice(0,4),b=!!(n||i||I.length>0)&&!O,S=N.length===1,C=!!(g&&!f),R=B=>_=>{_.preventDefault(),_.stopPropagation(),C&&(g==null||g({content:t,previewExamples:N,initialIndex:B}))},U=B=>{B.preventDefault(),B.stopPropagation()},P=B=>_=>{_.key!=="Enter"&&_.key!==" "||(_.preventDefault(),_.stopPropagation(),C&&(g==null||g({content:t,previewExamples:N,initialIndex:B})))},J=s.jsxs("div",{className:`prompt-list-item ${o?"prompt-list-item--pinned":""} ${c?"prompt-list-item--preset":""} ${f?"prompt-list-item--disabled":""}`,onClick:f?void 0:d,children:[o&&s.jsx("div",{className:"prompt-list-item__pin-badge",children:s.jsx(vs,{size:10})}),c&&s.jsx("div",{className:"prompt-list-item__preset-badge",children:s.jsx(pi,{size:10})}),m&&s.jsx("span",{className:`prompt-list-item__tag ${l&&Oc[l]||""}`,children:m}),s.jsx("span",{className:"prompt-list-item__text",children:T}),s.jsxs("div",{className:"prompt-list-item__actions",children:[p&&s.jsx(je,{content:o?y==="zh"?"取消置顶":"Unpin":y==="zh"?"置顶":"Pin",children:s.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:x,children:o?s.jsx(hi,{size:14}):s.jsx(vs,{size:14})})}),h&&s.jsx(je,{content:y==="zh"?"删除":"Delete",children:s.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:z,children:s.jsx(Mt,{size:14})})})]})]}),ee=O?s.jsxs("div",{className:"prompt-list-item__hover-card",children:[s.jsx("div",{className:"prompt-list-item__hover-text",children:t}),s.jsx("div",{className:`prompt-list-item__hover-gallery ${S?"prompt-list-item__hover-gallery--single":""}`,children:N.map((B,_)=>s.jsx("div",{className:`prompt-list-item__hover-thumb ${S?"prompt-list-item__hover-thumb--single":""}`,children:C?s.jsx("button",{type:"button",className:"prompt-list-item__hover-thumb-button","aria-label":`${y==="zh"?"预览示例图":"Preview example"} ${_+1}`,onMouseDown:R(_),onClick:U,onKeyDown:P(_),children:s.jsx(Tt,{src:B.kind==="video"&&B.posterSrc||B.src,alt:B.alt,showSkeleton:!1})}):s.jsx(Tt,{src:B.kind==="video"&&B.posterSrc||B.src,alt:B.alt,showSkeleton:!1})},`${B.src}-${B.alt}`))}),C&&s.jsx("div",{className:"prompt-list-item__hover-hint",children:y==="zh"?"点击预览":"Click to preview"})]}):null,X=i?s.jsxs("div",{className:"prompt-list-item__result-preview",children:[(i.kind==="image"||i.kind==="video")&&s.jsx("div",{className:"prompt-list-item__result-media",children:s.jsx(Tt,{src:i.kind==="video"&&i.posterUrl||i.url,alt:i.title||T,showSkeleton:!1})}),i.kind==="audio"&&s.jsxs("div",{className:"prompt-list-item__result-audio",children:[i.coverUrl&&s.jsx(Tt,{src:i.coverUrl,alt:i.title||T,showSkeleton:!1}),s.jsxs("div",{children:[s.jsx("div",{className:"prompt-list-item__result-title",children:i.title||"音频结果"}),i.text&&s.jsx("div",{className:"prompt-list-item__result-text",children:i.text})]})]}),(i.kind==="text"||i.kind==="error"||i.kind==="none")&&s.jsxs("div",{className:`prompt-list-item__result-text ${i.kind==="error"?"prompt-list-item__result-text--error":""}`,children:[i.kind==="text"&&i.title&&s.jsx("strong",{children:i.title}),i.text]})]}):null,Q=b?s.jsxs("div",{className:"prompt-list-item__history-card",children:[s.jsx("div",{className:"prompt-list-item__history-title",children:T}),n&&s.jsxs("div",{className:"prompt-list-item__history-section",children:[s.jsx("div",{className:"prompt-list-item__history-label",children:"发送提示词"}),s.jsx("div",{className:"prompt-list-item__history-text",children:n})]}),I.length>0&&s.jsx("div",{className:"prompt-list-item__history-tags",children:I.map(B=>s.jsx("span",{children:B},B))}),X&&s.jsxs("div",{className:"prompt-list-item__history-section",children:[s.jsx("div",{className:"prompt-list-item__history-label",children:"结果预览"}),X]})]}):null;return ee?s.jsx(je,{content:ee,placement:"right",delay:40,overlayClassName:"prompt-list-item__hover-card-popover",children:J}):Q?s.jsx(je,{content:Q,placement:"right",delay:60,overlayClassName:"prompt-list-item__history-card-popover",children:J}):s.jsx(je,{content:T===t?t:`${T}
3
-
4
- ${t}`,placement:"right-top",delay:80,overlayClassName:"prompt-list-item__text-tip-popover",overlayInnerClassName:"prompt-list-item__text-tip",children:J})},so="drawnix-runtime-model-discovery";function sn(t){return{profileId:t,status:"idle",sourceBaseUrl:"",signature:"",discoveredAt:null,discoveredModels:[],selectedModelIds:[],models:[],error:null}}function Uc(t){let e=5381;for(let n=0;n<t.length;n+=1)e=(e<<5)+e^t.charCodeAt(n);return Math.abs(e>>>0).toString(16)}function ro(t){const e=(t||"").trim(),n="https://api.tu-zi.com/v1";if(!e)return n;let r=e.replace(/\/+$/,"");return r=r.replace(/\/models$/i,""),/\/v1$/i.test(r)||(r=`${_i(r)}/v1`),r}function Fs(t,e){return`${ro(t)}::${Uc(e.trim())}`}function Wc(t,e){var r,i;const n=t.trim();if(!n)return e;try{const o=JSON.parse(n),c=typeof o.error=="string"?o.error:((r=o.error)==null?void 0:r.message)||((i=o.error)==null?void 0:i.details);return o.message||c||o.detail||e}catch{return n.replace(/\s+/g," ").slice(0,120)||e}}function Hc(t,e){return typeof e=="string"?t.includes(e):e.test(t)}function Ut(t,e){return e.some(n=>Hc(t,n))}function Vc(t,e){return t.some(n=>Ut(n,e))}function oo(t){const e=t.toLowerCase(),n=/(^|[^a-z0-9])(o1|o3|o4|o4-mini|gpt-4o|gpt-4\.1|chatgpt)([^a-z0-9]|$)/;return e.includes("flux")?se.FLUX:e.startsWith("mj")||e.includes("midjourney")?se.MIDJOURNEY:e.includes("grok")||e.includes("xai")||e.includes("supergrok")?se.GROK:e.includes("qwen")||e.includes("qwq")||e.includes("qvq")||e.includes("wanx")?se.QWEN:e.includes("glm")||e.includes("zhipu")||e.includes("bigmodel")||e.includes("cogview")||e.includes("cogvideo")?se.GLM:e.includes("minimax")||e.includes("abab")||e.includes("hailuo")||e.includes("speech-02")||e.includes("music-01")?se.MINIMAX:e.includes("mistral")||e.includes("mixtral")||e.includes("pixtral")||e.includes("ministral")||e.includes("codestral")?se.MISTRAL:e.includes("runway")||e.includes("runwayml")||/^gen[-_]?3/.test(e)||/^gen[-_]?4/.test(e)?se.RUNWAY:e.includes("pika")?se.PIKA:e.includes("llama")||e.includes("meta-llama")||e.includes("llama3")||e.includes("llama-3")||e.includes("llama-4")?se.LLAMA:e.includes("hunyuan")||e.includes("hunyuan-video")||e.includes("hunyuanimage")||e.includes("hunyuan-image")?se.HUNYUAN:e.includes("stepfun")||e.includes("jieyue")||/^step[-_]?1/.test(e)||e.startsWith("step-")?se.STEPFUN:e.includes("claude")||e.includes("sonnet")||e.includes("haiku")||e.includes("opus")?se.ANTHROPIC:e.includes("deepseek")?se.DEEPSEEK:e.includes("kling")?se.KLING:e.includes("happyhorse")?se.HAPPYHORSE:e.includes("veo")?se.VEO:e.includes("sora")?se.SORA:e.includes("suno")||e.includes("chirp")?se.SUNO:e.includes("seedream")||e.includes("seedance")||e.includes("doubao")||e.includes("jimeng")?se.DOUBAO:e.includes("gpt")||e.includes("openai")||e.includes("dall-e")||e.includes("whisper")||e.includes("codex")||e.includes("text-embedding")||e.includes("omni")||e.includes("tts-")||e.includes("babbage")||e.includes("davinci")||e.includes("computer-use")||n.test(e)?se.GPT:e.includes("gemini")||e.includes("banana")||e.includes("gemma")||e.includes("imagen")||e.includes("learnlm")?se.GEMINI:e.includes("google")?se.GOOGLE:se.OTHER}function io(t){const e=(t.owned_by||"").trim().toLowerCase(),n=oo(t.id);return e==="openai"||e.includes("openai")?se.GPT:e==="xai"||e.includes("x.ai")||e.includes("grok")?se.GROK:e==="qwen"||e.includes("alibaba")||e.includes("dashscope")||e.includes("tongyi")?se.QWEN:e==="zhipu"||e.includes("zhipu")||e.includes("bigmodel")||e.includes("glm")?se.GLM:e==="minimax"||e.includes("minimax")||e.includes("abab")||e.includes("hailuo")?se.MINIMAX:e==="mistral"||e.includes("mistral")?se.MISTRAL:e==="runway"||e.includes("runway")||e.includes("runwayml")?se.RUNWAY:e==="pika"||e.includes("pika")?se.PIKA:e==="meta"||e.includes("meta")||e.includes("llama")?se.LLAMA:e==="hunyuan"||e.includes("hunyuan")||e.includes("tencent")?se.HUNYUAN:e==="stepfun"||e.includes("stepfun")||e.includes("jieyue")?se.STEPFUN:e==="deepseek"||e.includes("deepseek")?se.DEEPSEEK:e==="anthropic"||e==="claude"||e.includes("anthropic")||e.includes("claude")?se.ANTHROPIC:e==="volcengine"||e==="doubao-video"||e==="doubao"||e.includes("volc")||e.includes("doubao")?se.DOUBAO:e==="suno"||e.includes("suno")||e.includes("chirp")?se.SUNO:e==="happyhorse"||e.includes("happyhorse")?se.HAPPYHORSE:e==="google"||e.includes("google")?n!==se.OTHER?n:se.GOOGLE:e==="vertex-ai"||e.includes("vertex")||e.includes("gemini")?n!==se.OTHER?n:se.GOOGLE:n}function Bc(t){const e=(t.supported_endpoint_types||[]).map(h=>h.toLowerCase()).filter(Boolean),n=t.id.toLowerCase(),r=io(t),i=(...h)=>Ut(n,[/(^|[^a-z0-9])t2v([^a-z0-9]|$)/,/(^|[^a-z0-9])i2v([^a-z0-9]|$)/,"video",...h]),o=(...h)=>Ut(n,[/(^|[^a-z0-9])t2i([^a-z0-9]|$)/,/(^|[^a-z0-9])i2i([^a-z0-9]|$)/,"image",...h]),c=(...h)=>Ut(n,["audio","music","suno","chirp","lyrics","midi","stems",...h]),l=(...h)=>Ut(n,h),m=(...h)=>Vc(e,h);if(m("audio","music","audio_generation","music-generation","lyrics","stems","midi"))return"audio";if(m("video","videos","video_generation","video-generation","videos.generate","video/generations","text-to-video","image-to-video","t2v","i2v","video-edit","video_edit"))return"video";if(m("image","images","image_generation","image-generation","images.generate","image/generations","image-edit","image_edit","images.edit","text-to-image","image-to-image","t2i","i2i"))return"image";switch(r){case se.FLUX:case se.MIDJOURNEY:return"image";case se.SORA:case se.VEO:case se.HAPPYHORSE:return"video";case se.RUNWAY:return o("frame","keyframe","reference-image","image-to-video")?"image":"video";case se.PIKA:return o("pikadditions","pikaswaps","pikascenes","reference-image")?"image":"video";case se.KLING:return o("kling_image","kling-image","img","picture","photo","poster","design")?"image":(i("kling_video","kling-video","motion","animate"),"video");case se.GLM:if(l("cogvideo"))return"video";if(l("cogview"))return"image";break;case se.MINIMAX:if(l("hailuo",/(^|[^a-z0-9])video[-_]?0\d/,"video-01","video-02","minimax-video","abab-video"))return"video";if(l("image-01","image-02","minimax-image","abab-image","visual-generation"))return"image";break;case se.DOUBAO:if(l("seedance"))return"video";if(l("seedream","jimeng"))return"image";break;case se.HUNYUAN:if(i("hunyuan-video","tencent-video","video-generation"))return"video";if(o("hunyuan-image","hunyuanimage","vision"))return"image";break;case se.QWEN:if(l("wanx",/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/)&&i("wan-video","wanx-video","animate","motion"))return"video";if(l("wanx",/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/)&&o("wanx-image","wan-image","poster","illustration")||l("wanx"))return"image";if(l(/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/))return"video";break;case se.GEMINI:case se.GOOGLE:if(l("veo"))return"video";if(l("imagen","gpt-image"))return"image";break;case se.SUNO:return"audio";case se.OTHER:if(c())return"audio";break}return l("sora-2")||n.includes("veo")||n.includes("sora")||n.includes("runway")||n.includes("gen-3")||n.includes("gen3")||n.includes("gen-4")||n.includes("gen4")||n.includes("pika")||n.includes("kling")||n.includes("hunyuan-video")||n.includes("cogvideo")||n.includes("seedance")||n.includes("t2v")||n.includes("i2v")||n.includes("video")?"video":m("banana")||n.includes("image")||n.includes("banana")||n.includes("flux")||n.startsWith("mj")||n.includes("midjourney")||n.includes("cogview")||n.includes("hunyuan-image")||n.includes("hunyuanimage")||n.includes("seedream")||n.includes("jimeng")||n.includes("imagen")||n.includes("gpt-image")?"image":n.includes("suno")||n.includes("chirp")||n.includes("music")||n.includes("lyrics")||n.includes("midi")||n.includes("stems")||n.includes("remix")||n.includes("infill")?"audio":"text"}function Fn(t,e){const n=t.split(/[^a-zA-Z0-9]+/).filter(Boolean).slice(0,4).map(r=>{var i;return((i=r[0])==null?void 0:i.toLowerCase())||""}).join("");return n?n.slice(0,6):e==="audio"?"aud":e==="video"?"vid":e==="text"?"txt":"img"}function Gc(t){const e=Bc(t),n=io(t),r=Zn[n],i=t.id.toLowerCase(),o=e==="text"&&(t.supported_endpoint_types||[]).some(l=>l.toLowerCase().includes("openai-chat"));if(t.id.toLowerCase()==="kling_video")return{id:t.id,label:"Kling",shortLabel:"Kling",shortCode:Fn(t.id,"video"),description:"Kling 标准视频能力,版本通过 model_name 选择",type:"video",vendor:se.KLING,supportsTools:!1,tags:["runtime","kling"],videoDefaults:{duration:"5",size:"1280x720",aspectRatio:"16:9"}};const c={id:t.id,label:t.id,shortLabel:t.id,shortCode:Fn(t.id,e),description:`${r} ${e==="image"?"图片模型":e==="video"?"视频模型":e==="audio"?"音频模型":"文本模型"}`,type:e,vendor:n,supportsTools:o,tags:e==="audio"&&vi(i)?["runtime","suno","audio","music"]:["runtime"],imageDefaults:e==="image"?{aspectRatio:"auto",width:1024,height:1024}:void 0,videoDefaults:e==="video"?{duration:"8",size:"1280x720",aspectRatio:"16:9"}:void 0};return e==="audio"?Si(c):c}function ao(t){return{...t,tags:t.tags?[...t.tags]:void 0,imageDefaults:t.imageDefaults?{...t.imageDefaults}:void 0,videoDefaults:t.videoDefaults?{...t.videoDefaults}:void 0}}function qc(t){if(!(t!=null&&t.id)||typeof t.id!="string")return null;const e=Kn(t.id);return e?ao(e):Gc(t)}function It(t,e){const n=new Set(t.map(r=>r.id));return Array.from(new Set(e.filter(r=>n.has(r))))}function Bt(t,e){return t.filter(n=>e.includes(n.id))}function Kc(t,e){const n=[...e],r=new Set(e.map(i=>i.id));for(const i of t)r.has(i.id)||n.push(i);return n}function Zc(t){const e=Array.isArray(t)?[...t]:[];return e.includes("runtime")||e.push("runtime"),e}function kt(t,e){return t?`${t}::${e}`:e}function rs(t){return bi.get().find(e=>e.id===t)||null}function Yc(t){var e;return t===Fe?!0:((e=rs(t))==null?void 0:e.enabled)!==!1}function os(t,e){var r;const n=((r=rs(t))==null?void 0:r.name)||null;return{...e,tags:Zc(e.tags),sourceProfileId:t,sourceProfileName:n,selectionKey:kt(t,e.id)}}function Xc(t){const e=Kn(t.id);if(e)return ao(e);const n=t.id.toLowerCase(),r=(t.tags||[]).map(i=>i.toLowerCase());return n.includes("happyhorse")||r.includes("happyhorse")?{...t,type:"video",vendor:se.HAPPYHORSE,tags:Array.from(new Set([...t.tags||[],"happyhorse"]))}:t}function co(t,e){return e.map(n=>os(t,Xc(n)))}function Us(t){return t.map(e=>({...e,selectionKey:e.selectionKey||kt(null,e.id)}))}function Jc(t,e,n){var o;const r=((o=rs(t))==null?void 0:o.name)||"供应商模型",i=oo(e);return os(t,{id:e,label:e,shortLabel:e,shortCode:Fn(e,n),description:`${r} · ${e}`,type:n,vendor:i})}function Ws(t){const e=co(t.profileId,Array.isArray(t.discoveredModels)?t.discoveredModels:[]),n=It(e,Array.isArray(t.selectedModelIds)?t.selectedModelIds:[]),r=Bt(e,n);return{profileId:t.profileId,status:t.error?"error":e.length>0?"ready":"idle",sourceBaseUrl:t.sourceBaseUrl||"",signature:t.signature||"",discoveredAt:Number.isFinite(t.discoveredAt)?t.discoveredAt:null,discoveredModels:e,selectedModelIds:n,models:r,error:t.error||null}}function Hs(t){return{profileId:t.profileId,discoveredAt:t.discoveredAt,discoveredModels:t.discoveredModels,selectedModelIds:t.selectedModelIds,sourceBaseUrl:t.sourceBaseUrl||void 0,signature:t.signature||void 0,error:t.error}}function Qc(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(so);if(!t)return null;const e=JSON.parse(t);if(!e||!Array.isArray(e.discoveredModels))return null;const n=co(Fe,e.discoveredModels),r=It(n,Array.isArray(e.selectedModelIds)?e.selectedModelIds:[]);return{profileId:Fe,status:"ready",sourceBaseUrl:e.sourceBaseUrl||"",signature:e.signature||"",discoveredAt:Number.isFinite(e.discoveredAt)?e.discoveredAt:Date.now(),discoveredModels:n,selectedModelIds:r,models:Bt(n,r),error:null}}catch{return null}}function Tn(){if(!(typeof window>"u"))try{window.localStorage.removeItem(so)}catch{}}class el{constructor(){this.catalogStates=new Map,this.listeners=new Set,this.handleCatalogSettingsChange=e=>{const n=new Map;for(const r of e)n.set(r.profileId,Ws(r));n.has(Fe)||n.set(Fe,sn(Fe)),this.catalogStates=n,this.syncRuntimeModelConfigs(),this.emit()},this.handlePresetSettingsChange=()=>{this.syncRuntimeModelConfigs(),this.emit()},this.handleActivePresetIdChange=()=>{this.syncRuntimeModelConfigs(),this.emit()},this.catalogStates=this.loadCatalogStatesFromSettings(),this.migrateLegacyCacheIfNeeded(),this.syncRuntimeModelConfigs(),vn.addListener(this.handleCatalogSettingsChange),fi.addListener(this.handlePresetSettingsChange),gi.addListener("activePresetId",this.handleActivePresetIdChange)}loadCatalogStatesFromSettings(){const e=new Map;for(const n of vn.get())e.set(n.profileId,Ws(n));return e.has(Fe)||e.set(Fe,sn(Fe)),e}migrateLegacyCacheIfNeeded(){const e=Qc();if(!e)return;const n=this.catalogStates.get(Fe);if(!!n&&(n.discoveredModels.length>0||n.selectedModelIds.length>0)){Tn();return}this.catalogStates.set(Fe,e),this.persistCatalogs(),Tn()}emit(){for(const e of this.listeners)e()}async persistCatalogs(){const e=Array.from(this.catalogStates.values()).map(Hs);await vn.update(e)}setCatalogState(e,n,r=!0){this.catalogStates.set(e,{...n,profileId:e,selectedModelIds:It(n.discoveredModels,n.selectedModelIds),models:Bt(n.discoveredModels,It(n.discoveredModels,n.selectedModelIds))}),this.syncRuntimeModelConfigs(),r&&this.persistCatalogs(),this.emit()}getCatalogState(e){return this.catalogStates.get(e)||sn(e)}resolveRuntimeModels(){const e=new Set,n=[];for(const r of this.catalogStates.values())for(const i of r.models)e.has(i.id)||(e.add(i.id),n.push(i));return n}syncRuntimeModelConfigs(){wi(this.resolveRuntimeModels())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getState(e=Fe){return this.getCatalogState(e)}getCatalogs(e){const n=e?new Set(e):null;return Array.from(this.catalogStates.values()).filter(r=>!n||n.has(r.profileId)).map(r=>Hs(r))}getDiscoveredModels(e=Fe,n){const r=this.getCatalogState(e);return n?r.discoveredModels.filter(i=>i.type===n):r.discoveredModels}getSelectedModelIds(e=Fe){return[...this.getCatalogState(e).selectedModelIds]}getPreferredModels(e){return yi(e)}getSelectableModels(e){const n=[];for(const r of this.catalogStates.values())Yc(r.profileId)&&n.push(...r.models.filter(i=>i.type===e));return xi([...n,...Us(Ss(e))])}getPinnedSelectableModel(e,n,r){if(!n)return null;const i=(r==null?void 0:r.profileId)||null,o=kt(i,n);if(i){const l=this.catalogStates.get(i),m=(l==null?void 0:l.models.find(d=>d.type===e&&(d.selectionKey||kt(i,d.id))===o))||(l==null?void 0:l.discoveredModels.find(d=>d.type===e&&(d.selectionKey||kt(i,d.id))===o));return m||((l==null?void 0:l.models.find(d=>(d.selectionKey||kt(i,d.id))===o))||(l==null?void 0:l.discoveredModels.find(d=>(d.selectionKey||kt(i,d.id))===o))?null:Jc(i,n,e))}const c=Kn(n);if(c&&c.type===e)return Us([c])[0];for(const l of this.catalogStates.values()){const m=l.models.find(u=>u.type===e&&u.id===n)||l.discoveredModels.find(u=>u.type===e&&u.id===n);if(m)return m}return null}getProfilePreferredModels(e=Fe,n){const i=this.getCatalogState(e).models.filter(o=>o.type===n);return Kc(Ss(n),i)}invalidateIfConfigChanged(e=Fe,n,r){const i=this.getCatalogState(e),o=Fs(n,r);!i.signature||i.signature===o||this.clear(e)}applySelection(e=Fe,n){const r=this.getCatalogState(e),i=It(r.discoveredModels,r.selectedModelIds),o=It(r.discoveredModels,n),c=new Set(i),l=new Set(o),m=Bt(r.discoveredModels,o),u=o.filter(p=>!c.has(p)),d=i.filter(p=>!l.has(p));return this.setCatalogState(e,{...r,status:r.discoveredModels.length>0?"ready":r.status,selectedModelIds:o,models:m,error:null}),{models:m,addedModelIds:u,removedModelIds:d}}clear(e=Fe){this.setCatalogState(e,sn(e)),e===Fe&&Tn()}async discover(e=Fe,n,r){const i=r.trim();if(!i)throw new Error("缺少 API Key");const o=this.getCatalogState(e),c=ro(n),l=Fs(c,i);this.setCatalogState(e,{...o,status:"loading",sourceBaseUrl:c,signature:l,error:null},!1);const m=await fetch(`${c}/models`,{headers:{Authorization:`Bearer ${i}`}}),u=await m.text();if(!m.ok)throw new Error(Wc(u,`获取模型列表失败: HTTP ${m.status}`));let d;try{d=JSON.parse(u)}catch{throw new Error("模型列表接口未返回有效 JSON")}const p=d.data;if(!Array.isArray(p))throw new Error("模型列表接口缺少 data 数组");const h=[],g=new Set;for(const x of p){const z=qc(x);!z||g.has(z.id)||(g.add(z.id),h.push(os(e,z)))}if(h.length===0)throw new Error("模型列表为空");const y=o.signature===l?It(h,o.selectedModelIds):[],f=Bt(h,y);return this.setCatalogState(e,{profileId:e,status:"ready",sourceBaseUrl:c,signature:l,discoveredAt:Date.now(),discoveredModels:h,selectedModelIds:y,models:f,error:null}),h}setError(e=Fe,n){const r=this.getCatalogState(e);this.setCatalogState(e,{...r,status:"error",error:n})}}const wt=new el;function am(t){return wt.getPreferredModels(t)}function tl(t){return wt.getSelectableModels(t)}function Un(t,e,n){return wt.getPinnedSelectableModel(t,e,n)}function nl(t,e){return wt.getProfilePreferredModels(t,e)}function lo(t=Fe){const[e,n]=a.useState(()=>wt.getState(t));return a.useEffect(()=>(n(wt.getState(t)),wt.subscribe(()=>{n(wt.getState(t))})),[t]),e}function uo(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n].id!==e[n].id||t[n].selectionKey!==e[n].selectionKey)return!1;return!0}function mo(t){const e=lo(),n=a.useRef([]);return a.useMemo(()=>{const r=tl(t);return uo(n.current,r)?n.current:(n.current=r,r)},[t,e])}function cm(t,e){const n=lo(t),r=a.useRef([]);return a.useMemo(()=>{const i=nl(t,e);return uo(r.current,i)?r.current:(r.current=i,i)},[t,e,n])}function is(t,e){return e!=null&&e.profileId?`${e.profileId}::${t}`:t}function po(t){return t.selectionKey||(t.sourceProfileId?`${t.sourceProfileId}::${t.id}`:t.id)}function Vs(t){return t?ht(t.sourceProfileId||null,t.id):null}function pn(t,e,n){if(!e)return;const r=is(e,n),i=(n==null?void 0:n.profileId)||null;return t.find(o=>po(o)===r)||t.find(o=>o.id===e&&(o.sourceProfileId||null)===i)||(i===null?t.find(o=>o.id===e&&!o.sourceProfileId):void 0)||t.find(o=>o.id===e)}const sl=({title:t,items:e,onSelect:n,onTogglePin:r,onDelete:i,language:o="zh",disabled:c=!1,showCount:l=!0,onTitleClick:m,className:u="",analyticsSurface:d="prompt_list",analyticsPromptType:p})=>{const[h,g]=a.useState(!1),[y,f]=a.useState([]),[x,z]=a.useState(0),N=a.useCallback((b,{content:S,previewExamples:C,initialIndex:R})=>{f(C.map((U,P)=>{const J=U.kind==="video"&&U.playable!==!1;return{id:`${b}-preview-${P}`,url:J?U.src:U.kind==="video"&&U.posterSrc||U.src,type:J?"video":"image",posterUrl:J?U.posterSrc:void 0,alt:U.alt,title:S}})),z(R),g(!0),ye.trackPromptAction({action:"preview_example",surface:d,promptType:p,prompt:S,itemCount:C.length})},[p,d]),O=a.useCallback(b=>{ye.trackPromptAction({action:"select",surface:d,promptType:p||b.modelType,prompt:b.content,source:b.isPreset?"preset":b.pinned?"pinned":"history"}),n==null||n(b)},[p,d,n]),T=a.useCallback(b=>{ye.trackPromptAction({action:b.pinned?"unpin":"pin",surface:d,promptType:p||b.modelType,prompt:b.content}),r==null||r(b.id)},[p,d,r]),I=a.useCallback(b=>{ye.trackPromptAction({action:"delete",surface:d,promptType:p||b.modelType,prompt:b.content}),i==null||i(b.id)},[p,d,i]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`prompt-list-panel ${u}`,children:[s.jsxs("div",{className:"prompt-list-panel__header",children:[m?s.jsx("button",{type:"button",className:"prompt-list-panel__title prompt-list-panel__title-button",onClick:m,children:t}):s.jsx("span",{className:"prompt-list-panel__title",children:t}),l&&s.jsx("span",{className:"prompt-list-panel__count",children:e.length})]}),s.jsx("div",{className:"prompt-list-panel__list",children:e.map(b=>s.jsx(Fc,{content:b.content,title:b.title,sentPrompt:b.sentPrompt,tags:b.tags,resultPreview:b.resultPreview,pinned:b.pinned,isPreset:b.isPreset,modelType:b.modelType,scene:b.scene,previewExamples:b.previewExamples,onClick:()=>O(b),onTogglePin:r&&!b.isPreset?()=>T(b):void 0,onDelete:i&&!b.isPreset?()=>I(b):void 0,onPreviewExample:S=>N(b.id,S),language:o,disabled:c},b.id))})]}),s.jsx(mn,{visible:h,items:y,initialIndex:x,onClose:()=>g(!1),showThumbnails:y.length>1,videoAutoPlay:!0})]})},rl=["结构化 JSON 视觉提示词 schema:","- 每个页面图片提示词必须是一个可直接用于图片生成的 JSON 对象,顶层只使用 layout 和 style。","- layout.header 包含 location_title、main_title、subtitle,用于页面顶部地点/分类、主标题和副标题。","- layout.body.content_blocks 包含 block_type、left_column、right_column;左右栏都包含 title 和 content 数组。","- layout.footer.elements 描述页脚、CTA、滚动提示、页码或辅助信息。","- style.background 描述背景、摄影/插画质感、光影、景深和构图。","- style.elements 描述核心视觉元素、图标、建筑、产品、人物、道具或装饰。","- style.colors 使用数组,包含颜色名称、用途和可选 HEX。","- style.fonts 使用数组,描述标题、副标和正文的字体方向。","- 不要输出 subject、scene、negativePrompt 等旧式字段作为顶层字段;如确实需要,放入 style.elements 或对应内容字段中。","","目标结构示例:","{",' "layout": {',' "header": {',' "location_title": "中国 · 广东 | CHINA GUANGDONG",',' "main_title": "潮起岭南 寻味山海",',' "subtitle": "汕头 × 潮州 × 南澳 × 揭阳 · 4天3晚高定纯玩之旅"'," },",' "body": {',' "content_blocks": {',' "block_type": "首页视觉海报",',' "left_column": { "title": "文化与海岸的交响", "content": ["英歌舞非遗脸谱虚影", "民国骑楼复古剪影"] },',' "right_column": { "title": "留白与张力", "content": [] }'," }"," },",' "footer": { "elements": "SCROLL TO DISCOVER 开启寻味之旅" }'," },",' "style": {',' "background": "电影级光影质感,暖色文化元素平滑过渡至蓝色海浪,景深丰富,光影对比高级",',' "elements": "广济桥灯光、南澳长山尾灯塔、高级几何留白排版",',' "colors": ["潮汕非遗红 (#D13B3B)", "南澳海岛蓝 (#1A4B82)", "骑楼复古暖棕 (#B59372)"],',' "fonts": ["主标题:苍劲大气书法体", "副标及正文:现代极简无衬线几何体"]'," }","}"].join(`
5
- `),ol=["Structured JSON visual prompt schema:","- Each page image prompt must be a JSON object for image generation with only layout and style at the top level.","- layout.header includes location_title, main_title, subtitle.","- layout.body.content_blocks includes block_type, left_column, right_column; each column includes title and content array.","- layout.footer.elements describes footer, CTA, scroll cue, page number, or auxiliary information.","- style.background describes background, rendering/photography quality, lighting, depth of field, and composition.","- style.elements describes key visual elements, icons, architecture, product, people, props, or decorations.","- style.colors is an array with color names, usage, and optional HEX values.","- style.fonts is an array describing title, subtitle, and body font direction.","- Do not use old top-level fields such as subject, scene, or negativePrompt; fold them into style.elements or the matching content fields if needed."].join(`
6
- `);function il(t="zh"){return t==="en"?ol:rl}const Nn="提示词优化",al="aitu://prompt-optimization/",ho={"ai-input.image":{id:"ai-input.image",name:"AI 输入框图片生成",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"AI输入-图片",focus:"补足主体、构图、风格、光线、材质、比例、负面约束和画面细节。"},"ai-input.video":{id:"ai-input.video",name:"AI 输入框视频生成",type:"video",historyType:"video",defaultMode:"structured",noteTitle:"AI输入-视频",focus:"补足主体动作、镜头语言、运镜、时序、转场、连续性和画面节奏。"},"ai-input.audio":{id:"ai-input.audio",name:"AI 输入框音频生成",type:"audio",historyType:"audio",defaultMode:"polish",noteTitle:"AI输入-音频",focus:"补足音乐风格、节奏、情绪、乐器、人声、歌词结构、时长和使用场景。"},"ai-input.text":{id:"ai-input.text",name:"AI 输入框文本生成",type:"text",historyType:"text",defaultMode:"polish",noteTitle:"AI输入-文本",focus:"补足主题、受众、结构、语气、信息密度、格式和交付标准。"},"ai-input.agent":{id:"ai-input.agent",name:"AI 输入框 Agent 指令",type:"agent",historyType:"agent",defaultMode:"polish",noteTitle:"AI输入-Agent",focus:"补足目标、上下文、约束、输入输出、执行步骤、工具边界和验收标准。"},"tool.image":{id:"tool.image",name:"图片工具提示词",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"工具-图片生成",focus:"面向图片生成工具,突出可直接生成的画面描述、构图、风格、尺寸比例和质量约束。"},"tool.video":{id:"tool.video",name:"视频工具提示词",type:"video",historyType:"video",defaultMode:"structured",noteTitle:"工具-视频生成",focus:"面向视频生成工具,突出镜头序列、运动方式、时长、首尾帧关系、主体一致性和节奏。"},"ppt.common":{id:"ppt.common",name:"PPT 公共提示词",type:"image",historyType:"ppt-common",defaultMode:"polish",noteTitle:"PPT-公共提示词",focus:"优化整套 PPT 的统一视觉方向、受众、版式规则、品牌语气、图文密度和风格约束。"},"ppt.slide":{id:"ppt.slide",name:"PPT 单页提示词",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"PPT-单页提示词",focus:"优化单页幻灯片的页面目标、标题层级、内容区块、视觉重点、版式和生成可控性。"},"music.create-song":{id:"music.create-song",name:"爆款音乐歌曲创作",type:"audio",historyType:"audio",defaultMode:"polish",noteTitle:"爆款音乐-歌曲创作",focus:"补足爆款歌曲定位、曲风标签、情绪弧线、人声设定、段落结构、歌词主题和 Suno 可用表达。"}},cl={image:"ai-input.image",video:"ai-input.video",audio:"ai-input.audio",text:"ai-input.text",agent:"ai-input.agent"},ll=new Set(["ai-input.image","tool.image","ppt.slide"]);function dl(t){return`${al}${t}`}function fo(t,e){const n=t||(e?cl[e]:"ai-input.image");return ho[n]}function ul(t,e){return e==="structured"&&ll.has(t.id)}function ml(t,e,n){return ul(t,e)?["",n==="zh"?"【视觉结构化 JSON 强制要求】":"[Required Visual Structured JSON]",il(n),n==="zh"?"最终输出必须是单个合法 JSON 对象,不要 Markdown,不要代码块,不要解释。":"The final output must be one valid JSON object. No Markdown, no code fence, no explanation."].join(`
7
- `):""}function pl(t){return["你是一名专业的「{{scenarioName}}」提示词优化助手。","","请基于用户原始提示词和补充要求,输出一版可直接用于下游模型的最终提示词。","","场景优化方向:",t.focus,"","通用要求:","1. 保持原始意图,不要擅自改题、换主题或新增关键事实。","2. 优先满足补充要求;补充要求为空时,仅做必要润色、结构补全和可执行性增强。","3. 输出语言尽量跟随原始提示词;中英混合时保留原表达习惯。","4. 原始提示词已经完整时,做轻量优化,避免堆砌无关细节。","5. 当前模式为 {{mode}}。structured 模式下可以强化结构、字段和可复用性;polish 模式下保持自然文本。","6. 只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。","","可用变量:{{originalPrompt}}、{{requirements}}、{{language}}、{{mode}}、{{scenarioName}}。"].join(`
8
- `)}function hl(t,e){return t.replace(/\{\{\s*(originalPrompt|requirements|language|mode|scenarioName)\s*\}\}/g,(n,r)=>e[r])}async function fl(){const e=(await Dt()).find(n=>n.name===Nn);if(e)return e.id;try{return(await vr(Nn)).id}catch{const r=(await Dt()).find(i=>i.name===Nn);if(!r)throw new Error("提示词优化目录创建失败");return r.id}}async function go(t){const e=await fl(),n=dl(t.id),r=pl(t),o=(await Ii(n))[0];if(o){const c=await ln(o.id),l=(c==null?void 0:c.content)||"";return l.trim()?l:(await ki(o.id,{title:o.title||t.noteTitle,directoryId:o.directoryId||e,content:r,metadata:{...o.metadata,sourceUrl:n,domain:"提示词优化",tags:["提示词优化",t.type]}}),r)}return await br(t.noteTitle,e,r,{sourceUrl:n,domain:"提示词优化",tags:["提示词优化",t.type]}),r}async function lm(){for(const t of Object.values(ho))await go(t)}async function gl({scenarioId:t,originalPrompt:e,optimizationRequirements:n,language:r,type:i,mode:o}){const c=fo(t,i),l=o||c.defaultMode,m=e.trim(),u=(n==null?void 0:n.trim())||"",d=await go(c),p=hl(d,{originalPrompt:m,requirements:u||"无",language:r,mode:l,scenarioName:c.name}),h=ml(c,l,r),g=r==="zh"?["","---","以下输入块由系统固定附加,请必须以此为准:","","【原始提示词】",m,"","【补充要求】",u||"无,做通顺、准确、可执行的轻量优化。",h,"","【输出要求】",h?"只输出符合视觉结构化 schema 的合法 JSON 对象,不要解释、不要标题、不要 Markdown 代码块。":"只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。"]:["","---","The following input block is appended by the system and must be treated as authoritative:","","[Original Prompt]",m,"","[Refinement Requirements]",u||"None. Apply light polishing for clarity and execution quality.",h,"","[Output Requirement]",h?"Output only a valid JSON object following the visual structured schema. No explanation, no title, no Markdown code block.":"Output only the final optimized prompt. No explanation, no title, no Markdown code block."];return`${p.trim()}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-BJH8E5sr.css","./editor-engines-B8u8agiX.css","./tool-windows-CegtMid1.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,n as ut,s as _s,j as s,P as Bo,i as cr,g as Bn,a as Gn,C as Ue,b as qt,c as Rn,d as lr,H as Go,M as Ke,A as dr,R as Tt,G as qo,Z as ur,e as mr,f as Kt,h as pr,F as hr,k as fr,l as gr,D as wr,m as yr,o as xr,p as Ko,q as Zo,t as Yo,u as cn,X as Mt,v as gn,w as _r,x as vs,y as it,z as Xo,B as Jo,L as Qo,U as ei,S as ti,E as je,I as ni,J as si,K as ri,N as oi,O as ii,Q as ai,T as ci,V as li,W as di,Y as ui,_ as Rt,$ as mi,a0 as qn,a1 as vr,a2 as pi,a3 as bs,a4 as hi,a5 as fi,a6 as Fe,a7 as bn,a8 as gi,a9 as wi,aa as yi,ab as xi,ac as _i,ad as Ss,ae as Kn,af as vi,ag as bi,ah as se,ai as Si,aj as Ii,ak as Zn,al as ht,am as ye,an as ki,ao as ln,ap as Mi,aq as br,ar as Dt,as as Sr,at as Ci,au as Ir,av as zn,aw as ji,ax as kr,ay as Is,az as Dn,aA as Ti,aB as ks,aC as Ht,aD as Ln,aE as Ni,aF as Sn,aG as Ei,aH as Pi,aI as Ai,aJ as Ri,aK as zi,aL as Di,aM as Mr,aN as Li,aO as $i,aP as Ms,aQ as Oi,aR as Yn,aS as Fi,aT as Ui,aU as Cr,aV as jr,aW as Tr,aX as at,aY as Xn,aZ as Jn,a_ as Qn,a$ as Wi,b0 as Hi,b1 as Nr,b2 as Er,b3 as Zt,b4 as Pr,b5 as Ar,b6 as Vi,b7 as Bi,b8 as Cs,b9 as Gi,ba as Rr,bb as Yt,bc as Ct,bd as qi,be as wn,bf as zr,bg as xt,bh as yn,bi as Ki,bj as Zi,bk as Dr,bl as Yi,bm as Xi,bn as es,bo as Ji,bp as Lr,bq as $n,br as Qi,bs as $r,bt as ts,bu as Or,bv as ea,bw as ns,bx as ss,by as Fr,bz as ft,bA as ta,bB as na,bC as Ur,bD as sa,bE as ra,bF as oa,bG as ia,bH as aa,bI as ca,bJ as la,bK as Wr,bL as da,bM as ua,bN as ma,bO as pa,bP as ha,bQ as fa,bR as js,bS as ga,bT as wa,bU as ya,bV as xa,bW as _a,bX as va,bY as ba,bZ as Sa,b_ as Ia,b$ as ka,c0 as Hr,c1 as Ma,c2 as Ca,c3 as ja,c4 as Ta,c5 as Ts,c6 as Na,c7 as Ea,c8 as Pa,c9 as Aa,ca as Ra,cb as za,cc as Da,cd as La,ce as Vr,cf as $a,cg as Oa,ch as Fa,ci as Ua,cj as Wa,ck as Ha,cl as Va,cm as Br,cn as Ba,co as Gr,cp as In,cq as kn,cr as Ns,cs as Es,ct as Ga,cu as qa}from"./startup-app-M6vjXkRC.js";import{_ as dt}from"./startup-runtime-DTmhLESk.js";const St=new Map,qr=300*1e3,Ps=500,gt=new Set;let zt=!1,Mn=null,Cn=null;function Ka(){return Mn||(Mn=caches.open("drawnix-images-thumb")),Mn}function Za(){return Cn||(Cn=caches.open("drawnix-images")),Cn}function Kr(t,e){return`${t}|${e}`}function Ya(t,e){try{const n=new URL(t,window.location.origin);return n.searchParams.delete("thumbnail"),n.searchParams.set("_thumb",e),n.toString()}catch{const n=t.replace(/[?&]thumbnail=[^&]*/g,"").replace(/thumbnail=[^&]*&?/g,""),r=n.includes("?")?"&":"?";return`${n}${r}_thumb=${e}`}}function xn(t,e){return t.startsWith("data:")||t.startsWith("blob:")||e!=="video"&&(t.startsWith("http://")||t.startsWith("https://"))}function As(t,e="small",n){const r=ut(t);if(xn(r,n))return r;try{const i=new URL(r,window.location.origin);return i.searchParams.set("thumbnail",e),i.toString()}catch{const i=r.includes("?")?"&":"?";return`${r}${i}thumbnail=${e}`}}async function Vt(){if(!(zt||gt.size===0)){zt=!0;try{const t=Date.now();if(St.size>Ps)for(const[r,i]of St)(t-i>qr||St.size>Ps)&&St.delete(r);const n=Array.from(gt).slice(0,5);for(const r of n){gt.delete(r);const[i,o,c="small"]=r.split("|");try{await Zr(i,o,c),St.set(Kr(i,c),Date.now())}catch(l){console.warn("Failed to ensure thumbnail:",i,l)}}gt.size>0&&("requestIdleCallback"in window?window.requestIdleCallback(Vt):setTimeout(Vt,100))}finally{zt=!1}}}async function Zr(t,e,n){const r=ut(t);if(xn(r,e))return;const i=Ya(r,n);if(await(await Ka()).match(i))return;const l=await Za();let m=await l.match(r);if(!m)try{const u=new URL(r,window.location.origin);(u.pathname.startsWith("/__aitu_cache__/")||u.pathname.startsWith("/asset-library/"))&&(m=await l.match(u.pathname))}catch{}if(m){const u=await m.blob();if(_s.isInitialized()){const d=await u.arrayBuffer();await _s.generateThumbnail(r,e,d,u.type,[n])}}}function Xa(t,e,n,r=!1){const i=ut(t);if(xn(i,e))return;const o=Kr(i,n),c=St.get(o);if(c&&Date.now()-c<qr)return;const l=`${i}|${e}|${n}`;if(!gt.has(l)){if(gt.add(l),r){(async()=>{if(!zt)try{zt=!0,gt.delete(l),await Zr(i,e,n),St.set(o,Date.now())}catch(m){console.warn("Failed to ensure thumbnail immediately:",i,m)}finally{zt=!1,gt.size>0&&setTimeout(Vt,0)}})();return}"requestIdleCallback"in window?window.requestIdleCallback(Vt,{timeout:2e3}):setTimeout(Vt,200)}}function Ja(t,e,n="small"){const[r,i]=a.useState(t?As(t,n,e):void 0);return a.useEffect(()=>{if(!t){i(void 0);return}const o=ut(t),c=As(o,n,e);i(c),e&&!xn(t,e)&&Xa(t,e,n,e==="video")},[t,e,n]),r}const Rs=1,Qa=4,Yr=600*1e3,Xr=600*1e3,dn=new Map,un=new Map;function Jr(t){dn.forEach((e,n)=>{t-e>Yr&&dn.delete(n)})}function ec(t){const e=Date.now();Jr(e),dn.set(t,e)}function tc(t){const e=Date.now();Jr(e);const n=dn.get(t);return typeof n=="number"&&e-n<=Yr}function Qr(t){un.forEach((e,n)=>{t-e.resolvedAt>Xr&&un.delete(n)})}function nc(t,e){const n=Date.now();Qr(n),un.set(t,{resolvedPoster:e,resolvedAt:n})}function zs(t){if(!t)return null;const e=Date.now();Qr(e);const n=un.get(t);return n&&e-n.resolvedAt<=Xr?n.resolvedPoster:null}function sc(t,e){if(e<=0||!t)return t;try{const n=new URL(t,window.location.origin);return n.searchParams.set("_poster_retry",String(e)),n.toString()}catch{const n=t.includes("?")?"&":"?";return`${t}${n}_poster_retry=${e}`}}function jn(t,e){return s.jsxs("div",{className:"video-poster-preview",children:[t,e&&s.jsx("div",{className:"video-poster-preview__play-overlay","aria-hidden":"true",children:s.jsx(Bo,{size:"32px"})})]})}const rc=({src:t,poster:e,alt:n="",className:r,thumbnailSize:i="small",imageLoading:o="lazy",activateVideoOnClick:c=!1,playOnActivate:l=!1,onClick:m,videoProps:u})=>{const d=a.useMemo(()=>typeof e=="string"&&e.trim()?e.trim():void 0,[e]),p=a.useMemo(()=>d?tc(d):!1,[d]),h=Ja(t,"video",i),[g,y]=a.useState(p),f=g?h:d||h,x=!!(d&&!g),z=!!(f&&f===h&&f!==t),N=a.useRef(null),O=a.useRef(!1),T=a.useRef(null),[I,v]=a.useState(()=>zs(f)),[S,C]=a.useState(0),[R,U]=a.useState(!1),P=c;a.useEffect(()=>{y(p)},[p]),a.useEffect(()=>{v(zs(f)),C(0),U(!1),O.current=!1,T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[t,f,c,h,d,i]),a.useEffect(()=>{if(R||I&&I===f)return;if(!f){P||U(!0);return}const Q=x?f:sc(f,S);let B=!1;const _=new Image,E=()=>{if(!z||S>=Qa){P||U(!0);return}T.current=window.setTimeout(()=>{C(M=>M+1)},180+S*220)};return _.onload=()=>{if(!B){if(x||_.naturalWidth>Rs||_.naturalHeight>Rs){nc(f,f),v(f);return}E()}},_.onerror=()=>{if(!B){if(x&&d){ec(d),y(!0),v(null),C(0);return}E()}},_.src=Q,()=>{B=!0,_.onload=null,_.onerror=null,T.current!==null&&(window.clearTimeout(T.current),T.current=null)}},[t,f,S,x,z,R,d,I,P]),a.useEffect(()=>{var Q;!R||!l||!O.current||(O.current=!1,(Q=N.current)==null||Q.play().catch(()=>{}))},[R,l]),a.useEffect(()=>()=>{const Q=N.current;if(Q)try{Q.pause(),Q.removeAttribute("src"),Q.load()}catch{}},[]);const J=Q=>{c&&(O.current=!0,U(!0)),m==null||m(Q)},ee=Q=>{m==null||m(Q)},X=c&&!R;return!R&&I?jn(s.jsx("img",{src:I,alt:n,className:`video-poster-preview__media${r?` ${r}`:""}`,loading:o,decoding:"async",draggable:!1,referrerPolicy:"no-referrer",onClick:J}),X):!R&&!I?jn(s.jsx("div",{className:`video-poster-preview__placeholder${r?` ${r}`:""}`,"aria-hidden":"true",onClick:c?()=>{O.current=!0,U(!0)}:void 0}),X):jn(s.jsx("video",{ref:N,src:t,poster:I||d,className:`video-poster-preview__media${r?` ${r}`:""}`,playsInline:!0,...u,onClick:ee}),!1)},oc=.1,ic=5,Ds=t=>Math.max(oc,Math.min(ic,t));function ac(t){const{items:e,initialMode:n="single",initialIndex:r=0,maxCompareSlots:i=4,defaultCompareLayout:o="horizontal",visible:c,onModeChange:l}=t,m=a.useCallback(()=>{if(Array.isArray(r))return r.slice(0,i);const q=typeof r=="number"?r:0,ce=(q+1)%e.length;return e.length>1?[q,ce]:[q]},[r,i,e.length]),u=a.useCallback(()=>{const q=m().length;return q>=4?4:q===3?3:2},[m]),[d,p]=a.useState(n),[h,g]=a.useState(typeof r=="number"?r:0),[y,f]=a.useState(m),[x,z]=a.useState(o),[N,O]=a.useState(!1),[T,I]=a.useState(1),[v,S]=a.useState({x:0,y:0}),[C,R]=a.useState(0),[U,P]=a.useState(u);a.useEffect(()=>{if(c){const q=m();p(n),g(typeof r=="number"?r:0),f(q),P(q.length>=4?4:q.length===3?3:2),I(1),S({x:0,y:0}),R(0)}},[c,n,r,m]);const J=a.useRef(e);a.useEffect(()=>{if(!c||e===J.current){J.current=e;return}const q=J.current;J.current=e;const ce=q[h];if(!(ce!=null&&ce.id))return;const be=e.findIndex(me=>me.id===ce.id);be!==-1&&be!==h&&g(be)},[c,e,h]);const ee=a.useMemo(()=>({mode:d,currentIndex:h,compareIndices:y,compareLayout:x,syncMode:N,zoomLevel:T,panOffset:v,focusedSlot:C}),[d,h,y,x,N,T,v,C]),X=a.useCallback(q=>{if(q!==d){if(q==="compare"){const ce=(h+1)%e.length;f(e.length>1?[h,ce]:[h])}else{const ce=y[C]??y[0]??0;g(ce)}p(q),I(1),S({x:0,y:0}),l==null||l(q)}},[d,h,e.length,y,C,l]),Q=a.useCallback(q=>{q>=0&&q<e.length&&(g(q),I(1),S({x:0,y:0}))},[e.length]),B=a.useCallback(()=>{const q=h>0?h-1:e.length-1;Q(q)},[h,e.length,Q]),_=a.useCallback(()=>{const q=h<e.length-1?h+1:0;Q(q)},[h,e.length,Q]),E=a.useCallback((q,ce)=>{f(be=>{const me=[...be];return typeof ce=="number"&&ce<U?me[ce]=q:me.length<U?me.push(q):me[C]=q,me})},[U,C]),M=a.useCallback(q=>{f(ce=>{if(ce.length<=2)return ce;const be=[...ce];return be.splice(q,1),be}),C>=q&&C>0&&R(C-1)},[C]),$=a.useCallback((q,ce)=>{f(be=>{const me=[...be],Re=me[q];return me[q]=me[ce],me[ce]=Re,me})},[]),re=a.useCallback(q=>{z(q)},[]),fe=a.useCallback(()=>{O(q=>!q)},[]),K=a.useCallback(q=>{I(ce=>{const be=ce+q;return Ds(be)})},[]),de=a.useCallback(q=>{I(Ds(q))},[]),ie=a.useCallback(()=>{I(1),S({x:0,y:0})},[]),ue=a.useCallback(q=>{S(q)},[]),xe=a.useCallback(q=>{R(q)},[]),pe=a.useCallback(q=>{P(q),f(ce=>{if(ce.length>q)return ce.slice(0,q);if(ce.length<q&&e.length>ce.length){const be=[...ce];let me=(ce[ce.length-1]+1)%e.length;for(;be.length<q&&be.length<e.length;)be.includes(me)||be.push(me),me=(me+1)%e.length;return be}return ce})},[e.length]),ae=a.useMemo(()=>({setMode:X,goTo:Q,goToPrev:B,goToNext:_,addToCompare:E,removeFromCompare:M,swapSlots:$,setCompareLayout:re,toggleSyncMode:fe,zoom:K,setZoomLevel:de,setPan:ue,resetView:ie,setFocusedSlot:xe,setSlotCount:pe}),[X,Q,B,_,E,M,$,re,fe,K,de,ue,ie,xe,pe]);return[ee,ae]}let eo=null;function im(t){eo=t}function cc(){return eo}const Nt=400;function lc(t){return t==="video"?{width:Nt,height:Math.round(Nt*(9/16))}:{width:Nt,height:Nt}}async function dc(t,e,n,r,i){const o=i||lc(e);return e==="video"?(await Rn(t,n,r,!1,o,!0,!0),o):(await lr(t,n,r,!1,o,!0,!0),o)}async function uc(t,e,n,r){const i=cc();if(!i)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{if(!n){const u=await cr(i,e,t,r);if(u)return{success:!0,data:{insertedCount:1,items:[{type:t,point:u.point,elementId:u.elementId,size:u.size}],firstElementId:u.elementId,firstElementPosition:u.point,firstElementSize:u.size},type:"text"}}const o=n||Bn(i,{logPrefix:"MediaQuickInsert"})||Gn(i,{emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT,c=i.children.length,l=await dc(i,t,e,o,r),m=i.children[c];return requestAnimationFrame(()=>{qt(i,[o[0]+Nt/2,o[1]+Nt/2])}),{success:!0,data:{insertedCount:1,items:[{type:t,point:o,elementId:m==null?void 0:m.id,size:l}],firstElementId:m==null?void 0:m.id,firstElementPosition:o,firstElementSize:l},type:"text"}}catch(o){return console.error("[MediaQuickInsert] Failed to insert media:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const ke=({content:t,children:e,placement:n="bottom",sideOffset:r=8,crossAxisOffset:i=0,contentClassName:o,closeDelay:c=100})=>s.jsx(Go,{content:t,placement:n,sideOffset:r,crossAxisOffset:i,contentClassName:o||"viewer-popover",closeDelay:c,children:e}),tn={x:0,y:0},mc=.1,pc=5,Ft=.001,Ls=.25,hc=.0025,$s=.08,fc=1,gc=2,wc=16,yc=800,xc=32,_c=88,vc=140,bc=t=>Math.max(mc,Math.min(pc,t)),Sc=t=>t.deltaMode===fc?t.deltaY*wc:t.deltaMode===gc?t.deltaY*yc:t.deltaY,Ic=t=>Math.max(-$s,Math.min($s,t)),kc=(t,e)=>{if(t.offsetWidth>0&&t.offsetHeight>0)return{width:t.offsetWidth,height:t.offsetHeight};const n=t.getBoundingClientRect(),r=Math.max(Math.abs(e),Ft);return{width:n.width/r,height:n.height/r}},to="media-viewport-toolbar-state-single",Mc=()=>{try{const t=localStorage.getItem(to);if(t)return JSON.parse(t)}catch{}return{orientation:"horizontal",position:null}},Cc=t=>{try{localStorage.setItem(to,JSON.stringify(t))}catch{}},On=a.forwardRef(({item:t,slotIndex:e,isFocused:n=!1,zoomLevel:r=1,panOffset:i,onClick:o,videoAutoPlay:c=!1,videoLoop:l=!0,onZoomChange:m,onPanChange:u,isCompareMode:d=!1,onInsertToCanvas:p,onDownload:h,onEdit:g,onVideoPlayStateChange:y,onVideoTimeUpdate:f,isSyncMode:x=!1},z)=>{var Ze;const N=a.useRef(null),O=a.useRef(null),T=a.useRef(null),[I,v]=a.useState(!1),[S,C]=a.useState(!0),[R,U]=a.useState(!1),[P,J]=a.useState({x:0,y:0}),[ee,X]=a.useState(i??tn),[Q,B]=a.useState(r),_=a.useRef(r),[E,M]=a.useState(0),[$,re]=a.useState(!1),[fe,K]=a.useState(!1),[de,ie]=a.useState(!1),[ue,xe]=a.useState(!1),[pe,ae]=a.useState(!1),q=a.useRef(null),ce=a.useRef(!1),be=a.useRef(r),me=a.useRef(i);a.useImperativeHandle(z,()=>({resetVideo:()=>{O.current&&(O.current.currentTime=0,O.current.play().catch(()=>{}))},playVideo:()=>{O.current&&O.current.play().catch(()=>{})},pauseVideo:()=>{O.current&&O.current.pause()},toggleVideoPlayback:()=>{if(O.current){if(O.current.paused||O.current.ended){O.current.play().catch(()=>{});return}O.current.pause()}},setVideoTime:A=>{O.current&&(O.current.currentTime=A)},getVideoTime:()=>{var A;return((A=O.current)==null?void 0:A.currentTime)??0},isVideo:()=>(t==null?void 0:t.type)==="video"}),[t]);const[Re]=a.useState(()=>d?{orientation:"horizontal",position:null}:Mc()),[Me,We]=a.useState(Re.orientation),[Ee,Te]=a.useState(Re.position),[Ye,$e]=a.useState(!1),ve=a.useRef({x:0,y:0,posX:0,posY:0}),Ie=(t==null?void 0:t.type)==="video",he=(t==null?void 0:t.type)==="audio",ze=((Ze=t==null?void 0:t.prompt)==null?void 0:Ze.trim())||"",De=!!ze&&(de||ue)&&!pe,He=t?Ie||he?t.url:ut(t.url):"",Be=t!=null&&t.posterUrl?ut(t.posterUrl):"",Ge=t?`${t.type}:${t.id||t.url}`:"empty",Qe=!!(t!=null&&t.url&&!he&&!d&&!I),Ne=a.useCallback(()=>{q.current!==null&&(window.clearTimeout(q.current),q.current=null)},[]),L=a.useCallback(()=>{Ne(),ie(!0)},[Ne]),w=a.useCallback(()=>{ie(!1),Ne(),q.current=window.setTimeout(()=>{xe(!1),q.current=null},120)},[Ne]),V=a.useCallback(()=>{Ne(),xe(!0)},[Ne]),b=a.useCallback(()=>{xe(!1)},[]);a.useLayoutEffect(()=>{v(!1),C(!(t!=null&&t.url)||he||d),U(!1);const A=me.current??tn,ge=be.current;X(A),_.current=ge,B(ge),M(0),re(!1),K(!1),ce.current=!1},[Ge,t==null?void 0:t.url,he,d]),a.useEffect(()=>()=>{Ne()},[Ne]),a.useEffect(()=>{d||Cc({orientation:Me,position:Ee})},[Me,Ee,d]),a.useLayoutEffect(()=>{const A=i??tn;me.current=i,X(ge=>ge.x===A.x&&ge.y===A.y?ge:A)},[i]),a.useLayoutEffect(()=>{be.current=r,_.current=r,B(A=>A===r?A:r)},[r]);const D=a.useCallback((A,ge="manual")=>{const Le=bc(A);ge==="manual"&&(ce.current=!0),!(Math.abs(_.current-Le)<=Ft)&&(_.current=Le,B(tt=>Math.abs(tt-Le)<=Ft?tt:Le),m==null||m(Le))},[m]),W=a.useCallback(A=>{const ge=me.current??tn;Math.abs(ge.x-A.x)<=Ft&&Math.abs(ge.y-A.y)<=Ft||(me.current=A,X(A),u==null||u(A))},[u]),G=a.useCallback(()=>{if(d||he||!N.current)return;if(ce.current){C(!0);return}const A=Ie?O.current:T.current;if(!A||!N.current)return;const ge=N.current.getBoundingClientRect();if(ge.width<=0||ge.height<=0)return;const Le=Ie?A.videoWidth:A.naturalWidth,tt=Ie?A.videoHeight:A.naturalHeight;if(Le<=0||tt<=0)return;const Xe=kc(A,_.current);if(Xe.width<=0||Xe.height<=0)return;const Je=Ie?vc:_c,rt=Math.max(ge.width-xc,0),mt=Math.max(ge.height-Je,0);if(rt<=0||mt<=0)return;const ct=Math.min(rt/Xe.width,mt/Xe.height);!Number.isFinite(ct)||ct<=0||(W({x:0,y:-Je/2}),D(ct,"auto"),C(!0))},[d,he,Ie,W,D]);a.useLayoutEffect(()=>{if(!(t!=null&&t.url)||he||d)return;const A=Ie?O.current:T.current;if(!A)return;if(Ie){A.readyState>=1&&G();return}const ge=A;ge.complete&&ge.naturalWidth>0&&G()},[t,he,d,Ie,G]),a.useEffect(()=>{if(!(t!=null&&t.url)||he||d||typeof ResizeObserver>"u"||!N.current)return;const A=new ResizeObserver(()=>{G()});return A.observe(N.current),()=>{A.disconnect()}},[t==null?void 0:t.url,he,d,G]);const Y=a.useCallback(A=>{A.button===0&&(A.preventDefault(),U(!0),J({x:A.clientX-ee.x,y:A.clientY-ee.y}))},[ee]),le=a.useCallback(A=>{if(!R)return;ce.current=!0;const ge={x:A.clientX-P.x,y:A.clientY-P.y};me.current=ge,X(ge),u==null||u(ge)},[R,P,u]),_e=a.useCallback(()=>{U(!1)},[]),k=a.useCallback(A=>{A.preventDefault();const ge=Sc(A);if(!Number.isFinite(ge)||ge===0)return;const Le=Ic(-ge*hc);D(_.current+Le)},[D]),H=a.useCallback(()=>{D(_.current+Ls)},[D]),F=a.useCallback(()=>{D(_.current-Ls)},[D]),Z=a.useCallback(()=>{M(A=>A-90)},[]),oe=a.useCallback(()=>{M(A=>A+90)},[]),te=a.useCallback(()=>{re(A=>!A)},[]),Pe=a.useCallback(()=>{K(A=>!A)},[]),Ce=a.useCallback(async()=>{if(t)try{const A=t.type==="video"?"video":"image";if(t.type==="audio"){Ke.warning("音频暂不支持直接插入到画布");return}const ge=await uc(A,He);ge.success?Ke.success(t.type==="video"?"视频已插入到画布":"图片已插入到画布"):Ke.error(ge.error||"插入失败")}catch(A){console.error("Failed to insert to canvas:",A),Ke.error("插入失败")}},[t,He]),Ae=a.useCallback(()=>{We(A=>A==="horizontal"?"vertical":"horizontal")},[]),qe=a.useCallback(A=>{A.preventDefault(),A.stopPropagation(),$e(!0);const ge=Ee||{x:0,y:0};ve.current={x:A.clientX,y:A.clientY,posX:ge.x,posY:ge.y};const Le=Xe=>{const Je=Xe.clientX-ve.current.x,rt=Xe.clientY-ve.current.y;Te({x:ve.current.posX+Je,y:ve.current.posY+rt})},tt=()=>{$e(!1),document.removeEventListener("mousemove",Le),document.removeEventListener("mouseup",tt)};document.addEventListener("mousemove",Le),document.addEventListener("mouseup",tt)},[Ee]),et=a.useCallback(A=>{if(A.stopPropagation(),A.touches.length!==1)return;const ge=A.touches[0];$e(!0);const Le=Ee||{x:0,y:0};ve.current={x:ge.clientX,y:ge.clientY,posX:Le.x,posY:Le.y};const tt=Je=>{if(Je.touches.length!==1)return;Je.preventDefault();const rt=Je.touches[0],mt=rt.clientX-ve.current.x,ct=rt.clientY-ve.current.y;Te({x:ve.current.posX+mt,y:ve.current.posY+ct})},Xe=()=>{$e(!1),document.removeEventListener("touchmove",tt),document.removeEventListener("touchend",Xe),document.removeEventListener("touchcancel",Xe)};document.addEventListener("touchmove",tt,{passive:!1}),document.addEventListener("touchend",Xe),document.addEventListener("touchcancel",Xe)},[Ee]),Ve=a.useCallback(()=>{Te(null)},[]);if(!t)return s.jsx("div",{className:`media-viewport media-viewport--empty ${n?"media-viewport--focused":""}`,onClick:o,children:s.jsx("div",{className:"media-viewport__placeholder",children:s.jsx("span",{children:"点击底部缩略图添加媒体"})})});const j=$?-Q:Q,ne=fe?-Q:Q,we={transform:`translate(${ee.x}px, ${ee.y}px) scale(${j}, ${ne}) rotate(${E}deg)`},Oe=Qe&&!S;return s.jsxs("div",{ref:N,className:`media-viewport ${n?"media-viewport--focused":""} ${he?"media-viewport--audio":""} ${Ie?"media-viewport--video":""} ${d?"":"media-viewport--single"}`,onClick:o,onMouseDown:he?void 0:Y,onMouseMove:he?void 0:le,onMouseUp:he?void 0:_e,onWheel:he?void 0:k,onMouseLeave:()=>{he||_e(),ie(!1),xe(!1),ae(!1),Ne()},"data-slot":e,children:[s.jsx("div",{className:`media-viewport__content ${Oe?"media-viewport__content--auto-fitting":""}`,style:he?void 0:we,children:Ie?s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx("video",{ref:O,src:He,autoPlay:c,loop:l,controls:!0,className:"media-viewport__video",referrerPolicy:"no-referrer",onClick:A=>A.stopPropagation(),onPlay:()=>{x&&y&&y(!0)},onPause:()=>{x&&y&&y(!1)},onSeeked:()=>{x&&f&&O.current&&f(O.current.currentTime)},onLoadedMetadata:G})}):he?s.jsx("div",{className:"media-viewport__audio-shell",onClick:A=>A.stopPropagation(),children:s.jsxs("div",{className:"media-viewport__audio-card",children:[s.jsx(dr,{src:Be,alt:t.alt||t.title||"",imageClassName:"media-viewport__audio-poster",fallbackClassName:"media-viewport__audio-poster media-viewport__audio-poster--fallback",iconSize:56}),s.jsxs("div",{className:"media-viewport__audio-meta",children:[t.title&&s.jsx("div",{className:"media-viewport__audio-title",children:t.title}),typeof t.duration=="number"&&Number.isFinite(t.duration)&&t.duration>0&&s.jsxs("div",{className:"media-viewport__audio-duration",children:[Math.floor(t.duration/60),":",String(Math.round(t.duration%60)).padStart(2,"0")]})]}),s.jsx("audio",{src:He,controls:!0,preload:"metadata",className:"media-viewport__audio",referrerPolicy:"no-referrer"})]})}):I?s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx("div",{className:"media-viewport__image-fallback",children:s.jsx("span",{children:"图片加载失败"})})}):s.jsx("div",{className:"media-viewport__media-hitbox",onMouseEnter:L,onMouseLeave:w,children:s.jsx(Tt,{ref:T,src:He,alt:t.alt||t.title||"",className:"media-viewport__image",draggable:!1,showSkeleton:!1,eager:!0,onLoad:G,onError:()=>{v(!0),C(!0)}})})}),s.jsxs("div",{className:`media-viewport__toolbar media-viewport__toolbar--${Me} ${Ye?"media-viewport__toolbar--dragging":""} ${d?"media-viewport__toolbar--compact":""}`,style:!d&&Ee?{transform:`translate(calc(-50% + ${Ee.x}px), ${Ee.y}px)`}:void 0,onMouseEnter:()=>ae(!0),onMouseLeave:()=>ae(!1),onMouseDown:A=>A.stopPropagation(),onClick:A=>A.stopPropagation(),children:[!he&&s.jsxs(s.Fragment,{children:[!d&&s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"拖拽移动工具栏,双击重置位置",placement:"top",contentClassName:"viewer-popover",children:s.jsx("div",{className:"media-viewport__toolbar-handle",onMouseDown:qe,onTouchStart:et,onDoubleClick:A=>{A.stopPropagation(),Ve()},children:s.jsx(qo,{size:14})})}),s.jsx(ke,{content:Me==="horizontal"?"切换为垂直布局":"切换为水平布局",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",className:"media-viewport__toolbar-orientation-btn",onClick:A=>{A.stopPropagation(),A.preventDefault(),Ae()},children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Me==="horizontal"?s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("polyline",{points:"8 7 12 3 16 7"}),s.jsx("polyline",{points:"8 17 12 21 16 17"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),s.jsx("polyline",{points:"7 8 3 12 7 16"}),s.jsx("polyline",{points:"17 8 21 12 17 16"})]})})})}),s.jsx("div",{className:"media-viewport__toolbar-divider"})]}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"缩小",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"缩小",onClick:A=>{A.stopPropagation(),A.preventDefault(),F()},children:s.jsx(ur,{size:16})})}),s.jsxs("span",{className:"media-viewport__zoom-level",children:[Math.round(Q*100),"%"]}),s.jsx(ke,{content:"放大",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"放大",onClick:A=>{A.stopPropagation(),A.preventDefault(),H()},children:s.jsx(mr,{size:16})})})]}),s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"向左旋转 90°",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"向左旋转 90°",onClick:A=>{A.stopPropagation(),A.preventDefault(),Z()},children:s.jsx(Kt,{size:16})})}),s.jsx(ke,{content:"向右旋转 90°",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"向右旋转 90°",onClick:A=>{A.stopPropagation(),A.preventDefault(),oe()},children:s.jsx(pr,{size:16})})})]}),s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsxs("div",{className:"media-viewport__toolbar-group",children:[s.jsx(ke,{content:"水平翻转",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"水平翻转",className:$?"active":"",onClick:A=>{A.stopPropagation(),A.preventDefault(),te()},children:s.jsx(hr,{size:16})})}),s.jsx(ke,{content:"垂直翻转",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button","aria-label":"垂直翻转",className:fe?"active":"",onClick:A=>{A.stopPropagation(),A.preventDefault(),Pe()},children:s.jsx(fr,{size:16})})})]})]}),!d&&!he&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsx(ke,{content:"插入到画布",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),p?p():Ce()},children:s.jsx(gr,{size:16})})})]}),!d&&h&&s.jsxs(s.Fragment,{children:[he&&s.jsx("div",{className:"media-viewport__toolbar-divider"}),s.jsx(ke,{content:"下载",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),h()},children:s.jsx(wr,{size:16})})})]}),!d&&g&&(t==null?void 0:t.type)==="image"&&s.jsx(ke,{content:"编辑图片",placement:"top",contentClassName:"viewer-popover",children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),A.preventDefault(),g()},children:s.jsx(yr,{size:16})})})]}),ze&&!he&&s.jsx(ke,{content:ze,placement:"bottom",sideOffset:10,contentClassName:"viewer-popover viewer-popover--prompt",children:s.jsx("div",{className:`media-viewport__prompt ${De?"media-viewport__prompt--visible":""} ${ue?"media-viewport__prompt--expanded":""}`,onMouseEnter:V,onMouseLeave:b,children:ze})})]})});On.displayName="MediaViewport";const jc=({src:t,fallbackSrc:e,alt:n})=>{const[r,i]=a.useState(t),[o,c]=a.useState(!1);return a.useEffect(()=>{i(t),c(!1)},[t]),o?s.jsx("div",{className:"thumbnail-queue__image thumbnail-queue__image-fallback",children:s.jsx("span",{children:"加载失败"})}):s.jsx(Tt,{src:r,alt:n,className:"thumbnail-queue__image",showSkeleton:!1,onError:()=>{if(e&&r!==e){i(e);return}c(!0)}})};function Tc(t,e="small"){const n=ut(t);if(n.startsWith("http://")||n.startsWith("https://")||n.startsWith("blob:")||Yo(n))return n;try{const r=new URL(n,window.location.origin);return r.searchParams.set("thumbnail",e),r.toString()}catch{const r=n.includes("?")?"&":"?";return`${n}${r}thumbnail=${e}`}}const Nc=({items:t,mode:e,currentIndex:n,compareIndices:r,onThumbnailClick:i,onDragStart:o})=>{const c=a.useRef(null),[l,m]=a.useState(null);a.useEffect(()=>{if(e==="single"&&c.current){const y=c.current.querySelector(".thumbnail-queue__item--active");y&&y.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}},[n,e]);const u=a.useCallback((y,f)=>{f.dataTransfer.setData("text/plain",String(y)),f.dataTransfer.effectAllowed="move",m(y),o==null||o(y)},[o]),d=a.useCallback(()=>{m(null)},[]),p=a.useCallback(y=>e==="single"?y===n:r.includes(y),[e,n,r]),h=a.useCallback(y=>{if(e!=="compare")return;const f=r.indexOf(y);return f>=0?f+1:void 0},[e,r]),g=a.useCallback((y,f)=>{const x=p(f),z=h(f),N=l===f,O=y.type==="video",T=y.type==="audio",I=ut(y.url),v=y.posterUrl?ut(y.posterUrl):"",S=Tc(T&&v?v:I,"small");return s.jsxs("div",{className:`thumbnail-queue__item ${x?"thumbnail-queue__item--active":""} ${N?"thumbnail-queue__item--dragging":""}`,onClick:()=>i(f),draggable:e==="compare",onDragStart:C=>u(f,C),onDragEnd:d,role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),i(f))},children:[s.jsx("div",{className:"thumbnail-queue__thumb",children:O?s.jsxs(s.Fragment,{children:[s.jsx(rc,{src:I,poster:v||void 0,className:"thumbnail-queue__video",alt:y.alt||y.title||"",thumbnailSize:"small",videoProps:{muted:!0,preload:"metadata"}}),s.jsx("div",{className:"thumbnail-queue__video-icon",children:s.jsx(xr,{size:16})})]}):T?s.jsxs(s.Fragment,{children:[s.jsx(dr,{src:v?S:void 0,fallbackSrc:v,alt:y.alt||y.title||"",imageClassName:"thumbnail-queue__image",fallbackClassName:"thumbnail-queue__image thumbnail-queue__audio-fallback",iconSize:18,loading:"lazy"}),s.jsx("div",{className:"thumbnail-queue__video-icon",children:s.jsx(Ko,{size:16})})]}):s.jsx(jc,{src:S,alt:y.alt||y.title||"",fallbackSrc:I})}),x&&s.jsx("div",{className:"thumbnail-queue__check",children:z?s.jsx("span",{className:"thumbnail-queue__slot-number",children:z}):s.jsx(Zo,{size:18})})]},y.id||`${y.url}-${f}`)},[p,h,l,e,i,u,d]);return t.length===0?null:s.jsx("div",{className:"thumbnail-queue",ref:c,children:s.jsx("div",{className:"thumbnail-queue__list",children:t.map((y,f)=>g(y,f))})})},Ec=({mode:t,currentIndex:e,totalCount:n,slotCount:r,compareLayout:i,syncMode:o,onModeChange:c,onSlotCountChange:l,onLayoutChange:m,onSyncToggle:u,onResetView:d,onClose:p,onFullscreen:h,isImage:g=!1,showEditButton:y=!1,onBackToPreview:f,onResetEdit:x,onSaveEdit:z})=>{const N=a.useCallback(C=>{m(C),C==="grid"&&r<4&&l(4)},[m,l,r]),O=()=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"viewer-toolbar__indicator",children:[s.jsx("span",{className:"viewer-toolbar__current",children:e+1}),s.jsx("span",{className:"viewer-toolbar__separator",children:"/"}),s.jsx("span",{className:"viewer-toolbar__total",children:n})]}),n>1&&s.jsx(ke,{content:"对比模式",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>c("compare"),"aria-label":"对比模式",children:s.jsx(vs,{size:18})})}),y&&g&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx(ke,{content:"编辑图片",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:()=>c("edit"),"aria-label":"编辑图片",children:s.jsx(yr,{size:18})})})]})]}),T=()=>s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__btn",onClick:f,"aria-label":"返回预览",children:[s.jsx(cn,{size:18}),s.jsx("span",{className:"viewer-toolbar__btn-text",children:"返回"})]})}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx("div",{className:"viewer-toolbar__title",children:"编辑图片"})]}),I=()=>s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"单图模式",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__btn",onClick:()=>c("single"),"aria-label":"单图模式",children:[s.jsx(cn,{size:18}),s.jsx("span",{className:"viewer-toolbar__btn-text",children:"单图"})]})}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsxs("div",{className:"viewer-toolbar__group",children:[s.jsx("span",{className:"viewer-toolbar__label",children:"分屏"}),[2,3,4].map(C=>s.jsx(it.Fragment,{children:s.jsx(ke,{content:`${C}分屏`,placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn viewer-toolbar__btn--small ${r===C?"viewer-toolbar__btn--active":""}`,onClick:()=>l(C),"aria-label":`${C}分屏`,children:C})})},C))]}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsxs("div",{className:"viewer-toolbar__group",children:[s.jsx(ke,{content:"水平布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="horizontal"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("horizontal"),"aria-label":"水平布局",children:s.jsx(vs,{size:18})})}),s.jsx(ke,{content:"垂直布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="vertical"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("vertical"),"aria-label":"垂直布局",children:s.jsx(Xo,{size:18})})}),s.jsx(ke,{content:"网格布局",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${i==="grid"?"viewer-toolbar__btn--active":""}`,onClick:()=>N("grid"),"aria-label":"网格布局",children:s.jsx(Jo,{size:18})})})]}),s.jsx("div",{className:"viewer-toolbar__divider"}),s.jsx(ke,{content:o?"取消联动(快捷键 S)":"联动缩放/拖拽(快捷键 S)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:`viewer-toolbar__btn ${o?"viewer-toolbar__btn--active":""}`,onClick:u,"aria-label":o?"取消联动":"联动缩放/拖拽",children:o?s.jsx(Qo,{size:18}):s.jsx(ei,{size:18})})}),o&&s.jsx(ke,{content:"重置视图",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:d,children:s.jsx(Kt,{size:18})})})]}),v=()=>{switch(t){case"edit":return T();case"compare":return I();default:return O()}},S=()=>t==="edit"?s.jsxs(s.Fragment,{children:[s.jsx(ke,{content:"重置",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:x,children:s.jsx(Kt,{size:18})})}),s.jsx(ke,{content:"保存",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--primary",onClick:z,"aria-label":"保存",children:s.jsx(gn,{size:18})})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]}):s.jsxs(s.Fragment,{children:[h&&s.jsx(ke,{content:"全屏",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn",onClick:h,children:s.jsx(_r,{size:18})})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__btn viewer-toolbar__btn--close",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]});return t==="edit"?s.jsxs("div",{className:"viewer-toolbar viewer-toolbar--edit-simplified",children:[s.jsx(ke,{content:"返回预览",placement:"bottom",contentClassName:"viewer-popover",children:s.jsxs("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--left",onClick:f,"aria-label":"返回预览",children:[s.jsx(cn,{size:20}),s.jsx("span",{children:"返回"})]})}),s.jsx(ke,{content:"关闭(Esc)",placement:"bottom",contentClassName:"viewer-popover",children:s.jsx("button",{className:"viewer-toolbar__corner-btn viewer-toolbar__corner-btn--right",onClick:p,"aria-label":"关闭",children:s.jsx(Mt,{size:20})})})]}):s.jsxs("div",{className:"viewer-toolbar",children:[s.jsx("div",{className:"viewer-toolbar__left",children:v()}),s.jsx("div",{className:"viewer-toolbar__right",children:S()})]})},_t={brightness:100,contrast:100,saturate:100,blur:0,grayscale:0,sepia:0,hueRotate:0,invert:0},Pc=[{label:"自由",value:null},{label:"1:1",value:1},{label:"4:3",value:4/3},{label:"3:4",value:3/4},{label:"16:9",value:16/9},{label:"9:16",value:9/16},{label:"3:2",value:3/2},{label:"2:3",value:2/3}],Os=[{label:"原图",type:"none",filter:"none"},{label:"黑白",type:"grayscale",filter:"grayscale(100%)"},{label:"怀旧",type:"sepia",filter:"sepia(80%)"},{label:"复古",type:"vintage",filter:"sepia(40%) contrast(110%) brightness(90%)"},{label:"冷色",type:"cold",filter:"saturate(80%) hue-rotate(180deg) brightness(105%)"},{label:"暖色",type:"warm",filter:"saturate(120%) sepia(20%) brightness(105%)"},{label:"高对比",type:"contrast",filter:"contrast(150%)"},{label:"高饱和",type:"saturate",filter:"saturate(180%)"},{label:"反转",type:"invert",filter:"invert(100%)"}],Ac=({aspectRatio:t,presets:e,onAspectRatioChange:n,rotation:r,flipH:i,flipV:o,onRotate:c,onFlipH:l,onFlipV:m,onConfirmCrop:u,hasCropArea:d=!1,onAutoTrimWhitespace:p,isDetectingWhitespace:h=!1})=>s.jsxs("div",{className:"crop-panel",children:[p&&s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"智能裁剪"}),s.jsxs("button",{type:"button",className:`crop-panel__auto-trim-btn ${h?"loading":""}`,onClick:p,disabled:h,children:[s.jsx(ti,{size:16}),s.jsx("span",{children:h?"检测中...":"智能去白边"})]}),s.jsx("div",{className:"crop-panel__auto-trim-hint",children:"自动检测并移除图片周围的白色边框"})]}),s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"裁剪比例"}),s.jsx("div",{className:"crop-panel__ratio-grid",children:e.map(g=>s.jsx("button",{type:"button",className:`crop-panel__ratio-btn ${t===g.value?"active":""}`,onClick:()=>n(g.value),children:g.label},g.label))})]}),s.jsxs("div",{className:"crop-panel__section",children:[s.jsx("div",{className:"crop-panel__section-title",children:"旋转和翻转"}),s.jsxs("div",{className:"crop-panel__transform-row",children:[s.jsx(je,{content:"向左旋转 90°",placement:"top",children:s.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>c(-90),children:s.jsx(Kt,{size:18})})}),s.jsx(je,{content:"向右旋转 90°",placement:"top",children:s.jsx("button",{type:"button",className:"crop-panel__transform-btn",onClick:()=>c(90),children:s.jsx(pr,{size:18})})}),s.jsx(je,{content:"水平翻转",placement:"top",children:s.jsx("button",{type:"button",className:`crop-panel__transform-btn ${i?"active":""}`,onClick:l,children:s.jsx(hr,{size:18})})}),s.jsx(je,{content:"垂直翻转",placement:"top",children:s.jsx("button",{type:"button",className:`crop-panel__transform-btn ${o?"active":""}`,onClick:m,children:s.jsx(fr,{size:18})})})]}),r!==0&&s.jsxs("div",{className:"crop-panel__rotation-info",children:["当前旋转: ",r,"°"]})]}),u&&s.jsxs("div",{className:"crop-panel__section",children:[s.jsxs("button",{type:"button",className:`crop-panel__confirm-btn ${d?"":"disabled"}`,onClick:u,disabled:!d,children:[s.jsx(gn,{size:16}),s.jsx("span",{children:"应用裁剪"})]}),s.jsx("div",{className:"crop-panel__confirm-hint",children:"按 Enter 键快速确认"})]}),s.jsxs("div",{className:"crop-panel__tips",children:[s.jsx("p",{children:"拖动裁剪框调整位置"}),s.jsx("p",{children:"拖动边角调整大小"})]})]}),Rc=({filterType:t,filterParams:e,presets:n,imageUrl:r,onPresetSelect:i,onParamChange:o})=>s.jsxs("div",{className:"filter-panel",children:[s.jsxs("div",{className:"filter-panel__section",children:[s.jsx("div",{className:"filter-panel__section-title",children:"滤镜预设"}),s.jsx("div",{className:"filter-panel__preset-grid",children:n.map(c=>s.jsxs("button",{type:"button",className:`filter-panel__preset-btn ${t===c.type?"active":""}`,onClick:()=>i(c.type),children:[s.jsx("div",{className:"filter-panel__preset-preview",style:{backgroundImage:`url(${r})`,filter:c.filter}}),s.jsx("span",{className:"filter-panel__preset-label",children:c.label})]},c.type))})]}),s.jsxs("div",{className:"filter-panel__section",children:[s.jsx("div",{className:"filter-panel__section-title",children:"参数调节"}),s.jsxs("div",{className:"filter-panel__sliders",children:[s.jsx(vt,{label:"亮度",value:e.brightness,min:0,max:200,defaultValue:100,onChange:c=>o("brightness",c)}),s.jsx(vt,{label:"对比度",value:e.contrast,min:0,max:200,defaultValue:100,onChange:c=>o("contrast",c)}),s.jsx(vt,{label:"饱和度",value:e.saturate,min:0,max:200,defaultValue:100,onChange:c=>o("saturate",c)}),s.jsx(vt,{label:"灰度",value:e.grayscale,min:0,max:100,defaultValue:0,onChange:c=>o("grayscale",c)}),s.jsx(vt,{label:"复古",value:e.sepia,min:0,max:100,defaultValue:0,onChange:c=>o("sepia",c)}),s.jsx(vt,{label:"色相",value:e.hueRotate,min:0,max:360,defaultValue:0,onChange:c=>o("hueRotate",c)}),s.jsx(vt,{label:"模糊",value:e.blur,min:0,max:10,defaultValue:0,step:.5,onChange:c=>o("blur",c)})]})]})]}),vt=({label:t,value:e,min:n,max:r,defaultValue:i,step:o=1,onChange:c})=>{const l=e===i;return s.jsxs("div",{className:"filter-slider",children:[s.jsxs("div",{className:"filter-slider__header",children:[s.jsx("span",{className:"filter-slider__label",children:t}),s.jsx("span",{className:`filter-slider__value ${l?"":"modified"}`,children:e})]}),s.jsx(ni,{value:e,min:n,max:r,step:o,onChange:m=>c(m)})]})},pt=10010;function zc(t,e={}){const{threshold:n=250,tolerance:r=.02,minContentSize:i=50}=e,o=t.naturalWidth,c=t.naturalHeight,l=document.createElement("canvas");l.width=o,l.height=c;const m=l.getContext("2d");if(!m)return null;m.drawImage(t,0,0);const d=m.getImageData(0,0,o,c).data,p=v=>{const S=d[v],C=d[v+1],R=d[v+2];return d[v+3]<10?!0:S>=n&&C>=n&&R>=n},h=v=>{let S=0;for(let C=0;C<o;C++){const R=(v*o+C)*4;p(R)&&S++}return S/o>=1-r},g=v=>{let S=0;for(let C=0;C<c;C++){const R=(C*o+v)*4;p(R)&&S++}return S/c>=1-r};let y=0;for(;y<c&&h(y);)y++;let f=c-1;for(;f>y&&h(f);)f--;let x=0;for(;x<o&&g(x);)x++;let z=o-1;for(;z>x&&g(z);)z--;const N=z-x+1,O=f-y+1,T=y>0||x>0||z<o-1||f<c-1,I=N>=i&&O>=i;return!T||!I?null:{x,y,width:N,height:O}}const no=a.forwardRef(({imageUrl:t,showOverwrite:e=!1,onOverwrite:n,onInsert:r,onClose:i,onSave:o,className:c},l)=>{const[m,u]=a.useState("crop"),[d,p]=a.useState(null),[h,g]=a.useState(null),[y,f]=a.useState("none"),[x,z]=a.useState(_t),[N,O]=a.useState(0),[T,I]=a.useState(!1),[v,S]=a.useState(!1),[C,R]=a.useState({width:0,height:0}),[U,P]=a.useState(1),[J,ee]=a.useState(1),X=.1,Q=5,B=.1,[_,E]=a.useState({x:0,y:0}),[M,$]=a.useState(!1),[re,fe]=a.useState({x:0,y:0}),[K,de]=a.useState(!1),[ie,ue]=a.useState(null),[xe,pe]=a.useState(!1),[ae,q]=a.useState(null),[ce,be]=a.useState(!1),[me,Re]=a.useState([]),[Me,We]=a.useState(-1),Ee=a.useRef(!1),Te=a.useRef(null),Ye=a.useRef(null),$e=a.useRef(null);a.useEffect(()=>{$e.current!==null&&$e.current!==t&&(p(null),q(null),g(null),f("none"),z(_t),O(0),I(!1),S(!1),ee(1),P(1),R({width:0,height:0}),E({x:0,y:0}),u("crop"),Re([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:_t,rotation:0,flipH:!1,flipV:!1}]),We(0)),$e.current=t},[t]),a.useEffect(()=>{if(!t)return;const j=new Image;return j.crossOrigin="anonymous",j.onload=()=>{Te.current=j,R({width:j.naturalWidth,height:j.naturalHeight})},j.onerror=()=>{Ke.error("图片加载失败")},j.src=t,()=>{Te.current=null}},[t]),a.useEffect(()=>{t&&me.length===0&&(Re([{cropArea:null,confirmedCropArea:null,aspectRatio:null,filterType:"none",filterParams:_t,rotation:0,flipH:!1,flipV:!1}]),We(0))},[t,me.length]),a.useEffect(()=>{if(!Ye.current||C.width===0)return;const j=()=>{const we=Ye.current;if(!we)return;const Oe=we.clientWidth-80,Ze=we.clientHeight-80;if(Oe<=0||Ze<=0)return;const A=Oe/C.width,ge=Ze/C.height,Le=Math.min(A,ge,1);Le>0&&isFinite(Le)&&P(Le)};requestAnimationFrame(j);const ne=new ResizeObserver(j);return ne.observe(Ye.current),()=>ne.disconnect()},[C]);const ve=a.useRef(null);a.useEffect(()=>{if(!(Ee.current||me.length===0))return ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{He()},300),()=>{ve.current&&clearTimeout(ve.current)}},[N,T,v,y,x,h,ae]);const Ie=a.useCallback(()=>{if(y!=="none"){const ne=Os.find(we=>we.type===y);if(ne)return ne.filter}const j=[];return x.brightness!==100&&j.push(`brightness(${x.brightness}%)`),x.contrast!==100&&j.push(`contrast(${x.contrast}%)`),x.saturate!==100&&j.push(`saturate(${x.saturate}%)`),x.blur>0&&j.push(`blur(${x.blur}px)`),x.grayscale>0&&j.push(`grayscale(${x.grayscale}%)`),x.sepia>0&&j.push(`sepia(${x.sepia}%)`),x.hueRotate!==0&&j.push(`hue-rotate(${x.hueRotate}deg)`),x.invert>0&&j.push(`invert(${x.invert}%)`),j.length>0?j.join(" "):"none"},[y,x]),he=a.useCallback(()=>{const j=[];return N!==0&&j.push(`rotate(${N}deg)`),T&&j.push("scaleX(-1)"),v&&j.push("scaleY(-1)"),j.length>0?j.join(" "):"none"},[N,T,v]),ze=a.useCallback(()=>({cropArea:d,confirmedCropArea:ae,aspectRatio:h,filterType:y,filterParams:x,rotation:N,flipH:T,flipV:v}),[d,ae,h,y,x,N,T,v]),De=a.useCallback(j=>{Ee.current=!0,p(j.cropArea),q(j.confirmedCropArea),g(j.aspectRatio),f(j.filterType),z(j.filterParams),O(j.rotation),I(j.flipH),S(j.flipV),requestAnimationFrame(()=>{Ee.current=!1})},[]),He=a.useCallback(()=>{if(Ee.current)return;const j=ze();Re(ne=>{const we=ne.slice(0,Me+1);return we.push(j),we.length>50&&we.shift(),we}),We(ne=>Math.min(ne+1,49))},[ze,Me]),Be=a.useCallback(()=>{if(Me<=0)return;const j=Me-1;We(j),De(me[j])},[Me,me,De]),Ge=a.useCallback(()=>{if(Me>=me.length-1)return;const j=Me+1;We(j),De(me[j])},[Me,me,De]),Qe=Me>0,Ne=Me<me.length-1,L=a.useCallback(()=>ae!==null||d!==null||N!==0||T||v||y!=="none"||Object.keys(x).some(j=>x[j]!==_t[j]),[ae,d,N,T,v,y,x]),w=a.useCallback(()=>{p(null),q(null),g(null),f("none"),z(_t),O(0),I(!1),S(!1),ee(1),E({x:0,y:0}),Re([]),We(-1)},[]),V=a.useCallback(async()=>{const j=Te.current;if(!j){Ke.error("图片未加载");return}const ne=Ke.loading("正在处理图片...",0);try{const we=document.createElement("canvas"),Oe=we.getContext("2d");if(!Oe)throw new Error("无法创建 Canvas 上下文");let Ze=j.naturalWidth,A=j.naturalHeight,ge=0,Le=0,tt=j.naturalWidth,Xe=j.naturalHeight;const Je=ae||d;Je&&(ge=Je.x,Le=Je.y,tt=Je.width,Xe=Je.height,Ze=Je.width,A=Je.height);const rt=(N%360+360)%360;(rt===90||rt===270)&&([Ze,A]=[A,Ze]),we.width=Ze,we.height=A,Oe.save(),Oe.translate(Ze/2,A/2),N!==0&&Oe.rotate(N*Math.PI/180),T&&Oe.scale(-1,1),v&&Oe.scale(1,-1);let mt=tt,ct=Xe;(rt===90||rt===270)&&([mt,ct]=[ct,mt]);const ys=Ie();ys!=="none"&&(Oe.filter=ys),Oe.drawImage(j,ge,Le,tt,Xe,-mt/2,-ct/2,mt,ct),Oe.restore();const xs=we.toDataURL("image/png");if(Ke.close(ne),o){o(xs);return}ue(xs),de(!0)}catch(we){Ke.close(ne),Ke.error(we instanceof Error?we.message:"图片处理失败")}},[ae,d,N,T,v,Ie,o]),b=a.useCallback(j=>{if(ie){switch(j){case"overwrite":n==null||n(ie);break;case"insert":r==null||r(ie);break;case"download":{const ne=document.createElement("a");ne.href=ie,ne.download=`edited-image-${Date.now()}.png`,ne.click(),Ke.success("图片已下载");break}}de(!1),ue(null),i==null||i()}},[ie,n,r,i]),D=a.useCallback(j=>{g(j),p(null),q(null)},[]),W=a.useCallback(j=>{f(j),j!=="none"&&z(_t)},[]),G=a.useCallback((j,ne)=>{z(we=>({...we,[j]:ne})),f("none")},[]),Y=a.useCallback(j=>{O(ne=>ne+j)},[]),le=a.useCallback(()=>{I(j=>!j)},[]),_e=a.useCallback(()=>{S(j=>!j)},[]),k=a.useCallback(()=>{!d||!Te.current||(q({...d}),u("filter"))},[d]),H=a.useCallback(()=>{const j=Te.current;if(!j){Ke.warning("图片未加载完成");return}be(!0),requestAnimationFrame(()=>{try{const ne=zc(j);ne?(g(null),p(ne),Ke.success("已检测到白边,裁剪框已自动调整")):Ke.info("未检测到明显的白边")}catch{Ke.error("检测白边失败")}finally{be(!1)}})},[]);a.useEffect(()=>{const j=ne=>{ne.target instanceof HTMLInputElement||ne.target instanceof HTMLTextAreaElement||(ne.key==="Enter"&&m==="crop"&&d&&(ne.preventDefault(),k()),(ne.ctrlKey||ne.metaKey)&&ne.key==="z"&&!ne.shiftKey&&(ne.preventDefault(),Be()),(ne.ctrlKey||ne.metaKey)&&(ne.key==="y"||ne.key==="z"&&ne.shiftKey)&&(ne.preventDefault(),Ge()))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[m,d,k,Be,Ge]);const F=a.useCallback(()=>{ee(j=>Math.min(j+B,Q))},[]),Z=a.useCallback(()=>{ee(j=>Math.max(j-B,X))},[]),oe=a.useCallback(()=>{ee(1),E({x:0,y:0})},[]),te=a.useCallback(j=>{j.preventDefault();const ne=Math.abs(j.deltaY);let we;ne>50?we=j.deltaY>0?-.15:.15:we=-j.deltaY*.008,ee(Oe=>Math.max(X,Math.min(Q,Oe+we)))},[]);a.useEffect(()=>{const j=Ye.current;if(j)return j.addEventListener("wheel",te,{passive:!1}),()=>j.removeEventListener("wheel",te)},[te]);const Pe=a.useCallback(j=>{j==="crop"&&ae&&!d&&p({...ae}),u(j)},[ae,d]),Ce=a.useCallback(j=>{m!=="crop"&&($(!0),fe({x:j.clientX-_.x,y:j.clientY-_.y}))},[m,_]),Ae=a.useCallback(j=>{M&&E({x:j.clientX-re.x,y:j.clientY-re.y})},[M,re]),qe=a.useCallback(()=>{$(!1)},[]);a.useEffect(()=>{if(!M)return;const j=we=>{E({x:we.clientX-re.x,y:we.clientY-re.y})},ne=()=>{$(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",ne),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",ne)}},[M,re]),a.useEffect(()=>{ee(1),E({x:0,y:0})},[m]),a.useImperativeHandle(l,()=>({reset:w,save:V,hasChanges:L,getState:ze,setState:De}));const et=Ie(),Ve=he();return s.jsxs("div",{className:`image-editor-core ${c||""}`,children:[s.jsxs("div",{className:"image-editor-core__header",children:[s.jsx("div",{className:"image-editor-core__title",children:"编辑图片"}),s.jsxs("div",{className:"image-editor-core__actions",children:[s.jsx(je,{content:"撤销 (Ctrl+Z)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${Qe?"":"disabled"}`,onClick:Be,disabled:!Qe,children:s.jsx(si,{size:18})})}),s.jsx(je,{content:"重做 (Ctrl+Y)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${Ne?"":"disabled"}`,onClick:Ge,disabled:!Ne,children:s.jsx(ri,{size:18})})}),s.jsx("div",{className:"image-editor-core__divider"}),s.jsx(je,{content:"对比原图(按住查看)",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:`image-editor-core__btn ${xe?"active":""}`,onMouseDown:()=>pe(!0),onMouseUp:()=>pe(!1),onMouseLeave:()=>pe(!1),children:s.jsx(oi,{size:18})})}),s.jsx(je,{content:"重置",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:w,children:s.jsx(Kt,{size:18})})}),i&&s.jsx(je,{content:"取消",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn",onClick:i,children:s.jsx(Mt,{size:18})})}),(o||n||r)&&s.jsx(je,{content:"保存",theme:"light",placement:"bottom",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__btn image-editor-core__btn--primary",onClick:V,children:s.jsx(gn,{size:18})})})]})]}),s.jsxs("div",{className:"image-editor-core__main",children:[s.jsxs("div",{className:"image-editor-core__sidebar",children:[s.jsxs("div",{className:"image-editor-core__mode-tabs",children:[s.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${m==="crop"?"active":""}`,onClick:()=>Pe("crop"),children:[s.jsx(ii,{size:16}),s.jsx("span",{children:"裁剪"})]}),s.jsxs("button",{type:"button",className:`image-editor-core__mode-tab ${m==="filter"?"active":""}`,onClick:()=>Pe("filter"),children:[s.jsx(ai,{size:16}),s.jsx("span",{children:"滤镜"})]})]}),s.jsx("div",{className:"image-editor-core__panel",children:m==="crop"?s.jsx(Ac,{aspectRatio:h,presets:Pc,onAspectRatioChange:D,rotation:N,flipH:T,flipV:v,onRotate:Y,onFlipH:le,onFlipV:_e,onConfirmCrop:k,hasCropArea:!!d,onAutoTrimWhitespace:H,isDetectingWhitespace:ce}):s.jsx(Rc,{filterType:y,filterParams:x,presets:Os,imageUrl:t,onPresetSelect:W,onParamChange:G})})]}),s.jsxs("div",{className:"image-editor-core__preview",ref:Ye,onMouseDown:Ce,onMouseMove:Ae,onMouseUp:qe,onMouseLeave:qe,style:{cursor:M?"grabbing":"grab"},children:[s.jsx("div",{className:"image-editor-core__canvas-wrapper",style:{transform:`translate(${_.x}px, ${_.y}px)`},children:xe?ae?(()=>{const j=ae.y/C.height*100,ne=(C.width-ae.x-ae.width)/C.width*100,we=(C.height-ae.y-ae.height)/C.height*100,Oe=ae.x/C.width*100;return s.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ve} scale(${U*J})`.trim(),clipPath:`inset(${j}% ${ne}% ${we}% ${Oe}%)`},children:s.jsx("img",{src:t,alt:"Original",draggable:!1})})})():s.jsx("div",{className:"image-editor-core__filter-preview",style:{transform:`${Ve} scale(${U*J})`.trim()},children:s.jsx("img",{src:t,alt:"Original",draggable:!1})}):m==="crop"?s.jsx(Dc,{imageUrl:t,imageSize:C,cropArea:d,aspectRatio:h,rotation:N,displayScale:U,flipH:T,flipV:v,zoom:J,filterCSS:et,onCropChange:p},t):ae?(()=>{const j=ae.y/C.height*100,ne=(C.width-ae.x-ae.width)/C.width*100,we=(C.height-ae.y-ae.height)/C.height*100,Oe=ae.x/C.width*100;return s.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:et,transform:`${Ve} scale(${U*J})`.trim(),clipPath:`inset(${j}% ${ne}% ${we}% ${Oe}%)`},children:s.jsx("img",{src:t,alt:"Preview",draggable:!1})})})():s.jsx("div",{className:"image-editor-core__filter-preview",style:{filter:et,transform:`${Ve} scale(${U*J})`.trim()},children:s.jsx("img",{src:t,alt:"Preview",draggable:!1})})}),s.jsxs("div",{className:"image-editor-core__zoom-controls",children:[s.jsx(je,{content:"缩小",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:Z,disabled:J<=X,children:s.jsx(ur,{size:16})})}),s.jsxs("span",{className:"image-editor-core__zoom-value",children:[Math.round(J*100),"%"]}),s.jsx(je,{content:"放大",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:F,disabled:J>=Q,children:s.jsx(mr,{size:16})})}),s.jsx(je,{content:"重置视图",theme:"light",placement:"top",zIndex:pt,children:s.jsx("button",{type:"button",className:"image-editor-core__zoom-btn",onClick:oe,children:s.jsx(_r,{size:16})})})]})]})]}),K&&ie&&s.jsxs("div",{className:"image-editor-core__save-dialog",children:[s.jsx("div",{className:"image-editor-core__save-dialog-backdrop",onClick:()=>de(!1)}),s.jsxs("div",{className:"image-editor-core__save-dialog-content",children:[s.jsx("h3",{className:"image-editor-core__save-dialog-title",children:"保存图片"}),s.jsxs("div",{className:"image-editor-core__save-options",children:[e&&n&&s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>b("overwrite"),children:[s.jsx(ci,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"覆盖原图"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"替换画布中的原图片"})]})]}),r&&s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>b("insert"),children:[s.jsx(li,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"插入新图片"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"在画布中插入编辑后的图片"})]})]}),s.jsxs("button",{type:"button",className:"image-editor-core__save-option",onClick:()=>b("download"),children:[s.jsx(wr,{size:20}),s.jsxs("div",{className:"image-editor-core__save-option-content",children:[s.jsx("span",{className:"image-editor-core__save-option-label",children:"下载到本地"}),s.jsx("span",{className:"image-editor-core__save-option-desc",children:"保存编辑后的图片到本地"})]})]})]}),s.jsx("button",{type:"button",className:"image-editor-core__save-cancel",onClick:()=>de(!1),children:"取消"})]})]})]})});no.displayName="ImageEditorCore";const Dc=({imageUrl:t,imageSize:e,cropArea:n,aspectRatio:r,rotation:i,flipH:o,flipV:c,zoom:l,displayScale:m,filterCSS:u,onCropChange:d})=>{const p=a.useRef(null),[h,g]=a.useState(!1),[y,f]=a.useState(null),[x,z]=a.useState(null),[N,O]=a.useState({x:0,y:0}),[T,I]=a.useState(null);a.useEffect(()=>{if(!n&&e.width>0){let P;if(r)if(e.width/e.height>r){const ee=e.height,X=ee*r;P={x:(e.width-X)/2,y:0,width:X,height:ee}}else{const ee=e.width,X=ee/r;P={x:0,y:(e.height-X)/2,width:ee,height:X}}else P={x:0,y:0,width:e.width,height:e.height};d(P)}},[r,e,n,d]);const v=a.useCallback((P,J,ee)=>{P.preventDefault(),P.stopPropagation(),g(!0),f(J),z(ee||null),O({x:P.clientX,y:P.clientY}),I(n)},[n]);a.useEffect(()=>{if(!h||!T)return;const P=ee=>{let X=(ee.clientX-N.x)/(m*l),Q=(ee.clientY-N.y)/(m*l);const B=(i%360+360)%360;let _,E;switch(B){case 90:_=Q,E=-X;break;case 180:_=-X,E=-Q;break;case 270:_=-Q,E=X;break;default:_=X,E=Q}o&&(_=-_),c&&(E=-E);const M={...T};if(y==="move")M.x=Math.max(0,Math.min(T.x+_,e.width-T.width)),M.y=Math.max(0,Math.min(T.y+E,e.height-T.height));else if(y==="resize"&&x){switch(x){case"nw":M.x=Math.min(T.x+_,T.x+T.width-20),M.y=Math.min(T.y+E,T.y+T.height-20),M.width=Math.max(20,T.width-_),M.height=Math.max(20,T.height-E);break;case"ne":M.y=Math.min(T.y+E,T.y+T.height-20),M.width=Math.max(20,T.width+_),M.height=Math.max(20,T.height-E);break;case"sw":M.x=Math.min(T.x+_,T.x+T.width-20),M.width=Math.max(20,T.width-_),M.height=Math.max(20,T.height+E);break;case"se":M.width=Math.max(20,T.width+_),M.height=Math.max(20,T.height+E);break;case"n":M.y=Math.min(T.y+E,T.y+T.height-20),M.height=Math.max(20,T.height-E);break;case"s":M.height=Math.max(20,T.height+E);break;case"w":M.x=Math.min(T.x+_,T.x+T.width-20),M.width=Math.max(20,T.width-_);break;case"e":M.width=Math.max(20,T.width+_);break}if(r&&(["e","w","ne","nw","se","sw"].includes(x)?M.height=M.width/r:["n","s"].includes(x)&&(M.width=M.height*r)),M.x<0&&(M.width+=M.x,M.x=0),M.y<0&&(M.height+=M.y,M.y=0),M.width=Math.min(M.width,e.width-M.x),M.height=Math.min(M.height,e.height-M.y),M.width=Math.max(20,M.width),M.height=Math.max(20,M.height),r){const re=M.height*r,fe=M.width/r;M.width>re?M.width=re:M.height>fe&&(M.height=fe)}}d(M)},J=()=>{g(!1),f(null),z(null)};return document.addEventListener("mousemove",P),document.addEventListener("mouseup",J),()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",J)}},[h,y,x,N,T,m,l,i,o,c,e,r,d]);const S=e.width*m*l,C=e.height*m*l,R={transform:`rotate(${i}deg) ${o?"scaleX(-1)":""} ${c?"scaleY(-1)":""}`.trim()},U=P=>{const J={nw:"nw-resize",ne:"ne-resize",sw:"sw-resize",se:"se-resize",n:"n-resize",s:"s-resize",w:"w-resize",e:"e-resize"},ee={nw:"ne",ne:"se",se:"sw",sw:"nw",n:"e",e:"s",s:"w",w:"n"};let X=P;const Q=(i%360+360)%360,B=Math.round(Q/90)%4;for(let _=0;_<B;_++)X=ee[X]||X;return o&&(X.includes("w")?X=X.replace("w","e"):X.includes("e")&&(X=X.replace("e","w"))),c&&(X.includes("n")?X=X.replace("n","s"):X.includes("s")&&(X=X.replace("s","n"))),J[X]||"pointer"};return s.jsx("div",{ref:p,className:"crop-canvas",children:s.jsxs("div",{className:"crop-canvas__image-container",style:{width:S,height:C,...R},children:[s.jsx("img",{src:t,alt:"Crop",draggable:!1,style:{filter:u||"none"}}),n&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"crop-canvas__overlay"}),s.jsxs("div",{className:"crop-canvas__crop-area",style:{left:n.x*m*l,top:n.y*m*l,width:n.width*m*l,height:n.height*m*l},onMouseDown:P=>v(P,"move"),children:[s.jsx("div",{className:"crop-canvas__crop-image",style:{backgroundImage:`url(${t})`,backgroundPosition:`-${n.x*m*l}px -${n.y*m*l}px`,backgroundSize:`${S}px ${C}px`,filter:u||"none"}}),s.jsxs("div",{className:"crop-canvas__grid",children:[s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h1"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--h2"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v1"}),s.jsx("div",{className:"crop-canvas__grid-line crop-canvas__grid-line--v2"})]}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--nw",style:{cursor:U("nw")},onMouseDown:P=>v(P,"resize","nw")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--ne",style:{cursor:U("ne")},onMouseDown:P=>v(P,"resize","ne")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--sw",style:{cursor:U("sw")},onMouseDown:P=>v(P,"resize","sw")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--se",style:{cursor:U("se")},onMouseDown:P=>v(P,"resize","se")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--n",style:{cursor:U("n")},onMouseDown:P=>v(P,"resize","n")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--s",style:{cursor:U("s")},onMouseDown:P=>v(P,"resize","s")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--w",style:{cursor:U("w")},onMouseDown:P=>v(P,"resize","w")}),s.jsx("div",{className:"crop-canvas__handle crop-canvas__handle--e",style:{cursor:U("e")},onMouseDown:P=>v(P,"resize","e")})]})]})]})})},so=a.forwardRef(({imageUrl:t,showOverwrite:e=!1,onOverwrite:n,onInsert:r},i)=>s.jsx(no,{ref:i,imageUrl:t,showOverwrite:e,onOverwrite:n,onInsert:r,className:"embedded-editor"}));so.displayName="ImageEditorContent";const mn=({visible:t,items:e,initialMode:n="single",initialIndex:r=0,onClose:i,onModeChange:o,showThumbnails:c=!0,maxCompareSlots:l=4,defaultCompareLayout:m="horizontal",className:u="",showTitle:d=!0,videoAutoPlay:p=!1,videoLoop:h=!0,onInsertToCanvas:g,onEdit:y,useBuiltInEditor:f=!1,onEditOverwrite:x,onEditInsert:z,showEditOverwrite:N=!1})=>{const O=a.useRef(null),T=a.useRef(null),[I,v]=a.useState(2),[S,C]=a.useState(!1),[R,U]=a.useState(null),P=a.useRef(null),J=a.useRef(new Map),ee=a.useRef([]),X=a.useRef(null),Q=a.useRef(!1),[B,_]=ac({items:e,initialMode:n,initialIndex:r,maxCompareSlots:l,defaultCompareLayout:m,visible:t,onModeChange:o}),{mode:E,currentIndex:M,compareIndices:$,compareLayout:re,syncMode:fe,zoomLevel:K,panOffset:de,focusedSlot:ie}=B,ue=a.useCallback(b=>{P.current=b,U(b)},[]);a.useEffect(()=>{t||(J.current.clear(),ue(null))},[t,ue]);const xe=a.useCallback(()=>{if(e.length<=I)return;const D=Math.max(...$)+1;if(D>=e.length){const W=[];for(let G=0;G<I&&G<e.length;G++)W.push(G);W.forEach((G,Y)=>_.addToCompare(G,Y))}else{const W=[];for(let G=0;G<I;G++){const Y=(D+G)%e.length;W.push(Y)}W.forEach((G,Y)=>_.addToCompare(G,Y))}},[e.length,I,$,_]),pe=a.useCallback(()=>{if(e.length<=I)return;const D=Math.min(...$)-I;if(D<0){const W=Math.max(0,e.length-I),G=[];for(let Y=0;Y<I&&W+Y<e.length;Y++)G.push(W+Y);G.forEach((Y,le)=>_.addToCompare(Y,le))}else{const W=[];for(let G=0;G<I;G++)W.push(D+G);W.forEach((G,Y)=>_.addToCompare(G,Y))}},[e.length,I,$,_]),ae=a.useCallback(b=>{const D=e[b];if(!D||D.type!=="image")return!1;const W=P.current;if(W&&T.current){const G=T.current.getState();J.current.set(W.url,G)}return _.goTo(b),ue(D),setTimeout(()=>{const G=J.current.get(D.url);G&&T.current&&T.current.setState(G)},50),!0},[e,_,ue]),q=a.useCallback(()=>{_.resetView(),ee.current.forEach(b=>{b!=null&&b.isVideo()&&b.resetVideo()})},[_]);a.useEffect(()=>{if(!t)return;const b=D=>{const W=D.target instanceof HTMLElement?D.target:null;if(W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement||W instanceof HTMLSelectElement||W instanceof HTMLButtonElement||W!=null&&W.isContentEditable)return;const G=E==="single"?X.current:ee.current[ie]||null;switch(D.key){case"Escape":D.preventDefault(),i();break;case"ArrowLeft":case"ArrowUp":if(D.preventDefault(),E==="edit"){const Y=(M-1+e.length)%e.length;ae(Y)}else E==="single"?_.goToPrev():pe();break;case"ArrowRight":case"ArrowDown":if(D.preventDefault(),E==="edit"){const Y=(M+1)%e.length;ae(Y)}else E==="single"?_.goToNext():xe();break;case"c":case"C":e.length>1&&(D.preventDefault(),_.setMode(E==="single"?"compare":"single"));break;case"1":case"2":case"3":case"4":if(E==="compare"){const Y=parseInt(D.key,10)-1;Y<I&&(D.preventDefault(),_.setFocusedSlot(Y))}break;case"+":case"=":D.preventDefault(),_.zoom(.25);break;case"-":case"_":D.preventDefault(),_.zoom(-.25);break;case"0":D.preventDefault(),E==="compare"?q():_.resetView();break;case" ":case"Spacebar":G!=null&&G.isVideo()&&(D.preventDefault(),G.toggleVideoPlayback());break;case"s":case"S":E==="compare"&&(D.preventDefault(),_.toggleSyncMode());break}};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[t,E,e.length,e,M,ie,_,i,I,xe,pe,ae,q]);const ce=a.useCallback(()=>{if(O.current)if(S){const b=ui();b==null||b.catch(()=>{})}else{const b=di(O.current);b==null||b.catch(()=>{})}},[S]);a.useEffect(()=>{const b=()=>{C(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",b),()=>document.removeEventListener("fullscreenchange",b)},[]);const be=a.useCallback(b=>{b.target===b.currentTarget&&i()},[i]),me=a.useCallback(b=>{E==="edit"?ae(b):E==="single"?_.goTo(b):_.addToCompare(b,ie)},[E,_,ie,ae]),Re=a.useCallback(b=>{v(b),_.setSlotCount(b)},[_]),Me=a.useCallback((b,D)=>b==="grid"?D<=2?"layout-horizontal":"layout-grid":`layout-${b}`,[]),We=a.useCallback(()=>{const b=e[M];b&&g&&g(b)},[e,M,g]),Ee=a.useCallback(async()=>{const b=e[M];if(!b)return;const D=b.type==="image"?ut(b.url):b.url;if(D.startsWith("blob:")){const{unifiedCacheService:Y}=await dt(async()=>{const{unifiedCacheService:H}=await import("./startup-app-M6vjXkRC.js").then(F=>F.nR);return{unifiedCacheService:H}},__vite__mapDeps([0]),import.meta.url),{downloadFromBlob:le}=await dt(async()=>{const{downloadFromBlob:H}=await import("./startup-app-M6vjXkRC.js").then(F=>F.nP);return{downloadFromBlob:H}},__vite__mapDeps([0]),import.meta.url),_e=D.indexOf("#"),k=_e>0?D.substring(_e+1):null;if(k&&k.startsWith("merged-video-")){const H=await Y.getCachedBlob(k);if(H){const F=H.type||"video/webm",Z=F.startsWith("video/mp4")?"mp4":F.startsWith("video/webm")?"webm":"bin";le(H,`merged-video-${Date.now()}.${Z}`);return}}try{const F=await(await fetch(D)).blob(),Z=F.type.startsWith("video/mp4")?"mp4":F.type.startsWith("video/webm")?"webm":F.type.startsWith("audio/mpeg")?"mp3":F.type.startsWith("audio/wav")?"wav":F.type.startsWith("audio/")?"m4a":F.type.startsWith("image/")?"png":"bin";le(F,`${b.type}_${Date.now()}.${Z}`)}catch(H){console.error("[UnifiedMediaViewer] Failed to fetch blob URL:",H)}return}const{smartDownload:W,buildDownloadFilename:G}=await dt(async()=>{const{smartDownload:Y,buildDownloadFilename:le}=await import("./startup-app-M6vjXkRC.js").then(_e=>_e.o1);return{smartDownload:Y,buildDownloadFilename:le}},__vite__mapDeps([0]),import.meta.url);await W([{url:D,type:b.type,filename:b.type==="audio"?G(b.title,"audio","mp3"):void 0,audioMetadata:b.type==="audio"?{title:b.title,prompt:b.prompt,tags:b.tags,coverUrl:b.posterUrl,artist:b.artist,album:b.album}:void 0}])},[e,M]),Te=a.useCallback(()=>{const b=e[M];b&&b.type==="image"&&(f?(ue(b),_.setMode("edit")):y&&y(b))},[e,M,y,f,_,ue]),Ye=a.useCallback(b=>{if(b==="edit"){const D=e[M];D&&D.type==="image"&&ue(D)}_.setMode(b)},[e,M,_,ue]),$e=a.useCallback(()=>{J.current.clear(),ue(null),_.setMode("single")},[_,ue]),ve=a.useCallback(()=>{var b;(b=T.current)==null||b.reset()},[]),Ie=a.useCallback(()=>{var b;(b=T.current)==null||b.save()},[]),he=a.useCallback(b=>{const D=P.current;x&&D&&x(b,D),$e()},[x,$e]),ze=a.useCallback(b=>{z&&z(b),$e()},[z,$e]),De=a.useCallback((b,D)=>{ee.current[b]=D},[]),He=a.useCallback((b,D)=>{Q.current||(Q.current=!0,ee.current.forEach((W,G)=>{G!==b&&(W!=null&&W.isVideo())&&(D?W.playVideo():W.pauseVideo())}),setTimeout(()=>{Q.current=!1},50))},[]),Be=a.useCallback((b,D)=>{Q.current||(Q.current=!0,ee.current.forEach((W,G)=>{G!==b&&(W!=null&&W.isVideo())&&W.setVideoTime(D)}),setTimeout(()=>{Q.current=!1},50))},[]),Ge=()=>{const b=e[M]||null;return s.jsxs("div",{className:"unified-viewer__single",children:[e.length>1&&s.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--prev",onClick:_.goToPrev,"aria-label":"上一个",children:s.jsx(cn,{size:32})}),s.jsx(On,{ref:X,item:b,zoomLevel:K,panOffset:de,videoAutoPlay:p,videoLoop:h,onZoomChange:_.setZoomLevel,onPanChange:()=>{},onInsertToCanvas:g?We:void 0,onDownload:Ee,onEdit:y?Te:void 0}),e.length>1&&s.jsx("button",{className:"unified-viewer__nav unified-viewer__nav--next",onClick:_.goToNext,"aria-label":"下一个",children:s.jsx(mi,{size:32})})]})},Qe=()=>{const b=Me(re,I);return s.jsx("div",{className:`unified-viewer__compare ${b}`,children:Array.from({length:I}).map((D,W)=>{const G=$[W],Y=typeof G=="number"?e[G]:null;return s.jsx(On,{ref:le=>De(W,le),item:Y,slotIndex:W,isFocused:ie===W,zoomLevel:fe?K:void 0,panOffset:fe?de:void 0,onClick:()=>_.setFocusedSlot(W),onClose:I>2?()=>_.removeFromCompare(W):void 0,videoAutoPlay:p,videoLoop:h,onZoomChange:fe?_.setZoomLevel:void 0,onPanChange:fe?_.setPan:void 0,isCompareMode:!0,isSyncMode:fe,onVideoPlayStateChange:fe?le=>He(W,le):void 0,onVideoTimeUpdate:fe?le=>Be(W,le):void 0},W)})})},Ne=()=>{const b=R||e[M];return!b||b.type!=="image"?null:s.jsx("div",{className:"unified-viewer__edit",children:s.jsx(so,{ref:T,imageUrl:b.url,showOverwrite:N,onOverwrite:x?he:void 0,onInsert:z?ze:void 0})})},L=e[M]||null;if(!t||e.length===0)return null;const w=()=>{switch(E){case"edit":return Ne();case"compare":return Qe();default:return Ge()}},V=s.jsx("div",{ref:O,className:`unified-viewer ${u} ${S?"unified-viewer--fullscreen":""} ${E==="edit"?"unified-viewer--edit-mode":""}`,onClick:be,children:s.jsxs("div",{className:"unified-viewer__container",children:[s.jsx(Ec,{mode:E,currentIndex:M,totalCount:e.length,slotCount:I,compareLayout:re,syncMode:fe,onModeChange:Ye,onSlotCountChange:Re,onLayoutChange:_.setCompareLayout,onSyncToggle:_.toggleSyncMode,onResetView:E==="compare"?q:_.resetView,onClose:i,onFullscreen:ce,isImage:(L==null?void 0:L.type)==="image",showEditButton:f||!!y,onBackToPreview:$e,onResetEdit:ve,onSaveEdit:Ie}),s.jsx("div",{className:"unified-viewer__content",children:w()}),c&&e.length>1&&s.jsx(Nc,{items:e,mode:E==="edit"?"single":E,currentIndex:M,compareIndices:$,onThumbnailClick:me})]})});return Rt.createPortal(V,document.body)},am=Object.freeze(Object.defineProperty({__proto__:null,UnifiedMediaViewer:mn,default:mn},Symbol.toStringTag,{value:"Module"})),Lc=qn.DIALOG_AI_IMAGE;class Et{constructor(){this.windows=new Map,this.counter=0}static getInstance(){return Et.instance||(Et.instance=new Et),Et.instance}register(e,n){const r=this.windows.get(e);r?(r.element=n,r.activationOrder=++this.counter):this.windows.set(e,{windowId:e,activationOrder:++this.counter,element:n}),this.applyAllZIndexes()}unregister(e){this.windows.delete(e)&&this.applyAllZIndexes()}bringToFront(e){const n=this.windows.get(e);n&&(this.isTopWindow(e)||(n.activationOrder=++this.counter,this.applyAllZIndexes()))}updateElement(e,n){const r=this.windows.get(e);r&&(r.element=n,this.applyZIndex(r,this.getPositionIndex(e)))}getTopWindowId(){let e=null,n=-1;return this.windows.forEach(r=>{r.activationOrder>n&&(n=r.activationOrder,e=r.windowId)}),e}isTopWindow(e){return this.getTopWindowId()===e}getPositionIndex(e){return this.getSortedEntries().findIndex(r=>r.windowId===e)}getSortedEntries(){return Array.from(this.windows.values()).sort((e,n)=>e.activationOrder-n.activationOrder)}applyAllZIndexes(){this.getSortedEntries().forEach((n,r)=>{this.applyZIndex(n,r)})}applyZIndex(e,n){!e.element||n<0||e.element.style.setProperty("--aitu-winbox-z-index",String(Lc+n))}}const bt=Et.getInstance();let nt=null,nn=null;const $c=async()=>nt||(typeof window<"u"&&window.WinBox?(nt=window.WinBox,nt):nn||(nn=(async()=>{try{if(await dt(()=>import("./winbox.bundle.min-CoRPjCs5.js"),[],import.meta.url),nt=window.WinBox,nt)return nt;throw new Error("WinBox not found after import")}catch(t){return console.warn("Dynamic import failed, falling back to CDN:",t),new Promise((e,n)=>{const r=document.createElement("script");r.src="https://cdn.jsdelivr.net/npm/winbox@0.2.82/dist/winbox.bundle.min.js",r.async=!0,r.onload=()=>{nt=window.WinBox,nt?e(nt):n(new Error("WinBox not found after CDN loading"))},r.onerror=n,document.head.appendChild(r)})}})(),nn)),Oc=({visible:t,title:e,icon:n,onClose:r,children:i,width:o="80%",height:c="80%",minWidth:l=400,minHeight:m=300,x:u="center",y:d="center",maximizable:p=!0,minimizable:h=!0,resizable:g=!0,movable:y=!0,modal:f=!1,background:x="linear-gradient(135deg, #5A4FCF 0%, #7B68EE 50%, #E91E63 100%)",border:z=0,className:N,id:O,headerContent:T,container:I,onMaximize:v,onMinimize:S,onRestore:C,onFocus:R,onBlur:U,onMove:P,onResize:J,autoMaximize:ee=!1,minVisiblePixels:X=50,onInsertToCanvas:Q,keepAlive:B=!1,minimizeTargetSelector:_,onActivate:E})=>{var _e;const M=a.useRef(O||`winbox-${vr()}`),$=a.useRef(null),re=a.useRef(null),fe=a.useRef(r),K=a.useRef(E),de=a.useRef(!0),ie=a.useRef(!1),ue=a.useRef(null),xe=a.useRef([]);fe.current=r,K.current=E;const pe=a.useRef(null),ae=a.useRef(!1),[q,ce]=a.useState(null),[be,me]=a.useState(null),[Re,Me]=a.useState(null),[We,Ee]=a.useState(!1),[Te,Ye]=a.useState(!!nt),[$e,ve]=a.useState(null),Ie=a.useRef(null),he=a.useRef(null),ze=a.useCallback(()=>{xe.current.forEach(k=>{window.clearTimeout(k)}),xe.current=[]},[]),De=a.useCallback((k,H)=>{const F=window.setTimeout(()=>{xe.current=xe.current.filter(Z=>Z!==F),k()},H);return xe.current.push(F),F},[]),He=a.useCallback(()=>{de.current&&(ce(null),me(null),Me(null),Ee(!1))},[]),Be=a.useCallback((k,H=!0)=>{if(k){ze(),H&&(k.onclose=null);try{k.close(!0)}catch{}}},[ze]),Ge=a.useCallback(()=>{const k=ue.current;k&&(ue.current=null,Be(k))},[Be]),Qe=a.useCallback(k=>{if(k){ze(),ue.current=k;try{k.hide()}catch{}De(()=>{ie.current=!1,Ge()},800)}},[ze,Ge,De]),Ne=a.useCallback(k=>{ve(k),Ie.current=k,k===null&&he.current!==null&&$.current&&($.current.minwidth=he.current,he.current=null)},[]),L=a.useCallback(()=>{const k={left:!1,right:!1};if(typeof window>"u"||!window.WinBox)return k;const F=window.WinBox.stack(),Z=window.innerWidth;return F.forEach(oe=>{if(oe===$.current)return;Math.abs(oe.width-Z/2)<20&&(oe.x<20&&(k.left=!0),Math.abs(oe.x+oe.width-Z)<20&&(k.right=!0))}),k},[]),w=a.useCallback(k=>{if(!k||!k.window)return;const H=window.innerWidth,F=window.innerHeight;he.current!==null&&(k.minwidth=he.current,he.current=null),k.left=0,k.right=0,k.top=0,k.bottom=0;let Z,oe;typeof o=="string"&&o.endsWith("%")?Z=Math.floor(H*parseInt(o)/100):Z=typeof o=="number"?o:Math.floor(H*.8),typeof c=="string"&&c.endsWith("%")?oe=Math.floor(F*parseInt(c)/100):oe=typeof c=="number"?c:Math.floor(F*.8),Z=Math.max(Z,l),oe=Math.max(oe,m);const te=Math.floor((H-Z)/2),Pe=Math.floor((F-oe)/2);k.resize(Z,oe).move(te,Pe),Ne(null)},[o,c,l,m,Ne]),V=a.useCallback((k,H,F,Z,oe)=>{!k||!k.window||(k.left=0,k.right=0,k.top=0,k.bottom=0,H==="left"?(k.resize(F,oe).move(0,0),Ne("left")):(k.resize(F,oe).move(Z-F,0),Ne("right")))},[Ne]),b=a.useCallback(()=>{const k=$.current,H=Ie.current;if(!k||!k.window)return;const F=window.innerWidth,Z=window.innerHeight,oe=L(),te=Math.floor(F/2),Pe=Ae=>{he.current===null&&(he.current=k.minwidth),k.minwidth=Math.min(200,te),k.max?(k.restore(),requestAnimationFrame(()=>{!k||!k.window||V(k,Ae,te,F,Z)})):V(k,Ae,te,F,Z)},Ce=()=>{k.max?(k.restore(),requestAnimationFrame(()=>{!k||!k.window||w(k)})):w(k)};if(H==="left"){Ce();return}if(H==="right"){oe.left?Ce():Pe("left");return}oe.right&&!oe.left?Pe("left"):Pe("right")},[L,w,V]),D=pi(re,{enablePositionTracking:!1,enableScaleCompensation:!$e&&!((_e=$.current)!=null&&_e.max)});a.useEffect(()=>{Te||$c().then(()=>Ye(!0))},[Te]),a.useEffect(()=>(de.current=!0,()=>{de.current=!1}),[]);const W=a.useRef(!1),G=a.useCallback(()=>{var k;return bt.unregister(M.current),(k=fe.current)==null||k.call(fe),!1},[]),Y=a.useCallback(()=>{var k;bt.bringToFront(M.current),(k=K.current)==null||k.call(K)},[]);a.useEffect(()=>{if(!(!Te||!nt)){if(!t){if($.current)if(bt.unregister(M.current),ze(),B)try{$.current.hide()}catch{}else{const k=$.current;ie.current?Qe(k):Be(k),$.current=null,re.current=null,He()}return}if(t&&$.current){$.current.show(),$.current.focus(),bt.register(M.current,$.current.window);return}if(t&&!$.current){Ge();const k=["winbox-react"];p||k.push("no-max"),h||k.push("no-min"),g||k.push("no-resize"),y||k.push("no-move"),k.push("no-full"),N&&k.push(N);const H=new nt({id:O,title:e,width:o,height:c,minwidth:l,minheight:m,x:u,y:d,modal:f,background:x,border:z,overflow:!0,class:k,root:I||document.body,onclose:G,onmaximize:v,onminimize:function(){ae.current=!0;const F=pe.current,Z=F?{x:F.x,y:F.y}:{x:this.x||0,y:this.y||0},oe=F?{width:F.width,height:F.height}:{width:this.width||800,height:this.height||600},te=this.window;if(_&&te){const Pe=document.querySelector(_);if(Pe){te.style.transition="none",te.style.transform="",te.style.opacity="1",F&&(te.style.left=`${F.x}px`,te.style.top=`${F.y}px`,te.style.width=`${F.width}px`,te.style.height=`${F.height}px`),te.offsetHeight;const Ce=te.getBoundingClientRect(),Ae=Pe.getBoundingClientRect(),qe=Ae.left+Ae.width/2,et=Ae.top+Ae.height/2,Ve=Ce.left,j=Ce.top+Ce.height/2,ne=qe-Ve,we=et-j,Oe=Math.min(Ae.width/Ce.width,Ae.height/Ce.height,.06);te.style.transformOrigin="left center";const Ze=te.parentElement;Ze&&(Ze.style.perspective="1000px",Ze.style.perspectiveOrigin="left center"),te.offsetHeight;const A=400;return te.style.transition=`transform ${A}ms cubic-bezier(0.4, 0, 0.2, 1), opacity ${A}ms ease-out`,te.style.transform=`translate(${ne}px, ${we}px) scale(${Oe}) rotateY(-30deg)`,te.style.opacity="0",De(()=>{te.isConnected&&(te.style.transition="none",te.style.transform="",te.style.opacity="",Ze&&(Ze.style.perspective="",Ze.style.perspectiveOrigin=""),this.hide(),S==null||S(Z,oe))},A),!0}}return this.hide(),S==null||S(Z,oe),!0},onrestore:C,onfocus:function(){R==null||R(),Y()},onblur:U,onmove:function(F,Z){if(this.max||this.min||W.current)return;const oe=window.innerWidth,te=window.innerHeight,Pe=this.width;this.height;const Ce=X;if(Ie.current){const j=Ie.current==="left"?0:oe-Pe;Math.abs(F-j)>50&&Ne(null)}let Ae=F,qe=Z;F<Ce-Pe&&(Ae=Ce-Pe),F>oe-Ce&&(Ae=oe-Ce),Z<0&&(qe=0),Z>te-Ce&&(qe=te-Ce),(Ae!==F||qe!==Z)&&(W.current=!0,this.move(Ae,qe),W.current=!1);const et=pe.current,Ve=et&&qe-et.y>200;!this.min&&!this.max&&!ae.current&&!Ve&&(pe.current={x:Ae,y:qe,width:this.width,height:this.height}),P==null||P(Ae,qe)},onresize:function(F,Z){const oe=pe.current,te=oe&&(Z<100||oe.height-Z>200);!this.min&&!this.max&&!ae.current&&!te&&(pe.current={x:this.x,y:this.y,width:F,height:Z}),J==null||J(F,Z)}});if($.current=H,H.addControl({index:0,class:"wb-split",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiIHJ5PSIyIj48L3JlY3Q+PGxpbmUgeDE9IjEyIiB5MT0iMyIgeDI9IjEyIiB5Mj0iMjEiPjwvbGluZT48L3N2Zz4=",click:F=>{F.preventDefault(),F.stopPropagation(),b()}}),Q&&H.addControl({index:0,class:"wb-insert-canvas",image:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjMiIHk9IjMiIHdpZHRoPSIxOCIgaGVpZ2h0PSIxOCIgcng9IjIiLz48cGF0aCBkPSJNMTIgOHY4Ii8+PHBhdGggZD0iTTggMTJoOCIvPjwvc3ZnPg==",click:F=>{F.preventDefault(),F.stopPropagation();const Z=H.window;if(Z){const oe=Z.getBoundingClientRect(),te={x:oe.left,y:oe.top,width:oe.width,height:oe.height};Q(te)}else{const oe={x:H.x||0,y:H.y||0,width:H.width||800,height:H.height||600};Q(oe)}}}),H.window){re.current=H.window,bt.register(M.current,re.current),requestAnimationFrame(()=>{D()});const F=H.window.querySelector(".wb-body");if(F&&me(F),n){const Z=H.window.querySelector(".wb-drag"),oe=H.window.querySelector(".wb-title");if(Z&&oe){const te=document.createElement("div");te.className="wb-icon-container",Z.insertBefore(te,oe),Me(te)}}}if(T&&H.window){const F=H.window.querySelector(".wb-drag");if(F){const Z=document.createElement("div");Z.className="wb-header-custom";const oe=te=>{te.stopPropagation()};Z.addEventListener("mousedown",oe,!0),Z.addEventListener("touchstart",oe,!0),Z.addEventListener("pointerdown",oe,!0),F.appendChild(Z),ce(Z)}}H&&!H.min&&!H.max&&(pe.current={x:H.x,y:H.y,width:H.width,height:H.height}),Ee(!0),ee&&De(()=>{$.current&&$.current.maximize()},100)}}},[t,Te,ee,B,ze,Be,Qe,Ge,He,De]),a.useEffect(()=>{const k=M.current;return()=>{if(bt.unregister(k),$.current){const H=$.current;ie.current?Qe(H):Be(H),$.current=null,re.current=null}ue.current||ze()}},[ze,Be,Qe]),a.useEffect(()=>{$.current&&e&&$.current.setTitle(e)},[e]),a.useEffect(()=>{var k,H;if($.current&&n&&!Re){const F=$.current,Z=(k=F.window)==null?void 0:k.querySelector(".wb-drag"),oe=(H=F.window)==null?void 0:H.querySelector(".wb-title");if(Z&&oe&&!Z.querySelector(".wb-icon-container")){const Pe=document.createElement("div");Pe.className="wb-icon-container",Z.insertBefore(Pe,oe),Me(Pe)}}},[n,Re]),a.useEffect(()=>{if($.current){const k=pe.current;if(t){const H=$.current.min||$.current.hidden;$.current.min&&($.current.restore(),k&&($.current.move(k.x,k.y),$.current.resize(k.width,k.height)),ae.current=!1),$.current.show(),$.current.focus(),bt.bringToFront(M.current),H&&_&&requestAnimationFrame(()=>{le()})}else $.current.hide()}},[t]);const le=a.useCallback(()=>{if(!_||!$.current)return;const k=$.current.window,H=document.querySelector(_);if(!k||!H)return;const F=pe.current;if(!F)return;const Z=H.getBoundingClientRect(),oe=Z.left+Z.width/2,te=Z.top+Z.height/2,Pe=F.x,Ce=F.y+F.height/2,Ae=oe-Pe,qe=te-Ce,et=Math.min(Z.width/F.width,Z.height/F.height,.06),Ve=k.parentElement;Ve&&(Ve.style.perspective="1000px",Ve.style.perspectiveOrigin="left center"),k.style.transition="none",k.style.transformOrigin="left center",k.style.transform=`translate(${Ae}px, ${qe}px) scale(${et}) rotateY(-30deg)`,k.style.opacity="0",k.offsetHeight;const j=350;k.style.transition=`transform ${j}ms cubic-bezier(0.2, 0, 0.4, 1), opacity ${j*.6}ms ease-out`,k.style.transform="",k.style.opacity="1",De(()=>{k.isConnected&&(k.style.transition="none",k.style.transform="",k.style.transformOrigin="",Ve&&(Ve.style.perspective="",Ve.style.perspectiveOrigin=""))},j)},[_,De]);return a.useEffect(()=>{const k=re.current;if(!k)return;const H=[".wb-drag",".wb-n",".wb-s",".wb-e",".wb-w",".wb-ne",".wb-nw",".wb-se",".wb-sw"].join(", "),F=oe=>{const te=oe.target;te instanceof Element&&te.closest(H)&&(ie.current=!0)},Z=()=>{!ie.current&&!ue.current||(ie.current=!1,Ge())};return k.addEventListener("mousedown",F,!0),k.addEventListener("touchstart",F,!0),window.addEventListener("mouseup",Z,!0),window.addEventListener("touchend",Z,!0),window.addEventListener("touchcancel",Z,!0),window.addEventListener("blur",Z),()=>{k.removeEventListener("mousedown",F,!0),k.removeEventListener("touchstart",F,!0),window.removeEventListener("mouseup",Z,!0),window.removeEventListener("touchend",Z,!0),window.removeEventListener("touchcancel",Z,!0),window.removeEventListener("blur",Z)}},[We,Ge]),a.useEffect(()=>{$.current&&ee&&$.current.maximize()},[ee]),a.useEffect(()=>{const k=re.current;if(!k)return;const H=()=>{Y()},F=()=>{Y()};return k.addEventListener("pointerdown",H,!0),k.addEventListener("focusin",F,!0),()=>{k.removeEventListener("pointerdown",H,!0),k.removeEventListener("focusin",F,!0)}},[We,Y]),a.useEffect(()=>{if(!$.current||!t||Ie.current)return;const k=typeof o=="number"?o:$.current.width,H=typeof c=="number"?c:$.current.height;typeof k!="number"||typeof H!="number"||$.current.width===k&&$.current.height===H&&$.current.minwidth===l&&$.current.minheight===m||($.current.minwidth=l,$.current.minheight=m,$.current.resize(k,H))},[c,m,l,t,o]),s.jsxs(s.Fragment,{children:[We&&n&&Re&&Rt.createPortal(s.jsx("span",{className:"wb-icon-content",children:n}),Re),We&&be&&Rt.createPortal(s.jsx("div",{className:"winbox-content-wrapper",children:i}),be),We&&T&&q&&Rt.createPortal(T,q)]})},Fc={image:"prompt-list-item__tag--image",video:"prompt-list-item__tag--video",audio:"prompt-list-item__tag--audio",text:"prompt-list-item__tag--text",agent:"prompt-list-item__tag--agent","ppt-common":"prompt-list-item__tag--ppt-common","ppt-slide":"prompt-list-item__tag--ppt-slide"},Uc=({content:t,title:e,sentPrompt:n,tags:r,resultPreview:i,pinned:o=!1,isPreset:c=!1,modelType:l,scene:m,previewExamples:u,onClick:d,onTogglePin:p,onDelete:h,onPreviewExample:g,language:y="zh",disabled:f=!1})=>{const x=B=>{B.stopPropagation(),p==null||p()},z=B=>{B.stopPropagation(),h==null||h()},N=(u==null?void 0:u.slice(0,3))??[],O=N.length>0,T=(e==null?void 0:e.trim())||t,I=(r||[]).filter(Boolean).slice(0,4),v=!!(n||i||I.length>0)&&!O,S=N.length===1,C=!!(g&&!f),R=B=>_=>{_.preventDefault(),_.stopPropagation(),C&&(g==null||g({content:t,previewExamples:N,initialIndex:B}))},U=B=>{B.preventDefault(),B.stopPropagation()},P=B=>_=>{_.key!=="Enter"&&_.key!==" "||(_.preventDefault(),_.stopPropagation(),C&&(g==null||g({content:t,previewExamples:N,initialIndex:B})))},J=s.jsxs("div",{className:`prompt-list-item ${o?"prompt-list-item--pinned":""} ${c?"prompt-list-item--preset":""} ${f?"prompt-list-item--disabled":""}`,onClick:f?void 0:d,children:[o&&s.jsx("div",{className:"prompt-list-item__pin-badge",children:s.jsx(bs,{size:10})}),c&&s.jsx("div",{className:"prompt-list-item__preset-badge",children:s.jsx(hi,{size:10})}),m&&s.jsx("span",{className:`prompt-list-item__tag ${l&&Fc[l]||""}`,children:m}),s.jsx("span",{className:"prompt-list-item__text",children:T}),s.jsxs("div",{className:"prompt-list-item__actions",children:[p&&s.jsx(je,{content:o?y==="zh"?"取消置顶":"Unpin":y==="zh"?"置顶":"Pin",children:s.jsx("button",{type:"button",className:"prompt-list-item__action",onClick:x,children:o?s.jsx(fi,{size:14}):s.jsx(bs,{size:14})})}),h&&s.jsx(je,{content:y==="zh"?"删除":"Delete",children:s.jsx("button",{type:"button",className:"prompt-list-item__action prompt-list-item__action--delete",onClick:z,children:s.jsx(Mt,{size:14})})})]})]}),ee=O?s.jsxs("div",{className:"prompt-list-item__hover-card",children:[s.jsx("div",{className:"prompt-list-item__hover-text",children:t}),s.jsx("div",{className:`prompt-list-item__hover-gallery ${S?"prompt-list-item__hover-gallery--single":""}`,children:N.map((B,_)=>s.jsx("div",{className:`prompt-list-item__hover-thumb ${S?"prompt-list-item__hover-thumb--single":""}`,children:C?s.jsx("button",{type:"button",className:"prompt-list-item__hover-thumb-button","aria-label":`${y==="zh"?"预览示例图":"Preview example"} ${_+1}`,onMouseDown:R(_),onClick:U,onKeyDown:P(_),children:s.jsx(Tt,{src:B.kind==="video"&&B.posterSrc||B.src,alt:B.alt,showSkeleton:!1})}):s.jsx(Tt,{src:B.kind==="video"&&B.posterSrc||B.src,alt:B.alt,showSkeleton:!1})},`${B.src}-${B.alt}`))}),C&&s.jsx("div",{className:"prompt-list-item__hover-hint",children:y==="zh"?"点击预览":"Click to preview"})]}):null,X=i?s.jsxs("div",{className:"prompt-list-item__result-preview",children:[(i.kind==="image"||i.kind==="video")&&s.jsx("div",{className:"prompt-list-item__result-media",children:s.jsx(Tt,{src:i.kind==="video"&&i.posterUrl||i.url,alt:i.title||T,showSkeleton:!1})}),i.kind==="audio"&&s.jsxs("div",{className:"prompt-list-item__result-audio",children:[i.coverUrl&&s.jsx(Tt,{src:i.coverUrl,alt:i.title||T,showSkeleton:!1}),s.jsxs("div",{children:[s.jsx("div",{className:"prompt-list-item__result-title",children:i.title||"音频结果"}),i.text&&s.jsx("div",{className:"prompt-list-item__result-text",children:i.text})]})]}),(i.kind==="text"||i.kind==="error"||i.kind==="none")&&s.jsxs("div",{className:`prompt-list-item__result-text ${i.kind==="error"?"prompt-list-item__result-text--error":""}`,children:[i.kind==="text"&&i.title&&s.jsx("strong",{children:i.title}),i.text]})]}):null,Q=v?s.jsxs("div",{className:"prompt-list-item__history-card",children:[s.jsx("div",{className:"prompt-list-item__history-title",children:T}),n&&s.jsxs("div",{className:"prompt-list-item__history-section",children:[s.jsx("div",{className:"prompt-list-item__history-label",children:"发送提示词"}),s.jsx("div",{className:"prompt-list-item__history-text",children:n})]}),I.length>0&&s.jsx("div",{className:"prompt-list-item__history-tags",children:I.map(B=>s.jsx("span",{children:B},B))}),X&&s.jsxs("div",{className:"prompt-list-item__history-section",children:[s.jsx("div",{className:"prompt-list-item__history-label",children:"结果预览"}),X]})]}):null;return ee?s.jsx(je,{content:ee,placement:"right",delay:40,overlayClassName:"prompt-list-item__hover-card-popover",children:J}):Q?s.jsx(je,{content:Q,placement:"right",delay:60,overlayClassName:"prompt-list-item__history-card-popover",children:J}):s.jsx(je,{content:T===t?t:`${T}
3
+
4
+ ${t}`,placement:"right-top",delay:80,overlayClassName:"prompt-list-item__text-tip-popover",overlayInnerClassName:"prompt-list-item__text-tip",children:J})},ro="drawnix-runtime-model-discovery";function sn(t){return{profileId:t,status:"idle",sourceBaseUrl:"",signature:"",discoveredAt:null,discoveredModels:[],selectedModelIds:[],models:[],error:null}}function Wc(t){let e=5381;for(let n=0;n<t.length;n+=1)e=(e<<5)+e^t.charCodeAt(n);return Math.abs(e>>>0).toString(16)}function oo(t){const e=(t||"").trim(),n="https://api.tu-zi.com/v1";if(!e)return n;let r=e.replace(/\/+$/,"");return r=r.replace(/\/models$/i,""),/\/v1$/i.test(r)||(r=`${vi(r)}/v1`),r}function Fs(t,e){return`${oo(t)}::${Wc(e.trim())}`}function Hc(t,e){var r,i;const n=t.trim();if(!n)return e;try{const o=JSON.parse(n),c=typeof o.error=="string"?o.error:((r=o.error)==null?void 0:r.message)||((i=o.error)==null?void 0:i.details);return o.message||c||o.detail||e}catch{return n.replace(/\s+/g," ").slice(0,120)||e}}function Vc(t,e){return typeof e=="string"?t.includes(e):e.test(t)}function Ut(t,e){return e.some(n=>Vc(t,n))}function Bc(t,e){return t.some(n=>Ut(n,e))}function io(t){const e=t.toLowerCase(),n=/(^|[^a-z0-9])(o1|o3|o4|o4-mini|gpt-4o|gpt-4\.1|chatgpt)([^a-z0-9]|$)/;return e.includes("flux")?se.FLUX:e.startsWith("mj")||e.includes("midjourney")?se.MIDJOURNEY:e.includes("grok")||e.includes("xai")||e.includes("supergrok")?se.GROK:e.includes("qwen")||e.includes("qwq")||e.includes("qvq")||e.includes("wanx")?se.QWEN:e.includes("glm")||e.includes("zhipu")||e.includes("bigmodel")||e.includes("cogview")||e.includes("cogvideo")?se.GLM:e.includes("minimax")||e.includes("abab")||e.includes("hailuo")||e.includes("speech-02")||e.includes("music-01")?se.MINIMAX:e.includes("mistral")||e.includes("mixtral")||e.includes("pixtral")||e.includes("ministral")||e.includes("codestral")?se.MISTRAL:e.includes("runway")||e.includes("runwayml")||/^gen[-_]?3/.test(e)||/^gen[-_]?4/.test(e)?se.RUNWAY:e.includes("pika")?se.PIKA:e.includes("llama")||e.includes("meta-llama")||e.includes("llama3")||e.includes("llama-3")||e.includes("llama-4")?se.LLAMA:e.includes("hunyuan")||e.includes("hunyuan-video")||e.includes("hunyuanimage")||e.includes("hunyuan-image")?se.HUNYUAN:e.includes("stepfun")||e.includes("jieyue")||/^step[-_]?1/.test(e)||e.startsWith("step-")?se.STEPFUN:e.includes("claude")||e.includes("sonnet")||e.includes("haiku")||e.includes("opus")?se.ANTHROPIC:e.includes("deepseek")?se.DEEPSEEK:e.includes("kling")?se.KLING:e.includes("happyhorse")?se.HAPPYHORSE:e.includes("veo")?se.VEO:e.includes("sora")?se.SORA:e.includes("suno")||e.includes("chirp")?se.SUNO:e.includes("seedream")||e.includes("seedance")||e.includes("doubao")||e.includes("jimeng")?se.DOUBAO:e.includes("gpt")||e.includes("openai")||e.includes("dall-e")||e.includes("whisper")||e.includes("codex")||e.includes("text-embedding")||e.includes("omni")||e.includes("tts-")||e.includes("babbage")||e.includes("davinci")||e.includes("computer-use")||n.test(e)?se.GPT:e.includes("gemini")||e.includes("banana")||e.includes("gemma")||e.includes("imagen")||e.includes("learnlm")?se.GEMINI:e.includes("google")?se.GOOGLE:se.OTHER}function ao(t){const e=(t.owned_by||"").trim().toLowerCase(),n=io(t.id);return e==="openai"||e.includes("openai")?se.GPT:e==="xai"||e.includes("x.ai")||e.includes("grok")?se.GROK:e==="qwen"||e.includes("alibaba")||e.includes("dashscope")||e.includes("tongyi")?se.QWEN:e==="zhipu"||e.includes("zhipu")||e.includes("bigmodel")||e.includes("glm")?se.GLM:e==="minimax"||e.includes("minimax")||e.includes("abab")||e.includes("hailuo")?se.MINIMAX:e==="mistral"||e.includes("mistral")?se.MISTRAL:e==="runway"||e.includes("runway")||e.includes("runwayml")?se.RUNWAY:e==="pika"||e.includes("pika")?se.PIKA:e==="meta"||e.includes("meta")||e.includes("llama")?se.LLAMA:e==="hunyuan"||e.includes("hunyuan")||e.includes("tencent")?se.HUNYUAN:e==="stepfun"||e.includes("stepfun")||e.includes("jieyue")?se.STEPFUN:e==="deepseek"||e.includes("deepseek")?se.DEEPSEEK:e==="anthropic"||e==="claude"||e.includes("anthropic")||e.includes("claude")?se.ANTHROPIC:e==="volcengine"||e==="doubao-video"||e==="doubao"||e.includes("volc")||e.includes("doubao")?se.DOUBAO:e==="suno"||e.includes("suno")||e.includes("chirp")?se.SUNO:e==="happyhorse"||e.includes("happyhorse")?se.HAPPYHORSE:e==="google"||e.includes("google")?n!==se.OTHER?n:se.GOOGLE:e==="vertex-ai"||e.includes("vertex")||e.includes("gemini")?n!==se.OTHER?n:se.GOOGLE:n}function Gc(t){const e=(t.supported_endpoint_types||[]).map(h=>h.toLowerCase()).filter(Boolean),n=t.id.toLowerCase(),r=ao(t),i=(...h)=>Ut(n,[/(^|[^a-z0-9])t2v([^a-z0-9]|$)/,/(^|[^a-z0-9])i2v([^a-z0-9]|$)/,"video",...h]),o=(...h)=>Ut(n,[/(^|[^a-z0-9])t2i([^a-z0-9]|$)/,/(^|[^a-z0-9])i2i([^a-z0-9]|$)/,"image",...h]),c=(...h)=>Ut(n,["audio","music","suno","chirp","lyrics","midi","stems",...h]),l=(...h)=>Ut(n,h),m=(...h)=>Bc(e,h);if(m("audio","music","audio_generation","music-generation","lyrics","stems","midi"))return"audio";if(m("video","videos","video_generation","video-generation","videos.generate","video/generations","text-to-video","image-to-video","t2v","i2v","video-edit","video_edit"))return"video";if(m("image","images","image_generation","image-generation","images.generate","image/generations","image-edit","image_edit","images.edit","text-to-image","image-to-image","t2i","i2i"))return"image";switch(r){case se.FLUX:case se.MIDJOURNEY:return"image";case se.SORA:case se.VEO:case se.HAPPYHORSE:return"video";case se.RUNWAY:return o("frame","keyframe","reference-image","image-to-video")?"image":"video";case se.PIKA:return o("pikadditions","pikaswaps","pikascenes","reference-image")?"image":"video";case se.KLING:return o("kling_image","kling-image","img","picture","photo","poster","design")?"image":(i("kling_video","kling-video","motion","animate"),"video");case se.GLM:if(l("cogvideo"))return"video";if(l("cogview"))return"image";break;case se.MINIMAX:if(l("hailuo",/(^|[^a-z0-9])video[-_]?0\d/,"video-01","video-02","minimax-video","abab-video"))return"video";if(l("image-01","image-02","minimax-image","abab-image","visual-generation"))return"image";break;case se.DOUBAO:if(l("seedance"))return"video";if(l("seedream","jimeng"))return"image";break;case se.HUNYUAN:if(i("hunyuan-video","tencent-video","video-generation"))return"video";if(o("hunyuan-image","hunyuanimage","vision"))return"image";break;case se.QWEN:if(l("wanx",/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/)&&i("wan-video","wanx-video","animate","motion"))return"video";if(l("wanx",/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/)&&o("wanx-image","wan-image","poster","illustration")||l("wanx"))return"image";if(l(/(^|[^a-z0-9])wan([0-9.-]|$)/,/(^|[^a-z0-9])wan2([^a-z0-9]|$)/))return"video";break;case se.GEMINI:case se.GOOGLE:if(l("veo"))return"video";if(l("imagen","gpt-image"))return"image";break;case se.SUNO:return"audio";case se.OTHER:if(c())return"audio";break}return l("sora-2")||n.includes("veo")||n.includes("sora")||n.includes("runway")||n.includes("gen-3")||n.includes("gen3")||n.includes("gen-4")||n.includes("gen4")||n.includes("pika")||n.includes("kling")||n.includes("hunyuan-video")||n.includes("cogvideo")||n.includes("seedance")||n.includes("t2v")||n.includes("i2v")||n.includes("video")?"video":m("banana")||n.includes("image")||n.includes("banana")||n.includes("flux")||n.startsWith("mj")||n.includes("midjourney")||n.includes("cogview")||n.includes("hunyuan-image")||n.includes("hunyuanimage")||n.includes("seedream")||n.includes("jimeng")||n.includes("imagen")||n.includes("gpt-image")?"image":n.includes("suno")||n.includes("chirp")||n.includes("music")||n.includes("lyrics")||n.includes("midi")||n.includes("stems")||n.includes("remix")||n.includes("infill")?"audio":"text"}function Fn(t,e){const n=t.split(/[^a-zA-Z0-9]+/).filter(Boolean).slice(0,4).map(r=>{var i;return((i=r[0])==null?void 0:i.toLowerCase())||""}).join("");return n?n.slice(0,6):e==="audio"?"aud":e==="video"?"vid":e==="text"?"txt":"img"}function qc(t){const e=Gc(t),n=ao(t),r=Zn[n],i=t.id.toLowerCase(),o=e==="text"&&(t.supported_endpoint_types||[]).some(l=>l.toLowerCase().includes("openai-chat"));if(t.id.toLowerCase()==="kling_video")return{id:t.id,label:"Kling",shortLabel:"Kling",shortCode:Fn(t.id,"video"),description:"Kling 标准视频能力,版本通过 model_name 选择",type:"video",vendor:se.KLING,supportsTools:!1,tags:["runtime","kling"],videoDefaults:{duration:"5",size:"1280x720",aspectRatio:"16:9"}};const c={id:t.id,label:t.id,shortLabel:t.id,shortCode:Fn(t.id,e),description:`${r} ${e==="image"?"图片模型":e==="video"?"视频模型":e==="audio"?"音频模型":"文本模型"}`,type:e,vendor:n,supportsTools:o,tags:e==="audio"&&Si(i)?["runtime","suno","audio","music"]:["runtime"],imageDefaults:e==="image"?{aspectRatio:"auto",width:1024,height:1024}:void 0,videoDefaults:e==="video"?{duration:"8",size:"1280x720",aspectRatio:"16:9"}:void 0};return e==="audio"?Ii(c):c}function co(t){return{...t,tags:t.tags?[...t.tags]:void 0,imageDefaults:t.imageDefaults?{...t.imageDefaults}:void 0,videoDefaults:t.videoDefaults?{...t.videoDefaults}:void 0}}function Kc(t){if(!(t!=null&&t.id)||typeof t.id!="string")return null;const e=Kn(t.id);return e?co(e):qc(t)}function It(t,e){const n=new Set(t.map(r=>r.id));return Array.from(new Set(e.filter(r=>n.has(r))))}function Bt(t,e){return t.filter(n=>e.includes(n.id))}function Zc(t,e){const n=[...e],r=new Set(e.map(i=>i.id));for(const i of t)r.has(i.id)||n.push(i);return n}function Yc(t){const e=Array.isArray(t)?[...t]:[];return e.includes("runtime")||e.push("runtime"),e}function kt(t,e){return t?`${t}::${e}`:e}function rs(t){return bi.get().find(e=>e.id===t)||null}function Xc(t){var e;return t===Fe?!0:((e=rs(t))==null?void 0:e.enabled)!==!1}function os(t,e){var r;const n=((r=rs(t))==null?void 0:r.name)||null;return{...e,tags:Yc(e.tags),sourceProfileId:t,sourceProfileName:n,selectionKey:kt(t,e.id)}}function Jc(t){const e=Kn(t.id);if(e)return co(e);const n=t.id.toLowerCase(),r=(t.tags||[]).map(i=>i.toLowerCase());return n.includes("happyhorse")||r.includes("happyhorse")?{...t,type:"video",vendor:se.HAPPYHORSE,tags:Array.from(new Set([...t.tags||[],"happyhorse"]))}:t}function lo(t,e){return e.map(n=>os(t,Jc(n)))}function Us(t){return t.map(e=>({...e,selectionKey:e.selectionKey||kt(null,e.id)}))}function Qc(t,e,n){var o;const r=((o=rs(t))==null?void 0:o.name)||"供应商模型",i=io(e);return os(t,{id:e,label:e,shortLabel:e,shortCode:Fn(e,n),description:`${r} · ${e}`,type:n,vendor:i})}function Ws(t){const e=lo(t.profileId,Array.isArray(t.discoveredModels)?t.discoveredModels:[]),n=It(e,Array.isArray(t.selectedModelIds)?t.selectedModelIds:[]),r=Bt(e,n);return{profileId:t.profileId,status:t.error?"error":e.length>0?"ready":"idle",sourceBaseUrl:t.sourceBaseUrl||"",signature:t.signature||"",discoveredAt:Number.isFinite(t.discoveredAt)?t.discoveredAt:null,discoveredModels:e,selectedModelIds:n,models:r,error:t.error||null}}function Hs(t){return{profileId:t.profileId,discoveredAt:t.discoveredAt,discoveredModels:t.discoveredModels,selectedModelIds:t.selectedModelIds,sourceBaseUrl:t.sourceBaseUrl||void 0,signature:t.signature||void 0,error:t.error}}function el(){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(ro);if(!t)return null;const e=JSON.parse(t);if(!e||!Array.isArray(e.discoveredModels))return null;const n=lo(Fe,e.discoveredModels),r=It(n,Array.isArray(e.selectedModelIds)?e.selectedModelIds:[]);return{profileId:Fe,status:"ready",sourceBaseUrl:e.sourceBaseUrl||"",signature:e.signature||"",discoveredAt:Number.isFinite(e.discoveredAt)?e.discoveredAt:Date.now(),discoveredModels:n,selectedModelIds:r,models:Bt(n,r),error:null}}catch{return null}}function Tn(){if(!(typeof window>"u"))try{window.localStorage.removeItem(ro)}catch{}}class tl{constructor(){this.catalogStates=new Map,this.listeners=new Set,this.handleCatalogSettingsChange=e=>{const n=new Map;for(const r of e)n.set(r.profileId,Ws(r));n.has(Fe)||n.set(Fe,sn(Fe)),this.catalogStates=n,this.syncRuntimeModelConfigs(),this.emit()},this.handlePresetSettingsChange=()=>{this.syncRuntimeModelConfigs(),this.emit()},this.handleActivePresetIdChange=()=>{this.syncRuntimeModelConfigs(),this.emit()},this.catalogStates=this.loadCatalogStatesFromSettings(),this.migrateLegacyCacheIfNeeded(),this.syncRuntimeModelConfigs(),bn.addListener(this.handleCatalogSettingsChange),gi.addListener(this.handlePresetSettingsChange),wi.addListener("activePresetId",this.handleActivePresetIdChange)}loadCatalogStatesFromSettings(){const e=new Map;for(const n of bn.get())e.set(n.profileId,Ws(n));return e.has(Fe)||e.set(Fe,sn(Fe)),e}migrateLegacyCacheIfNeeded(){const e=el();if(!e)return;const n=this.catalogStates.get(Fe);if(!!n&&(n.discoveredModels.length>0||n.selectedModelIds.length>0)){Tn();return}this.catalogStates.set(Fe,e),this.persistCatalogs(),Tn()}emit(){for(const e of this.listeners)e()}async persistCatalogs(){const e=Array.from(this.catalogStates.values()).map(Hs);await bn.update(e)}setCatalogState(e,n,r=!0){this.catalogStates.set(e,{...n,profileId:e,selectedModelIds:It(n.discoveredModels,n.selectedModelIds),models:Bt(n.discoveredModels,It(n.discoveredModels,n.selectedModelIds))}),this.syncRuntimeModelConfigs(),r&&this.persistCatalogs(),this.emit()}getCatalogState(e){return this.catalogStates.get(e)||sn(e)}resolveRuntimeModels(){const e=new Set,n=[];for(const r of this.catalogStates.values())for(const i of r.models)e.has(i.id)||(e.add(i.id),n.push(i));return n}syncRuntimeModelConfigs(){yi(this.resolveRuntimeModels())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getState(e=Fe){return this.getCatalogState(e)}getCatalogs(e){const n=e?new Set(e):null;return Array.from(this.catalogStates.values()).filter(r=>!n||n.has(r.profileId)).map(r=>Hs(r))}getDiscoveredModels(e=Fe,n){const r=this.getCatalogState(e);return n?r.discoveredModels.filter(i=>i.type===n):r.discoveredModels}getSelectedModelIds(e=Fe){return[...this.getCatalogState(e).selectedModelIds]}getPreferredModels(e){return xi(e)}getSelectableModels(e){const n=[];for(const r of this.catalogStates.values())Xc(r.profileId)&&n.push(...r.models.filter(i=>i.type===e));return _i([...n,...Us(Ss(e))])}getPinnedSelectableModel(e,n,r){if(!n)return null;const i=(r==null?void 0:r.profileId)||null,o=kt(i,n);if(i){const l=this.catalogStates.get(i),m=(l==null?void 0:l.models.find(d=>d.type===e&&(d.selectionKey||kt(i,d.id))===o))||(l==null?void 0:l.discoveredModels.find(d=>d.type===e&&(d.selectionKey||kt(i,d.id))===o));return m||((l==null?void 0:l.models.find(d=>(d.selectionKey||kt(i,d.id))===o))||(l==null?void 0:l.discoveredModels.find(d=>(d.selectionKey||kt(i,d.id))===o))?null:Qc(i,n,e))}const c=Kn(n);if(c&&c.type===e)return Us([c])[0];for(const l of this.catalogStates.values()){const m=l.models.find(u=>u.type===e&&u.id===n)||l.discoveredModels.find(u=>u.type===e&&u.id===n);if(m)return m}return null}getProfilePreferredModels(e=Fe,n){const i=this.getCatalogState(e).models.filter(o=>o.type===n);return Zc(Ss(n),i)}invalidateIfConfigChanged(e=Fe,n,r){const i=this.getCatalogState(e),o=Fs(n,r);!i.signature||i.signature===o||this.clear(e)}applySelection(e=Fe,n){const r=this.getCatalogState(e),i=It(r.discoveredModels,r.selectedModelIds),o=It(r.discoveredModels,n),c=new Set(i),l=new Set(o),m=Bt(r.discoveredModels,o),u=o.filter(p=>!c.has(p)),d=i.filter(p=>!l.has(p));return this.setCatalogState(e,{...r,status:r.discoveredModels.length>0?"ready":r.status,selectedModelIds:o,models:m,error:null}),{models:m,addedModelIds:u,removedModelIds:d}}clear(e=Fe){this.setCatalogState(e,sn(e)),e===Fe&&Tn()}async discover(e=Fe,n,r){const i=r.trim();if(!i)throw new Error("缺少 API Key");const o=this.getCatalogState(e),c=oo(n),l=Fs(c,i);this.setCatalogState(e,{...o,status:"loading",sourceBaseUrl:c,signature:l,error:null},!1);const m=await fetch(`${c}/models`,{headers:{Authorization:`Bearer ${i}`}}),u=await m.text();if(!m.ok)throw new Error(Hc(u,`获取模型列表失败: HTTP ${m.status}`));let d;try{d=JSON.parse(u)}catch{throw new Error("模型列表接口未返回有效 JSON")}const p=d.data;if(!Array.isArray(p))throw new Error("模型列表接口缺少 data 数组");const h=[],g=new Set;for(const x of p){const z=Kc(x);!z||g.has(z.id)||(g.add(z.id),h.push(os(e,z)))}if(h.length===0)throw new Error("模型列表为空");const y=o.signature===l?It(h,o.selectedModelIds):[],f=Bt(h,y);return this.setCatalogState(e,{profileId:e,status:"ready",sourceBaseUrl:c,signature:l,discoveredAt:Date.now(),discoveredModels:h,selectedModelIds:y,models:f,error:null}),h}setError(e=Fe,n){const r=this.getCatalogState(e);this.setCatalogState(e,{...r,status:"error",error:n})}}const wt=new tl;function cm(t){return wt.getPreferredModels(t)}function nl(t){return wt.getSelectableModels(t)}function Un(t,e,n){return wt.getPinnedSelectableModel(t,e,n)}function sl(t,e){return wt.getProfilePreferredModels(t,e)}function uo(t=Fe){const[e,n]=a.useState(()=>wt.getState(t));return a.useEffect(()=>(n(wt.getState(t)),wt.subscribe(()=>{n(wt.getState(t))})),[t]),e}function mo(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n].id!==e[n].id||t[n].selectionKey!==e[n].selectionKey)return!1;return!0}function po(t){const e=uo(),n=a.useRef([]);return a.useMemo(()=>{const r=nl(t);return mo(n.current,r)?n.current:(n.current=r,r)},[t,e])}function lm(t,e){const n=uo(t),r=a.useRef([]);return a.useMemo(()=>{const i=sl(t,e);return mo(r.current,i)?r.current:(r.current=i,i)},[t,e,n])}function is(t,e){return e!=null&&e.profileId?`${e.profileId}::${t}`:t}function ho(t){return t.selectionKey||(t.sourceProfileId?`${t.sourceProfileId}::${t.id}`:t.id)}function Vs(t){return t?ht(t.sourceProfileId||null,t.id):null}function pn(t,e,n){if(!e)return;const r=is(e,n),i=(n==null?void 0:n.profileId)||null;return t.find(o=>ho(o)===r)||t.find(o=>o.id===e&&(o.sourceProfileId||null)===i)||(i===null?t.find(o=>o.id===e&&!o.sourceProfileId):void 0)||t.find(o=>o.id===e)}const rl=({title:t,items:e,onSelect:n,onTogglePin:r,onDelete:i,language:o="zh",disabled:c=!1,showCount:l=!0,onTitleClick:m,className:u="",analyticsSurface:d="prompt_list",analyticsPromptType:p})=>{const[h,g]=a.useState(!1),[y,f]=a.useState([]),[x,z]=a.useState(0),N=a.useCallback((v,{content:S,previewExamples:C,initialIndex:R})=>{f(C.map((U,P)=>{const J=U.kind==="video"&&U.playable!==!1;return{id:`${v}-preview-${P}`,url:J?U.src:U.kind==="video"&&U.posterSrc||U.src,type:J?"video":"image",posterUrl:J?U.posterSrc:void 0,alt:U.alt,title:S}})),z(R),g(!0),ye.trackPromptAction({action:"preview_example",surface:d,promptType:p,prompt:S,itemCount:C.length})},[p,d]),O=a.useCallback(v=>{ye.trackPromptAction({action:"select",surface:d,promptType:p||v.modelType,prompt:v.content,source:v.isPreset?"preset":v.pinned?"pinned":"history"}),n==null||n(v)},[p,d,n]),T=a.useCallback(v=>{ye.trackPromptAction({action:v.pinned?"unpin":"pin",surface:d,promptType:p||v.modelType,prompt:v.content}),r==null||r(v.id)},[p,d,r]),I=a.useCallback(v=>{ye.trackPromptAction({action:"delete",surface:d,promptType:p||v.modelType,prompt:v.content}),i==null||i(v.id)},[p,d,i]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`prompt-list-panel ${u}`,children:[s.jsxs("div",{className:"prompt-list-panel__header",children:[m?s.jsx("button",{type:"button",className:"prompt-list-panel__title prompt-list-panel__title-button",onClick:m,children:t}):s.jsx("span",{className:"prompt-list-panel__title",children:t}),l&&s.jsx("span",{className:"prompt-list-panel__count",children:e.length})]}),s.jsx("div",{className:"prompt-list-panel__list",children:e.map(v=>s.jsx(Uc,{content:v.content,title:v.title,sentPrompt:v.sentPrompt,tags:v.tags,resultPreview:v.resultPreview,pinned:v.pinned,isPreset:v.isPreset,modelType:v.modelType,scene:v.scene,previewExamples:v.previewExamples,onClick:()=>O(v),onTogglePin:r&&!v.isPreset?()=>T(v):void 0,onDelete:i&&!v.isPreset?()=>I(v):void 0,onPreviewExample:S=>N(v.id,S),language:o,disabled:c},v.id))})]}),s.jsx(mn,{visible:h,items:y,initialIndex:x,onClose:()=>g(!1),showThumbnails:y.length>1,videoAutoPlay:!0})]})},ol=["结构化 JSON 视觉提示词 schema:","- 每个页面图片提示词必须是一个可直接用于图片生成的 JSON 对象,顶层只使用 layout 和 style。","- layout.header 包含 location_title、main_title、subtitle,用于页面顶部地点/分类、主标题和副标题。","- layout.body.content_blocks 包含 block_type、left_column、right_column;左右栏都包含 title 和 content 数组。","- layout.footer.elements 描述页脚、CTA、滚动提示、页码或辅助信息。","- style.background 描述背景、摄影/插画质感、光影、景深和构图。","- style.elements 描述核心视觉元素、图标、建筑、产品、人物、道具或装饰。","- style.colors 使用数组,包含颜色名称、用途和可选 HEX。","- style.fonts 使用数组,描述标题、副标和正文的字体方向。","- 不要输出 subject、scene、negativePrompt 等旧式字段作为顶层字段;如确实需要,放入 style.elements 或对应内容字段中。","","目标结构示例:","{",' "layout": {',' "header": {',' "location_title": "中国 · 广东 | CHINA GUANGDONG",',' "main_title": "潮起岭南 寻味山海",',' "subtitle": "汕头 × 潮州 × 南澳 × 揭阳 · 4天3晚高定纯玩之旅"'," },",' "body": {',' "content_blocks": {',' "block_type": "首页视觉海报",',' "left_column": { "title": "文化与海岸的交响", "content": ["英歌舞非遗脸谱虚影", "民国骑楼复古剪影"] },',' "right_column": { "title": "留白与张力", "content": [] }'," }"," },",' "footer": { "elements": "SCROLL TO DISCOVER 开启寻味之旅" }'," },",' "style": {',' "background": "电影级光影质感,暖色文化元素平滑过渡至蓝色海浪,景深丰富,光影对比高级",',' "elements": "广济桥灯光、南澳长山尾灯塔、高级几何留白排版",',' "colors": ["潮汕非遗红 (#D13B3B)", "南澳海岛蓝 (#1A4B82)", "骑楼复古暖棕 (#B59372)"],',' "fonts": ["主标题:苍劲大气书法体", "副标及正文:现代极简无衬线几何体"]'," }","}"].join(`
5
+ `),il=["Structured JSON visual prompt schema:","- Each page image prompt must be a JSON object for image generation with only layout and style at the top level.","- layout.header includes location_title, main_title, subtitle.","- layout.body.content_blocks includes block_type, left_column, right_column; each column includes title and content array.","- layout.footer.elements describes footer, CTA, scroll cue, page number, or auxiliary information.","- style.background describes background, rendering/photography quality, lighting, depth of field, and composition.","- style.elements describes key visual elements, icons, architecture, product, people, props, or decorations.","- style.colors is an array with color names, usage, and optional HEX values.","- style.fonts is an array describing title, subtitle, and body font direction.","- Do not use old top-level fields such as subject, scene, or negativePrompt; fold them into style.elements or the matching content fields if needed."].join(`
6
+ `);function al(t="zh"){return t==="en"?il:ol}const Nn="提示词优化",cl="aitu://prompt-optimization/",fo={"ai-input.image":{id:"ai-input.image",name:"AI 输入框图片生成",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"AI输入-图片",focus:"补足主体、构图、风格、光线、材质、比例、负面约束和画面细节。"},"ai-input.video":{id:"ai-input.video",name:"AI 输入框视频生成",type:"video",historyType:"video",defaultMode:"structured",noteTitle:"AI输入-视频",focus:"补足主体动作、镜头语言、运镜、时序、转场、连续性和画面节奏。"},"ai-input.audio":{id:"ai-input.audio",name:"AI 输入框音频生成",type:"audio",historyType:"audio",defaultMode:"polish",noteTitle:"AI输入-音频",focus:"补足音乐风格、节奏、情绪、乐器、人声、歌词结构、时长和使用场景。"},"ai-input.text":{id:"ai-input.text",name:"AI 输入框文本生成",type:"text",historyType:"text",defaultMode:"polish",noteTitle:"AI输入-文本",focus:"补足主题、受众、结构、语气、信息密度、格式和交付标准。"},"ai-input.agent":{id:"ai-input.agent",name:"AI 输入框 Agent 指令",type:"agent",historyType:"agent",defaultMode:"polish",noteTitle:"AI输入-Agent",focus:"补足目标、上下文、约束、输入输出、执行步骤、工具边界和验收标准。"},"tool.image":{id:"tool.image",name:"图片工具提示词",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"工具-图片生成",focus:"面向图片生成工具,突出可直接生成的画面描述、构图、风格、尺寸比例和质量约束。"},"tool.video":{id:"tool.video",name:"视频工具提示词",type:"video",historyType:"video",defaultMode:"structured",noteTitle:"工具-视频生成",focus:"面向视频生成工具,突出镜头序列、运动方式、时长、首尾帧关系、主体一致性和节奏。"},"ppt.common":{id:"ppt.common",name:"PPT 公共提示词",type:"image",historyType:"ppt-common",defaultMode:"polish",noteTitle:"PPT-公共提示词",focus:"优化整套 PPT 的统一视觉方向、受众、版式规则、品牌语气、图文密度和风格约束。"},"ppt.slide":{id:"ppt.slide",name:"PPT 单页提示词",type:"image",historyType:"image",defaultMode:"structured",noteTitle:"PPT-单页提示词",focus:"优化单页幻灯片的页面目标、标题层级、内容区块、视觉重点、版式和生成可控性。"},"music.create-song":{id:"music.create-song",name:"爆款音乐歌曲创作",type:"audio",historyType:"audio",defaultMode:"polish",noteTitle:"爆款音乐-歌曲创作",focus:"补足爆款歌曲定位、曲风标签、情绪弧线、人声设定、段落结构、歌词主题和 Suno 可用表达。"}},ll={image:"ai-input.image",video:"ai-input.video",audio:"ai-input.audio",text:"ai-input.text",agent:"ai-input.agent"},dl=new Set(["ai-input.image","tool.image","ppt.slide"]);function ul(t){return`${cl}${t}`}function go(t,e){const n=t||(e?ll[e]:"ai-input.image");return fo[n]}function ml(t,e){return e==="structured"&&dl.has(t.id)}function pl(t,e,n){return ml(t,e)?["",n==="zh"?"【视觉结构化 JSON 强制要求】":"[Required Visual Structured JSON]",al(n),n==="zh"?"最终输出必须是单个合法 JSON 对象,不要 Markdown,不要代码块,不要解释。":"The final output must be one valid JSON object. No Markdown, no code fence, no explanation."].join(`
7
+ `):""}function hl(t){return["你是一名专业的「{{scenarioName}}」提示词优化助手。","","请基于用户原始提示词和补充要求,输出一版可直接用于下游模型的最终提示词。","","场景优化方向:",t.focus,"","通用要求:","1. 保持原始意图,不要擅自改题、换主题或新增关键事实。","2. 优先满足补充要求;补充要求为空时,仅做必要润色、结构补全和可执行性增强。","3. 输出语言尽量跟随原始提示词;中英混合时保留原表达习惯。","4. 原始提示词已经完整时,做轻量优化,避免堆砌无关细节。","5. 当前模式为 {{mode}}。structured 模式下可以强化结构、字段和可复用性;polish 模式下保持自然文本。","6. 只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。","","可用变量:{{originalPrompt}}、{{requirements}}、{{language}}、{{mode}}、{{scenarioName}}。"].join(`
8
+ `)}function fl(t,e){return t.replace(/\{\{\s*(originalPrompt|requirements|language|mode|scenarioName)\s*\}\}/g,(n,r)=>e[r])}async function gl(){const e=(await Dt()).find(n=>n.name===Nn);if(e)return e.id;try{return(await Sr(Nn)).id}catch{const r=(await Dt()).find(i=>i.name===Nn);if(!r)throw new Error("提示词优化目录创建失败");return r.id}}async function wo(t){const e=await gl(),n=ul(t.id),r=hl(t),o=(await ki(n))[0];if(o){const c=await ln(o.id),l=(c==null?void 0:c.content)||"";return l.trim()?l:(await Mi(o.id,{title:o.title||t.noteTitle,directoryId:o.directoryId||e,content:r,metadata:{...o.metadata,sourceUrl:n,domain:"提示词优化",tags:["提示词优化",t.type]}}),r)}return await br(t.noteTitle,e,r,{sourceUrl:n,domain:"提示词优化",tags:["提示词优化",t.type]}),r}async function dm(){for(const t of Object.values(fo))await wo(t)}async function wl({scenarioId:t,originalPrompt:e,optimizationRequirements:n,language:r,type:i,mode:o}){const c=go(t,i),l=o||c.defaultMode,m=e.trim(),u=(n==null?void 0:n.trim())||"",d=await wo(c),p=fl(d,{originalPrompt:m,requirements:u||"无",language:r,mode:l,scenarioName:c.name}),h=pl(c,l,r),g=r==="zh"?["","---","以下输入块由系统固定附加,请必须以此为准:","","【原始提示词】",m,"","【补充要求】",u||"无,做通顺、准确、可执行的轻量优化。",h,"","【输出要求】",h?"只输出符合视觉结构化 schema 的合法 JSON 对象,不要解释、不要标题、不要 Markdown 代码块。":"只输出最终优化后的提示词,不要解释、不要标题、不要 Markdown 代码块。"]:["","---","The following input block is appended by the system and must be treated as authoritative:","","[Original Prompt]",m,"","[Refinement Requirements]",u||"None. Apply light polishing for clarity and execution quality.",h,"","[Output Requirement]",h?"Output only a valid JSON object following the visual structured schema. No explanation, no title, no Markdown code block.":"Output only the final optimized prompt. No explanation, no title, no Markdown code block."];return`${p.trim()}
9
9
  ${g.join(`
10
- `)}`}const wl=t=>{const e=t.trim(),n=e.match(/^```[\w-]*\n?([\s\S]*?)\n?```$/);return n?n[1].trim():e},as=30,yl=60;function hn(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(Ht.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY),e=t?JSON.parse(t):[];return Array.isArray(e)?e.filter(n=>n&&typeof n.id=="string"&&typeof n.content=="string"&&typeof n.timestamp=="number"&&n.content.trim().length>0).sort((n,r)=>r.timestamp-n.timestamp).slice(0,as):[]}catch{return[]}}function xl(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Ht.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY,JSON.stringify(t.slice(0,as)))}catch{}}function _l(t){const e=t.trim();if(!e)return hn();const n=[{id:`requirements-${Date.now()}`,content:e,timestamp:Date.now()},...hn().filter(r=>r.content!==e)].slice(0,as);return xl(n),n}const bl=t=>{const{open:e,onOpenChange:n,originalPrompt:r,language:i,type:o,onApply:c,historyType:l,allowStructuredMode:m=!1,defaultMode:u}=t,d=t.scenarioId,p=a.useId(),h=a.useId(),g=a.useId(),y=a.useId(),f=a.useMemo(()=>fo(d,o),[d,o]),x=o||f.type,z=l||f.historyType,N=u??f.defaultMode,[O,T]=a.useState(""),[I,b]=a.useState(r),[S,C]=a.useState(""),[R,U]=a.useState(N),[P,J]=a.useState(!1),[ee,X]=a.useState(null),[Q,B]=a.useState([]),_=a.useRef(null),E=a.useRef(!1),M=a.useRef(null),{isMobile:$,viewportWidth:re,viewportHeight:fe}=Mi(),{history:K,addHistory:de,refreshHistory:ie}=Sr({deduplicateWithPresets:!1,modelTypeFilter:z}),ue=mo("text"),xe=a.useCallback(()=>{var _e;const w=zn("text"),V=ht(w.profileId,w.modelId),v=w.modelId||((_e=ue[0])==null?void 0:_e.id)||"",D=V||(v?ht(null,v):null),W=Ci(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,v,D),G=pn(ue,W.modelId,W.modelRef)||Un("text",W.modelId,W.modelRef),Y=(G==null?void 0:G.id)||W.modelId||v,le=Vs(G)||W.modelRef||D||(Y?ht(null,Y):null);return{modelId:Y,modelRef:le}},[ue]),[pe,ae]=a.useState(()=>xe().modelId),[q,ce]=a.useState(()=>xe().modelRef),ve=a.useMemo(()=>{if(pn(ue,pe,q)||!pe)return ue;const V=Un("text",pe,q);return V?[V,...ue]:ue},[pe,q,ue]),me=a.useCallback(()=>{const w=xe();ae(w.modelId),ce(w.modelRef)},[xe]),Re=a.useCallback(()=>{var w;(w=_.current)==null||w.abort(),_.current=null,E.current=!1,J(!1),T(""),C(""),U(N),n(!1)},[N,n]),Me=a.useCallback(async()=>{var D;const w=I.trim();if(!w){Ke.warning(i==="zh"?"请先填写当前提示词":"Please enter the current prompt first");return}if(E.current||P)return;E.current=!0,de(w,!1,z||x),O.trim()&&B(_l(O));const V=new AbortController,v=Date.now();(D=_.current)==null||D.abort(),_.current=V,J(!0),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"start",model:pe||void 0,prompt:w,requirements:O});try{const W=wl((await Ir.getFallbackExecutor().generateText({prompt:await gl({scenarioId:d,originalPrompt:w,optimizationRequirements:O,language:i,type:x,mode:R}),model:pe||void 0,modelRef:q},{signal:V.signal})).content);if(!W)throw new Error("Empty optimized prompt");C(W),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"success",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-v,metadata:{result_length_bucket:W.length<=200?"1-200":W.length<=500?"201-500":W.length<=1e3?"501-1000":"1000+"}}),Ke.success(i==="zh"?R==="structured"?"结构化提示词已生成,可继续优化或回填":"提示词优化完成,可继续优化或回填":R==="structured"?"Structured prompt generated. You can refine again or apply it.":"Prompt optimized. You can refine again or apply it."),T("")}catch(W){if(V.signal.aborted){ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"cancelled",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-v});return}console.error("[PromptOptimizeDialog] Failed to optimize prompt:",W),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"failed",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-v,metadata:{error:W instanceof Error?W.name||"Error":typeof W}}),Ke.error(i==="zh"?R==="structured"?"结构化提示词生成失败,请稍后重试":"提示词优化失败,请稍后重试":R==="structured"?"Failed to generate structured prompt, please try again later":"Failed to optimize prompt, please try again later")}finally{_.current===V&&(_.current=null),E.current=!1,J(!1)}},[I,i,R,pe,q,O,de,z,x,P,d]),We=a.useCallback(()=>{const w=S.trim();w&&(ye.trackPromptAction({action:"use_draft_as_current",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,prompt:w}),b(w),T(""))},[z,x,R,S]),Ee=a.useCallback(()=>{const w=(S||I).trim();if(!w){Ke.warning(i==="zh"?"没有可回填的提示词":"There is no prompt to apply");return}ye.trackPromptAction({action:"apply",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,prompt:w}),c(w),Re()},[I,z,x,Re,i,R,c,S]);a.useEffect(()=>{e&&(me(),b(r),C(""),T(""),B(hn()),X(null),U(N))},[N,e,r,me]),a.useEffect(()=>()=>{var w;(w=_.current)==null||w.abort(),_.current=null,E.current=!1},[]),a.useEffect(()=>{if(!ee)return;const w=V=>{var D;const v=V.target;v instanceof Node&&((D=M.current)!=null&&D.contains(v))||v instanceof Element&&v.closest(".prompt-optimize-dialog__history-btn")||X(null)};return document.addEventListener("mousedown",w,!0),()=>{document.removeEventListener("mousedown",w,!0)}},[ee]);const Te=i==="zh"?R==="structured"?"例如:突出时间轴结构、把区域与数量拆开、保留标题与图例、输出 JSON 不要解释...":"例如:更电影感、补充镜头语言、减少冗余、强调主体与光线...":R==="structured"?"For example: emphasize timeline structure, split regions and counts, preserve titles and legends, output JSON only...":"For example: make it more cinematic, add camera language, reduce redundancy, emphasize subject and lighting...",Ye=I.trim().length>0,$e=(S.length>0?S:I).trim().length>0,be=S.length>0,Ie=a.useMemo(()=>K.slice(0,yl).map(w=>({id:w.id,content:w.content,pinned:w.pinned,modelType:w.modelType})),[K]),he=a.useMemo(()=>Q.map(w=>({id:w.id,content:w.content})),[Q]),ze=a.useMemo(()=>`prompt-optimize-dialog-${p.replace(/[^a-zA-Z0-9_-]/g,"")}`,[p]),De=i==="zh"?R==="structured"?"结构化提示词":"提示词优化":R==="structured"?"Structured Prompt":"Prompt Optimization",He=a.useMemo(()=>{const w=$?16:48,V=Math.max(280,re-w),v=Math.max(320,fe-w),D=be?1120:680,W=be?760:680,G=Math.max(280,Math.min(D,V)),Y=Math.max(320,Math.min(W,v));return{width:G,height:Y,minWidth:Math.min(be?640:320,G),minHeight:Math.min(420,Y)}},[be,$,fe,re]),Be=a.useCallback(w=>{w==="current"?ie():B(hn()),ye.trackPromptAction({action:"toggle_history",surface:"prompt_optimize_dialog",promptType:w==="current"?z||x:void 0,mode:R,metadata:{panel:w}}),X(V=>V===w?null:w)},[z,x,R,ie]),Ge=a.useCallback(w=>{b(w.content),X(null)},[]),Qe=a.useCallback(w=>{T(w.content),X(null)},[]),Ne=a.useCallback(w=>{ye.trackPromptAction({action:"mode_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:w}),U(w)},[z,x]),L=(w,V,v)=>ee!==w?null:s.jsx("div",{ref:M,className:"prompt-optimize-dialog__history-panel",children:V.length>0?s.jsx(sl,{title:i==="zh"?"历史":"History",items:V,onSelect:v,language:i,analyticsSurface:`prompt_optimize_${w}_history`,analyticsPromptType:w==="current"?z||x:void 0,showCount:!0}):s.jsx("div",{className:"prompt-optimize-dialog__history-empty",children:i==="zh"?"暂无历史":"No history yet"})});return e?s.jsx($c,{id:ze,visible:e,title:De,icon:s.jsx(Dn,{size:16}),onClose:Re,width:He.width,height:He.height,minWidth:He.minWidth,minHeight:He.minHeight,x:"center",y:"center",maximizable:!$,minimizable:!1,resizable:!$,movable:!$,modal:!1,background:"#ffffff",className:`winbox-ai-generation winbox-prompt-optimize ${be?"winbox-prompt-optimize--split":""}`,children:s.jsxs("div",{className:`prompt-optimize-dialog ${be?"prompt-optimize-dialog--split":""}`,children:[s.jsxs("div",{className:`prompt-optimize-dialog__body ${be?"prompt-optimize-dialog__body--split":""}`,children:[s.jsxs("div",{className:"prompt-optimize-dialog__form-pane",children:[s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--current",children:[s.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:h,children:i==="zh"?"当前提示词":"Current Prompt"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Be("current"),"aria-label":i==="zh"?"当前提示词历史":"Current prompt history",children:s.jsx(Is,{size:16})}),L("current",Ie,Ge)]}),s.jsx("textarea",{id:h,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--current",value:I,onChange:w=>b(w.target.value),placeholder:i==="zh"?"输入或编辑要优化的提示词...":"Enter or edit the prompt to optimize...",rows:5,disabled:P})]}),s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--requirements",children:[s.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:g,children:i==="zh"?"补充要求":"Additional Requirements"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Be("requirements"),"aria-label":i==="zh"?"补充要求历史":"Additional requirements history",children:s.jsx(Is,{size:16})}),L("requirements",he,Qe)]}),s.jsx("textarea",{id:g,className:"prompt-optimize-dialog__textarea",value:O,onChange:w=>T(w.target.value),placeholder:Te,rows:4,disabled:P})]})]}),be&&s.jsx("div",{className:"prompt-optimize-dialog__result-pane",children:s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--result",children:[s.jsx("div",{className:"prompt-optimize-dialog__result-header",children:s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:y,children:i==="zh"?"优化结果草稿":"Optimized Draft"})}),s.jsx("textarea",{id:y,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--draft",value:S,onChange:w=>C(w.target.value),rows:6,disabled:P})]})})]}),s.jsxs("div",{className:`prompt-optimize-dialog__footer ${be?"prompt-optimize-dialog__footer--split":""}`,children:[s.jsxs("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--form",children:[s.jsxs("div",{className:"prompt-optimize-dialog__footer-controls",children:[m&&s.jsxs("div",{className:"prompt-optimize-dialog__mode-switch","aria-label":i==="zh"?"输出模式":"Output Mode",children:[s.jsxs("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="polish"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>Ne("polish"),disabled:P,children:[s.jsx(Dn,{size:14}),s.jsx("span",{children:i==="zh"?"普通润色":"Polish"})]}),s.jsx("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="structured"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>Ne("structured"),disabled:P,children:s.jsx("span",{children:i==="zh"?"结构化 JSON":"Structured JSON"})})]}),s.jsx("div",{className:"prompt-optimize-dialog__model",children:s.jsx(ji,{selectedModel:pe,selectedSelectionKey:is(pe,q),onSelect:(w,V)=>{const v=V||null;ye.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,model:w}),ae(w),ce(v),ks(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,w,v)},onSelectModel:w=>{const V=Vs(w);ye.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,model:w.id}),ae(w.id),ce(V),ks(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,w.id,V)},language:i,models:ve,placement:"up",header:i==="zh"?"选择文本模型 (↑↓ Tab)":"Select text model (↑↓ Tab)",disabled:P})})]}),s.jsxs("div",{className:"prompt-optimize-dialog__footer-buttons",children:[s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--primary",onClick:()=>void Me(),disabled:P||!Ye,children:i==="zh"?P?R==="structured"?"生成中...":"优化中...":R==="structured"?"生成结构化提示词":"开始优化":P?R==="structured"?"Generating...":"Optimizing...":R==="structured"?"Generate Structured Prompt":"Optimize"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--apply",onClick:Ee,disabled:P||!$e,children:i==="zh"?"回填":"Apply"})]})]}),be&&s.jsx("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--result",children:s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--secondary",onClick:We,disabled:P,children:i==="zh"?"用结果继续优化":"Use Draft to Refine"})})]})]})}):null},dm=({disabled:t=!1,className:e,iconSize:n=16,tooltipPlacement:r="right",tooltipContent:i,language:o,onApply:c,onMouseDown:l,onOpenChange:m,...u})=>{const[d,p]=a.useState(!1),h=a.useCallback(f=>{p(f),m==null||m(f)},[m]),g=a.useCallback(f=>{c(f)},[c]),y=o==="zh"?"提示词优化":"Prompt optimization";return s.jsxs(s.Fragment,{children:[s.jsx(je,{content:i??y,placement:r,disabled:t,children:s.jsx("button",{type:"button",className:e||"prompt-optimize-button",disabled:t,onMouseDown:l,onClick:()=>h(!0),"aria-label":y,children:s.jsx(Dn,{size:n})})}),s.jsx(bl,{...u,language:o,open:d,onOpenChange:h,onApply:g})]})};function Bs(t){return t.toLowerCase().replace(/\s+/g,"").trim()}function vl(t,e,n){const r=Bs(n);if(!r)return t;const i=new Map(e.map(o=>[o.id,o.name]));return t.filter(o=>{var l,m,u,d;return Bs([o.title,(l=o.metadata)==null?void 0:l.description,(m=o.metadata)==null?void 0:m.domain,(u=o.metadata)==null?void 0:u.sourceUrl,i.get(o.directoryId),...((d=o.metadata)==null?void 0:d.tags)||[]].filter(Boolean).join(" ")).includes(r)})}function Sl(t,e,n){return!e.includes(t)&&e.length>=n}function Il(t,e="zh"){const n=t.map(o=>o.title||"未命名笔记"),r=n.join("、"),i=t.length>0;return{triggerLabel:i?e==="zh"?`知识库上下文,已选 ${t.length} 篇笔记`:`Knowledge context, ${t.length} notes selected`:e==="zh"?"选择知识库笔记":"Select knowledge notes",selectedTitleText:r,hoverTitle:e==="zh"?"已选知识库笔记":"Selected notes",noteTitles:n,shouldShowChips:!1,canClear:i,clearLabel:e==="zh"?"清除":"Clear",clearAriaLabel:e==="zh"?"清除已选知识库笔记":"Clear selected knowledge notes",addNoteLabel:e==="zh"?"添加笔记":"Add note",addNoteAriaLabel:e==="zh"?"打开知识库新建笔记":"Open knowledge base to add note",badgeText:i?String(t.length):void 0}}function kl(t){if(!t)return"";try{return new Date(t).toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})}catch{return""}}const um=({value:t,onChange:e,disabled:n=!1,label:r,language:i="zh",maxNotes:o=Ti,className:c="",variant:l="default",placement:m="down"})=>{const[u,d]=a.useState(!1),[p,h]=a.useState(!1),[g,y]=a.useState([]),[f,x]=a.useState([]),[z,N]=a.useState(""),O=a.useRef(null),T=a.useRef(null),[I,b]=a.useState({}),S=a.useMemo(()=>Ln(t,o),[o,t]),C=a.useMemo(()=>new Set(S.map(K=>K.noteId)),[S]),R=a.useMemo(()=>new Map(f.map(K=>[K.id,K.name])),[f]),U=a.useCallback(async()=>{h(!0);try{await Sn.initialize();const[K,de]=await Promise.all([Sn.getAllNoteMetas(),Sn.getAllDirectories()]);y([...K].sort((ie,ue)=>ue.updatedAt-ie.updatedAt)),x(de)}finally{h(!1)}},[]);a.useEffect(()=>{u&&U()},[U,u]),a.useEffect(()=>{if(!u)return;const K=de=>{var ue,xe;const ie=de.target;!((ue=O.current)!=null&&ue.contains(ie))&&!((xe=T.current)!=null&&xe.contains(ie))&&d(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[u]),a.useEffect(()=>{if(!u||l!=="compact"||!O.current)return;const K=()=>{var xe;const de=(xe=O.current)==null?void 0:xe.getBoundingClientRect();if(!de)return;const ie=Math.min(360,Math.max(240,window.innerWidth-32)),ue=Math.min(Math.max(16,de.left),window.innerWidth-ie-16);b({position:"fixed",top:"auto",bottom:window.innerHeight-de.top+8,left:ue,width:ie,zIndex:qn.DROPDOWN_PORTAL})};return K(),window.addEventListener("resize",K),window.addEventListener("scroll",K,!0),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0)}},[u,l]);const P=a.useMemo(()=>vl(g,f,z),[f,g,z]),J=a.useCallback(K=>{const ie=C.has(K.id)?S.filter(ue=>ue.noteId!==K.id):[...S,Ni(K)];e(Ln(ie,o))},[o,e,C,S]),ee=a.useCallback(K=>{e(S.filter(de=>de.noteId!==K))},[e,S]),X=a.useCallback(K=>{K==null||K.stopPropagation(),e([])},[e]),Q=a.useCallback(K=>{if(K==null||K.stopPropagation(),n||typeof window>"u")return;const de={directoryName:"笔记",autoCreateNote:!0};window.__kbPendingNavigation=de,window.dispatchEvent(new CustomEvent("kb:open",{detail:{}})),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:de}))},300),d(!1)},[n]),B=r||(i==="zh"?"知识库上下文":"Knowledge Context"),_=i==="zh"?"搜索知识库笔记...":"Search notes...",E=i==="zh"?"暂无可选笔记":"No notes available",M=i==="zh"?"无匹配笔记":"No matching notes",$=l==="compact",re=Il(S,i),fe=u?s.jsxs("div",{ref:T,className:"knowledge-note-context-selector__dropdown",style:$?I:void 0,onMouseDown:K=>K.stopPropagation(),children:[s.jsxs("div",{className:"knowledge-note-context-selector__search",children:[s.jsx(Ei,{size:14}),s.jsx("input",{value:z,onChange:K=>N(K.target.value),placeholder:_,autoFocus:!0})]}),s.jsx("div",{className:"knowledge-note-context-selector__list",children:p?s.jsx("div",{className:"knowledge-note-context-selector__empty",children:i==="zh"?"加载中...":"Loading..."}):P.length>0?P.map(K=>{const de=C.has(K.id),ie=Sl(K.id,S.map(xe=>xe.noteId),o),ue=R.get(K.directoryId);return s.jsxs("button",{type:"button",className:`knowledge-note-context-selector__item ${de?"knowledge-note-context-selector__item--selected":""}`,onClick:()=>!ie&&J(K),disabled:ie,children:[s.jsxs("span",{className:"knowledge-note-context-selector__item-main",children:[s.jsx("span",{className:"knowledge-note-context-selector__item-title",children:K.title||"未命名笔记"}),s.jsx("span",{className:"knowledge-note-context-selector__item-meta",children:[ue,kl(K.updatedAt)].filter(Boolean).join(" · ")})]}),de?s.jsx(gn,{size:15}):null]},K.id)}):s.jsx("div",{className:"knowledge-note-context-selector__empty",children:g.length===0?E:M})}),s.jsxs("div",{className:"knowledge-note-context-selector__footer",children:[s.jsx("span",{className:"knowledge-note-context-selector__footer-text",children:i==="zh"?`最多选择 ${o} 篇,提交时按需读取正文`:`Up to ${o}; content is read on submit`}),s.jsxs("span",{className:"knowledge-note-context-selector__footer-actions",children:[s.jsxs("button",{type:"button",className:"knowledge-note-context-selector__footer-add",onClick:Q,disabled:n,"aria-label":re.addNoteAriaLabel,children:[s.jsx(fr,{size:12}),re.addNoteLabel]}),re.canClear?s.jsx("button",{type:"button",className:"knowledge-note-context-selector__footer-clear",onClick:X,disabled:n,"aria-label":re.clearAriaLabel,children:re.clearLabel}):null]})]})]}):null;return s.jsxs("div",{className:Pi("knowledge-note-context-selector",{"knowledge-note-context-selector--compact":$,"knowledge-note-context-selector--selected":S.length>0,"knowledge-note-context-selector--open":u,"knowledge-note-context-selector--placement-up":m==="up"},c),ref:O,children:[$?null:s.jsxs("div",{className:"knowledge-note-context-selector__header",children:[s.jsx("span",{className:"knowledge-note-context-selector__label",children:B}),S.length>0?s.jsx("button",{type:"button",className:"knowledge-note-context-selector__clear",onClick:X,disabled:n,children:i==="zh"?"清空":"Clear"}):null]}),s.jsxs("button",{type:"button",className:"knowledge-note-context-selector__trigger",onClick:()=>!n&&d(K=>!K),disabled:n,"aria-expanded":u,"aria-label":re.triggerLabel,title:$?re.selectedTitleText||re.triggerLabel:void 0,children:[s.jsx(Ai,{size:$?18:15}),$?re.badgeText?s.jsx("span",{className:"knowledge-note-context-selector__badge",children:re.badgeText}):null:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:S.length>0?i==="zh"?`已选 ${S.length} 篇笔记`:`${S.length} notes selected`:i==="zh"?"选择知识库笔记":"Select notes"}),s.jsx(Ri,{size:15})]})]}),$&&S.length>0?s.jsxs("div",{className:"knowledge-note-context-selector__hover-summary","aria-label":i==="zh"?`已选知识库笔记:${re.selectedTitleText}`:`Selected knowledge notes: ${re.selectedTitleText}`,children:[s.jsx("div",{className:"knowledge-note-context-selector__hover-title",children:re.hoverTitle}),s.jsx("div",{className:"knowledge-note-context-selector__hover-list",children:S.map((K,de)=>s.jsx("div",{className:"knowledge-note-context-selector__hover-item",children:re.noteTitles[de]},K.noteId))})]}):null,!$&&S.length>0?s.jsx("div",{className:"knowledge-note-context-selector__chips",children:S.map(K=>s.jsxs("span",{className:"knowledge-note-context-selector__chip",children:[s.jsx("span",{children:K.title}),s.jsx("button",{type:"button",onClick:()=>ee(K.noteId),disabled:n,"aria-label":i==="zh"?"移除笔记":"Remove note",children:s.jsx(Mt,{size:12})})]},K.noteId))}):null,$&&fe?Rt.createPortal(fe,document.body):fe]})},mm=({visible:t,items:e,initialIndex:n=0,onClose:r,onIndexChange:i,showToolbar:o=!0,className:c="",showTitle:l=!0,videoAutoPlay:m=!0,videoLoop:u=!0})=>{const d=e.map((p,h)=>({id:`media-${h}`,url:p.url,type:p.type,title:p.title,alt:p.alt,posterUrl:p.posterUrl,duration:p.duration,prompt:p.prompt,tags:p.tags,artist:p.artist,album:p.album}));return s.jsx(mn,{visible:t,items:d,initialMode:"single",initialIndex:n,onClose:r,showThumbnails:e.length>1,className:c,showTitle:l,videoAutoPlay:m,videoLoop:u})};let cs=null;function Ml(t){cs=t}function wo(){return cs}async function Gs(t,e,n,r){if(r){const o=Math.round(window.innerWidth*.5);return Ms(t,[{title:r,body:e}],n,o),{width:o,height:120}}const i=$i(e);if(i&&i.length>0){const o=Math.round(window.innerWidth*.5);Ms(t,i,n,o);const c=Math.min(i.length,3),l=Math.ceil(i.length/3);return{width:c*(o+20)-20,height:l*140-20}}return Yn.insertText(t,n,e),kr(e)}async function qs(t,e,n,r){const i=r||{width:Ue.MEDIA_DEFAULT_SIZE,height:Ue.MEDIA_DEFAULT_SIZE};try{await cr(t,e,n,!1,i,!0,!0)}catch(o){throw console.error("[CanvasInsertion] insertImageFromUrl failed:",o),o}return i}async function Ks(t,e,n,r){if(r)return await Rn(t,e,n,!1,r,!0,!0),r;const i={width:Ue.MEDIA_DEFAULT_SIZE,height:Math.round(Ue.MEDIA_DEFAULT_SIZE*(9/16))};return await Rn(t,e,n,!1,i,!0,!0),i}async function Zs(t,e,n,r,i){const o=Oi({...i,width:r==null?void 0:r.width,height:r==null?void 0:r.height});return await Fi(t,e,{...i,width:o.width,height:o.height},n,!1,!0),o}async function Ys(t,e,n){const r=Mr(e),i=Cr(r),o=Math.min(i.width,Ue.MEDIA_DEFAULT_SIZE),c=i.height/i.width,l=o*c,u={url:jr(r),width:o,height:l};return Yn.insertImage(t,u,n),{width:o,height:l}}async function yo(t){const e=cs;if(!e)return console.error("[CanvasInsertion] Board is null!"),{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{items:n,verticalGap:r=Ue.DEFAULT_VERTICAL_GAP,horizontalGap:i=Ue.DEFAULT_HORIZONTAL_GAP}=t;if(!n||n.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{if(!t.startPoint&&n.length===1){const d=n[0];if(d.type==="image"||d.type==="video"){const p=await ar(e,d.content,d.type,d.dimensions);if(p)return{success:!0,data:{insertedCount:1,items:[{type:d.type,point:p.point}],firstElementPosition:p.point,firstElementSize:p.size},type:"text"}}}let o=t.startPoint;o||(o=Bn(e,{verticalGap:r,logPrefix:"CanvasInsertion"})),o||(o=Gn(e,{verticalGap:r,emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT);const c=zi(n);let l=o[1];const m=o[0],u=[];for(const d of c)if(d.length===1){const p=d[0];let h={width:Ue.MEDIA_DEFAULT_SIZE,height:225};p.type==="text"?h=kr(p.content):p.type==="image"?h=p.dimensions||{width:Ue.MEDIA_DEFAULT_SIZE,height:Ue.MEDIA_DEFAULT_SIZE}:p.type==="video"?h=p.dimensions||{width:Ue.MEDIA_DEFAULT_SIZE,height:Math.round(Ue.MEDIA_DEFAULT_SIZE*(9/16))}:p.type==="audio"&&(h=p.dimensions||{width:Li,height:Di});const g=[m,l];if(p.type==="text")await Gs(e,p.content,g,p.label),l+=h.height+r;else if(p.type==="image"){const y=await qs(e,p.content,g,p.dimensions);l+=y.height+r}else if(p.type==="video")await Ks(e,p.content,g,p.dimensions),l+=h.height+r;else if(p.type==="audio"){const y=await Zs(e,p.content,g,p.dimensions,p.metadata);l+=y.height+r}else if(p.type==="svg"){const y=await Ys(e,p.content,g);l+=y.height+r}u.push({type:p.type,point:g})}else{let p=m,h=0;for(const g of d){const y=[p,l];if(g.type==="text"){const f=await Gs(e,g.content,y,g.label);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="image"){const f=await qs(e,g.content,y,g.dimensions);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="video")await Ks(e,g.content,y),h=Math.max(h,225),p+=Ue.MEDIA_DEFAULT_SIZE+i;else if(g.type==="audio"){const f=await Zs(e,g.content,y,g.dimensions,g.metadata);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="svg"){const f=await Ys(e,g.content,y);h=Math.max(h,f.height),p+=f.width+i}u.push({type:g.type,point:y})}l+=h+r}if(u.length>0){const d=u[0],p=[d.point[0]+Ue.MEDIA_DEFAULT_SIZE/2,d.point[1]+Ue.MEDIA_DEFAULT_SIZE/2];requestAnimationFrame(()=>{qt(e,p)})}return{success:!0,data:{insertedCount:u.length,items:u,firstElementPosition:u.length>0?u[0].point:void 0},type:"text"}}catch(o){return console.error("[CanvasInsertion] Failed to insert content:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const xo={name:"insert_to_canvas",description:`将内容插入到画布工具。用于将AI生成的文本、图片、视频等内容插入到画布中。
10
+ `)}`}const yl=t=>{const e=t.trim(),n=e.match(/^```[\w-]*\n?([\s\S]*?)\n?```$/);return n?n[1].trim():e},as=30,xl=60;function hn(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(Ht.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY),e=t?JSON.parse(t):[];return Array.isArray(e)?e.filter(n=>n&&typeof n.id=="string"&&typeof n.content=="string"&&typeof n.timestamp=="number"&&n.content.trim().length>0).sort((n,r)=>r.timestamp-n.timestamp).slice(0,as):[]}catch{return[]}}function _l(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Ht.PROMPT_OPTIMIZE_REQUIREMENTS_HISTORY,JSON.stringify(t.slice(0,as)))}catch{}}function vl(t){const e=t.trim();if(!e)return hn();const n=[{id:`requirements-${Date.now()}`,content:e,timestamp:Date.now()},...hn().filter(r=>r.content!==e)].slice(0,as);return _l(n),n}const bl=t=>{const{open:e,onOpenChange:n,originalPrompt:r,language:i,type:o,onApply:c,historyType:l,allowStructuredMode:m=!1,defaultMode:u}=t,d=t.scenarioId,p=a.useId(),h=a.useId(),g=a.useId(),y=a.useId(),f=a.useMemo(()=>go(d,o),[d,o]),x=o||f.type,z=l||f.historyType,N=u??f.defaultMode,[O,T]=a.useState(""),[I,v]=a.useState(r),[S,C]=a.useState(""),[R,U]=a.useState(N),[P,J]=a.useState(!1),[ee,X]=a.useState(null),[Q,B]=a.useState([]),_=a.useRef(null),E=a.useRef(!1),M=a.useRef(null),{isMobile:$,viewportWidth:re,viewportHeight:fe}=Ci(),{history:K,addHistory:de,refreshHistory:ie}=Ir({deduplicateWithPresets:!1,modelTypeFilter:z}),ue=po("text"),xe=a.useCallback(()=>{var _e;const w=zn("text"),V=ht(w.profileId,w.modelId),b=w.modelId||((_e=ue[0])==null?void 0:_e.id)||"",D=V||(b?ht(null,b):null),W=ji(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,b,D),G=pn(ue,W.modelId,W.modelRef)||Un("text",W.modelId,W.modelRef),Y=(G==null?void 0:G.id)||W.modelId||b,le=Vs(G)||W.modelRef||D||(Y?ht(null,Y):null);return{modelId:Y,modelRef:le}},[ue]),[pe,ae]=a.useState(()=>xe().modelId),[q,ce]=a.useState(()=>xe().modelRef),be=a.useMemo(()=>{if(pn(ue,pe,q)||!pe)return ue;const V=Un("text",pe,q);return V?[V,...ue]:ue},[pe,q,ue]),me=a.useCallback(()=>{const w=xe();ae(w.modelId),ce(w.modelRef)},[xe]),Re=a.useCallback(()=>{var w;(w=_.current)==null||w.abort(),_.current=null,E.current=!1,J(!1),T(""),C(""),U(N),n(!1)},[N,n]),Me=a.useCallback(async()=>{var D;const w=I.trim();if(!w){Ke.warning(i==="zh"?"请先填写当前提示词":"Please enter the current prompt first");return}if(E.current||P)return;E.current=!0,de(w,!1,z||x),O.trim()&&B(vl(O));const V=new AbortController,b=Date.now();(D=_.current)==null||D.abort(),_.current=V,J(!0),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"start",model:pe||void 0,prompt:w,requirements:O});try{const W=yl((await kr.getFallbackExecutor().generateText({prompt:await wl({scenarioId:d,originalPrompt:w,optimizationRequirements:O,language:i,type:x,mode:R}),model:pe||void 0,modelRef:q},{signal:V.signal})).content);if(!W)throw new Error("Empty optimized prompt");C(W),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"success",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-b,metadata:{result_length_bucket:W.length<=200?"1-200":W.length<=500?"201-500":W.length<=1e3?"501-1000":"1000+"}}),Ke.success(i==="zh"?R==="structured"?"结构化提示词已生成,可继续优化或回填":"提示词优化完成,可继续优化或回填":R==="structured"?"Structured prompt generated. You can refine again or apply it.":"Prompt optimized. You can refine again or apply it."),T("")}catch(W){if(V.signal.aborted){ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"cancelled",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-b});return}console.error("[PromptOptimizeDialog] Failed to optimize prompt:",W),ye.trackPromptAction({action:"optimize",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,status:"failed",model:pe||void 0,prompt:w,requirements:O,durationMs:Date.now()-b,metadata:{error:W instanceof Error?W.name||"Error":typeof W}}),Ke.error(i==="zh"?R==="structured"?"结构化提示词生成失败,请稍后重试":"提示词优化失败,请稍后重试":R==="structured"?"Failed to generate structured prompt, please try again later":"Failed to optimize prompt, please try again later")}finally{_.current===V&&(_.current=null),E.current=!1,J(!1)}},[I,i,R,pe,q,O,de,z,x,P,d]),We=a.useCallback(()=>{const w=S.trim();w&&(ye.trackPromptAction({action:"use_draft_as_current",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,prompt:w}),v(w),T(""))},[z,x,R,S]),Ee=a.useCallback(()=>{const w=(S||I).trim();if(!w){Ke.warning(i==="zh"?"没有可回填的提示词":"There is no prompt to apply");return}ye.trackPromptAction({action:"apply",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,prompt:w}),c(w),Re()},[I,z,x,Re,i,R,c,S]);a.useEffect(()=>{e&&(me(),v(r),C(""),T(""),B(hn()),X(null),U(N))},[N,e,r,me]),a.useEffect(()=>()=>{var w;(w=_.current)==null||w.abort(),_.current=null,E.current=!1},[]),a.useEffect(()=>{if(!ee)return;const w=V=>{var D;const b=V.target;b instanceof Node&&((D=M.current)!=null&&D.contains(b))||b instanceof Element&&b.closest(".prompt-optimize-dialog__history-btn")||X(null)};return document.addEventListener("mousedown",w,!0),()=>{document.removeEventListener("mousedown",w,!0)}},[ee]);const Te=i==="zh"?R==="structured"?"例如:突出时间轴结构、把区域与数量拆开、保留标题与图例、输出 JSON 不要解释...":"例如:更电影感、补充镜头语言、减少冗余、强调主体与光线...":R==="structured"?"For example: emphasize timeline structure, split regions and counts, preserve titles and legends, output JSON only...":"For example: make it more cinematic, add camera language, reduce redundancy, emphasize subject and lighting...",Ye=I.trim().length>0,$e=(S.length>0?S:I).trim().length>0,ve=S.length>0,Ie=a.useMemo(()=>K.slice(0,xl).map(w=>({id:w.id,content:w.content,pinned:w.pinned,modelType:w.modelType})),[K]),he=a.useMemo(()=>Q.map(w=>({id:w.id,content:w.content})),[Q]),ze=a.useMemo(()=>`prompt-optimize-dialog-${p.replace(/[^a-zA-Z0-9_-]/g,"")}`,[p]),De=i==="zh"?R==="structured"?"结构化提示词":"提示词优化":R==="structured"?"Structured Prompt":"Prompt Optimization",He=a.useMemo(()=>{const w=$?16:48,V=Math.max(280,re-w),b=Math.max(320,fe-w),D=ve?1120:680,W=ve?760:680,G=Math.max(280,Math.min(D,V)),Y=Math.max(320,Math.min(W,b));return{width:G,height:Y,minWidth:Math.min(ve?640:320,G),minHeight:Math.min(420,Y)}},[ve,$,fe,re]),Be=a.useCallback(w=>{w==="current"?ie():B(hn()),ye.trackPromptAction({action:"toggle_history",surface:"prompt_optimize_dialog",promptType:w==="current"?z||x:void 0,mode:R,metadata:{panel:w}}),X(V=>V===w?null:w)},[z,x,R,ie]),Ge=a.useCallback(w=>{v(w.content),X(null)},[]),Qe=a.useCallback(w=>{T(w.content),X(null)},[]),Ne=a.useCallback(w=>{ye.trackPromptAction({action:"mode_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:w}),U(w)},[z,x]),L=(w,V,b)=>ee!==w?null:s.jsx("div",{ref:M,className:"prompt-optimize-dialog__history-panel",children:V.length>0?s.jsx(rl,{title:i==="zh"?"历史":"History",items:V,onSelect:b,language:i,analyticsSurface:`prompt_optimize_${w}_history`,analyticsPromptType:w==="current"?z||x:void 0,showCount:!0}):s.jsx("div",{className:"prompt-optimize-dialog__history-empty",children:i==="zh"?"暂无历史":"No history yet"})});return e?s.jsx(Oc,{id:ze,visible:e,title:De,icon:s.jsx(Dn,{size:16}),onClose:Re,width:He.width,height:He.height,minWidth:He.minWidth,minHeight:He.minHeight,x:"center",y:"center",maximizable:!$,minimizable:!1,resizable:!$,movable:!$,modal:!1,background:"#ffffff",className:`winbox-ai-generation winbox-prompt-optimize ${ve?"winbox-prompt-optimize--split":""}`,children:s.jsxs("div",{className:`prompt-optimize-dialog ${ve?"prompt-optimize-dialog--split":""}`,children:[s.jsxs("div",{className:`prompt-optimize-dialog__body ${ve?"prompt-optimize-dialog__body--split":""}`,children:[s.jsxs("div",{className:"prompt-optimize-dialog__form-pane",children:[s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--current",children:[s.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:h,children:i==="zh"?"当前提示词":"Current Prompt"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Be("current"),"aria-label":i==="zh"?"当前提示词历史":"Current prompt history",children:s.jsx(Is,{size:16})}),L("current",Ie,Ge)]}),s.jsx("textarea",{id:h,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--current",value:I,onChange:w=>v(w.target.value),placeholder:i==="zh"?"输入或编辑要优化的提示词...":"Enter or edit the prompt to optimize...",rows:5,disabled:P})]}),s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--requirements",children:[s.jsxs("div",{className:"prompt-optimize-dialog__label-row",children:[s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:g,children:i==="zh"?"补充要求":"Additional Requirements"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__history-btn",onClick:()=>Be("requirements"),"aria-label":i==="zh"?"补充要求历史":"Additional requirements history",children:s.jsx(Is,{size:16})}),L("requirements",he,Qe)]}),s.jsx("textarea",{id:g,className:"prompt-optimize-dialog__textarea",value:O,onChange:w=>T(w.target.value),placeholder:Te,rows:4,disabled:P})]})]}),ve&&s.jsx("div",{className:"prompt-optimize-dialog__result-pane",children:s.jsxs("div",{className:"prompt-optimize-dialog__section prompt-optimize-dialog__section--result",children:[s.jsx("div",{className:"prompt-optimize-dialog__result-header",children:s.jsx("label",{className:"prompt-optimize-dialog__label",htmlFor:y,children:i==="zh"?"优化结果草稿":"Optimized Draft"})}),s.jsx("textarea",{id:y,className:"prompt-optimize-dialog__textarea prompt-optimize-dialog__textarea--draft",value:S,onChange:w=>C(w.target.value),rows:6,disabled:P})]})})]}),s.jsxs("div",{className:`prompt-optimize-dialog__footer ${ve?"prompt-optimize-dialog__footer--split":""}`,children:[s.jsxs("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--form",children:[s.jsxs("div",{className:"prompt-optimize-dialog__footer-controls",children:[m&&s.jsxs("div",{className:"prompt-optimize-dialog__mode-switch","aria-label":i==="zh"?"输出模式":"Output Mode",children:[s.jsxs("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="polish"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>Ne("polish"),disabled:P,children:[s.jsx(Dn,{size:14}),s.jsx("span",{children:i==="zh"?"普通润色":"Polish"})]}),s.jsx("button",{type:"button",className:`prompt-optimize-dialog__mode-btn ${R==="structured"?"prompt-optimize-dialog__mode-btn--active":""}`,onClick:()=>Ne("structured"),disabled:P,children:s.jsx("span",{children:i==="zh"?"结构化 JSON":"Structured JSON"})})]}),s.jsx("div",{className:"prompt-optimize-dialog__model",children:s.jsx(Ti,{selectedModel:pe,selectedSelectionKey:is(pe,q),onSelect:(w,V)=>{const b=V||null;ye.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,model:w}),ae(w),ce(b),ks(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,w,b)},onSelectModel:w=>{const V=Vs(w);ye.trackPromptAction({action:"model_select",surface:"prompt_optimize_dialog",promptType:z||x,mode:R,model:w.id}),ae(w.id),ce(V),ks(Ht.PROMPT_OPTIMIZE_TEXT_MODEL,w.id,V)},language:i,models:be,placement:"up",header:i==="zh"?"选择文本模型 (↑↓ Tab)":"Select text model (↑↓ Tab)",disabled:P})})]}),s.jsxs("div",{className:"prompt-optimize-dialog__footer-buttons",children:[s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--primary",onClick:()=>void Me(),disabled:P||!Ye,children:i==="zh"?P?R==="structured"?"生成中...":"优化中...":R==="structured"?"生成结构化提示词":"开始优化":P?R==="structured"?"Generating...":"Optimizing...":R==="structured"?"Generate Structured Prompt":"Optimize"}),s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--apply",onClick:Ee,disabled:P||!$e,children:i==="zh"?"回填":"Apply"})]})]}),ve&&s.jsx("div",{className:"prompt-optimize-dialog__footer-actions prompt-optimize-dialog__footer-actions--result",children:s.jsx("button",{type:"button",className:"prompt-optimize-dialog__footer-btn prompt-optimize-dialog__footer-btn--secondary",onClick:We,disabled:P,children:i==="zh"?"用结果继续优化":"Use Draft to Refine"})})]})]})}):null},um=({disabled:t=!1,className:e,iconSize:n=16,tooltipPlacement:r="right",tooltipContent:i,language:o,onApply:c,onMouseDown:l,onOpenChange:m,...u})=>{const[d,p]=a.useState(!1),h=a.useCallback(f=>{p(f),m==null||m(f)},[m]),g=a.useCallback(f=>{c(f)},[c]),y=o==="zh"?"提示词优化":"Prompt optimization";return s.jsxs(s.Fragment,{children:[s.jsx(je,{content:i??y,placement:r,disabled:t,children:s.jsx("button",{type:"button",className:e||"prompt-optimize-button",disabled:t,onMouseDown:l,onClick:()=>h(!0),"aria-label":y,children:s.jsx(Dn,{size:n})})}),s.jsx(bl,{...u,language:o,open:d,onOpenChange:h,onApply:g})]})};function Bs(t){return t.toLowerCase().replace(/\s+/g,"").trim()}function Sl(t,e,n){const r=Bs(n);if(!r)return t;const i=new Map(e.map(o=>[o.id,o.name]));return t.filter(o=>{var l,m,u,d;return Bs([o.title,(l=o.metadata)==null?void 0:l.description,(m=o.metadata)==null?void 0:m.domain,(u=o.metadata)==null?void 0:u.sourceUrl,i.get(o.directoryId),...((d=o.metadata)==null?void 0:d.tags)||[]].filter(Boolean).join(" ")).includes(r)})}function Il(t,e,n){return!e.includes(t)&&e.length>=n}function kl(t,e="zh"){const n=t.map(o=>o.title||"未命名笔记"),r=n.join("、"),i=t.length>0;return{triggerLabel:i?e==="zh"?`知识库上下文,已选 ${t.length} 篇笔记`:`Knowledge context, ${t.length} notes selected`:e==="zh"?"选择知识库笔记":"Select knowledge notes",selectedTitleText:r,hoverTitle:e==="zh"?"已选知识库笔记":"Selected notes",noteTitles:n,shouldShowChips:!1,canClear:i,clearLabel:e==="zh"?"清除":"Clear",clearAriaLabel:e==="zh"?"清除已选知识库笔记":"Clear selected knowledge notes",addNoteLabel:e==="zh"?"添加笔记":"Add note",addNoteAriaLabel:e==="zh"?"打开知识库新建笔记":"Open knowledge base to add note",badgeText:i?String(t.length):void 0}}function Ml(t){if(!t)return"";try{return new Date(t).toLocaleDateString("zh-CN",{month:"2-digit",day:"2-digit"})}catch{return""}}const mm=({value:t,onChange:e,disabled:n=!1,label:r,language:i="zh",maxNotes:o=Ni,className:c="",variant:l="default",placement:m="down"})=>{const[u,d]=a.useState(!1),[p,h]=a.useState(!1),[g,y]=a.useState([]),[f,x]=a.useState([]),[z,N]=a.useState(""),O=a.useRef(null),T=a.useRef(null),[I,v]=a.useState({}),S=a.useMemo(()=>Ln(t,o),[o,t]),C=a.useMemo(()=>new Set(S.map(K=>K.noteId)),[S]),R=a.useMemo(()=>new Map(f.map(K=>[K.id,K.name])),[f]),U=a.useCallback(async()=>{h(!0);try{await Sn.initialize();const[K,de]=await Promise.all([Sn.getAllNoteMetas(),Sn.getAllDirectories()]);y([...K].sort((ie,ue)=>ue.updatedAt-ie.updatedAt)),x(de)}finally{h(!1)}},[]);a.useEffect(()=>{u&&U()},[U,u]),a.useEffect(()=>{if(!u)return;const K=de=>{var ue,xe;const ie=de.target;!((ue=O.current)!=null&&ue.contains(ie))&&!((xe=T.current)!=null&&xe.contains(ie))&&d(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[u]),a.useEffect(()=>{if(!u||l!=="compact"||!O.current)return;const K=()=>{var xe;const de=(xe=O.current)==null?void 0:xe.getBoundingClientRect();if(!de)return;const ie=Math.min(360,Math.max(240,window.innerWidth-32)),ue=Math.min(Math.max(16,de.left),window.innerWidth-ie-16);v({position:"fixed",top:"auto",bottom:window.innerHeight-de.top+8,left:ue,width:ie,zIndex:qn.DROPDOWN_PORTAL})};return K(),window.addEventListener("resize",K),window.addEventListener("scroll",K,!0),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0)}},[u,l]);const P=a.useMemo(()=>Sl(g,f,z),[f,g,z]),J=a.useCallback(K=>{const ie=C.has(K.id)?S.filter(ue=>ue.noteId!==K.id):[...S,Ei(K)];e(Ln(ie,o))},[o,e,C,S]),ee=a.useCallback(K=>{e(S.filter(de=>de.noteId!==K))},[e,S]),X=a.useCallback(K=>{K==null||K.stopPropagation(),e([])},[e]),Q=a.useCallback(K=>{if(K==null||K.stopPropagation(),n||typeof window>"u")return;const de={directoryName:"笔记",autoCreateNote:!0};window.__kbPendingNavigation=de,window.dispatchEvent(new CustomEvent("kb:open",{detail:{}})),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:de}))},300),d(!1)},[n]),B=r||(i==="zh"?"知识库上下文":"Knowledge Context"),_=i==="zh"?"搜索知识库笔记...":"Search notes...",E=i==="zh"?"暂无可选笔记":"No notes available",M=i==="zh"?"无匹配笔记":"No matching notes",$=l==="compact",re=kl(S,i),fe=u?s.jsxs("div",{ref:T,className:"knowledge-note-context-selector__dropdown",style:$?I:void 0,onMouseDown:K=>K.stopPropagation(),children:[s.jsxs("div",{className:"knowledge-note-context-selector__search",children:[s.jsx(Pi,{size:14}),s.jsx("input",{value:z,onChange:K=>N(K.target.value),placeholder:_,autoFocus:!0})]}),s.jsx("div",{className:"knowledge-note-context-selector__list",children:p?s.jsx("div",{className:"knowledge-note-context-selector__empty",children:i==="zh"?"加载中...":"Loading..."}):P.length>0?P.map(K=>{const de=C.has(K.id),ie=Il(K.id,S.map(xe=>xe.noteId),o),ue=R.get(K.directoryId);return s.jsxs("button",{type:"button",className:`knowledge-note-context-selector__item ${de?"knowledge-note-context-selector__item--selected":""}`,onClick:()=>!ie&&J(K),disabled:ie,children:[s.jsxs("span",{className:"knowledge-note-context-selector__item-main",children:[s.jsx("span",{className:"knowledge-note-context-selector__item-title",children:K.title||"未命名笔记"}),s.jsx("span",{className:"knowledge-note-context-selector__item-meta",children:[ue,Ml(K.updatedAt)].filter(Boolean).join(" · ")})]}),de?s.jsx(gn,{size:15}):null]},K.id)}):s.jsx("div",{className:"knowledge-note-context-selector__empty",children:g.length===0?E:M})}),s.jsxs("div",{className:"knowledge-note-context-selector__footer",children:[s.jsx("span",{className:"knowledge-note-context-selector__footer-text",children:i==="zh"?`最多选择 ${o} 篇,提交时按需读取正文`:`Up to ${o}; content is read on submit`}),s.jsxs("span",{className:"knowledge-note-context-selector__footer-actions",children:[s.jsxs("button",{type:"button",className:"knowledge-note-context-selector__footer-add",onClick:Q,disabled:n,"aria-label":re.addNoteAriaLabel,children:[s.jsx(gr,{size:12}),re.addNoteLabel]}),re.canClear?s.jsx("button",{type:"button",className:"knowledge-note-context-selector__footer-clear",onClick:X,disabled:n,"aria-label":re.clearAriaLabel,children:re.clearLabel}):null]})]})]}):null;return s.jsxs("div",{className:Ai("knowledge-note-context-selector",{"knowledge-note-context-selector--compact":$,"knowledge-note-context-selector--selected":S.length>0,"knowledge-note-context-selector--open":u,"knowledge-note-context-selector--placement-up":m==="up"},c),ref:O,children:[$?null:s.jsxs("div",{className:"knowledge-note-context-selector__header",children:[s.jsx("span",{className:"knowledge-note-context-selector__label",children:B}),S.length>0?s.jsx("button",{type:"button",className:"knowledge-note-context-selector__clear",onClick:X,disabled:n,children:i==="zh"?"清空":"Clear"}):null]}),s.jsxs("button",{type:"button",className:"knowledge-note-context-selector__trigger",onClick:()=>!n&&d(K=>!K),disabled:n,"aria-expanded":u,"aria-label":re.triggerLabel,title:$?re.selectedTitleText||re.triggerLabel:void 0,children:[s.jsx(Ri,{size:$?18:15}),$?re.badgeText?s.jsx("span",{className:"knowledge-note-context-selector__badge",children:re.badgeText}):null:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:S.length>0?i==="zh"?`已选 ${S.length} 篇笔记`:`${S.length} notes selected`:i==="zh"?"选择知识库笔记":"Select notes"}),s.jsx(zi,{size:15})]})]}),$&&S.length>0?s.jsxs("div",{className:"knowledge-note-context-selector__hover-summary","aria-label":i==="zh"?`已选知识库笔记:${re.selectedTitleText}`:`Selected knowledge notes: ${re.selectedTitleText}`,children:[s.jsx("div",{className:"knowledge-note-context-selector__hover-title",children:re.hoverTitle}),s.jsx("div",{className:"knowledge-note-context-selector__hover-list",children:S.map((K,de)=>s.jsx("div",{className:"knowledge-note-context-selector__hover-item",children:re.noteTitles[de]},K.noteId))})]}):null,!$&&S.length>0?s.jsx("div",{className:"knowledge-note-context-selector__chips",children:S.map(K=>s.jsxs("span",{className:"knowledge-note-context-selector__chip",children:[s.jsx("span",{children:K.title}),s.jsx("button",{type:"button",onClick:()=>ee(K.noteId),disabled:n,"aria-label":i==="zh"?"移除笔记":"Remove note",children:s.jsx(Mt,{size:12})})]},K.noteId))}):null,$&&fe?Rt.createPortal(fe,document.body):fe]})},pm=({visible:t,items:e,initialIndex:n=0,onClose:r,onIndexChange:i,showToolbar:o=!0,className:c="",showTitle:l=!0,videoAutoPlay:m=!0,videoLoop:u=!0})=>{const d=e.map((p,h)=>({id:`media-${h}`,url:p.url,type:p.type,title:p.title,alt:p.alt,posterUrl:p.posterUrl,duration:p.duration,prompt:p.prompt,tags:p.tags,artist:p.artist,album:p.album}));return s.jsx(mn,{visible:t,items:d,initialMode:"single",initialIndex:n,onClose:r,showThumbnails:e.length>1,className:c,showTitle:l,videoAutoPlay:m,videoLoop:u})};let cs=null;function Cl(t){cs=t}function yo(){return cs}async function Gs(t,e,n,r){if(r){const o=Math.round(window.innerWidth*.5);return Ms(t,[{title:r,body:e}],n,o),{width:o,height:120}}const i=Oi(e);if(i&&i.length>0){const o=Math.round(window.innerWidth*.5);Ms(t,i,n,o);const c=Math.min(i.length,3),l=Math.ceil(i.length/3);return{width:c*(o+20)-20,height:l*140-20}}return Yn.insertText(t,n,e),Mr(e)}async function qs(t,e,n,r){const i=r||{width:Ue.MEDIA_DEFAULT_SIZE,height:Ue.MEDIA_DEFAULT_SIZE};try{await lr(t,e,n,!1,i,!0,!0)}catch(o){throw console.error("[CanvasInsertion] insertImageFromUrl failed:",o),o}return i}async function Ks(t,e,n,r){if(r)return await Rn(t,e,n,!1,r,!0,!0),r;const i={width:Ue.MEDIA_DEFAULT_SIZE,height:Math.round(Ue.MEDIA_DEFAULT_SIZE*(9/16))};return await Rn(t,e,n,!1,i,!0,!0),i}async function Zs(t,e,n,r,i){const o=Fi({...i,width:r==null?void 0:r.width,height:r==null?void 0:r.height});return await Ui(t,e,{...i,width:o.width,height:o.height},n,!1,!0),o}async function Ys(t,e,n){const r=Cr(e),i=jr(r),o=Math.min(i.width,Ue.MEDIA_DEFAULT_SIZE),c=i.height/i.width,l=o*c,u={url:Tr(r),width:o,height:l};return Yn.insertImage(t,u,n),{width:o,height:l}}async function xo(t){const e=cs;if(!e)return console.error("[CanvasInsertion] Board is null!"),{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{items:n,verticalGap:r=Ue.DEFAULT_VERTICAL_GAP,horizontalGap:i=Ue.DEFAULT_HORIZONTAL_GAP}=t;if(!n||n.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{if(!t.startPoint&&n.length===1){const d=n[0];if(d.type==="image"||d.type==="video"){const p=await cr(e,d.content,d.type,d.dimensions);if(p)return{success:!0,data:{insertedCount:1,items:[{type:d.type,point:p.point}],firstElementPosition:p.point,firstElementSize:p.size},type:"text"}}}let o=t.startPoint;o||(o=Bn(e,{verticalGap:r,logPrefix:"CanvasInsertion"})),o||(o=Gn(e,{verticalGap:r,emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT);const c=Di(n);let l=o[1];const m=o[0],u=[];for(const d of c)if(d.length===1){const p=d[0];let h={width:Ue.MEDIA_DEFAULT_SIZE,height:225};p.type==="text"?h=Mr(p.content):p.type==="image"?h=p.dimensions||{width:Ue.MEDIA_DEFAULT_SIZE,height:Ue.MEDIA_DEFAULT_SIZE}:p.type==="video"?h=p.dimensions||{width:Ue.MEDIA_DEFAULT_SIZE,height:Math.round(Ue.MEDIA_DEFAULT_SIZE*(9/16))}:p.type==="audio"&&(h=p.dimensions||{width:$i,height:Li});const g=[m,l];if(p.type==="text")await Gs(e,p.content,g,p.label),l+=h.height+r;else if(p.type==="image"){const y=await qs(e,p.content,g,p.dimensions);l+=y.height+r}else if(p.type==="video")await Ks(e,p.content,g,p.dimensions),l+=h.height+r;else if(p.type==="audio"){const y=await Zs(e,p.content,g,p.dimensions,p.metadata);l+=y.height+r}else if(p.type==="svg"){const y=await Ys(e,p.content,g);l+=y.height+r}u.push({type:p.type,point:g})}else{let p=m,h=0;for(const g of d){const y=[p,l];if(g.type==="text"){const f=await Gs(e,g.content,y,g.label);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="image"){const f=await qs(e,g.content,y,g.dimensions);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="video")await Ks(e,g.content,y),h=Math.max(h,225),p+=Ue.MEDIA_DEFAULT_SIZE+i;else if(g.type==="audio"){const f=await Zs(e,g.content,y,g.dimensions,g.metadata);h=Math.max(h,f.height),p+=f.width+i}else if(g.type==="svg"){const f=await Ys(e,g.content,y);h=Math.max(h,f.height),p+=f.width+i}u.push({type:g.type,point:y})}l+=h+r}if(u.length>0){const d=u[0],p=[d.point[0]+Ue.MEDIA_DEFAULT_SIZE/2,d.point[1]+Ue.MEDIA_DEFAULT_SIZE/2];requestAnimationFrame(()=>{qt(e,p)})}return{success:!0,data:{insertedCount:u.length,items:u,firstElementPosition:u.length>0?u[0].point:void 0},type:"text"}}catch(o){return console.error("[CanvasInsertion] Failed to insert content:",o),{success:!1,error:`插入失败: ${o.message||"未知错误"}`,type:"error"}}}const _o={name:"insert_to_canvas",description:`将内容插入到画布工具。用于将AI生成的文本、图片、视频等内容插入到画布中。
11
11
 
12
12
  使用场景:
13
13
  - AI对话产生的Prompt需要显示在画布上
@@ -20,7 +20,7 @@ ${g.join(`
20
20
  - 水平布局:同组内容(相同groupId)从左到右排列,表示并列关系
21
21
 
22
22
  不适用场景:
23
- - 仅生成内容但不需要显示在画布上`,inputSchema:{type:"object",properties:{items:{type:"array",description:"要插入的内容列表",items:{type:"object",properties:{type:{type:"string",description:"内容类型:text(文本)、image(图片URL)、video(视频URL)、audio(音频URL)、svg(SVG代码)",enum:["text","image","video","audio","svg"]},content:{type:"string",description:"内容:文本内容或媒体URL"},label:{type:"string",description:"标签/描述(可选)"},groupId:{type:"string",description:"分组ID,相同groupId的内容会水平排列(可选)"},metadata:{type:"object",description:"可选元数据(音频卡片标题、封面、时长等)"}},required:["type","content"]}},verticalGap:{type:"number",description:"垂直间距(像素),默认50",default:50},horizontalGap:{type:"number",description:"水平间距(像素),默认20",default:20}},required:["items"]},execute:async t=>yo(t)};async function Cl(t,e,n,r,i){return yo({items:[{type:t,content:e,dimensions:r,metadata:i}],startPoint:n})}const pm=Object.freeze(Object.defineProperty({__proto__:null,canvasInsertionTool:xo,getCanvasBoard:wo,quickInsert:Cl,setCanvasBoard:Ml},Symbol.toStringTag,{value:"Module"})),jl=[{style:"scattered",labelZh:"散落",labelEn:"Scattered",description:"随机位置和旋转角度,模拟真实照片散落效果"},{style:"grid",labelZh:"网格",labelEn:"Grid",description:"整齐的网格排列,适合展示类场景"},{style:"circular",labelZh:"环形",labelEn:"Circular",description:"围绕中心点环形分布,适合突出中心主题"},{style:"inspiration-board",labelZh:"灵感图",labelEn:"Inspiration Board",description:"不规则大小的紧凑拼贴布局,适合创意灵感展示"}],$t={gridConfig:{rows:3,cols:3},layoutStyle:"scattered",imageSize:"1x1",imageQuality:"2k",layoutParams:{gap:20},scatteredConfig:{maxRotation:15,minScale:.85,maxScale:1.15,positionJitter:40},circularConfig:{centerIndex:-1,startAngle:-90}},Tl={imageCount:9,minWidthRatio:.7,maxWidthRatio:1.4,maxRotation:8,gap:15,imageQuality:"2k"},Nl={zh:(t,e)=>`创建一个边缘到边缘的灵感拼贴图(生产用),主题是"${t}",包含 ${e} 张图片。
23
+ - 仅生成内容但不需要显示在画布上`,inputSchema:{type:"object",properties:{items:{type:"array",description:"要插入的内容列表",items:{type:"object",properties:{type:{type:"string",description:"内容类型:text(文本)、image(图片URL)、video(视频URL)、audio(音频URL)、svg(SVG代码)",enum:["text","image","video","audio","svg"]},content:{type:"string",description:"内容:文本内容或媒体URL"},label:{type:"string",description:"标签/描述(可选)"},groupId:{type:"string",description:"分组ID,相同groupId的内容会水平排列(可选)"},metadata:{type:"object",description:"可选元数据(音频卡片标题、封面、时长等)"}},required:["type","content"]}},verticalGap:{type:"number",description:"垂直间距(像素),默认50",default:50},horizontalGap:{type:"number",description:"水平间距(像素),默认20",default:20}},required:["items"]},execute:async t=>xo(t)};async function jl(t,e,n,r,i){return xo({items:[{type:t,content:e,dimensions:r,metadata:i}],startPoint:n})}const hm=Object.freeze(Object.defineProperty({__proto__:null,canvasInsertionTool:_o,getCanvasBoard:yo,quickInsert:jl,setCanvasBoard:Cl},Symbol.toStringTag,{value:"Module"})),Tl=[{style:"scattered",labelZh:"散落",labelEn:"Scattered",description:"随机位置和旋转角度,模拟真实照片散落效果"},{style:"grid",labelZh:"网格",labelEn:"Grid",description:"整齐的网格排列,适合展示类场景"},{style:"circular",labelZh:"环形",labelEn:"Circular",description:"围绕中心点环形分布,适合突出中心主题"},{style:"inspiration-board",labelZh:"灵感图",labelEn:"Inspiration Board",description:"不规则大小的紧凑拼贴布局,适合创意灵感展示"}],$t={gridConfig:{rows:3,cols:3},layoutStyle:"scattered",imageSize:"1x1",imageQuality:"2k",layoutParams:{gap:20},scatteredConfig:{maxRotation:15,minScale:.85,maxScale:1.15,positionJitter:40},circularConfig:{centerIndex:-1,startAngle:-90}},Nl={imageCount:9,minWidthRatio:.7,maxWidthRatio:1.4,maxRotation:8,gap:15,imageQuality:"2k"},El={zh:(t,e)=>`创建一个边缘到边缘的灵感拼贴图(生产用),主题是"${t}",包含 ${e} 张图片。
24
24
 
25
25
  【关键要求 - 必须铺满画面】
26
26
  - 图片必须完全铺满整个画布,从左边缘到右边缘,从上边缘到下边缘
@@ -51,7 +51,7 @@ ${g.join(`
51
51
 
52
52
  【输出要求】
53
53
  - 横向布局,宽高比约 16:9
54
- - 整个画面必须被图片填满,无外部留白`},El={zh:(t,e,n)=>`创建一个边缘到边缘的 ${e}x${n} 网格拼贴图(生产用),主题是"${t}"。
54
+ - 整个画面必须被图片填满,无外部留白`},Pl={zh:(t,e,n)=>`创建一个边缘到边缘的 ${e}x${n} 网格拼贴图(生产用),主题是"${t}"。
55
55
 
56
56
  【关键要求 - 必须铺满画面】
57
57
  - 图片必须完全铺满整个画布,从左边缘到右边缘,从上边缘到下边缘
@@ -109,7 +109,7 @@ ${c.warnings.map(u=>` ⚠️ ${u}`).join(`
109
109
 
110
110
  ---
111
111
 
112
- `)}generateToolSchemas(){return this.getAllTools().map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}}))}clear(){this.tools.clear()}}const ls=Pt.getInstance();function Pl(t){const{width:e,height:n}=t,r=e/n;return r>1.5?{imageSize:"16x9",videoSize:"1280x720"}:r<.67?{imageSize:"9x16",videoSize:"720x1280"}:r>=.9&&r<=1.1?{imageSize:"1x1",videoSize:"1024x1024"}:r>1.1&&r<=1.5?{imageSize:"4x3",videoSize:"1280x720"}:{imageSize:"3x4",videoSize:"720x1280"}}function _o(){return`# 角色定义
112
+ `)}generateToolSchemas(){return this.getAllTools().map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}}))}clear(){this.tools.clear()}}const ls=Pt.getInstance();function Al(t){const{width:e,height:n}=t,r=e/n;return r>1.5?{imageSize:"16x9",videoSize:"1280x720"}:r<.67?{imageSize:"9x16",videoSize:"720x1280"}:r>=.9&&r<=1.1?{imageSize:"1x1",videoSize:"1024x1024"}:r>1.1&&r<=1.5?{imageSize:"4x3",videoSize:"1280x720"}:{imageSize:"3x4",videoSize:"720x1280"}}function vo(){return`# 角色定义
113
113
  你是一个专门执行图片和视频生成任务的工具调用器。
114
114
 
115
115
  ## 立即示例(按此格式响应)
@@ -277,7 +277,7 @@ ${ls.generateToolsDescription()}
277
277
 
278
278
  ✅ 正确:详细提示词直接使用
279
279
  用户:夕阳下的海滩,海鸥在飞翔
280
- {"content": "生成海滩夕阳场景", "next": [{"mcp": "generate_image", "args": {"prompt": "夕阳下的海滩,海鸥在飞翔", "size": "16x9"}}]}`}function Al(t,e){const n=Array.from({length:t},(o,c)=>{const l=`[图片${c+1}]`;if(e&&e[c]){const m=e[c];return`${l}(${m.width}x${m.height})`}return l}).join("、"),r=Array.from({length:t},(o,c)=>`"[图片${c+1}]"`).join(", ");let i="";if(t===1&&e&&e[0]){const o=e[0],{imageSize:c,videoSize:l}=Pl(o);i=`
280
+ {"content": "生成海滩夕阳场景", "next": [{"mcp": "generate_image", "args": {"prompt": "夕阳下的海滩,海鸥在飞翔", "size": "16x9"}}]}`}function Rl(t,e){const n=Array.from({length:t},(o,c)=>{const l=`[图片${c+1}]`;if(e&&e[c]){const m=e[c];return`${l}(${m.width}x${m.height})`}return l}).join("、"),r=Array.from({length:t},(o,c)=>`"[图片${c+1}]"`).join(", ");let i="";if(t===1&&e&&e[0]){const o=e[0],{imageSize:c,videoSize:l}=Al(o);i=`
281
281
 
282
282
  **尺寸推断规则(重要)**:
283
283
  - 参考图片尺寸为 ${o.width}x${o.height}
@@ -298,11 +298,11 @@ ${o}
298
298
  **使用方法**:
299
299
  - 在 \`referenceImages\` 参数中使用占位符数组:\`"referenceImages": [${r}]\`
300
300
  - 系统会自动将占位符替换为真实图片 URL
301
- - prompt 中描述你希望如何处理这些图片${i}`}function Xs(t,e){let n=t;return n=n.replace(/\[图片(\d+)\]/g,(r,i)=>{const o=parseInt(i,10)-1;return o>=0&&o<e.length?e[o]:r}),n=n.replace(/\[Image\s*(\d+)\]/gi,(r,i)=>{const o=parseInt(i,10)-1;return o>=0&&o<e.length?e[o]:r}),n}function Rl(t,e){var i;if(!e.trim())return t;const n=(i=[...t].map((o,c)=>({message:o,index:c})).reverse().find(({message:o})=>o.role==="user"))==null?void 0:i.index,r={type:"text",text:e};return n==null?[...t,{role:"user",content:[r]}]:t.map((o,c)=>c===n?{...o,content:[...o.content,r]}:o)}function zl(t){const e=[];e.push("## 生成配置"),e.push("");const n=t.model.isExplicit?"(用户指定)":"(默认)",i={text:"Agent 智能模式",image:"图片生成",video:"视频生成"}[t.model.type]||"Agent 智能模式";e.push(`- **模式**: ${i}`),t.model.type==="text"?e.push(`- **文本模型**: ${t.model.id} ${n}`):e.push(`- **当前模型**: ${t.model.id} ${n}`),t.defaultModels&&(t.defaultModels.image&&e.push(`- **图片生成模型**: ${t.defaultModels.image}`),t.defaultModels.video&&e.push(`- **视频生成模型**: ${t.defaultModels.video}`),t.defaultModels.audio&&e.push(`- **音频生成模型**: ${t.defaultModels.audio}`)),e.push(`- **数量**: ${t.params.count}`),t.params.size&&e.push(`- **尺寸**: ${t.params.size}(默认值,如用户指令中有尺寸描述则优先使用用户的)`),t.params.duration&&e.push(`- **时长**: ${t.params.duration}秒`),e.push(""),t.selection.texts.length>0&&(e.push("## 选中的文本内容(作为生成提示词)"),e.push(""),e.push("```"),e.push(t.selection.texts.join(`
301
+ - prompt 中描述你希望如何处理这些图片${i}`}function Xs(t,e){let n=t;return n=n.replace(/\[图片(\d+)\]/g,(r,i)=>{const o=parseInt(i,10)-1;return o>=0&&o<e.length?e[o]:r}),n=n.replace(/\[Image\s*(\d+)\]/gi,(r,i)=>{const o=parseInt(i,10)-1;return o>=0&&o<e.length?e[o]:r}),n}function zl(t,e){var i;if(!e.trim())return t;const n=(i=[...t].map((o,c)=>({message:o,index:c})).reverse().find(({message:o})=>o.role==="user"))==null?void 0:i.index,r={type:"text",text:e};return n==null?[...t,{role:"user",content:[r]}]:t.map((o,c)=>c===n?{...o,content:[...o.content,r]}:o)}function Dl(t){const e=[];e.push("## 生成配置"),e.push("");const n=t.model.isExplicit?"(用户指定)":"(默认)",i={text:"Agent 智能模式",image:"图片生成",video:"视频生成"}[t.model.type]||"Agent 智能模式";e.push(`- **模式**: ${i}`),t.model.type==="text"?e.push(`- **文本模型**: ${t.model.id} ${n}`):e.push(`- **当前模型**: ${t.model.id} ${n}`),t.defaultModels&&(t.defaultModels.image&&e.push(`- **图片生成模型**: ${t.defaultModels.image}`),t.defaultModels.video&&e.push(`- **视频生成模型**: ${t.defaultModels.video}`),t.defaultModels.audio&&e.push(`- **音频生成模型**: ${t.defaultModels.audio}`)),e.push(`- **数量**: ${t.params.count}`),t.params.size&&e.push(`- **尺寸**: ${t.params.size}(默认值,如用户指令中有尺寸描述则优先使用用户的)`),t.params.duration&&e.push(`- **时长**: ${t.params.duration}秒`),e.push(""),t.selection.texts.length>0&&(e.push("## 选中的文本内容(作为生成提示词)"),e.push(""),e.push("```"),e.push(t.selection.texts.join(`
302
302
  `)),e.push("```"),e.push("")),t.userInstruction&&(e.push("## 用户指令"),e.push(""),e.push(t.userInstruction),e.push(""));const o=t.selection.images.length>0||t.selection.graphics.length>0,c=t.selection.videos.length>0;if(o||c){if(e.push("## 参考素材(已把url替换为占位符,严格返回即可)"),e.push(""),o){const m=[...t.selection.images,...t.selection.graphics].map((u,d)=>`[图片${d+1}]`).join("、");e.push(`- **参考图片**: ${m}`)}if(c){const l=t.selection.videos.map((m,u)=>`[视频${u+1}]`).join("、");e.push(`- **参考视频**: ${l}`)}e.push("")}return!t.userInstruction&&t.selection.texts.length===0&&t.finalPrompt&&(e.push("## 生成提示词"),e.push(""),e.push(t.finalPrompt),e.push("")),e.join(`
303
- `)}function Dl(t,e){const n={};for(const[r,i]of Object.entries(t.arguments))if((r==="referenceImages"||r==="inputReferences")&&Array.isArray(i)){const o=i.map(c=>{if(typeof c=="string"){const l=c.match(/^\[图片(\d+)\]$/),m=c.match(/^\[Image\s*(\d+)\]$/i),u=l||m;if(u){const d=parseInt(u[1],10)-1;if(d>=0&&d<e.length)return e[d]}return c}else if(c&&typeof c=="object"&&c.url){const l=c.url;if(typeof l=="string"){const m=l.match(/^\[图片(\d+)\]$/),u=l.match(/^\[Image\s*(\d+)\]$/i),d=m||u;if(d){const p=parseInt(d[1],10)-1;if(p>=0&&p<e.length)return{...c,url:e[p]}}}}return c}).filter(Boolean);n[r]=o.length>0?r==="referenceImages"?o.map(c=>typeof c=="string"?c:c.url):o:e}else(r==="referenceImage"||r==="inputReference")&&typeof i=="string"?n[r]=Xs(i,e):Array.isArray(i)?n[r]=i.map(o=>typeof o=="string"?Xs(o,e):o):n[r]=i;return!n.referenceImages&&!n.inputReferences&&e.length>0?(n.referenceImages=e,n.inputReferences=e.map(r=>({url:r}))):n.referenceImages&&!n.inputReferences&&(n.inputReferences=n.referenceImages.map(r=>({url:r}))),{...t,arguments:n}}class At{constructor(){}static getInstance(){return At.instance||(At.instance=new At),At.instance}async execute(e,n={}){var h;const{model:r,modelRef:i,onChunk:o,onToolCall:c,signal:l,maxIterations:m=3,messages:u}=n,d=Date.now(),p=[];ye.track("agent_workflow_start",{modelType:e.model.type,modelId:e.model.id,hasReferenceImages:e.selection.images.length>0,hasSelectedTexts:e.selection.texts.length>0,triggerSource:e.userInstruction?"user_input":"selection"});try{const g=[...e.selection.images,...e.selection.graphics],y=at.get(),f=i||r||y.textModelName||e.model.id,x=Xn("text",f),z=Jn(x==null?void 0:x.binding),N=Qn(x==null?void 0:x.binding);let O;if(u&&u.length>0)O=u.map(S=>({role:S.role,content:typeof S.content=="string"?[{type:"text",text:S.content}]:S.content}));else{let S=_o();g.length>0&&(S+=Al(g.length,e.selection.imageDimensions));const C=zl(e);O=[{role:"system",content:[{type:"text",text:S}]},{role:"user",content:[{type:"text",text:C}]}]}if((h=e.knowledgeContextRefs)!=null&&h.length){const{contextBlock:S}=await Ui(e.knowledgeContextRefs);S&&(O=Rl(O,`
303
+ `)}function Ll(t,e){const n={};for(const[r,i]of Object.entries(t.arguments))if((r==="referenceImages"||r==="inputReferences")&&Array.isArray(i)){const o=i.map(c=>{if(typeof c=="string"){const l=c.match(/^\[图片(\d+)\]$/),m=c.match(/^\[Image\s*(\d+)\]$/i),u=l||m;if(u){const d=parseInt(u[1],10)-1;if(d>=0&&d<e.length)return e[d]}return c}else if(c&&typeof c=="object"&&c.url){const l=c.url;if(typeof l=="string"){const m=l.match(/^\[图片(\d+)\]$/),u=l.match(/^\[Image\s*(\d+)\]$/i),d=m||u;if(d){const p=parseInt(d[1],10)-1;if(p>=0&&p<e.length)return{...c,url:e[p]}}}}return c}).filter(Boolean);n[r]=o.length>0?r==="referenceImages"?o.map(c=>typeof c=="string"?c:c.url):o:e}else(r==="referenceImage"||r==="inputReference")&&typeof i=="string"?n[r]=Xs(i,e):Array.isArray(i)?n[r]=i.map(o=>typeof o=="string"?Xs(o,e):o):n[r]=i;return!n.referenceImages&&!n.inputReferences&&e.length>0?(n.referenceImages=e,n.inputReferences=e.map(r=>({url:r}))):n.referenceImages&&!n.inputReferences&&(n.inputReferences=n.referenceImages.map(r=>({url:r}))),{...t,arguments:n}}class At{constructor(){}static getInstance(){return At.instance||(At.instance=new At),At.instance}async execute(e,n={}){var h;const{model:r,modelRef:i,onChunk:o,onToolCall:c,signal:l,maxIterations:m=3,messages:u}=n,d=Date.now(),p=[];ye.track("agent_workflow_start",{modelType:e.model.type,modelId:e.model.id,hasReferenceImages:e.selection.images.length>0,hasSelectedTexts:e.selection.texts.length>0,triggerSource:e.userInstruction?"user_input":"selection"});try{const g=[...e.selection.images,...e.selection.graphics],y=at.get(),f=i||r||y.textModelName||e.model.id,x=Xn("text",f),z=Jn(x==null?void 0:x.binding),N=Qn(x==null?void 0:x.binding);let O;if(u&&u.length>0)O=u.map(S=>({role:S.role,content:typeof S.content=="string"?[{type:"text",text:S.content}]:S.content}));else{let S=vo();g.length>0&&(S+=Rl(g.length,e.selection.imageDimensions));const C=Dl(e);O=[{role:"system",content:[{type:"text",text:S}]},{role:"user",content:[{type:"text",text:C}]}]}if((h=e.knowledgeContextRefs)!=null&&h.length){const{contextBlock:S}=await Wi(e.knowledgeContextRefs);S&&(O=zl(O,`
304
304
 
305
- ${S}`))}if(z&&g.length>0&&!Wi(O)){const S=await Tr(g,N);O=Nr(O,S)}let T=0,I="";const b=(typeof f=="string"?f:f==null?void 0:f.modelId)||y.textModelName;for(;T<m;){T++;let S="";const C=Date.now(),R=await Zt.sendChat(O,P=>{S=P,o==null||o(P)},l,f);R.choices&&R.choices.length>0&&(S=R.choices[0].message.content||S);const U=Er(S);if(I=Pr(S)||S,U.length===0)break;for(const P of U){const J=g.length>0?Dl(P,g):P;p.push(J.name),ye.track("mcp_tool_execution",{toolName:J.name,hasArguments:Object.keys(J.arguments).length>0}),c==null||c(J)}return ye.track("agent_workflow_success",{duration:Date.now()-d,toolsExecuted:p,toolCount:p.length,iterations:T}),{success:!0,response:I,toolResults:[],model:r}}return ye.track("agent_workflow_success",{duration:Date.now()-d,toolsExecuted:[],toolCount:0,iterations:T}),{success:!0,response:I,toolResults:[],model:r}}catch(g){return console.error("[AgentExecutor] Execution failed:",g),ye.track("agent_workflow_failed",{duration:Date.now()-d,error:g.message||"Unknown error",toolsExecuted:p}),{success:!1,error:g.message||"Agent 执行失败",model:r}}}}const Ll=At.getInstance(),$l={generate_image:"image",generate_grid_image:"image",generate_photo_wall:"image",generate_inspiration_board:"image",generate_video:"video",generate_long_video:"video",generate_audio:"audio"};function bo(t){return t?$l[t]:void 0}function vo(t,e,n){if(t==="generate_ppt")return delete e.imageModel,delete e.imageModelRef,Ol(e,n),e;const r=bo(t);if(!r)return e;const i=Fl(r,n);if(!i)return e;const o=Ul(r,i,n),c=typeof e.model=="string"&&e.model.trim()?e.model.trim():void 0;return n.overrideSpecifiedModel||!c||!Wl(c,r)?(e.model=i,o?e.modelRef=o:delete e.modelRef,e):(o&&o.modelId===c?e.modelRef=o:delete e.modelRef,e)}function Ol(t,e){var n,r;((n=e.contextModel)==null?void 0:n.type)!=="text"||!e.contextModel.id||(t.textModel=e.contextModel.id,((r=e.contextModelRef)==null?void 0:r.modelId)===e.contextModel.id?t.textModelRef=e.contextModelRef:delete t.textModelRef)}function Fl(t,e){var r,i,o;const n=(r=e.defaultModels)==null?void 0:r[t];return n||(((i=e.contextModel)==null?void 0:i.type)===t&&e.contextModel.id?e.contextModel.id:(o=e.fallbackModels)==null?void 0:o[t])}function Ul(t,e,n){var i,o,c;const r=(i=n.defaultModelRefs)==null?void 0:i[t];return(r==null?void 0:r.modelId)===e?r:((o=n.contextModel)==null?void 0:o.type)===t&&((c=n.contextModelRef)==null?void 0:c.modelId)===e?n.contextModelRef:null}function Wl(t,e){const n=Hi(t);return!n||n===e}const Hl=({items:t,language:e="zh",enableHoverPreview:n=!0,className:r,onRemove:i,removableStartIndex:o=0})=>{const[c,l]=a.useState(null),m=a.useCallback((d,p)=>{if(!n)return;const h=p.currentTarget.getBoundingClientRect(),g=h.left+h.width/2,y=h.top-10;l({type:d.type,url:d.url,text:d.text,x:g,y})},[n]),u=a.useCallback(()=>{l(null)},[]);return t.length===0?null:s.jsxs(s.Fragment,{children:[n&&c&&Vi.createPortal(s.jsxs("div",{className:`selected-content-preview__hover selected-content-preview__hover--${c.type}`,style:{left:`${c.x}px`,top:`${c.y}px`,transform:"translate(-50%, -100%)"},children:[(c.type==="image"||c.type==="graphics")&&c.url&&s.jsx("img",{src:c.url,alt:"Preview"}),c.type==="video"&&c.url&&s.jsx("div",{className:"selected-content-preview__hover-video",children:s.jsx("video",{src:c.url,controls:!0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0})}),c.type==="text"&&c.text&&s.jsxs("div",{className:"selected-content-preview__hover-text",children:[s.jsxs("div",{className:"selected-content-preview__hover-text-header",children:[s.jsx(Cs,{size:16}),s.jsx("span",{children:e==="zh"?"文字内容":"Text Content"})]}),s.jsx("div",{className:"selected-content-preview__hover-text-content",children:c.text})]})]}),document.body),s.jsx("div",{className:`selected-content-preview ${r||""}`,children:t.map((d,p)=>{const h=i&&p<o;return s.jsxs("div",{className:`selected-content-preview__item selected-content-preview__item--${d.type}`,onMouseEnter:g=>m(d,g),onMouseLeave:u,children:[d.type==="text"?s.jsxs("div",{className:"selected-content-preview__text",children:[s.jsx(Cs,{size:14,className:"selected-content-preview__text-icon"}),s.jsx("span",{className:"selected-content-preview__text-content",children:d.text&&d.text.length>20?`${d.text.substring(0,20)}...`:d.text})]}):d.type==="video"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"selected-content-preview__video-placeholder",children:s.jsx(Bi,{size:20})}),s.jsx("div",{className:"selected-content-preview__video-overlay",children:s.jsx(yr,{size:16,fill:"white"})})]}):s.jsx("img",{src:d.url,alt:d.name}),d.type==="graphics"&&s.jsx("span",{className:"selected-content-preview__label",children:e==="zh"?"图形":"Graphics"}),d.type==="video"&&s.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--video",children:e==="zh"?"视频":"Video"}),h&&s.jsx(je,{content:e==="zh"?"移除":"Remove",showArrow:!1,children:s.jsx("button",{className:"selected-content-preview__remove-btn",onClick:g=>{g.stopPropagation(),i(p)},onMouseDown:g=>g.preventDefault(),children:s.jsx(Mt,{size:12})})})]},`${d.type}-${p}`)})})]})};function Wt(t){return t.tagName==="TEXTAREA"||t.tagName==="INPUT"}function Vl(t){const e=t.selectionStart||0,n=t.selectionEnd||0;return t.value.substring(e,n)}function So(t){const e=window.getSelection();if(!e||e.rangeCount===0)return"";const n=e.getRangeAt(0);return t.contains(n.commonAncestorContainer)?e.toString():""}function En(t){return Wt(t)?Vl(t):So(t)}function Bl(t,e={}){const{enableCopy:n=!0,stopPropagation:r=!0}=e,i=a.useRef(null);return a.useEffect(()=>{const o=t.current;if(!o)return;const c=f=>!f||!(f instanceof HTMLElement)?!1:!!(["BUTTON","A","INPUT","SELECT","TEXTAREA","LABEL"].includes(f.tagName)||f.onclick||f.getAttribute("role")==="button"||f.closest('button, a, [role="button"], [onclick]')),l=()=>{const f=window.getSelection();return f!==null&&f.toString().length>0},m=f=>{r&&(c(f.target)||l()&&f.stopPropagation())},u=f=>{r&&(c(f.target)||f.stopPropagation())},d=f=>{const x=(f.ctrlKey||f.metaKey)&&f.key==="c",z=(f.ctrlKey||f.metaKey)&&f.key==="x";if(n&&(x||z)){const N=En(o);N&&Ar(N).then(()=>{}).catch(O=>{console.error("Failed to copy text:",O)}),r&&f.stopPropagation()}},p=f=>{if(n){const x=En(o);x&&f.clipboardData&&(f.clipboardData.setData("text/plain",x),f.preventDefault())}r&&f.stopPropagation()},h=f=>{if(n){const x=En(o);x&&f.clipboardData&&f.clipboardData.setData("text/plain",x)}r&&f.stopPropagation()},g=()=>{if(Wt(o)){const f=o.selectionStart||0,x=o.selectionEnd||0;f!==x&&(i.current={text:o.value.substring(f,x),start:f,end:x})}else{const f=So(o);f&&(i.current={text:f})}},y=()=>{Wt(o)||g()};return o.addEventListener("pointerdown",u),o.addEventListener("mousedown",u),o.addEventListener("pointerup",m),o.addEventListener("pointermove",m),o.addEventListener("mouseup",m),o.addEventListener("click",m),o.addEventListener("keydown",d),o.addEventListener("copy",p),o.addEventListener("cut",h),Wt(o)?o.addEventListener("select",g):document.addEventListener("selectionchange",y),()=>{o.removeEventListener("pointerdown",u),o.removeEventListener("mousedown",u),o.removeEventListener("pointerup",m),o.removeEventListener("pointermove",m),o.removeEventListener("mouseup",m),o.removeEventListener("click",m),o.removeEventListener("keydown",d),o.removeEventListener("copy",p),o.removeEventListener("cut",h),Wt(o)?o.removeEventListener("select",g):document.removeEventListener("selectionchange",y)}},[t,n,r]),{lastSelection:i.current}}function ds(){const t=at.get();return(t==null?void 0:t.videoModelName)||Yt()}function Gl(){const t=new Set;return Object.values(Ct).forEach(e=>{e.durationOptions.forEach(n=>t.add(n.value))}),Array.from(t).sort((e,n)=>parseInt(e)-parseInt(n))}function ql(){const t=new Set;return Object.values(Ct).forEach(e=>{e.sizeOptions.forEach(n=>t.add(n.value))}),Array.from(t)}async function Kl(t){const{prompt:e,model:n="veo3",modelRef:r,seconds:i="8",size:o="1280x720",referenceImages:c,params:l}=t,m=yn(e);if(m)return m;try{const u=n,d=qi("video",u,r||null);if(!d||d.kind!=="video")return{success:!1,error:`未找到可用的视频适配器: ${u}`,type:"error"};const p=i?Number(i):void 0,h=await d.generateVideo(Ki("video",r||u),{prompt:e,size:o,model:u,modelRef:r||null,duration:Number.isFinite(p)?p:void 0,referenceImages:c,params:l}),g=h.url;return g?{success:!0,data:{url:g,format:h.format||"mp4",prompt:e,model:n,seconds:i,size:o},type:"video"}:{success:!1,error:"API 未返回有效的视频 URL",type:"error"}}catch(u){return console.error("[VideoGenerationTool] Generation failed:",u),zr(u,"视频生成失败")}}function Zl(t){const e=t.model||"veo3",n=Ct[e]||Ct.veo3,r=Rr(t.referenceImages);return{taskType:xt.VIDEO,resultType:"video",getDefaultModel:ds,logPrefix:"VideoGenerationTool",buildTaskPayload:()=>({prompt:t.prompt,size:t.size||"16x9",duration:parseInt(t.seconds||n.defaultDuration,10),model:e,modelRef:t.modelRef||null,uploadedImages:r&&r.length>0?r:void 0,referenceImages:t.referenceImages&&t.referenceImages.length>0?t.referenceImages:void 0,params:t.params,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs}),buildResultData:()=>({size:t.size||"16x9",duration:parseInt(t.seconds||n.defaultDuration,10)})}}const us={name:"generate_video",description:`生成视频工具。根据用户的文字描述生成视频。
305
+ ${S}`))}if(z&&g.length>0&&!Hi(O)){const S=await Nr(g,N);O=Er(O,S)}let T=0,I="";const v=(typeof f=="string"?f:f==null?void 0:f.modelId)||y.textModelName;for(;T<m;){T++;let S="";const C=Date.now(),R=await Zt.sendChat(O,P=>{S=P,o==null||o(P)},l,f);R.choices&&R.choices.length>0&&(S=R.choices[0].message.content||S);const U=Pr(S);if(I=Ar(S)||S,U.length===0)break;for(const P of U){const J=g.length>0?Ll(P,g):P;p.push(J.name),ye.track("mcp_tool_execution",{toolName:J.name,hasArguments:Object.keys(J.arguments).length>0}),c==null||c(J)}return ye.track("agent_workflow_success",{duration:Date.now()-d,toolsExecuted:p,toolCount:p.length,iterations:T}),{success:!0,response:I,toolResults:[],model:r}}return ye.track("agent_workflow_success",{duration:Date.now()-d,toolsExecuted:[],toolCount:0,iterations:T}),{success:!0,response:I,toolResults:[],model:r}}catch(g){return console.error("[AgentExecutor] Execution failed:",g),ye.track("agent_workflow_failed",{duration:Date.now()-d,error:g.message||"Unknown error",toolsExecuted:p}),{success:!1,error:g.message||"Agent 执行失败",model:r}}}}const $l=At.getInstance(),Ol={generate_image:"image",generate_grid_image:"image",generate_photo_wall:"image",generate_inspiration_board:"image",generate_video:"video",generate_long_video:"video",generate_audio:"audio"};function bo(t){return t?Ol[t]:void 0}function So(t,e,n){if(t==="generate_ppt")return delete e.imageModel,delete e.imageModelRef,Fl(e,n),e;const r=bo(t);if(!r)return e;const i=Ul(r,n);if(!i)return e;const o=Wl(r,i,n),c=typeof e.model=="string"&&e.model.trim()?e.model.trim():void 0;return n.overrideSpecifiedModel||!c||!Hl(c,r)?(e.model=i,o?e.modelRef=o:delete e.modelRef,e):(o&&o.modelId===c?e.modelRef=o:delete e.modelRef,e)}function Fl(t,e){var n,r;((n=e.contextModel)==null?void 0:n.type)!=="text"||!e.contextModel.id||(t.textModel=e.contextModel.id,((r=e.contextModelRef)==null?void 0:r.modelId)===e.contextModel.id?t.textModelRef=e.contextModelRef:delete t.textModelRef)}function Ul(t,e){var r,i,o;const n=(r=e.defaultModels)==null?void 0:r[t];return n||(((i=e.contextModel)==null?void 0:i.type)===t&&e.contextModel.id?e.contextModel.id:(o=e.fallbackModels)==null?void 0:o[t])}function Wl(t,e,n){var i,o,c;const r=(i=n.defaultModelRefs)==null?void 0:i[t];return(r==null?void 0:r.modelId)===e?r:((o=n.contextModel)==null?void 0:o.type)===t&&((c=n.contextModelRef)==null?void 0:c.modelId)===e?n.contextModelRef:null}function Hl(t,e){const n=Vi(t);return!n||n===e}function Js(t,e){if(!t.url)return null;if(!t.maskImage)return s.jsx("img",{src:t.url,alt:t.name});const n=t.width&&t.height&&t.width>0&&t.height>0?{"--mask-pair-aspect":String(t.width*2/t.height)}:void 0;return s.jsxs("div",{className:`${e}__media-pair`,style:n,children:[s.jsx("img",{src:t.url,alt:t.name}),s.jsx("div",{className:`${e}__mask-thumb`,children:s.jsx("img",{src:t.maskImage,alt:`${t.name} mask`})})]})}const Vl=({items:t,language:e="zh",enableHoverPreview:n=!0,className:r,onRemove:i,removableStartIndex:o=0})=>{const[c,l]=a.useState(null),m=a.useCallback((d,p)=>{if(!n)return;const h=p.currentTarget.getBoundingClientRect(),g=h.left+h.width/2,y=h.top-10;l({type:d.type,url:d.url,maskImage:d.maskImage,width:d.width,height:d.height,text:d.text,x:g,y})},[n]),u=a.useCallback(()=>{l(null)},[]);return t.length===0?null:s.jsxs(s.Fragment,{children:[n&&c&&Bi.createPortal(s.jsxs("div",{className:`selected-content-preview__hover selected-content-preview__hover--${c.type}`,style:{left:`${c.x}px`,top:`${c.y}px`,transform:"translate(-50%, -100%)"},children:[(c.type==="image"||c.type==="graphics")&&c.url&&Js({url:c.url,maskImage:c.maskImage,width:c.width,height:c.height,name:"Preview"},"selected-content-preview"),c.type==="video"&&c.url&&s.jsx("div",{className:"selected-content-preview__hover-video",children:s.jsx("video",{src:c.url,controls:!0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0})}),c.type==="text"&&c.text&&s.jsxs("div",{className:"selected-content-preview__hover-text",children:[s.jsxs("div",{className:"selected-content-preview__hover-text-header",children:[s.jsx(Cs,{size:16}),s.jsx("span",{children:e==="zh"?"文字内容":"Text Content"})]}),s.jsx("div",{className:"selected-content-preview__hover-text-content",children:c.text})]})]}),document.body),s.jsx("div",{className:`selected-content-preview ${r||""}`,children:t.map((d,p)=>{const h=i&&p<o;return s.jsxs("div",{className:`selected-content-preview__item selected-content-preview__item--${d.type}`,onMouseEnter:g=>m(d,g),onMouseLeave:u,children:[d.type==="text"?s.jsxs("div",{className:"selected-content-preview__text",children:[s.jsx(Cs,{size:14,className:"selected-content-preview__text-icon"}),s.jsx("span",{className:"selected-content-preview__text-content",children:d.text&&d.text.length>20?`${d.text.substring(0,20)}...`:d.text})]}):d.type==="video"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"selected-content-preview__video-placeholder",children:s.jsx(Gi,{size:20})}),s.jsx("div",{className:"selected-content-preview__video-overlay",children:s.jsx(xr,{size:16,fill:"white"})})]}):Js(d,"selected-content-preview"),d.type==="image"&&d.maskImage&&s.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--mask",children:"Mask"}),d.type==="graphics"&&s.jsx("span",{className:"selected-content-preview__label",children:e==="zh"?"图形":"Graphics"}),d.type==="video"&&s.jsx("span",{className:"selected-content-preview__label selected-content-preview__label--video",children:e==="zh"?"视频":"Video"}),h&&s.jsx(je,{content:e==="zh"?"移除":"Remove",showArrow:!1,children:s.jsx("button",{className:"selected-content-preview__remove-btn",onClick:g=>{g.stopPropagation(),i(p)},onMouseDown:g=>g.preventDefault(),children:s.jsx(Mt,{size:12})})})]},`${d.type}-${p}`)})})]})};function Wt(t){return t.tagName==="TEXTAREA"||t.tagName==="INPUT"}function Bl(t){const e=t.selectionStart||0,n=t.selectionEnd||0;return t.value.substring(e,n)}function Io(t){const e=window.getSelection();if(!e||e.rangeCount===0)return"";const n=e.getRangeAt(0);return t.contains(n.commonAncestorContainer)?e.toString():""}function En(t){return Wt(t)?Bl(t):Io(t)}function Gl(t,e={}){const{enableCopy:n=!0,stopPropagation:r=!0}=e,i=a.useRef(null);return a.useEffect(()=>{const o=t.current;if(!o)return;const c=f=>!f||!(f instanceof HTMLElement)?!1:!!(["BUTTON","A","INPUT","SELECT","TEXTAREA","LABEL"].includes(f.tagName)||f.onclick||f.getAttribute("role")==="button"||f.closest('button, a, [role="button"], [onclick]')),l=()=>{const f=window.getSelection();return f!==null&&f.toString().length>0},m=f=>{r&&(c(f.target)||l()&&f.stopPropagation())},u=f=>{r&&(c(f.target)||f.stopPropagation())},d=f=>{const x=(f.ctrlKey||f.metaKey)&&f.key==="c",z=(f.ctrlKey||f.metaKey)&&f.key==="x";if(n&&(x||z)){const N=En(o);N&&Rr(N).then(()=>{}).catch(O=>{console.error("Failed to copy text:",O)}),r&&f.stopPropagation()}},p=f=>{if(n){const x=En(o);x&&f.clipboardData&&(f.clipboardData.setData("text/plain",x),f.preventDefault())}r&&f.stopPropagation()},h=f=>{if(n){const x=En(o);x&&f.clipboardData&&f.clipboardData.setData("text/plain",x)}r&&f.stopPropagation()},g=()=>{if(Wt(o)){const f=o.selectionStart||0,x=o.selectionEnd||0;f!==x&&(i.current={text:o.value.substring(f,x),start:f,end:x})}else{const f=Io(o);f&&(i.current={text:f})}},y=()=>{Wt(o)||g()};return o.addEventListener("pointerdown",u),o.addEventListener("mousedown",u),o.addEventListener("pointerup",m),o.addEventListener("pointermove",m),o.addEventListener("mouseup",m),o.addEventListener("click",m),o.addEventListener("keydown",d),o.addEventListener("copy",p),o.addEventListener("cut",h),Wt(o)?o.addEventListener("select",g):document.addEventListener("selectionchange",y),()=>{o.removeEventListener("pointerdown",u),o.removeEventListener("mousedown",u),o.removeEventListener("pointerup",m),o.removeEventListener("pointermove",m),o.removeEventListener("mouseup",m),o.removeEventListener("click",m),o.removeEventListener("keydown",d),o.removeEventListener("copy",p),o.removeEventListener("cut",h),Wt(o)?o.removeEventListener("select",g):document.removeEventListener("selectionchange",y)}},[t,n,r]),{lastSelection:i.current}}function ds(){const t=at.get();return(t==null?void 0:t.videoModelName)||Yt()}function ql(){const t=new Set;return Object.values(Ct).forEach(e=>{e.durationOptions.forEach(n=>t.add(n.value))}),Array.from(t).sort((e,n)=>parseInt(e)-parseInt(n))}function Kl(){const t=new Set;return Object.values(Ct).forEach(e=>{e.sizeOptions.forEach(n=>t.add(n.value))}),Array.from(t)}async function Zl(t){const{prompt:e,model:n="veo3",modelRef:r,seconds:i="8",size:o="1280x720",referenceImages:c,params:l}=t,m=yn(e);if(m)return m;try{const u=n,d=Ki("video",u,r||null);if(!d||d.kind!=="video")return{success:!1,error:`未找到可用的视频适配器: ${u}`,type:"error"};const p=i?Number(i):void 0,h=await d.generateVideo(Zi("video",r||u),{prompt:e,size:o,model:u,modelRef:r||null,duration:Number.isFinite(p)?p:void 0,referenceImages:c,params:l}),g=h.url;return g?{success:!0,data:{url:g,format:h.format||"mp4",prompt:e,model:n,seconds:i,size:o},type:"video"}:{success:!1,error:"API 未返回有效的视频 URL",type:"error"}}catch(u){return console.error("[VideoGenerationTool] Generation failed:",u),Dr(u,"视频生成失败")}}function Yl(t){const e=t.model||"veo3",n=Ct[e]||Ct.veo3,r=zr(t.referenceImages);return{taskType:xt.VIDEO,resultType:"video",getDefaultModel:ds,logPrefix:"VideoGenerationTool",buildTaskPayload:()=>({prompt:t.prompt,size:t.size||"16x9",duration:parseInt(t.seconds||n.defaultDuration,10),model:e,modelRef:t.modelRef||null,uploadedImages:r&&r.length>0?r:void 0,referenceImages:t.referenceImages&&t.referenceImages.length>0?t.referenceImages:void 0,params:t.params,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs}),buildResultData:()=>({size:t.size||"16x9",duration:parseInt(t.seconds||n.defaultDuration,10)})}}const us={name:"generate_video",description:`生成视频工具。根据用户的文字描述生成视频。
306
306
 
307
307
  使用场景:
308
308
  - 用户想要创建、生成视频
@@ -314,7 +314,7 @@ ${S}`))}if(z&&g.length>0&&!Wi(O)){const S=await Tr(g,N);O=Nr(O,S)}let T=0,I="";c
314
314
  - 用户想要生成静态图片(使用 generate_image 工具)
315
315
  - 用户只是在聊天,没有生成视频的意图
316
316
 
317
- 当前使用模型:${ds()}`,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"视频描述提示词,详细描述想要生成的视频内容、动作、场景、风格等"},model:{type:"string",description:`视频生成模型,默认使用 ${Yt()}`,default:Yt()},seconds:{type:"string",description:"视频时长(秒),不同模型支持的时长不同",enum:Gl(),default:"8"},size:{type:"string",description:"视频尺寸",enum:ql(),default:"1280x720"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于图生视频",items:{type:"string"}},params:{type:"object",description:"额外模型参数,Kling 可用字段包括 model_name、klingAction2、mode、cfg_scale、negative_prompt 与 camera_*;其中 cfg_scale 取值 0 到 1,camera_* 取值 -10 到 10 且需为整数",properties:{model_name:{type:"string",enum:["kling-v3","kling-v2-6","kling-v2-1","kling-v1-6","kling-v1-5"]},klingAction2:{type:"string",enum:["text2video","image2video"]},mode:{type:"string",enum:["std","pro"]},cfg_scale:{type:"number",description:"Kling 自由度,取值范围 0 到 1"},negative_prompt:{type:"string"},camera_control_type:{type:"string"},camera_horizontal:{type:"number",description:"Kling 水平运镜,取值范围 -10 到 10,且必须为整数"},camera_vertical:{type:"number",description:"Kling 垂直运镜,取值范围 -10 到 10,且必须为整数"},camera_pan:{type:"number",description:"Kling 水平摇镜,取值范围 -10 到 10,且必须为整数"},camera_tilt:{type:"number",description:"Kling 垂直摇镜,取值范围 -10 到 10,且必须为整数"},camera_roll:{type:"number",description:"Kling 旋转运镜,取值范围 -10 到 10,且必须为整数"},camera_zoom:{type:"number",description:"Kling 变焦,取值范围 -10 到 10,且必须为整数"}}},count:{type:"number",description:"生成数量,1-10 之间,默认为 1",default:1}},required:["prompt"]},supportedModes:["async","queue"],promptGuidance:{whenToUse:"当用户想要生成视频、动画或动态内容时使用。适用于:将图片变成视频、创建短视频、生成动态场景等。关键词:视频、动画、动起来、动态。",parameterGuidance:{prompt:"将用户描述扩展为详细的英文视频提示词,包含:主体动作(walking, flying, spinning)、场景描述、镜头运动(camera pan, zoom in, tracking shot)、氛围(cinematic, dreamy)、时间节奏(slow motion, timelapse)。",model:"默认使用 veo3,支持高质量视频生成。可选其他模型如需特定效果。",seconds:"根据内容复杂度选择:简单动作用 5-8 秒,复杂场景用 8-10 秒。默认 8 秒。",size:"横屏视频用 1280x720 或 1920x1080,竖屏用 720x1280,正方形用 1024x1024。",referenceImages:'当用户提供图片并想让它"动起来"时使用,传入图片 URL 实现图生视频。',count:'用户明确要求批量生成时使用,如 "+3 生成视频" 则 count=3。'},bestPractices:["prompt 使用英文能获得更好的生成效果",'描述具体的动作和运动,如 "a cat walking slowly" 而非 "a cat"','添加镜头运动描述如 "camera slowly pans right"、"zoom in smoothly"','描述氛围和风格如 "cinematic lighting"、"slow motion"、"dreamy atmosphere"','对于图生视频,描述图片中元素如何运动,如 "the waves start to move"',"避免过于复杂的场景变化,每个视频专注一个主要动作"],examples:[{input:"生成一个猫咪走路的视频",args:{prompt:"A fluffy orange cat walking gracefully across a sunny room, soft natural lighting, camera tracking shot following the cat, gentle movements, high quality, cinematic",seconds:"8",size:"1280x720"}},{input:"让这张日落图片动起来",args:{prompt:"Beautiful sunset scene with moving clouds drifting slowly across the sky, sun rays shifting, gentle wind effect on trees, time-lapse style, warm golden hour lighting, peaceful atmosphere",referenceImages:["[图片1]"],seconds:"8"},explanation:"图生视频使用 referenceImages 传递原图,prompt 描述期望的动态效果"},{input:"赛博朋克城市夜景动画",args:{prompt:"Cyberpunk city at night with flying cars moving through neon-lit streets, holographic advertisements flickering, rain falling, camera slowly panning across the skyline, atmospheric fog, cinematic sci-fi mood",seconds:"10",size:"1920x1080"}},{input:"生成一个产品旋转展示视频",args:{prompt:"Product showcase video, sleek modern headphones rotating 360 degrees on a white pedestal, smooth continuous rotation, professional studio lighting, minimal clean background, commercial quality",seconds:"8",size:"1280x720"}}],warnings:["视频生成时间较长(通常 1-3 分钟),请耐心等待","避免描述突然的场景切换或多个不连贯的动作","图生视频时,确保参考图片清晰且主体明确"]},execute:async(t,e)=>{const n=t,r=(e==null?void 0:e.mode)||"async";let i=n.size;if(n.size){const c=n.model||"veo3",l=Ct[c]||Ct.veo3,m=l.sizeOptions.map(u=>u.value);i=Gi(n.size,m,l.defaultSize)}const o={...n,size:i};return r==="queue"?wn(o,e||{},Zl(o)):Kl(o)}};async function Yl(t,e){return await us.execute(t,{...e,mode:"queue"})}const hm=Object.freeze(Object.defineProperty({__proto__:null,createVideoTask:Yl,getCurrentVideoModel:ds,videoGenerationTool:us},Symbol.toStringTag,{value:"Module"}));function Wn(){const t=at.get();return(t==null?void 0:t.audioModelName)||es()}async function Xl(t){const e=yn(t.prompt);if(e)return e;try{const n=await Zi.generateAudioWithPolling({model:t.model||Wn(),modelRef:t.modelRef||null,prompt:t.prompt,sunoAction:t.sunoAction,notifyHook:t.notifyHook,title:t.title,tags:t.tags,mv:t.mv,continueClipId:t.continueClipId,continueTaskId:t.continueTaskId,continueAt:t.continueAt,infillStartS:t.infillStartS,infillEndS:t.infillEndS,params:{...t.params||{},...t.continueSource?{continueSource:t.continueSource}:{}}}),r=Yi(n);return{success:!0,data:{url:r.url,urls:r.urls,resultKind:r.resultKind,title:r.title,lyricsText:r.lyricsText,lyricsTitle:r.lyricsTitle,lyricsTags:r.lyricsTags,duration:r.duration,imageUrl:r.imageUrl,format:r.format||(r.resultKind==="lyrics"?"lyrics":"mp3"),providerTaskId:r.providerTaskId,primaryClipId:r.primaryClipId,clipIds:r.clipIds,clips:r.clips},type:"audio"}}catch(n){return{success:!1,error:n.message||"音频生成失败",type:"error"}}}function Jl(t){return{taskType:xt.AUDIO,resultType:"audio",getDefaultModel:Wn,maxCount:1,buildTaskPayload:()=>({prompt:t.prompt,model:t.model||Wn(),modelRef:t.modelRef||null,sunoAction:t.sunoAction,notifyHook:t.notifyHook,title:t.title,tags:t.tags,mv:t.mv,continueClipId:t.continueClipId,continueTaskId:t.continueTaskId,continueAt:t.continueAt,infillStartS:t.infillStartS,infillEndS:t.infillEndS,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs,...t.params||t.continueSource?{params:{...t.params||{},...t.continueSource?{continueSource:t.continueSource}:{}}}:{}}),buildResultData:()=>({mv:t.mv})}}async function Ql(t,e={}){return(e.mode||"async")==="queue"?wn(t,e,Jl(t)):Xl(t)}const ed={name:"generate_audio",description:"生成音频或音乐,可用于 Suno 音乐生成与续写",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{prompt:{type:"string",description:"音乐描述或歌词内容"},model:{type:"string",description:"音频能力模型 ID,默认 suno_music"},title:{type:"string",description:"歌曲标题"},sunoAction:{type:"string",description:"Suno 动作类型,music 或 lyrics"},notifyHook:{type:"string",description:"歌词生成完成后的回调地址"},tags:{type:"string",description:"风格标签,逗号分隔"},mv:{type:"string",description:"Suno 版本字段,如 chirp-v5-5、chirp-v5、chirp-v4-5、chirp-v4、chirp-v3-5"},continueClipId:{type:"string",description:"续写目标 clip ID"},continueTaskId:{type:"string",description:"续写目标所属任务 task_id"},continueSource:{type:"string",description:"续写来源,clip 或 upload;upload 会自动拼接 -upload 版本"},continueAt:{type:"number",description:"从第几秒开始续写"},infillStartS:{type:"number",description:"Infill 开始秒数"},infillEndS:{type:"number",description:"Infill 结束秒数"}},required:["prompt"]},async execute(t,e){return Ql(t,e)}};function Hn(){const t=at.get();return(t==null?void 0:t.textModelName)||Xi()}function td(t){return typeof t=="object"&&t!==null&&typeof t.prompt=="string"}async function nd(t,e={}){const n=yn(t.prompt);if(n)return n;try{return{success:!0,data:await Ir.getFallbackExecutor().generateText({prompt:t.prompt,model:t.model||Hn(),modelRef:t.modelRef||null,referenceImages:t.referenceImages,params:t.params},void 0),type:"text"}}catch(r){return{success:!1,error:r.message||"文本生成失败",type:"error"}}}function sd(t){return{taskType:xt.CHAT,resultType:"text",getDefaultModel:Hn,maxCount:1,buildTaskPayload:()=>({prompt:t.prompt,model:t.model||Hn(),modelRef:t.modelRef||null,referenceImages:t.referenceImages,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs,...t.params?{params:t.params}:{}})}}async function rd(t,e={}){return(e.mode||"async")==="queue"?wn(t,e,sd(t)):nd(t,e)}const od={name:"generate_text",description:"生成纯文本内容,可用于文章、摘要、说明、Markdown 等文本直出场景",supportedModes:["async","queue"],execute:async(t,e)=>td(t)?rd(t,e):{success:!1,error:"缺少必填参数 prompt",type:"error"},inputSchema:{type:"object",properties:{prompt:{type:"string",description:"文本生成提示词"},model:{type:"string",description:"文本模型 ID,默认使用当前文本路由模型"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于图像理解后输出文本",items:{type:"string"}},params:{type:"object",description:"文本模型额外参数,如 temperature、top_p、max_tokens"},knowledgeContextRefs:{type:"array",description:"本次生成使用的知识库笔记轻量引用"}},required:["prompt"]}},id={name:"ai_analyze",description:`AI 分析工具。调用文本模型分析用户意图,决定需要执行的操作。
317
+ 当前使用模型:${ds()}`,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"视频描述提示词,详细描述想要生成的视频内容、动作、场景、风格等"},model:{type:"string",description:`视频生成模型,默认使用 ${Yt()}`,default:Yt()},seconds:{type:"string",description:"视频时长(秒),不同模型支持的时长不同",enum:ql(),default:"8"},size:{type:"string",description:"视频尺寸",enum:Kl(),default:"1280x720"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于图生视频",items:{type:"string"}},params:{type:"object",description:"额外模型参数,Kling 可用字段包括 model_name、klingAction2、mode、cfg_scale、negative_prompt 与 camera_*;其中 cfg_scale 取值 0 到 1,camera_* 取值 -10 到 10 且需为整数",properties:{model_name:{type:"string",enum:["kling-v3","kling-v2-6","kling-v2-1","kling-v1-6","kling-v1-5"]},klingAction2:{type:"string",enum:["text2video","image2video"]},mode:{type:"string",enum:["std","pro"]},cfg_scale:{type:"number",description:"Kling 自由度,取值范围 0 到 1"},negative_prompt:{type:"string"},camera_control_type:{type:"string"},camera_horizontal:{type:"number",description:"Kling 水平运镜,取值范围 -10 到 10,且必须为整数"},camera_vertical:{type:"number",description:"Kling 垂直运镜,取值范围 -10 到 10,且必须为整数"},camera_pan:{type:"number",description:"Kling 水平摇镜,取值范围 -10 到 10,且必须为整数"},camera_tilt:{type:"number",description:"Kling 垂直摇镜,取值范围 -10 到 10,且必须为整数"},camera_roll:{type:"number",description:"Kling 旋转运镜,取值范围 -10 到 10,且必须为整数"},camera_zoom:{type:"number",description:"Kling 变焦,取值范围 -10 到 10,且必须为整数"}}},count:{type:"number",description:"生成数量,1-10 之间,默认为 1",default:1}},required:["prompt"]},supportedModes:["async","queue"],promptGuidance:{whenToUse:"当用户想要生成视频、动画或动态内容时使用。适用于:将图片变成视频、创建短视频、生成动态场景等。关键词:视频、动画、动起来、动态。",parameterGuidance:{prompt:"将用户描述扩展为详细的英文视频提示词,包含:主体动作(walking, flying, spinning)、场景描述、镜头运动(camera pan, zoom in, tracking shot)、氛围(cinematic, dreamy)、时间节奏(slow motion, timelapse)。",model:"默认使用 veo3,支持高质量视频生成。可选其他模型如需特定效果。",seconds:"根据内容复杂度选择:简单动作用 5-8 秒,复杂场景用 8-10 秒。默认 8 秒。",size:"横屏视频用 1280x720 或 1920x1080,竖屏用 720x1280,正方形用 1024x1024。",referenceImages:'当用户提供图片并想让它"动起来"时使用,传入图片 URL 实现图生视频。',count:'用户明确要求批量生成时使用,如 "+3 生成视频" 则 count=3。'},bestPractices:["prompt 使用英文能获得更好的生成效果",'描述具体的动作和运动,如 "a cat walking slowly" 而非 "a cat"','添加镜头运动描述如 "camera slowly pans right"、"zoom in smoothly"','描述氛围和风格如 "cinematic lighting"、"slow motion"、"dreamy atmosphere"','对于图生视频,描述图片中元素如何运动,如 "the waves start to move"',"避免过于复杂的场景变化,每个视频专注一个主要动作"],examples:[{input:"生成一个猫咪走路的视频",args:{prompt:"A fluffy orange cat walking gracefully across a sunny room, soft natural lighting, camera tracking shot following the cat, gentle movements, high quality, cinematic",seconds:"8",size:"1280x720"}},{input:"让这张日落图片动起来",args:{prompt:"Beautiful sunset scene with moving clouds drifting slowly across the sky, sun rays shifting, gentle wind effect on trees, time-lapse style, warm golden hour lighting, peaceful atmosphere",referenceImages:["[图片1]"],seconds:"8"},explanation:"图生视频使用 referenceImages 传递原图,prompt 描述期望的动态效果"},{input:"赛博朋克城市夜景动画",args:{prompt:"Cyberpunk city at night with flying cars moving through neon-lit streets, holographic advertisements flickering, rain falling, camera slowly panning across the skyline, atmospheric fog, cinematic sci-fi mood",seconds:"10",size:"1920x1080"}},{input:"生成一个产品旋转展示视频",args:{prompt:"Product showcase video, sleek modern headphones rotating 360 degrees on a white pedestal, smooth continuous rotation, professional studio lighting, minimal clean background, commercial quality",seconds:"8",size:"1280x720"}}],warnings:["视频生成时间较长(通常 1-3 分钟),请耐心等待","避免描述突然的场景切换或多个不连贯的动作","图生视频时,确保参考图片清晰且主体明确"]},execute:async(t,e)=>{const n=t,r=(e==null?void 0:e.mode)||"async";let i=n.size;if(n.size){const c=n.model||"veo3",l=Ct[c]||Ct.veo3,m=l.sizeOptions.map(u=>u.value);i=qi(n.size,m,l.defaultSize)}const o={...n,size:i};return r==="queue"?wn(o,e||{},Yl(o)):Zl(o)}};async function Xl(t,e){return await us.execute(t,{...e,mode:"queue"})}const fm=Object.freeze(Object.defineProperty({__proto__:null,createVideoTask:Xl,getCurrentVideoModel:ds,videoGenerationTool:us},Symbol.toStringTag,{value:"Module"}));function Wn(){const t=at.get();return(t==null?void 0:t.audioModelName)||es()}async function Jl(t){const e=yn(t.prompt);if(e)return e;try{const n=await Yi.generateAudioWithPolling({model:t.model||Wn(),modelRef:t.modelRef||null,prompt:t.prompt,sunoAction:t.sunoAction,notifyHook:t.notifyHook,title:t.title,tags:t.tags,mv:t.mv,continueClipId:t.continueClipId,continueTaskId:t.continueTaskId,continueAt:t.continueAt,infillStartS:t.infillStartS,infillEndS:t.infillEndS,params:{...t.params||{},...t.continueSource?{continueSource:t.continueSource}:{}}}),r=Xi(n);return{success:!0,data:{url:r.url,urls:r.urls,resultKind:r.resultKind,title:r.title,lyricsText:r.lyricsText,lyricsTitle:r.lyricsTitle,lyricsTags:r.lyricsTags,duration:r.duration,imageUrl:r.imageUrl,format:r.format||(r.resultKind==="lyrics"?"lyrics":"mp3"),providerTaskId:r.providerTaskId,primaryClipId:r.primaryClipId,clipIds:r.clipIds,clips:r.clips},type:"audio"}}catch(n){return{success:!1,error:n.message||"音频生成失败",type:"error"}}}function Ql(t){return{taskType:xt.AUDIO,resultType:"audio",getDefaultModel:Wn,maxCount:1,buildTaskPayload:()=>({prompt:t.prompt,model:t.model||Wn(),modelRef:t.modelRef||null,sunoAction:t.sunoAction,notifyHook:t.notifyHook,title:t.title,tags:t.tags,mv:t.mv,continueClipId:t.continueClipId,continueTaskId:t.continueTaskId,continueAt:t.continueAt,infillStartS:t.infillStartS,infillEndS:t.infillEndS,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs,...t.params||t.continueSource?{params:{...t.params||{},...t.continueSource?{continueSource:t.continueSource}:{}}}:{}}),buildResultData:()=>({mv:t.mv})}}async function ed(t,e={}){return(e.mode||"async")==="queue"?wn(t,e,Ql(t)):Jl(t)}const td={name:"generate_audio",description:"生成音频或音乐,可用于 Suno 音乐生成与续写",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{prompt:{type:"string",description:"音乐描述或歌词内容"},model:{type:"string",description:"音频能力模型 ID,默认 suno_music"},title:{type:"string",description:"歌曲标题"},sunoAction:{type:"string",description:"Suno 动作类型,music 或 lyrics"},notifyHook:{type:"string",description:"歌词生成完成后的回调地址"},tags:{type:"string",description:"风格标签,逗号分隔"},mv:{type:"string",description:"Suno 版本字段,如 chirp-v5-5、chirp-v5、chirp-v4-5、chirp-v4、chirp-v3-5"},continueClipId:{type:"string",description:"续写目标 clip ID"},continueTaskId:{type:"string",description:"续写目标所属任务 task_id"},continueSource:{type:"string",description:"续写来源,clip 或 upload;upload 会自动拼接 -upload 版本"},continueAt:{type:"number",description:"从第几秒开始续写"},infillStartS:{type:"number",description:"Infill 开始秒数"},infillEndS:{type:"number",description:"Infill 结束秒数"}},required:["prompt"]},async execute(t,e){return ed(t,e)}};function Hn(){const t=at.get();return(t==null?void 0:t.textModelName)||Ji()}function nd(t){return typeof t=="object"&&t!==null&&typeof t.prompt=="string"}async function sd(t,e={}){const n=yn(t.prompt);if(n)return n;try{return{success:!0,data:await kr.getFallbackExecutor().generateText({prompt:t.prompt,model:t.model||Hn(),modelRef:t.modelRef||null,referenceImages:t.referenceImages,params:t.params},void 0),type:"text"}}catch(r){return{success:!1,error:r.message||"文本生成失败",type:"error"}}}function rd(t){return{taskType:xt.CHAT,resultType:"text",getDefaultModel:Hn,maxCount:1,buildTaskPayload:()=>({prompt:t.prompt,model:t.model||Hn(),modelRef:t.modelRef||null,referenceImages:t.referenceImages,promptMeta:t.promptMeta,knowledgeContextRefs:t.knowledgeContextRefs,...t.params?{params:t.params}:{}})}}async function od(t,e={}){return(e.mode||"async")==="queue"?wn(t,e,rd(t)):sd(t,e)}const id={name:"generate_text",description:"生成纯文本内容,可用于文章、摘要、说明、Markdown 等文本直出场景",supportedModes:["async","queue"],execute:async(t,e)=>nd(t)?od(t,e):{success:!1,error:"缺少必填参数 prompt",type:"error"},inputSchema:{type:"object",properties:{prompt:{type:"string",description:"文本生成提示词"},model:{type:"string",description:"文本模型 ID,默认使用当前文本路由模型"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于图像理解后输出文本",items:{type:"string"}},params:{type:"object",description:"文本模型额外参数,如 temperature、top_p、max_tokens"},knowledgeContextRefs:{type:"array",description:"本次生成使用的知识库笔记轻量引用"}},required:["prompt"]}},ad={name:"ai_analyze",description:`AI 分析工具。调用文本模型分析用户意图,决定需要执行的操作。
318
318
 
319
319
  使用场景:
320
320
  - 用户输入包含额外要求或复杂指令
@@ -322,7 +322,7 @@ ${S}`))}if(z&&g.length>0&&!Wi(O)){const S=await Tr(g,N);O=Nr(O,S)}let T=0,I="";c
322
322
  - 用户选择了文本内容作为生成素材
323
323
 
324
324
  不适用场景:
325
- - 简单的直接生成(使用 generate_image 或 generate_video)`,inputSchema:{type:"object",properties:{context:{type:"object",description:"Agent 执行上下文,包含用户指令、选中内容等"},textModel:{type:"string",description:"使用的文本模型 ID"},messages:{type:"array",description:"预构建的消息数组,传入时直接使用,不再生成默认系统提示词(用于 Skill 角色扮演/精准工具注入)"},knowledgeContextRefs:{type:"array",description:"本次 Agent 分析使用的知识库笔记轻量引用"}},required:["context"]},supportedModes:["async"],execute:async(t,e)=>{const{context:n,textModel:r,messages:i,modelRef:o,knowledgeContextRefs:c}=t;if(!n)return{success:!1,error:"缺少必填参数 context",type:"error"};const l=Date.now(),m=[],u=Ln(c||n.knowledgeContextRefs),d={...n,knowledgeContextRefs:u.length>0?u:void 0};try{const p=await Ll.execute(d,{model:r||d.model.id,modelRef:o||null,messages:i,onChunk:g=>{var y;(y=e==null?void 0:e.onChunk)==null||y.call(e,g)},onToolCall:g=>{var z;const y=at.get(),f=vo(g.name,{...g.arguments},{defaultModels:d.defaultModels,defaultModelRefs:d.defaultModelRefs,contextModel:d.model,contextModelRef:o||null,fallbackModels:{image:y.imageModelName||Dr(),video:y.videoModelName||Yt(),audio:y.audioModelName||es()}});u.length>0&&["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(g.name)&&!f.knowledgeContextRefs&&(f.knowledgeContextRefs=u);const x={id:`step-tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,mcp:g.name,args:f,description:ad(g.name,f),status:"running"};m.push(x),(z=e==null?void 0:e.onAddSteps)==null||z.call(e,[x])},onToolResult:g=>{var y;if(m.length>0){const f=m[m.length-1];f.status=g.success?"completed":"failed",(y=e==null?void 0:e.onUpdateStep)==null||y.call(e,f.id,f.status,g.data,g.error)}}}),h=Date.now()-l;return p.success?{success:!0,type:"text",data:{response:p.response,generatedSteps:m,duration:h}}:{success:!1,error:p.error||"AI 分析失败",type:"error",data:{duration:h,generatedSteps:m}}}catch(p){return console.error("[AIAnalyzeTool] Analysis failed:",p),{success:!1,error:p.message||"AI 分析失败",type:"error",data:{duration:Date.now()-l,generatedSteps:m}}}}};function ad(t,e){switch(t){case"generate_image":return`生成图片: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_audio":return`生成音频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_ppt":return`生成PPT: ${((e==null?void 0:e.topic)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((e==null?void 0:e.theme)||"").substring(0,30)}...`;case"insert_svg":return"插入SVG矢量图";case"canvas_insertion":case"insert_to_canvas":return"插入到画布";default:return`执行 ${t}`}}let Xt=null;function cd(t){Xt=t}function en(){return Xt}function ld(){return Xt!==null}function dd(){if(!Xt)throw new Error("画布未初始化,请先打开画布");return Xt}const Jt=20,_n=50,ud=100;function Qt(t,e){if(e){const i=new RegExp(`\`\`\`(?:${e}|${e.charAt(0).toUpperCase()+e.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),o=t.match(i);if(o)return o[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=t.match(n);return r?r[1].trim():t.trim()}function Io(t){return $n.getBoundingRectangle(t.filter(e=>!Ji.isGroup(e)).map(e=>$n.getRectangleByPoints(e.points)))}function ko(t,e,n=Jt){const r=t.x-n,i=t.x+t.width+n,o=t.y-n,c=t.y+t.height+n,l=e.x,m=e.x+e.width,u=e.y,d=e.y+e.height;return!(i<l||r>m||c<u||o>d)}function ms(t){const e=[];if(!t.children||t.children.length===0)return e;for(const n of t.children)try{const r=ns(t,[n],!1);e.push({x:r.x,y:r.y,width:r.width,height:r.height})}catch(r){console.warn("[InsertUtils] Failed to get bounding box for element:",r)}return e}function ps(t,e,n=Jt){for(const r of e)if(ko(t,r,n))return!0;return!1}function hs(t,e,n,r=Jt,i=_n){let o=[...t],c=0;for(;c<ud;){const l={x:o[0],y:o[1],width:e.width,height:e.height};if(!ps(l,n,r))return o;o=[o[0],o[1]+i],c++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",o),o}function md(t,e){const n=Io(e),r=n.width,i=n.height,o=ms(t);let c;const l=Lr(t);if(l)c=[l[0]-r/2,l[1]];else if(o.length>0){let u=-1/0,d=0;for(const p of o){const h=p.y+p.height;h>u&&(u=h,d=p.x+p.width/2)}c=[d-r/2,u+_n]}else{const u=ts.getBoardContainer(t).getBoundingClientRect(),d=[u.width/2,u.height/2],p=t.viewport.zoom,h=$r(t),g=h[0]+d[0]/p,y=h[1]+d[1]/p;c=[g-r/2,y-i/2]}return hs(c,{width:r,height:i},o)}function Mo(t,e){try{const n=ns(t,[e],!1);return{x:n.x,y:n.y,width:n.width,height:n.height}}catch(n){return console.warn("[InsertUtils] Failed to get actual bounding box:",n),null}}function Co(t,e){const n=[];if(!t.children||t.children.length===0)return n;for(const r of t.children){const i=r;if(!e.has(i.id))try{const o=ns(t,[i],!1);n.push({x:o.x,y:o.y,width:o.width,height:o.height})}catch{}}return n}function jo(t,e,n,r){try{const i=t.children.findIndex(l=>l.id===e.id);if(i<0)return console.warn("[InsertUtils] Element not found in board:",e.id),!1;const o=e.points;if(!o||o.length===0)return console.warn("[InsertUtils] Element has no points:",e.id),!1;const c=o.map(l=>[l[0]+n,l[1]+r]);return ss.setNode(t,{points:c},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function To(t){const e=Lr(t);if(e)return e;const n=ms(t);if(n.length>0){let u=-1/0,d=0;for(const p of n){const h=p.y+p.height;h>u&&(u=h,d=p.x+p.width/2)}return[d,u+_n]}const r=ts.getBoardContainer(t).getBoundingClientRect(),i=[r.width/2,r.height/2],o=t.viewport.zoom,c=$r(t),l=c[0]+i[0]/o,m=c[1]+i[1]/o;return[l,m]}function No(t,e){let n=!1;for(const r of e){const i=t.children.find(d=>d.id===r);if(!i)continue;const o=Mo(t,i);if(!o)continue;const c=Co(t,e);if(c.length===0||!ps(o,c,Jt))continue;const l=hs([o.x,o.y],{width:o.width,height:o.height},c,Jt,_n),m=l[0]-o.x,u=l[1]-o.y;(m!==0||u!==0)&&jo(t,i,m,u)&&(n=!0)}return n}function fs(t,e,n){if(!e||e.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(t.children.map(c=>c.id)),i=n||To(t);t.insertFragment({elements:JSON.parse(JSON.stringify(e))},i,Qi.paste);const o=new Set;for(const c of t.children){const l=c;r.has(l.id)||o.add(l.id)}return o.size>0?requestAnimationFrame(()=>{const c=No(t,o);i&&qt(t,i)}):i&&requestAnimationFrame(()=>{qt(t,i)}),{success:!0,elementsCount:e.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const fm=Object.freeze(Object.defineProperty({__proto__:null,adjustOverlappingElements:No,calculateElementsBoundingRect:Io,createQueueTask:wn,extractCodeBlock:Qt,findNonOverlappingPosition:hs,getAllElementBoundingBoxes:ms,getBoard:en,getElementActualBoundingBox:Mo,getInitialInsertionPoint:To,getInsertionPoint:md,getOtherElementBoundingBoxes:Co,hasOverlapWithAny:ps,insertElementsToCanvas:fs,isBoardAvailable:ld,isOverlapping:ko,moveElement:jo,requireBoard:dd,setBoard:cd,toUploadedImages:Rr,validatePrompt:yn,wrapApiError:zr},Symbol.toStringTag,{value:"Module"}));let rn=null;function pd(){return rn||(rn=dt(()=>import("./index-jxwTv7c1.js"),__vite__mapDeps([0]),import.meta.url).catch(t=>{throw rn=null,t})),rn}function hd(t){return Qt(t,"mermaid")}function fd(t){const e=t.trim().toLowerCase();return e.startsWith("flowchart")||e.startsWith("graph")?"flowchart":e.startsWith("sequencediagram")?"sequence":e.startsWith("classdiagram")?"classDiagram":e.startsWith("statediagram")?"stateDiagram":e.startsWith("erdiagram")?"erDiagram":e.startsWith("gantt")?"gantt":e.startsWith("pie")?"pie":e.startsWith("mindmap")?"mindmap":"unknown"}async function gd(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{mermaid:n}=t;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 mermaid,请提供有效的Mermaid markdown字符串",type:"error"};try{const r=hd(n),i=fd(r),o=await pd();let c;try{c=await o.parseMermaidToDrawnix(r)}catch(u){console.warn("[MermaidTool] First parse attempt failed, retrying with quote replacement:",u.message),c=await o.parseMermaidToDrawnix(r.replace(/"/g,"'"))}const{elements:l}=c;if(!l||l.length===0)return{success:!1,error:"Mermaid代码解析成功,但未生成任何图表元素",type:"error"};const m=fs(e,l);return m.success?{success:!0,data:{diagramType:i,elementsCount:m.elementsCount,mermaidCode:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:m.error||"插入图表失败",type:"error"}}catch(r){return console.error("[MermaidTool] Failed to process mermaid:",r),{success:!1,error:`Mermaid转换失败: ${r.message||"未知错误"}`,type:"error"}}}const wd={name:"insert_mermaid",description:`将Mermaid图表插入到画布工具。将Mermaid markdown语法转换为可视化图表并插入到画布中。
325
+ - 简单的直接生成(使用 generate_image 或 generate_video)`,inputSchema:{type:"object",properties:{context:{type:"object",description:"Agent 执行上下文,包含用户指令、选中内容等"},textModel:{type:"string",description:"使用的文本模型 ID"},messages:{type:"array",description:"预构建的消息数组,传入时直接使用,不再生成默认系统提示词(用于 Skill 角色扮演/精准工具注入)"},knowledgeContextRefs:{type:"array",description:"本次 Agent 分析使用的知识库笔记轻量引用"}},required:["context"]},supportedModes:["async"],execute:async(t,e)=>{const{context:n,textModel:r,messages:i,modelRef:o,knowledgeContextRefs:c}=t;if(!n)return{success:!1,error:"缺少必填参数 context",type:"error"};const l=Date.now(),m=[],u=Ln(c||n.knowledgeContextRefs),d={...n,knowledgeContextRefs:u.length>0?u:void 0};try{const p=await $l.execute(d,{model:r||d.model.id,modelRef:o||null,messages:i,onChunk:g=>{var y;(y=e==null?void 0:e.onChunk)==null||y.call(e,g)},onToolCall:g=>{var z;const y=at.get(),f=So(g.name,{...g.arguments},{defaultModels:d.defaultModels,defaultModelRefs:d.defaultModelRefs,contextModel:d.model,contextModelRef:o||null,fallbackModels:{image:y.imageModelName||Lr(),video:y.videoModelName||Yt(),audio:y.audioModelName||es()}});u.length>0&&["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(g.name)&&!f.knowledgeContextRefs&&(f.knowledgeContextRefs=u);const x={id:`step-tool-${Date.now()}-${Math.random().toString(36).substring(2,6)}`,mcp:g.name,args:f,description:cd(g.name,f),status:"running"};m.push(x),(z=e==null?void 0:e.onAddSteps)==null||z.call(e,[x])},onToolResult:g=>{var y;if(m.length>0){const f=m[m.length-1];f.status=g.success?"completed":"failed",(y=e==null?void 0:e.onUpdateStep)==null||y.call(e,f.id,f.status,g.data,g.error)}}}),h=Date.now()-l;return p.success?{success:!0,type:"text",data:{response:p.response,generatedSteps:m,duration:h}}:{success:!1,error:p.error||"AI 分析失败",type:"error",data:{duration:h,generatedSteps:m}}}catch(p){return console.error("[AIAnalyzeTool] Analysis failed:",p),{success:!1,error:p.message||"AI 分析失败",type:"error",data:{duration:Date.now()-l,generatedSteps:m}}}}};function cd(t,e){switch(t){case"generate_image":return`生成图片: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_audio":return`生成音频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_ppt":return`生成PPT: ${((e==null?void 0:e.topic)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((e==null?void 0:e.theme)||"").substring(0,30)}...`;case"insert_svg":return"插入SVG矢量图";case"canvas_insertion":case"insert_to_canvas":return"插入到画布";default:return`执行 ${t}`}}let Xt=null;function ld(t){Xt=t}function en(){return Xt}function dd(){return Xt!==null}function ud(){if(!Xt)throw new Error("画布未初始化,请先打开画布");return Xt}const Jt=20,_n=50,md=100;function Qt(t,e){if(e){const i=new RegExp(`\`\`\`(?:${e}|${e.charAt(0).toUpperCase()+e.slice(1)})\\s*([\\s\\S]*?)\`\`\``,"i"),o=t.match(i);if(o)return o[1].trim()}const n=/```(?:\w+)?\s*([\s\S]*?)```/,r=t.match(n);return r?r[1].trim():t.trim()}function ko(t){return $n.getBoundingRectangle(t.filter(e=>!Qi.isGroup(e)).map(e=>$n.getRectangleByPoints(e.points)))}function Mo(t,e,n=Jt){const r=t.x-n,i=t.x+t.width+n,o=t.y-n,c=t.y+t.height+n,l=e.x,m=e.x+e.width,u=e.y,d=e.y+e.height;return!(i<l||r>m||c<u||o>d)}function ms(t){const e=[];if(!t.children||t.children.length===0)return e;for(const n of t.children)try{const r=ns(t,[n],!1);e.push({x:r.x,y:r.y,width:r.width,height:r.height})}catch(r){console.warn("[InsertUtils] Failed to get bounding box for element:",r)}return e}function ps(t,e,n=Jt){for(const r of e)if(Mo(t,r,n))return!0;return!1}function hs(t,e,n,r=Jt,i=_n){let o=[...t],c=0;for(;c<md;){const l={x:o[0],y:o[1],width:e.width,height:e.height};if(!ps(l,n,r))return o;o=[o[0],o[1]+i],c++}return console.warn("[InsertUtils] Max iterations reached, returning current position:",o),o}function pd(t,e){const n=ko(e),r=n.width,i=n.height,o=ms(t);let c;const l=$r(t);if(l)c=[l[0]-r/2,l[1]];else if(o.length>0){let u=-1/0,d=0;for(const p of o){const h=p.y+p.height;h>u&&(u=h,d=p.x+p.width/2)}c=[d-r/2,u+_n]}else{const u=ts.getBoardContainer(t).getBoundingClientRect(),d=[u.width/2,u.height/2],p=t.viewport.zoom,h=Or(t),g=h[0]+d[0]/p,y=h[1]+d[1]/p;c=[g-r/2,y-i/2]}return hs(c,{width:r,height:i},o)}function Co(t,e){try{const n=ns(t,[e],!1);return{x:n.x,y:n.y,width:n.width,height:n.height}}catch(n){return console.warn("[InsertUtils] Failed to get actual bounding box:",n),null}}function jo(t,e){const n=[];if(!t.children||t.children.length===0)return n;for(const r of t.children){const i=r;if(!e.has(i.id))try{const o=ns(t,[i],!1);n.push({x:o.x,y:o.y,width:o.width,height:o.height})}catch{}}return n}function To(t,e,n,r){try{const i=t.children.findIndex(l=>l.id===e.id);if(i<0)return console.warn("[InsertUtils] Element not found in board:",e.id),!1;const o=e.points;if(!o||o.length===0)return console.warn("[InsertUtils] Element has no points:",e.id),!1;const c=o.map(l=>[l[0]+n,l[1]+r]);return ss.setNode(t,{points:c},[i]),!0}catch(i){return console.error("[InsertUtils] Failed to move element:",i),!1}}function No(t){const e=$r(t);if(e)return e;const n=ms(t);if(n.length>0){let u=-1/0,d=0;for(const p of n){const h=p.y+p.height;h>u&&(u=h,d=p.x+p.width/2)}return[d,u+_n]}const r=ts.getBoardContainer(t).getBoundingClientRect(),i=[r.width/2,r.height/2],o=t.viewport.zoom,c=Or(t),l=c[0]+i[0]/o,m=c[1]+i[1]/o;return[l,m]}function Eo(t,e){let n=!1;for(const r of e){const i=t.children.find(d=>d.id===r);if(!i)continue;const o=Co(t,i);if(!o)continue;const c=jo(t,e);if(c.length===0||!ps(o,c,Jt))continue;const l=hs([o.x,o.y],{width:o.width,height:o.height},c,Jt,_n),m=l[0]-o.x,u=l[1]-o.y;(m!==0||u!==0)&&To(t,i,m,u)&&(n=!0)}return n}function fs(t,e,n){if(!e||e.length===0)return{success:!1,error:"没有可插入的元素"};try{const r=new Set(t.children.map(c=>c.id)),i=n||No(t);t.insertFragment({elements:JSON.parse(JSON.stringify(e))},i,ea.paste);const o=new Set;for(const c of t.children){const l=c;r.has(l.id)||o.add(l.id)}return o.size>0?requestAnimationFrame(()=>{const c=Eo(t,o);i&&qt(t,i)}):i&&requestAnimationFrame(()=>{qt(t,i)}),{success:!0,elementsCount:e.length}}catch(r){return console.error("[InsertUtils] Failed to insert elements:",r),{success:!1,error:r.message||"插入元素失败"}}}const gm=Object.freeze(Object.defineProperty({__proto__:null,adjustOverlappingElements:Eo,calculateElementsBoundingRect:ko,createQueueTask:wn,extractCodeBlock:Qt,findNonOverlappingPosition:hs,getAllElementBoundingBoxes:ms,getBoard:en,getElementActualBoundingBox:Co,getInitialInsertionPoint:No,getInsertionPoint:pd,getOtherElementBoundingBoxes:jo,hasOverlapWithAny:ps,insertElementsToCanvas:fs,isBoardAvailable:dd,isOverlapping:Mo,moveElement:To,requireBoard:ud,setBoard:ld,toUploadedImages:zr,validatePrompt:yn,wrapApiError:Dr},Symbol.toStringTag,{value:"Module"}));let rn=null;function hd(){return rn||(rn=dt(()=>import("./index-BOOKwIS8.js"),__vite__mapDeps([0]),import.meta.url).catch(t=>{throw rn=null,t})),rn}function fd(t){return Qt(t,"mermaid")}function gd(t){const e=t.trim().toLowerCase();return e.startsWith("flowchart")||e.startsWith("graph")?"flowchart":e.startsWith("sequencediagram")?"sequence":e.startsWith("classdiagram")?"classDiagram":e.startsWith("statediagram")?"stateDiagram":e.startsWith("erdiagram")?"erDiagram":e.startsWith("gantt")?"gantt":e.startsWith("pie")?"pie":e.startsWith("mindmap")?"mindmap":"unknown"}async function wd(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{mermaid:n}=t;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 mermaid,请提供有效的Mermaid markdown字符串",type:"error"};try{const r=fd(n),i=gd(r),o=await hd();let c;try{c=await o.parseMermaidToDrawnix(r)}catch(u){console.warn("[MermaidTool] First parse attempt failed, retrying with quote replacement:",u.message),c=await o.parseMermaidToDrawnix(r.replace(/"/g,"'"))}const{elements:l}=c;if(!l||l.length===0)return{success:!1,error:"Mermaid代码解析成功,但未生成任何图表元素",type:"error"};const m=fs(e,l);return m.success?{success:!0,data:{diagramType:i,elementsCount:m.elementsCount,mermaidCode:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:m.error||"插入图表失败",type:"error"}}catch(r){return console.error("[MermaidTool] Failed to process mermaid:",r),{success:!1,error:`Mermaid转换失败: ${r.message||"未知错误"}`,type:"error"}}}const yd={name:"insert_mermaid",description:`将Mermaid图表插入到画布工具。将Mermaid markdown语法转换为可视化图表并插入到画布中。
326
326
 
327
327
  使用场景:
328
328
  - 用户需要在画布上创建流程图、时序图、类图等图表
@@ -355,7 +355,7 @@ sequenceDiagram
355
355
  AuthServer->>Client: 返回Access Token
356
356
  Client->>ResourceServer: 携带Token请求资源
357
357
  ResourceServer->>Client: 返回资源
358
- \`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async t=>gd(t)};let on=null;function yd(){return on||(on=dt(()=>import("./index-IHNaVKGH.js"),__vite__mapDeps([0,1]),import.meta.url).catch(t=>{throw on=null,t})),on}function xd(t){const e=Qt(t,"markdown");return e===t.trim(),e}async function _d(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{markdown:n}=t;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 markdown,请提供有效的 Markdown 思维导图定义",type:"error"};try{const r=xd(n),i=await yd();let o;try{o=await i.parseMarkdownToDrawnix(r)}catch(m){console.warn("[MindmapTool] First parse attempt failed, retrying with quote replacement:",m.message),o=await i.parseMarkdownToDrawnix(r.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析成功,但未生成思维导图元素",type:"error"};o.points=[[0,0]];const l=fs(e,[o]);return l.success?{success:!0,data:{type:"mindmap",elementsCount:l.elementsCount,markdownPreview:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:l.error||"插入思维导图失败",type:"error"}}catch(r){return console.error("[MindmapTool] Failed to process markdown:",r),{success:!1,error:`思维导图转换失败: ${r.message||"未知错误"}`,type:"error"}}}const bd={name:"insert_mindmap",description:`将 Markdown 思维导图插入到画布工具。将 Markdown 语法转换为可视化思维导图并插入到画布中。
358
+ \`\`\``,inputSchema:{type:"object",properties:{mermaid:{type:"string",description:"Mermaid markdown字符串,可以是纯Mermaid代码或包含```mermaid代码块的markdown"}},required:["mermaid"]},execute:async t=>wd(t)};let on=null;function xd(){return on||(on=dt(()=>import("./index-CrsvRs42.js"),__vite__mapDeps([0,1]),import.meta.url).catch(t=>{throw on=null,t})),on}function _d(t){const e=Qt(t,"markdown");return e===t.trim(),e}async function vd(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{markdown:n}=t;if(!n||typeof n!="string"||n.trim()==="")return{success:!1,error:"缺少必填参数 markdown,请提供有效的 Markdown 思维导图定义",type:"error"};try{const r=_d(n),i=await xd();let o;try{o=await i.parseMarkdownToDrawnix(r)}catch(m){console.warn("[MindmapTool] First parse attempt failed, retrying with quote replacement:",m.message),o=await i.parseMarkdownToDrawnix(r.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析成功,但未生成思维导图元素",type:"error"};o.points=[[0,0]];const l=fs(e,[o]);return l.success?{success:!0,data:{type:"mindmap",elementsCount:l.elementsCount,markdownPreview:r.substring(0,200)+(r.length>200?"...":"")},type:"canvas"}:{success:!1,error:l.error||"插入思维导图失败",type:"error"}}catch(r){return console.error("[MindmapTool] Failed to process markdown:",r),{success:!1,error:`思维导图转换失败: ${r.message||"未知错误"}`,type:"error"}}}const bd={name:"insert_mindmap",description:`将 Markdown 思维导图插入到画布工具。将 Markdown 语法转换为可视化思维导图并插入到画布中。
359
359
 
360
360
  使用场景:
361
361
  - 用户需要在画布上创建思维导图
@@ -397,8 +397,8 @@ sequenceDiagram
397
397
  - 算力成本
398
398
  - 数据安全
399
399
  - 伦理规范
400
- \`\`\``,inputSchema:{type:"object",properties:{markdown:{type:"string",description:"Markdown 格式的思维导图定义,支持标题和列表语法"}},required:["markdown"]},execute:async t=>_d(t)};function vd(){return jl.map(t=>`- ${t.style}(${t.labelZh}):${t.description}`).join(`
401
- `)}function Sd(t,e){const n=El.zh;return n(t,e.rows,e.cols)}function Id(t,e){const{theme:n,rows:r=$t.gridConfig.rows,cols:i=$t.gridConfig.cols,layoutStyle:o=$t.layoutStyle,imageSize:c=$t.imageSize,imageQuality:l=$t.imageQuality,referenceImages:m,model:u}=t,d=u||Or();if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 theme(主题描述)",type:"error"};const p=Math.min(Math.max(2,r),5),h=Math.min(Math.max(2,i),5),g={rows:p,cols:h},y=Sd(n,g),f=m==null?void 0:m.map((x,z)=>({type:"url",url:x,name:`reference-${z+1}`}));try{let x;if(e.retryTaskId){if(ft.retryTask(e.retryTaskId),x=ft.getTask(e.retryTaskId),!x)throw new Error(`重试任务不存在: ${e.retryTaskId}`)}else x=ft.createTask({prompt:y,size:c,model:d,uploadedImages:f&&f.length>0?f:void 0,params:{resolution:l},gridImageRows:p,gridImageCols:h,gridImageLayoutStyle:o,originalTheme:n,batchId:e.batchId,globalIndex:e.globalIndex||1,autoInsertToCanvas:!0},xt.IMAGE);return{success:!0,data:{taskId:x.id,theme:n,gridConfig:g,layoutStyle:o,prompt:y.substring(0,100)+"..."},type:"image",taskId:x.id,task:x}}catch(x){return console.error("[GridImageTool] Failed to create task:",x),{success:!1,error:x.message||"创建宫格图任务失败",type:"error"}}}const kd={name:"generate_grid_image",description:`宫格图生成工具。根据主题描述生成一组相关图片,并按照指定布局风格排列在画板上,形成宫格图效果。
400
+ \`\`\``,inputSchema:{type:"object",properties:{markdown:{type:"string",description:"Markdown 格式的思维导图定义,支持标题和列表语法"}},required:["markdown"]},execute:async t=>vd(t)};function Sd(){return Tl.map(t=>`- ${t.style}(${t.labelZh}):${t.description}`).join(`
401
+ `)}function Id(t,e){const n=Pl.zh;return n(t,e.rows,e.cols)}function kd(t,e){const{theme:n,rows:r=$t.gridConfig.rows,cols:i=$t.gridConfig.cols,layoutStyle:o=$t.layoutStyle,imageSize:c=$t.imageSize,imageQuality:l=$t.imageQuality,referenceImages:m,model:u}=t,d=u||Fr();if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 theme(主题描述)",type:"error"};const p=Math.min(Math.max(2,r),5),h=Math.min(Math.max(2,i),5),g={rows:p,cols:h},y=Id(n,g),f=m==null?void 0:m.map((x,z)=>({type:"url",url:x,name:`reference-${z+1}`}));try{let x;if(e.retryTaskId){if(ft.retryTask(e.retryTaskId),x=ft.getTask(e.retryTaskId),!x)throw new Error(`重试任务不存在: ${e.retryTaskId}`)}else x=ft.createTask({prompt:y,size:c,model:d,uploadedImages:f&&f.length>0?f:void 0,params:{resolution:l},gridImageRows:p,gridImageCols:h,gridImageLayoutStyle:o,originalTheme:n,batchId:e.batchId,globalIndex:e.globalIndex||1,autoInsertToCanvas:!0},xt.IMAGE);return{success:!0,data:{taskId:x.id,theme:n,gridConfig:g,layoutStyle:o,prompt:y.substring(0,100)+"..."},type:"image",taskId:x.id,task:x}}catch(x){return console.error("[GridImageTool] Failed to create task:",x),{success:!1,error:x.message||"创建宫格图任务失败",type:"error"}}}const Md={name:"generate_grid_image",description:`宫格图生成工具。根据主题描述生成一组相关图片,并按照指定布局风格排列在画板上,形成宫格图效果。
402
402
 
403
403
  使用场景:
404
404
  - 用户想要创建宫格图、图片墙、产品展示墙
@@ -412,11 +412,11 @@ sequenceDiagram
412
412
  4. 批量插入到画板
413
413
 
414
414
  可用布局风格:
415
- ${vd()}
415
+ ${Sd()}
416
416
 
417
417
  不适用场景:
418
418
  - 只想生成单张图片(使用 generate_image 工具)
419
- - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'宫格图主题描述,如"孟菲斯风格餐具"、"可爱猫咪表情包"、"复古相机收藏"等'},rows:{type:"number",description:"网格行数,2-5 之间,默认 3",default:3},cols:{type:"number",description:"网格列数,2-5 之间,默认 3",default:3},layoutStyle:{type:"string",description:"布局风格",enum:["scattered","grid","circular"],default:"scattered"},imageSize:{type:"string",description:"生成图片的尺寸比例",enum:["1x1","16x9","9x16","3x2","4x3"],default:"1x1"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型名称(可选,默认使用当前设置的模型)"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成多个相关主题的图片并以宫格图/拼贴画形式展示时使用。关键词:宫格图、九宫格、图片墙、表情包、产品展示、拼贴画、系列图片。",parameterGuidance:{theme:'主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体(如"不同品种的可爱猫咪"、"各种颜色的马卡龙")。避免:过于具体的单一描述(如"一只橘猫")。',rows:"根据内容数量决定:表情包通常3x3或4x4,产品展示2x3或3x4,大型展示4x4或5x5。",cols:"建议与rows相同创建正方形网格,或cols略大于rows创建横向布局。",layoutStyle:"scattered(散落)适合艺术感展示;grid(网格)适合产品目录;circular(环形)适合突出中心主题。"},bestPractices:['主题应强调多样性,如"各种姿态的猫咪"而非"一只猫"','描述具体的视觉风格,如"扁平插画风格"、"3D渲染"、"水彩画风"','对于表情包,明确情绪类型如"开心、惊讶、生气、困惑等表情"','对于产品展示,说明产品类别和风格如"北欧简约风格家具"'],examples:[{input:"生成一个猫咪表情包",args:{theme:"可爱猫咪表情包,包含开心、惊讶、生气、困惑、得意、卖萌等各种有趣表情,卡通风格",rows:4,cols:4,layoutStyle:"grid"},explanation:"表情包适合用网格布局,主题描述了多种表情变体"},{input:"做一个孟菲斯风格的餐具宫格图",args:{theme:"孟菲斯风格餐具,包含碗、盘、杯、勺等不同类型,色彩鲜艳,几何图案装饰,白色背景",rows:3,cols:3,layoutStyle:"scattered"},explanation:"散落布局增加艺术感,主题明确了风格和物品多样性"},{input:"创建花卉插画集",args:{theme:"水彩风格花卉插画,包含玫瑰、向日葵、郁金香、樱花、薰衣草等不同种类的花朵,柔和色彩",rows:4,cols:4,layoutStyle:"scattered"},explanation:"4x4网格提供更多展示空间,主题列举了多种花卉种类"},{input:"做个美食九宫格",args:{theme:"精致甜点美食摄影,包含蛋糕、马卡龙、泡芙、冰淇淋等各式甜品,俯视角度,浅色背景",rows:3,cols:3,layoutStyle:"grid"},explanation:"美食九宫格用网格布局更整齐,俯视角度适合食物展示"}],warnings:['避免主题过于抽象(如"美丽的东西"),应该具体到某类事物',"rows 和 cols 的乘积即生成图片数量,过大(如5x5=25张)会增加处理时间","生成后系统会自动拆分图片,请确保主题适合被分割成独立元素"]},execute:async(t,e)=>Id(t,e||{})};function Md(t,e){const n=Nl.zh;return n(t,e)}function Cd(t,e){const{theme:n,imageCount:r=Tl.imageCount,imageSize:i="16x9",imageQuality:o="2k",referenceImages:c,model:l}=t;if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 theme(主题描述)",type:"error"};const m=Math.min(Math.max(1,r),16),u=Md(n,m),d=l||Or(),p=c==null?void 0:c.map((h,g)=>({type:"url",url:h,name:`reference-${g+1}`}));try{let h;if(e.retryTaskId){if(ft.retryTask(e.retryTaskId),h=ft.getTask(e.retryTaskId),!h)throw new Error(`重试任务不存在: ${e.retryTaskId}`)}else h=ft.createTask({prompt:u,size:i,model:d,uploadedImages:p&&p.length>0?p:void 0,params:{resolution:o},isInspirationBoard:!0,inspirationBoardImageCount:m,inspirationBoardLayoutStyle:"inspiration-board",originalTheme:n,batchId:e.batchId,globalIndex:e.globalIndex||1,autoInsertToCanvas:!0},xt.IMAGE);return{success:!0,data:{taskId:h.id,theme:n,imageCount:m,prompt:u.substring(0,100)+"..."},type:"image",taskId:h.id,task:h}}catch(h){return console.error("[InspirationBoardTool] Failed to create task:",h),{success:!1,error:h.message||"创建灵感图任务失败",type:"error"}}}const jd={name:"generate_inspiration_board",description:`灵感图生成工具。根据主题描述生成一组等大小的高质量图片,
419
+ - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'宫格图主题描述,如"孟菲斯风格餐具"、"可爱猫咪表情包"、"复古相机收藏"等'},rows:{type:"number",description:"网格行数,2-5 之间,默认 3",default:3},cols:{type:"number",description:"网格列数,2-5 之间,默认 3",default:3},layoutStyle:{type:"string",description:"布局风格",enum:["scattered","grid","circular"],default:"scattered"},imageSize:{type:"string",description:"生成图片的尺寸比例",enum:["1x1","16x9","9x16","3x2","4x3"],default:"1x1"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型名称(可选,默认使用当前设置的模型)"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成多个相关主题的图片并以宫格图/拼贴画形式展示时使用。关键词:宫格图、九宫格、图片墙、表情包、产品展示、拼贴画、系列图片。",parameterGuidance:{theme:'主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体(如"不同品种的可爱猫咪"、"各种颜色的马卡龙")。避免:过于具体的单一描述(如"一只橘猫")。',rows:"根据内容数量决定:表情包通常3x3或4x4,产品展示2x3或3x4,大型展示4x4或5x5。",cols:"建议与rows相同创建正方形网格,或cols略大于rows创建横向布局。",layoutStyle:"scattered(散落)适合艺术感展示;grid(网格)适合产品目录;circular(环形)适合突出中心主题。"},bestPractices:['主题应强调多样性,如"各种姿态的猫咪"而非"一只猫"','描述具体的视觉风格,如"扁平插画风格"、"3D渲染"、"水彩画风"','对于表情包,明确情绪类型如"开心、惊讶、生气、困惑等表情"','对于产品展示,说明产品类别和风格如"北欧简约风格家具"'],examples:[{input:"生成一个猫咪表情包",args:{theme:"可爱猫咪表情包,包含开心、惊讶、生气、困惑、得意、卖萌等各种有趣表情,卡通风格",rows:4,cols:4,layoutStyle:"grid"},explanation:"表情包适合用网格布局,主题描述了多种表情变体"},{input:"做一个孟菲斯风格的餐具宫格图",args:{theme:"孟菲斯风格餐具,包含碗、盘、杯、勺等不同类型,色彩鲜艳,几何图案装饰,白色背景",rows:3,cols:3,layoutStyle:"scattered"},explanation:"散落布局增加艺术感,主题明确了风格和物品多样性"},{input:"创建花卉插画集",args:{theme:"水彩风格花卉插画,包含玫瑰、向日葵、郁金香、樱花、薰衣草等不同种类的花朵,柔和色彩",rows:4,cols:4,layoutStyle:"scattered"},explanation:"4x4网格提供更多展示空间,主题列举了多种花卉种类"},{input:"做个美食九宫格",args:{theme:"精致甜点美食摄影,包含蛋糕、马卡龙、泡芙、冰淇淋等各式甜品,俯视角度,浅色背景",rows:3,cols:3,layoutStyle:"grid"},explanation:"美食九宫格用网格布局更整齐,俯视角度适合食物展示"}],warnings:['避免主题过于抽象(如"美丽的东西"),应该具体到某类事物',"rows 和 cols 的乘积即生成图片数量,过大(如5x5=25张)会增加处理时间","生成后系统会自动拆分图片,请确保主题适合被分割成独立元素"]},execute:async(t,e)=>kd(t,e||{})};function Cd(t,e){const n=El.zh;return n(t,e)}function jd(t,e){const{theme:n,imageCount:r=Nl.imageCount,imageSize:i="16x9",imageQuality:o="2k",referenceImages:c,model:l}=t;if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 theme(主题描述)",type:"error"};const m=Math.min(Math.max(1,r),16),u=Cd(n,m),d=l||Fr(),p=c==null?void 0:c.map((h,g)=>({type:"url",url:h,name:`reference-${g+1}`}));try{let h;if(e.retryTaskId){if(ft.retryTask(e.retryTaskId),h=ft.getTask(e.retryTaskId),!h)throw new Error(`重试任务不存在: ${e.retryTaskId}`)}else h=ft.createTask({prompt:u,size:i,model:d,uploadedImages:p&&p.length>0?p:void 0,params:{resolution:o},isInspirationBoard:!0,inspirationBoardImageCount:m,inspirationBoardLayoutStyle:"inspiration-board",originalTheme:n,batchId:e.batchId,globalIndex:e.globalIndex||1,autoInsertToCanvas:!0},xt.IMAGE);return{success:!0,data:{taskId:h.id,theme:n,imageCount:m,prompt:u.substring(0,100)+"..."},type:"image",taskId:h.id,task:h}}catch(h){return console.error("[InspirationBoardTool] Failed to create task:",h),{success:!1,error:h.message||"创建灵感图任务失败",type:"error"}}}const Td={name:"generate_inspiration_board",description:`灵感图生成工具。根据主题描述生成一组等大小的高质量图片,
420
420
  以散落的横向布局插入画板,形成有创意感的灵感板效果。
421
421
 
422
422
  生成策略(重要):
@@ -443,7 +443,7 @@ ${vd()}
443
443
  不适用场景:
444
444
  - 只想生成单张图片(使用 generate_image 工具)
445
445
  - 想要整齐的网格排列(使用 generate_grid_image 工具)
446
- - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'灵感图主题描述,如"可爱香蕉的各种形态"、"咖啡文化"、"城市街角"等'},imageCount:{type:"number",description:"图片数量,1-16 之间,默认 9",default:9},imageSize:{type:"string",description:"生成图片的尺寸比例(建议横向)",enum:["16x9","3x2","1x1"],default:"16x9"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型,不指定时使用用户设置的模型"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成创意灵感图、灵感板、Mood Board 效果时使用。关键词:灵感图、灵感板、创意拼贴、艺术展示、Mood Board、Pinterest 风格。",parameterGuidance:{theme:"主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体、不同角度或不同场景。避免过于具体的单一描述。",imageCount:"1-16 张,会自动计算最优网格布局(如 9 张 = 3x3,12 张 = 3x4)。",imageSize:"建议使用 16x9 横向比例,生成更大尺寸的图片。"},bestPractices:['主题应强调多样性和变化,如"咖啡的各种形态"而非"一杯咖啡"','可以指定风格混搭,如"写实与插画混合"、"不同时代风格"',"描述具体的视觉元素,帮助 AI 生成更丰富的内容","生成的是紧凑网格图,拆分后每张子图都是高质量大图"],examples:[{input:"生成一个可爱香蕉的灵感图",args:{theme:"可爱香蕉的各种形态,包含卡通香蕉、写实香蕉、香蕉角色、香蕉图案等不同风格",imageCount:9},explanation:"生成 3x3 网格,拆分后 9 张等大图片以散落布局插入"},{input:"做个城市街角的 Mood Board",args:{theme:"城市街角,包含不同城市、不同时间、不同天气、不同风格的街角场景",imageCount:8,imageSize:"16x9"},explanation:"生成 2x4 网格,横向布局更适合展示街景"}],warnings:["生成的是紧凑网格生产图,拆分后以散落布局插入画布","实际图片数量取决于网格布局(如 7 张会调整为 2x4 = 8 张)","建议使用横向比例(16x9)以获得更大的子图尺寸"]},execute:async(t,e)=>Cd(t,e||{})};function Td(t){return!t||typeof t!="string"?!1:t.startsWith("http://")||t.startsWith("https://")||t.startsWith("data:image/")||t.startsWith("blob:")}async function Nd(t,e){const{imageUrl:n}=t;if(!Td(n))return{success:!1,error:"无效的图片 URL,支持 http/https/base64/blob 格式",type:"error"};const r=wo();if(!r)return{success:!1,error:"画板未初始化",type:"error"};try{const i=await ea(r,n,{scrollToResult:!0});return i.success?{success:!0,data:{count:i.count},type:"text"}:{success:!1,error:i.error||"拆分失败",type:"error"}}catch(i){return console.error("[SplitImageTool] Execution failed:",i),{success:!1,error:i.message||"拆分执行失败",type:"error"}}}const Ed={name:"split_image",description:`图片拆分工具。将一张包含多个元素的图片拆分成多个独立图片,并插入到画板中。
446
+ - 想要生成视频(使用 generate_video 工具)`,inputSchema:{type:"object",properties:{theme:{type:"string",description:'灵感图主题描述,如"可爱香蕉的各种形态"、"咖啡文化"、"城市街角"等'},imageCount:{type:"number",description:"图片数量,1-16 之间,默认 9",default:9},imageSize:{type:"string",description:"生成图片的尺寸比例(建议横向)",enum:["16x9","3x2","1x1"],default:"16x9"},imageQuality:{type:"string",description:"图片质量",enum:["1k","2k","4k"],default:"2k"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于风格参考",items:{type:"string"}},model:{type:"string",description:"图片生成模型,不指定时使用用户设置的模型"}},required:["theme"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成创意灵感图、灵感板、Mood Board 效果时使用。关键词:灵感图、灵感板、创意拼贴、艺术展示、Mood Board、Pinterest 风格。",parameterGuidance:{theme:"主题描述应该具体且有多样性潜力。好的主题:描述一类事物的多种变体、不同角度或不同场景。避免过于具体的单一描述。",imageCount:"1-16 张,会自动计算最优网格布局(如 9 张 = 3x3,12 张 = 3x4)。",imageSize:"建议使用 16x9 横向比例,生成更大尺寸的图片。"},bestPractices:['主题应强调多样性和变化,如"咖啡的各种形态"而非"一杯咖啡"','可以指定风格混搭,如"写实与插画混合"、"不同时代风格"',"描述具体的视觉元素,帮助 AI 生成更丰富的内容","生成的是紧凑网格图,拆分后每张子图都是高质量大图"],examples:[{input:"生成一个可爱香蕉的灵感图",args:{theme:"可爱香蕉的各种形态,包含卡通香蕉、写实香蕉、香蕉角色、香蕉图案等不同风格",imageCount:9},explanation:"生成 3x3 网格,拆分后 9 张等大图片以散落布局插入"},{input:"做个城市街角的 Mood Board",args:{theme:"城市街角,包含不同城市、不同时间、不同天气、不同风格的街角场景",imageCount:8,imageSize:"16x9"},explanation:"生成 2x4 网格,横向布局更适合展示街景"}],warnings:["生成的是紧凑网格生产图,拆分后以散落布局插入画布","实际图片数量取决于网格布局(如 7 张会调整为 2x4 = 8 张)","建议使用横向比例(16x9)以获得更大的子图尺寸"]},execute:async(t,e)=>jd(t,e||{})};function Nd(t){return!t||typeof t!="string"?!1:t.startsWith("http://")||t.startsWith("https://")||t.startsWith("data:image/")||t.startsWith("blob:")}async function Ed(t,e){const{imageUrl:n}=t;if(!Nd(n))return{success:!1,error:"无效的图片 URL,支持 http/https/base64/blob 格式",type:"error"};const r=yo();if(!r)return{success:!1,error:"画板未初始化",type:"error"};try{const i=await ta(r,n,{scrollToResult:!0});return i.success?{success:!0,data:{count:i.count},type:"text"}:{success:!1,error:i.error||"拆分失败",type:"error"}}catch(i){return console.error("[SplitImageTool] Execution failed:",i),{success:!1,error:i.message||"拆分执行失败",type:"error"}}}const Pd={name:"split_image",description:`图片拆分工具。将一张包含多个元素的图片拆分成多个独立图片,并插入到画板中。
447
447
 
448
448
  使用场景:
449
449
  - 用户有一张九宫格/拼贴图,想要拆分成独立图片
@@ -460,7 +460,7 @@ ${vd()}
460
460
  不适用场景:
461
461
  - 想要生成图片(使用 generate_image 工具)
462
462
  - 想要生成宫格图(使用 generate_grid_image 工具)
463
- - 图片没有分割线也不是规则网格结构`,inputSchema:{type:"object",properties:{imageUrl:{type:"string",description:"要拆分的图片 URL(支持 http/https/base64/blob 格式)"}},required:["imageUrl"]},supportedModes:["direct"],execute:async(t,e)=>Nd(t)},Pn={SVG_DEFAULT_WIDTH:400,SVG_MAX_WIDTH:800,SVG_MIN_WIDTH:100};function Pd(t){let e=Qt(t,"svg");if(e===t&&(e=Qt(t,"xml")),e===t&&!e.trim().startsWith("<svg")){const n=e.match(/<svg[\s\S]*?<\/svg>/i);n&&(e=n[0])}return e.trim()}function Ad(t){if(!t||typeof t!="string")return{valid:!1,error:"缺少SVG代码"};const e=t.trim();return!e.startsWith("<svg")&&!e.startsWith("<?xml")?{valid:!1,error:"SVG代码格式无效,必须以<svg开头"}:e.includes("</svg>")?{valid:!0}:{valid:!1,error:"SVG代码不完整,缺少</svg>结束标签"}}async function Rd(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{svg:n,startPoint:r,width:i}=t,o=Ad(n);if(!o.valid)return{success:!1,error:o.error||"SVG代码无效",type:"error"};try{const c=Mr(Pd(n)),l=Cr(c),m=Math.min(Math.max(i||Pn.SVG_DEFAULT_WIDTH,Pn.SVG_MIN_WIDTH),Pn.SVG_MAX_WIDTH),u=l.height/l.width,d=m*u,p=jr(c);let h=r;h||(h=Bn(e,{align:"center",logPrefix:"SvgTool"})),h||(h=Gn(e,{align:"center",emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT),h=[h[0]-m/2,h[1]];const g={url:p,width:m,height:d};Yn.insertImage(e,g,h);const y=[h[0]+m/2,h[1]+d/2];return requestAnimationFrame(()=>{qt(e,y)}),{success:!0,data:{width:m,height:d,position:h,svgPreview:c.substring(0,200)+(c.length>200?"...":"")},type:"canvas"}}catch(c){return console.error("[SvgTool] Failed to process SVG:",c),{success:!1,error:`SVG插入失败: ${c.message||"未知错误"}`,type:"error"}}}const zd={name:"insert_svg",description:`将SVG矢量图插入到画布工具。将SVG代码转换为可缩放矢量图形并插入到画布中。
463
+ - 图片没有分割线也不是规则网格结构`,inputSchema:{type:"object",properties:{imageUrl:{type:"string",description:"要拆分的图片 URL(支持 http/https/base64/blob 格式)"}},required:["imageUrl"]},supportedModes:["direct"],execute:async(t,e)=>Ed(t)},Pn={SVG_DEFAULT_WIDTH:400,SVG_MAX_WIDTH:800,SVG_MIN_WIDTH:100};function Ad(t){let e=Qt(t,"svg");if(e===t&&(e=Qt(t,"xml")),e===t&&!e.trim().startsWith("<svg")){const n=e.match(/<svg[\s\S]*?<\/svg>/i);n&&(e=n[0])}return e.trim()}function Rd(t){if(!t||typeof t!="string")return{valid:!1,error:"缺少SVG代码"};const e=t.trim();return!e.startsWith("<svg")&&!e.startsWith("<?xml")?{valid:!1,error:"SVG代码格式无效,必须以<svg开头"}:e.includes("</svg>")?{valid:!0}:{valid:!1,error:"SVG代码不完整,缺少</svg>结束标签"}}async function zd(t){const e=en();if(!e)return{success:!1,error:"画布未初始化,请先打开画布",type:"error"};const{svg:n,startPoint:r,width:i}=t,o=Rd(n);if(!o.valid)return{success:!1,error:o.error||"SVG代码无效",type:"error"};try{const c=Cr(Ad(n)),l=jr(c),m=Math.min(Math.max(i||Pn.SVG_DEFAULT_WIDTH,Pn.SVG_MIN_WIDTH),Pn.SVG_MAX_WIDTH),u=l.height/l.width,d=m*u,p=Tr(c);let h=r;h||(h=Bn(e,{align:"center",logPrefix:"SvgTool"})),h||(h=Gn(e,{align:"center",emptyPoint:Ue.DEFAULT_POINT})||Ue.DEFAULT_POINT),h=[h[0]-m/2,h[1]];const g={url:p,width:m,height:d};Yn.insertImage(e,g,h);const y=[h[0]+m/2,h[1]+d/2];return requestAnimationFrame(()=>{qt(e,y)}),{success:!0,data:{width:m,height:d,position:h,svgPreview:c.substring(0,200)+(c.length>200?"...":"")},type:"canvas"}}catch(c){return console.error("[SvgTool] Failed to process SVG:",c),{success:!1,error:`SVG插入失败: ${c.message||"未知错误"}`,type:"error"}}}const Dd={name:"insert_svg",description:`将SVG矢量图插入到画布工具。将SVG代码转换为可缩放矢量图形并插入到画布中。
464
464
 
465
465
  使用场景:
466
466
  - 用户需要在画布上创建图标、Logo、徽章等矢量图
@@ -491,7 +491,7 @@ SVG的优势:
491
491
  <path d="M50 10 L60 50 L55 50 L55 70 L45 70 L45 50 L40 50 Z" fill="#E67E22"/>
492
492
  <circle cx="50" cy="35" r="5" fill="#5A4FCF"/>
493
493
  <path d="M45 70 L40 85 L50 75 L60 85 L55 70" fill="#F39C12"/>
494
- </svg>`,width:300},explanation:"生成简约火箭图标,使用品牌色彩"}],warnings:["不要生成过于复杂的SVG,可能导致渲染性能问题","确保SVG代码格式正确,包含完整的开始和结束标签"]},execute:async t=>Rd(t)},Eo=8,Dd="veo3.1";function Ld(t,e,n){const r=n?`
494
+ </svg>`,width:300},explanation:"生成简约火箭图标,使用品牌色彩"}],warnings:["不要生成过于复杂的SVG,可能导致渲染性能问题","确保SVG代码格式正确,包含完整的开始和结束标签"]},execute:async t=>zd(t)},Po=8,Ld="veo3.1";function $d(t,e,n){const r=n?`
495
495
  角色一致性要求(极其重要!):
496
496
  - 视频中有固定角色,描述为:"${n}"
497
497
  - 每个片段的 prompt 必须以 "The same ${n}," 开头
@@ -531,13 +531,13 @@ ${r}
531
531
  - 相邻片段的结尾和开头要能自然衔接(因为会用尾帧作为下一段首帧)
532
532
  - transition_hint 从 'cut'/'dissolve'/'match_cut'/'fade_to_black' 中选择
533
533
  - 最后一个片段的 transition_hint 设为 'fade_to_black'
534
- - 最后一个片段要有完整的收尾`}function $d(t){try{const e=ta(t,n=>Array.isArray(n.segments));return Array.isArray(e.segments)?e.segments.map((n,r)=>({index:n.index||r+1,prompt:n.prompt||"",duration:n.duration||Eo,transition_hint:n.transition_hint||void 0,end_frame_description:n.end_frame_description||void 0})):(console.error("[LongVideo] Invalid script format: segments is not an array"),[])}catch(e){return console.error("[LongVideo] Failed to parse script:",e),[]}}async function Od(t,e,n,r,i){const c=at.get().textModelName,m=[{role:"system",content:[{type:"text",text:Ld(e,n,r)}]},{role:"user",content:[{type:"text",text:`视频主题:${t}`}]}];let u="";const d=await Zt.sendChat(m,p=>{u+=p,i==null||i(p)},void 0,c);return d.choices&&d.choices.length>0&&(u=d.choices[0].message.content||u),$d(u)}function Fd(t,e,n){const r=[];n&&r.push({slot:0,slotLabel:"首帧",url:n,name:"first-frame.png"});const i=e.characterReferenceUrls&&e.characterReferenceUrls.length>0?e.characterReferenceUrls:void 0;return ft.createTask({prompt:t.prompt,size:e.size,duration:t.duration,model:e.model,uploadedImages:r.length>0?r:void 0,referenceImages:i,longVideoMeta:e,batchId:e.batchId,batchIndex:t.index,batchTotal:e.totalSegments},xt.VIDEO)}async function Ud(t,e){var d,p,h,g,y,f,x,z,N,O,T,I;const{prompt:n,totalDuration:r=60,segmentDuration:i=Eo,model:o=Dd,size:c="16x9",firstFrameImage:l,characterDescription:m}=t;if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 prompt",type:"error"};const u=Ct[o];(!u||u.imageUpload.mode!=="frames")&&console.warn(`[LongVideo] Model ${o} does not support first/last frame, using veo3.1`);try{const b=Math.ceil(r/i);(d=e.onChunk)==null||d.call(e,`正在为您规划 ${r} 秒的长视频,分为 ${b} 个片段...
534
+ - 最后一个片段要有完整的收尾`}function Od(t){try{const e=na(t,n=>Array.isArray(n.segments));return Array.isArray(e.segments)?e.segments.map((n,r)=>({index:n.index||r+1,prompt:n.prompt||"",duration:n.duration||Po,transition_hint:n.transition_hint||void 0,end_frame_description:n.end_frame_description||void 0})):(console.error("[LongVideo] Invalid script format: segments is not an array"),[])}catch(e){return console.error("[LongVideo] Failed to parse script:",e),[]}}async function Fd(t,e,n,r,i){const c=at.get().textModelName,m=[{role:"system",content:[{type:"text",text:$d(e,n,r)}]},{role:"user",content:[{type:"text",text:`视频主题:${t}`}]}];let u="";const d=await Zt.sendChat(m,p=>{u+=p,i==null||i(p)},void 0,c);return d.choices&&d.choices.length>0&&(u=d.choices[0].message.content||u),Od(u)}function Ud(t,e,n){const r=[];n&&r.push({slot:0,slotLabel:"首帧",url:n,name:"first-frame.png"});const i=e.characterReferenceUrls&&e.characterReferenceUrls.length>0?e.characterReferenceUrls:void 0;return ft.createTask({prompt:t.prompt,size:e.size,duration:t.duration,model:e.model,uploadedImages:r.length>0?r:void 0,referenceImages:i,longVideoMeta:e,batchId:e.batchId,batchIndex:t.index,batchTotal:e.totalSegments},xt.VIDEO)}async function Wd(t,e){var d,p,h,g,y,f,x,z,N,O,T,I;const{prompt:n,totalDuration:r=60,segmentDuration:i=Po,model:o=Ld,size:c="16x9",firstFrameImage:l,characterDescription:m}=t;if(!n||typeof n!="string")return{success:!1,error:"缺少必填参数 prompt",type:"error"};const u=Ct[o];(!u||u.imageUpload.mode!=="frames")&&console.warn(`[LongVideo] Model ${o} does not support first/last frame, using veo3.1`);try{const v=Math.ceil(r/i);(d=e.onChunk)==null||d.call(e,`正在为您规划 ${r} 秒的长视频,分为 ${v} 个片段...
535
535
 
536
- `);const S=await Od(n,b,i,m,e.onChunk);if(S.length===0)return{success:!1,error:"视频脚本生成失败,请重试",type:"error"};(p=e.onChunk)==null||p.call(e,`
536
+ `);const S=await Fd(n,v,i,m,e.onChunk);if(S.length===0)return{success:!1,error:"视频脚本生成失败,请重试",type:"error"};(p=e.onChunk)==null||p.call(e,`
537
537
 
538
538
  ✓ 脚本生成完成,共 ${S.length} 个片段
539
539
 
540
- `);const C=`long_video_${Date.now()}`,R=S[0],U={batchId:C,segmentIndex:1,totalSegments:S.length,needsLastFrame:S.length>1,scripts:S,model:o,size:c,characterDescription:m},P=Fd(R,U,l);return(h=e.onAddSteps)==null||h.call(e,[{id:P.id,mcp:"generate_video",args:{prompt:R.prompt,model:o,size:c},description:`生成视频片段 1/${S.length}: ${R.prompt.substring(0,50)}...`,status:"completed",options:{mode:"queue",batchId:C,batchIndex:1,batchTotal:S.length,globalIndex:1}}]),(g=e.onChunk)==null||g.call(e,`
540
+ `);const C=`long_video_${Date.now()}`,R=S[0],U={batchId:C,segmentIndex:1,totalSegments:S.length,needsLastFrame:S.length>1,scripts:S,model:o,size:c,characterDescription:m},P=Ud(R,U,l);return(h=e.onAddSteps)==null||h.call(e,[{id:P.id,mcp:"generate_video",args:{prompt:R.prompt,model:o,size:c},description:`生成视频片段 1/${S.length}: ${R.prompt.substring(0,50)}...`,status:"completed",options:{mode:"queue",batchId:C,batchIndex:1,batchTotal:S.length,globalIndex:1}}]),(g=e.onChunk)==null||g.call(e,`
541
541
  ✓ 已创建第 1 个视频生成任务
542
542
  `),(y=e.onChunk)==null||y.call(e,`
543
543
  📊 **长视频生成计划**:
@@ -549,7 +549,7 @@ ${r}
549
549
  `),(O=e.onChunk)==null||O.call(e,`- 每段视频生成完成后,系统会自动提取尾帧作为下一段的首帧,确保画面连贯
550
550
  `),(T=e.onChunk)==null||T.call(e,`- 所有片段生成完成后会自动合并并插入画布
551
551
  `),(I=e.onChunk)==null||I.call(e,`- 您可以在任务队列中查看实时进度
552
- `),{success:!0,data:{batchId:C,taskId:P.id,segmentCount:S.length,totalDuration:r,scripts:S},type:"video",taskId:P.id}}catch(b){return console.error("[LongVideo] Generation failed:",b),{success:!1,error:b.message||"长视频生成失败",type:"error"}}}const Wd={name:"generate_long_video",description:`生成长视频工具。用于生成超过单个模型时长限制的长视频(如1分钟)。
552
+ `),{success:!0,data:{batchId:C,taskId:P.id,segmentCount:S.length,totalDuration:r,scripts:S},type:"video",taskId:P.id}}catch(v){return console.error("[LongVideo] Generation failed:",v),{success:!1,error:v.message||"长视频生成失败",type:"error"}}}const Hd={name:"generate_long_video",description:`生成长视频工具。用于生成超过单个模型时长限制的长视频(如1分钟)。
553
553
 
554
554
  使用场景:
555
555
  - 用户想要生成1分钟或更长的视频
@@ -563,23 +563,23 @@ ${r}
563
563
 
564
564
  不适用场景:
565
565
  - 用户只需要一个短视频(15秒以内),使用 generate_video 工具
566
- - 用户只是在聊天,没有生成视频的意图`,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"视频主题/故事描述,详细描述想要生成的视频内容、故事情节"},totalDuration:{type:"number",description:"目标总时长(秒),默认 60 秒",default:60},segmentDuration:{type:"number",description:"每个片段的时长(秒),默认 8 秒",default:8},model:{type:"string",description:"视频生成模型,默认使用 veo3.1(支持首尾帧)",default:"veo3.1"},size:{type:"string",description:"视频尺寸,默认 16x9",default:"16x9"},firstFrameImage:{type:"string",description:"第一段视频的首帧参考图片 URL(可选)"}},required:["prompt"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成超过15秒的长视频时使用,特别是1分钟视频。关键词:长视频、1分钟、完整故事、多场景。",parameterGuidance:{prompt:"用户的视频主题或故事描述,可以是一个完整的故事大纲。工具会自动将其拆分为多个连贯的片段。",totalDuration:'默认60秒(1分钟)。用户说"1分钟视频"时设为60,"30秒"设为30。',segmentDuration:"每段视频时长,默认8秒。这个值通常不需要用户指定。",model:"默认使用 veo3.1,因为它支持首尾帧,能保证片段间的连贯性。",firstFrameImage:'可选参数。当用户选中图片并希望从该图片开始生成视频时使用。传递 "[图片1]" 等占位符,系统会自动替换为真实URL。'},bestPractices:["将用户的描述直接传给 prompt,工具会自动调用文本模型生成分段脚本","不需要用户提供详细的分段描述,工具会自动规划","建议提醒用户长视频生成需要较长时间(每段约1-3分钟)","如果用户选中了图片,可以将其作为 firstFrameImage 传递,这样第一段视频会从该图片开始"],examples:[{input:"帮我生成一个1分钟的视频,讲述一只猫咪从早到晚的一天",args:{prompt:"一只可爱的橘猫从早到晚的一天生活:清晨在窗台晒太阳、中午在厨房偷吃鱼、下午追逐蝴蝶玩耍、傍晚蜷缩在沙发上打盹、夜晚望着月亮",totalDuration:60}},{input:"创作一个30秒的日落延时视频",args:{prompt:"从太阳开始下山到完全落入地平线的日落延时摄影,天空从金色渐变为橙色再到粉紫色",totalDuration:30}},{input:"[图片1] 让这个场景动起来,生成30秒视频",args:{prompt:"Cinematic video starting from this scene, camera slowly panning around, natural ambient movement, objects gently swaying, dynamic lighting changes, smooth transitions",totalDuration:30,firstFrameImage:"[图片1]"}}],warnings:["长视频生成需要较长时间,每个片段约1-3分钟,且串行生成","生成完成后会产生多个独立的视频文件,需要用户手动下载或合并","确保使用支持首尾帧的模型(如 veo3.1)以保证片段间的连贯性"]},execute:async(t,e)=>Ud(t,e||{})};function Hd(t){return ha(t)&&!!t.pptMeta}function Vd(t){const e=t.pptMeta;return e?[e.slideImageElementId,...(e.slideImageHistory||[]).map(n=>n.elementId)].filter(n=>typeof n=="string"&&n.length>0):[]}function Bd(t,e){for(let n=t.children.length-1;n>=0;n-=1)e.has(t.children[n].id)&&ss.removeNode(t,[n])}function Gd(t){const e=t.children.filter(Hd);if(e.length===0)return 0;const n=new Set(e.map(o=>o.id)),r=Ur.getFrameContents(t,n),i=new Set(r.map(o=>o.id));for(const o of e)for(const c of Vd(o))i.add(c);return Bd(t,i),e.length}function qd(t,e){const n=$n.getRectangleByPoints(e.points),r=80,i=ts.getBoardContainer(t),o=(i==null?void 0:i.clientWidth)??1920,c=(i==null?void 0:i.clientHeight)??1080,l=o/(n.width+r*2),m=c/(n.height+r*2),u=Math.min(l,m,1),d=n.x+n.width/2,p=n.y+n.height/2,h=[d-o/2/u,p-c/2/u];pa.updateViewport(t,h,u)}async function Kd(t,e){const n=at.get(),r=e.textModelRef||e.textModel||e.modelRef||e.model||n.textModelName,i=ia({pageCount:e.pageCount,language:e.language,extraRequirements:e.extraRequirements}),o=aa(t,e),c=(e.referenceImages||[]).filter(Boolean);let l=[{role:"system",content:[{type:"text",text:i}]},{role:"user",content:[{type:"text",text:o}]}];if(c.length>0){let d=null;try{d=Xn("text",r)}catch{d=null}if(Jn(d==null?void 0:d.binding))try{const p=await Tr(c,Qn(d==null?void 0:d.binding));l=Nr(l,p)}catch(p){console.warn("[PPT] Failed to attach reference images:",p)}}let m="";const u=await Zt.sendChat(l,void 0,void 0,r);return u.choices&&u.choices.length>0&&(m=u.choices[0].message.content||m),ca(m,e)}function Zd(t,e,n,r,i,o){const c=Fr(o.referenceImages),l={...o,referenceImages:c},m=[i,[i[0]+la,i[1]+da]],u=n.title||`Slide ${r}`,d=Ur.insertFrame(t,m,u),p=ua(e,n,r,l),h={deckTitle:e.title,layout:n.layout,pageIndex:r,slidePrompt:p,styleSpec:e.styleSpec,commonPrompt:ma(e.styleSpec,l),slideImageStatus:"placeholder",imageStatus:"placeholder"};c.length>0&&(h.referenceImages=c),n.imagePrompt&&(h.imagePrompt=n.imagePrompt),n.notes&&(h.notes=n.notes);const g=t.children.findIndex(y=>y.id===d.id);return g!==-1&&ss.setNode(t,{pptMeta:h},[g]),{frame:d,slidePrompt:p}}async function Yd(t,e){var m,u,d,p,h,g,y,f,x,z,N,O,T;const{topic:n,pageCount:r,language:i,extraRequirements:o}=t,c=Date.now();if(!n||typeof n!="string")return ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"failed",error:"MissingTopic"}),{success:!1,error:"缺少必填参数 topic(PPT 主题)",type:"error"};const l=en();if(!l)return ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"failed",prompt:n,error:"BoardUnavailable"}),{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{const I=(t.referenceImages||[]).filter(Boolean),b=Fr(t.referenceImages),S={...t,referenceImages:b},C=at.get(),R=t.textModelRef||t.textModel||t.modelRef||t.model||C.textModelName,U=typeof R=="string"?R:(R==null?void 0:R.modelId)||C.textModelName;ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"start",model:U,prompt:n,metadata:{page_count_option:r||"normal",has_extra_requirements:!!(o!=null&&o.trim()),reference_image_count:b.length,language:i}}),(m=e.onChunk)==null||m.call(e,`🎯 正在为「${n}」生成 PPT 大纲...
566
+ - 用户只是在聊天,没有生成视频的意图`,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"视频主题/故事描述,详细描述想要生成的视频内容、故事情节"},totalDuration:{type:"number",description:"目标总时长(秒),默认 60 秒",default:60},segmentDuration:{type:"number",description:"每个片段的时长(秒),默认 8 秒",default:8},model:{type:"string",description:"视频生成模型,默认使用 veo3.1(支持首尾帧)",default:"veo3.1"},size:{type:"string",description:"视频尺寸,默认 16x9",default:"16x9"},firstFrameImage:{type:"string",description:"第一段视频的首帧参考图片 URL(可选)"}},required:["prompt"]},supportedModes:["queue"],promptGuidance:{whenToUse:"当用户想要生成超过15秒的长视频时使用,特别是1分钟视频。关键词:长视频、1分钟、完整故事、多场景。",parameterGuidance:{prompt:"用户的视频主题或故事描述,可以是一个完整的故事大纲。工具会自动将其拆分为多个连贯的片段。",totalDuration:'默认60秒(1分钟)。用户说"1分钟视频"时设为60,"30秒"设为30。',segmentDuration:"每段视频时长,默认8秒。这个值通常不需要用户指定。",model:"默认使用 veo3.1,因为它支持首尾帧,能保证片段间的连贯性。",firstFrameImage:'可选参数。当用户选中图片并希望从该图片开始生成视频时使用。传递 "[图片1]" 等占位符,系统会自动替换为真实URL。'},bestPractices:["将用户的描述直接传给 prompt,工具会自动调用文本模型生成分段脚本","不需要用户提供详细的分段描述,工具会自动规划","建议提醒用户长视频生成需要较长时间(每段约1-3分钟)","如果用户选中了图片,可以将其作为 firstFrameImage 传递,这样第一段视频会从该图片开始"],examples:[{input:"帮我生成一个1分钟的视频,讲述一只猫咪从早到晚的一天",args:{prompt:"一只可爱的橘猫从早到晚的一天生活:清晨在窗台晒太阳、中午在厨房偷吃鱼、下午追逐蝴蝶玩耍、傍晚蜷缩在沙发上打盹、夜晚望着月亮",totalDuration:60}},{input:"创作一个30秒的日落延时视频",args:{prompt:"从太阳开始下山到完全落入地平线的日落延时摄影,天空从金色渐变为橙色再到粉紫色",totalDuration:30}},{input:"[图片1] 让这个场景动起来,生成30秒视频",args:{prompt:"Cinematic video starting from this scene, camera slowly panning around, natural ambient movement, objects gently swaying, dynamic lighting changes, smooth transitions",totalDuration:30,firstFrameImage:"[图片1]"}}],warnings:["长视频生成需要较长时间,每个片段约1-3分钟,且串行生成","生成完成后会产生多个独立的视频文件,需要用户手动下载或合并","确保使用支持首尾帧的模型(如 veo3.1)以保证片段间的连贯性"]},execute:async(t,e)=>Wd(t,e||{})};function Vd(t){return fa(t)&&!!t.pptMeta}function Bd(t){const e=t.pptMeta;return e?[e.slideImageElementId,...(e.slideImageHistory||[]).map(n=>n.elementId)].filter(n=>typeof n=="string"&&n.length>0):[]}function Gd(t,e){for(let n=t.children.length-1;n>=0;n-=1)e.has(t.children[n].id)&&ss.removeNode(t,[n])}function qd(t){const e=t.children.filter(Vd);if(e.length===0)return 0;const n=new Set(e.map(o=>o.id)),r=Wr.getFrameContents(t,n),i=new Set(r.map(o=>o.id));for(const o of e)for(const c of Bd(o))i.add(c);return Gd(t,i),e.length}function Kd(t,e){const n=$n.getRectangleByPoints(e.points),r=80,i=ts.getBoardContainer(t),o=(i==null?void 0:i.clientWidth)??1920,c=(i==null?void 0:i.clientHeight)??1080,l=o/(n.width+r*2),m=c/(n.height+r*2),u=Math.min(l,m,1),d=n.x+n.width/2,p=n.y+n.height/2,h=[d-o/2/u,p-c/2/u];ha.updateViewport(t,h,u)}async function Zd(t,e){const n=at.get(),r=e.textModelRef||e.textModel||e.modelRef||e.model||n.textModelName,i=aa({pageCount:e.pageCount,language:e.language,extraRequirements:e.extraRequirements}),o=ca(t,e),c=(e.referenceImages||[]).filter(Boolean);let l=[{role:"system",content:[{type:"text",text:i}]},{role:"user",content:[{type:"text",text:o}]}];if(c.length>0){let d=null;try{d=Xn("text",r)}catch{d=null}if(Jn(d==null?void 0:d.binding))try{const p=await Nr(c,Qn(d==null?void 0:d.binding));l=Er(l,p)}catch(p){console.warn("[PPT] Failed to attach reference images:",p)}}let m="";const u=await Zt.sendChat(l,void 0,void 0,r);return u.choices&&u.choices.length>0&&(m=u.choices[0].message.content||m),la(m,e)}function Yd(t,e,n,r,i,o){const c=Ur(o.referenceImages),l={...o,referenceImages:c},m=[i,[i[0]+da,i[1]+ua]],u=n.title||`Slide ${r}`,d=Wr.insertFrame(t,m,u),p=ma(e,n,r,l),h={deckTitle:e.title,layout:n.layout,pageIndex:r,slidePrompt:p,styleSpec:e.styleSpec,commonPrompt:pa(e.styleSpec,l),slideImageStatus:"placeholder",imageStatus:"placeholder"};c.length>0&&(h.referenceImages=c),n.imagePrompt&&(h.imagePrompt=n.imagePrompt),n.notes&&(h.notes=n.notes);const g=t.children.findIndex(y=>y.id===d.id);return g!==-1&&ss.setNode(t,{pptMeta:h},[g]),{frame:d,slidePrompt:p}}async function Xd(t,e){var m,u,d,p,h,g,y,f,x,z,N,O,T;const{topic:n,pageCount:r,language:i,extraRequirements:o}=t,c=Date.now();if(!n||typeof n!="string")return ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"failed",error:"MissingTopic"}),{success:!1,error:"缺少必填参数 topic(PPT 主题)",type:"error"};const l=en();if(!l)return ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"failed",prompt:n,error:"BoardUnavailable"}),{success:!1,error:"画布未初始化,请先打开画布",type:"error"};try{const I=(t.referenceImages||[]).filter(Boolean),v=Ur(t.referenceImages),S={...t,referenceImages:v},C=at.get(),R=t.textModelRef||t.textModel||t.modelRef||t.model||C.textModelName,U=typeof R=="string"?R:(R==null?void 0:R.modelId)||C.textModelName;ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"start",model:U,prompt:n,metadata:{page_count_option:r||"normal",has_extra_requirements:!!(o!=null&&o.trim()),reference_image_count:v.length,language:i}}),(m=e.onChunk)==null||m.call(e,`🎯 正在为「${n}」生成 PPT 大纲...
567
567
 
568
- `),b.length>0&&((u=e.onChunk)==null||u.call(e,`已关联 ${b.length} 张参考图片作为配图参考。
568
+ `),v.length>0&&((u=e.onChunk)==null||u.call(e,`已关联 ${v.length} 张参考图片作为配图参考。
569
569
 
570
- `));const P=await Kd(n,{...t,referenceImages:I});(d=e.onChunk)==null||d.call(e,`
570
+ `));const P=await Zd(n,{...t,referenceImages:I});(d=e.onChunk)==null||d.call(e,`
571
571
 
572
572
  ✓ 大纲生成完成,共 ${P.pages.length} 页
573
573
 
574
574
  `),(p=e.onChunk)==null||p.call(e,`📑 **PPT 结构**:
575
575
  `),P.pages.forEach((_,E)=>{var $;const M=_.imagePrompt?" 🖼️":"";($=e.onChunk)==null||$.call(e,`${E+1}. ${_.title} (${_.layout})${M}
576
- `)});const J=Gd(l);J>0&&((h=e.onChunk)==null||h.call(e,`
576
+ `)});const J=qd(l);J>0&&((h=e.onChunk)==null||h.call(e,`
577
577
  已替换画布中原有 ${J} 个 PPT 页面及其内容。
578
578
  `)),(g=e.onChunk)==null||g.call(e,`
579
579
  正在创建 PPT 页面并填充提示词...
580
580
 
581
- `);const ee=na(l),X=sa(P.pages.length,ee,ra()),Q=new Array(P.pages.length);let B=0;for(let _=0;_<P.pages.length;_++){const E=P.pages[_],M=_+1,$=X[_],{frame:re}=Zd(l,P,E,M,$,S);Q[_]=re,B++,(y=e.onChunk)==null||y.call(e,`✓ 第 ${B}/${P.pages.length} 页已创建
582
- `)}return Q[0]&&qd(l,Q[0]),oa({viewMode:"outline"}),ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"success",pageCount:B,frameCount:B,durationMs:Date.now()-c,model:U,prompt:n,metadata:{replaced_frame_count:J,layout_count:P.pages.reduce((_,E)=>(_[E.layout]=(_[E.layout]||0)+1,_),{}),reference_image_count:b.length}}),(f=e.onChunk)==null||f.call(e,`
581
+ `);const ee=sa(l),X=ra(P.pages.length,ee,oa()),Q=new Array(P.pages.length);let B=0;for(let _=0;_<P.pages.length;_++){const E=P.pages[_],M=_+1,$=X[_],{frame:re}=Yd(l,P,E,M,$,S);Q[_]=re,B++,(y=e.onChunk)==null||y.call(e,`✓ 第 ${B}/${P.pages.length} 页已创建
582
+ `)}return Q[0]&&Kd(l,Q[0]),ia({viewMode:"outline"}),ye.trackPPTAction({action:"generate_outline",source:"mcp_generate_ppt",status:"success",pageCount:B,frameCount:B,durationMs:Date.now()-c,model:U,prompt:n,metadata:{replaced_frame_count:J,layout_count:P.pages.reduce((_,E)=>(_[E.layout]=(_[E.layout]||0)+1,_),{}),reference_image_count:v.length}}),(f=e.onChunk)==null||f.call(e,`
583
583
  🎉 **PPT 大纲已生成!**
584
584
  `),(x=e.onChunk)==null||x.call(e,`- 共创建 ${B} 个 Frame
585
585
  `),(z=e.onChunk)==null||z.call(e,`- 已填充公共提示词和每页 PPT 提示词
@@ -612,28 +612,28 @@ ${r}
612
612
  生成说明:
613
613
  - 每页 PPT 由一张完整图片构成,文字、背景和视觉设计都包含在图片内
614
614
  - 此工具只生成大纲和提示词,不会立即提交图片任务
615
- - 可在「PPT 编辑」大纲视图修改提示词并选择串行/并行生成`,inputSchema:{type:"object",properties:{topic:{type:"string",description:"PPT 主题或内容描述"},pageCount:{type:"string",description:"页数控制:short(5-7页), normal(8-12页), long(13-18页)",enum:["short","normal","long"],default:"normal"},language:{type:"string",description:"输出语言,默认中文",default:"中文"},extraRequirements:{type:"string",description:"额外要求,如风格、重点内容等"},textModel:{type:"string",description:"PPT 大纲生成文本模型,默认使用输入栏当前文本模型"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于规划 PPT 配图和后续页面生图参考",items:{type:"string"}}},required:["topic"]},supportedModes:["async"],promptGuidance:{whenToUse:"当用户想要创建 PPT、演示文稿、幻灯片时使用。关键词:PPT、演示文稿、幻灯片、presentation、slides、做个汇报、生成演示。",parameterGuidance:{topic:"用户的 PPT 主题或内容描述。可以是一个简单的主题词,也可以是详细的内容大纲。",pageCount:"根据用户需求选择:short 适合简短汇报(5-7页),normal 适合常规演示(8-12页),long 适合详细讲解(13-18页)。",language:"根据用户语言偏好设置,默认中文。如果用户用英文交流,可以设为 English。",extraRequirements:'用户的额外要求,如"简洁风格"、"重点突出数据"、"适合技术分享"等。'},bestPractices:["将用户的描述直接作为 topic 传递,工具会自动规划内容结构",'如果用户提到"简短"、"快速",使用 pageCount: "short"','如果用户提到"详细"、"完整",使用 pageCount: "long"',"生成完成后提醒用户先检查大纲提示词,再在 PPT 编辑面板生成图片"],examples:[{input:"帮我做一个关于人工智能发展的 PPT",args:{topic:"人工智能发展",pageCount:"normal",language:"中文"}},{input:"生成一个简短的产品介绍幻灯片",args:{topic:"产品介绍",pageCount:"short",language:"中文"}},{input:"Create a detailed presentation about climate change",args:{topic:"Climate Change",pageCount:"long",language:"English"}},{input:"做一个关于团队年度总结的 PPT,要突出数据和成果",args:{topic:"团队年度总结",pageCount:"normal",language:"中文",extraRequirements:"突出数据展示和成果呈现"}}],warnings:["PPT 生成需要几秒钟时间,请耐心等待","此工具只创建页面和提示词,不会立即生图","一个画布只保留一套 PPT;每次生成会替换已有 PPT 页面及其内容"]},execute:async(t,e)=>Yd(t,e||{})};async function Xd(t,e){return gs.execute(t,{...e,mode:"async"})}const gm=Object.freeze(Object.defineProperty({__proto__:null,generatePPT:Xd,pptGenerationTool:gs},Symbol.toStringTag,{value:"Module"})),Jd=new Set([",","。","!","?","“","”","‘","’",";",":","(",")","、","-","—","《","》",",",".","!","?",'"',"'",";",":","(",")","&","-","/","\\","[","]","{","}"]),Po=new Set(["啊","哎","唉","吧","比","便","不","差不多","的","得","地","对","多少","哒","对于","诶","而","而且","二","非常","否","咯","跟","哈","哈哈","哈啊","哎呀","嘿","哼","很多","后","会","唧","或","或许","哟","几","及","假如","即使","即便","就","觉得","喀","可以","可能","啦","了","呃","吗","嘛","么","每","没","没有","哪里","那","那个","那么","呢","嗯","哦","其他","或者","呕","前","若","三","啥","什么","甚","甚至","十分","是","手","太","哇","为","为什么","无论","无","嘻嘻","些","许多","呀","哎哟","一","已经","应该","咦","因为","由","于","有","有的","咋","再","再说","怎","怎么","怎么样","这","这个","这样","总","总是","总之","a","about","above","after","again","against","all","am","an","and","any","are","aren't","as","at","be","because","been","before","being","below","between","both","but","by","can't","cannot","could","couldn't","did","didn't","do","does","doesn't","doing","don't","down","during","each","few","for","from","further","had","hadn't","has","hasn't","have","haven't","having","he","he'd","he'll","he's","her","here","here's","hers","herself","him","himself","his","how","how's","i","i'd","i'll","i'm","i've","if","in","into","is","isn't","it","it's","its","itself","let's","me","more","most","mustn't","my","myself","no","nor","not","of","off","on","once","only","or","other","ought","our","ours","ourselves","out","over","own","same","shan't","she","she'd","she'll","she's","should","shouldn't","so","some","such","than","that","that's","the","their","theirs","them","themselves","then","there","there's","these","they","they'd","they'll","they're","they've","this","those","through","to","too","under","until","up","very","was","wasn't","we","we'd","we'll","we're","we've","were","weren't","what","what's","when","when's","where","where's","which","while","who","who's","whom","why","why's","with","won't","would","wouldn't","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves"]);function Qd(t,e=2){if(!t||t.length<e)return[];const n=[];for(let r=0;r<=t.length-e;r++)n.push(t.substring(r,r+e));return n}function Ao(t,e={}){const{ngramSize:n=2}=e,r=[];if(!t)return r;let i=t;Jd.forEach(c=>{i=i.replace(new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")," ")}),i=i.replace(/[.,!?;:()[\]{}"'`~@#$%^&*+=|\\<>\-]/g," ");const o=i.split(/\s+/).filter(Boolean);for(const c of o){const l=c.match(/[\u4e00-\u9fa5]+|[^\u4e00-\u9fa5]+/g)||[c];for(const m of l)if(/[\u4e00-\u9fa5]/.test(m))r.push(...Qd(m,n));else{const u=m.match(/^([^_\d]*)([_\d]+)$/);u?u[1]?(r.push(u[1]),r.push(u[1]+u[2])):r.push(u[2]):r.push(m)}}return r}function eu(t,e=Po,n={}){for(const r of t)r&&!e.has(r)&&(n[r]=(n[r]||0)+1);return n}function an(t,e={}){return t?eu(Ao(t),Po,e):e}function Ot(t,e){let n=0;for(const o in t)Object.prototype.hasOwnProperty.call(e,o)&&(n+=t[o]*(e[o]||0));let r=0;for(const o in t)r+=t[o]*t[o];r=Math.sqrt(r);let i=0;for(const o in e)i+=e[o]*e[o];return i=Math.sqrt(i),r===0||i===0?0:n/(r*i)}class tu{constructor(){this.documentFrequency={},this.idfValues={},this.docCount=0,this.isFitted=!1}fit(e){this.docCount=e.length,this.documentFrequency={},this.idfValues={};for(const n of e)for(const r of Object.keys(n))this.documentFrequency[r]=(this.documentFrequency[r]||0)+1;for(const n in this.documentFrequency){const r=this.documentFrequency[n]||0;this.idfValues[n]=Math.log((this.docCount+1)/(r+1))+1}return this.isFitted=!0,this}getIdf(e){return this.idfValues[e]||0}getIdfValues(){return this.idfValues}get fitted(){return this.isFitted}}const nu={limit:20,minSimilarity:.1,filter:{},includeContent:!1,snippetLength:200};class su{constructor(){this.documents=[],this.tfidfVectorizer=null,this.directoryMap=new Map,this.indexedVersions=new Map,this.isIndexed=!1,this.lastIndexTime=0}async buildIndex(){const[e,n]=await Promise.all([js(),Dt()]);this.directoryMap.clear();for(const i of n)this.directoryMap.set(i.id,i);this.documents=[],this.indexedVersions.clear();const r=[];for(const i of e){const o=await ln(i.id),c=(o==null?void 0:o.content)||"",l=this._buildIndexedDoc(i,c);this.documents.push(l),this.indexedVersions.set(i.id,i.updatedAt),r.push(l.combinedVector)}r.length>0&&(this.tfidfVectorizer=new tu,this.tfidfVectorizer.fit(r)),this.isIndexed=!0,this.lastIndexTime=Date.now()}async syncIndex(){const[e,n]=await Promise.all([js(),Dt()]);this.directoryMap.clear();for(const l of n)this.directoryMap.set(l.id,l);const r=new Set;let i=0,o=0;for(const l of e){r.add(l.id);const m=this.indexedVersions.get(l.id);if(m===void 0||m<l.updatedAt){const u=await ln(l.id),d=(u==null?void 0:u.content)||"",p=this._buildIndexedDoc(l,d);if(m===void 0)this.documents.push(p),i++;else{const h=this.documents.findIndex(g=>g.id===l.id);h!==-1?this.documents[h]=p:this.documents.push(p),o++}this.indexedVersions.set(l.id,l.updatedAt)}}const c=[];for(const l of this.indexedVersions.keys())r.has(l)||c.push(l);for(const l of c)this.documents=this.documents.filter(m=>m.id!==l),this.indexedVersions.delete(l);return this.lastIndexTime=Date.now(),{added:i,updated:o,removed:c.length}}async ensureIndex(){this.isIndexed?await this.syncIndex():await this.buildIndex()}async search(e,n){var c;const r={...nu,...n};if(!e.trim())return[];if(await this.ensureIndex(),this.documents.length===0)return[];const i=an(e),o=[];for(const l of this.documents){if(r.filter.directoryId&&l.directoryId!==r.filter.directoryId||r.filter.domain&&((c=l.metadata)==null?void 0:c.domain)!==r.filter.domain)continue;const m=Ot(i,l.titleVector),u=Ot(i,l.contentVector),d=Ot(i,l.metadataVector),p=Ot(i,l.combinedVector),h=Math.max(p,m*1.5,u,d*1.3);h>=r.minSimilarity&&o.push({doc:l,similarity:h})}return o.sort((l,m)=>m.similarity-l.similarity),o.slice(0,r.limit).map(({doc:l,similarity:m})=>{var d,p;const u=this.directoryMap.get(l.directoryId);return{id:l.id,title:l.title,snippet:this._generateSnippet(l.content,e,r.snippetLength),content:r.includeContent?l.content:"",similarity:m,directoryId:l.directoryId,directoryName:u==null?void 0:u.name,sourceUrl:(d=l.metadata)==null?void 0:d.sourceUrl,domain:(p=l.metadata)==null?void 0:p.domain,updatedAt:l.updatedAt,createdAt:l.createdAt,metadata:l.metadata}})}async getRelatedNotes(e,n=5){await this.ensureIndex();const r=this.documents.find(o=>o.id===e);if(!r)return[];const i=[];for(const o of this.documents){if(o.id===e)continue;const c=Ot(r.combinedVector,o.combinedVector);c>.1&&i.push({doc:o,similarity:c})}return i.sort((o,c)=>c.similarity-o.similarity),i.slice(0,n).map(({doc:o,similarity:c})=>{var m,u;const l=this.directoryMap.get(o.directoryId);return{id:o.id,title:o.title,snippet:o.content.substring(0,200)+(o.content.length>200?"...":""),content:"",similarity:c,directoryId:o.directoryId,directoryName:l==null?void 0:l.name,sourceUrl:(m=o.metadata)==null?void 0:m.sourceUrl,domain:(u=o.metadata)==null?void 0:u.domain,updatedAt:o.updatedAt,createdAt:o.createdAt,metadata:o.metadata}})}addNote(e,n,r,i,o,c,l){this.documents=this.documents.filter(u=>u.id!==e);const m={id:e,title:n,directoryId:i,updatedAt:o,createdAt:c,metadata:l};this.documents.push(this._buildIndexedDoc(m,r)),this.indexedVersions.set(e,o)}removeNote(e){this.documents=this.documents.filter(n=>n.id!==e),this.indexedVersions.delete(e)}getStats(){return{documentCount:this.documents.length,isIndexed:this.isIndexed,lastIndexTime:this.lastIndexTime}}clearIndex(){this.documents=[],this.indexedVersions.clear(),this.tfidfVectorizer=null,this.isIndexed=!1,this.lastIndexTime=0}_buildIndexedDoc(e,n){const r=an(e.title),i=an(n),o=this._buildMetadataText(e.metadata),c=an(o),l={};for(const[m,u]of Object.entries(r))l[m]=(l[m]||0)+u*2;for(const[m,u]of Object.entries(i))l[m]=(l[m]||0)+u;for(const[m,u]of Object.entries(c))l[m]=(l[m]||0)+u*1.5;return{id:e.id,title:e.title,content:n,directoryId:e.directoryId,updatedAt:e.updatedAt,createdAt:e.createdAt,metadata:e.metadata,titleVector:r,contentVector:i,metadataVector:c,combinedVector:l}}_buildMetadataText(e){if(!e)return"";const n=[];return e.domain&&n.push(e.domain),e.tags&&n.push(...e.tags),n.join(" ")}_generateSnippet(e,n,r){if(!e)return"";const i=Ao(n),o=e.toLowerCase();let c=0,l=0;for(const p of i){const h=o.indexOf(p.toLowerCase());if(h!==-1){const g=Math.max(0,h-50),y=Math.min(e.length,h+50),f=o.substring(g,y);let x=0;for(const z of i)f.includes(z.toLowerCase())&&x++;x>l&&(l=x,c=h)}}const m=Math.max(0,c-Math.floor(r/2)),u=Math.min(e.length,m+r);let d=e.substring(m,u);return m>0&&(d="..."+d),u<e.length&&(d=d+"..."),d}}let An=null;function ru(){return An||(An=new su),An}const ou={name:"search_notes",description:`在知识库中搜索笔记。使用语义搜索(TF-IDF + 余弦相似度)返回最相关的笔记摘要。
615
+ - 可在「PPT 编辑」大纲视图修改提示词并选择串行/并行生成`,inputSchema:{type:"object",properties:{topic:{type:"string",description:"PPT 主题或内容描述"},pageCount:{type:"string",description:"页数控制:short(5-7页), normal(8-12页), long(13-18页)",enum:["short","normal","long"],default:"normal"},language:{type:"string",description:"输出语言,默认中文",default:"中文"},extraRequirements:{type:"string",description:"额外要求,如风格、重点内容等"},textModel:{type:"string",description:"PPT 大纲生成文本模型,默认使用输入栏当前文本模型"},referenceImages:{type:"array",description:"参考图片 URL 列表,用于规划 PPT 配图和后续页面生图参考",items:{type:"string"}}},required:["topic"]},supportedModes:["async"],promptGuidance:{whenToUse:"当用户想要创建 PPT、演示文稿、幻灯片时使用。关键词:PPT、演示文稿、幻灯片、presentation、slides、做个汇报、生成演示。",parameterGuidance:{topic:"用户的 PPT 主题或内容描述。可以是一个简单的主题词,也可以是详细的内容大纲。",pageCount:"根据用户需求选择:short 适合简短汇报(5-7页),normal 适合常规演示(8-12页),long 适合详细讲解(13-18页)。",language:"根据用户语言偏好设置,默认中文。如果用户用英文交流,可以设为 English。",extraRequirements:'用户的额外要求,如"简洁风格"、"重点突出数据"、"适合技术分享"等。'},bestPractices:["将用户的描述直接作为 topic 传递,工具会自动规划内容结构",'如果用户提到"简短"、"快速",使用 pageCount: "short"','如果用户提到"详细"、"完整",使用 pageCount: "long"',"生成完成后提醒用户先检查大纲提示词,再在 PPT 编辑面板生成图片"],examples:[{input:"帮我做一个关于人工智能发展的 PPT",args:{topic:"人工智能发展",pageCount:"normal",language:"中文"}},{input:"生成一个简短的产品介绍幻灯片",args:{topic:"产品介绍",pageCount:"short",language:"中文"}},{input:"Create a detailed presentation about climate change",args:{topic:"Climate Change",pageCount:"long",language:"English"}},{input:"做一个关于团队年度总结的 PPT,要突出数据和成果",args:{topic:"团队年度总结",pageCount:"normal",language:"中文",extraRequirements:"突出数据展示和成果呈现"}}],warnings:["PPT 生成需要几秒钟时间,请耐心等待","此工具只创建页面和提示词,不会立即生图","一个画布只保留一套 PPT;每次生成会替换已有 PPT 页面及其内容"]},execute:async(t,e)=>Xd(t,e||{})};async function Jd(t,e){return gs.execute(t,{...e,mode:"async"})}const wm=Object.freeze(Object.defineProperty({__proto__:null,generatePPT:Jd,pptGenerationTool:gs},Symbol.toStringTag,{value:"Module"})),Qd=new Set([",","。","!","?","“","”","‘","’",";",":","(",")","、","-","—","《","》",",",".","!","?",'"',"'",";",":","(",")","&","-","/","\\","[","]","{","}"]),Ao=new Set(["啊","哎","唉","吧","比","便","不","差不多","的","得","地","对","多少","哒","对于","诶","而","而且","二","非常","否","咯","跟","哈","哈哈","哈啊","哎呀","嘿","哼","很多","后","会","唧","或","或许","哟","几","及","假如","即使","即便","就","觉得","喀","可以","可能","啦","了","呃","吗","嘛","么","每","没","没有","哪里","那","那个","那么","呢","嗯","哦","其他","或者","呕","前","若","三","啥","什么","甚","甚至","十分","是","手","太","哇","为","为什么","无论","无","嘻嘻","些","许多","呀","哎哟","一","已经","应该","咦","因为","由","于","有","有的","咋","再","再说","怎","怎么","怎么样","这","这个","这样","总","总是","总之","a","about","above","after","again","against","all","am","an","and","any","are","aren't","as","at","be","because","been","before","being","below","between","both","but","by","can't","cannot","could","couldn't","did","didn't","do","does","doesn't","doing","don't","down","during","each","few","for","from","further","had","hadn't","has","hasn't","have","haven't","having","he","he'd","he'll","he's","her","here","here's","hers","herself","him","himself","his","how","how's","i","i'd","i'll","i'm","i've","if","in","into","is","isn't","it","it's","its","itself","let's","me","more","most","mustn't","my","myself","no","nor","not","of","off","on","once","only","or","other","ought","our","ours","ourselves","out","over","own","same","shan't","she","she'd","she'll","she's","should","shouldn't","so","some","such","than","that","that's","the","their","theirs","them","themselves","then","there","there's","these","they","they'd","they'll","they're","they've","this","those","through","to","too","under","until","up","very","was","wasn't","we","we'd","we'll","we're","we've","were","weren't","what","what's","when","when's","where","where's","which","while","who","who's","whom","why","why's","with","won't","would","wouldn't","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves"]);function eu(t,e=2){if(!t||t.length<e)return[];const n=[];for(let r=0;r<=t.length-e;r++)n.push(t.substring(r,r+e));return n}function Ro(t,e={}){const{ngramSize:n=2}=e,r=[];if(!t)return r;let i=t;Qd.forEach(c=>{i=i.replace(new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g")," ")}),i=i.replace(/[.,!?;:()[\]{}"'`~@#$%^&*+=|\\<>\-]/g," ");const o=i.split(/\s+/).filter(Boolean);for(const c of o){const l=c.match(/[\u4e00-\u9fa5]+|[^\u4e00-\u9fa5]+/g)||[c];for(const m of l)if(/[\u4e00-\u9fa5]/.test(m))r.push(...eu(m,n));else{const u=m.match(/^([^_\d]*)([_\d]+)$/);u?u[1]?(r.push(u[1]),r.push(u[1]+u[2])):r.push(u[2]):r.push(m)}}return r}function tu(t,e=Ao,n={}){for(const r of t)r&&!e.has(r)&&(n[r]=(n[r]||0)+1);return n}function an(t,e={}){return t?tu(Ro(t),Ao,e):e}function Ot(t,e){let n=0;for(const o in t)Object.prototype.hasOwnProperty.call(e,o)&&(n+=t[o]*(e[o]||0));let r=0;for(const o in t)r+=t[o]*t[o];r=Math.sqrt(r);let i=0;for(const o in e)i+=e[o]*e[o];return i=Math.sqrt(i),r===0||i===0?0:n/(r*i)}class nu{constructor(){this.documentFrequency={},this.idfValues={},this.docCount=0,this.isFitted=!1}fit(e){this.docCount=e.length,this.documentFrequency={},this.idfValues={};for(const n of e)for(const r of Object.keys(n))this.documentFrequency[r]=(this.documentFrequency[r]||0)+1;for(const n in this.documentFrequency){const r=this.documentFrequency[n]||0;this.idfValues[n]=Math.log((this.docCount+1)/(r+1))+1}return this.isFitted=!0,this}getIdf(e){return this.idfValues[e]||0}getIdfValues(){return this.idfValues}get fitted(){return this.isFitted}}const su={limit:20,minSimilarity:.1,filter:{},includeContent:!1,snippetLength:200};class ru{constructor(){this.documents=[],this.tfidfVectorizer=null,this.directoryMap=new Map,this.indexedVersions=new Map,this.isIndexed=!1,this.lastIndexTime=0}async buildIndex(){const[e,n]=await Promise.all([js(),Dt()]);this.directoryMap.clear();for(const i of n)this.directoryMap.set(i.id,i);this.documents=[],this.indexedVersions.clear();const r=[];for(const i of e){const o=await ln(i.id),c=(o==null?void 0:o.content)||"",l=this._buildIndexedDoc(i,c);this.documents.push(l),this.indexedVersions.set(i.id,i.updatedAt),r.push(l.combinedVector)}r.length>0&&(this.tfidfVectorizer=new nu,this.tfidfVectorizer.fit(r)),this.isIndexed=!0,this.lastIndexTime=Date.now()}async syncIndex(){const[e,n]=await Promise.all([js(),Dt()]);this.directoryMap.clear();for(const l of n)this.directoryMap.set(l.id,l);const r=new Set;let i=0,o=0;for(const l of e){r.add(l.id);const m=this.indexedVersions.get(l.id);if(m===void 0||m<l.updatedAt){const u=await ln(l.id),d=(u==null?void 0:u.content)||"",p=this._buildIndexedDoc(l,d);if(m===void 0)this.documents.push(p),i++;else{const h=this.documents.findIndex(g=>g.id===l.id);h!==-1?this.documents[h]=p:this.documents.push(p),o++}this.indexedVersions.set(l.id,l.updatedAt)}}const c=[];for(const l of this.indexedVersions.keys())r.has(l)||c.push(l);for(const l of c)this.documents=this.documents.filter(m=>m.id!==l),this.indexedVersions.delete(l);return this.lastIndexTime=Date.now(),{added:i,updated:o,removed:c.length}}async ensureIndex(){this.isIndexed?await this.syncIndex():await this.buildIndex()}async search(e,n){var c;const r={...su,...n};if(!e.trim())return[];if(await this.ensureIndex(),this.documents.length===0)return[];const i=an(e),o=[];for(const l of this.documents){if(r.filter.directoryId&&l.directoryId!==r.filter.directoryId||r.filter.domain&&((c=l.metadata)==null?void 0:c.domain)!==r.filter.domain)continue;const m=Ot(i,l.titleVector),u=Ot(i,l.contentVector),d=Ot(i,l.metadataVector),p=Ot(i,l.combinedVector),h=Math.max(p,m*1.5,u,d*1.3);h>=r.minSimilarity&&o.push({doc:l,similarity:h})}return o.sort((l,m)=>m.similarity-l.similarity),o.slice(0,r.limit).map(({doc:l,similarity:m})=>{var d,p;const u=this.directoryMap.get(l.directoryId);return{id:l.id,title:l.title,snippet:this._generateSnippet(l.content,e,r.snippetLength),content:r.includeContent?l.content:"",similarity:m,directoryId:l.directoryId,directoryName:u==null?void 0:u.name,sourceUrl:(d=l.metadata)==null?void 0:d.sourceUrl,domain:(p=l.metadata)==null?void 0:p.domain,updatedAt:l.updatedAt,createdAt:l.createdAt,metadata:l.metadata}})}async getRelatedNotes(e,n=5){await this.ensureIndex();const r=this.documents.find(o=>o.id===e);if(!r)return[];const i=[];for(const o of this.documents){if(o.id===e)continue;const c=Ot(r.combinedVector,o.combinedVector);c>.1&&i.push({doc:o,similarity:c})}return i.sort((o,c)=>c.similarity-o.similarity),i.slice(0,n).map(({doc:o,similarity:c})=>{var m,u;const l=this.directoryMap.get(o.directoryId);return{id:o.id,title:o.title,snippet:o.content.substring(0,200)+(o.content.length>200?"...":""),content:"",similarity:c,directoryId:o.directoryId,directoryName:l==null?void 0:l.name,sourceUrl:(m=o.metadata)==null?void 0:m.sourceUrl,domain:(u=o.metadata)==null?void 0:u.domain,updatedAt:o.updatedAt,createdAt:o.createdAt,metadata:o.metadata}})}addNote(e,n,r,i,o,c,l){this.documents=this.documents.filter(u=>u.id!==e);const m={id:e,title:n,directoryId:i,updatedAt:o,createdAt:c,metadata:l};this.documents.push(this._buildIndexedDoc(m,r)),this.indexedVersions.set(e,o)}removeNote(e){this.documents=this.documents.filter(n=>n.id!==e),this.indexedVersions.delete(e)}getStats(){return{documentCount:this.documents.length,isIndexed:this.isIndexed,lastIndexTime:this.lastIndexTime}}clearIndex(){this.documents=[],this.indexedVersions.clear(),this.tfidfVectorizer=null,this.isIndexed=!1,this.lastIndexTime=0}_buildIndexedDoc(e,n){const r=an(e.title),i=an(n),o=this._buildMetadataText(e.metadata),c=an(o),l={};for(const[m,u]of Object.entries(r))l[m]=(l[m]||0)+u*2;for(const[m,u]of Object.entries(i))l[m]=(l[m]||0)+u;for(const[m,u]of Object.entries(c))l[m]=(l[m]||0)+u*1.5;return{id:e.id,title:e.title,content:n,directoryId:e.directoryId,updatedAt:e.updatedAt,createdAt:e.createdAt,metadata:e.metadata,titleVector:r,contentVector:i,metadataVector:c,combinedVector:l}}_buildMetadataText(e){if(!e)return"";const n=[];return e.domain&&n.push(e.domain),e.tags&&n.push(...e.tags),n.join(" ")}_generateSnippet(e,n,r){if(!e)return"";const i=Ro(n),o=e.toLowerCase();let c=0,l=0;for(const p of i){const h=o.indexOf(p.toLowerCase());if(h!==-1){const g=Math.max(0,h-50),y=Math.min(e.length,h+50),f=o.substring(g,y);let x=0;for(const z of i)f.includes(z.toLowerCase())&&x++;x>l&&(l=x,c=h)}}const m=Math.max(0,c-Math.floor(r/2)),u=Math.min(e.length,m+r);let d=e.substring(m,u);return m>0&&(d="..."+d),u<e.length&&(d=d+"..."),d}}let An=null;function ou(){return An||(An=new ru),An}const iu={name:"search_notes",description:`在知识库中搜索笔记。使用语义搜索(TF-IDF + 余弦相似度)返回最相关的笔记摘要。
616
616
 
617
617
  使用场景:
618
618
  - 用户问到"我之前保存过…"、"关于XX的笔记"
619
619
  - 需要查找知识库中的信息用于回答问题
620
- - 查找与某个主题相关的所有笔记`,inputSchema:{type:"object",properties:{query:{type:"string",description:"搜索关键词或语义查询"},limit:{type:"number",description:"返回结果数量上限,默认 10"},directoryId:{type:"string",description:"限制在指定目录中搜索(可选)"}},required:["query"]},promptGuidance:{whenToUse:"当用户需要搜索知识库中的信息时使用,支持语义搜索",parameterGuidance:{query:"尽量使用核心关键词或简短的自然语言描述",limit:"一般用默认值即可,除非用户明确说了需要几条"},bestPractices:["优先使用核心词搜索,避免过长的句子","如果搜索不到结果,尝试换关键词","结合 get_note 工具获取完整内容"],examples:[{input:"搜索关于 React 的笔记",args:{query:"React"},explanation:"使用核心关键词搜索"},{input:"找一下上周保存的 AI 文章",args:{query:"AI 文章"},explanation:"自然语言搜索"}]},execute:async t=>{const e=t.query,n=t.limit||10,r=t.directoryId;if(!(e!=null&&e.trim()))return{success:!1,error:"搜索关键词不能为空",type:"error"};try{const o=await ru().search(e,{limit:n,filter:r?{directoryId:r}:{},includeContent:!1,snippetLength:200});return o.length>0?{success:!0,type:"text",data:o.map(u=>({id:u.id,title:u.title,excerpt:u.snippet,similarity:Math.round(u.similarity*100)/100,directoryName:u.directoryName,domain:u.domain,updatedAt:new Date(u.updatedAt).toISOString()}))}:{success:!0,type:"text",data:(await fa(e)).slice(0,n).map(m=>({id:m.id,title:m.title,directoryId:m.directoryId,updatedAt:new Date(m.updatedAt).toISOString()}))}}catch(i){return{success:!1,error:`搜索失败: ${i.message}`,type:"error"}}}},iu={name:"get_note",description:`获取知识库中某篇笔记的完整内容。
620
+ - 查找与某个主题相关的所有笔记`,inputSchema:{type:"object",properties:{query:{type:"string",description:"搜索关键词或语义查询"},limit:{type:"number",description:"返回结果数量上限,默认 10"},directoryId:{type:"string",description:"限制在指定目录中搜索(可选)"}},required:["query"]},promptGuidance:{whenToUse:"当用户需要搜索知识库中的信息时使用,支持语义搜索",parameterGuidance:{query:"尽量使用核心关键词或简短的自然语言描述",limit:"一般用默认值即可,除非用户明确说了需要几条"},bestPractices:["优先使用核心词搜索,避免过长的句子","如果搜索不到结果,尝试换关键词","结合 get_note 工具获取完整内容"],examples:[{input:"搜索关于 React 的笔记",args:{query:"React"},explanation:"使用核心关键词搜索"},{input:"找一下上周保存的 AI 文章",args:{query:"AI 文章"},explanation:"自然语言搜索"}]},execute:async t=>{const e=t.query,n=t.limit||10,r=t.directoryId;if(!(e!=null&&e.trim()))return{success:!1,error:"搜索关键词不能为空",type:"error"};try{const o=await ou().search(e,{limit:n,filter:r?{directoryId:r}:{},includeContent:!1,snippetLength:200});return o.length>0?{success:!0,type:"text",data:o.map(u=>({id:u.id,title:u.title,excerpt:u.snippet,similarity:Math.round(u.similarity*100)/100,directoryName:u.directoryName,domain:u.domain,updatedAt:new Date(u.updatedAt).toISOString()}))}:{success:!0,type:"text",data:(await ga(e)).slice(0,n).map(m=>({id:m.id,title:m.title,directoryId:m.directoryId,updatedAt:new Date(m.updatedAt).toISOString()}))}}catch(i){return{success:!1,error:`搜索失败: ${i.message}`,type:"error"}}}},au={name:"get_note",description:`获取知识库中某篇笔记的完整内容。
621
621
 
622
622
  使用场景:
623
623
  - 搜索到笔记后需要查看完整内容
624
- - 用户指定了笔记 ID 要查看详情`,inputSchema:{type:"object",properties:{id:{type:"string",description:"笔记 ID"}},required:["id"]},promptGuidance:{whenToUse:"在 search_notes 返回结果后,需要获取某篇笔记的完整内容时使用",parameterGuidance:{id:"使用 search_notes 返回结果中的 id 字段"},examples:[{input:"查看笔记详情",args:{id:"note_12345"},explanation:"传入 search_notes 返回的笔记 ID"}]},execute:async t=>{const e=t.id;if(!e)return{success:!1,error:"笔记 ID 不能为空",type:"error"};try{const n=await ln(e);return n?{success:!0,type:"text",data:{id:n.id,title:n.title,content:n.content,directoryId:n.directoryId,createdAt:new Date(n.createdAt).toISOString(),updatedAt:new Date(n.updatedAt).toISOString(),metadata:n.metadata}}:{success:!1,error:"笔记不存在",type:"error"}}catch(n){return{success:!1,error:`获取笔记失败: ${n.message}`,type:"error"}}}},au={name:"create_note",description:`在知识库中创建新笔记。支持 Markdown 格式内容、指定目录、标签和来源 URL。
624
+ - 用户指定了笔记 ID 要查看详情`,inputSchema:{type:"object",properties:{id:{type:"string",description:"笔记 ID"}},required:["id"]},promptGuidance:{whenToUse:"在 search_notes 返回结果后,需要获取某篇笔记的完整内容时使用",parameterGuidance:{id:"使用 search_notes 返回结果中的 id 字段"},examples:[{input:"查看笔记详情",args:{id:"note_12345"},explanation:"传入 search_notes 返回的笔记 ID"}]},execute:async t=>{const e=t.id;if(!e)return{success:!1,error:"笔记 ID 不能为空",type:"error"};try{const n=await ln(e);return n?{success:!0,type:"text",data:{id:n.id,title:n.title,content:n.content,directoryId:n.directoryId,createdAt:new Date(n.createdAt).toISOString(),updatedAt:new Date(n.updatedAt).toISOString(),metadata:n.metadata}}:{success:!1,error:"笔记不存在",type:"error"}}catch(n){return{success:!1,error:`获取笔记失败: ${n.message}`,type:"error"}}}},cu={name:"create_note",description:`在知识库中创建新笔记。支持 Markdown 格式内容、指定目录、标签和来源 URL。
625
625
 
626
626
  使用场景:
627
627
  - 用户要求保存内容到知识库
628
628
  - AI 对话中用户说"帮我记住这个"
629
629
  - 保存 AI 生成的内容供后续参考`,inputSchema:{type:"object",properties:{title:{type:"string",description:"笔记标题"},content:{type:"string",description:"笔记内容(支持 Markdown 格式)"},directoryName:{type:"string",description:'目录名称(不存在则自动创建),默认为"笔记"'},tags:{type:"array",description:"标签列表(字符串数组,不存在则自动创建)"},sourceUrl:{type:"string",description:"来源 URL(可选)"}},required:["title","content"]},promptGuidance:{whenToUse:"当用户要求将信息保存到知识库时使用",parameterGuidance:{title:"简洁明了的标题,概括笔记核心内容",content:"完整的笔记内容,建议使用 Markdown 格式",directoryName:"根据内容类型推断合适的目录名称",tags:"提取内容中的核心主题作为标签"},bestPractices:["自动为笔记生成 2-4 个有意义的标签","标题控制在 50 字以内","内容保持完整结构化"],examples:[{input:"帮我保存这段关于 React Hooks 的笔记",args:{title:"React Hooks 使用指南",content:`## React Hooks
630
630
 
631
- 核心 Hook 包括...`,directoryName:"技术笔记",tags:["React","Hooks","前端"]}}]},execute:async t=>{const e=t.title,n=t.content,r=t.directoryName||"笔记",i=t.tags,o=t.sourceUrl;if(!(e!=null&&e.trim()))return{success:!1,error:"标题不能为空",type:"error"};if(!(n!=null&&n.trim()))return{success:!1,error:"内容不能为空",type:"error"};try{let l=(await Dt()).find(d=>d.name===r);l||(l=await vr(r));const m=o?{sourceUrl:o}:void 0,u=await br(e,l.id,n,m);if(i&&i.length>0)for(const d of i){const p=await ga(d);await wa(u.id,p.id)}return{success:!0,type:"text",data:{id:u.id,title:u.title,message:"笔记创建成功"}}}catch(c){return{success:!1,error:`创建笔记失败: ${c.message}`,type:"error"}}}},cu={name:"list_directories",description:`列出知识库中的所有目录。
631
+ 核心 Hook 包括...`,directoryName:"技术笔记",tags:["React","Hooks","前端"]}}]},execute:async t=>{const e=t.title,n=t.content,r=t.directoryName||"笔记",i=t.tags,o=t.sourceUrl;if(!(e!=null&&e.trim()))return{success:!1,error:"标题不能为空",type:"error"};if(!(n!=null&&n.trim()))return{success:!1,error:"内容不能为空",type:"error"};try{let l=(await Dt()).find(d=>d.name===r);l||(l=await Sr(r));const m=o?{sourceUrl:o}:void 0,u=await br(e,l.id,n,m);if(i&&i.length>0)for(const d of i){const p=await wa(d);await ya(u.id,p.id)}return{success:!0,type:"text",data:{id:u.id,title:u.title,message:"笔记创建成功"}}}catch(c){return{success:!1,error:`创建笔记失败: ${c.message}`,type:"error"}}}},lu={name:"list_directories",description:`列出知识库中的所有目录。
632
632
 
633
633
  使用场景:
634
634
  - 需要了解知识库的目录结构
635
- - 创建笔记前查看可用目录`,inputSchema:{type:"object",properties:{}},execute:async()=>{try{return{success:!0,type:"text",data:(await Dt()).map(e=>({id:e.id,name:e.name,isDefault:e.isDefault,createdAt:new Date(e.createdAt).toISOString()}))}}catch(t){return{success:!1,error:`获取目录失败: ${t.message}`,type:"error"}}}},lu=[ou,iu,au,cu];function du(t){const e=t.prompt||xa,n=t.videoAnalyzerAction||"analyze";if(n!=="prompt-generate"&&!t.videoData&&!t.youtubeUrl&&!t.videoCacheUrl)return{success:!1,error:"需要提供 videoData、videoCacheUrl 或 youtubeUrl",type:"error"};const r=ft.createTask({prompt:t.taskLabel||"视频分析",model:t.model,modelRef:t.modelRef||null,mimeType:t.mimeType||"video/mp4",youtubeUrl:t.youtubeUrl,videoData:t.videoData,videoCacheUrl:t.videoCacheUrl,pdfCacheUrl:t.pdfCacheUrl,pdfMimeType:t.pdfMimeType,pdfName:t.pdfName,videoAnalyzerAction:n,videoAnalyzerPrompt:e,videoAnalyzerSource:t.videoAnalyzerSource,videoAnalyzerSourceLabel:t.videoAnalyzerSourceLabel,videoAnalyzerSourceSnapshot:t.videoAnalyzerSourceSnapshot,videoAnalyzerProductInfo:t.videoAnalyzerProductInfo,knowledgeContextRefs:t.knowledgeContextRefs,autoInsertToCanvas:!1},xt.CHAT);return{success:!0,data:{taskId:r.id,prompt:t.taskLabel||"视频分析",model:t.model},type:"text",taskId:r.id,task:r}}const uu={name:"video_analyze",description:"分析视频内容,返回结构化的镜头拆解、脚本提取、风格分析等数据",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{videoData:{type:"string",description:"base64 编码的视频数据(不含 data: 前缀),≤20MB"},mimeType:{type:"string",description:"视频 MIME 类型,默认 video/mp4",default:"video/mp4"},youtubeUrl:{type:"string",description:"YouTube 视频 URL"},videoCacheUrl:{type:"string",description:"本地缓存的视频 URL(队列模式)"},pdfCacheUrl:{type:"string",description:"本地缓存的 PDF URL(提示词生成上下文)"},pdfMimeType:{type:"string",description:"PDF MIME 类型,默认 application/pdf"},pdfName:{type:"string",description:"PDF 文件名"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},videoAnalyzerAction:{type:"string",description:"视频工具动作:analyze 或 prompt-generate"},videoAnalyzerProductInfo:{type:"object",description:"提示词生成时的画面风格、视频模型、单段时长等表单参数"},model:{type:"string",description:"模型 ID,默认使用当前文本模型"}},required:[]},execute:async(t,e)=>(e==null?void 0:e.mode)==="queue"?du(t):ya(t)};function mu(t){const e=t.prompt||ba;if(!t.audioData&&!t.audioCacheUrl)return{success:!1,error:"需要提供 audioData 或 audioCacheUrl",type:"error"};const n=ft.createTask({prompt:t.taskLabel||"音频分析",model:t.model,modelRef:t.modelRef||null,mimeType:t.mimeType||"audio/mpeg",audioData:t.audioData,audioCacheUrl:t.audioCacheUrl,musicAnalyzerAction:"analyze",musicAnalyzerPrompt:e,musicAnalyzerSource:t.musicAnalyzerSource,musicAnalyzerSourceLabel:t.musicAnalyzerSourceLabel,musicAnalyzerSourceSnapshot:t.musicAnalyzerSourceSnapshot,autoInsertToCanvas:!1},xt.CHAT);return{success:!0,data:{taskId:n.id,prompt:t.taskLabel||"音频分析",model:t.model},type:"text",taskId:n.id,task:n}}const pu={name:"audio_analyze",description:"分析音频内容,返回结构化的音乐风格、情绪、Suno 标签和歌词改写建议",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{audioData:{type:"string",description:"base64 编码的音频数据(不含 data: 前缀)"},mimeType:{type:"string",description:"音频 MIME 类型,默认 audio/mpeg",default:"audio/mpeg"},audioCacheUrl:{type:"string",description:"本地缓存的音频 URL(队列模式)"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},model:{type:"string",description:"Gemini 多模态模型 ID,默认使用当前文本模型"}},required:[]},execute:async(t,e)=>(e==null?void 0:e.mode)==="queue"?mu(t):_a(t)};let Js=!1;function hu(){Js||(Js=!0,ls.registerAll([va,us,ed,od,Wd,xo,id,wd,bd,kd,jd,Ed,zd,gs,...lu,uu,pu]))}const Ro=it.memo(({session:t,isActive:e,onSelect:n,onDelete:r,onRename:i})=>{const[o,c]=a.useState(!1),[l,m]=a.useState(t.title),u=a.useRef(null),d=a.useCallback(()=>{o||n()},[n,o]),p=a.useCallback(N=>{N.stopPropagation(),r()},[r]),h=a.useCallback(N=>{N.stopPropagation(),m(t.title),c(!0)},[t.title]),g=a.useCallback(()=>{const N=l.trim();N&&N!==t.title&&i(N),c(!1)},[l,t.title,i]),y=a.useCallback(()=>{m(t.title),c(!1)},[t.title]),f=a.useCallback(N=>{N.key==="Enter"?(N.preventDefault(),g()):N.key==="Escape"&&(N.preventDefault(),y())},[g,y]),x=a.useCallback(N=>{m(N.target.value)},[]);a.useEffect(()=>{o&&u.current&&(u.current.focus(),u.current.select())},[o]);const z=a.useMemo(()=>{const N=new Date(t.updatedAt),O=new Date;return N.toDateString()===O.toDateString()?N.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):N.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[t.updatedAt]);return s.jsxs("div",{className:`session-item ${e?"session-item--active":""} ${o?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:d,role:"button",tabIndex:0,onKeyDown:N=>!o&&N.key==="Enter"&&d(),children:[s.jsxs("div",{className:"session-item__content",children:[o?s.jsx("input",{ref:u,className:"session-item__title-input",value:l,onChange:x,onKeyDown:f,onBlur:g,onClick:N=>N.stopPropagation(),maxLength:50}):s.jsx("div",{className:"session-item__title",children:t.title}),s.jsx("div",{className:"session-item__time",children:z})]}),!o&&s.jsxs("div",{className:"session-item__actions",children:[s.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:h,"aria-label":`编辑会话标题: ${t.title}`,children:s.jsx(Sa,{size:14})}),s.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:p,"aria-label":`删除会话: ${t.title}`,children:s.jsx(Ia,{size:14})})]})]})});Ro.displayName="SessionItem";const zo=it.memo(({sessions:t,activeSessionId:e,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:o})=>{const[c,l]=it.useState(null),m=a.useCallback(g=>{n(g)},[n]),u=a.useCallback(g=>{l(g)},[]),d=a.useCallback(()=>{c&&(i(c),l(null))},[c,i]),p=a.useCallback(()=>{l(null)},[]),h=a.useCallback((g,y)=>{o(g,y)},[o]);return s.jsxs("div",{className:"session-list",children:[s.jsxs("div",{className:"session-list__header",children:[s.jsx("span",{className:"session-list__title",children:"会话列表"}),s.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:r,"aria-label":"新建会话",children:[s.jsx(Wr,{size:14}),s.jsx("span",{children:"新建"})]})]}),s.jsx("div",{className:"session-list__items",children:t.length===0?s.jsx("div",{className:"session-list__empty",children:"暂无会话"}):t.map(g=>s.jsx(Ro,{session:g,isActive:g.id===e,onSelect:()=>m(g.id),onDelete:()=>u(g.id),onRename:y=>h(g.id,y)},g.id))}),s.jsx(ka,{open:c!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:g=>{g||p()},onConfirm:d})]})});zo.displayName="SessionList";const Do=it.memo(({isOpen:t,onClick:e,drawerWidth:n})=>{const r={right:t&&n?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${n-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return s.jsx(je,{content:t?"收起对话":"展开对话",children:s.jsx("button",{className:`chat-drawer-trigger ${t?"chat-drawer-trigger--active":""}`,"data-track":t?"chat_click_drawer_close":"chat_click_drawer_open",onClick:e,"aria-label":t?"收起对话":"展开对话","aria-expanded":t,style:r,children:s.jsx(Ma,{size:16,className:"chat-drawer-trigger__icon"})})})});Do.displayName="ChatDrawerTrigger";function fn(t){return t.sourceProfileName||Zn[t.vendor]||t.id}const fu=it.memo(({model:t})=>{const{summary:e,detail:n}=Ra(t.sourceProfileId,t.id);return e?s.jsx(je,{content:n,placement:"top",disabled:n===e,children:s.jsx("span",{className:"model-selector__item-price",children:e})}):null}),gu=it.memo(({model:t})=>{const e=za(t.sourceProfileId,t.id);return e!=null&&e.description?s.jsx("div",{className:"model-selector__item-desc",children:e.description}):null});function wu(t,e){var o;const n=fn(t),r=(o=t.description)==null?void 0:o.trim(),i=(e==null?void 0:e.includeProvider)??!0;return r?!i||r.includes(n)?r:`${n} · ${r}`:i?n:""}function yu(t){return fn(t).trim().slice(0,1).toUpperCase()||"M"}const Lo=it.memo(({className:t,value:e,valueRef:n,onChange:r,variant:i="capsule"})=>{var B;const o=mo("text"),c=((B=o[0])==null?void 0:B.id)||Ca,[l,m]=a.useState(c),[u,d]=a.useState(()=>ht(null,c)),p=e??l,h=n===void 0?u:n,[g,y]=a.useState(!1),[f,x]=a.useState(""),[z,N]=a.useState(null),O=a.useRef(null),T=a.useRef(null);a.useEffect(()=>{!e&&c&&l!==c&&(m(c),d(ht(null,c)))},[c,l,e]),a.useEffect(()=>{if(!g)return;const _=M=>{const $=M.target;O.current&&!O.current.contains($)&&T.current&&!T.current.contains($)&&(y(!1),x(""))},E=setTimeout(()=>{document.addEventListener("mousedown",_)},100);return()=>{clearTimeout(E),document.removeEventListener("mousedown",_)}},[g]);const I=a.useMemo(()=>p?is(p,h):null,[p,h]),b=a.useMemo(()=>{if(pn(o,p,h)||!p)return o;const E=Un("text",p,h);return E?[E,...o]:o},[o,p,h]),S=a.useMemo(()=>pn(b,p,h)||b.find(_=>_.id===p),[b,p,h]),C=a.useCallback(_=>{const E=ht(_.sourceProfileId||null,_.id);e===void 0&&m(_.id),n===void 0&&d(E),r==null||r(_.id,E),y(!1),x("")},[e,n,r]),R=a.useCallback(()=>{const _=!g;y(_),_?N((S==null?void 0:S.vendor)||null):x("")},[S==null?void 0:S.vendor,g]),U=a.useMemo(()=>{const _=new Map,E=[];return b.forEach(M=>{_.has(M.vendor)||(E.push(M.vendor),_.set(M.vendor,0)),_.set(M.vendor,(_.get(M.vendor)??0)+1)}),E.map(M=>({id:M,label:Zn[M],count:_.get(M)??0,icon:s.jsx(ja,{vendor:M,size:14})}))},[b]),P=a.useCallback(_=>{N(_)},[]),J=a.useMemo(()=>{const _=f.toLowerCase().trim();return _?b.filter(E=>{var $,re;const M=fn(E).toLowerCase();return E.id.toLowerCase().includes(_)||E.label.toLowerCase().includes(_)||(($=E.shortLabel)==null?void 0:$.toLowerCase().includes(_))||((re=E.description)==null?void 0:re.toLowerCase().includes(_))||M.includes(_)}):z?b.filter(E=>E.vendor===z):b},[f,z,b]),[ee,X]=a.useState({top:0,left:0,width:0,bottom:0,placement:"bottom",maxHeight:480});a.useLayoutEffect(()=>{if(!g)return;const _=()=>{if(!T.current)return;const E=T.current.getBoundingClientRect(),M=window.innerHeight,$=M-E.bottom,re=E.top,fe=$<400&&re>$?"top":"bottom",K=fe==="top"?re-16:M-E.bottom-16;X({top:E.top,left:E.left,width:E.width,bottom:E.bottom,placement:fe,maxHeight:Math.min(Math.max(K,200),600)})};return _(),window.addEventListener("resize",_),window.addEventListener("scroll",_,!0),()=>{window.removeEventListener("resize",_),window.removeEventListener("scroll",_,!0)}},[g]);const Q=()=>{if(!g)return null;const _=s.jsxs("div",{ref:O,className:"model-selector__dropdown",style:{position:"fixed",zIndex:qn.DROPDOWN_PORTAL,left:ee.left,top:ee.placement==="bottom"?ee.bottom+8:"auto",bottom:ee.placement==="top"?window.innerHeight-ee.top+8:"auto",minWidth:360,width:i==="form"?ee.width:"auto",maxHeight:ee.maxHeight,visibility:ee.width===0?"hidden":"visible",transformOrigin:ee.placement==="bottom"?"top left":"bottom left",display:"flex",flexDirection:"column"},onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"model-selector__search",children:s.jsx(Na,{value:f,onChange:x,placeholder:"搜索模型...",prefixIcon:s.jsx(Ea,{}),clearable:!0,autofocus:!0})}),s.jsx(Pa,{tabs:U,activeTab:z,onTabChange:P,searchQuery:f,compact:!0,children:s.jsx("div",{className:"model-selector__list",children:J.length===0?s.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):J.map(E=>{const M=po(E),$=M===I,re=!!f.trim(),fe=wu(E,{includeProvider:!re});return s.jsxs("button",{className:`model-selector__item ${$?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>C(E),children:[s.jsx("span",{className:"model-selector__item-icon model-selector__item-icon--text","aria-hidden":"true",children:yu(E)}),s.jsxs("div",{className:"model-selector__item-content",children:[s.jsxs("div",{className:"model-selector__item-header",children:[s.jsx("span",{className:"model-selector__item-name",children:E.shortLabel||E.label}),re?s.jsx("span",{className:"model-selector__item-provider",children:fn(E)}):null,s.jsx(Ts,{modelId:E.id,profileId:E.sourceProfileId||null}),s.jsx(Aa,{modelId:E.id}),s.jsx(fu,{model:E})]}),fe?s.jsx("div",{className:"model-selector__item-desc",children:fe}):s.jsx(gu,{model:E})]}),$&&s.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:s.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},M)})})})]});return Rt.createPortal(_,document.body)};return s.jsxs("div",{className:`model-selector ${t||""} model-selector--variant-${i}`,children:[s.jsxs("button",{ref:T,className:`model-selector__trigger ${g?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:R,"aria-label":"选择模型","aria-expanded":g,children:[s.jsxs("div",{className:"model-selector__trigger-content",children:[s.jsx(Ts,{modelId:(S==null?void 0:S.id)||p,profileId:(S==null?void 0:S.sourceProfileId)||null,className:"model-selector__trigger-health"}),s.jsx("span",{className:"model-selector__trigger-text",children:(S==null?void 0:S.shortLabel)||(S==null?void 0:S.label)||"选择模型"})]}),s.jsx(Ta,{size:16,className:`model-selector__trigger-icon ${g?"model-selector__trigger-icon--open":""}`})]}),Q()]})});Lo.displayName="ModelSelector";const $o=a.forwardRef(({selectedContent:t,onSend:e,disabled:n=!1,placeholder:r="输入消息..."},i)=>{const o=a.useRef(null),c=a.useRef(null),[l,m]=a.useState(""),u=t.length>0,{addHistory:d}=Sr();a.useImperativeHandle(i,()=>({setContent:f=>{var x;m(f),(x=o.current)==null||x.focus()},getContent:()=>l,focus:()=>{var f;return(f=o.current)==null?void 0:f.focus()}}),[l]);const p=a.useCallback(()=>{const f=l.trim();if(!f&&t.length===0)return;const x=[];f&&x.push({type:"text",text:f}),t.forEach((N,O)=>{N.type==="image"||N.type==="graphics"?x.push({type:"data-file",data:{filename:`${N.type}-${O+1}.png`,mediaType:"image/png",url:N.url||""}}):N.type==="video"&&x.push({type:"data-file",data:{filename:`video-${O+1}.mp4`,mediaType:"video/mp4",url:N.url||""}})});const z={id:`msg_${Date.now()}`,role:"user",parts:x};f&&d(f,u,"agent"),Promise.resolve(e(z)).catch(N=>{console.error("[EnhancedChatInput] send failed:",N)}),m("")},[l,t,e,d,u]),h=a.useCallback(f=>{f.nativeEvent.isComposing||f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),p())},[p]);a.useEffect(()=>{o.current&&(o.current.style.height="auto",o.current.style.height=`${Math.min(o.current.scrollHeight,120)}px`)},[l]);const g=()=>t.length===0?null:s.jsx("div",{className:"enhanced-chat-input__selection",children:s.jsx(Hl,{items:t,language:"zh",enableHoverPreview:!0})}),y=(l.trim()||t.length>0)&&!n;return s.jsxs("div",{className:"enhanced-chat-input",ref:c,children:[g(),s.jsxs("div",{className:"enhanced-chat-input__form",children:[s.jsx("div",{className:"enhanced-chat-input__input-wrapper",children:s.jsx("textarea",{ref:o,className:"enhanced-chat-input__textarea",value:l,onChange:f=>m(f.target.value),onKeyDown:h,placeholder:u?"描述你想要的效果...":r,disabled:n,rows:4})}),s.jsx("button",{className:`enhanced-chat-input__send ${y?"enhanced-chat-input__send--active":""}`,onClick:p,disabled:!y,"aria-label":"发送",children:s.jsx(Da,{size:20})})]})]})});$o.displayName="EnhancedChatInput";const Gt={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},jt={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},Lt=Hr.createInstance({name:jt.DATABASE_NAME,storeName:jt.SESSIONS_STORE}),yt=Hr.createInstance({name:jt.DATABASE_NAME,storeName:jt.MESSAGES_STORE});function Oo(){return _r()}function xu(t){const e=t.trim().replace(/\n/g," ");return e.length<=Gt.MAX_TITLE_LENGTH?e:e.slice(0,Gt.MAX_TITLE_LENGTH-3)+"..."}async function _u(){const t=Date.now(),e={id:Oo(),title:"新对话",createdAt:t,updatedAt:t,messageCount:0};return await Lt.setItem(e.id,e),e}async function bn(t){return Lt.getItem(t)}async function bu(){const t=[];return await Lt.iterate(e=>{t.push(e)}),await new Promise(e=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>e(),{timeout:50}):setTimeout(e,0)}),t.sort((e,n)=>n.updatedAt-e.updatedAt)}async function ws(t,e){const n=await bn(t);if(n){const r={...n,...e,updatedAt:Date.now()};await Lt.setItem(t,r)}}async function vu(t){const e=await Fo(t);for(const n of e)await yt.removeItem(n.id);await Lt.removeItem(t)}async function Su(t){await yt.setItem(t.id,t);const e=await bn(t.sessionId);if(e){const n={messageCount:e.messageCount+1,updatedAt:Date.now()};await ws(t.sessionId,n)}}async function Fo(t){const e=[];return await yt.iterate(n=>{n.sessionId===t&&e.push(n)}),e.sort((n,r)=>n.timestamp-r.timestamp)}async function Iu(t,e){const n=await yt.getItem(t);if(n){const r={...n,...e};await yt.setItem(t,r)}}async function ku(t){const e=await yt.getItem(t);if(e){await yt.removeItem(t);const n=await bn(e.sessionId);n&&await ws(e.sessionId,{messageCount:Math.max(0,n.messageCount-1)})}}const Qs={isOpen:!1,width:Math.min(Gt.DRAWER_MAX_WIDTH,Math.max(Gt.DRAWER_MIN_WIDTH,window.innerWidth*Gt.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function Uo(){try{const t=localStorage.getItem(jt.DRAWER_STATE);if(t)return{...Qs,...JSON.parse(t)}}catch(t){console.error("[ChatStorage] Failed to get drawer state:",t)}return Qs}function Mu(t){try{const n={...Uo(),...t};localStorage.setItem(jt.DRAWER_STATE,JSON.stringify(n))}catch(e){console.error("[ChatStorage] Failed to set drawer state:",e)}}async function Cu(){await Lt.clear(),await yt.clear(),localStorage.removeItem(jt.DRAWER_STATE)}const Se={createSession:_u,getSession:bn,getAllSessions:bu,updateSession:ws,deleteSession:vu,addMessage:Su,getMessages:Fo,updateMessage:Iu,deleteMessage:ku,getDrawerState:Uo,setDrawerState:Mu,clearAllData:Cu,generateId:Oo,generateTitle:xu};var st=(t=>(t.SENDING="sending",t.STREAMING="streaming",t.SUCCESS="success",t.FAILED="failed",t))(st||{}),ot=(t=>(t.USER="user",t.ASSISTANT="assistant",t))(ot||{});let lt=null;function Wo(t){const e={};let n=1,r=1,i=1,o=t;return o=o.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[图片${n}]`;return e[l]=c,n++,l}),o=o.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[视频${r}]`;return e[l]=c,r++,l}),o=o.replace(/blob:[^\s"'<>]+/g,c=>{const l=`[媒体${i}]`;return e[l]=c,i++,l}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,c=>{const l=`[图片${n}]`;return e[l]=c,n++,l}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,c=>{const l=`[视频${r}]`;return e[l]=c,r++,l}),{sanitized:o,urlMap:e}}function ju(t,e){let n=t;for(const[r,i]of Object.entries(e))n=n.split(r).join(i);return n}async function Tu(t,e={}){const n={};let r=e.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(t.filter(o=>o.status==="success"||o.status==="streaming").map(async o=>{const{sanitized:c,urlMap:l}=Wo(o.content);Object.assign(n,l);const m=[{type:"text",text:c}];if(e.includeImageAttachments&&o.role===ot.USER&&o.attachments&&o.attachments.length>0&&r>0){const u=await Fa(o.attachments,r);r-=u.length,m.push(...u)}return{role:o.role===ot.USER?"user":"assistant",content:m}})),urlMap:n}}async function Nu(t,e,n=[],r,i,o){return Eu(t,e,n,r,i,o)}async function Eu(t,e,n=[],r,i,o){lt&&lt.abort(),lt=new AbortController;const c=lt.signal,l=Date.now().toString(),m=Date.now(),u=(typeof i=="string"?i:i==null?void 0:i.modelId)||Zt.getConfig().modelName||"unknown";try{ye.trackModelCall({taskId:l,taskType:"chat",model:u,promptLength:e.length,hasUploadedImage:n.length>0,startTime:m});const d=Xn("text",i),p=Jn(d==null?void 0:d.binding),h=Qn(d==null?void 0:d.binding),g=La(n),y=Math.max(h-g,0),{geminiMessages:f,urlMap:x}=await Tu(t,{includeImageAttachments:p,maxImageCount:y}),{sanitized:z,urlMap:N}=Wo(e),O={...x,...N},T=$a(f),I=Math.max(h-T,0),b=[{type:"text",text:z}];if(p&&n.length>0&&I>0){const U=await Oa(n,I);b.push(...U)}const S=[];o&&S.push({role:"system",content:[{type:"text",text:o}]}),S.push(...f,{role:"user",content:b});let C="";if(await Zt.sendChat(S,U=>{if(c.aborted)return;const P=ju(U,O);C=P,r({type:"content",content:P})},c,i||void 0),c.aborted)throw new Error("Request cancelled");const R=Date.now()-m;return ye.trackModelSuccess({taskId:l,taskType:"chat",model:u,duration:R,resultSize:C.length}),r({type:"done"}),lt=null,C}catch(d){lt=null;const p=Date.now()-m;if(c.aborted||d.message==="Request cancelled"||d.name==="AbortError")throw ye.trackTaskCancellation({taskId:l,taskType:"chat",duration:p}),r({type:"done"}),new Error("Request cancelled");const h=d instanceof Error?d.message:"Unknown error occurred";throw ye.trackModelFailure({taskId:l,taskType:"chat",model:u,duration:p,error:h}),r({type:"error",error:h}),d}}function Pu(){lt&&(lt.abort(),lt=null)}function Au(){return lt!==null}const er={sendChatMessage:Nu,stopGeneration:Pu,isGenerating:Au},Vn="[[WORKFLOW_MESSAGE]]",Ru=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function zu(t){if(!Ru.includes(t.name)||!bo(t.name))return t;const e=at.get(),n=vo(t.name,{...t.arguments},{fallbackModels:{image:e.imageModelName||Dr(),video:e.videoModelName||Yt(),audio:e.audioModelName||es()}});return{...t,arguments:n}}function Du(t){const e=[];t.aiAnalysis&&e.push(t.aiAnalysis);const n=t.steps.filter(c=>c.status==="completed"),r=t.steps.filter(c=>c.status==="failed");if(n.length>0||r.length>0){const c=[];n.length>0&&c.push(`成功执行 ${n.length} 个工具`),r.length>0&&c.push(`${r.length} 个工具执行失败`),c.length>0&&e.push(`[执行结果: ${c.join(",")}]`)}const i=t.steps.map(c=>{const l={};for(const[m,u]of Object.entries(c.args||{}))m!=="context"&&(typeof u=="string"&&u.length>200?l[m]=u.substring(0,200)+"...":l[m]=u);return{mcp:c.mcp,args:l}}),o={content:e.join(`
636
- `)||`已完成任务: ${t.name}`,next:i};return JSON.stringify(o)}function Lu(t){const e=[{type:"text",text:t.content}];if(t.attachments&&t.attachments.length>0)for(const n of t.attachments)e.push({type:"data-file",data:{filename:n.name,mediaType:n.type,url:n.data}});return{id:t.id,role:t.role===ot.USER?"user":"assistant",parts:e}}function $u(t,e){const r=t.parts.filter(c=>c.type==="text").map(c=>c.text).join(""),o=t.parts.filter(c=>c.type==="data-file").map((c,l)=>{const m=c.data;return{id:`${t.id}-att-${l}`,name:m.filename,type:m.mediaType,size:0,data:m.url,isBlob:!1}});return{id:t.id,sessionId:e,role:t.role==="user"?ot.USER:ot.ASSISTANT,content:r,timestamp:Date.now(),status:st.SUCCESS,attachments:o.length>0?o:void 0}}function Ou(t){return t.workflow&&t.content.startsWith(Vn)?{...t,content:Du(t.workflow)}:t}function tr(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join("")}hu();function Fu(t){const{sessionId:e,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=t,o=a.useRef(_o()),c=a.useRef(r);c.current=r;const l=a.useRef(i);l.current=i;const m=a.useRef(n);m.current=n;const[u,d]=a.useState([]),[p,h]=a.useState("ready"),[g,y]=a.useState(!1),f=a.useRef(null),x=a.useRef([]),z=a.useRef(!1);a.useEffect(()=>{if(!e){d([]),x.current=[];return}(async()=>{y(!0);try{const C=await Se.getMessages(e);x.current=C,d(C.map(Lu))}catch(C){console.error("[useChatHandler] Failed to load messages:",C),d([]),x.current=[]}finally{y(!1)}})()},[e]);const N=a.useCallback(async S=>{if(!e)return;if(z.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}z.current=!0,h("submitted");const C=$u(S,e);await Se.addMessage(C),d(B=>[...B,S]);const R=await Se.getSession(e);await Se.updateSession(e,{updatedAt:Date.now(),messageCount:((R==null?void 0:R.messageCount)||0)+1});const U=Se.generateId();f.current=U;const P={id:U,role:"assistant",parts:[{type:"text",text:""}]};d(B=>[...B,P]),h("streaming");const J=x.current.map(Ou);J.push(C),x.current=[...x.current,C];const ee=tr(S);let X="",Q=!1;try{await er.sendChatMessage(J.slice(0,-1),ee,C.attachments||[],B=>{if(B.type==="content"&&B.content)X=B.content,d(_=>_.map(E=>E.id===U?{...E,parts:[{type:"text",text:X}]}:E));else if(B.type==="done"){const _=Er(X),E=Pr(X)||X;if(_.length>0&&c.current){const $=_.map(K=>zu(K)),re=async()=>{const K=[];for(const de of $)try{const ie=await ls.executeTool(de);K.push({toolCall:de,success:ie.success,data:ie.data,error:ie.error,taskId:ie.taskId})}catch(ie){K.push({toolCall:de,success:!1,error:ie.message||"工具执行失败"})}return K},fe=`${Vn}${U}`;d(K=>K.map(de=>de.id===U?{...de,parts:[{type:"text",text:fe}]}:de)),c.current($,U,re,E)}h("ready");const M={id:U,sessionId:e,role:ot.ASSISTANT,content:_.length>0?`${Vn}${U}`:X,timestamp:Date.now(),status:_.length>0?st.STREAMING:st.SUCCESS};Se.addMessage(M),x.current=[...x.current,M],Se.updateSession(e,{updatedAt:Date.now(),messageCount:((R==null?void 0:R.messageCount)||0)+2}),f.current=null,z.current=!1}else if(B.type==="error"&&B.error){Q=!0,h("error");const _=`❌ 错误: ${B.error}`;d(M=>M.map($=>$.id===U?{...$,parts:[{type:"text",text:_}]}:$));const E={id:U,sessionId:e,role:ot.ASSISTANT,content:_,timestamp:Date.now(),status:st.FAILED,error:B.error};Se.addMessage(E),x.current=[...x.current,E],f.current=null,z.current=!1}},m.current,o.current)}catch(B){if(B.message!=="Request cancelled"&&!Q){h("error"),console.error("[useChatHandler] Stream error:",B);const _=`❌ 错误: ${B.message||"未知错误"}`;if(d(E=>E.map(M=>M.id===U?{...M,parts:[{type:"text",text:_}]}:M)),e&&U){const E={id:U,sessionId:e,role:ot.ASSISTANT,content:_,timestamp:Date.now(),status:st.FAILED,error:B.message||"未知错误"};Se.addMessage(E),x.current=[...x.current,E]}}f.current=null,z.current=!1}},[e]),O=a.useCallback(async()=>{if(er.stopGeneration(),h("ready"),f.current&&e){const S=u.find(C=>C.id===f.current);if(S){const C=tr(S),R={id:S.id,sessionId:e,role:ot.ASSISTANT,content:C,timestamp:Date.now(),status:st.SUCCESS};await Se.addMessage(R)}f.current=null}},[e,u]),T=a.useCallback(S=>{if(u.length<2)return;const C=[...u].reverse().findIndex(J=>J.role==="user");if(C===-1)return;const R=u.length-1-C,U=u[R],P=u.slice(0,R+1);d(P),N(U)},[u,N]),I=a.useCallback((S,C)=>{d(S),C&&(x.current=C)},[]),b=a.useCallback((S,C)=>{x.current=x.current.map(R=>R.id===S?{...R,workflow:C}:R)},[]);return{messages:u,status:p,sendMessage:N,stop:O,regenerate:T,setMessages:d,setMessagesWithRaw:I,updateRawMessageWorkflow:b,isLoading:g}}const Uu=it.lazy(()=>dt(()=>Promise.resolve().then(()=>Qu),void 0,import.meta.url)),nr="[[WORKFLOW_MESSAGE]]";function Wu(t,e){switch(t){case"generate_image":return`生成图片: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_audio":return`生成音频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_text":return`生成文本: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((e==null?void 0:e.theme)||"").substring(0,30)}...`;case"canvas_insertion":return"插入到画布";case"generate_mermaid":return"生成流程图";case"generate_mindmap":return"生成思维导图";default:return`执行 ${t}`}}const sr="chat-drawer-width",Hu=Math.max(375,window.innerWidth*.5),rr=375,Ho=a.forwardRef(({defaultOpen:t=!1,onOpenChange:e},n)=>{const[r,i]=a.useState(()=>Se.getDrawerState().isOpen??t),[o,c]=a.useState([]),[l,m]=a.useState(null),[u,d]=a.useState(!1),[p,h]=a.useState(()=>{const L=localStorage.getItem(sr);if(L){const w=parseInt(L,10);if(!isNaN(w)&&w>=rr)return Math.min(w,window.innerWidth-60)}return Hu}),[g,y]=a.useState(!1),f=a.useRef(null),[x,z]=a.useState(()=>zn("text").modelId),[N,O]=a.useState(()=>{const L=zn("text");return ht(L.profileId,L.modelId)}),[T,I]=a.useState(new Map),b=a.useRef(null),[S,C]=a.useState(null),{executeRetry:R,selectedContent:U,setIsDrawerOpen:P,setDrawerWidth:J}=Ua();a.useEffect(()=>{P(r)},[r,P]),a.useEffect(()=>{J(p)},[p,J]);const ee=it.useRef(null),X=it.useRef(null),{appState:Q,setAppState:B}=Wa();a.useEffect(()=>{if(!g)return;const L=V=>{const v=window.innerWidth-V.clientX,D=Math.max(rr,Math.min(v,window.innerWidth-60));h(D)},w=()=>{y(!1),localStorage.setItem(sr,String(p))};return document.addEventListener("mousemove",L),document.addEventListener("mouseup",w),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",w),document.body.style.userSelect="",document.body.style.cursor=""}},[g,p]),a.useEffect(()=>{const L=()=>{const w=window.innerWidth-60;p>w&&h(w)};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[p]);const _=a.useCallback(L=>{L.preventDefault(),y(!0)},[]),E=a.useCallback(async(L,w,V,v)=>{var G,Y;const W={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(G=L[0])!=null&&G.name.includes("video")?"video":(Y=L[0])!=null&&Y.name.includes("audio")?"audio":"image",prompt:v||"",aiAnalysis:v,count:L.length,steps:L.map((le,_e)=>({id:`step-${_e}`,mcp:le.name,status:"pending",description:Wu(le.name,le.arguments),args:le.arguments}))};I(le=>{const _e=new Map(le);return _e.set(w,W),_e}),b.current=w,Se.updateMessage(w,{workflow:W});try{const le=await V();ye.track("chat_tool_execution_complete",{success:!0,resultCount:le.length}),ye.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:L.length,resultCount:le.length}),I(_e=>{const k=new Map(_e),H=k.get(w);if(H){const F={...H,steps:H.steps.map((Z,oe)=>{const te=le[oe];return{...Z,status:te!=null&&te.success?"completed":"failed",error:te==null?void 0:te.error,result:te==null?void 0:te.data}})};k.set(w,F),Se.updateMessage(w,{workflow:F,status:st.SUCCESS})}return k})}catch(le){console.error("[ChatDrawer] Tool execution failed:",le),I(_e=>{const k=new Map(_e),H=k.get(w);if(H){const F={...H,steps:H.steps.map(Z=>({...Z,status:"failed",error:le.message||"执行失败"}))};k.set(w,F),Se.updateMessage(w,{workflow:F,status:st.FAILED})}return k})}},[]),M=Fu({sessionId:l,temporaryModel:N||x,onToolCalls:E}),$=a.useRef(M.sendMessage);$.current=M.sendMessage,a.useEffect(()=>{(async()=>{const w=Se.getDrawerState(),V=await Se.getAllSessions();c(V);let v=null;if(w.activeSessionId?(v=w.activeSessionId,m(w.activeSessionId)):V.length>0&&(v=V[0].id,m(V[0].id)),v)try{const D=await Se.getMessages(v),W=new Map;for(const Y of D)Y.workflow&&W.set(Y.id,Y.workflow);I(W);const G=D.find(Y=>Y.workflow&&Y.status===st.STREAMING);b.current=(G==null?void 0:G.id)||null}catch(D){console.error("[ChatDrawer] Failed to load workflow messages:",D)}})()},[]),a.useEffect(()=>{Se.setDrawerState({isOpen:r,activeSessionId:l})},[r,l]),a.useEffect(()=>{if(l&&pe.current){const L=pe.current;pe.current=null,setTimeout(()=>{$.current(L)},100)}},[l]),a.useEffect(()=>{if(!Q.openSettings&&pe.current){const L=at.get();if(L!=null&&L.apiKey){const w=pe.current;pe.current=null,l?setTimeout(()=>{$.current(w)},100):(async()=>{const V=await Se.createSession();c(v=>[V,...v]),m(V.id),pe.current=w})()}}},[Q.openSettings,l]),a.useEffect(()=>{const L=w=>{w.key==="Escape"&&r&&(i(!1),e==null||e(!1))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,e]),a.useEffect(()=>{let L=null;return(async()=>{const{workflowSubmissionService:V}=await dt(async()=>{const{workflowSubmissionService:v}=await import("./workflow-submission-service-Ce0cpj8E.js").then(D=>D.a);return{workflowSubmissionService:v}},__vite__mapDeps([0,2]),import.meta.url);L=V.subscribeToAllEvents(v=>{const D=v;I(W=>{let G=null;for(const[k,H]of W.entries())if(H.id===D.workflowId){G=k;break}if(!G)return W;const Y=W.get(G);if(!Y)return W;const le=new Map(W);let _e;switch(D.type){case"step":{_e={...Y,steps:Y.steps.map(k=>k.id===D.stepId?{...k,status:D.status||k.status,result:D.result??k.result,error:D.error??k.error}:k)};break}case"steps_added":{const H=(D.steps||[]).map(F=>({id:F.id,mcp:F.mcp,args:F.args,description:F.description,status:F.status}));_e={...Y,steps:[...Y.steps,...H]};break}case"completed":case"failed":{const k=D.type==="completed"?"completed":"failed";_e={...Y,status:k,steps:Y.steps.map(H=>{if(H.status==="running"||H.status==="pending"){const F=H.result;return F!=null&&F.taskId?H:{...H,status:k,error:D.type==="failed"?D.error:void 0}}return H})};break}default:return W}return le.set(G,_e),Se.updateMessage(G,{workflow:_e}),le})})})().catch(V=>{console.error("[ChatDrawer] Failed to setup workflow sync:",V)}),()=>{L==null||L.unsubscribe()}},[]),a.useEffect(()=>{if(!u)return;const L=V=>{const v=V.target;v.closest(".t-dialog")===null&&ee.current&&!ee.current.contains(v)&&X.current&&!X.current.contains(v)&&d(!1)},w=setTimeout(()=>{document.addEventListener("mousedown",L)},100);return()=>{clearTimeout(w),document.removeEventListener("mousedown",L)}},[u]);const re=a.useCallback(()=>{i(L=>{const w=!L;return e==null||e(w),w})},[e]),fe=a.useCallback(()=>{i(!1),e==null||e(!1)},[e]),K=a.useCallback(async()=>{ye.track("chat_session_create");const L=await Se.createSession();c(w=>[L,...w]),m(L.id),d(!1),I(new Map),b.current=null,z(void 0)},[]),de=a.useCallback(()=>{d(L=>!L)},[]),ie=a.useCallback(async L=>{ye.track("chat_session_select"),m(L),d(!1),z(void 0);try{const w=await Se.getMessages(L),V=new Map;for(const D of w)D.workflow&&V.set(D.id,D.workflow);I(V);const v=w.find(D=>D.workflow&&D.status===st.STREAMING);b.current=(v==null?void 0:v.id)||null}catch(w){console.error("[ChatDrawer] Failed to load workflow messages:",w),I(new Map),b.current=null}},[]),ue=a.useCallback(async L=>{ye.track("chat_session_delete"),await Se.deleteSession(L),c(w=>{const V=w.filter(v=>v.id!==L);if(l===L){const v=V[0]||null;m((v==null?void 0:v.id)||null)}return V})},[l]),xe=a.useCallback(async(L,w)=>{ye.track("chat_session_rename"),await Se.updateSession(L,{title:w}),c(V=>V.map(v=>v.id===L?{...v,title:w}:v))},[]),pe=it.useRef(null),ae=a.useCallback(async L=>{try{ye.track("chat_message_send",{hasImages:L.parts.some(V=>V.type==="image_url")}),ye.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:L.parts.some(V=>V.type==="image_url"),partCount:L.parts.length,textLength:L.parts.filter(V=>V.type==="text").reduce((V,v)=>V+String(v.text||"").length,0)});const w=at.get();if(!(w!=null&&w.apiKey)){pe.current=L,B({...Q,openSettings:!0});return}if(pe.current=null,!l){const V=await Se.createSession();c(v=>[V,...v]),m(V.id),pe.current=L;return}await M.sendMessage(L)}catch(w){console.error("[ChatDrawer] send message failed:",w),pe.current=L}},[l,M,Q,B]),q=a.useCallback(async L=>{var Ve;const{context:w,workflow:V,textModel:v,autoOpen:D=!0}=L;D&&(i(!0),e==null||e(!0)),v&&z(v);const W=await Se.createSession(),G=[];w.userInstruction&&G.push(w.userInstruction),w.selection.texts.length>0&&G.push(`
635
+ - 创建笔记前查看可用目录`,inputSchema:{type:"object",properties:{}},execute:async()=>{try{return{success:!0,type:"text",data:(await Dt()).map(e=>({id:e.id,name:e.name,isDefault:e.isDefault,createdAt:new Date(e.createdAt).toISOString()}))}}catch(t){return{success:!1,error:`获取目录失败: ${t.message}`,type:"error"}}}},du=[iu,au,cu,lu];function uu(t){const e=t.prompt||_a,n=t.videoAnalyzerAction||"analyze";if(n!=="prompt-generate"&&!t.videoData&&!t.youtubeUrl&&!t.videoCacheUrl)return{success:!1,error:"需要提供 videoData、videoCacheUrl 或 youtubeUrl",type:"error"};const r=ft.createTask({prompt:t.taskLabel||"视频分析",model:t.model,modelRef:t.modelRef||null,mimeType:t.mimeType||"video/mp4",youtubeUrl:t.youtubeUrl,videoData:t.videoData,videoCacheUrl:t.videoCacheUrl,pdfCacheUrl:t.pdfCacheUrl,pdfMimeType:t.pdfMimeType,pdfName:t.pdfName,videoAnalyzerAction:n,videoAnalyzerPrompt:e,videoAnalyzerSource:t.videoAnalyzerSource,videoAnalyzerSourceLabel:t.videoAnalyzerSourceLabel,videoAnalyzerSourceSnapshot:t.videoAnalyzerSourceSnapshot,videoAnalyzerProductInfo:t.videoAnalyzerProductInfo,knowledgeContextRefs:t.knowledgeContextRefs,autoInsertToCanvas:!1},xt.CHAT);return{success:!0,data:{taskId:r.id,prompt:t.taskLabel||"视频分析",model:t.model},type:"text",taskId:r.id,task:r}}const mu={name:"video_analyze",description:"分析视频内容,返回结构化的镜头拆解、脚本提取、风格分析等数据",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{videoData:{type:"string",description:"base64 编码的视频数据(不含 data: 前缀),≤20MB"},mimeType:{type:"string",description:"视频 MIME 类型,默认 video/mp4",default:"video/mp4"},youtubeUrl:{type:"string",description:"YouTube 视频 URL"},videoCacheUrl:{type:"string",description:"本地缓存的视频 URL(队列模式)"},pdfCacheUrl:{type:"string",description:"本地缓存的 PDF URL(提示词生成上下文)"},pdfMimeType:{type:"string",description:"PDF MIME 类型,默认 application/pdf"},pdfName:{type:"string",description:"PDF 文件名"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},videoAnalyzerAction:{type:"string",description:"视频工具动作:analyze 或 prompt-generate"},videoAnalyzerProductInfo:{type:"object",description:"提示词生成时的画面风格、视频模型、单段时长等表单参数"},model:{type:"string",description:"模型 ID,默认使用当前文本模型"}},required:[]},execute:async(t,e)=>(e==null?void 0:e.mode)==="queue"?uu(t):xa(t)};function pu(t){const e=t.prompt||ba;if(!t.audioData&&!t.audioCacheUrl)return{success:!1,error:"需要提供 audioData 或 audioCacheUrl",type:"error"};const n=ft.createTask({prompt:t.taskLabel||"音频分析",model:t.model,modelRef:t.modelRef||null,mimeType:t.mimeType||"audio/mpeg",audioData:t.audioData,audioCacheUrl:t.audioCacheUrl,musicAnalyzerAction:"analyze",musicAnalyzerPrompt:e,musicAnalyzerSource:t.musicAnalyzerSource,musicAnalyzerSourceLabel:t.musicAnalyzerSourceLabel,musicAnalyzerSourceSnapshot:t.musicAnalyzerSourceSnapshot,autoInsertToCanvas:!1},xt.CHAT);return{success:!0,data:{taskId:n.id,prompt:t.taskLabel||"音频分析",model:t.model},type:"text",taskId:n.id,task:n}}const hu={name:"audio_analyze",description:"分析音频内容,返回结构化的音乐风格、情绪、Suno 标签和歌词改写建议",supportedModes:["async","queue"],inputSchema:{type:"object",properties:{audioData:{type:"string",description:"base64 编码的音频数据(不含 data: 前缀)"},mimeType:{type:"string",description:"音频 MIME 类型,默认 audio/mpeg",default:"audio/mpeg"},audioCacheUrl:{type:"string",description:"本地缓存的音频 URL(队列模式)"},prompt:{type:"string",description:"自定义分析 prompt(可选,有内置默认值)"},model:{type:"string",description:"Gemini 多模态模型 ID,默认使用当前文本模型"}},required:[]},execute:async(t,e)=>(e==null?void 0:e.mode)==="queue"?pu(t):va(t)};let Qs=!1;function fu(){Qs||(Qs=!0,ls.registerAll([Sa,us,td,id,Hd,_o,ad,yd,bd,Md,Td,Pd,Dd,gs,...du,mu,hu]))}const zo=it.memo(({session:t,isActive:e,onSelect:n,onDelete:r,onRename:i})=>{const[o,c]=a.useState(!1),[l,m]=a.useState(t.title),u=a.useRef(null),d=a.useCallback(()=>{o||n()},[n,o]),p=a.useCallback(N=>{N.stopPropagation(),r()},[r]),h=a.useCallback(N=>{N.stopPropagation(),m(t.title),c(!0)},[t.title]),g=a.useCallback(()=>{const N=l.trim();N&&N!==t.title&&i(N),c(!1)},[l,t.title,i]),y=a.useCallback(()=>{m(t.title),c(!1)},[t.title]),f=a.useCallback(N=>{N.key==="Enter"?(N.preventDefault(),g()):N.key==="Escape"&&(N.preventDefault(),y())},[g,y]),x=a.useCallback(N=>{m(N.target.value)},[]);a.useEffect(()=>{o&&u.current&&(u.current.focus(),u.current.select())},[o]);const z=a.useMemo(()=>{const N=new Date(t.updatedAt),O=new Date;return N.toDateString()===O.toDateString()?N.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):N.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[t.updatedAt]);return s.jsxs("div",{className:`session-item ${e?"session-item--active":""} ${o?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:d,role:"button",tabIndex:0,onKeyDown:N=>!o&&N.key==="Enter"&&d(),children:[s.jsxs("div",{className:"session-item__content",children:[o?s.jsx("input",{ref:u,className:"session-item__title-input",value:l,onChange:x,onKeyDown:f,onBlur:g,onClick:N=>N.stopPropagation(),maxLength:50}):s.jsx("div",{className:"session-item__title",children:t.title}),s.jsx("div",{className:"session-item__time",children:z})]}),!o&&s.jsxs("div",{className:"session-item__actions",children:[s.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:h,"aria-label":`编辑会话标题: ${t.title}`,children:s.jsx(Ia,{size:14})}),s.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:p,"aria-label":`删除会话: ${t.title}`,children:s.jsx(ka,{size:14})})]})]})});zo.displayName="SessionItem";const Do=it.memo(({sessions:t,activeSessionId:e,onSelectSession:n,onNewSession:r,onDeleteSession:i,onRenameSession:o})=>{const[c,l]=it.useState(null),m=a.useCallback(g=>{n(g)},[n]),u=a.useCallback(g=>{l(g)},[]),d=a.useCallback(()=>{c&&(i(c),l(null))},[c,i]),p=a.useCallback(()=>{l(null)},[]),h=a.useCallback((g,y)=>{o(g,y)},[o]);return s.jsxs("div",{className:"session-list",children:[s.jsxs("div",{className:"session-list__header",children:[s.jsx("span",{className:"session-list__title",children:"会话列表"}),s.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:r,"aria-label":"新建会话",children:[s.jsx(Hr,{size:14}),s.jsx("span",{children:"新建"})]})]}),s.jsx("div",{className:"session-list__items",children:t.length===0?s.jsx("div",{className:"session-list__empty",children:"暂无会话"}):t.map(g=>s.jsx(zo,{session:g,isActive:g.id===e,onSelect:()=>m(g.id),onDelete:()=>u(g.id),onRename:y=>h(g.id,y)},g.id))}),s.jsx(Ma,{open:c!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:g=>{g||p()},onConfirm:d})]})});Do.displayName="SessionList";const Lo=it.memo(({isOpen:t,onClick:e,drawerWidth:n})=>{const r={right:t&&n?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${n-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return s.jsx(je,{content:t?"收起对话":"展开对话",children:s.jsx("button",{className:`chat-drawer-trigger ${t?"chat-drawer-trigger--active":""}`,"data-track":t?"chat_click_drawer_close":"chat_click_drawer_open",onClick:e,"aria-label":t?"收起对话":"展开对话","aria-expanded":t,style:r,children:s.jsx(Ca,{size:16,className:"chat-drawer-trigger__icon"})})})});Lo.displayName="ChatDrawerTrigger";function fn(t){return t.sourceProfileName||Zn[t.vendor]||t.id}const gu=it.memo(({model:t})=>{const{summary:e,detail:n}=za(t.sourceProfileId,t.id);return e?s.jsx(je,{content:n,placement:"top",disabled:n===e,children:s.jsx("span",{className:"model-selector__item-price",children:e})}):null}),wu=it.memo(({model:t})=>{const e=Da(t.sourceProfileId,t.id);return e!=null&&e.description?s.jsx("div",{className:"model-selector__item-desc",children:e.description}):null});function yu(t,e){var o;const n=fn(t),r=(o=t.description)==null?void 0:o.trim(),i=(e==null?void 0:e.includeProvider)??!0;return r?!i||r.includes(n)?r:`${n} · ${r}`:i?n:""}function xu(t){return fn(t).trim().slice(0,1).toUpperCase()||"M"}const $o=it.memo(({className:t,value:e,valueRef:n,onChange:r,variant:i="capsule"})=>{var B;const o=po("text"),c=((B=o[0])==null?void 0:B.id)||ja,[l,m]=a.useState(c),[u,d]=a.useState(()=>ht(null,c)),p=e??l,h=n===void 0?u:n,[g,y]=a.useState(!1),[f,x]=a.useState(""),[z,N]=a.useState(null),O=a.useRef(null),T=a.useRef(null);a.useEffect(()=>{!e&&c&&l!==c&&(m(c),d(ht(null,c)))},[c,l,e]),a.useEffect(()=>{if(!g)return;const _=M=>{const $=M.target;O.current&&!O.current.contains($)&&T.current&&!T.current.contains($)&&(y(!1),x(""))},E=setTimeout(()=>{document.addEventListener("mousedown",_)},100);return()=>{clearTimeout(E),document.removeEventListener("mousedown",_)}},[g]);const I=a.useMemo(()=>p?is(p,h):null,[p,h]),v=a.useMemo(()=>{if(pn(o,p,h)||!p)return o;const E=Un("text",p,h);return E?[E,...o]:o},[o,p,h]),S=a.useMemo(()=>pn(v,p,h)||v.find(_=>_.id===p),[v,p,h]),C=a.useCallback(_=>{const E=ht(_.sourceProfileId||null,_.id);e===void 0&&m(_.id),n===void 0&&d(E),r==null||r(_.id,E),y(!1),x("")},[e,n,r]),R=a.useCallback(()=>{const _=!g;y(_),_?N((S==null?void 0:S.vendor)||null):x("")},[S==null?void 0:S.vendor,g]),U=a.useMemo(()=>{const _=new Map,E=[];return v.forEach(M=>{_.has(M.vendor)||(E.push(M.vendor),_.set(M.vendor,0)),_.set(M.vendor,(_.get(M.vendor)??0)+1)}),E.map(M=>({id:M,label:Zn[M],count:_.get(M)??0,icon:s.jsx(Ta,{vendor:M,size:14})}))},[v]),P=a.useCallback(_=>{N(_)},[]),J=a.useMemo(()=>{const _=f.toLowerCase().trim();return _?v.filter(E=>{var $,re;const M=fn(E).toLowerCase();return E.id.toLowerCase().includes(_)||E.label.toLowerCase().includes(_)||(($=E.shortLabel)==null?void 0:$.toLowerCase().includes(_))||((re=E.description)==null?void 0:re.toLowerCase().includes(_))||M.includes(_)}):z?v.filter(E=>E.vendor===z):v},[f,z,v]),[ee,X]=a.useState({top:0,left:0,width:0,bottom:0,placement:"bottom",maxHeight:480});a.useLayoutEffect(()=>{if(!g)return;const _=()=>{if(!T.current)return;const E=T.current.getBoundingClientRect(),M=window.innerHeight,$=M-E.bottom,re=E.top,fe=$<400&&re>$?"top":"bottom",K=fe==="top"?re-16:M-E.bottom-16;X({top:E.top,left:E.left,width:E.width,bottom:E.bottom,placement:fe,maxHeight:Math.min(Math.max(K,200),600)})};return _(),window.addEventListener("resize",_),window.addEventListener("scroll",_,!0),()=>{window.removeEventListener("resize",_),window.removeEventListener("scroll",_,!0)}},[g]);const Q=()=>{if(!g)return null;const _=s.jsxs("div",{ref:O,className:"model-selector__dropdown",style:{position:"fixed",zIndex:qn.DROPDOWN_PORTAL,left:ee.left,top:ee.placement==="bottom"?ee.bottom+8:"auto",bottom:ee.placement==="top"?window.innerHeight-ee.top+8:"auto",minWidth:360,width:i==="form"?ee.width:"auto",maxHeight:ee.maxHeight,visibility:ee.width===0?"hidden":"visible",transformOrigin:ee.placement==="bottom"?"top left":"bottom left",display:"flex",flexDirection:"column"},onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"model-selector__search",children:s.jsx(Ea,{value:f,onChange:x,placeholder:"搜索模型...",prefixIcon:s.jsx(Pa,{}),clearable:!0,autofocus:!0})}),s.jsx(Aa,{tabs:U,activeTab:z,onTabChange:P,searchQuery:f,compact:!0,children:s.jsx("div",{className:"model-selector__list",children:J.length===0?s.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):J.map(E=>{const M=ho(E),$=M===I,re=!!f.trim(),fe=yu(E,{includeProvider:!re});return s.jsxs("button",{className:`model-selector__item ${$?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>C(E),children:[s.jsx("span",{className:"model-selector__item-icon model-selector__item-icon--text","aria-hidden":"true",children:xu(E)}),s.jsxs("div",{className:"model-selector__item-content",children:[s.jsxs("div",{className:"model-selector__item-header",children:[s.jsx("span",{className:"model-selector__item-name",children:E.shortLabel||E.label}),re?s.jsx("span",{className:"model-selector__item-provider",children:fn(E)}):null,s.jsx(Ts,{modelId:E.id,profileId:E.sourceProfileId||null}),s.jsx(Ra,{modelId:E.id}),s.jsx(gu,{model:E})]}),fe?s.jsx("div",{className:"model-selector__item-desc",children:fe}):s.jsx(wu,{model:E})]}),$&&s.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:s.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},M)})})})]});return Rt.createPortal(_,document.body)};return s.jsxs("div",{className:`model-selector ${t||""} model-selector--variant-${i}`,children:[s.jsxs("button",{ref:T,className:`model-selector__trigger ${g?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:R,"aria-label":"选择模型","aria-expanded":g,children:[s.jsxs("div",{className:"model-selector__trigger-content",children:[s.jsx(Ts,{modelId:(S==null?void 0:S.id)||p,profileId:(S==null?void 0:S.sourceProfileId)||null,className:"model-selector__trigger-health"}),s.jsx("span",{className:"model-selector__trigger-text",children:(S==null?void 0:S.shortLabel)||(S==null?void 0:S.label)||"选择模型"})]}),s.jsx(Na,{size:16,className:`model-selector__trigger-icon ${g?"model-selector__trigger-icon--open":""}`})]}),Q()]})});$o.displayName="ModelSelector";const Oo=a.forwardRef(({selectedContent:t,onSend:e,disabled:n=!1,placeholder:r="输入消息..."},i)=>{const o=a.useRef(null),c=a.useRef(null),[l,m]=a.useState(""),u=t.length>0,{addHistory:d}=Ir();a.useImperativeHandle(i,()=>({setContent:f=>{var x;m(f),(x=o.current)==null||x.focus()},getContent:()=>l,focus:()=>{var f;return(f=o.current)==null?void 0:f.focus()}}),[l]);const p=a.useCallback(()=>{const f=l.trim();if(!f&&t.length===0)return;const x=[];f&&x.push({type:"text",text:f}),t.forEach((N,O)=>{N.type==="image"||N.type==="graphics"?x.push({type:"data-file",data:{filename:`${N.type}-${O+1}.png`,mediaType:"image/png",url:N.url||""}}):N.type==="video"&&x.push({type:"data-file",data:{filename:`video-${O+1}.mp4`,mediaType:"video/mp4",url:N.url||""}})});const z={id:`msg_${Date.now()}`,role:"user",parts:x};f&&d(f,u,"agent"),Promise.resolve(e(z)).catch(N=>{console.error("[EnhancedChatInput] send failed:",N)}),m("")},[l,t,e,d,u]),h=a.useCallback(f=>{f.nativeEvent.isComposing||f.key==="Enter"&&!f.shiftKey&&(f.preventDefault(),p())},[p]);a.useEffect(()=>{o.current&&(o.current.style.height="auto",o.current.style.height=`${Math.min(o.current.scrollHeight,120)}px`)},[l]);const g=()=>t.length===0?null:s.jsx("div",{className:"enhanced-chat-input__selection",children:s.jsx(Vl,{items:t,language:"zh",enableHoverPreview:!0})}),y=(l.trim()||t.length>0)&&!n;return s.jsxs("div",{className:"enhanced-chat-input",ref:c,children:[g(),s.jsxs("div",{className:"enhanced-chat-input__form",children:[s.jsx("div",{className:"enhanced-chat-input__input-wrapper",children:s.jsx("textarea",{ref:o,className:"enhanced-chat-input__textarea",value:l,onChange:f=>m(f.target.value),onKeyDown:h,placeholder:u?"描述你想要的效果...":r,disabled:n,rows:4})}),s.jsx("button",{className:`enhanced-chat-input__send ${y?"enhanced-chat-input__send--active":""}`,onClick:p,disabled:!y,"aria-label":"发送",children:s.jsx(La,{size:20})})]})]})});Oo.displayName="EnhancedChatInput";const Gt={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},jt={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},Lt=Vr.createInstance({name:jt.DATABASE_NAME,storeName:jt.SESSIONS_STORE}),yt=Vr.createInstance({name:jt.DATABASE_NAME,storeName:jt.MESSAGES_STORE});function Fo(){return vr()}function _u(t){const e=t.trim().replace(/\n/g," ");return e.length<=Gt.MAX_TITLE_LENGTH?e:e.slice(0,Gt.MAX_TITLE_LENGTH-3)+"..."}async function vu(){const t=Date.now(),e={id:Fo(),title:"新对话",createdAt:t,updatedAt:t,messageCount:0};return await Lt.setItem(e.id,e),e}async function vn(t){return Lt.getItem(t)}async function bu(){const t=[];return await Lt.iterate(e=>{t.push(e)}),await new Promise(e=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>e(),{timeout:50}):setTimeout(e,0)}),t.sort((e,n)=>n.updatedAt-e.updatedAt)}async function ws(t,e){const n=await vn(t);if(n){const r={...n,...e,updatedAt:Date.now()};await Lt.setItem(t,r)}}async function Su(t){const e=await Uo(t);for(const n of e)await yt.removeItem(n.id);await Lt.removeItem(t)}async function Iu(t){await yt.setItem(t.id,t);const e=await vn(t.sessionId);if(e){const n={messageCount:e.messageCount+1,updatedAt:Date.now()};await ws(t.sessionId,n)}}async function Uo(t){const e=[];return await yt.iterate(n=>{n.sessionId===t&&e.push(n)}),e.sort((n,r)=>n.timestamp-r.timestamp)}async function ku(t,e){const n=await yt.getItem(t);if(n){const r={...n,...e};await yt.setItem(t,r)}}async function Mu(t){const e=await yt.getItem(t);if(e){await yt.removeItem(t);const n=await vn(e.sessionId);n&&await ws(e.sessionId,{messageCount:Math.max(0,n.messageCount-1)})}}const er={isOpen:!1,width:Math.min(Gt.DRAWER_MAX_WIDTH,Math.max(Gt.DRAWER_MIN_WIDTH,window.innerWidth*Gt.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function Wo(){try{const t=localStorage.getItem(jt.DRAWER_STATE);if(t)return{...er,...JSON.parse(t)}}catch(t){console.error("[ChatStorage] Failed to get drawer state:",t)}return er}function Cu(t){try{const n={...Wo(),...t};localStorage.setItem(jt.DRAWER_STATE,JSON.stringify(n))}catch(e){console.error("[ChatStorage] Failed to set drawer state:",e)}}async function ju(){await Lt.clear(),await yt.clear(),localStorage.removeItem(jt.DRAWER_STATE)}const Se={createSession:vu,getSession:vn,getAllSessions:bu,updateSession:ws,deleteSession:Su,addMessage:Iu,getMessages:Uo,updateMessage:ku,deleteMessage:Mu,getDrawerState:Wo,setDrawerState:Cu,clearAllData:ju,generateId:Fo,generateTitle:_u};var st=(t=>(t.SENDING="sending",t.STREAMING="streaming",t.SUCCESS="success",t.FAILED="failed",t))(st||{}),ot=(t=>(t.USER="user",t.ASSISTANT="assistant",t))(ot||{});let lt=null;function Ho(t){const e={};let n=1,r=1,i=1,o=t;return o=o.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[图片${n}]`;return e[l]=c,n++,l}),o=o.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[视频${r}]`;return e[l]=c,r++,l}),o=o.replace(/blob:[^\s"'<>]+/g,c=>{const l=`[媒体${i}]`;return e[l]=c,i++,l}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,c=>{const l=`[图片${n}]`;return e[l]=c,n++,l}),o=o.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,c=>{const l=`[视频${r}]`;return e[l]=c,r++,l}),{sanitized:o,urlMap:e}}function Tu(t,e){let n=t;for(const[r,i]of Object.entries(e))n=n.split(r).join(i);return n}async function Nu(t,e={}){const n={};let r=e.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(t.filter(o=>o.status==="success"||o.status==="streaming").map(async o=>{const{sanitized:c,urlMap:l}=Ho(o.content);Object.assign(n,l);const m=[{type:"text",text:c}];if(e.includeImageAttachments&&o.role===ot.USER&&o.attachments&&o.attachments.length>0&&r>0){const u=await Ua(o.attachments,r);r-=u.length,m.push(...u)}return{role:o.role===ot.USER?"user":"assistant",content:m}})),urlMap:n}}async function Eu(t,e,n=[],r,i,o){return Pu(t,e,n,r,i,o)}async function Pu(t,e,n=[],r,i,o){lt&&lt.abort(),lt=new AbortController;const c=lt.signal,l=Date.now().toString(),m=Date.now(),u=(typeof i=="string"?i:i==null?void 0:i.modelId)||Zt.getConfig().modelName||"unknown";try{ye.trackModelCall({taskId:l,taskType:"chat",model:u,promptLength:e.length,hasUploadedImage:n.length>0,startTime:m});const d=Xn("text",i),p=Jn(d==null?void 0:d.binding),h=Qn(d==null?void 0:d.binding),g=$a(n),y=Math.max(h-g,0),{geminiMessages:f,urlMap:x}=await Nu(t,{includeImageAttachments:p,maxImageCount:y}),{sanitized:z,urlMap:N}=Ho(e),O={...x,...N},T=Oa(f),I=Math.max(h-T,0),v=[{type:"text",text:z}];if(p&&n.length>0&&I>0){const U=await Fa(n,I);v.push(...U)}const S=[];o&&S.push({role:"system",content:[{type:"text",text:o}]}),S.push(...f,{role:"user",content:v});let C="";if(await Zt.sendChat(S,U=>{if(c.aborted)return;const P=Tu(U,O);C=P,r({type:"content",content:P})},c,i||void 0),c.aborted)throw new Error("Request cancelled");const R=Date.now()-m;return ye.trackModelSuccess({taskId:l,taskType:"chat",model:u,duration:R,resultSize:C.length}),r({type:"done"}),lt=null,C}catch(d){lt=null;const p=Date.now()-m;if(c.aborted||d.message==="Request cancelled"||d.name==="AbortError")throw ye.trackTaskCancellation({taskId:l,taskType:"chat",duration:p}),r({type:"done"}),new Error("Request cancelled");const h=d instanceof Error?d.message:"Unknown error occurred";throw ye.trackModelFailure({taskId:l,taskType:"chat",model:u,duration:p,error:h}),r({type:"error",error:h}),d}}function Au(){lt&&(lt.abort(),lt=null)}function Ru(){return lt!==null}const tr={sendChatMessage:Eu,stopGeneration:Au,isGenerating:Ru},Vn="[[WORKFLOW_MESSAGE]]",zu=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function Du(t){if(!zu.includes(t.name)||!bo(t.name))return t;const e=at.get(),n=So(t.name,{...t.arguments},{fallbackModels:{image:e.imageModelName||Lr(),video:e.videoModelName||Yt(),audio:e.audioModelName||es()}});return{...t,arguments:n}}function Lu(t){const e=[];t.aiAnalysis&&e.push(t.aiAnalysis);const n=t.steps.filter(c=>c.status==="completed"),r=t.steps.filter(c=>c.status==="failed");if(n.length>0||r.length>0){const c=[];n.length>0&&c.push(`成功执行 ${n.length} 个工具`),r.length>0&&c.push(`${r.length} 个工具执行失败`),c.length>0&&e.push(`[执行结果: ${c.join(",")}]`)}const i=t.steps.map(c=>{const l={};for(const[m,u]of Object.entries(c.args||{}))m!=="context"&&(typeof u=="string"&&u.length>200?l[m]=u.substring(0,200)+"...":l[m]=u);return{mcp:c.mcp,args:l}}),o={content:e.join(`
636
+ `)||`已完成任务: ${t.name}`,next:i};return JSON.stringify(o)}function $u(t){const e=[{type:"text",text:t.content}];if(t.attachments&&t.attachments.length>0)for(const n of t.attachments)e.push({type:"data-file",data:{filename:n.name,mediaType:n.type,url:n.data}});return{id:t.id,role:t.role===ot.USER?"user":"assistant",parts:e}}function Ou(t,e){const r=t.parts.filter(c=>c.type==="text").map(c=>c.text).join(""),o=t.parts.filter(c=>c.type==="data-file").map((c,l)=>{const m=c.data;return{id:`${t.id}-att-${l}`,name:m.filename,type:m.mediaType,size:0,data:m.url,isBlob:!1}});return{id:t.id,sessionId:e,role:t.role==="user"?ot.USER:ot.ASSISTANT,content:r,timestamp:Date.now(),status:st.SUCCESS,attachments:o.length>0?o:void 0}}function Fu(t){return t.workflow&&t.content.startsWith(Vn)?{...t,content:Lu(t.workflow)}:t}function nr(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join("")}fu();function Uu(t){const{sessionId:e,temporaryModel:n,onToolCalls:r,onWorkflowUpdate:i}=t,o=a.useRef(vo()),c=a.useRef(r);c.current=r;const l=a.useRef(i);l.current=i;const m=a.useRef(n);m.current=n;const[u,d]=a.useState([]),[p,h]=a.useState("ready"),[g,y]=a.useState(!1),f=a.useRef(null),x=a.useRef([]),z=a.useRef(!1);a.useEffect(()=>{if(!e){d([]),x.current=[];return}(async()=>{y(!0);try{const C=await Se.getMessages(e);x.current=C,d(C.map($u))}catch(C){console.error("[useChatHandler] Failed to load messages:",C),d([]),x.current=[]}finally{y(!1)}})()},[e]);const N=a.useCallback(async S=>{if(!e)return;if(z.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}z.current=!0,h("submitted");const C=Ou(S,e);await Se.addMessage(C),d(B=>[...B,S]);const R=await Se.getSession(e);await Se.updateSession(e,{updatedAt:Date.now(),messageCount:((R==null?void 0:R.messageCount)||0)+1});const U=Se.generateId();f.current=U;const P={id:U,role:"assistant",parts:[{type:"text",text:""}]};d(B=>[...B,P]),h("streaming");const J=x.current.map(Fu);J.push(C),x.current=[...x.current,C];const ee=nr(S);let X="",Q=!1;try{await tr.sendChatMessage(J.slice(0,-1),ee,C.attachments||[],B=>{if(B.type==="content"&&B.content)X=B.content,d(_=>_.map(E=>E.id===U?{...E,parts:[{type:"text",text:X}]}:E));else if(B.type==="done"){const _=Pr(X),E=Ar(X)||X;if(_.length>0&&c.current){const $=_.map(K=>Du(K)),re=async()=>{const K=[];for(const de of $)try{const ie=await ls.executeTool(de);K.push({toolCall:de,success:ie.success,data:ie.data,error:ie.error,taskId:ie.taskId})}catch(ie){K.push({toolCall:de,success:!1,error:ie.message||"工具执行失败"})}return K},fe=`${Vn}${U}`;d(K=>K.map(de=>de.id===U?{...de,parts:[{type:"text",text:fe}]}:de)),c.current($,U,re,E)}h("ready");const M={id:U,sessionId:e,role:ot.ASSISTANT,content:_.length>0?`${Vn}${U}`:X,timestamp:Date.now(),status:_.length>0?st.STREAMING:st.SUCCESS};Se.addMessage(M),x.current=[...x.current,M],Se.updateSession(e,{updatedAt:Date.now(),messageCount:((R==null?void 0:R.messageCount)||0)+2}),f.current=null,z.current=!1}else if(B.type==="error"&&B.error){Q=!0,h("error");const _=`❌ 错误: ${B.error}`;d(M=>M.map($=>$.id===U?{...$,parts:[{type:"text",text:_}]}:$));const E={id:U,sessionId:e,role:ot.ASSISTANT,content:_,timestamp:Date.now(),status:st.FAILED,error:B.error};Se.addMessage(E),x.current=[...x.current,E],f.current=null,z.current=!1}},m.current,o.current)}catch(B){if(B.message!=="Request cancelled"&&!Q){h("error"),console.error("[useChatHandler] Stream error:",B);const _=`❌ 错误: ${B.message||"未知错误"}`;if(d(E=>E.map(M=>M.id===U?{...M,parts:[{type:"text",text:_}]}:M)),e&&U){const E={id:U,sessionId:e,role:ot.ASSISTANT,content:_,timestamp:Date.now(),status:st.FAILED,error:B.message||"未知错误"};Se.addMessage(E),x.current=[...x.current,E]}}f.current=null,z.current=!1}},[e]),O=a.useCallback(async()=>{if(tr.stopGeneration(),h("ready"),f.current&&e){const S=u.find(C=>C.id===f.current);if(S){const C=nr(S),R={id:S.id,sessionId:e,role:ot.ASSISTANT,content:C,timestamp:Date.now(),status:st.SUCCESS};await Se.addMessage(R)}f.current=null}},[e,u]),T=a.useCallback(S=>{if(u.length<2)return;const C=[...u].reverse().findIndex(J=>J.role==="user");if(C===-1)return;const R=u.length-1-C,U=u[R],P=u.slice(0,R+1);d(P),N(U)},[u,N]),I=a.useCallback((S,C)=>{d(S),C&&(x.current=C)},[]),v=a.useCallback((S,C)=>{x.current=x.current.map(R=>R.id===S?{...R,workflow:C}:R)},[]);return{messages:u,status:p,sendMessage:N,stop:O,regenerate:T,setMessages:d,setMessagesWithRaw:I,updateRawMessageWorkflow:v,isLoading:g}}const Wu=it.lazy(()=>dt(()=>Promise.resolve().then(()=>em),void 0,import.meta.url)),sr="[[WORKFLOW_MESSAGE]]";function Hu(t,e){switch(t){case"generate_image":return`生成图片: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_audio":return`生成音频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_text":return`生成文本: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((e==null?void 0:e.theme)||"").substring(0,30)}...`;case"canvas_insertion":return"插入到画布";case"generate_mermaid":return"生成流程图";case"generate_mindmap":return"生成思维导图";default:return`执行 ${t}`}}const rr="chat-drawer-width",Vu=Math.max(375,window.innerWidth*.5),or=375,Vo=a.forwardRef(({defaultOpen:t=!1,onOpenChange:e},n)=>{const[r,i]=a.useState(()=>Se.getDrawerState().isOpen??t),[o,c]=a.useState([]),[l,m]=a.useState(null),[u,d]=a.useState(!1),[p,h]=a.useState(()=>{const L=localStorage.getItem(rr);if(L){const w=parseInt(L,10);if(!isNaN(w)&&w>=or)return Math.min(w,window.innerWidth-60)}return Vu}),[g,y]=a.useState(!1),f=a.useRef(null),[x,z]=a.useState(()=>zn("text").modelId),[N,O]=a.useState(()=>{const L=zn("text");return ht(L.profileId,L.modelId)}),[T,I]=a.useState(new Map),v=a.useRef(null),[S,C]=a.useState(null),{executeRetry:R,selectedContent:U,setIsDrawerOpen:P,setDrawerWidth:J}=Wa();a.useEffect(()=>{P(r)},[r,P]),a.useEffect(()=>{J(p)},[p,J]);const ee=it.useRef(null),X=it.useRef(null),{appState:Q,setAppState:B}=Ha();a.useEffect(()=>{if(!g)return;const L=V=>{const b=window.innerWidth-V.clientX,D=Math.max(or,Math.min(b,window.innerWidth-60));h(D)},w=()=>{y(!1),localStorage.setItem(rr,String(p))};return document.addEventListener("mousemove",L),document.addEventListener("mouseup",w),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",w),document.body.style.userSelect="",document.body.style.cursor=""}},[g,p]),a.useEffect(()=>{const L=()=>{const w=window.innerWidth-60;p>w&&h(w)};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[p]);const _=a.useCallback(L=>{L.preventDefault(),y(!0)},[]),E=a.useCallback(async(L,w,V,b)=>{var G,Y;const W={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(G=L[0])!=null&&G.name.includes("video")?"video":(Y=L[0])!=null&&Y.name.includes("audio")?"audio":"image",prompt:b||"",aiAnalysis:b,count:L.length,steps:L.map((le,_e)=>({id:`step-${_e}`,mcp:le.name,status:"pending",description:Hu(le.name,le.arguments),args:le.arguments}))};I(le=>{const _e=new Map(le);return _e.set(w,W),_e}),v.current=w,Se.updateMessage(w,{workflow:W});try{const le=await V();ye.track("chat_tool_execution_complete",{success:!0,resultCount:le.length}),ye.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:L.length,resultCount:le.length}),I(_e=>{const k=new Map(_e),H=k.get(w);if(H){const F={...H,steps:H.steps.map((Z,oe)=>{const te=le[oe];return{...Z,status:te!=null&&te.success?"completed":"failed",error:te==null?void 0:te.error,result:te==null?void 0:te.data}})};k.set(w,F),Se.updateMessage(w,{workflow:F,status:st.SUCCESS})}return k})}catch(le){console.error("[ChatDrawer] Tool execution failed:",le),I(_e=>{const k=new Map(_e),H=k.get(w);if(H){const F={...H,steps:H.steps.map(Z=>({...Z,status:"failed",error:le.message||"执行失败"}))};k.set(w,F),Se.updateMessage(w,{workflow:F,status:st.FAILED})}return k})}},[]),M=Uu({sessionId:l,temporaryModel:N||x,onToolCalls:E}),$=a.useRef(M.sendMessage);$.current=M.sendMessage,a.useEffect(()=>{(async()=>{const w=Se.getDrawerState(),V=await Se.getAllSessions();c(V);let b=null;if(w.activeSessionId?(b=w.activeSessionId,m(w.activeSessionId)):V.length>0&&(b=V[0].id,m(V[0].id)),b)try{const D=await Se.getMessages(b),W=new Map;for(const Y of D)Y.workflow&&W.set(Y.id,Y.workflow);I(W);const G=D.find(Y=>Y.workflow&&Y.status===st.STREAMING);v.current=(G==null?void 0:G.id)||null}catch(D){console.error("[ChatDrawer] Failed to load workflow messages:",D)}})()},[]),a.useEffect(()=>{Se.setDrawerState({isOpen:r,activeSessionId:l})},[r,l]),a.useEffect(()=>{if(l&&pe.current){const L=pe.current;pe.current=null,setTimeout(()=>{$.current(L)},100)}},[l]),a.useEffect(()=>{if(!Q.openSettings&&pe.current){const L=at.get();if(L!=null&&L.apiKey){const w=pe.current;pe.current=null,l?setTimeout(()=>{$.current(w)},100):(async()=>{const V=await Se.createSession();c(b=>[V,...b]),m(V.id),pe.current=w})()}}},[Q.openSettings,l]),a.useEffect(()=>{const L=w=>{w.key==="Escape"&&r&&(i(!1),e==null||e(!1))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,e]),a.useEffect(()=>{let L=null;return(async()=>{const{workflowSubmissionService:V}=await dt(async()=>{const{workflowSubmissionService:b}=await import("./workflow-submission-service-Dk47OkGu.js").then(D=>D.a);return{workflowSubmissionService:b}},__vite__mapDeps([0,2]),import.meta.url);L=V.subscribeToAllEvents(b=>{const D=b;I(W=>{let G=null;for(const[k,H]of W.entries())if(H.id===D.workflowId){G=k;break}if(!G)return W;const Y=W.get(G);if(!Y)return W;const le=new Map(W);let _e;switch(D.type){case"step":{_e={...Y,steps:Y.steps.map(k=>k.id===D.stepId?{...k,status:D.status||k.status,result:D.result??k.result,error:D.error??k.error}:k)};break}case"steps_added":{const H=(D.steps||[]).map(F=>({id:F.id,mcp:F.mcp,args:F.args,description:F.description,status:F.status}));_e={...Y,steps:[...Y.steps,...H]};break}case"completed":case"failed":{const k=D.type==="completed"?"completed":"failed";_e={...Y,status:k,steps:Y.steps.map(H=>{if(H.status==="running"||H.status==="pending"){const F=H.result;return F!=null&&F.taskId?H:{...H,status:k,error:D.type==="failed"?D.error:void 0}}return H})};break}default:return W}return le.set(G,_e),Se.updateMessage(G,{workflow:_e}),le})})})().catch(V=>{console.error("[ChatDrawer] Failed to setup workflow sync:",V)}),()=>{L==null||L.unsubscribe()}},[]),a.useEffect(()=>{if(!u)return;const L=V=>{const b=V.target;b.closest(".t-dialog")===null&&ee.current&&!ee.current.contains(b)&&X.current&&!X.current.contains(b)&&d(!1)},w=setTimeout(()=>{document.addEventListener("mousedown",L)},100);return()=>{clearTimeout(w),document.removeEventListener("mousedown",L)}},[u]);const re=a.useCallback(()=>{i(L=>{const w=!L;return e==null||e(w),w})},[e]),fe=a.useCallback(()=>{i(!1),e==null||e(!1)},[e]),K=a.useCallback(async()=>{ye.track("chat_session_create");const L=await Se.createSession();c(w=>[L,...w]),m(L.id),d(!1),I(new Map),v.current=null,z(void 0)},[]),de=a.useCallback(()=>{d(L=>!L)},[]),ie=a.useCallback(async L=>{ye.track("chat_session_select"),m(L),d(!1),z(void 0);try{const w=await Se.getMessages(L),V=new Map;for(const D of w)D.workflow&&V.set(D.id,D.workflow);I(V);const b=w.find(D=>D.workflow&&D.status===st.STREAMING);v.current=(b==null?void 0:b.id)||null}catch(w){console.error("[ChatDrawer] Failed to load workflow messages:",w),I(new Map),v.current=null}},[]),ue=a.useCallback(async L=>{ye.track("chat_session_delete"),await Se.deleteSession(L),c(w=>{const V=w.filter(b=>b.id!==L);if(l===L){const b=V[0]||null;m((b==null?void 0:b.id)||null)}return V})},[l]),xe=a.useCallback(async(L,w)=>{ye.track("chat_session_rename"),await Se.updateSession(L,{title:w}),c(V=>V.map(b=>b.id===L?{...b,title:w}:b))},[]),pe=it.useRef(null),ae=a.useCallback(async L=>{try{ye.track("chat_message_send",{hasImages:L.parts.some(V=>V.type==="image_url")}),ye.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:L.parts.some(V=>V.type==="image_url"),partCount:L.parts.length,textLength:L.parts.filter(V=>V.type==="text").reduce((V,b)=>V+String(b.text||"").length,0)});const w=at.get();if(!(w!=null&&w.apiKey)){pe.current=L,B({...Q,openSettings:!0});return}if(pe.current=null,!l){const V=await Se.createSession();c(b=>[V,...b]),m(V.id),pe.current=L;return}await M.sendMessage(L)}catch(w){console.error("[ChatDrawer] send message failed:",w),pe.current=L}},[l,M,Q,B]),q=a.useCallback(async L=>{var Ve;const{context:w,workflow:V,textModel:b,autoOpen:D=!0}=L;D&&(i(!0),e==null||e(!0)),b&&z(b);const W=await Se.createSession(),G=[];w.userInstruction&&G.push(w.userInstruction),w.selection.texts.length>0&&G.push(`
637
637
  📝 选中的文本:
638
638
  ${w.selection.texts.join(`
639
639
  `)}`),w.selection.texts.length===0&&!w.userInstruction&&w.finalPrompt&&G.push(`
@@ -641,10 +641,10 @@ ${w.selection.texts.join(`
641
641
  ${w.finalPrompt}`);const Y=[],le=w.model.isExplicit?`模型: ${w.model.id}`:`模型: ${w.model.id} (默认)`;Y.push(le),w.params.count>1&&Y.push(`数量: ${w.params.count}`),Y.length>0&&G.push(`
642
642
  ---
643
643
  ${Y.join(" • ")}`);const _e=G.join(`
644
- `);let k="新任务";if(w.finalPrompt)k=w.finalPrompt;else if(w.selection.texts.length>0)k=w.selection.texts[0];else if(w.userInstruction){const j=w.userInstruction.indexOf(":"),ne=w.userInstruction.indexOf(":"),we=j>=0&&ne>=0?Math.min(j,ne):Math.max(j,ne);we>=0&&we<w.userInstruction.length-1?k=w.userInstruction.substring(we+1).trim():k=w.userInstruction}else w.model.id&&(k=`模型: ${w.model.id}`);const H=k;await Se.updateSession(W.id,{title:H}),W.title=H,c(j=>[W,...j]),m(W.id);const F=Date.now(),Z=`msg_${F}_user`,oe=[{type:"text",text:_e}],te=[...w.selection.images,...w.selection.graphics];for(let j=0;j<te.length;j++)oe.push({type:"data-file",data:{filename:`image-${j+1}.png`,mediaType:"image/png",url:te[j]}});for(let j=0;j<w.selection.videos.length;j++)oe.push({type:"data-file",data:{filename:`video-${j+1}.mp4`,mediaType:"video/mp4",url:w.selection.videos[j]}});const Pe={id:Z,role:"user",parts:oe},Ce=`msg_${F}_workflow`,Ae={id:Ce,role:"assistant",parts:[{type:"text",text:`${nr}${Ce}`}]};I(j=>{const ne=new Map(j);return ne.set(Ce,V),ne}),b.current=Ce;const qe={id:Z,sessionId:W.id,role:ot.USER,content:_e,timestamp:Date.now(),status:st.SUCCESS,aiContext:w,attachments:te.length>0||w.selection.videos.length>0?[...te.map((j,ne)=>({id:`${Z}-img-${ne}`,name:`image-${ne+1}.png`,type:"image/png",size:0,data:j,isBlob:!1})),...w.selection.videos.map((j,ne)=>({id:`${Z}-vid-${ne}`,name:`video-${ne+1}.mp4`,type:"video/mp4",size:0,data:j,isBlob:!1}))]:void 0};await Se.addMessage(qe);const et={id:Ce,sessionId:W.id,role:ot.ASSISTANT,content:`${nr}${Ce}`,timestamp:Date.now(),status:st.STREAMING,workflow:V};await Se.addMessage(et),(Ve=M.setMessagesWithRaw)==null||Ve.call(M,[Pe,Ae],[qe,et])},[M,e]),ce=a.useCallback(async L=>{var V;let w=b.current;if(!w){for(const[v,D]of T.entries())if(D.id===L.id){w=v,b.current=v;break}}w&&(I(v=>{const D=new Map(v);return D.set(w,L),D}),Se.updateMessage(w,{workflow:L}),(V=M.updateRawMessageWorkflow)==null||V.call(M,w,L))},[l,o,M,T]),ve=a.useCallback(L=>{const w=b.current;w&&I(V=>{var W;const v=new Map(V),D=v.get(w);if(D){const G=D.logs||[],Y={...D,logs:[...G,L]};v.set(w,Y),Se.updateMessage(w,{workflow:Y}),(W=M.updateRawMessageWorkflow)==null||W.call(M,w,Y)}return v})},[M]),me=a.useRef(null),Re=a.useCallback(L=>{const w=b.current;w&&I(V=>{const v=new Map(V),D=v.get(w);if(D){const W=D.logs||[];let G=-1;for(let le=W.length-1;le>=0;le--)if(W[le].type==="thinking"){G=le;break}let Y;if(G>=0){const le=[...W],_e=le[G];le[G]={..._e,content:_e.content+L},Y={...D,logs:le}}else Y={...D,logs:[...W,{type:"thinking",timestamp:Date.now(),content:L}]};v.set(w,Y),me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{var le;Se.updateMessage(w,{workflow:Y}),(le=M.updateRawMessageWorkflow)==null||le.call(M,w,Y)},500)}return v})},[M]),Me=a.useCallback(async(L,w,V)=>{if(!S){ye.track("chat_workflow_retry",{stepIndex:V});try{C(L),b.current=L,await R(w,V)}finally{C(null)}}},[R,S]);a.useImperativeHandle(n,()=>({open:()=>{i(!0),e==null||e(!0)},close:()=>{i(!1),e==null||e(!1)},toggle:re,sendMessage:async L=>{i(!0),e==null||e(!0);const w={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:L}]};await ae(w)},sendWorkflowMessage:q,updateWorkflowMessage:ce,appendAgentLog:ve,updateThinkingContent:Re,isOpen:()=>r,retryWorkflowFromStep:async(L,w)=>{let V=null;for(const[v,D]of T.entries())if(D.id===L.id){V=v;break}V?await Me(V,L,w):console.warn("[ChatDrawer] Could not find message ID for workflow retry",L.id)}}),[r,re,ae,q,ce,ve,Re,e,T,Me]);const We=a.useMemo(()=>({...M,sendMessage:ae}),[M,ae]),Ee=o.find(L=>L.id===l),Te=(Ee==null?void 0:Ee.title)||"新对话",[Ye,$e]=a.useState(!1),[be,Ie]=a.useState(""),he=a.useRef(null),ze=a.useCallback(()=>{Ie(Te),$e(!0)},[Te]),De=a.useCallback(async()=>{const L=be.trim();L&&L!==Te&&l&&await xe(l,L),$e(!1)},[be,Te,l,xe]),He=a.useCallback(()=>{Ie(Te),$e(!1)},[Te]),Be=a.useCallback(L=>{L.key==="Enter"?(L.preventDefault(),De()):L.key==="Escape"&&(L.preventDefault(),He())},[De,He]);a.useEffect(()=>{Ye&&he.current&&(he.current.focus(),he.current.select())},[Ye]);const Ge=a.useRef(null);Bl(Ge,{enableCopy:!0,stopPropagation:!0});const[Qe,Ne]=a.useState(!1);return a.useEffect(()=>{r&&Ne(!0)},[r]),s.jsxs(s.Fragment,{children:[s.jsx(Do,{isOpen:r,onClick:re,drawerWidth:p}),s.jsxs("div",{className:`chat-drawer ${Ha} ${r?"chat-drawer--open":""} ${g?"chat-drawer--dragging":""}`,style:{width:p},"data-testid":"chat-drawer",children:[s.jsx("div",{ref:f,className:"chat-drawer__resize-handle",onMouseDown:_}),s.jsxs("div",{ref:Ge,className:"chat-drawer__body",children:[s.jsxs("div",{className:"chat-drawer__header",children:[s.jsxs("div",{className:"chat-drawer__header-top",children:[s.jsx(je,{content:"关闭",children:s.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:fe,"aria-label":"关闭对话",children:s.jsx(Vr,{size:16})})}),Ye?s.jsx("input",{ref:he,className:"chat-drawer__title-input",value:be,onChange:L=>Ie(L.target.value),onKeyDown:Be,onBlur:De,maxLength:50}):s.jsx(je,{content:"点击编辑标题",showArrow:!1,children:s.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:ze,children:Te})})]}),s.jsxs("div",{className:"chat-drawer__header-bottom",children:[s.jsx(Lo,{value:x,valueRef:N,onChange:(L,w)=>{z(L),O(w||ht(null,L))}}),s.jsxs("div",{className:"chat-drawer__session-actions",children:[s.jsx(je,{content:"会话列表",children:s.jsx("button",{ref:X,className:`chat-drawer__close-btn ${u?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:de,"aria-label":"会话列表",children:s.jsx(Va,{size:16})})}),s.jsx(je,{content:"新对话",children:s.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:K,"aria-label":"新对话",children:s.jsx(Wr,{size:16})})})]})]})]}),u&&s.jsx("div",{ref:ee,children:s.jsx(zo,{sessions:o,activeSessionId:l,onSelectSession:ie,onNewSession:K,onDeleteSession:ue,onRenameSession:xe})}),s.jsxs("div",{className:"chat-drawer__content",children:[Qe&&s.jsx(a.Suspense,{fallback:s.jsx("div",{className:"chat-loading chat-loading--full",children:s.jsx("div",{className:"chat-loading__spinner"})}),children:s.jsx(Uu,{handler:We,workflowMessages:T,retryingWorkflowId:S,handleWorkflowRetry:Me})}),s.jsx($o,{selectedContent:U,onSend:ae,placeholder:"支持连续对话"})]})]})]})]})});Ho.displayName="ChatDrawer";const wm=Object.freeze(Object.defineProperty({__proto__:null,ChatDrawer:Ho},Symbol.toStringTag,{value:"Module"})),Vu=a.lazy(()=>dt(()=>Promise.resolve().then(()=>nm),void 0,import.meta.url).then(t=>({default:t.MermaidRenderer}))),Bu={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},Gu={pending:"待执行",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"};function qu(t,e,n){if(e==="mermaid")return s.jsx(a.Suspense,{fallback:null,children:s.jsx(Vu,{code:t.trim(),className:"chat-markdown__mermaid"})},n)}function Ku(t){return s.jsx(Br,{markdown:t,className:"chat-markdown",renderCodeBlock:qu})}const Zu=({step:t,index:e,isCurrentStep:n})=>{const[r,i]=a.useState(!1),o=Bu[t.status],c=Gu[t.status],l=Object.keys(t.args).length>0,m=t.result!==void 0&&t.result!==null,u=l||m||!!t.error||t.duration!==void 0,d=h=>{if(!h)return null;const g={};for(const[y,f]of Object.entries(h))y==="context"?g[y]="[AgentExecutionContext]":typeof f=="string"&&f.length>200?g[y]=f.substring(0,200)+"...":g[y]=f;return g},p=a.useMemo(()=>l&&JSON.stringify(d(t.args),null,2)||"",[l,t.args]);return s.jsxs("div",{className:`workflow-bubble-step workflow-bubble-step--${t.status} ${n?"workflow-bubble-step--current":""}`,children:[s.jsxs("div",{className:"workflow-bubble-step__main",onClick:()=>u&&i(!r),style:{cursor:u?"pointer":"default"},children:[s.jsx("div",{className:"workflow-bubble-step__index",children:e+1}),s.jsx("div",{className:`workflow-bubble-step__status workflow-bubble-step__status--${t.status}`,children:t.status==="running"?s.jsx("span",{className:"workflow-bubble-step__spinner"}):o}),s.jsxs("div",{className:"workflow-bubble-step__content",children:[s.jsx("div",{className:"workflow-bubble-step__title",children:t.description}),s.jsx("div",{className:"workflow-bubble-step__status-text",children:c})]}),u&&s.jsx("div",{className:`workflow-bubble-step__expand ${r?"workflow-bubble-step__expand--open":""}`,children:"▼"})]}),r&&u&&s.jsxs("div",{className:"workflow-bubble-step__details",children:[s.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"工具:"}),s.jsx("code",{className:"workflow-bubble-step__tool",children:t.mcp})]}),l?s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"输入参数:"}),s.jsx("pre",{className:"workflow-bubble-step__args",children:p})]}):null,t.duration!==void 0&&s.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"耗时:"}),s.jsxs("span",{children:[t.duration,"ms"]})]}),m?s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"执行结果:"}),s.jsx("div",{className:"workflow-bubble-step__result",children:typeof t.result=="string"?t.result:String(JSON.stringify(t.result,null,2))})]}):null,t.error&&s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"错误信息:"}),s.jsx("div",{className:"workflow-bubble-step__error",children:t.error})]})]})]})},Yu=({log:t})=>{const[e,n]=a.useState(!1);if(t.type==="thinking"){const r=t.content,i=r.length>200,o=e?r:r.substring(0,200);return s.jsxs("div",{className:"agent-log agent-log--thinking",children:[s.jsxs("div",{className:"agent-log__header",children:[s.jsx("span",{className:"agent-log__icon",children:"💭"}),s.jsx("span",{className:"agent-log__title",children:"AI 分析"})]}),s.jsxs("div",{className:"agent-log__content",children:[s.jsxs("pre",{className:"agent-log__thinking-text",children:[o,i&&!e&&"..."]}),i&&s.jsx("button",{className:"agent-log__toggle",onClick:()=>n(!e),children:e?"收起":"展开全部"})]})]})}if(t.type==="tool_call")return s.jsxs("div",{className:"agent-log agent-log--tool-call",children:[s.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>n(!e),children:[s.jsx("span",{className:"agent-log__icon",children:"🔧"}),s.jsxs("span",{className:"agent-log__title",children:["调用工具: ",t.toolName]}),s.jsx("span",{className:`agent-log__expand ${e?"agent-log__expand--open":""}`,children:"▼"})]}),e&&s.jsx("div",{className:"agent-log__content",children:s.jsx("pre",{className:"agent-log__args",children:JSON.stringify(t.args,null,2)})})]});if(t.type==="tool_result"){const r=t.success?"success":"error",i=t.success?"✅":"❌",o=t.data!==void 0&&t.data!==null;return s.jsxs("div",{className:`agent-log agent-log--tool-result agent-log--${r}`,children:[s.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>n(!e),children:[s.jsx("span",{className:"agent-log__icon",children:i}),s.jsxs("span",{className:"agent-log__title",children:[t.toolName," ",t.success?"执行成功":"执行失败"]}),s.jsx("span",{className:`agent-log__expand ${e?"agent-log__expand--open":""}`,children:"▼"})]}),e&&s.jsxs("div",{className:"agent-log__content",children:[t.error&&s.jsx("div",{className:"agent-log__error",children:t.error}),o&&s.jsx("pre",{className:"agent-log__data",children:typeof t.data=="string"?t.data:String(JSON.stringify(t.data,null,2))})]})]})}return t.type==="retry"?s.jsx("div",{className:"agent-log agent-log--retry",children:s.jsxs("div",{className:"agent-log__header",children:[s.jsx("span",{className:"agent-log__icon",children:"🔄"}),s.jsxs("span",{className:"agent-log__title",children:["重试 #",t.attempt,": ",t.reason]})]})}):null},Xu=({workflow:t,className:e="",onRetry:n,isRetrying:r=!1})=>{const i=a.useMemo(()=>t.steps.map(I=>{const b=I.result,S=!!(b!=null&&b.taskId),C=I.result!==void 0&&I.result!==null,R=I.duration!==void 0;if((I.status==="running"||I.status==="pending")&&!S){if(I.error)return{...I,status:"failed"};if(C||R)return{...I,status:"completed"}}return I}),[t.steps]),o=a.useMemo(()=>t.generationType==="image"&&i.some(I=>I.mcp==="generate_image"||I.mcp==="generate_grid_image"||I.mcp==="generate_inspiration_board"),[t.generationType,i]),c=a.useMemo(()=>{const I=i,b=I.length,S=I.filter(P=>P.status==="completed").length,C=I.filter(P=>P.status==="failed").length,R=I.filter(P=>P.status==="running").length;let U="pending";if(C>0)U="failed";else if(S===b&&b>0)if(o){const P=t.postProcessingStatus;P==="completed"?U="completed":P==="failed"?U="failed":U="running"}else U="completed";else(R>0||S>0)&&(U="running");return{status:U,totalSteps:b,completedSteps:S}},[i,t.postProcessingStatus,o]),l=c.totalSteps>0?c.completedSteps/c.totalSteps*100:0,m=a.useMemo(()=>{const I={pending:"待开始",running:"执行中",completed:"已完成",failed:"执行失败"},b=i.every(S=>S.status==="completed");return b&&o&&t.postProcessingStatus==="processing"?"正在插入画布":b&&o&&!t.postProcessingStatus?"正在处理":I[c.status]},[c.status,i,t.postProcessingStatus,o]),u=c.status==="completed",d=c.status==="failed",p=c.status==="running",h=a.useMemo(()=>{var I,b,S;if(!u)return"";for(let C=i.length-1;C>=0;C-=1){const R=(I=i[C])==null?void 0:I.result;if(R){if(typeof R=="string"){const U=R.trim();if(U)return U;continue}if(typeof R=="object"&&R!==null){const U=R,P=((b=U.data)==null?void 0:b.content)||((S=U.data)==null?void 0:S.response)||U.content||U.response;if(typeof P=="string"){const J=P.trim();if(J)return J}}}}return t.aiAnalysis||""},[u,i,t.aiAnalysis]),g=a.useMemo(()=>{const I=["generate_image","generate_video","generate_grid_image","generate_inspiration_board","generate_long_video"];return i.some(b=>I.includes(b.mcp||""))},[i]),y=a.useMemo(()=>!u&&!d?null:d?{variant:"info",icon:"❌",text:"生成失败"}:h?{variant:"markdown",icon:"✨",markdown:h}:g?{variant:"info",icon:"✅",text:"已生成"}:{variant:"info",icon:"ℹ️",text:"未生成任何内容"},[u,d,h,g]),f=a.useMemo(()=>!y||y.variant!=="markdown"?null:y.markdown,[y]),x=a.useMemo(()=>i.findIndex(I=>I.status==="running"),[i]),z=a.useMemo(()=>i.findIndex(I=>I.status==="failed"),[i]);a.useRef(null);const N=a.useRef(null);a.useEffect(()=>{p&&requestAnimationFrame(()=>{N.current&&N.current.scrollIntoView({behavior:"smooth",block:"end"})})},[x,p,i.length]);const O=d&&t.retryContext&&z>=0,T=()=>{n&&z>=0&&n(z)};return s.jsxs("div",{ref:N,className:`workflow-bubble chat-message chat-message--assistant ${e}`,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:t.generationType==="image"?"🖼️":t.generationType==="video"?"🎬":t.generationType==="audio"?"🎵":"📝"})}),s.jsxs("div",{className:"workflow-bubble__content chat-message-content",children:[s.jsxs("div",{className:"workflow-bubble__header",children:[s.jsx("span",{className:"workflow-bubble__title",children:t.name}),s.jsxs("div",{className:"workflow-bubble__status-info",children:[s.jsx("span",{className:`workflow-bubble__status workflow-bubble__status--${c.status}`,children:m}),s.jsxs("span",{className:"workflow-bubble__progress-text",children:[c.completedSteps,"/",c.totalSteps]})]})]}),s.jsx("div",{className:"workflow-bubble__progress",children:s.jsx("div",{className:`workflow-bubble__progress-bar workflow-bubble__progress-bar--${c.status}`,style:{width:`${l}%`}})}),t.prompt&&s.jsxs("div",{className:"workflow-bubble__prompt",children:[s.jsx("span",{className:"workflow-bubble__label",children:"请求:"}),s.jsx("span",{className:"workflow-bubble__prompt-text",children:t.prompt.length>100?`${t.prompt.substring(0,100)}...`:t.prompt})]}),s.jsx("div",{className:"workflow-bubble__steps",children:i.map((I,b)=>s.jsx(Zu,{step:I,index:b,isCurrentStep:b===x&&p},I.id))}),t.logs&&t.logs.length>0&&s.jsxs("div",{className:"workflow-bubble__logs",children:[s.jsx("div",{className:"workflow-bubble__logs-header",children:s.jsx("span",{className:"workflow-bubble__logs-title",children:"执行详情"})}),s.jsx("div",{className:"workflow-bubble__logs-list",children:t.logs.map((I,b)=>s.jsx(Yu,{log:I},`log-${b}-${I.timestamp}`))})]}),y&&y.variant!=="markdown"&&s.jsxs("div",{className:`workflow-bubble__summary workflow-bubble__summary--${y.variant}`,children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:y.icon}),s.jsx("span",{children:y.text})]}),y&&y.variant==="markdown"&&f&&s.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--success workflow-bubble__summary--markdown",children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:y.icon}),s.jsx("div",{className:"workflow-bubble__summary-markdown",children:s.jsx("div",{className:"workflow-bubble__markdown-message",children:s.jsx("div",{className:"workflow-bubble__markdown-content",children:Ku(f)})})})]}),d&&s.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--error",children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:"❌"}),s.jsx("span",{children:"执行失败,请重试"}),O&&n&&s.jsx("button",{className:"workflow-bubble__retry-btn",onClick:T,disabled:r,children:r?"重试中...":"🔄 从失败步骤重试"})]})]})]})},Ju=({message:t,className:e=""})=>{const n=a.useRef(null),{text:r,meta:i,images:o}=a.useMemo(()=>{var y,f,x,z,N,O,T;let u="";const d=[];for(const I of t.parts)if(I.type==="text")u+=I.text;else if(I.type==="data-file"){const b=I.data;((y=b==null?void 0:b.mediaType)!=null&&y.startsWith("image/")||(f=b==null?void 0:b.url)!=null&&f.startsWith("data:image/"))&&d.push({url:b.url,filename:b.filename||"image"})}const p=t;if(p.aiContext){const I=p.aiContext,b=[];return(x=I.model)!=null&&x.id&&b.push({label:I.model.id,icon:s.jsx(In,{size:"12px"})}),((z=I.params)==null?void 0:z.count)>1&&b.push({label:`${I.params.count} 张`,icon:s.jsx(kn,{size:"12px"})}),(N=I.params)!=null&&N.size&&b.push({label:I.params.size,icon:s.jsx(Ns,{size:"12px"})}),((T=(O=I.selection)==null?void 0:O.texts)==null?void 0:T.length)>0&&b.push({label:`${I.selection.texts.length} 段文本`,icon:s.jsx(Es,{size:"12px"})}),{text:I.userInstruction||I.finalPrompt||u,meta:b,images:d}}let h=u;const g=[];if(h.includes(`
644
+ `);let k="新任务";if(w.finalPrompt)k=w.finalPrompt;else if(w.selection.texts.length>0)k=w.selection.texts[0];else if(w.userInstruction){const j=w.userInstruction.indexOf(":"),ne=w.userInstruction.indexOf(":"),we=j>=0&&ne>=0?Math.min(j,ne):Math.max(j,ne);we>=0&&we<w.userInstruction.length-1?k=w.userInstruction.substring(we+1).trim():k=w.userInstruction}else w.model.id&&(k=`模型: ${w.model.id}`);const H=k;await Se.updateSession(W.id,{title:H}),W.title=H,c(j=>[W,...j]),m(W.id);const F=Date.now(),Z=`msg_${F}_user`,oe=[{type:"text",text:_e}],te=[...w.selection.images,...w.selection.graphics];for(let j=0;j<te.length;j++)oe.push({type:"data-file",data:{filename:`image-${j+1}.png`,mediaType:"image/png",url:te[j]}});for(let j=0;j<w.selection.videos.length;j++)oe.push({type:"data-file",data:{filename:`video-${j+1}.mp4`,mediaType:"video/mp4",url:w.selection.videos[j]}});const Pe={id:Z,role:"user",parts:oe},Ce=`msg_${F}_workflow`,Ae={id:Ce,role:"assistant",parts:[{type:"text",text:`${sr}${Ce}`}]};I(j=>{const ne=new Map(j);return ne.set(Ce,V),ne}),v.current=Ce;const qe={id:Z,sessionId:W.id,role:ot.USER,content:_e,timestamp:Date.now(),status:st.SUCCESS,aiContext:w,attachments:te.length>0||w.selection.videos.length>0?[...te.map((j,ne)=>({id:`${Z}-img-${ne}`,name:`image-${ne+1}.png`,type:"image/png",size:0,data:j,isBlob:!1})),...w.selection.videos.map((j,ne)=>({id:`${Z}-vid-${ne}`,name:`video-${ne+1}.mp4`,type:"video/mp4",size:0,data:j,isBlob:!1}))]:void 0};await Se.addMessage(qe);const et={id:Ce,sessionId:W.id,role:ot.ASSISTANT,content:`${sr}${Ce}`,timestamp:Date.now(),status:st.STREAMING,workflow:V};await Se.addMessage(et),(Ve=M.setMessagesWithRaw)==null||Ve.call(M,[Pe,Ae],[qe,et])},[M,e]),ce=a.useCallback(async L=>{var V;let w=v.current;if(!w){for(const[b,D]of T.entries())if(D.id===L.id){w=b,v.current=b;break}}w&&(I(b=>{const D=new Map(b);return D.set(w,L),D}),Se.updateMessage(w,{workflow:L}),(V=M.updateRawMessageWorkflow)==null||V.call(M,w,L))},[l,o,M,T]),be=a.useCallback(L=>{const w=v.current;w&&I(V=>{var W;const b=new Map(V),D=b.get(w);if(D){const G=D.logs||[],Y={...D,logs:[...G,L]};b.set(w,Y),Se.updateMessage(w,{workflow:Y}),(W=M.updateRawMessageWorkflow)==null||W.call(M,w,Y)}return b})},[M]),me=a.useRef(null),Re=a.useCallback(L=>{const w=v.current;w&&I(V=>{const b=new Map(V),D=b.get(w);if(D){const W=D.logs||[];let G=-1;for(let le=W.length-1;le>=0;le--)if(W[le].type==="thinking"){G=le;break}let Y;if(G>=0){const le=[...W],_e=le[G];le[G]={..._e,content:_e.content+L},Y={...D,logs:le}}else Y={...D,logs:[...W,{type:"thinking",timestamp:Date.now(),content:L}]};b.set(w,Y),me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{var le;Se.updateMessage(w,{workflow:Y}),(le=M.updateRawMessageWorkflow)==null||le.call(M,w,Y)},500)}return b})},[M]),Me=a.useCallback(async(L,w,V)=>{if(!S){ye.track("chat_workflow_retry",{stepIndex:V});try{C(L),v.current=L,await R(w,V)}finally{C(null)}}},[R,S]);a.useImperativeHandle(n,()=>({open:()=>{i(!0),e==null||e(!0)},close:()=>{i(!1),e==null||e(!1)},toggle:re,sendMessage:async L=>{i(!0),e==null||e(!0);const w={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:L}]};await ae(w)},sendWorkflowMessage:q,updateWorkflowMessage:ce,appendAgentLog:be,updateThinkingContent:Re,isOpen:()=>r,retryWorkflowFromStep:async(L,w)=>{let V=null;for(const[b,D]of T.entries())if(D.id===L.id){V=b;break}V?await Me(V,L,w):console.warn("[ChatDrawer] Could not find message ID for workflow retry",L.id)}}),[r,re,ae,q,ce,be,Re,e,T,Me]);const We=a.useMemo(()=>({...M,sendMessage:ae}),[M,ae]),Ee=o.find(L=>L.id===l),Te=(Ee==null?void 0:Ee.title)||"新对话",[Ye,$e]=a.useState(!1),[ve,Ie]=a.useState(""),he=a.useRef(null),ze=a.useCallback(()=>{Ie(Te),$e(!0)},[Te]),De=a.useCallback(async()=>{const L=ve.trim();L&&L!==Te&&l&&await xe(l,L),$e(!1)},[ve,Te,l,xe]),He=a.useCallback(()=>{Ie(Te),$e(!1)},[Te]),Be=a.useCallback(L=>{L.key==="Enter"?(L.preventDefault(),De()):L.key==="Escape"&&(L.preventDefault(),He())},[De,He]);a.useEffect(()=>{Ye&&he.current&&(he.current.focus(),he.current.select())},[Ye]);const Ge=a.useRef(null);Gl(Ge,{enableCopy:!0,stopPropagation:!0});const[Qe,Ne]=a.useState(!1);return a.useEffect(()=>{r&&Ne(!0)},[r]),s.jsxs(s.Fragment,{children:[s.jsx(Lo,{isOpen:r,onClick:re,drawerWidth:p}),s.jsxs("div",{className:`chat-drawer ${Va} ${r?"chat-drawer--open":""} ${g?"chat-drawer--dragging":""}`,style:{width:p},"data-testid":"chat-drawer",children:[s.jsx("div",{ref:f,className:"chat-drawer__resize-handle",onMouseDown:_}),s.jsxs("div",{ref:Ge,className:"chat-drawer__body",children:[s.jsxs("div",{className:"chat-drawer__header",children:[s.jsxs("div",{className:"chat-drawer__header-top",children:[s.jsx(je,{content:"关闭",children:s.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:fe,"aria-label":"关闭对话",children:s.jsx(Br,{size:16})})}),Ye?s.jsx("input",{ref:he,className:"chat-drawer__title-input",value:ve,onChange:L=>Ie(L.target.value),onKeyDown:Be,onBlur:De,maxLength:50}):s.jsx(je,{content:"点击编辑标题",showArrow:!1,children:s.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:ze,children:Te})})]}),s.jsxs("div",{className:"chat-drawer__header-bottom",children:[s.jsx($o,{value:x,valueRef:N,onChange:(L,w)=>{z(L),O(w||ht(null,L))}}),s.jsxs("div",{className:"chat-drawer__session-actions",children:[s.jsx(je,{content:"会话列表",children:s.jsx("button",{ref:X,className:`chat-drawer__close-btn ${u?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:de,"aria-label":"会话列表",children:s.jsx(Ba,{size:16})})}),s.jsx(je,{content:"新对话",children:s.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:K,"aria-label":"新对话",children:s.jsx(Hr,{size:16})})})]})]})]}),u&&s.jsx("div",{ref:ee,children:s.jsx(Do,{sessions:o,activeSessionId:l,onSelectSession:ie,onNewSession:K,onDeleteSession:ue,onRenameSession:xe})}),s.jsxs("div",{className:"chat-drawer__content",children:[Qe&&s.jsx(a.Suspense,{fallback:s.jsx("div",{className:"chat-loading chat-loading--full",children:s.jsx("div",{className:"chat-loading__spinner"})}),children:s.jsx(Wu,{handler:We,workflowMessages:T,retryingWorkflowId:S,handleWorkflowRetry:Me})}),s.jsx(Oo,{selectedContent:U,onSend:ae,placeholder:"支持连续对话"})]})]})]})]})});Vo.displayName="ChatDrawer";const ym=Object.freeze(Object.defineProperty({__proto__:null,ChatDrawer:Vo},Symbol.toStringTag,{value:"Module"})),Bu=a.lazy(()=>dt(()=>Promise.resolve().then(()=>sm),void 0,import.meta.url).then(t=>({default:t.MermaidRenderer}))),Gu={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},qu={pending:"待执行",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"};function Ku(t,e,n){if(e==="mermaid")return s.jsx(a.Suspense,{fallback:null,children:s.jsx(Bu,{code:t.trim(),className:"chat-markdown__mermaid"})},n)}function Zu(t){return s.jsx(Gr,{markdown:t,className:"chat-markdown",renderCodeBlock:Ku})}const Yu=({step:t,index:e,isCurrentStep:n})=>{const[r,i]=a.useState(!1),o=Gu[t.status],c=qu[t.status],l=Object.keys(t.args).length>0,m=t.result!==void 0&&t.result!==null,u=l||m||!!t.error||t.duration!==void 0,d=h=>{if(!h)return null;const g={};for(const[y,f]of Object.entries(h))y==="context"?g[y]="[AgentExecutionContext]":typeof f=="string"&&f.length>200?g[y]=f.substring(0,200)+"...":g[y]=f;return g},p=a.useMemo(()=>l&&JSON.stringify(d(t.args),null,2)||"",[l,t.args]);return s.jsxs("div",{className:`workflow-bubble-step workflow-bubble-step--${t.status} ${n?"workflow-bubble-step--current":""}`,children:[s.jsxs("div",{className:"workflow-bubble-step__main",onClick:()=>u&&i(!r),style:{cursor:u?"pointer":"default"},children:[s.jsx("div",{className:"workflow-bubble-step__index",children:e+1}),s.jsx("div",{className:`workflow-bubble-step__status workflow-bubble-step__status--${t.status}`,children:t.status==="running"?s.jsx("span",{className:"workflow-bubble-step__spinner"}):o}),s.jsxs("div",{className:"workflow-bubble-step__content",children:[s.jsx("div",{className:"workflow-bubble-step__title",children:t.description}),s.jsx("div",{className:"workflow-bubble-step__status-text",children:c})]}),u&&s.jsx("div",{className:`workflow-bubble-step__expand ${r?"workflow-bubble-step__expand--open":""}`,children:"▼"})]}),r&&u&&s.jsxs("div",{className:"workflow-bubble-step__details",children:[s.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"工具:"}),s.jsx("code",{className:"workflow-bubble-step__tool",children:t.mcp})]}),l?s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"输入参数:"}),s.jsx("pre",{className:"workflow-bubble-step__args",children:p})]}):null,t.duration!==void 0&&s.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"耗时:"}),s.jsxs("span",{children:[t.duration,"ms"]})]}),m?s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"执行结果:"}),s.jsx("div",{className:"workflow-bubble-step__result",children:typeof t.result=="string"?t.result:String(JSON.stringify(t.result,null,2))})]}):null,t.error&&s.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[s.jsx("span",{className:"workflow-bubble-step__label",children:"错误信息:"}),s.jsx("div",{className:"workflow-bubble-step__error",children:t.error})]})]})]})},Xu=({log:t})=>{const[e,n]=a.useState(!1);if(t.type==="thinking"){const r=t.content,i=r.length>200,o=e?r:r.substring(0,200);return s.jsxs("div",{className:"agent-log agent-log--thinking",children:[s.jsxs("div",{className:"agent-log__header",children:[s.jsx("span",{className:"agent-log__icon",children:"💭"}),s.jsx("span",{className:"agent-log__title",children:"AI 分析"})]}),s.jsxs("div",{className:"agent-log__content",children:[s.jsxs("pre",{className:"agent-log__thinking-text",children:[o,i&&!e&&"..."]}),i&&s.jsx("button",{className:"agent-log__toggle",onClick:()=>n(!e),children:e?"收起":"展开全部"})]})]})}if(t.type==="tool_call")return s.jsxs("div",{className:"agent-log agent-log--tool-call",children:[s.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>n(!e),children:[s.jsx("span",{className:"agent-log__icon",children:"🔧"}),s.jsxs("span",{className:"agent-log__title",children:["调用工具: ",t.toolName]}),s.jsx("span",{className:`agent-log__expand ${e?"agent-log__expand--open":""}`,children:"▼"})]}),e&&s.jsx("div",{className:"agent-log__content",children:s.jsx("pre",{className:"agent-log__args",children:JSON.stringify(t.args,null,2)})})]});if(t.type==="tool_result"){const r=t.success?"success":"error",i=t.success?"✅":"❌",o=t.data!==void 0&&t.data!==null;return s.jsxs("div",{className:`agent-log agent-log--tool-result agent-log--${r}`,children:[s.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>n(!e),children:[s.jsx("span",{className:"agent-log__icon",children:i}),s.jsxs("span",{className:"agent-log__title",children:[t.toolName," ",t.success?"执行成功":"执行失败"]}),s.jsx("span",{className:`agent-log__expand ${e?"agent-log__expand--open":""}`,children:"▼"})]}),e&&s.jsxs("div",{className:"agent-log__content",children:[t.error&&s.jsx("div",{className:"agent-log__error",children:t.error}),o&&s.jsx("pre",{className:"agent-log__data",children:typeof t.data=="string"?t.data:String(JSON.stringify(t.data,null,2))})]})]})}return t.type==="retry"?s.jsx("div",{className:"agent-log agent-log--retry",children:s.jsxs("div",{className:"agent-log__header",children:[s.jsx("span",{className:"agent-log__icon",children:"🔄"}),s.jsxs("span",{className:"agent-log__title",children:["重试 #",t.attempt,": ",t.reason]})]})}):null},Ju=({workflow:t,className:e="",onRetry:n,isRetrying:r=!1})=>{const i=a.useMemo(()=>t.steps.map(I=>{const v=I.result,S=!!(v!=null&&v.taskId),C=I.result!==void 0&&I.result!==null,R=I.duration!==void 0;if((I.status==="running"||I.status==="pending")&&!S){if(I.error)return{...I,status:"failed"};if(C||R)return{...I,status:"completed"}}return I}),[t.steps]),o=a.useMemo(()=>t.generationType==="image"&&i.some(I=>I.mcp==="generate_image"||I.mcp==="generate_grid_image"||I.mcp==="generate_inspiration_board"),[t.generationType,i]),c=a.useMemo(()=>{const I=i,v=I.length,S=I.filter(P=>P.status==="completed").length,C=I.filter(P=>P.status==="failed").length,R=I.filter(P=>P.status==="running").length;let U="pending";if(C>0)U="failed";else if(S===v&&v>0)if(o){const P=t.postProcessingStatus;P==="completed"?U="completed":P==="failed"?U="failed":U="running"}else U="completed";else(R>0||S>0)&&(U="running");return{status:U,totalSteps:v,completedSteps:S}},[i,t.postProcessingStatus,o]),l=c.totalSteps>0?c.completedSteps/c.totalSteps*100:0,m=a.useMemo(()=>{const I={pending:"待开始",running:"执行中",completed:"已完成",failed:"执行失败"},v=i.every(S=>S.status==="completed");return v&&o&&t.postProcessingStatus==="processing"?"正在插入画布":v&&o&&!t.postProcessingStatus?"正在处理":I[c.status]},[c.status,i,t.postProcessingStatus,o]),u=c.status==="completed",d=c.status==="failed",p=c.status==="running",h=a.useMemo(()=>{var I,v,S;if(!u)return"";for(let C=i.length-1;C>=0;C-=1){const R=(I=i[C])==null?void 0:I.result;if(R){if(typeof R=="string"){const U=R.trim();if(U)return U;continue}if(typeof R=="object"&&R!==null){const U=R,P=((v=U.data)==null?void 0:v.content)||((S=U.data)==null?void 0:S.response)||U.content||U.response;if(typeof P=="string"){const J=P.trim();if(J)return J}}}}return t.aiAnalysis||""},[u,i,t.aiAnalysis]),g=a.useMemo(()=>{const I=["generate_image","generate_video","generate_grid_image","generate_inspiration_board","generate_long_video"];return i.some(v=>I.includes(v.mcp||""))},[i]),y=a.useMemo(()=>!u&&!d?null:d?{variant:"info",icon:"❌",text:"生成失败"}:h?{variant:"markdown",icon:"✨",markdown:h}:g?{variant:"info",icon:"✅",text:"已生成"}:{variant:"info",icon:"ℹ️",text:"未生成任何内容"},[u,d,h,g]),f=a.useMemo(()=>!y||y.variant!=="markdown"?null:y.markdown,[y]),x=a.useMemo(()=>i.findIndex(I=>I.status==="running"),[i]),z=a.useMemo(()=>i.findIndex(I=>I.status==="failed"),[i]);a.useRef(null);const N=a.useRef(null);a.useEffect(()=>{p&&requestAnimationFrame(()=>{N.current&&N.current.scrollIntoView({behavior:"smooth",block:"end"})})},[x,p,i.length]);const O=d&&t.retryContext&&z>=0,T=()=>{n&&z>=0&&n(z)};return s.jsxs("div",{ref:N,className:`workflow-bubble chat-message chat-message--assistant ${e}`,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:t.generationType==="image"?"🖼️":t.generationType==="video"?"🎬":t.generationType==="audio"?"🎵":"📝"})}),s.jsxs("div",{className:"workflow-bubble__content chat-message-content",children:[s.jsxs("div",{className:"workflow-bubble__header",children:[s.jsx("span",{className:"workflow-bubble__title",children:t.name}),s.jsxs("div",{className:"workflow-bubble__status-info",children:[s.jsx("span",{className:`workflow-bubble__status workflow-bubble__status--${c.status}`,children:m}),s.jsxs("span",{className:"workflow-bubble__progress-text",children:[c.completedSteps,"/",c.totalSteps]})]})]}),s.jsx("div",{className:"workflow-bubble__progress",children:s.jsx("div",{className:`workflow-bubble__progress-bar workflow-bubble__progress-bar--${c.status}`,style:{width:`${l}%`}})}),t.prompt&&s.jsxs("div",{className:"workflow-bubble__prompt",children:[s.jsx("span",{className:"workflow-bubble__label",children:"请求:"}),s.jsx("span",{className:"workflow-bubble__prompt-text",children:t.prompt.length>100?`${t.prompt.substring(0,100)}...`:t.prompt})]}),s.jsx("div",{className:"workflow-bubble__steps",children:i.map((I,v)=>s.jsx(Yu,{step:I,index:v,isCurrentStep:v===x&&p},I.id))}),t.logs&&t.logs.length>0&&s.jsxs("div",{className:"workflow-bubble__logs",children:[s.jsx("div",{className:"workflow-bubble__logs-header",children:s.jsx("span",{className:"workflow-bubble__logs-title",children:"执行详情"})}),s.jsx("div",{className:"workflow-bubble__logs-list",children:t.logs.map((I,v)=>s.jsx(Xu,{log:I},`log-${v}-${I.timestamp}`))})]}),y&&y.variant!=="markdown"&&s.jsxs("div",{className:`workflow-bubble__summary workflow-bubble__summary--${y.variant}`,children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:y.icon}),s.jsx("span",{children:y.text})]}),y&&y.variant==="markdown"&&f&&s.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--success workflow-bubble__summary--markdown",children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:y.icon}),s.jsx("div",{className:"workflow-bubble__summary-markdown",children:s.jsx("div",{className:"workflow-bubble__markdown-message",children:s.jsx("div",{className:"workflow-bubble__markdown-content",children:Zu(f)})})})]}),d&&s.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--error",children:[s.jsx("span",{className:"workflow-bubble__summary-icon",children:"❌"}),s.jsx("span",{children:"执行失败,请重试"}),O&&n&&s.jsx("button",{className:"workflow-bubble__retry-btn",onClick:T,disabled:r,children:r?"重试中...":"🔄 从失败步骤重试"})]})]})]})},Qu=({message:t,className:e=""})=>{const n=a.useRef(null),{text:r,meta:i,images:o}=a.useMemo(()=>{var y,f,x,z,N,O,T;let u="";const d=[];for(const I of t.parts)if(I.type==="text")u+=I.text;else if(I.type==="data-file"){const v=I.data;((y=v==null?void 0:v.mediaType)!=null&&y.startsWith("image/")||(f=v==null?void 0:v.url)!=null&&f.startsWith("data:image/"))&&d.push({url:v.url,filename:v.filename||"image"})}const p=t;if(p.aiContext){const I=p.aiContext,v=[];return(x=I.model)!=null&&x.id&&v.push({label:I.model.id,icon:s.jsx(In,{size:"12px"})}),((z=I.params)==null?void 0:z.count)>1&&v.push({label:`${I.params.count} 张`,icon:s.jsx(kn,{size:"12px"})}),(N=I.params)!=null&&N.size&&v.push({label:I.params.size,icon:s.jsx(Ns,{size:"12px"})}),((T=(O=I.selection)==null?void 0:O.texts)==null?void 0:T.length)>0&&v.push({label:`${I.selection.texts.length} 段文本`,icon:s.jsx(Es,{size:"12px"})}),{text:I.userInstruction||I.finalPrompt||u,meta:v,images:d}}let h=u;const g=[];if(h.includes(`
645
645
  ---
646
646
  `)){const I=h.split(`
647
647
  ---
648
648
  `);h=I[0],I[1].split(" • ").forEach(S=>{const C=S.replace(/模型:\s*/,"").replace(/数量:\s*/,"").replace(/尺寸:\s*/,"").trim();if(C){let R=s.jsx(In,{size:"12px"});S.includes("数量")&&(R=s.jsx(kn,{size:"12px"})),S.includes("尺寸")&&(R=s.jsx(Ns,{size:"12px"})),g.push({label:C,icon:R})}})}else{const I=h.split(`
649
- `),b=[];for(const S of I){const C=S.trim();if(C.startsWith("模型:")||C.startsWith("数量:")||C.startsWith("提示词:")){const R=C.replace(/.*:\s*/,"").trim();let U=s.jsx(In,{size:"12px"});C.includes("数量")&&(U=s.jsx(kn,{size:"12px"})),g.push({label:R,icon:U})}else C.startsWith("📝 选中的文本:")?g.push({label:C.replace("📝 ","").trim(),icon:s.jsx(Es,{size:"12px"})}):C&&!C.startsWith("💬 用户指令:")&&b.push(S)}h=b.join(`
650
- `).trim()}if(!h&&g.length>0){const I=u.match(/💬 用户指令:\s*([\s\S]*?)(?=\n模型:|\n数量:|$)/);I&&I[1].trim()&&(h=I[1].trim())}return{text:h||u,meta:g,images:d}},[t.parts,t.aiContext]),c=a.useCallback(u=>{u.stopPropagation()},[]),l=a.useCallback(u=>{if((u.ctrlKey||u.metaKey)&&u.key==="c"){const p=window.getSelection(),h=p==null?void 0:p.toString();h&&(Ar(h).catch(g=>{console.error("Failed to copy text:",g)}),u.stopPropagation())}},[]);a.useEffect(()=>{const u=n.current;if(u)return u.addEventListener("pointerdown",c),u.addEventListener("pointerup",c),u.addEventListener("mousedown",c),u.addEventListener("mouseup",c),u.addEventListener("click",c),u.addEventListener("keydown",l),()=>{u.removeEventListener("pointerdown",c),u.removeEventListener("pointerup",c),u.removeEventListener("mousedown",c),u.removeEventListener("mouseup",c),u.removeEventListener("click",c),u.removeEventListener("keydown",l)}},[c,l]);const m=o.length===0&&(!i||i.length===0);return s.jsxs("div",{className:`user-bubble chat-message chat-message--user ${m?"user-bubble--text-only":""} ${e}`,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:"👤"})}),s.jsxs("div",{className:"user-bubble__content chat-message-content",children:[o.length>0&&s.jsx("div",{className:`user-bubble__images user-bubble__images--${Math.min(o.length,4)}`,children:o.map((u,d)=>s.jsx("div",{className:"user-bubble__image-wrapper",children:s.jsx("img",{src:u.url,alt:u.filename,className:"user-bubble__image",loading:"lazy"})},d))}),r&&s.jsx("div",{ref:n,className:"user-bubble__text user-bubble__text--selectable",children:r}),i&&i.length>0&&s.jsx("div",{className:"user-bubble__meta-tags",children:i.map((u,d)=>s.jsxs("div",{className:"user-bubble__meta-tag",children:[s.jsx("span",{className:"user-bubble__meta-icon",children:u.icon}),s.jsx("span",{className:"user-bubble__meta-label",children:u.label})]},d))})]})]})},or="[[WORKFLOW_MESSAGE]]",ir=({handler:t,workflowMessages:e,retryingWorkflowId:n,handleWorkflowRetry:r,className:i="chat-section"})=>{const o=a.useCallback(d=>{const p=d.parts.find(h=>h.type==="text");if(p&&"text"in p){const h=p.text;if(h.startsWith(or))return h.replace(or,"")}return null},[]),c=a.useCallback(d=>d.parts.some(p=>p.type==="data-file"),[]),l=a.useCallback(d=>{let p=null,h=null;for(const g of d.parts)if(g.type==="text"){if(p===null){p=g.text;continue}h||(h=[p]),h.push(g.text)}return h?h.join(""):p??""},[]),m=t.status==="submitted"||t.status==="streaming",u=t.messages.length===0&&!m;return s.jsx("div",{className:i,children:s.jsx("div",{className:"chat-messages",children:s.jsxs("div",{className:"chat-messages-list",children:[t.messages.map((d,p)=>{const h=o(d);if(h){const f=e.get(h);if(f)return s.jsx(Xu,{workflow:f,onRetry:x=>r(h,f,x),isRetrying:n===h},d.id)}const g=d.parts.some(f=>f.type==="text"&&"text"in f&&typeof f.text=="string"&&f.text.startsWith("❌ 错误")),y=`chat-message chat-message--${d.role} ${g?"chat-message--error":""}`;return d.role==="user"&&c(d)?s.jsx(Ju,{message:d},d.id):s.jsxs("div",{className:y,"data-message-id":d.id,"data-message-last":p===t.messages.length-1,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:d.role==="user"?"👤":"🤖"})}),s.jsx("div",{className:"chat-message-content",children:s.jsx(Br,{markdown:l(d),className:"chat-markdown"})}),d.role==="assistant"&&!g&&s.jsx("div",{className:"chat-message-actions"})]},d.id)}),m&&s.jsxs("div",{className:"chat-loading",children:[s.jsx("div",{className:"chat-loading__spinner"}),s.jsx("span",{children:"思考中..."})]}),u&&s.jsxs("div",{className:"chat-empty",children:[s.jsx("h3",{children:"开始对话"}),s.jsx("p",{children:"输入消息与AI助手交流"})]})]})})})},Qu=Object.freeze(Object.defineProperty({__proto__:null,ChatMessagesArea:ir,default:ir},Symbol.toStringTag,{value:"Module"}));function em(t){let e=t;return e=e.replace(/\[([^\]]*[:\,\=\(\)\|\/\\][^\]]*)\]/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`["${r}"]`),e=e.replace(/\(([^\)]*[:\,\=\[\]\|\/\\][^\)]*)\)/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`("${r}")`),e=e.replace(/\{([^\}]*[:\,\=\[\]\(\)\|\/\\][^\}]*)\}/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`{"${r}"}`),e}const tm=({code:t,className:e=""})=>{const n=a.useRef(null),[r,i]=a.useState(null),[o,c]=a.useState(!0),[l,m]=a.useState(""),[u,d]=a.useState(!1),[p,h]=a.useState("");if(a.useEffect(()=>{let y=!1;return(async()=>{if(!(!n.current||!t))try{c(!0),i(null);const x=em(t);m(x);const z=(await dt(async()=>{const{default:T}=await import("./diagram-engines-CSzW_-6N.js").then(I=>I.b);return{default:T}},__vite__mapDeps([0]),import.meta.url)).default;z.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:"Inter, SF Pro Display, -apple-system, sans-serif"});const N=`mermaid-${Math.random().toString(36).substr(2,9)}`,{svg:O}=await z.render(N,x);!y&&n.current&&(n.current.innerHTML=O,h(O),c(!1))}catch(x){console.error("[MermaidRenderer] Failed to render:",x),y||(i(x.message||"Failed to render diagram"),c(!1))}})(),()=>{y=!0}},[t]),r){const y=l&&l!==t;return s.jsx("div",{className:`mermaid-renderer mermaid-renderer--error ${e}`,children:s.jsxs("div",{className:"mermaid-renderer__error",children:[s.jsx("strong",{children:"Mermaid渲染错误:"}),s.jsx("pre",{children:r}),s.jsxs("details",{children:[s.jsx("summary",{children:"查看原始代码"}),s.jsx("pre",{children:t})]}),y&&s.jsxs("details",{children:[s.jsx("summary",{children:"查看预处理后的代码(已自动添加引号)"}),s.jsx("pre",{children:l})]})]})})}const g=()=>{!o&&p&&d(!0)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`mermaid-renderer ${e}`,children:[o&&s.jsx("div",{className:"mermaid-renderer__loading",children:"渲染中..."}),s.jsx(je,{content:"点击查看大图",showArrow:!1,children:s.jsx("div",{ref:n,className:"mermaid-renderer__container",style:{display:o?"none":"block"},onClick:g})}),!o&&p&&s.jsxs("div",{className:"mermaid-renderer__hint",children:[s.jsx(Ba,{size:16}),s.jsx("span",{children:"点击查看大图"})]})]}),s.jsx(Ga,{visible:u,onClose:()=>d(!1),header:"Mermaid 图表",width:"90vw",className:"mermaid-preview-dialog",footer:null,closeBtn:s.jsx(Vr,{}),children:s.jsx("div",{className:"mermaid-preview-content",dangerouslySetInnerHTML:{__html:p}})})]})},nm=Object.freeze(Object.defineProperty({__proto__:null,MermaidRenderer:tm},Symbol.toStringTag,{value:"Module"}));export{fm as $,Ec as A,wt as B,Pc as C,_t as D,ro as E,Ac as F,$t as G,Al as H,to as I,zl as J,um as K,_o as L,mm as M,ru as N,Lo as O,sl as P,lm as Q,Cl as R,Hl as S,uu as T,mn as U,sc as V,$c as W,il as X,im as Y,pm as Z,hm as _,Os as a,gm as a0,wm as a1,El as b,Tl as c,Nl as d,Ll as e,vo as f,am as g,ac as h,mo as i,pn as j,Vs as k,Un as l,is as m,bl as n,bo as o,Bl as p,ls as q,dm as r,hu as s,om as t,Xa as u,Ml as v,vt as w,cd as x,lo as y,cm as z};
649
+ `),v=[];for(const S of I){const C=S.trim();if(C.startsWith("模型:")||C.startsWith("数量:")||C.startsWith("提示词:")){const R=C.replace(/.*:\s*/,"").trim();let U=s.jsx(In,{size:"12px"});C.includes("数量")&&(U=s.jsx(kn,{size:"12px"})),g.push({label:R,icon:U})}else C.startsWith("📝 选中的文本:")?g.push({label:C.replace("📝 ","").trim(),icon:s.jsx(Es,{size:"12px"})}):C&&!C.startsWith("💬 用户指令:")&&v.push(S)}h=v.join(`
650
+ `).trim()}if(!h&&g.length>0){const I=u.match(/💬 用户指令:\s*([\s\S]*?)(?=\n模型:|\n数量:|$)/);I&&I[1].trim()&&(h=I[1].trim())}return{text:h||u,meta:g,images:d}},[t.parts,t.aiContext]),c=a.useCallback(u=>{u.stopPropagation()},[]),l=a.useCallback(u=>{if((u.ctrlKey||u.metaKey)&&u.key==="c"){const p=window.getSelection(),h=p==null?void 0:p.toString();h&&(Rr(h).catch(g=>{console.error("Failed to copy text:",g)}),u.stopPropagation())}},[]);a.useEffect(()=>{const u=n.current;if(u)return u.addEventListener("pointerdown",c),u.addEventListener("pointerup",c),u.addEventListener("mousedown",c),u.addEventListener("mouseup",c),u.addEventListener("click",c),u.addEventListener("keydown",l),()=>{u.removeEventListener("pointerdown",c),u.removeEventListener("pointerup",c),u.removeEventListener("mousedown",c),u.removeEventListener("mouseup",c),u.removeEventListener("click",c),u.removeEventListener("keydown",l)}},[c,l]);const m=o.length===0&&(!i||i.length===0);return s.jsxs("div",{className:`user-bubble chat-message chat-message--user ${m?"user-bubble--text-only":""} ${e}`,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:"👤"})}),s.jsxs("div",{className:"user-bubble__content chat-message-content",children:[o.length>0&&s.jsx("div",{className:`user-bubble__images user-bubble__images--${Math.min(o.length,4)}`,children:o.map((u,d)=>s.jsx("div",{className:"user-bubble__image-wrapper",children:s.jsx("img",{src:u.url,alt:u.filename,className:"user-bubble__image",loading:"lazy"})},d))}),r&&s.jsx("div",{ref:n,className:"user-bubble__text user-bubble__text--selectable",children:r}),i&&i.length>0&&s.jsx("div",{className:"user-bubble__meta-tags",children:i.map((u,d)=>s.jsxs("div",{className:"user-bubble__meta-tag",children:[s.jsx("span",{className:"user-bubble__meta-icon",children:u.icon}),s.jsx("span",{className:"user-bubble__meta-label",children:u.label})]},d))})]})]})},ir="[[WORKFLOW_MESSAGE]]",ar=({handler:t,workflowMessages:e,retryingWorkflowId:n,handleWorkflowRetry:r,className:i="chat-section"})=>{const o=a.useCallback(d=>{const p=d.parts.find(h=>h.type==="text");if(p&&"text"in p){const h=p.text;if(h.startsWith(ir))return h.replace(ir,"")}return null},[]),c=a.useCallback(d=>d.parts.some(p=>p.type==="data-file"),[]),l=a.useCallback(d=>{let p=null,h=null;for(const g of d.parts)if(g.type==="text"){if(p===null){p=g.text;continue}h||(h=[p]),h.push(g.text)}return h?h.join(""):p??""},[]),m=t.status==="submitted"||t.status==="streaming",u=t.messages.length===0&&!m;return s.jsx("div",{className:i,children:s.jsx("div",{className:"chat-messages",children:s.jsxs("div",{className:"chat-messages-list",children:[t.messages.map((d,p)=>{const h=o(d);if(h){const f=e.get(h);if(f)return s.jsx(Ju,{workflow:f,onRetry:x=>r(h,f,x),isRetrying:n===h},d.id)}const g=d.parts.some(f=>f.type==="text"&&"text"in f&&typeof f.text=="string"&&f.text.startsWith("❌ 错误")),y=`chat-message chat-message--${d.role} ${g?"chat-message--error":""}`;return d.role==="user"&&c(d)?s.jsx(Qu,{message:d},d.id):s.jsxs("div",{className:y,"data-message-id":d.id,"data-message-last":p===t.messages.length-1,children:[s.jsx("div",{className:"chat-message-avatar",children:s.jsx("span",{children:d.role==="user"?"👤":"🤖"})}),s.jsx("div",{className:"chat-message-content",children:s.jsx(Gr,{markdown:l(d),className:"chat-markdown"})}),d.role==="assistant"&&!g&&s.jsx("div",{className:"chat-message-actions"})]},d.id)}),m&&s.jsxs("div",{className:"chat-loading",children:[s.jsx("div",{className:"chat-loading__spinner"}),s.jsx("span",{children:"思考中..."})]}),u&&s.jsxs("div",{className:"chat-empty",children:[s.jsx("h3",{children:"开始对话"}),s.jsx("p",{children:"输入消息与AI助手交流"})]})]})})})},em=Object.freeze(Object.defineProperty({__proto__:null,ChatMessagesArea:ar,default:ar},Symbol.toStringTag,{value:"Module"}));function tm(t){let e=t;return e=e.replace(/\[([^\]]*[:\,\=\(\)\|\/\\][^\]]*)\]/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`["${r}"]`),e=e.replace(/\(([^\)]*[:\,\=\[\]\|\/\\][^\)]*)\)/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`("${r}")`),e=e.replace(/\{([^\}]*[:\,\=\[\]\(\)\|\/\\][^\}]*)\}/g,(n,r)=>r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?n:`{"${r}"}`),e}const nm=({code:t,className:e=""})=>{const n=a.useRef(null),[r,i]=a.useState(null),[o,c]=a.useState(!0),[l,m]=a.useState(""),[u,d]=a.useState(!1),[p,h]=a.useState("");if(a.useEffect(()=>{let y=!1;return(async()=>{if(!(!n.current||!t))try{c(!0),i(null);const x=tm(t);m(x);const z=(await dt(async()=>{const{default:T}=await import("./diagram-engines-y0JSIEUO.js").then(I=>I.b);return{default:T}},__vite__mapDeps([0]),import.meta.url)).default;z.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:"Inter, SF Pro Display, -apple-system, sans-serif"});const N=`mermaid-${Math.random().toString(36).substr(2,9)}`,{svg:O}=await z.render(N,x);!y&&n.current&&(n.current.innerHTML=O,h(O),c(!1))}catch(x){console.error("[MermaidRenderer] Failed to render:",x),y||(i(x.message||"Failed to render diagram"),c(!1))}})(),()=>{y=!0}},[t]),r){const y=l&&l!==t;return s.jsx("div",{className:`mermaid-renderer mermaid-renderer--error ${e}`,children:s.jsxs("div",{className:"mermaid-renderer__error",children:[s.jsx("strong",{children:"Mermaid渲染错误:"}),s.jsx("pre",{children:r}),s.jsxs("details",{children:[s.jsx("summary",{children:"查看原始代码"}),s.jsx("pre",{children:t})]}),y&&s.jsxs("details",{children:[s.jsx("summary",{children:"查看预处理后的代码(已自动添加引号)"}),s.jsx("pre",{children:l})]})]})})}const g=()=>{!o&&p&&d(!0)};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`mermaid-renderer ${e}`,children:[o&&s.jsx("div",{className:"mermaid-renderer__loading",children:"渲染中..."}),s.jsx(je,{content:"点击查看大图",showArrow:!1,children:s.jsx("div",{ref:n,className:"mermaid-renderer__container",style:{display:o?"none":"block"},onClick:g})}),!o&&p&&s.jsxs("div",{className:"mermaid-renderer__hint",children:[s.jsx(Ga,{size:16}),s.jsx("span",{children:"点击查看大图"})]})]}),s.jsx(qa,{visible:u,onClose:()=>d(!1),header:"Mermaid 图表",width:"90vw",className:"mermaid-preview-dialog",footer:null,closeBtn:s.jsx(Br,{}),children:s.jsx("div",{className:"mermaid-preview-content",dangerouslySetInnerHTML:{__html:p}})})]})},sm=Object.freeze(Object.defineProperty({__proto__:null,MermaidRenderer:nm},Symbol.toStringTag,{value:"Module"}));export{gm as $,Pc as A,wt as B,Ac as C,_t as D,oo as E,Rc as F,$t as G,Rl as H,no as I,Dl as J,mm as K,vo as L,pm as M,ou as N,$o as O,rl as P,dm as Q,jl as R,Vl as S,mu as T,mn as U,rc as V,Oc as W,al as X,am as Y,hm as Z,fm as _,Os as a,wm as a0,ym as a1,Pl as b,Nl as c,El as d,$l as e,So as f,cm as g,cc as h,po as i,pn as j,Vs as k,Un as l,is as m,bl as n,bo as o,Gl as p,ls as q,um as r,fu as s,im as t,Ja as u,Cl as v,bt as w,ld as x,uo as y,lm as z};