aitu-app 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +3 -3
  2. package/assets/{CanvasAudioPlayer-CZVC9SHi.js → CanvasAudioPlayer-C_USx5uz.js} +1 -1
  3. package/assets/{ComicCreator-C7g-hysw.js → ComicCreator-qGQaXp7h.js} +2 -2
  4. package/assets/DeferredAIInputBar-CPykEFYX.css +1 -0
  5. package/assets/DeferredAIInputBar-LmZGQCLT.js +107 -0
  6. package/assets/{DrawnixDeferredFeatures-B2-HoTXj.js → DrawnixDeferredFeatures-Hy_-quZ1.js} +1 -1
  7. package/assets/{KnowledgeBaseContent-BeADhfA-.js → KnowledgeBaseContent-DSKNA70H.js} +8 -8
  8. package/assets/{MVCreator-CA2NyGKz.js → MVCreator-C3iClDLU.js} +12 -10
  9. package/assets/{ModelBenchmarkWorkbench-gOIZuctB.js → ModelBenchmarkWorkbench-BxwdcZ0q.js} +2 -2
  10. package/assets/{MusicAnalyzer-mzL-zDQJ.js → MusicAnalyzer-f_T6_YPJ.js} +2 -2
  11. package/assets/{ParametersDropdown-CBNxsp7u.js → ParametersDropdown-CTSN3ClD.js} +1 -1
  12. package/assets/{PromptHistoryTool-DNVmfpaU.js → PromptHistoryTool-DV-8RSdz.js} +2 -2
  13. package/assets/{ResizableDivider-C9gImQ7_.js → ResizableDivider-CUQBmPpx.js} +1 -1
  14. package/assets/TaskQueuePanel-CtjY1W4t.js +1 -0
  15. package/assets/{VideoAnalyzer-DOhiHjdh.js → VideoAnalyzer-BBVBSONO.js} +3 -3
  16. package/assets/{VideoAnalyzer-P9t7IwO6.js → VideoAnalyzer-BmAjGvN8.js} +1 -1
  17. package/assets/{ai-chat-CYiA-Evp.js → ai-chat-BO5vbKZW.js} +5 -5
  18. package/assets/{ai-generation-preferences-service-BMzL3ZwF.js → ai-generation-preferences-service-ZmPTR-wz.js} +1 -1
  19. package/assets/{batch-image-generation-Dv9sbP2v.js → batch-image-generation-BLBSv-t6.js} +6 -6
  20. package/assets/{diagram-engines-C-yGOIVo.js → diagram-engines-CSzW_-6N.js} +2 -2
  21. package/assets/{editor-engines-B_8hZKat.js → editor-engines-C573k8UM.js} +1 -1
  22. package/assets/{index-CuaA2bii.js → index-BT-rxxI3.js} +2 -2
  23. package/assets/{index-DzFw1iiN.js → index-Dw_8lcIi.js} +1 -1
  24. package/assets/{index-Dbf95aKy.js → index-IHNaVKGH.js} +1 -1
  25. package/assets/{index-DLKpn37B.js → index-N8asYyaz.js} +1 -1
  26. package/assets/{index-ykkRAoXJ.js → index-jxwTv7c1.js} +1 -1
  27. package/assets/{index.es-t_StdQ50.js → index.es-BLXvmueB.js} +1 -1
  28. package/assets/{jspdf.es.min-Bb5vk9Xd.js → jspdf.es.min-DxWvbkh4.js} +2 -2
  29. package/assets/{markdown-to-drawnix-DEQJGbGl.js → markdown-to-drawnix-BVFYnimo.js} +2 -2
  30. package/assets/{mermaid-to-drawnix-CYoVku-v.js → mermaid-to-drawnix-nGs2aeZ7.js} +2 -2
  31. package/assets/{model-benchmark-launcher-vAbuQ2bD.js → model-benchmark-launcher-DAWoSySc.js} +1 -1
  32. package/assets/{photo-wall-splitter-DcIZHaQr.js → photo-wall-splitter-CCUURzGk.js} +1 -1
  33. package/assets/{prompt-utils-D8o9xMD5.js → prompt-utils-MF_LILNU.js} +1 -1
  34. package/assets/{settings-dialog-CrPi8M4R.js → settings-dialog-Ac7R-_CG.js} +1 -1
  35. package/assets/{skill-dsl-parser-Bfrt9BEW.js → skill-dsl-parser-Do9iAYbB.js} +1 -1
  36. package/assets/{startup-app-BRF2LNMY.js → startup-app-eD_rQhSh.js} +531 -527
  37. package/assets/{task-sync-CywHcqN6.js → task-sync-BJVOunRa.js} +1 -1
  38. package/assets/{tool-windows-Bqfr0PWo.js → tool-windows-CmgL3thd.js} +17 -17
  39. package/assets/ttd-dialog-B12v0SVY.js +6 -0
  40. package/assets/{ttd-dialog-submit-shortcut-t5drrFnN.js → ttd-dialog-submit-shortcut-C2lJygXA.js} +1 -1
  41. package/assets/useCharacters-BAKE4TeJ.js +2 -0
  42. package/assets/{useMediaViewer-DZkKIvyf.js → useMediaViewer-BGw5RkSR.js} +1 -1
  43. package/assets/{useWorkflowSubmission-DEh5niqN.js → useWorkflowSubmission-iAPmKke9.js} +6 -6
  44. package/assets/{video-recovery-service-DOwO0Zzy.js → video-recovery-service-CW7bErP2.js} +1 -1
  45. package/assets/{workflow-generation-utils-1Imo8bgT.js → workflow-generation-utils-DhIVnOHO.js} +2 -2
  46. package/assets/{workflow-submission-service-sC9Y29-G.js → workflow-submission-service-Ce0cpj8E.js} +1 -1
  47. package/changelog.json +18 -13
  48. package/idle-prefetch-manifest.json +296 -296
  49. package/manifest.json +3 -3
  50. package/package.json +1 -1
  51. package/precache-manifest.json +6 -6
  52. package/sw.js +1 -1
  53. package/version.json +6 -3
  54. package/assets/DeferredAIInputBar-C0cG7P87.js +0 -107
  55. package/assets/DeferredAIInputBar-D_e6qG1y.css +0 -1
  56. package/assets/TaskQueuePanel-Y5iC1gTp.js +0 -1
  57. package/assets/ttd-dialog-C_7xm6Ln.js +0 -6
  58. package/assets/useCharacters-B0SpoLh6.js +0 -2
@@ -0,0 +1,107 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css"])))=>i.map(i=>d[i]);
2
+ import{au as Ho,ee as Bo,r as o,iz as ln,am as ze,iA as ms,f0 as fn,j as c,E as Xe,iB as Fr,bz as Fo,dB as Ht,bg as Gr,iC as Ur,iD as $r,b3 as Vr,n as Kr,e0 as oo,f_ as Yr,aR as Xr,iE as tt,iF as ls,aX as Un,bo as gs,bb as Bt,bn as Ft,bp as bt,aF as Bn,iG as xs,iH as Is,iI as et,iJ as _s,_ as bs,iK as ro,aK as vs,a0 as ks,cl as $n,de as Go,b9 as Uo,hf as Zr,dd as qr,v as Ss,l as Jr,iL as Qr,M as Ye,iM as ea,X as ta,a4 as na,c2 as sa,hD as oa,iN as ra,iO as ws,fB as Ms,az as aa,p as ia,iP as ca,iQ as la,iR as da,bq as Fn,iS as ys,y as $o,iT as ua,iU as pa,ec as fa,f$ as wt,ge as ds,al as vt,av as Ot,iV as ao,iW as io,iX as ha,g9 as Ge,fZ as us,bP as ma,iY as co,iZ as lo,i_ as En,aD as Gn,ef as uo,eg as ga,i$ as xa,j0 as wa,j1 as ya,j2 as Ia,j3 as po,hl as Vo,bw as ps,e1 as fo,j4 as _a,bQ as Ko,j5 as ho,b as mo,j6 as go,j7 as xo,aI as Lt,eu as ba,dk as va,aA as An,f6 as ka,w as Sa,eK as Ma,j8 as Ca,j9 as wo,ja as Ta,jb as Pa}from"./startup-app-eD_rQhSh.js";import{u as Ea,a as Aa,c as Dn,b as Wt,W as Da}from"./useWorkflowSubmission-iAPmKke9.js";import{_ as yo}from"./startup-runtime-DTmhLESk.js";import{P as Ra,c as Rn,G as Nn,b as Na,o as ja,i as jn,l as yt,p as za,q as Io,K as Oa,S as La,r as Wa,s as Ha,t as _o,v as bo,x as vo}from"./ai-chat-BO5vbKZW.js";import{c as Ba,q as Fa,M as Ga}from"./tool-windows-CmgL3thd.js";import{P as Ua}from"./ParametersDropdown-CTSN3ClD.js";import{u as $a,r as Va,g as Ka,a as Ya}from"./prompt-utils-MF_LILNU.js";import{s as ko}from"./workflow-submission-service-Ce0cpj8E.js";import{b as Xa}from"./mj-params-M-7csAp7.js";import{l as Za,a as zn,s as qa,b as Ja}from"./ai-generation-preferences-service-ZmPTR-wz.js";import"./skill-dsl-parser-Do9iAYbB.js";const Qa=({generationType:e,onSelectPrompt:t,language:n,extraActions:d,onBeforeOpenMyPrompts:r})=>{const{history:l,removeHistory:i,refreshHistory:h}=Ho({deduplicateWithPresets:!1,modelTypeFilter:e==="image"||e==="video"?void 0:e}),{imageHistory:p,videoHistory:m}=$a(),{confirm:f,confirmDialog:v}=Bo(),[b,y]=o.useState(!1),[,x]=o.useState(0),R=o.useRef(null),P=o.useRef(null),C=o.useRef(null),E=n==="zh"?"我的提示词":"My Prompts",A=e==="image"||e==="video"?Va({generationType:e,language:n,promptContents:Ka(e,n,e==="image"?p:m),imageHistory:p,videoHistory:m}):Ya({generationType:e,language:n,aiInputHistory:l,imageHistory:p,videoHistory:m});o.useEffect(()=>ln.subscribeChanges(()=>{h(),x(Z=>Z+1)}),[h]),o.useEffect(()=>()=>{P.current&&clearTimeout(P.current),C.current&&clearTimeout(C.current)},[]);const k=o.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null),P.current=setTimeout(()=>{h(),x(Z=>Z+1),b||ze.trackPromptAction({action:"open_panel",surface:"ai_input_prompt_popover",promptType:e,itemCount:A.length}),y(!0)},150)},[e,b,A.length,h]),L=o.useCallback(()=>{P.current&&(clearTimeout(P.current),P.current=null),C.current=setTimeout(()=>{y(!1)},200)},[]),H=o.useCallback(Z=>{t({content:Z.content,modelType:Z.modelType,scene:Z.scene}),y(!1)},[t]),Y=o.useCallback(async Z=>{const S=A.find(ae=>ae.id===Z);!S||!await f({title:n==="zh"?"确认删除提示词":"Delete Prompt",description:n==="zh"?"确定要删除这条提示词吗?此操作不可撤销。":"Are you sure you want to delete this prompt? This action cannot be undone.",confirmText:n==="zh"?"删除":"Delete",cancelText:n==="zh"?"取消":"Cancel",danger:!0})||(ln.deletePrompt(e,S.content),S.historyId&&e!=="image"&&e!=="video"?i(S.historyId):x(ae=>ae+1))},[f,e,n,A,i]),I=o.useCallback(Z=>{const S=A.find(N=>N.id===Z);S&&(ln.isPinned(e,S.content)?ln.unpinPrompt(e,S.content):ln.pinPrompt(e,S.content),x(N=>N+1))},[e,A]),X=o.useCallback(()=>{const Z=ms.find(ae=>ae.id==="prompt-history");if(!Z){ze.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"failed",metadata:{tool_id:"prompt-history",reason:"tool_not_found"}});return}r==null||r();const S=fn.getToolState("prompt-history");console.info("[PromptHistoryPopover] open my prompts",{generationType:e,beforeStatus:S==null?void 0:S.status,beforeInstanceId:S==null?void 0:S.instanceId,beforeIsLauncher:S==null?void 0:S.isLauncher,beforeIsPinned:S==null?void 0:S.isPinned}),ze.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"success",metadata:{tool_id:Z.id}}),y(!1),fn.openTool(Z,{componentProps:{initialCategory:e}});const N=fn.getToolState("prompt-history");console.info("[PromptHistoryPopover] requested my prompts open",{generationType:e,afterStatus:N==null?void 0:N.status,afterInstanceId:N==null?void 0:N.instanceId,afterIsLauncher:N==null?void 0:N.isLauncher,afterIsPinned:N==null?void 0:N.isPinned})},[e,r]);return c.jsxs("div",{ref:R,className:"prompt-history-popover",children:[c.jsxs("div",{className:"prompt-history-popover__actions",children:[c.jsx(Xe,{content:E,showArrow:!1,children:c.jsx("button",{className:"prompt-history-popover__trigger","data-track":"ai_input_click_history",onMouseEnter:k,onMouseLeave:L,children:c.jsx(Fr,{size:18})})}),d]}),b&&c.jsx("div",{className:"prompt-history-popover__panel-wrapper",onMouseEnter:k,onMouseLeave:L,children:c.jsx(Ra,{title:E,items:A,onSelect:H,onTogglePin:I,onDelete:Y,onTitleClick:X,language:n,showCount:!0,analyticsSurface:"ai_input_prompt_popover",analyticsPromptType:e})}),v]})};function ei(e){var t;return!!((t=e.params)!=null&&t.longVideoMeta)}function ti(e){var t;return((t=e.params)==null?void 0:t.longVideoMeta)||null}class Gt{constructor(){this.isInitialized=!1,this.batches=new Map,this.initTimestamp=0}static getInstance(){return Gt.instance||(Gt.instance=new Gt),Gt.instance}initialize(){this.isInitialized||(this.isInitialized=!0,this.initTimestamp=Date.now(),Fo.observeTaskUpdates().subscribe(t=>{if(t.type==="taskUpdated"&&t.task.status===Ht.COMPLETED&&t.task.type===Gr.VIDEO&&ei(t.task)){if((t.task.completedAt||0)<this.initTimestamp)return;this.handleSegmentCompleted(t.task).catch(d=>{console.error("[LongVideoChain] Error handling completed segment:",d)})}}))}async handleSegmentCompleted(t){var m;const n=ti(t);if(!n)return;const{segmentIndex:d,totalSegments:r,scripts:l,batchId:i}=n,h=(m=t.result)==null?void 0:m.url;let p=this.batches.get(i);if(p||(p={batchId:i,totalSegments:r,completedSegments:new Map,processedSegments:new Set,creatingNextFor:null,isMerging:!1,mergeCompleted:!1,scripts:l||[],characterReferenceUrls:n.characterReferenceUrls,characterDescription:n.characterDescription},this.batches.set(i,p)),!p.processedSegments.has(d)){if(p.processedSegments.add(d),h&&p.completedSegments.set(d,h),p.completedSegments.size===r){await this.mergeAndInsert(p);return}if(p.creatingNextFor!==d&&d<r){p.creatingNextFor=d;try{await this.createNextSegment(t,n,l,h,p.characterReferenceUrls,p.characterDescription)}finally{p.creatingNextFor=null}}}}async createNextSegment(t,n,d,r,l,i){const h=n.segmentIndex+1,p=d.find(v=>v.index===h);if(!p){console.error(`[LongVideoChain] Script not found for segment ${h}`);return}let m;if(r)try{m=(await Ur(r)).dataUrl}catch(v){console.error("[LongVideoChain] Failed to extract last frame:",v)}const f={...n,segmentIndex:h,needsLastFrame:h<n.totalSegments,characterReferenceUrls:l??n.characterReferenceUrls,characterDescription:i??n.characterDescription};Ba(p,f,m)}async mergeAndInsert(t){if(!(t.isMerging||t.mergeCompleted)){t.isMerging=!0;try{const n=[];for(let i=1;i<=t.totalSegments;i++){const h=t.completedSegments.get(i);h&&n.push(h)}if(n.length===0){console.error("[LongVideoChain] No video URLs to merge");return}const d=this.extractTransitions(t),l=await $r(n,(i,h,p)=>{const m=p||`${h} ${i.toFixed(1)}%`},{transitions:d,transitionDuration:.5});await this.insertMergedVideo(l.url),t.mergeCompleted=!0,this.cleanupBatch(t.batchId)}catch(n){console.error("[LongVideoChain] Merge failed:",n),this.cleanupBatch(t.batchId)}finally{t.isMerging=!1}}}async insertMergedVideo(t){try{await Fa("video",t)}catch(n){console.error("[LongVideoChain] Failed to insert video to canvas:",n)}}extractTransitions(t){return!t.scripts||t.scripts.length===0?[]:t.scripts.sort((n,d)=>n.index-d.index).slice(0,-1).map(n=>n.transition_hint||"cut")}cleanupBatch(t){const n=this.batches.get(t);n&&(n.completedSegments.clear(),n.processedSegments.clear(),this.batches.delete(t))}getBatchStatus(t){const n=this.batches.get(t);return n?{completed:n.completedSegments.size,total:n.totalSegments,isMerging:n.isMerging,mergeCompleted:n.mergeCompleted}:null}}const ni=Gt.getInstance();function si(){ni.initialize()}function So(){return`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function Mo(e){return new Promise((t,n)=>{const d=new Image,r=e.startsWith("http")&&!e.startsWith(location.origin);d.crossOrigin="anonymous",d.onload=()=>t(d),d.onerror=()=>{n(r?new Error("无法加载外部图片,可能是跨域 (CORS) 限制。请先下载图片到本地后再操作。"):new Error("图片加载失败,请检查图片是否有效"))},d.src=e})}function oi(e,t=.92){return e.toDataURL("image/jpeg",t)}class ri{async split(t,n){const{rows:d,cols:r}=n;if(d<1||r<1)throw new Error("Grid rows and cols must be at least 1");const l=await Mo(t),i=l.naturalWidth,h=l.naturalHeight,p=Math.floor(i/r),m=Math.floor(h/d),f=[];for(let v=0;v<d;v++)for(let b=0;b<r;b++){const y=v*r+b,x=b*p,R=v*m,P=document.createElement("canvas");P.width=p,P.height=m;const C=P.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(l,x,R,p,m,0,0,p,m);const E=oi(P);f.push({id:So(),imageData:E,originalIndex:y,width:p,height:m})}return f}async splitToBlob(t,n){const{rows:d,cols:r}=n;if(d<1||r<1)throw new Error("Grid rows and cols must be at least 1");const l=await Mo(t),i=l.naturalWidth,h=l.naturalHeight,p=Math.floor(i/r),m=Math.floor(h/d),f=[];for(let v=0;v<d;v++)for(let b=0;b<r;b++){const y=v*r+b,x=b*p,R=v*m,P=document.createElement("canvas");P.width=p,P.height=m;const C=P.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(l,x,R,p,m,0,0,p,m);const E=await new Promise((k,L)=>{P.toBlob(H=>{H?k(H):L(new Error("Failed to create blob"))},"image/png",.92)}),A=URL.createObjectURL(E);f.push({id:So(),imageData:A,originalIndex:y,width:p,height:m})}return f}revokeBlobUrls(t){for(const n of t)n.imageData.startsWith("blob:")&&URL.revokeObjectURL(n.imageData)}}const Co=new ri;function Ne(e,t){return Math.random()*(t-e)+e}function On(e){const t=[...e];for(let n=t.length-1;n>0;n--){const d=Math.floor(Math.random()*(n+1));[t[n],t[d]]=[t[d],t[n]]}return t}class ai{calculate(t,n,d,r){switch(n){case"scattered":return this.scatteredLayout(t,d,r);case"grid":return this.gridLayout(t,d);case"circular":return this.circularLayout(t,d,r);case"inspiration-board":return this.inspirationBoardLayout(t,d,r);default:return console.warn(`[LayoutEngine] Unknown layout style: ${n}, falling back to grid`),this.gridLayout(t,d)}}scatteredLayout(t,n,d){const{maxRotation:r=15,minScale:l=.85,maxScale:i=1.15,positionJitter:h=40}=d||{},{canvasWidth:p,canvasHeight:m,startX:f,startY:v,gap:b=20}=n,y=t.length,x=Math.ceil(Math.sqrt(y)),R=Math.ceil(y/x),P=Math.max(...t.map(I=>I.width)),C=Math.max(...t.map(I=>I.height)),E=p-b*2,A=m-b*2,k=E/x,L=A/R,H=Math.min((k-b)/P,(L-b)/C,1),Y=On(t.map((I,X)=>X));return t.map((I,X)=>{const Z=Math.floor(X/x),S=X%x,N=f+b+S*k+k/2,ae=v+b+Z*L+L/2,Q=Ne(-h,h),j=Ne(-h,h),we=Ne(-r,r),ie=Ne(l,i),Ie=H*ie,lt=I.width*Ie,St=I.height*Ie;return{...I,x:N+Q-lt/2,y:ae+j-St/2,rotation:we,scale:Ie,zIndex:Y[X]}})}gridLayout(t,n){const{canvasWidth:d,canvasHeight:r,startX:l,startY:i,gap:h=20}=n,p=t.length,m=Math.ceil(Math.sqrt(p)),f=Math.ceil(p/m),v=Math.max(...t.map(E=>E.width)),b=Math.max(...t.map(E=>E.height)),y=d-h*(m+1),x=r-h*(f+1),R=y/m,P=x/f,C=Math.min(R/v,P/b,1);return t.map((E,A)=>{const k=Math.floor(A/m),L=A%m,H=E.width*C,Y=E.height*C,I=l+h+L*(R+h),X=i+h+k*(P+h),Z=I+(R-H)/2,S=X+(P-Y)/2;return{...E,x:Z,y:S,rotation:0,scale:C,zIndex:A}})}circularLayout(t,n,d){const{centerIndex:r=-1,radius:l,startAngle:i=-90}=d||{},{canvasWidth:h,canvasHeight:p,startX:m,startY:f}=n,v=m+h/2,b=f+p/2,y=r>=0&&r<t.length?t.filter((S,N)=>N!==r):t,x=r>=0&&r<t.length?t[r]:null,R=Math.max(...t.map(S=>S.width)),P=Math.max(...t.map(S=>S.height)),C=Math.max(R,P),E=y.length,A=C*.8,k=E*C*1.2,L=Math.max(A,k/(2*Math.PI)),H=l||Math.min(L,Math.min(h,p)/2-C/2),Y=Math.min(h,p),I=Math.min(Y*.25/C,1),X=[];if(x){const S=x.width*I*1.2,N=x.height*I*1.2;X.push({...x,x:v-S/2,y:b-N/2,rotation:0,scale:I*1.2,zIndex:E})}const Z=360/E;return y.forEach((S,N)=>{const Q=(i+N*Z)*Math.PI/180,j=S.width*I,we=S.height*I,ie=v+H*Math.cos(Q)-j/2,Ie=b+H*Math.sin(Q)-we/2;X.push({...S,x:ie,y:Ie,rotation:0,scale:I,zIndex:N})}),X}inspirationBoardLayout(t,n,d){const{minWidthRatio:r=Rn.minWidthRatio,maxWidthRatio:l=Rn.maxWidthRatio,maxRotation:i=Rn.maxRotation,gap:h=Rn.gap}=d||{},{canvasWidth:p,canvasHeight:m,startX:f,startY:v}=n,b=t.length,y=this.assignSizeCategories(b),x=t.reduce((L,H)=>L+H.width,0)/b,R=t.reduce((L,H)=>L+H.height,0)/b,P=p||1200,C=m||600,E=Math.min(P*.25/x,C*.4/R,1),A=this.calculateInspirationBoardPositions(b,P,C,h),k=On(t.map((L,H)=>H));return t.map((L,H)=>{const Y=A[H],I=y[H];let X;switch(I){case"large":X=Ne(1.2,l);break;case"medium":X=Ne(.9,1.1);break;case"small":X=Ne(r,.85);break;default:X=1}const Z=E*X,S=Ne(-i,i),N=Ne(-20,20),ae=Ne(-15,15),Q=L.width*Z,j=L.height*Z;return{...L,x:f+Y.x+N-Q/2,y:v+Y.y+ae-j/2,rotation:S,scale:Z,zIndex:k[H]}})}assignSizeCategories(t){const n=[],d=Math.max(2,Math.floor(t*.25)),r=Math.max(2,Math.floor(t*.25)),l=t-d-r;for(let i=0;i<d;i++)n.push("large");for(let i=0;i<l;i++)n.push("medium");for(let i=0;i<r;i++)n.push("small");return On(n)}calculateInspirationBoardPositions(t,n,d,r){const l=[],i=Math.ceil(t/4),h=Math.ceil(t/i),p=(n-r*2)/h,m=(d-r*2)/i;for(let f=0;f<t;f++){const v=Math.floor(f/h),b=f%h,y=r+b*p+p/2,x=r+v*m+m/2,R=Ne(-p*.3,p*.3),P=Ne(-m*.2,m*.2);l.push({x:y+R,y:x+P})}return On(l)}calculateRequiredSize(t,n,d=.5){const r=t.length,l=Math.ceil(Math.sqrt(r)),i=Math.ceil(r/l),h=Math.max(...t.map(y=>y.width)),p=Math.max(...t.map(y=>y.height)),m=20,f=n==="scattered"?60:40,v=l*h*d+(l+1)*m+f*2,b=i*p*d+(i+1)*m+f*2;return{width:v,height:b}}}const To=new ai;class ii{constructor(){this.board=null}setBoard(t){this.board=t}getBoard(){return this.board}async generate(t){const{theme:n,gridConfig:d=Nn.gridConfig,layoutStyle:r=Nn.layoutStyle,imageSize:l=Nn.imageSize,imageQuality:i=Nn.imageQuality}=t;try{const h=this.buildPrompt(n,d),p=await Vr.generateImage(h,{size:l,quality:i,response_format:"url"});if(!p.data||p.data.length===0)throw new Error("AI 生成图片失败:未返回图片数据");const m=p.data[0].url||p.data[0].b64_json,f=m&&Kr(String(m));if(!f)throw new Error("AI 生成图片失败:未返回图片 URL");const v=await oo.getImageForAI(f),b=v.type==="base64"?v.value:f,y=await Co.split(b,d),x=this.calculateLayoutParams(y),R=To.calculate(y,r,x);return{success:!0,originalImageUrl:f,elements:R}}catch(h){return console.error("[GridImageService] Generation failed:",h),{success:!1,error:h.message||"宫格图生成失败"}}}async processExistingImage(t,n,d="scattered"){try{const r=await oo.getImageForAI(t),l=r.type==="base64"?r.value:t,i=await Co.split(l,n),h=this.calculateLayoutParams(i),p=To.calculate(i,d,h);return{success:!0,originalImageUrl:t,elements:p}}catch(r){return console.error("[GridImageService] Processing failed:",r),{success:!1,error:r.message||"宫格图处理失败"}}}async insertToBoard(t,n){if(!this.board)throw new Error("画板未初始化,请先调用 setBoard");let d=(n==null?void 0:n[0])??100,r=n==null?void 0:n[1];if(r===void 0){const i=Yr(this.board);r=(i==null?void 0:i[1])??100,d=(i==null?void 0:i[0])??d}const l=[...t].sort((i,h)=>i.zIndex-h.zIndex);for(const i of l){const h=d+i.x,p=r+i.y,m={url:i.imageData,width:i.width*i.scale,height:i.height*i.scale};Xr.insertImage(this.board,m,[h,p])}}async generateAndInsert(t,n){const d=await this.generate(t);return d.success&&d.elements&&await this.insertToBoard(d.elements,n),d}buildPrompt(t,n){const d=Na.zh;return d(t,n.rows,n.cols)}calculateLayoutParams(t){const n=t.reduce((y,x)=>y+x.width,0),d=t.reduce((y,x)=>y+x.height,0),r=t.length,l=Math.ceil(Math.sqrt(r)),i=Math.ceil(r/l),h=n/r,p=d/r,m=30,f=50,v=l*h+(l+1)*m+f*2,b=i*p+(i+1)*m+f*2;return{canvasWidth:v,canvasHeight:b,startX:0,startY:0,gap:m}}}const Po=new ii;function ci(e){return{cleanText:e,selectedAudioModel:null,selectedImageModel:null,selectedVideoModel:null,selectedParams:[],selectedCount:null}}function li(){const e=Un.get();return(e==null?void 0:e.imageModelName)||bt()}function di(){const e=Un.get();return(e==null?void 0:e.videoModelName)||Bt()}function ui(){const e=Un.get();return(e==null?void 0:e.audioModelName)||Ft()}function Eo(){const e=Un.get();return(e==null?void 0:e.textModelName)||gs()}function pi(e,t,n){if(t.length>0)return t.join(`
3
+ `);if(e){if(n===1)return"请仔细分析这张图片的内容、风格、构图、色调和艺术特点,推测生成这张图片可能使用的原始提示词,然后基于你推测的提示词重新生成一张全新的、风格相似但内容不完全相同的图片。不要直接复制原图。";if(n>1)return"请分析这些图片的主题、风格和视觉元素,找出它们之间的共同点或关联性,然后创造性地将它们融合成一张全新的、和谐统一的图片。融合时请保持各图片的精华元素,确保最终作品在构图、色调和风格上协调一致。"}return""}function dn(e){return e.replace(":","x").toLowerCase()}function fi(e,t,n){const d=t.texts.length>0||t.images.length>0||t.videos.length>0||t.graphics.length>0,r=t.texts,l=t.images.length+t.graphics.length,i=ci(e),h=i.cleanText.trim().length>0;let p=(n==null?void 0:n.generationType)||"image",m,f=!1;if(n!=null&&n.modelId){const k=tt(n.modelId);n.generationType||((k==null?void 0:k.type)==="video"?p="video":(k==null?void 0:k.type)==="audio"?p="audio":(k==null?void 0:k.type)==="text"?p="text":p="image"),m=n.modelId,f=!0}else i.selectedAudioModel?(p="audio",m=i.selectedAudioModel,f=!0):i.selectedVideoModel?(p="video",m=i.selectedVideoModel,f=!0):i.selectedImageModel?(p="image",m=i.selectedImageModel,f=!0):!d&&h&&!(n!=null&&n.generationType)?(p="agent",m=Eo()):p==="video"?m=di():p==="audio"?m=ui():p==="text"||p==="agent"?m=Eo():m=li();let v;(n==null?void 0:n.generationType)==="image"||(n==null?void 0:n.generationType)==="video"||(n==null?void 0:n.generationType)==="audio"||(n==null?void 0:n.generationType)==="text"?v="direct_generation":(n==null?void 0:n.generationType)==="agent"?v="agent_flow":v=h?"agent_flow":"direct_generation";const b=i.cleanText.trim(),y=r.join(`
4
+ `).trim();let x;if(y&&b?x=`${y}
5
+
6
+ ${b}`:b?x=b:y?x=y:d&&l>0?x=p==="text"?"":pi(d,[],l):x="",m.startsWith("mj")&&(n!=null&&n.params)){const k=Xa(n.params);k&&(x=[x,k].filter(Boolean).join(" "))}const R=(n==null?void 0:n.count)||i.selectedCount||1;let P,C,E;if(n!=null&&n.params){p!=="audio"&&p!=="text"&&p!=="agent"&&!m.startsWith("mj")&&n.params.size&&(P=dn(n.params.size)),n.params.duration&&(C=n.params.duration);const k={};for(const[L,H]of Object.entries(n.params))L!=="size"&&L!=="duration"&&H&&(k[L]=H);Object.keys(k).length>0&&(E=k)}if(!P&&(n!=null&&n.size)&&n.size!=="auto"&&(P=dn(n.size)),!P&&(n==null?void 0:n.size)!=="auto"){for(const k of i.selectedParams)if(k.id==="size"){P=dn(k.value);break}}if(!C){for(const k of i.selectedParams)if(k.id==="duration"){C=k.value;break}}if(!P&&(n==null?void 0:n.size)!=="auto"&&p!=="text"&&p!=="agent"&&p!=="audio"){const k=tt(m);if((k==null?void 0:k.type)==="image"&&k.imageDefaults)P="1x1";else if((k==null?void 0:k.type)==="video"&&k.videoDefaults){const L=ls(m,(n==null?void 0:n.modelRef)||m,n==null?void 0:n.params);P=dn(L.size||k.videoDefaults.size),C||(C=L.duration||k.videoDefaults.duration)}else if(p==="image")P="1x1";else if(p==="video"){const L=ls(m,(n==null?void 0:n.modelRef)||m,n==null?void 0:n.params);P=dn(L.size),C||(C=L.duration)}}!C&&p==="video"&&(C=ls(m,(n==null?void 0:n.modelRef)||m,n==null?void 0:n.params).duration);const A=i.cleanText.trim();return{scenario:v,generationType:p,modelId:m,modelRef:(n==null?void 0:n.modelRef)||null,defaultModels:n==null?void 0:n.defaultModels,defaultModelRefs:n==null?void 0:n.defaultModelRefs,isModelExplicit:f,prompt:x,userInstruction:A,rawInput:e,count:R,size:P,duration:C,extraParams:E,parseResult:i,hasExtraContent:h,selection:t,knowledgeContextRefs:n==null?void 0:n.knowledgeContextRefs}}const fs={id:et,name:"自动"},Ao=xs.map(e=>({id:e.id,name:e.name,isSystem:!0,mcpTool:e.mcpTool,outputType:e.outputType})),hi=({value:e,onSelect:t,onSelectSkill:n,onAddSkill:d,disabled:r=!1})=>{const[l,i]=o.useState(!1),[h,p]=o.useState([]),[m,f]=o.useState([]),[v,b]=o.useState(""),[y,x]=o.useState(0),R=o.useRef(null),P=o.useRef(null),C=o.useCallback(async()=>{try{const N=(await Bn.getAllDirectories()).find(we=>we.name==="Skill");if(!N)return;const ae=await Bn.getNoteMetasByDirectory(N.id),Q=new Set(xs.map(we=>we.id)),j=ae.filter(we=>!Q.has(we.id)).map(we=>{var ie;return{id:we.id,name:we.title,outputType:((ie=we.metadata)==null?void 0:ie.outputType)||void 0}});p(j)}catch{}},[]),E=o.useCallback(async()=>{try{const S=await Is.getAllExternalSkillsMeta(),N=new Set(xs.map(Q=>Q.id)),ae=S.filter(Q=>!N.has(Q.id)).map(Q=>({id:Q.id,name:Q.name,isExternal:!0,source:Q.source,outputType:Q.outputType}));f(ae)}catch{}},[]);o.useEffect(()=>{if(l){C(),E(),b("");const N=[fs,...Ao,...m,...h].findIndex(ae=>ae.id===e);x(N>=0?N:0),setTimeout(()=>{var ae;return(ae=P.current)==null?void 0:ae.focus()},50)}},[l,e]),o.useEffect(()=>{if(l&&R.current){const S=R.current.children[y];S&&S.scrollIntoView({block:"nearest"})}},[y,l]);const A=o.useCallback(S=>{S.preventDefault(),!r&&i(N=>!N)},[r]),k=o.useCallback(S=>{t(S.id),n==null||n(S),i(!1)},[t,n]),L=o.useCallback(S=>{S.stopPropagation(),i(!1),d()},[d]),H=[fs,...Ao,...m,...h],Y=v.trim()?H.filter(S=>S.name.toLowerCase().includes(v.toLowerCase())||S.id.toLowerCase().includes(v.toLowerCase())):H,I=H.length>15,X=o.useCallback(S=>S==="Escape"?(i(!1),!0):S==="ArrowDown"?(x(N=>N<Y.length-1?N+1:0),!0):S==="ArrowUp"?(x(N=>N>0?N-1:Y.length-1),!0):S==="Enter"||S===" "||S==="Tab"?(y<Y.length&&k(Y[y]),!0):!1,[y,Y,k]),Z=Y.find(S=>S.id===e)||fs;return c.jsx(_s,{isOpen:l,setIsOpen:i,disabled:r,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:X,children:({containerRef:S,menuRef:N,menuStyle:ae,handleTriggerKeyDown:Q})=>c.jsxs("div",{className:"skill-dropdown",ref:S,children:[c.jsx(Xe,{content:`Skill: ${Z.name}`,showArrow:!1,children:c.jsxs("button",{className:`skill-dropdown__trigger ${l?"skill-dropdown__trigger--open":""}`,onMouseDown:A,onKeyDown:Q,disabled:r,type:"button",children:[c.jsx("span",{className:"skill-dropdown__icon-prefix",children:c.jsx(ro,{size:14})}),c.jsx("span",{className:"skill-dropdown__label",children:Z.name}),c.jsx(vs,{size:14,className:`skill-dropdown__chevron ${l?"skill-dropdown__chevron--open":""}`})]})}),l&&bs.createPortal(c.jsxs("div",{ref:N,className:`skill-dropdown__menu ${$n}`,style:{...ae,zIndex:ks.DROPDOWN_PORTAL},onMouseDown:j=>j.stopPropagation(),onClick:j=>j.stopPropagation(),children:[c.jsxs("div",{className:"skill-dropdown__header",children:[c.jsx(ro,{size:14}),c.jsx("span",{children:"Skill"})]}),I&&c.jsx("div",{className:"skill-dropdown__search",children:c.jsx("input",{ref:P,type:"text",className:"skill-dropdown__search-input",placeholder:"搜索 Skill...",value:v,onChange:j=>{b(j.target.value),x(0)},onMouseDown:j=>j.stopPropagation(),onKeyDown:j=>j.stopPropagation()})}),c.jsx("div",{ref:R,className:"skill-dropdown__list",children:Y.map((j,we)=>{const ie=j.id===e,Ie=we===y;return c.jsxs("div",{className:`skill-dropdown__item ${ie?"skill-dropdown__item--selected":""} ${Ie?"skill-dropdown__item--highlighted":""}`,onClick:()=>k(j),onMouseEnter:()=>x(we),children:[c.jsx("span",{className:"skill-dropdown__item-label",children:j.name}),j.outputType==="image"&&c.jsx(Go,{size:12,className:"skill-dropdown__item-image-icon"}),j.outputType==="video"&&c.jsx(Uo,{size:12,className:"skill-dropdown__item-image-icon"}),j.outputType==="ppt"&&c.jsx(Zr,{size:12,className:"skill-dropdown__item-image-icon"}),j.outputType==="audio"&&c.jsx(qr,{size:12,className:"skill-dropdown__item-image-icon"}),j.isSystem&&c.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),j.isExternal&&c.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),ie&&c.jsx(Ss,{size:14,className:"skill-dropdown__item-check"})]},j.id)})}),c.jsx("div",{className:"skill-dropdown__divider"}),c.jsxs("div",{className:"skill-dropdown__add-btn",onClick:L,onMouseDown:j=>j.preventDefault(),children:[c.jsx(Jr,{size:14}),c.jsx("span",{children:"添加 Skill"})]})]}),document.body)]})})},Do=["image","video","audio"];function mi(e){if(e==="image"||e==="video"||e==="audio")return e}function It(e){if(!e)return[];const t=mi(e.outputType);if(t)return[t];if(e.outputType==="text")return[];const n=new Set,d=ja(e.mcpTool);d&&n.add(d);const r=[e.id,e.name,e.description,e.content].filter(Boolean).join(`
7
+ `);if(r)for(const l of Do)gi(l).some(h=>r.includes(h))&&n.add(l);return Do.filter(l=>n.has(l))}function gi(e){switch(e){case"image":return["generate_image","generate_grid_image","generate_photo_wall","generate_inspiration_board"];case"video":return["generate_video","generate_long_video"];case"audio":return["generate_audio"]}}var $e=(e=>(e.VIDEO="视频创作",e.IMAGE="图片生成",e.MINDMAP="思维导图",e.FLOWCHART="流程图",e.PPT="PPT大纲",e.GRID="宫格图",e.SVG="SVG矢量图",e))($e||{});const un=3,xi="data:image/svg+xml;utf8,"+encodeURIComponent(`
8
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 420">
9
+ <defs>
10
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
11
+ <stop offset="0" stop-color="#f8f4ff"/>
12
+ <stop offset="1" stop-color="#fff7ed"/>
13
+ </linearGradient>
14
+ <linearGradient id="accent" x1="0" y1="0" x2="1" y2="1">
15
+ <stop offset="0" stop-color="#a855f7"/>
16
+ <stop offset="1" stop-color="#f97316"/>
17
+ </linearGradient>
18
+ </defs>
19
+ <rect width="420" height="420" rx="34" fill="url(#bg)"/>
20
+ <rect x="38" y="46" width="344" height="316" rx="22" fill="#ffffff" opacity="0.95"/>
21
+ <g transform="translate(58 116)" stroke="#d8b4fe" stroke-width="3">
22
+ <rect width="86" height="72" rx="14" fill="#fff7ed"/>
23
+ <rect x="108" width="86" height="72" rx="14" fill="#f5f3ff"/>
24
+ <rect x="216" width="86" height="72" rx="14" fill="#fffbeb"/>
25
+ <rect y="92" width="86" height="72" rx="14" fill="#fef2f2"/>
26
+ <rect x="108" y="92" width="86" height="72" rx="14" fill="#eef2ff"/>
27
+ <rect x="216" y="92" width="86" height="72" rx="14" fill="#fff7ed"/>
28
+ <rect y="184" width="86" height="72" rx="14" fill="#f5f3ff"/>
29
+ <rect x="108" y="184" width="86" height="72" rx="14" fill="#fffbeb"/>
30
+ <rect x="216" y="184" width="86" height="72" rx="14" fill="#fef2f2"/>
31
+ </g>
32
+ <circle cx="101" cy="152" r="18" fill="#f97316"/>
33
+ <circle cx="209" cy="152" r="18" fill="#a855f7"/>
34
+ <circle cx="317" cy="152" r="18" fill="#f59e0b"/>
35
+ <circle cx="101" cy="244" r="18" fill="#ef4444"/>
36
+ <circle cx="209" cy="244" r="18" fill="#6366f1"/>
37
+ <circle cx="317" cy="244" r="18" fill="#fb923c"/>
38
+ <circle cx="101" cy="336" r="18" fill="#8b5cf6"/>
39
+ <circle cx="209" cy="336" r="18" fill="#eab308"/>
40
+ <circle cx="317" cy="336" r="18" fill="#f43f5e"/>
41
+ <path d="M356 78l8 10 12-20" fill="none" stroke="url(#accent)" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/>
42
+ </svg>`),wi="data:image/svg+xml;utf8,"+encodeURIComponent(`
43
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 420">
44
+ <defs>
45
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
46
+ <stop offset="0" stop-color="#eef5ff"/>
47
+ <stop offset="1" stop-color="#e7e2ff"/>
48
+ </linearGradient>
49
+ <linearGradient id="accent" x1="0" y1="0" x2="1" y2="1">
50
+ <stop offset="0" stop-color="#3b82f6"/>
51
+ <stop offset="1" stop-color="#8b5cf6"/>
52
+ </linearGradient>
53
+ </defs>
54
+ <rect width="420" height="420" rx="34" fill="url(#bg)"/>
55
+ <rect x="34" y="44" width="352" height="318" rx="22" fill="#ffffff" opacity="0.94"/>
56
+ <rect x="34" y="44" width="352" height="52" rx="22" fill="#e8edff"/>
57
+ <rect x="56" y="126" width="160" height="14" rx="7" fill="url(#accent)"/>
58
+ <rect x="56" y="164" width="274" height="12" rx="6" fill="#c7d2fe"/>
59
+ <rect x="56" y="192" width="220" height="12" rx="6" fill="#dbeafe"/>
60
+ <rect x="56" y="244" width="100" height="70" rx="12" fill="#eff6ff" stroke="#93c5fd"/>
61
+ <rect x="186" y="244" width="100" height="70" rx="12" fill="#f5f3ff" stroke="#a78bfa"/>
62
+ <rect x="316" y="244" width="52" height="70" rx="12" fill="#ecfeff" stroke="#67e8f9"/>
63
+ <circle cx="82" cy="279" r="14" fill="#3b82f6"/>
64
+ <circle cx="236" cy="279" r="14" fill="#8b5cf6"/>
65
+ <circle cx="342" cy="279" r="14" fill="#06b6d4"/>
66
+ <path d="M158 279h24M288 279h24" stroke="#94a3b8" stroke-width="8" stroke-linecap="round"/>
67
+ <rect x="56" y="334" width="312" height="10" rx="5" fill="#dbeafe"/>
68
+ </svg>`),yi="data:image/svg+xml;utf8,"+encodeURIComponent(`
69
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 420">
70
+ <defs>
71
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
72
+ <stop offset="0" stop-color="#f0fdf4"/>
73
+ <stop offset="1" stop-color="#ecfeff"/>
74
+ </linearGradient>
75
+ <linearGradient id="lineA" x1="0" y1="0" x2="1" y2="1">
76
+ <stop offset="0" stop-color="#22c55e"/>
77
+ <stop offset="1" stop-color="#06b6d4"/>
78
+ </linearGradient>
79
+ </defs>
80
+ <rect width="420" height="420" rx="34" fill="url(#bg)"/>
81
+ <rect x="34" y="48" width="352" height="312" rx="22" fill="#ffffff" opacity="0.94"/>
82
+ <g fill="none" stroke="url(#lineA)" stroke-width="3" stroke-linecap="round">
83
+ <path d="M210 210C170 190 150 156 126 128"/>
84
+ <path d="M210 210C170 220 144 252 116 286"/>
85
+ <path d="M210 210C250 184 278 150 312 128"/>
86
+ <path d="M210 210C252 224 280 254 322 292"/>
87
+ <path d="M126 128C108 116 94 110 78 104"/>
88
+ <path d="M312 128C332 116 346 110 362 104"/>
89
+ <path d="M116 286C98 300 82 310 66 324"/>
90
+ <path d="M322 292C342 302 356 312 372 326"/>
91
+ </g>
92
+ <rect x="168" y="178" width="84" height="64" rx="18" fill="#ecfdf5" stroke="#22c55e" stroke-width="3"/>
93
+ <circle cx="210" cy="210" r="16" fill="#22c55e"/>
94
+ <rect x="76" y="98" width="98" height="36" rx="13" fill="#f0fdf4" stroke="#86efac"/>
95
+ <rect x="72" y="270" width="102" height="36" rx="13" fill="#eff6ff" stroke="#93c5fd"/>
96
+ <rect x="262" y="98" width="102" height="36" rx="13" fill="#ecfeff" stroke="#67e8f9"/>
97
+ <rect x="266" y="276" width="108" height="36" rx="13" fill="#f0fdfa" stroke="#5eead4"/>
98
+ <circle cx="96" cy="116" r="7" fill="#22c55e"/>
99
+ <circle cx="96" cy="288" r="7" fill="#3b82f6"/>
100
+ <circle cx="286" cy="116" r="7" fill="#06b6d4"/>
101
+ <circle cx="290" cy="294" r="7" fill="#14b8a6"/>
102
+ <rect x="116" y="112" width="42" height="7" rx="3.5" fill="#bbf7d0"/>
103
+ <rect x="116" y="284" width="44" height="7" rx="3.5" fill="#bfdbfe"/>
104
+ <rect x="306" y="112" width="42" height="7" rx="3.5" fill="#a5f3fc"/>
105
+ <rect x="310" y="290" width="46" height="7" rx="3.5" fill="#99f6e4"/>
106
+ </svg>`),Ro=[{id:"grid-emoji",title:"智能拆分宫格图",description:"宫格图,风格统一",prompt:"生成16宫格猫咪表情包",category:$e.GRID,imageUrl:xi,badgeColor:"badge--grid",skillId:"generate_grid_image"},{id:"ppt-outline",title:"生成PPT大纲",description:"用参考图片规划配图与页面提示词",prompt:"生成一份关于「AI 创作工作流」的 PPT 大纲;如果已上传参考图片,请将参考图片作为配图和视觉风格参考。",category:$e.PPT,imageUrl:wi,badgeColor:"badge--ppt",skillId:"generate_ppt"},{id:"mindmap-project",title:"项目规划脑图",description:"快速生成结构化的思维导图,梳理项目计划",prompt:"创建一个关于「移动应用开发」的思维导图,包含需求分析、UI设计、前端开发、后端开发、测试上线等主要分支",category:$e.MINDMAP,imageUrl:yi,badgeColor:"badge--mindmap",skillId:"generate_mindmap"}],Yo={[$e.VIDEO]:{bg:"#fce7f3",text:"#be185d"},[$e.IMAGE]:{bg:"#dbeafe",text:"#1d4ed8"},[$e.MINDMAP]:{bg:"#dcfce7",text:"#15803d"},[$e.FLOWCHART]:{bg:"#fef3c7",text:"#b45309"},[$e.PPT]:{bg:"#dbeafe",text:"#1d4ed8"},[$e.GRID]:{bg:"#f3e8ff",text:"#7c3aed"},[$e.SVG]:{bg:"#e0e7ff",text:"#4338ca"}},Ii=({template:e,onClick:t})=>{const n=Yo[e.category],d=r=>{r.preventDefault()};return c.jsxs("div",{className:"inspiration-card",onMouseDown:d,onClick:t,"data-track":`inspiration_click_${e.id}`,children:[c.jsxs("div",{className:"inspiration-card__image-wrapper",children:[c.jsx("img",{src:e.imageUrl,alt:e.title,className:"inspiration-card__image",loading:"lazy"}),c.jsx("span",{className:"inspiration-card__badge",style:{backgroundColor:n.bg,color:n.text},children:e.category}),c.jsx("div",{className:"inspiration-card__hover-overlay",children:c.jsx("div",{className:"inspiration-card__arrow",children:c.jsx(Qr,{size:16})})})]}),c.jsxs("div",{className:"inspiration-card__content",children:[c.jsx("h3",{className:"inspiration-card__title",children:e.title}),c.jsx("p",{className:"inspiration-card__description",children:e.description})]})]})},No="aitu_hide_inspiration_board",_i=({isCanvasEmpty:e,onSelectPrompt:t,onOpenPromptTool:n,visible:d=!0,className:r=""})=>{const[l,i]=o.useState(0),[h,p]=o.useState(!1),[m,f]=o.useState("board"),[v,b]=o.useState(null);o.useEffect(()=>{localStorage.getItem(No)==="true"&&p(!0)},[]);const y=Math.ceil(Ro.length/un),x=y>1,R=Ro.slice(l*un,(l+1)*un),P=o.useCallback(I=>{I.preventDefault(),I.stopPropagation(),i(X=>(X-1+y)%y)},[y]),C=o.useCallback(I=>{I.preventDefault(),I.stopPropagation(),i(X=>(X+1)%y)},[y]),E=o.useCallback(I=>{b(I),f("guide"),t({prompt:I.prompt,modelType:"agent",skillId:I.skillId,templateId:I.id,title:I.title,category:I.category})},[t]),A=o.useCallback(I=>{I.preventDefault(),I.stopPropagation(),f("board")},[]),k=o.useCallback(I=>{I.preventDefault(),I.stopPropagation(),f("board"),b(null),p(!0),localStorage.setItem(No,"true")},[]),L=o.useCallback(I=>{I.preventDefault(),I.stopPropagation(),Ye.info("请点击右下角真正的发送按钮开始生成")},[]);if(!e||!d||h)return null;const H=m==="guide"&&v,Y=v?Yo[v.category]:null;return c.jsxs("div",{className:`inspiration-board ${H?"inspiration-board--guide":""} ${r}`,"data-testid":"inspiration-board",children:[c.jsxs("div",{className:"inspiration-board__header",children:[H?c.jsxs("div",{className:"inspiration-board__guide-title-group",children:[c.jsxs("button",{className:"inspiration-board__back-btn",onMouseDown:I=>I.preventDefault(),onClick:A,"aria-label":"返回灵感创意","data-testid":"inspiration-guide-back","data-track":"inspiration_click_guide_back",children:[c.jsx(ea,{size:15}),c.jsx("span",{children:"返回"})]}),c.jsx("h3",{className:"inspiration-board__title",children:"确认后发送"})]}):c.jsx("h3",{className:"inspiration-board__title",children:"灵感创意"}),c.jsx(Xe,{content:"不再提示",showArrow:!1,children:c.jsxs("button",{className:"inspiration-board__hide-btn",onClick:k,onMouseDown:I=>I.preventDefault(),"data-track":"inspiration_click_hide",children:[c.jsx(ta,{size:14}),c.jsx("span",{children:"不再提示"})]})}),!H&&n&&c.jsx(Xe,{content:"提示词工具",showArrow:!1,children:c.jsxs("button",{className:"inspiration-board__prompt-btn",onClick:n,onMouseDown:I=>I.preventDefault(),"data-track":"inspiration_click_prompt_tool",children:[c.jsx(na,{size:14}),c.jsx("span",{children:"提示词"})]})}),!H&&x&&c.jsxs("div",{className:"inspiration-board__pagination",children:[c.jsxs("span",{className:"inspiration-board__page-indicator",children:[l+1," / ",y]}),c.jsxs("div",{className:"inspiration-board__nav-buttons",children:[c.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:I=>I.preventDefault(),onClick:P,"aria-label":"上一页","data-track":"inspiration_click_prev",children:c.jsx(sa,{size:16})}),c.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:I=>I.preventDefault(),onClick:C,"aria-label":"下一页","data-track":"inspiration_click_next",children:c.jsx(oa,{size:16})})]})]})]}),H?c.jsx("div",{className:"inspiration-board__guide","data-testid":"inspiration-send-guide",children:c.jsxs("div",{className:"inspiration-board__guide-main",children:[c.jsxs("div",{className:"inspiration-board__guide-summary",children:[c.jsx("img",{src:v.imageUrl,alt:v.title,className:"inspiration-board__guide-image",loading:"lazy"}),c.jsxs("div",{className:"inspiration-board__guide-content",children:[Y&&c.jsx("span",{className:"inspiration-board__guide-badge",style:{backgroundColor:Y.bg,color:Y.text},children:v.category}),c.jsx("h4",{className:"inspiration-board__guide-name",children:v.title}),c.jsx("p",{className:"inspiration-board__guide-description",children:v.description})]})]}),c.jsxs("div",{className:"inspiration-board__guide-action",children:[c.jsxs("div",{className:"inspiration-board__guide-cue",children:[c.jsx(ra,{className:"inspiration-board__guide-pointer",size:26,"aria-hidden":"true"}),c.jsx(Xe,{content:"请点击右下角真正的发送按钮",showArrow:!1,children:c.jsx("button",{type:"button",className:"inspiration-board__guide-send-preview",onClick:L,onMouseDown:I=>I.preventDefault(),"aria-label":"示意发送按钮",children:c.jsx(ws,{size:17})})})]}),c.jsxs("div",{className:"inspiration-board__guide-tip",children:[c.jsx(ws,{size:16}),c.jsx("span",{children:"下一步:点击发送按钮开始生成"})]})]})]})}):c.jsxs("div",{className:"inspiration-board__grid",children:[R.map(I=>c.jsx(Ii,{template:I,onClick:()=>E(I)},I.id)),R.length<un&&Array.from({length:un-R.length}).map((I,X)=>c.jsx("div",{className:"inspiration-card inspiration-card--placeholder"},`placeholder-${X}`))]})]})},_t=[{value:"image",label:"图片",icon:c.jsx(Go,{size:14}),zh:"图片",en:"Image"},{value:"video",label:"视频",icon:c.jsx(Uo,{size:14}),zh:"视频",en:"Video"},{value:"audio",label:"音频",icon:c.jsx(ia,{size:14}),zh:"音频",en:"Audio"},{value:"text",label:"文本",icon:c.jsx(ca,{size:14}),zh:"文本",en:"Text"},{value:"agent",label:"Agent",icon:c.jsx(la,{size:14}),zh:"Agent",en:"Agent"}],bi=({value:e,onSelect:t,disabled:n=!1})=>{const[d,r]=o.useState(!1),{language:l}=Ms(),[i,h]=o.useState(0),p=o.useRef(null);o.useEffect(()=>{if(d){const y=_t.findIndex(x=>x.value===e);h(y>=0?y:0)}},[d,e]),o.useEffect(()=>{if(d&&p.current){const y=p.current.children[i];y&&y.scrollIntoView({block:"nearest"})}},[i,d]);const m=o.useCallback(y=>{y.preventDefault(),!n&&r(x=>!x)},[n]),f=o.useCallback(y=>{t(y),r(!1)},[t]),v=o.useCallback(y=>y==="Escape"?(r(!1),!0):y==="ArrowDown"?(h(x=>x<_t.length-1?x+1:0),!0):y==="ArrowUp"?(h(x=>x>0?x-1:_t.length-1),!0):y==="Enter"||y===" "||y==="Tab"?(f(_t[i].value),!0):!1,[i,f]),b=_t.find(y=>y.value===e)||_t[0];return c.jsx(_s,{isOpen:d,setIsOpen:r,disabled:n,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:v,children:({containerRef:y,menuRef:x,menuStyle:R,handleTriggerKeyDown:P})=>c.jsxs("div",{className:"generation-type-dropdown",ref:y,children:[c.jsx(Xe,{content:`${l==="zh"?"生成类型":"Type"}: ${l==="zh"?b.zh:b.en} (↑↓ Tab)`,showArrow:!1,children:c.jsxs("button",{className:`generation-type-dropdown__trigger ${d?"generation-type-dropdown__trigger--open":""}`,onMouseDown:m,onKeyDown:P,disabled:n,type:"button",children:[c.jsx("span",{className:"generation-type-dropdown__icon-prefix",children:b.icon}),c.jsx("span",{className:"generation-type-dropdown__label",children:l==="zh"?b.zh:b.en}),c.jsx(vs,{size:14,className:`generation-type-dropdown__chevron ${d?"generation-type-dropdown__chevron--open":""}`})]})}),d&&bs.createPortal(c.jsxs("div",{ref:x,className:`generation-type-dropdown__menu ${$n}`,style:{...R,zIndex:ks.DROPDOWN_PORTAL},onMouseDown:C=>C.stopPropagation(),onClick:C=>C.stopPropagation(),children:[c.jsxs("div",{className:"generation-type-dropdown__header",children:[c.jsx(aa,{size:14}),c.jsx("span",{children:l==="zh"?"生成类型 (↑↓ Tab)":"Generation type (↑↓ Tab)"})]}),c.jsx("div",{ref:p,className:"generation-type-dropdown__list",children:_t.map((C,E)=>{const A=C.value===e,k=E===i;return c.jsxs("div",{className:`generation-type-dropdown__item ${A?"generation-type-dropdown__item--selected":""} ${k?"generation-type-dropdown__item--highlighted":""}`,onClick:()=>f(C.value),onMouseEnter:()=>h(E),children:[c.jsx("span",{className:"generation-type-dropdown__item-icon",children:C.icon}),c.jsx("span",{className:"generation-type-dropdown__item-label",children:l==="zh"?C.zh:C.en}),A&&c.jsx(Ss,{size:14,className:"generation-type-dropdown__item-check"})]},C.value)})})]}),document.body)]})})},pn=[1,2,3,4,5,10,20],vi=({value:e,onSelect:t,disabled:n=!1,isOpen:d,onOpenChange:r})=>{const{value:l,setValue:i}=da({controlledValue:d,defaultValue:!1,onChange:r}),{language:h}=Ms(),[p,m]=o.useState(0),f=o.useRef(null);o.useEffect(()=>{if(l){const x=pn.indexOf(e);m(x>=0?x:0)}},[l,e]),o.useEffect(()=>{if(l&&f.current){const x=f.current.children[p];x&&x.scrollIntoView({block:"nearest"})}},[p,l]);const v=o.useCallback(x=>{x.preventDefault(),!n&&i(!l)},[n,l,i]),b=o.useCallback(x=>{t(x),i(!1)},[t]),y=o.useCallback(x=>x==="Escape"?(i(!1),!0):x==="ArrowDown"?(m(R=>R<pn.length-1?R+1:0),!0):x==="ArrowUp"?(m(R=>R>0?R-1:pn.length-1),!0):x==="Enter"||x===" "||x==="Tab"?(b(pn[p]),!0):!1,[p,b]);return c.jsx(_s,{isOpen:l,setIsOpen:i,disabled:n,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:y,children:({containerRef:x,menuRef:R,menuStyle:P,handleTriggerKeyDown:C})=>c.jsxs("div",{className:"count-dropdown",ref:x,children:[c.jsx(Xe,{content:`${h==="zh"?"生成数量":"Count"}: ${e} (↑↓ Tab)`,showArrow:!1,children:c.jsxs("button",{className:`count-dropdown__trigger ${l?"count-dropdown__trigger--open":""}`,onMouseDown:v,onKeyDown:C,disabled:n,type:"button",children:[c.jsxs("span",{className:"count-dropdown__label",children:[e,h==="zh"?"个":""]}),c.jsx(vs,{size:14,className:`count-dropdown__chevron ${l?"count-dropdown__chevron--open":""}`})]})}),l&&bs.createPortal(c.jsxs("div",{ref:R,className:`count-dropdown__menu ${$n}`,style:{...P,zIndex:ks.DROPDOWN_PORTAL},onMouseDown:E=>E.stopPropagation(),onClick:E=>E.stopPropagation(),children:[c.jsx("div",{className:"count-dropdown__header",children:c.jsx("span",{children:h==="zh"?"生成数量 (↑↓ Tab)":"Count (↑↓ Tab)"})}),c.jsx("div",{ref:f,className:"count-dropdown__list",children:pn.map((E,A)=>{const k=E===e,L=A===p;return c.jsxs("div",{className:`count-dropdown__item ${k?"count-dropdown__item--selected":""} ${L?"count-dropdown__item--highlighted":""}`,onClick:()=>b(E),onMouseEnter:()=>m(A),children:[c.jsxs("span",{className:"count-dropdown__item-label",children:[E,h==="zh"?"个":E>1?" items":" item"]}),k&&c.jsx(Ss,{size:14,className:"count-dropdown__item-check"})]},E)})})]}),document.body)]})})},Xo=["right","bottom","left","top"],Ln=4;function ki(e,t,n,d,r=32){const l=d<=2?d:d<=4?2:3,i=Math.floor(n/l),h=n%l;return[e[0]+h*(t.width+r),e[1]+i*(t.height+r)]}function Zo(e,t){const{ignoreElementIds:n=[],ignoreTypes:d=["workzone"],extraOccupiedRects:r=[]}=t;return[...e.children.filter(Si).filter(l=>!d.includes(l.type??"")&&!n.includes(l.id??"")).map(l=>({...Fn.getRectangleByPoints(l.points),id:l.id,type:l.type})),...r]}function Si(e){return typeof e=="object"&&e!==null&&Array.isArray(e.points)&&e.points.length===2}function qo(e,t,n){return e.x<t.x+t.width+n&&e.x+e.width+n>t.x&&e.y<t.y+t.height+n&&e.y+e.height+n>t.y}function Mi(e,t,n,d){const r=[e];for(let l=1;l<=d;l+=1)r.push([e[0]+t*l,e[1]],[e[0],e[1]+n*l],[e[0]+t*l,e[1]+n*l],[e[0]-t*l,e[1]],[e[0]-t*l,e[1]+n*l],[e[0],e[1]-n*l],[e[0]+t*l,e[1]-n*l],[e[0]-t*l,e[1]-n*l]);return r}function Ci(e,t,n,d,r){const l=Math.max(r,32),i=Math.max(Math.round(Math.min(t.width,t.height)*.16),28),h=Math.max(Math.round(Math.min(t.width,t.height)*.12),18),p=t.width+i,m=t.height+i,f=[];for(let v=0;v<n;v+=1){const b=Math.floor(v/Ln),y=v%Ln,x=Math.min(Ln,n-b*Ln),R=y-(x-1)/2,P=e.x+e.width/2-t.width/2,C=e.y+e.height/2-t.height/2,E=Math.abs(R)*h;let A=P,k=C;switch(d){case"right":A=e.x+e.width+l+b*p+E,k=C+R*(t.height+i);break;case"left":A=e.x-l-t.width-b*p-E,k=C+R*(t.height+i);break;case"top":A=P+R*(t.width+i),k=e.y-l-t.height-b*m-E;break;case"bottom":default:A=P+R*(t.width+i),k=e.y+e.height+l+b*m+E;break}f.push([Math.round(A),Math.round(k)])}return f}function jo(e,t,n,d,r){return e.reduce((i,h)=>{const p={x:h[0],y:h[1],width:t.width,height:t.height};return i+n.filter(m=>qo(p,m,d)).length},0)*1e3+Xo.indexOf(r)*10}function Ti(e,t,n,d,r){var m;const{gap:l=40,padding:i=16}=r,h=Zo(e,r),p=Xo.map(f=>({side:f,positions:Ci(t,n,d,f,l)}));return p.sort((f,v)=>jo(f.positions,n,h,i,f.side)-jo(v.positions,n,h,i,v.side)),((m=p[0])==null?void 0:m.positions)??[]}function Pi(e,t,n,d,r={}){const{frameRect:l,extraOccupiedRects:i=[],...h}=r,p={...h,extraOccupiedRects:i},m=l?Ti(e,l,n,d,p):Array.from({length:d},(v,b)=>ki(t,n,b,d,p.gap)),f=[...i];return m.map(v=>{const b=Ei(e,v,n,{...p,extraOccupiedRects:f});return f.push({x:b[0],y:b[1],width:n.width,height:n.height}),b})}function Ei(e,t,n,d={}){const{gap:r=40,padding:l=16,maxSearchRadius:i=6}=d,h=Zo(e,d),p=n.width+r,m=n.height+r,f=Mi(t,p,m,i);for(const v of f){const b={x:v[0],y:v[1],width:n.width,height:n.height};if(!h.some(x=>qo(b,x,l)))return v}return[t[0],t[1]+m*(i+1)]}function kt(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ai(e){return e==="image"||e==="video"||e==="audio"||e==="text"||e==="agent"}function Di(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.modelId=="string"&&t.modelId.trim().length>0&&(t.profileId===null||typeof t.profileId=="string")&&(t.providerIdHint===null||typeof t.providerIdHint=="string")&&(t.vendorHint===null||typeof t.vendorHint=="string")&&typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)}function Cs(){try{const e=window.localStorage.getItem(ys);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};return Object.entries(t).forEach(([d,r])=>{Ai(d)&&Di(r)&&(n[d]={modelId:r.modelId.trim(),profileId:kt(r.profileId),providerIdHint:kt(r.providerIdHint),vendorHint:kt(r.vendorHint),updatedAt:r.updatedAt})}),n}catch{return{}}}function Jo(e){try{if(!Object.values(e).some(Boolean)){window.localStorage.removeItem(ys);return}window.localStorage.setItem(ys,JSON.stringify(e))}catch{}}function Ri(e){const t=Cs();return t[e]?t[e]||null:e==="agent"&&t.text||null}function zo(e,t){var r;const n=kt(t.modelId);if(!n){Qo(e);return}const d=Cs();d[e]={modelId:n,profileId:kt((r=t.modelRef)==null?void 0:r.profileId),providerIdHint:kt(t.providerIdHint),vendorHint:kt(t.vendorHint),updatedAt:Date.now()},Jo(d)}function Qo(e){const t=Cs();t[e]&&(delete t[e],Jo(t))}function ct(e,t,n,d){var l;const r=e.metadata||{};return{id:e.id,name:e.name,generationType:e.generationType,prompt:r.prompt||((l=t==null?void 0:t.aiContext)==null?void 0:l.finalPrompt)||"",aiAnalysis:e.aiAnalysis,count:r.count,createdAt:e.createdAt,status:e.status,steps:e.steps.map(i=>({id:i.id,description:i.description,status:i.status,mcp:i.mcp,args:i.args,result:i.result,error:i.error,duration:i.duration,options:i.options})),retryContext:t,postProcessingStatus:n,insertedCount:d}}const Ni=new Set(["generate_image","generate_video","generate_long_video","generate_audio","generate_text"]);function ji(e,t){return e==="generate_image"?"image":e==="generate_video"||e==="generate_long_video"?"video":e==="generate_audio"?"audio":e==="generate_text"?"text":t.scenarioType==="skill_flow"||t.generationType==="agent"?"agent":t.generationType==="image"||t.generationType==="video"||t.generationType==="audio"||t.generationType==="text"?t.generationType:"agent"}function zi(e){const t=e.trim();if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("/")||t.startsWith("./")||t.startsWith("../"))return t||e;const n=t.replace(/\s+/g,"");return!/^[A-Za-z0-9+/=]+$/.test(n)||n.length<32?t:`data:image/png;base64,${n}`}function Wn(e){const t=zi(e);try{const n=new URL(t,window.location.origin);return n.searchParams.delete("_retry"),n.searchParams.delete("bypass_sw"),n.toString()}catch{return t}}function Oi(e,t){const n=typeof t.args.prompt=="string"?t.args.prompt.trim():e.metadata.prompt.trim(),d=(e.metadata.rawInput||e.metadata.userInstruction||e.metadata.prompt||n).trim().slice(0,2e3),r=e.scenarioType==="skill_flow"?e.name.trim():void 0,l=ji(t.mcp,e),i=Gn(e.metadata.knowledgeContextRefs);return{initialPrompt:d,sentPrompt:n.slice(0,2e3),category:l,skillId:e.skillId,skillName:r,tags:[l,r].filter(Boolean),knowledgeContextRefs:i.length>0?i:void 0}}function Hn(e,t){const n=Gn(e.metadata.knowledgeContextRefs),d=n.length>0&&Ni.has(t.mcp)&&!t.args.knowledgeContextRefs?{...t.args,knowledgeContextRefs:n}:t.args;return d.promptMeta||!["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(t.mcp)?{...t,args:d}:{...t,args:{...d,promptMeta:Oi(e,t)}}}let Oo=!1;Oo||(Ha(),si(),Is.initialize().catch(e=>{console.warn("[AIInputBar] 外部 Skill 服务初始化失败(非致命):",e)}),Oo=!0);function er(e){return e.selectionKey||(e.sourceProfileId?`${e.sourceProfileId}::${e.id}`:e.id)}function je(e,t){return t!=null&&t.profileId?`${t.profileId}::${e}`:e}function Ue(e){return e?vt(e.sourceProfileId||null,e.id):null}function hs(e){return e<=0?"0":e<=20?"1-20":e<=100?"21-100":e<=300?"101-300":e<=800?"301-800":"800+"}const Li=1,tr=4,Wi=6,Hi=5,Bi=8,Fi=.65,Gi=320,Ui=680,$i=1.5;function nr(e){const t=window.getComputedStyle(e),n=Number.parseFloat(t.fontSize)||15,d=Number.parseFloat(t.lineHeight)||n*$i,r=Number.parseFloat(t.paddingTop)+Number.parseFloat(t.paddingBottom),l=Number.parseFloat(t.borderTopWidth)+Number.parseFloat(t.borderBottomWidth);return{lineHeight:d,verticalPadding:r,verticalBorder:l}}function Lo(e,t){const{lineHeight:n,verticalPadding:d,verticalBorder:r}=nr(e);return Math.ceil(n*t+d+r)}function Vi(e){const{lineHeight:t,verticalPadding:n}=nr(e);let d=1;for(let h=0;h<e.value.length;h+=1)e.value.charCodeAt(h)===10&&(d+=1);const r=e.style.height;e.style.height="auto";const l=e.scrollHeight;e.style.height=r;const i=Math.ceil(Math.max(0,l-n)/t);return Math.max(d,i)}function Ki(){return Math.min(Math.max(Math.floor(window.innerHeight*Fi),Gi),Ui)}function Wo(e,t){if(!e)return;if(t==="collapsed"){e.style.height="",e.style.overflowY="";return}e.style.height="auto";const n=e.scrollHeight;if(t==="long-text"){const i=Ki();e.style.height=`${i}px`,e.style.overflowY=n>i?"auto":"hidden";return}const d=Lo(e,tr),r=Lo(e,Wi),l=Math.min(Math.max(n,d),r);e.style.height=`${l}px`,e.style.overflowY=n>r?"auto":"hidden"}function xe(e,t,n){if(!t)return;const d=je(t,n),r=(n==null?void 0:n.profileId)||null;return e.find(l=>er(l)===d)||e.find(l=>l.id===t&&(l.sourceProfileId||null)===r)||(r===null?e.find(l=>l.id===t&&!l.sourceProfileId):void 0)||e.find(l=>l.id===t)}function Yi(e,t){return e==="agent"&&t==="text"?"agent":t}function Xi(e){if(!e)return!1;const t=e.toLowerCase();return t.includes("#video")?!0:[".mp4",".webm",".mov",".avi",".mkv",".m4v",".flv",".wmv"].some(d=>t.includes(d))}const sr=$o.memo(({language:e,onSelectionChange:t,externalBoardRef:n,onCanvasEmptyChange:d,isDataReady:r,onFrameSelected:l})=>{const i=Ca(),h=o.useRef(i);h.current=i,o.useEffect(()=>(_o(i),bo(i),vo(i),ko(i),Po.setBoard(i),n&&(n.current=i),()=>{_o(null),bo(null),vo(null),ko(null),Po.setBoard(null),n&&(n.current=null)}),[i,n]);const p=o.useRef(d);p.current=d,o.useEffect(()=>{if(!i||!p.current||!r)return;const b=setInterval(()=>{var x;const y=i.children||[];(x=p.current)==null||x.call(p,y.length===0)},500);return()=>{clearInterval(b)}},[i,r]);const m=o.useRef(t);m.current=t;const f=o.useRef(l);return f.current=l,o.useEffect(()=>{const v=async()=>{var R,P,C,E;const y=h.current;if(!y)return;const x=Vo(y);if(x.length===1&&Ko(x[0])){const A=x[0],k=Fn.getRectangleByPoints(A.points);(R=f.current)==null||R.call(f,{id:A.id,width:k.width,height:k.height})}else(P=f.current)==null||P.call(f,null);if(x.length===0){m.current([]);return}try{const A=await Ta(y),k=[];A.graphicsImage&&k.push({url:A.graphicsImage,name:e==="zh"?"图形元素":"Graphics",type:"graphics",width:(C=A.graphicsImageDimensions)==null?void 0:C.width,height:(E=A.graphicsImageDimensions)==null?void 0:E.height});for(const L of A.remainingImages){const H=L.url||"",Y=Xi(H);k.push({url:H,name:L.name||(Y?`video-${Date.now()}`:`image-${Date.now()}`),type:Y?"video":"image",width:L.width,height:L.height})}A.remainingText&&A.remainingText.trim()&&k.push({type:"text",text:A.remainingText.trim(),name:e==="zh"?"文字内容":"Text Content"}),m.current(k)}catch(A){console.error("Failed to process selected content:",A),m.current([])}};v();const b=()=>{setTimeout(v,50)};return document.addEventListener("mouseup",b),document.addEventListener(wo,v),()=>{document.removeEventListener("mouseup",b),document.removeEventListener(wo,v)}},[e]),null});sr.displayName="SelectionWatcher";const or=$o.memo(({className:e,isDataReady:t,onEnableToolWindows:n,onEnableRuntime:d})=>{const{language:r}=Ms(),l=jn("image"),i=jn("video"),h=jn("audio"),p=jn("text"),m=ua(),f=Ea(),{setActiveSelections:v}=pa(),{addHistory:b}=Ho(),{addAsset:y}=fa(),{confirm:x,confirmDialog:R}=Bo(),P=o.useRef(m.sendWorkflowMessage);P.current=m.sendWorkflowMessage;const C=o.useRef(m.updateWorkflowMessage);C.current=m.updateWorkflowMessage;const E=o.useRef(m.appendAgentLog);E.current=m.appendAgentLog;const A=o.useRef(m.updateThinkingContent);A.current=m.updateThinkingContent;const k=o.useRef(m.setSelectedContent);k.current=m.setSelectedContent;const L=o.useRef(m.registerRetryHandler);L.current=m.registerRetryHandler;const H=o.useRef(null),Y=o.useRef([]),I=o.useRef(null),X=Za(),Z=o.useCallback((s,a,u)=>{if(!s)return;const g=Y.current,w=(u!=null&&u.workflowId&&(u!=null&&u.batchId)&&typeof u.batchIndex=="number"?wt.getAnchorByBatchSlot(s,{workflowId:u.workflowId,batchId:u.batchId,batchIndex:u.batchIndex}):null)||(u!=null&&u.workflowId?wt.getAnchorByWorkflowId(s,u.workflowId):null)||(g[0]?wt.getAnchorById(s,g[0]):null);if(!w)return;const T=w.taskIds.includes(a)?w.taskIds:[...w.taskIds,a];wt.updateAnchor(s,w.id,{taskIds:T,primaryTaskId:w.primaryTaskId||a})},[]),S=o.useCallback((s,a,u)=>{const g=Y.current;g.length===0||!s||g.forEach(w=>{wt.updateAnchor(s,w,ds(a,u))})},[]),N=o.useCallback(s=>{const a=Y.current;a.length===0||!s||(a.forEach(u=>{wt.removeAnchor(s,u)}),Y.current=[])},[]),ae=o.useCallback((s,a)=>{const u=Ri(s);if(!u)return;const g=xe(a,u.modelId,vt(u.profileId,u.modelId));if(g)return g;Qo(s)},[]),Q=o.useCallback((s,a)=>{const u=ae(s,a);if(u)return u;const w=Ot(s==="video"?"video":s==="audio"?"audio":s==="text"||s==="agent"?"text":"image"),T=xe(a,w.modelId,vt(w.profileId,w.modelId));if(T)return T;const U=s==="video"?Bt():s==="audio"?Ft():s==="text"||s==="agent"?gs():bt();return xe(a,U,null)||a[0]},[ae]),j=X.generationType,ie=Q(j,j==="video"?i:j==="audio"?h:j==="text"||j==="agent"?p:l)||tt(X.selectedModel)||tt(j==="video"?Bt():j==="audio"?Ft():j==="text"||j==="agent"?gs():bt()),Ie=Q("image",l)||tt(bt()),lt=Q("video",i)||tt(Bt()),St=Q("audio",h)||tt(Ft()),Vn=Ot("image"),hn=(Ie==null?void 0:Ie.id)||Vn.modelId||bt(),Ts=Ue(Ie)||vt(Vn.profileId,Vn.modelId),Ps=je((ie==null?void 0:ie.id)||hn,Ue(ie)||Ts),Es=j==="agent"?{}:zn(j,(ie==null?void 0:ie.id)||hn,Ps,X.selectedParams),[de,nt]=o.useState(""),[rr,mn]=o.useState(!1),[ar,ir]=o.useState(!1),[Mt,dt]=o.useState([]),[st,ut]=o.useState([]),[Ze,gn]=o.useState([]),[Te,pt]=o.useState(!1),qe=o.useRef(!1),_e=o.useRef(null),[Ut,ot]=o.useState(!1),[Ve,As]=o.useState(!1),[cr,lr]=o.useState(!1),[dr,ur]=o.useState(null),[_,Ke]=o.useState(j),[fe,xn]=o.useState(X.selectedSkillId||et),[z,Kn]=o.useState((ie==null?void 0:ie.id)||hn),[B,Yn]=o.useState(Ue(ie)||Ts),[Oe,Ds]=o.useState((Ie==null?void 0:Ie.id)||bt()),[Pe,Rs]=o.useState(Ue(Ie)),[Le,Ns]=o.useState((lt==null?void 0:lt.id)||Bt()),[Ee,js]=o.useState(Ue(lt)),[We,zs]=o.useState((St==null?void 0:St.id)||Ft()),[Ae,Os]=o.useState(Ue(St)),[ft,Je]=o.useState([]),wn=o.useMemo(()=>{if(_!=="image"||xe(l,z,B))return l;const a=yt("image",z,B);return a?[a,...l]:l},[_,l,z,B]),yn=o.useMemo(()=>{if(_!=="video"||xe(i,z,B))return i;const a=yt("video",z,B);return a?[a,...i]:i},[_,z,B,i]),In=o.useMemo(()=>{if(_!=="audio"||xe(h,z,B))return h;const a=yt("audio",z,B);return a?[a,...h]:h},[h,_,z,B]),_n=o.useMemo(()=>{if(_!=="text"&&_!=="agent"||xe(p,z,B))return p;const a=yt("text",z,B);return a?[a,...p]:p},[_,z,B,p]),$t=o.useMemo(()=>{if(xe(l,Oe,Pe))return l;const a=yt("image",Oe,Pe);return a?[a,...l]:l},[l,Oe,Pe]),Vt=o.useMemo(()=>{if(xe(i,Le,Ee))return i;const a=yt("video",Le,Ee);return a?[a,...i]:i},[Le,Ee,i]),Kt=o.useMemo(()=>{if(xe(h,We,Ae))return h;const a=yt("audio",We,Ae);return a?[a,...h]:h},[h,We,Ae]),[De,Yt]=o.useState(()=>{if(j==="agent")return{};const s=(ie==null?void 0:ie.id)||hn,a=ao(s).find(u=>u.id==="size");return{...Es,...s.startsWith("mj")||!a?{}:{size:Es.size||io(s)}}}),Ct=o.useRef(De),Xn=o.useRef(j==="agent"?"agent":`${j}:${Ps}`),Ls=o.useRef(de),Zn=o.useRef(Mt),Ws=o.useRef(st),Xt=o.useRef(new Set);o.useEffect(()=>{Ct.current=De},[De]),o.useEffect(()=>{Ls.current=de},[de]),o.useEffect(()=>{Zn.current=Mt},[Mt]),o.useEffect(()=>{Ws.current=st},[st]);const[Zt,qn]=o.useState(X.selectedCount),[Hs,Jn]=o.useState(!1),[Bs,Qn]=o.useState(!1),[Fs,es]=o.useState(!1),ht=o.useRef(null),pr=o.useCallback(s=>{Jn(s),s||(ht.current=null)},[]),fr=o.useCallback(s=>{Qn(s),s||(ht.current=null)},[]),hr=o.useCallback(s=>{es(s),s||(ht.current=null)},[]),[Gs,qt]=o.useState(!1),ce=o.useMemo(()=>[...st,...Mt],[st,Mt]),mt=o.useMemo(()=>({invalidFile:r==="zh"?"请上传图片文件":"Please upload image files",fileTooLarge:r==="zh"?"图片大小不能超过 25MB":"Image size cannot exceed 25MB",loadFailed:r==="zh"?"加载图片失败":"Failed to load image",compressionFailed:r==="zh"?"图片压缩失败":"Image compression failed",compressing:s=>r==="zh"?`正在压缩图片 (${s.toFixed(1)}MB)...`:`Compressing image (${s.toFixed(1)}MB)...`,compressed:(s,a)=>r==="zh"?`压缩完成: ${s.toFixed(1)}MB → ${a.toFixed(1)}MB`:`Compressed: ${s.toFixed(1)}MB → ${a.toFixed(1)}MB`}),[r]);o.useEffect(()=>{const s=_==="video"?yn:_==="audio"?In:_==="text"||_==="agent"?_n:wn,u=xe(s,z,B)||Q(_,s);if(u){const g=je(z,B),w=er(u);g!==w&&(Kn(u.id),Yn(Ue(u)))}_!=="agent"&&xn(et),(_==="agent"||_==="text"||_==="audio")&&qn(1)},[In,_,wn,Q,z,B,_n,yn]),o.useEffect(()=>{const s=(a,u,g,w,T,U)=>{if(xe(u,g,w))return;const O=Q(a,u);O&&(T(O.id),U(Ue(O)))};s("image",$t,Oe,Pe,Ds,Rs),s("video",Vt,Le,Ee,Ns,js),s("audio",Kt,We,Ae,zs,Os)},[Q,We,Ae,Oe,Pe,Le,Ee,Kt,$t,Vt]);const bn=o.useMemo(()=>_==="video"?yn:_==="audio"?In:_==="text"||_==="agent"?_n:wn,[In,_,wn,_n,yn]);o.useEffect(()=>{let s=!1;return(async()=>{var U;if(_!=="agent"||fe===et){Je([]);return}const u=En(fe);if(u){Je(It(u));return}const g=po(fe);if(g){Je(It(g));return}const w=await Is.getSkillById(fe);if(s)return;if(w){Je(It(w));return}const T=await Bn.getNoteById(fe);s||Je(T?It({id:T.id,name:T.title,content:T.content,outputType:(U=T.metadata)==null?void 0:U.outputType}):[])})().catch(()=>{s||Je([])}),()=>{s=!0}},[_,fe]);const Jt=o.useMemo(()=>{var u;if(_==="agent")return[];if(_==="video")return ha(z,B||z,De);const s=ao(z);return _!=="audio"?s:(De.sunoAction||((u=s.find(g=>g.id==="sunoAction"))==null?void 0:u.defaultValue)||"music")==="lyrics"?s.filter(g=>g.id==="sunoAction"||g.id==="mv"||g.id==="title"||g.id==="tags"):s},[_,z,B,De]);o.useEffect(()=>{if(!Ut)return;const s=a=>{const u=a.target;kn.current&&!kn.current.contains(u)&&ot(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[Ut]),o.useEffect(()=>()=>{_e.current&&clearTimeout(_e.current),qe.current=!1},[]),o.useEffect(()=>{const s=a=>{var u;((u=a.detail)==null?void 0:u.type)!=="image"&&(_e.current&&(clearTimeout(_e.current),_e.current=null),qe.current=!1,pt(!1))};return window.addEventListener("ai-generation-complete",s),()=>{window.removeEventListener("ai-generation-complete",s)}},[]),o.useEffect(()=>{const s=Fo.observeTaskUpdates().subscribe(a=>{var O,K;const u=a.task,g=f.getWorkflow();if(!g)return;const w=g.steps.find(W=>{const $=W.result;return($==null?void 0:$.taskId)===u.id});if(!w)return;let T=w.status,U=w.result,q=w.error;switch(u.status){case Ht.PENDING:case Ht.PROCESSING:T="running";break;case Ht.COMPLETED:T="completed",U={...typeof U=="object"?U:{},taskId:u.id,result:u.result};break;case Ht.FAILED:T="failed",q=((O=u.error)==null?void 0:O.message)||"任务执行失败";break;case Ht.CANCELLED:T="skipped";break}if(T!==w.status){if(f.updateStep(w.id,T,U,q),T==="failed"){const $=(K=w.options)==null?void 0:K.batchId;$&&g.steps.forEach(ee=>{var be;ee.id!==w.id&&((be=ee.options)==null?void 0:be.batchId)===$&&ee.status==="running"&&f.updateStep(ee.id,"skipped",void 0,"前置任务失败")})}const W=f.getWorkflow();if(W){const $=ct(W,H.current||void 0);C.current($);const ee=I.current,be=He.current;ee&&be&&Ge.updateWorkflow(be,ee,$)}}});return()=>s.unsubscribe()},[f]);const Us=o.useRef(void 0),vn=o.useRef(void 0);o.useEffect(()=>{const s=us.observeCompletionEvents().subscribe(a=>{const u=f.getWorkflow(),g=u==null?void 0:u.steps.find(U=>{const q=U.result;return(q==null?void 0:q.taskId)===a.taskId});let w,T;switch(a.type){case"postProcessingStarted":w="processing";break;case"postProcessingCompleted":w="completed",T=a.result.insertedCount;break;case"postProcessingFailed":w="failed";break}if(Us.current=w,T!==void 0&&(vn.current=(vn.current||0)+T),u&&g){const U=f.getWorkflow();if(U){const q=ct(U,H.current||void 0,w,vn.current);C.current(q);const O=I.current,K=He.current;O&&K&&Ge.updateWorkflow(K,O,q)}}if(a.type==="postProcessingCompleted"){const U=a.result.firstElementPosition;_e.current&&(clearTimeout(_e.current),_e.current=null),qe.current=!1,pt(!1),setTimeout(async()=>{var K;m.closeChatDrawer();const q=I.current,O=He.current;if(q&&O){const W=f.getWorkflow();if(W==null?void 0:W.steps.every(ee=>ee.status==="completed"||ee.status==="failed"||ee.status==="skipped")){const{workflowCompletionService:ee}=await yo(async()=>{const{workflowCompletionService:se}=await import("./startup-app-eD_rQhSh.js").then(Ce=>Ce.o2);return{workflowCompletionService:se}},__vite__mapDeps([0]),import.meta.url);(W==null?void 0:W.steps.every(se=>{const Ce=se.result;return Ce!=null&&Ce.taskId?ee.isPostProcessingCompleted(Ce.taskId):!0}))&&(Ge.removeWorkZone(O,q),I.current=null)}}if(U&&O){const W=(K=O.host)==null?void 0:K.getBoundingClientRect();if(W){const $=O.viewport.zoom,ee=U[0]-W.width/(2*$),be=U[1]-W.height/(2*$);ma.updateViewport(O,[ee,be],$)}}},500),Us.current=void 0,vn.current=void 0}});return()=>s.unsubscribe()},[f,m]);const He=o.useRef(null),{submitWorkflow:$s}=Aa({boardRef:He,workZoneIdRef:I}),Me=o.useRef(null),kn=o.useRef(null),Vs=o.useRef(null);za(Me,{enableCopy:!0,stopPropagation:!0});const Sn=o.useCallback(()=>{ot(!0),requestAnimationFrame(()=>{var s;(s=Me.current)==null||s.focus()})},[]),Ks=o.useCallback(async s=>{const a=Ls.current.trim().length>0,u=Ws.current.length>0,g=Zn.current.length>0,w=Ze.length>0;return(s==="canvas-toolbar"?a||u||w:a||u||g||w)?x({title:r==="zh"?"覆盖当前输入?":"Overwrite current input?",description:r==="zh"?"底部输入框已有提示词或参考图,继续会覆盖当前输入。":"The bottom input already has a prompt or reference images. Continuing will overwrite it.",confirmText:r==="zh"?"覆盖当前输入":"Overwrite input",cancelText:r==="zh"?"取消":"Cancel",confirmTheme:"warning"}):!0},[x,Ze.length,r]);o.useEffect(()=>{const s=a=>{const u=a.detail;if(u!=null&&u.generationType&&Ke(u.generationType),u!=null&&u.skillId){xn(u.skillId);const g=En(u.skillId);g&&Je(It(g))}Sn()};return window.addEventListener(co,s),()=>{window.removeEventListener(co,s)}},[Sn]),o.useEffect(()=>{const s=async a=>{const u=a.detail;if(!u||!await Ks(u.source))return;const g=u.generationType,w=g==="video"?i:g==="audio"?h:g==="text"||g==="agent"?p:l,T=xe(w,u.model,u.modelRef||null)||xe(w,u.model,null)||Q(g,w),U=Ue(T),q=(T==null?void 0:T.id)||u.model||z,O=je(q,U),K=g==="agent"?{}:{...zn(g,q,O),...u.params||{}};if(u.source==="canvas-toolbar"){const W=Zn.current.filter($=>$.type==="image"&&typeof $.url=="string").map($=>Wn($.url));Xt.current=new Set(W),dt($=>$.filter(ee=>ee.type!=="image"||typeof ee.url!="string"?!0:!Xt.current.has(Wn(ee.url))))}else Xt.current=new Set,dt([]),ts.current=null;Ke(g),nt(u.prompt||""),ut((u.images||[]).map((W,$)=>({type:"image",url:W.url,name:W.name||`参考图 ${$+1}`,width:W.width,height:W.height}))),Kn(q),Yn(U),gn(Gn(u.knowledgeContextRefs)),Yt(K),Ct.current=K,Xn.current=g==="agent"?"agent":`${g}:${O}`,typeof u.count=="number"&&u.count>0&&qn(u.count),Ye.success(r==="zh"?"已回填到底部输入框,请手动发送":"Loaded into the bottom input. Send manually when ready."),Sn()};return window.addEventListener(lo,s),()=>{window.removeEventListener(lo,s)}},[h,Ks,Sn,l,r,Q,z,p,i]);const mr=o.useCallback(s=>{var a;if(nt(s.prompt),mn(!0),Ke("agent"),s.skillId){xn(s.skillId);const u=En(s.skillId);u&&Je(It(u))}(a=Me.current)==null||a.focus(),ze.track("inspiration_selected",{promptLength:s.prompt.length,modelType:s.modelType,skillId:s.skillId,templateId:s.templateId,title:s.title,category:s.category})},[]),gr=o.useCallback(s=>{var a;nt(s.content),mn(!1),s.modelType&&(s.modelType==="image"?Ke("image"):s.modelType==="video"?Ke("video"):s.modelType==="audio"?Ke("audio"):s.modelType==="text"?Ke("text"):s.modelType==="agent"&&Ke("agent")),(a=Me.current)==null||a.focus()},[]),xr=o.useCallback(()=>{const s=ms.find(a=>a.id==="knowledge-base");s&&(window.__kbPendingNavigation={directoryName:"Skill",autoCreateNote:!0},fn.openTool(s),setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:{directoryName:"Skill",autoCreateNote:!0}}))},300))},[]),Ys=o.useCallback((s="ai_input_bar")=>{const a=ms.find(u=>u.id==="banana-prompt");if(!a){console.warn("[AIInputBar] Banana prompt tool not found"),ze.trackPromptAction({action:"open_tool",surface:s,promptType:_,prompt:de,source:s,status:"failed",metadata:{tool_id:"banana-prompt",reason:"tool_not_found"}});return}ze.trackPromptAction({action:"open_tool",surface:s,promptType:_,prompt:de,source:s,status:"success",metadata:{tool_id:a.id,tool_type:"external_prompt_library"}}),fn.openTool(a)},[_,de]),wr=o.useCallback(()=>{Ys("inspiration_board")},[Ys]),yr=o.useCallback(async s=>{try{const a=new Image;a.onload=()=>{const u={type:"image",url:s.url,name:s.name||`素材-${Date.now()}`,width:a.naturalWidth||void 0,height:a.naturalHeight||void 0};ut(g=>[...g,u]),qt(!1)},a.onerror=()=>{const u={type:"image",url:s.url,name:s.name||`素材-${Date.now()}`};ut(g=>[...g,u]),qt(!1)},a.src=s.url}catch(a){console.error("Failed to select asset from library:",a),qt(!1)}},[]),Ir=o.useCallback(s=>{gn(Gn(s))},[]),_r=o.useCallback(()=>{var s;(s=Vs.current)==null||s.click()},[]),Xs=o.useCallback(s=>new Promise((a,u)=>{const g=new FileReader;g.onload=()=>{const w=g.result,T=new Image;T.onload=()=>{a({url:w,width:T.naturalWidth,height:T.naturalHeight})},T.onerror=()=>{a({url:w,width:0,height:0})},T.src=w},g.onerror=u,g.readAsDataURL(s)}),[]),Mn=o.useCallback(async s=>{const a=Array.from(s);if(a.length===0)return;const u=[];for(const[g,w]of a.entries()){if(!w.type.startsWith("image/")){Ye.error(mt.invalidFile);continue}if(w.size>25*1024*1024){Ye.error(mt.fileTooLarge);continue}try{let T=w;if(w.size>10*1024*1024){const{compressImageBlob:W,getCompressionStrategy:$}=await yo(async()=>{const{compressImageBlob:se,getCompressionStrategy:Ce}=await import("./startup-app-eD_rQhSh.js").then(Qe=>Qe.nO);return{compressImageBlob:se,getCompressionStrategy:Ce}},__vite__mapDeps([0]),import.meta.url),ee=$(w.size/(1024*1024)),be=Ye.loading({content:mt.compressing(w.size/(1024*1024)),duration:0,placement:"top"});try{T=await W(w,ee.targetSizeMB),Ye.close(be),Ye.success({content:mt.compressed(w.size/(1024*1024),T.size/(1024*1024)),duration:2})}catch(se){Ye.close(be),console.error("[AIInputBar] Failed to compress image:",se),Ye.error(mt.compressionFailed);continue}}const U=T instanceof File?T:new File([T],w.name||`pasted-image-${Date.now()}.png`,{type:T.type||w.type||"image/png"});y(U,uo.IMAGE,ga.LOCAL,U.name).catch(W=>{console.warn("[AIInputBar] Failed to add asset to library:",W)});const{url:q,width:O,height:K}=await Xs(U);u.push({type:"image",url:q,name:U.name||`上传图片 ${g+1}`,width:O||void 0,height:K||void 0})}catch(T){console.error("[AIInputBar] Failed to import local image:",T),Ye.error(mt.loadFailed)}}u.length>0&&ut(g=>[...g,...u])},[y,Xs,mt]),br=o.useCallback(async s=>{const a=s.target.files;!a||a.length===0||(await Mn(a),s.target.value="")},[Mn]),vr=o.useCallback(s=>{const a=Xt.current;if(a.size===0){dt(s);return}if(!s.some(g=>g.type!=="image"||typeof g.url!="string"?!1:a.has(Wn(g.url)))){Xt.current=new Set,dt(s);return}dt(s.filter(g=>g.type!=="image"||typeof g.url!="string"?!0:!a.has(Wn(g.url))))},[]),ts=o.useRef(null),kr=o.useCallback(s=>{if(ts.current=s,!s)return;const a=xa(s.width,s.height,z);a&&Yt(u=>({...u,size:a}))},[z]),Sr=o.useCallback(s=>{s<st.length&&ut(a=>a.filter((u,g)=>g!==s))},[st.length]);o.useEffect(()=>{k.current(ce.map(s=>({type:s.type,url:s.url,text:s.text,name:s.name})))},[ce]),o.useEffect(()=>{const s=a=>{var O,K;const u=(O=a.clipboardData)==null?void 0:O.items;if(!u||u.length===0||!Array.from(u).some(W=>W.type.startsWith("image/")))return;const w=document.activeElement,T=kn.current;if(!(!!T&&(T.contains(w)||Ut&&(w===document.body||(w==null?void 0:w.tagName)==="BODY"))))return;const q=[];for(const W of Array.from(u)){if(!W.type.startsWith("image/"))continue;const $=W.getAsFile();$&&q.push($)}q.length!==0&&(a.preventDefault(),Mn(q),(K=Me.current)==null||K.focus())};return document.addEventListener("paste",s),()=>{document.removeEventListener("paste",s)}},[Mn,Ut]);const Tt=o.useCallback(()=>{if(ht.current!==null){const s=ht.current;nt(a=>a.substring(0,s)+a.substring(s+1)),ht.current=null}},[]),Cn=o.useCallback(s=>{const a=Yi(_,s.type);ze.track("ai_input_change_model",{model:s.id,type:s.type,profileId:s.sourceProfileId||null}),Tt(),Ke(a),Kn(s.id);const u=Ue(s);Yn(u),zo(a,{modelId:s.id,modelRef:u,providerIdHint:s.sourceProfileId||(u==null?void 0:u.profileId),vendorHint:s.vendor}),Yt(a==="agent"?{}:zn(a,s.id,je(s.id,u))),Jn(!1),setTimeout(()=>{var g;return(g=Me.current)==null?void 0:g.focus()},0)},[Tt,_]),Mr=o.useCallback(s=>{const a=xe(bn,s,B)||xe(bn,s,null)||tt(s);a&&Cn(a)},[Cn,bn,B]),Cr=o.useCallback(s=>{Cn(s)},[Cn]),Tn=o.useCallback((s,a)=>{const u=Ue(a);s==="image"?(Ds(a.id),Rs(u)):s==="video"?(Ns(a.id),js(u)):(zs(a.id),Os(u)),zo(s,{modelId:a.id,modelRef:u,providerIdHint:a.sourceProfileId||(u==null?void 0:u.profileId),vendorHint:a.vendor}),ze.track("ai_input_change_agent_media_model",{model:a.id,type:s,profileId:a.sourceProfileId||null})},[]),ns=o.useCallback((s,a,u)=>{const g=s==="image"?$t:s==="video"?Vt:Kt,w=xe(g,a,u||null)||xe(g,a,null)||tt(a);w&&Tn(s,w)},[Tn,Kt,$t,Vt]),ss=o.useCallback((s,a)=>{Tn(s,a)},[Tn]),Tr=o.useCallback(s=>{Je(It(s))},[]),Zs=o.useMemo(()=>({image:Oe,video:Le,audio:We}),[We,Oe,Le]),qs=o.useMemo(()=>({image:Pe,video:Ee,audio:Ae}),[Ae,Pe,Ee]);o.useEffect(()=>{const s=[{modelId:z,profileId:(B==null?void 0:B.profileId)||null}];_==="agent"&&fe!==et&&(ft.includes("image")&&s.push({modelId:Oe,profileId:(Pe==null?void 0:Pe.profileId)||null}),ft.includes("video")&&s.push({modelId:Le,profileId:(Ee==null?void 0:Ee.profileId)||null}),ft.includes("audio")&&s.push({modelId:We,profileId:(Ae==null?void 0:Ae.profileId)||null})),v(s)},[_,We,Ae,Oe,Pe,Le,Ee,z,B,fe,ft,v]),o.useEffect(()=>{const s=(O,K)=>{const W=Object.keys(O),$=Object.keys(K);return W.length!==$.length?!1:W.every(ee=>O[ee]===K[ee])},a=_==="agent"?"agent":`${_}:${je(z,B)}`,u=_==="agent"?{}:Xn.current===a?Ct.current||{}:zn(_,z,je(z,B),Ct.current),g={},w=Jt.find(O=>O.id==="size"),T=u.size,U=!T||!(w!=null&&w.options)||w.options.some(O=>O.value===T);!z.startsWith("mj")&&w&&(g.size=T&&U?T:w.defaultValue||io(z)),Jt.forEach(O=>{if(O.id==="size")return;const K=u[O.id],W=!K||O.valueType!=="enum"||!O.options||O.options.some($=>$.value===K);K&&W?g[O.id]=K:O.defaultValue&&(g[O.id]=O.defaultValue)});const q=wa(z,g);s(Ct.current||{},q)||(Yt(q),Ct.current=q),Xn.current=a},[_,z,B,Jt]),o.useEffect(()=>{qa({generationType:_,selectedModel:z,selectedParams:De,selectedCount:Zt,selectedSkillId:fe}),_!=="agent"&&Ja(_,z,De,je(z,B))},[_,z,B,De,Zt,fe]);const Pr=o.useCallback((s,a,u)=>{Tt(),Yt(g=>{const w={...g};return a===void 0||a===""?delete w[s]:w[s]=a,w}),u!=null&&u.keepOpen||(Qn(!1),setTimeout(()=>{var g;return(g=Me.current)==null?void 0:g.focus()},0))},[Tt]),Er=o.useCallback(s=>{Tt(),qn(s),es(!1),setTimeout(()=>{var a;return(a=Me.current)==null?void 0:a.focus()},0)},[Tt]),os=o.useCallback(async s=>{var U,q,O,K,W,$,ee,be;const a=de.trim();if(!a&&ce.length===0||qe.current||Te)return;qe.current=!0,mn(!1),d==null||d();const u=Date.now(),g=a.length,w={trigger:s,source:"ai_input_bar",generationType:_,generation_type:_,model:z,profileId:(B==null?void 0:B.profileId)||null,profile_id:(B==null?void 0:B.profileId)||null,hasAttachedContent:ce.length>0,has_attached_content:ce.length>0,attachedCount:ce.length,attached_count:ce.length,knowledgeContextCount:Ze.length,knowledge_context_count:Ze.length,promptLength:g,prompt_length:g,promptLengthBucket:hs(g),prompt_length_bucket:hs(g)},T=(se,Ce={})=>{const Qe=Date.now()-u;ze.track("ai_input_submit",{...w,status:se,durationMs:Qe,duration_ms:Qe,...Ce})};T("start"),pt(!0);try{if(!ya(_==="video"?"video":_==="audio"?"audio":_==="text"||_==="agent"?"text":"image",B||z)&&!await Ia()){T("cancelled",{reason:"missing_api_key",submitMode:"preflight",submit_mode:"preflight"}),qe.current=!1,pt(!1);return}const Qe=ce.filter(M=>M.type==="image"&&M.url),Qt=ce.filter(M=>M.type==="graphics"&&M.url),D=[...Qe,...Qt].map(M=>{if(M.width&&M.height)return{width:M.width,height:M.height}}).filter(M=>M!==void 0),ne={texts:ce.filter(M=>M.type==="text"&&M.text).map(M=>M.text),images:Qe.map(M=>M.url),videos:ce.filter(M=>M.type==="video"&&M.url).map(M=>M.url),graphics:Qt.map(M=>M.url),imageDimensions:D},G=fi(de,ne,{modelId:z,modelRef:B,params:De,generationType:_,count:Zt,knowledgeContextRefs:Ze,defaultModels:_==="agent"?Zs:void 0,defaultModelRefs:_==="agent"?qs:void 0}),oe=[...ne.images,...ne.graphics];let F;if(_==="agent"&&fe!==et){const M=En(fe);if(M)try{F=await Dn(G,M,oe)}catch(te){console.warn("[AIInputBar] 系统 Skill 工作流转换失败,降级到通用工作流:",te),F=Wt(G,oe)}else{const te=po(fe);if(te)try{F=await Dn(G,{id:te.id,name:te.name,type:"external",content:te.content,outputType:te.outputType},oe)}catch(J){console.warn("[AIInputBar] 外部 Skill 工作流转换失败,降级到角色扮演:",J),F=await Dn(G,{id:te.id,name:te.name,type:"external",content:te.content,outputType:te.outputType},oe).catch(()=>Wt(G,oe))}else try{const J=await Bn.getNoteById(fe);if(J){const le=((U=J.metadata)==null?void 0:U.outputType)||void 0;F=await Dn(G,{id:J.id,name:J.title,type:"user",content:J.content,outputType:le},oe)}else F=Wt(G,oe)}catch{F=Wt(G,oe)}}F||(console.warn("[AIInputBar] Skill 工作流未能生成,降级到通用工作流"),F=Wt(G,oe))}else F=Wt(G,oe);const V=He.current;if(V){const le=(q=V.host)==null?void 0:q.getBoundingClientRect(),me=((O=V.viewport)==null?void 0:O.zoom)||1,ge=((W=(K=V.viewport)==null?void 0:K.origination)==null?void 0:W[0])||0,Be=((ee=($=V.viewport)==null?void 0:$.origination)==null?void 0:ee[1])||0,sn=V.children.filter(ye=>ye.type!=="workzone"),Pn=ge+((le==null?void 0:le.width)||0)/2/me,Rt=Be+((le==null?void 0:le.height)||0)/2/me;let ke=Pn-200,re=Rt,Nt=ke,it=Rt-240/2;if(sn.length>0){const ye=Vo(V);let ue=!1;if(ye.length>0)try{const pe=ps(V,ye,!1);ye.every(Se=>fo.isDrawElement(Se)&&fo.isImage(Se)||_a(Se))&&pe.width>pe.height?(ke=pe.x+pe.width+50,re=pe.y):(ke=pe.x,re=pe.y+pe.height+50),Nt=ke,it=re,ue=!0}catch(pe){console.warn("[AIInputBar] Failed to calculate position for selected elements:",pe)}if(!ue){let pe=null,rn=-1/0;for(const Se of sn)try{const zt=ps(V,[Se],!1),an=zt.y+zt.height;an>rn&&(rn=an,pe=Se)}catch(zt){console.warn("[AIInputBar] Failed to get rectangle for element:",zt)}if(pe){const Se=ps(V,[pe],!1);ke=Se.x,re=Se.y+Se.height+50,Nt=ke,it=re}}}const gt=ct(F),jt=ts.current;let on,xt,to;if(jt){const ye=V.children.find(ue=>ue.id===jt.id);if(ye&&Ko(ye)){on=jt.id,xt={width:jt.width,height:jt.height};const ue=Fn.getRectangleByPoints(ye.points);to=ue,ke=ue.x,re=ue.y}}if(G.generationType==="image"){const ye=Math.max(G.count??1,1),ue=ye>1,pe=ue?void 0:on,rn=ue?void 0:xt,Se=[],zt=`wf_batch_${F.id}`,an=pe?null:Pi(V,[ke,re],ho({workflowId:F.id,expectedInsertPosition:[ke,re],requestedSize:G.size,requestedCount:1,zoom:me,title:gt.name||"图片生成",...ds("submitted")}).size??{width:320,height:180},ye,{frameRect:ue?to:void 0});for(let Fe=0;Fe<ye;Fe+=1){let cn=ho({workflowId:F.id,expectedInsertPosition:[ke,re],targetFrameId:pe,targetFrameDimensions:rn,frameAffinityId:ue?on:void 0,frameAffinityDimensions:ue?xt:void 0,requestedSize:G.size,requestedCount:ue?1:ye,batchId:ue?zt:void 0,batchIndex:ue?Fe+1:void 0,batchTotal:ue?ye:void 0,zoom:me,title:gt.name||"图片生成",...ds("submitted")});if(!pe){const so=an?an[Fe]??cn.position:cn.position;cn={...cn,position:so,expectedInsertPosition:so}}const Br=wt.insertAnchor(V,cn);Se.push(Br)}Y.current=Se.map(Fe=>Fe.id),I.current=null;const[no]=Se;no&&setTimeout(()=>{const Fe=Fn.getRectangleByPoints(no.points);mo(V,[Fe.x+Fe.width/2,Fe.y+Fe.height/2],100)},100)}else{const ye=Ge.insertWorkZone(V,{workflow:gt,position:[Nt,it],size:{width:360,height:240},expectedInsertPosition:[ke,re],targetFrameId:on,targetFrameDimensions:xt,zoom:me});I.current=ye.id,Y.current=[],setTimeout(()=>{const ue=Nt+180,pe=it+240/2;mo(V,[ue,pe],100)},100)}}const Pt=Ot("image"),Et=Ot("video"),At=Ot("audio"),Dt={rawInput:de,userInstruction:G.userInstruction,model:{id:G.modelId,type:G.generationType,isExplicit:G.isModelExplicit},modelRef:G.modelRef,defaultModels:G.defaultModels||{audio:At.modelId||Ft(),image:Pt.modelId||bt(),video:Et.modelId||Bt()},defaultModelRefs:G.defaultModelRefs||{audio:vt(At.profileId,At.modelId),image:vt(Pt.profileId,Pt.modelId),video:vt(Et.profileId,Et.modelId)},params:{count:G.count,size:G.size,duration:G.duration},selection:ne,finalPrompt:G.prompt,knowledgeContextRefs:G.knowledgeContextRefs},is=Ot("text").modelId,en={aiContext:Dt,referenceImages:oe,textModel:is};H.current=en;try{const M=Date.now(),{usedSW:te}=await $s(G,oe,en,F);if(te){if(T("success",{submitMode:"service_worker",submit_mode:"service_worker",workflowId:F.id,workflow_id:F.id,stepCount:F.steps.length,step_count:F.steps.length}),_==="image"&&S(V,"accepted"),de.trim()){const J=de.trim(),le=ce.length>0;b(J,le,_),_==="image"?go(J):_==="video"&&xo(J)}nt(""),dt([]),ut([]),gn([]),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{qe.current=!1,pt(!1),_e.current=null},1e3);return}}catch(M){console.warn("[AIInputBar] SW execution failed, falling back to main thread:",M)}if(_==="image"&&S(V,"handoff"),de.trim()){const M=de.trim(),te=ce.length>0;b(M,te,_),_==="image"?go(M):_==="video"&&xo(M)}nt(""),dt([]),ut([]),gn([]),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>{qe.current=!1,pt(!1),_e.current=null},1e3);const he=[],at=[],tn=(M,te)=>({onChunk:J=>{A.current(J)},onAddSteps:J=>{f.updateStep(M.id,"completed",{analysis:"completed"},void 0,Date.now()-te);const le=J.map((ge,Be)=>Hn(F,{...ge,status:ge.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:Be+1,batchTotal:J.length,globalIndex:Be+1}}));f.addSteps(le),at.push(...le),J.forEach(ge=>{E.current({type:"tool_call",timestamp:Date.now(),toolName:ge.mcp,args:ge.args})});const me=ct(f.getWorkflow(),H.current||void 0);C.current(me),I.current&&V&&Ge.updateWorkflow(V,I.current,me)},onUpdateStep:(J,le,me,ge)=>{f.updateStep(J,le,me,ge),E.current({type:"tool_result",timestamp:Date.now(),toolName:J,success:le==="completed",data:me,error:ge});const Be=ct(f.getWorkflow(),H.current||void 0);C.current(Be),I.current&&V&&Ge.updateWorkflow(V,I.current,Be)}});let Re=!1;const nn=()=>{const M=ct(f.getWorkflow(),H.current||void 0);C.current(M),I.current&&V&&Ge.updateWorkflow(V,I.current,M)},cs=async M=>{var le,me,ge,Be,sn,Pn;const te=Date.now(),J=at.length;f.updateStep(M.id,"running"),nn();try{const Rt={...M.options,...tn(M,te)},ke=Hn(F,M),re=await Io.executeTool({name:ke.mcp,arguments:ke.args},Rt),Nt=(me=(le=f.getWorkflow())==null?void 0:le.steps.find(it=>it.id===M.id))==null?void 0:me.status;if(re.success){if(re.taskId)he.push(re.taskId),f.updateStep(M.id,"running",{taskId:re.taskId}),Z(V,re.taskId,{workflowId:F.id,batchId:(ge=M.options)==null?void 0:ge.batchId,batchIndex:(Be=M.options)==null?void 0:Be.batchIndex});else if(Nt==="running"){const it=re.type==="text"&&re.data&&typeof re.data=="object"&&"content"in re.data?{content:re.data.content}:re.data;f.updateStep(M.id,"completed",it,void 0,Date.now()-te);const gt=M.mcp==="generate_text"?(sn=re.data)==null?void 0:sn.content:M.mcp==="ai_analyze"?(Pn=re.data)==null?void 0:Pn.response:void 0;if((M.mcp==="generate_text"||M.mcp==="ai_analyze")&&gt&&gt.trim()&&at.length===J){const xt={id:`${M.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:gt}]},description:M.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};f.addSteps([xt]),at.push(xt)}}}else return f.updateStep(M.id,"failed",void 0,re.error||"执行失败",Date.now()-te),!1;return!0}catch(Rt){return f.updateStep(M.id,"failed",void 0,String(Rt)),!1}finally{nn()}};for(const M of F.steps){if(Re){f.updateStep(M.id,"skipped"),nn();continue}await cs(M)||(Re=!0)}if(!Re&&at.length>0){const M=f.getWorkflow();for(const te of at){if(Re){f.updateStep(te.id,"skipped"),nn();continue}const J=(be=f.getWorkflow())==null?void 0:be.steps.find(me=>me.id===te.id);if(!J){console.warn(`[AIInputBar] Step ${te.id} not found in workflow!`);continue}if(J.status==="completed")continue;await cs(J)||(Re=!0)}}const ve=f.getWorkflow(),Wr=ve==null?void 0:ve.steps.every(M=>M.status==="completed"||M.status==="failed"||M.status==="skipped"),Hr=he.length>0;if(Wr&&!Hr){const M=I.current,te=Y.current,J=He.current;(M||te.length>0)&&J&&(ve!=null&&ve.steps.every(me=>{const ge=me.result;return ge!=null&&ge.taskId?us.isPostProcessingCompleted(ge.taskId):!0}))&&setTimeout(()=>{M&&(Ge.removeWorkZone(J,M),I.current=null),te.length>0&&(S(J,"completed"),N(J))},1500)}T(Re?"failed":"success",{submitMode:"main_thread",submit_mode:"main_thread",workflowId:F.id,workflow_id:F.id,stepCount:(ve==null?void 0:ve.steps.length)||F.steps.length,step_count:(ve==null?void 0:ve.steps.length)||F.steps.length,createdTaskCount:he.length,created_task_count:he.length,failureReason:Re?"workflow_step_failed":void 0,failure_reason:Re?"workflow_step_failed":void 0})}catch(se){console.error("Failed to create generation task:",se),T("failed",{submitMode:"setup",submit_mode:"setup",error:se instanceof Error?se.message:String(se)}),_==="image"&&S(He.current,"failed",{error:se instanceof Error?se.message:"创建图片任务失败"}),f.abortWorkflow(),qe.current=!1,pt(!1)}},[de,ce,Te,z,B,f,$s,b,De,Ze,Zs,qs,_,Zt,Z,S,N,d]),rs=o.useCallback(async(s,a,u)=>{var Qt;const g=s.retryContext;if(!g){console.error("[AIInputBar] No retry context available for workflow");return}u&&(I.current=u);const w={id:s.id,name:s.name,description:`重试: ${s.name}`,scenarioType:s.steps.some(D=>D.mcp==="ai_analyze")?"agent_flow":"direct_generation",generationType:s.generationType,steps:s.steps.map((D,ne)=>({id:D.id,mcp:D.mcp,args:D.args,description:D.description,status:ne<a?D.status:"pending",result:ne<a?D.result:void 0,error:ne<a?D.error:void 0,duration:ne<a?D.duration:void 0,options:D.options})),metadata:{prompt:s.prompt,userInstruction:g.aiContext.userInstruction,rawInput:g.aiContext.rawInput,modelId:g.aiContext.model.id,modelRef:g.aiContext.modelRef,defaultModels:g.aiContext.defaultModels,defaultModelRefs:g.aiContext.defaultModelRefs,isModelExplicit:g.aiContext.model.isExplicit,count:s.count,size:g.aiContext.params.size,duration:g.aiContext.params.duration,referenceImages:g.referenceImages,selection:g.aiContext.selection,knowledgeContextRefs:g.aiContext.knowledgeContextRefs},createdAt:Date.now()};f.startWorkflow(w),E.current({type:"retry",timestamp:Date.now(),reason:`从步骤 ${a+1} 开始重试`,attempt:1});const T=He.current,U=()=>{const D=ct(f.getWorkflow(),g);C.current(D),I.current&&T&&Ge.updateWorkflow(T,I.current,D)},q=ct(w,g);C.current(q),I.current&&T&&Ge.updateWorkflow(T,I.current,q);const O=(D,ne)=>({onChunk:G=>{A.current(G)},onAddSteps:G=>{f.updateStep(D.id,"completed",{analysis:"completed"},void 0,Date.now()-ne);const oe=G.map((F,V)=>Hn(w,{...F,status:F.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:V+1,batchTotal:G.length,globalIndex:V+1}}));f.addSteps(oe),K.push(...oe),G.forEach(F=>{E.current({type:"tool_call",timestamp:Date.now(),toolName:F.mcp,args:F.args})}),U()},onUpdateStep:(G,oe,F,V)=>{f.updateStep(G,oe,F,V),E.current({type:"tool_result",timestamp:Date.now(),toolName:G,success:oe==="completed",data:F,error:V}),U()}}),K=[];let W=!1;const $=new Map;s.steps.forEach(D=>{var G;const ne=(G=D.result)==null?void 0:G.taskId;ne&&$.set(D.id,ne)});const ee=async D=>{var oe,F,V,Pt,Et,At;const ne=Date.now(),G=K.length;f.updateStep(D.id,"running"),U();try{const Dt=$.get(D.id),is={...D.options,...O(D,ne),...Dt?{retryTaskId:Dt}:{}},en=Hn(w,D),he=await Io.executeTool({name:en.mcp,arguments:en.args},is),at=(F=(oe=f.getWorkflow())==null?void 0:oe.steps.find(tn=>tn.id===D.id))==null?void 0:F.status;if(he.success){if(he.taskId)f.updateStep(D.id,"running",{taskId:he.taskId}),Z(T,he.taskId,{workflowId:s.id,batchId:(V=D.options)==null?void 0:V.batchId,batchIndex:(Pt=D.options)==null?void 0:Pt.batchIndex});else if(at==="running"){const tn=he.type==="text"&&he.data&&typeof he.data=="object"&&"content"in he.data?{content:he.data.content}:he.data;f.updateStep(D.id,"completed",tn,void 0,Date.now()-ne);const Re=D.mcp==="generate_text"?(Et=he.data)==null?void 0:Et.content:D.mcp==="ai_analyze"?(At=he.data)==null?void 0:At.response:void 0;if((D.mcp==="generate_text"||D.mcp==="ai_analyze")&&Re&&Re.trim()&&K.length===G){const ve={id:`${D.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:Re}]},description:D.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};f.addSteps([ve]),K.push(ve)}}}else return f.updateStep(D.id,"failed",void 0,he.error||"执行失败",Date.now()-ne),!1;return!0}catch(Dt){return f.updateStep(D.id,"failed",void 0,String(Dt)),!1}finally{U()}},be=w.steps.slice(a);for(const D of be){if(W){f.updateStep(D.id,"skipped"),U();continue}await ee(D)||(W=!0)}if(!W&&K.length>0)for(const D of K){if(W){f.updateStep(D.id,"skipped"),U();continue}const ne=(Qt=f.getWorkflow())==null?void 0:Qt.steps.find(oe=>oe.id===D.id);if(!ne||ne.status==="completed")continue;await ee(ne)||(W=!0)}const se=f.getWorkflow(),Ce=se==null?void 0:se.steps.every(D=>D.status==="completed"||D.status==="failed"||D.status==="skipped"),Qe=se==null?void 0:se.steps.some(D=>{var ne;return(ne=D.result)==null?void 0:ne.taskId});if(Ce&&!Qe){const D=I.current,ne=He.current;D&&ne&&(se!=null&&se.steps.every(oe=>{const F=oe.result;return F!=null&&F.taskId?us.isPostProcessingCompleted(F.taskId):!0}))&&setTimeout(()=>{Ge.removeWorkZone(ne,D),I.current=null},1500)}},[f,Z]);o.useEffect(()=>{L.current(rs);const s=He.current;s&&(s.__executeWorkflowRetry=rs)},[rs]);const Ar=o.useCallback(s=>{var a;if(!s.nativeEvent.isComposing&&!(s.key==="Enter"&&(s.shiftKey||s.altKey))){if((Hs||Bs||Fs)&&(s.key==="Enter"||s.key==="Tab")){s.preventDefault();return}if(s.key==="Enter"){s.preventDefault(),ze.track("ai_input_submit_keyboard"),os("keyboard");return}if(s.key==="Escape"){ot(!1),(a=Me.current)==null||a.blur();return}}},[os]),Dr=o.useCallback(()=>{ze.track("ai_input_focus_textarea"),ot(!0)},[]),Rr=o.useCallback(()=>{ze.track("ai_input_blur_textarea"),ot(!1)},[]),Nr=o.useCallback(s=>{s.preventDefault(),s.stopPropagation(),As(a=>!a),ot(!0),requestAnimationFrame(()=>{var a;(a=Me.current)==null||a.focus()})},[]),jr=o.useCallback(s=>{const a=s.target.value,u=s.target.selectionStart||a.length;if(nt(a),mn(!1),u>0){const g=a[u-1],w=u>1?a[u-2]:" ";g==="#"&&(w===" "||w===`
107
+ `||u===1)&&(ht.current=u-1,Jn(!0),Qn(!1),es(!1))}},[]),zr=o.useMemo(()=>JSON.stringify({generationType:_,model:z,profileId:(B==null?void 0:B.profileId)||null,hasAttachedContent:ce.length>0,attachedCount:ce.length,knowledgeContextCount:Ze.length,promptLengthBucket:hs(de.trim().length)}),[ce.length,_,Ze.length,de,z,B==null?void 0:B.profileId]),as=de.trim().length>0||ce.length>0,Or=rr&&as&&!Te,Js=dr===!0,Lr=Mt.some(s=>{var a;return s.type==="text"&&((a=s.text)==null?void 0:a.trim())}),rt=Ve||Ut||ce.length>0||ar,Qs=Ve?"long-text":rt?"expanded":"collapsed",eo=Ve?r==="zh"?"收起提示词输入框":"Collapse prompt input":r==="zh"?"展开提示词输入框":"Expand prompt input";return o.useLayoutEffect(()=>{const s=Me.current;if(!s)return;const a=Vi(s)>Hi;if(lr(a),!a&&Ve){As(!1),Wo(s,rt?"expanded":"collapsed");return}Wo(s,Qs)},[Qs,Ve,de,rt]),c.jsxs(c.Fragment,{children:[R,c.jsxs("div",{ref:kn,className:Lt("ai-input-bar",$n,e,{"ai-input-bar--with-inspiration":Js}),"data-testid":"ai-input-bar",children:[c.jsx(sr,{language:r,onSelectionChange:vr,externalBoardRef:He,onCanvasEmptyChange:ur,isDataReady:t,onFrameSelected:kr}),c.jsx(_i,{isCanvasEmpty:Js,onSelectPrompt:mr,onOpenPromptTool:wr}),c.jsxs("div",{className:Lt("ai-input-bar__container",{"ai-input-bar__container--expanded":rt}),children:[c.jsxs("div",{className:"ai-input-bar__bottom-bar",children:[c.jsx("input",{ref:Vs,type:"file",accept:"image/*",multiple:!0,onChange:br,style:{display:"none"}}),c.jsx(Xe,{content:r==="zh"?"上传图片":"Upload images",showArrow:!1,children:c.jsx("button",{className:"ai-input-bar__upload-btn",onMouseDown:s=>{s.preventDefault(),s.stopPropagation()},onClick:_r,"data-track":"ai_input_click_upload",children:c.jsx(ba,{size:18})})}),c.jsx(Xe,{content:r==="zh"?"从素材库选择":"Select from library",showArrow:!1,children:c.jsx("button",{className:"ai-input-bar__library-btn",onMouseDown:s=>{s.preventDefault(),s.stopPropagation()},onClick:()=>qt(!0),"data-track":"ai_input_click_library",children:c.jsx(va,{size:18})})}),c.jsx(Oa,{value:Ze,onChange:Ir,disabled:Te,language:r,variant:"compact",className:"ai-input-bar__knowledge-selector"}),c.jsx(bi,{value:_,onSelect:Ke,disabled:Te}),_==="agent"&&c.jsx(hi,{value:fe,onSelect:xn,onSelectSkill:Tr,onAddSkill:xr,disabled:Te}),c.jsx(An,{selectedModel:z,selectedSelectionKey:je(z,B),onSelect:Mr,onSelectModel:Cr,language:r,models:bn,header:r==="zh"?_==="agent"?"选择文本模型 (↑↓ Tab)":"选择模型 (↑↓ Tab)":_==="agent"?"Select text model (↑↓ Tab)":"Select model (↑↓ Tab)",isOpen:Hs,onOpenChange:pr}),_==="agent"&&fe!==et&&ft.includes("image")&&c.jsx(An,{selectedModel:Oe,selectedSelectionKey:je(Oe,Pe),onSelect:(s,a)=>ns("image",s,a),onSelectModel:s=>ss("image",s),language:r,models:$t,header:r==="zh"?"选择图片模型 (↑↓ Tab)":"Select image model (↑↓ Tab)"}),_==="agent"&&fe!==et&&ft.includes("video")&&c.jsx(An,{selectedModel:Le,selectedSelectionKey:je(Le,Ee),onSelect:(s,a)=>ns("video",s,a),onSelectModel:s=>ss("video",s),language:r,models:Vt,header:r==="zh"?"选择视频模型 (↑↓ Tab)":"Select video model (↑↓ Tab)"}),_==="agent"&&fe!==et&&ft.includes("audio")&&c.jsx(An,{selectedModel:We,selectedSelectionKey:je(We,Ae),onSelect:(s,a)=>ns("audio",s,a),onSelectModel:s=>ss("audio",s),language:r,models:Kt,header:r==="zh"?"选择音频模型 (↑↓ Tab)":"Select audio model (↑↓ Tab)"}),_!=="agent"&&Jt.length>0&&c.jsx(Ua,{selectedParams:De,onParamChange:Pr,compatibleParams:Jt,modelId:z,language:r,isOpen:Bs,onOpenChange:fr},z),_!=="agent"&&_!=="text"&&_!=="audio"&&c.jsx(vi,{value:Zt,onSelect:Er,disabled:Te,isOpen:Fs,onOpenChange:hr}),c.jsx("div",{className:"ai-input-bar__bottom-spacer"}),c.jsx("button",{className:Lt("ai-input-bar__send-btn",{active:as,loading:Te,"ai-input-bar__send-btn--guide":Or}),onMouseDown:s=>{s.preventDefault(),s.stopPropagation()},onClick:()=>os("button"),disabled:!as||Te,"data-track":"ai_input_click_send","data-track-params":zr,"data-testid":"ai-send-btn",children:c.jsx(ws,{size:18})})]}),c.jsxs("div",{className:Lt("ai-input-bar__input-area",{"ai-input-bar__input-area--expanded":rt,"ai-input-bar__input-area--long-text":Ve}),children:[ce.length>0&&c.jsx("div",{className:"ai-input-bar__content-preview",children:c.jsx(La,{items:ce,language:r,enableHoverPreview:!0,onRemove:Sr,removableStartIndex:st.length})}),c.jsxs("div",{className:"ai-input-bar__prompt-row",children:[c.jsxs("div",{className:"ai-input-bar__rich-input",children:[cr?c.jsx(Xe,{content:eo,showArrow:!1,children:c.jsx("button",{type:"button",className:Lt("ai-input-bar__prompt-expand-btn",{"ai-input-bar__prompt-expand-btn--active":Ve}),"aria-label":eo,onMouseDown:s=>{s.preventDefault(),s.stopPropagation()},onClick:Nr,disabled:Te,children:Ve?c.jsx(ka,{size:13,"aria-hidden":"true"}):c.jsx(Sa,{size:13,"aria-hidden":"true"})})}):null,c.jsx("textarea",{ref:Me,className:Lt("ai-input-bar__input",{"ai-input-bar__input--focused":rt,"ai-input-bar__input--long-text":Ve}),value:de,onChange:jr,onKeyDown:Ar,onFocus:Dr,onBlur:Rr,placeholder:_==="agent"?r==="zh"?"输入指令,让 Agent 为你工作...":"Type instructions for Agent...":_==="text"?r==="zh"?"输入你想生成的文本内容、文章、摘要或 Markdown":"Describe the text, article, summary, or markdown you want":_==="audio"?Lr?r==="zh"?"已有文本,无需额外提示词,直接发送":"Text already selected. No extra prompt needed, just send":r==="zh"?"描述你想要生成的音乐、风格、歌词或情绪":"Describe the music, style, lyrics, or mood you want":r==="zh"?`描述你想要创建的${_==="image"?"图片":"视频"}`:`Describe the ${_==="image"?"image":"video"} you want to create`,rows:Ve?Bi:rt?tr:Li,disabled:Te,"data-testid":"ai-input-textarea"})]}),c.jsx(Qa,{generationType:_,onSelectPrompt:gr,language:r,onBeforeOpenMyPrompts:n,extraActions:rt?c.jsx(Wa,{className:"prompt-history-popover__action-btn",originalPrompt:de,language:r,scenarioId:`ai-input.${_}`,disabled:Te,allowStructuredMode:!0,onOpenChange:ir,onMouseDown:s=>{s.preventDefault(),s.stopPropagation(),ot(!0)},onApply:s=>{nt(s),ot(!0),requestAnimationFrame(()=>{var a;(a=Me.current)==null||a.focus()})}}):null})]})]})]}),Gs&&c.jsx(Ga,{isOpen:Gs,onClose:()=>qt(!1),mode:Ma.SELECT,filterType:uo.IMAGE,onSelect:yr})]})]})});or.displayName="AIInputBar";function cc({isDataReady:e,activationKey:t,onEnableToolWindows:n,onEnableRuntime:d}){const r=o.useRef(null);return o.useEffect(()=>{if(t<=0)return;const l=window.setTimeout(()=>{var h;const i=(h=r.current)==null?void 0:h.querySelector('[data-testid="ai-input-textarea"]');i==null||i.focus()},0);return()=>{window.clearTimeout(l)}},[t]),c.jsx(Da,{children:c.jsx(Pa,{children:c.jsx("div",{ref:r,children:c.jsx(or,{isDataReady:e,onEnableToolWindows:n,onEnableRuntime:d})})})})}export{cc as DeferredAIInputBar,cc as default};
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css","./ai-chat-DyV67c_f.css","./tool-windows-CegtMid1.css"])))=>i.map(i=>d[i]);
2
- import{_ as a}from"./startup-runtime-DTmhLESk.js";import{ck as M,j as t,r as n}from"./startup-app-BRF2LNMY.js";const F=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a2),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),U=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a3),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),W=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a4),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredMediaLibraryModal}))),X=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a5),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),q=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a6),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.VersionUpdatePrompt}))),G=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a7),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.PerformancePanel}))),H=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a8),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredSyncSettings}))),J=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.a9),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CommandPalette}))),K=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.aa),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CanvasSearch}))),N=n.lazy(()=>a(()=>import("./tool-windows-Bqfr0PWo.js").then(e=>e.ab),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolWinBoxManager})));function Z({board:e,value:S,containerRef:o,versionUpdateEnabled:v,performancePanelEnabled:D,toolWindowManagerEnabled:f,projectDrawerOpen:u,toolboxDrawerOpen:p,mediaLibraryOpen:_,mediaLibraryConfig:l,backupRestoreOpen:h,cloudSyncOpen:m,onBoardSwitch:r,setProjectDrawerOpen:T,setToolboxDrawerOpen:O,setMediaLibraryOpen:k,setBackupRestoreOpen:V,setCloudSyncOpen:A,handleOpenMediaLibrary:I,handleBeforeSwitch:x,onCreateProjectForMemory:R}){const{appState:P,setAppState:d}=M(),j=P.openCommandPalette||!1,E=P.openCanvasSearch||!1;return t.jsxs(t.Fragment,{children:[_&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(W,{isOpen:_,onClose:()=>k(!1),mode:l==null?void 0:l.mode,filterType:l==null?void 0:l.filterType,onSelect:l==null?void 0:l.onSelect,selectButtonText:l==null?void 0:l.selectButtonText})}),h&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(X,{open:h,onOpenChange:V,container:o.current,onBeforeImport:async()=>{await x()},onSwitchBoard:async(s,i)=>{const{workspaceService:w}=await a(async()=>{const{workspaceService:z}=await import("./startup-app-BRF2LNMY.js").then(B=>B.nX);return{workspaceService:z}},__vite__mapDeps([0]),import.meta.url),c=await w.switchBoard(s);c&&r&&(i&&(c.viewport=i),r(c))}})}),m&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(H,{visible:m,onClose:()=>A(!1)})}),v&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(q,{})}),f&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(N,{})}),j&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(J,{open:j,onClose:()=>{d(s=>({...s,openCommandPalette:!1}))},board:e,container:o.current})}),E&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(K,{open:E,onClose:()=>{d(s=>({...s,openCanvasSearch:!1}))},board:e})}),D&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(G,{container:o.current,onCreateProject:R,elements:(e==null?void 0:e.children)||S})}),u&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(F,{isOpen:u,onOpenChange:T,onBeforeSwitch:x,onBoardSwitch:r,onOpenMediaLibrary:I})}),p&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(U,{isOpen:p,onOpenChange:O})})]})}export{Z as DrawnixDeferredFeatures,Z as default};
2
+ import{_ as a}from"./startup-runtime-DTmhLESk.js";import{ck as M,j as t,r as n}from"./startup-app-eD_rQhSh.js";const F=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a1),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),U=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a2),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),W=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a3),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredMediaLibraryModal}))),q=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a4),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),G=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a5),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.VersionUpdatePrompt}))),H=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a6),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.PerformancePanel}))),J=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a7),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.DeferredSyncSettings}))),K=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a8),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CommandPalette}))),N=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.a9),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.CanvasSearch}))),Q=n.lazy(()=>a(()=>import("./tool-windows-CmgL3thd.js").then(e=>e.aa),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.ToolWinBoxManager})));function Z({board:e,value:S,containerRef:o,versionUpdateEnabled:v,performancePanelEnabled:D,toolWindowManagerEnabled:f,projectDrawerOpen:u,toolboxDrawerOpen:p,mediaLibraryOpen:_,mediaLibraryConfig:l,backupRestoreOpen:h,cloudSyncOpen:m,onBoardSwitch:r,setProjectDrawerOpen:T,setToolboxDrawerOpen:O,setMediaLibraryOpen:k,setBackupRestoreOpen:V,setCloudSyncOpen:A,handleOpenMediaLibrary:I,handleBeforeSwitch:x,onCreateProjectForMemory:R}){const{appState:P,setAppState:d}=M(),j=P.openCommandPalette||!1,E=P.openCanvasSearch||!1;return t.jsxs(t.Fragment,{children:[_&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(W,{isOpen:_,onClose:()=>k(!1),mode:l==null?void 0:l.mode,filterType:l==null?void 0:l.filterType,onSelect:l==null?void 0:l.onSelect,selectButtonText:l==null?void 0:l.selectButtonText})}),h&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(q,{open:h,onOpenChange:V,container:o.current,onBeforeImport:async()=>{await x()},onSwitchBoard:async(s,i)=>{const{workspaceService:w}=await a(async()=>{const{workspaceService:z}=await import("./startup-app-eD_rQhSh.js").then(B=>B.o3);return{workspaceService:z}},__vite__mapDeps([0]),import.meta.url),c=await w.switchBoard(s);c&&r&&(i&&(c.viewport=i),r(c))}})}),m&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(J,{visible:m,onClose:()=>A(!1)})}),v&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(G,{})}),f&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(Q,{})}),j&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(K,{open:j,onClose:()=>{d(s=>({...s,openCommandPalette:!1}))},board:e,container:o.current})}),E&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(N,{open:E,onClose:()=>{d(s=>({...s,openCanvasSearch:!1}))},board:e})}),D&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(H,{container:o.current,onCreateProject:R,elements:(e==null?void 0:e.children)||S})}),u&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(F,{isOpen:u,onOpenChange:T,onBeforeSwitch:x,onBoardSwitch:r,onOpenMediaLibrary:I})}),p&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(U,{isOpen:p,onOpenChange:O})})]})}export{Z as DrawnixDeferredFeatures,Z as default};