aitu-app 0.6.82 → 0.6.83

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 (101) hide show
  1. package/README.md +3 -3
  2. package/assets/CanvasAudioPlayer-COGs6SbE.js +2 -0
  3. package/assets/ChatDrawer-BjO2MnSZ.js +11 -0
  4. package/assets/ChatMessagesArea-CEucTOYp.js +8 -0
  5. package/assets/DeferredAIInputBar-COZcYmQu.js +8 -0
  6. package/assets/DrawnixDeferredFeatures-yhCrW499.js +2 -0
  7. package/assets/KnowledgeBaseContent-oKH91ZUN.js +53 -0
  8. package/assets/{MVCreator-DM_I1mJr.js → MVCreator-Cwei5n1a.js} +10 -10
  9. package/assets/MermaidRenderer-C2mk8jSz.js +2 -0
  10. package/assets/ModelBenchmarkWorkbench-BBiBKw-2.js +2 -0
  11. package/assets/ModelSelector-D7330mV9.js +1 -0
  12. package/assets/MusicAnalyzer-CaXoJukK.js +6 -0
  13. package/assets/MusicAnalyzer-DuSLoDYi.js +1 -0
  14. package/assets/PromptHistoryTool-BjHz-R0-.js +2 -0
  15. package/assets/ResizableDivider-BDI7_JH8.js +1 -0
  16. package/assets/TaskQueuePanel-BTbpPChN.js +1 -0
  17. package/assets/{VideoAnalyzer-D2uuXL5i.js → VideoAnalyzer-CvS---Jp.js} +2 -2
  18. package/assets/ai-generation-preferences-service-B14EtlzO.js +1 -0
  19. package/assets/{batch-image-generation-CNNwXxgK.js → batch-image-generation-BfeEJCgC.js} +5 -6
  20. package/assets/board-utils-CpAtoKn2.js +1 -0
  21. package/assets/{canvas-insertion-C-BRaM5S.js → canvas-insertion-BzIbRGcU.js} +3 -3
  22. package/assets/{clipper-Cb0TKfsP.js → clipper-p8ORpTD7.js} +1 -1
  23. package/assets/diagram-engines-BAca1QyG.js +2088 -0
  24. package/assets/{editor-engines-DGOT7Xqo.js → editor-engines-BtXR1R6e.js} +10 -10
  25. package/assets/index-BZxcmQk6.js +1 -0
  26. package/assets/index-BhIPuqvt.js +2 -0
  27. package/assets/index-CEkJlY_n.js +1 -0
  28. package/assets/{index-Bgp2wxvA.js → index-CrbtBXjZ.js} +2 -2
  29. package/assets/index-Cyi_RBqN.js +271 -0
  30. package/assets/{index-o5qBH2kC.js → index-Cz4MoLGQ.js} +8 -8
  31. package/assets/index-Dl-kSsRd.js +1 -0
  32. package/assets/{index-BbDNsPPx.js → index-eO62kWA6.js} +3 -3
  33. package/assets/kb-search-engine-BCA6z_98.js +1 -0
  34. package/assets/markdown-to-drawnix-BSgd_MRJ.js +90 -0
  35. package/assets/mermaid-to-drawnix-DkioZkcw.js +7 -0
  36. package/assets/model-benchmark-launcher-BIjsOG6q.js +1 -0
  37. package/assets/{office-data-2Ik8Wb2D.js → office-data-CVQuXBMb.js} +5 -5
  38. package/assets/photo-wall-splitter-BB-4V662.js +1 -0
  39. package/assets/{ppt-generation-BLs-dVnA.js → ppt-generation-CcWMarvM.js} +9 -9
  40. package/assets/{retry-image-BMMnhw_0.js → retry-image-6-c7PNQ8.js} +2 -2
  41. package/assets/settings-dialog-Cg0fzYdq.js +1 -0
  42. package/assets/skill-dsl-parser-Wxj3iyHM.js +3 -0
  43. package/assets/{diagram-engines-CGOhfK6V.css → startup-app-B7ypM2x4.css} +1 -1
  44. package/assets/startup-app-DC9IB1KI.js +2371 -0
  45. package/assets/startup-runtime-DTmhLESk.js +1 -0
  46. package/assets/tool-windows-CDLejk69.css +1 -0
  47. package/assets/tool-windows-Do7Od789.js +380 -0
  48. package/assets/ttd-dialog-BjGXdaRy.js +6 -0
  49. package/assets/ttd-dialog-DZBNihVL.css +1 -0
  50. package/assets/ttd-dialog-submit-shortcut-DyioEoKX.css +1 -0
  51. package/assets/ttd-dialog-submit-shortcut-R21LX75U.js +1 -0
  52. package/assets/{useCharacters-D3PdMQMn.js → useCharacters-BUnFn1Td.js} +2 -2
  53. package/assets/useWorkflowSubmission-BLZubY71.js +44 -0
  54. package/assets/video-analyze-KCWkdBAl.js +1 -0
  55. package/assets/{video-generation-C2GITib6.js → video-generation-rHwGvZFJ.js} +2 -2
  56. package/assets/video-recovery-service-DZv2DmY0.js +1 -0
  57. package/assets/workflow-generation-utils-CWjrNGe4.js +3 -0
  58. package/assets/workflow-submission-service-DWibArfo.js +4 -0
  59. package/changelog.json +13 -0
  60. package/idle-prefetch-manifest.json +484 -194
  61. package/manifest.json +3 -3
  62. package/package.json +1 -1
  63. package/precache-manifest.json +6 -6
  64. package/sw.js +1 -1
  65. package/version.json +5 -3
  66. package/assets/CanvasAudioPlayer-EQjMjqlc.js +0 -2
  67. package/assets/ChatDrawer-CbBhCIU_.js +0 -11
  68. package/assets/ChatMessagesArea-DatNDD1n.js +0 -7
  69. package/assets/DeferredAIInputBar-rIx0c8Qv.js +0 -8
  70. package/assets/DrawnixDeferredFeatures-C8aKfyQG.js +0 -2
  71. package/assets/KnowledgeBaseContent-vj5G-Ele.js +0 -53
  72. package/assets/ModelBenchmarkWorkbench-CfgAcLzz.js +0 -3
  73. package/assets/MusicAnalyzer-C-ZI5UZd.js +0 -6
  74. package/assets/MusicAnalyzer-DcDwJ88i.js +0 -1
  75. package/assets/PromptHistoryTool-DtvW3bCO.js +0 -2
  76. package/assets/ResizableDivider-DYCCpuYw.js +0 -1
  77. package/assets/TaskQueuePanel-DE2L1_EL.js +0 -1
  78. package/assets/ai-generation-preferences-service-BZMqxTjU.js +0 -1
  79. package/assets/diagram-engines-DmAewdsu.js +0 -6462
  80. package/assets/index-BDFn0Sob.js +0 -1
  81. package/assets/index-BVyqBBIM.js +0 -1
  82. package/assets/index-DDzCo7oj.js +0 -195
  83. package/assets/index-DQQV1ik6.js +0 -2
  84. package/assets/index-mUUunEI1.js +0 -1
  85. package/assets/main-B2ZrUywM.js +0 -37
  86. package/assets/main-CRPCRx46.css +0 -1
  87. package/assets/model-benchmark-launcher-QpuZmCET.js +0 -1
  88. package/assets/photo-wall-splitter-BD8mt52h.js +0 -1
  89. package/assets/settings-dialog-xu3d4MX_.js +0 -1
  90. package/assets/shared-runtime-DBavnB0U.js +0 -5
  91. package/assets/skill-dsl-parser-BAv2yCP9.js +0 -68
  92. package/assets/startup-runtime-BbuNXj6O.js +0 -1
  93. package/assets/tool-windows-CqSDeXz5.css +0 -1
  94. package/assets/tool-windows-DV-j2p51.js +0 -499
  95. package/assets/ttd-dialog-BVnF62mS.css +0 -1
  96. package/assets/ttd-dialog-CwkEQ_6x.js +0 -6
  97. package/assets/useWorkflowSubmission-BIFN-qvq.js +0 -70
  98. package/assets/video-analyze-BeuyAh9W.js +0 -1
  99. package/assets/video-recovery-service-BBDuz2L1.js +0 -1
  100. package/assets/workflow-generation-utils-Vh2FVA3M.js +0 -3
  101. package/assets/workflow-submission-service-BRb6CPDr.js +0 -4
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Opentu CDN Assets v0.6.82
1
+ # Opentu CDN Assets v0.6.83
2
2
 
3
3
  > 静态资源包,不含 HTML 文件
4
4
 
5
- - unpkg: https://unpkg.com/aitu-app@0.6.82/
6
- - jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.82/
5
+ - unpkg: https://unpkg.com/aitu-app@0.6.83/
6
+ - jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.83/
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-B7ypM2x4.css"])))=>i.map(i=>d[i]);
2
+ import{_ as ke}from"./startup-runtime-DTmhLESk.js";import{P as n,S as t,aS as he,a7 as C,il as Ae,e_ as Se,bE as Te,bF as Le,aW as ue,aU as J,cB as U,cr as Ee,at as de,cc as Ne,bW as Ce,bJ as Me,cv as Re,cD as oe,cE as pe,bb as ie,cw as _e,ai as De,df as $e,cF as ze,cu as Oe,as as Ue,cG as Fe,cH as fe,cI as qe,cC as le,im as Ye,io as Ve,ip as Be,ax as He,cK as We,cL as Qe,cM as Ke,cN as Xe,cO as Ge}from"./startup-app-DC9IB1KI.js";import{K as Je,L as Ze,N as et,O as ye,P as Z,Q as tt}from"./tool-windows-Do7Od789.js";const me=5;function ve(e,i,s){const c=Math.max(0,window.innerWidth-i),f=Math.max(0,window.innerHeight-s);return{x:Math.max(0,Math.min(e.x,c)),y:Math.max(0,Math.min(e.y,f))}}function at(e){try{const i=localStorage.getItem(e);if(!i)return null;const s=JSON.parse(i);if(typeof s.x=="number"&&typeof s.y=="number")return s}catch{}return null}function nt(e,i){try{localStorage.setItem(e,JSON.stringify(i))}catch{}}function st(e){const{storageKey:i,enabled:s=!0}=e,[c,f]=n.useState(()=>s?at(i):null),[v,b]=n.useState(!1),w=n.useRef(!1),h=n.useRef(null),j=n.useRef(null),_=n.useCallback(y=>{if(!s||y.button!==0)return;const m=j.current;if(!m)return;const p=m.getBoundingClientRect();h.current={startPointerX:y.clientX,startPointerY:y.clientY,startElX:p.left,startElY:p.top,activated:!1,frameId:0}},[s]);n.useEffect(()=>{if(!s)return;const y=p=>{const u=h.current;if(!u)return;const g=p.clientX-u.startPointerX,M=p.clientY-u.startPointerY;if(!u.activated){if(Math.abs(g)<me&&Math.abs(M)<me)return;u.activated=!0,b(!0)}cancelAnimationFrame(u.frameId),u.frameId=requestAnimationFrame(()=>{const S=j.current;if(!S)return;const d=ve({x:u.startElX+g,y:u.startElY+M},S.offsetWidth,S.offsetHeight);f(d)})},m=()=>{const p=h.current;if(!p)return;cancelAnimationFrame(p.frameId);const u=p.activated;h.current=null,b(!1),u&&(w.current=!0,requestAnimationFrame(()=>{w.current=!1}),f(g=>(g&&nt(i,g),g)))};return window.addEventListener("pointermove",y),window.addEventListener("pointerup",m),()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",m)}},[s,i]),n.useEffect(()=>{if(!s||!c)return;const y=()=>{const m=j.current;m&&f(p=>p&&ve(p,m.offsetWidth,m.offsetHeight))};return window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[s,!!c]);const P=n.useCallback(()=>{f(null);try{localStorage.removeItem(i)}catch{}},[i]);return{position:c,isDragging:v,wasDraggedRef:w,elementRef:j,handlePointerDown:_,resetPosition:P}}const ot=({volume:e,onVolumeChange:i})=>{const s=n.useRef(null),c=n.useRef(null),f=n.useRef(!1),v=n.useRef(!1),b=n.useRef(!1),[w,h]=n.useState(!1),[j,_]=n.useState(!1),[P,y]=n.useState(!1),m=Math.round(e*100),p={"--canvas-audio-progress":`${e*100}%`},u=()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},g=()=>{u(),h(!0)},M=()=>{u(),h(d=>!d)},S=()=>{u(),!(v.current||b.current)&&(c.current=window.setTimeout(()=>{h(!1)},180))};return n.useEffect(()=>{v.current=j},[j]),n.useEffect(()=>{b.current=P},[P]),n.useEffect(()=>()=>u(),[]),n.useEffect(()=>{if(!w)return;const d=x=>{var k;(k=s.current)!=null&&k.contains(x.target)||(u(),h(!1),y(!1),_(!1),f.current=!1)};return document.addEventListener("pointerdown",d,!0),()=>document.removeEventListener("pointerdown",d,!0)},[w]),n.useEffect(()=>{if(!P)return;const d=()=>{b.current=!1,y(!1),v.current||(u(),c.current=window.setTimeout(()=>{h(!1)},180))};return window.addEventListener("pointerup",d),()=>window.removeEventListener("pointerup",d)},[P]),t.jsx("div",{ref:s,className:he("canvas-audio-player__volume",{"canvas-audio-player__volume--expanded":w}),onPointerDown:d=>d.stopPropagation(),onMouseEnter:()=>{v.current=!0,_(!0),u()},onMouseLeave:()=>{v.current=!1,_(!1),S()},onBlur:d=>{var k;const x=d.relatedTarget;x&&((k=s.current)!=null&&k.contains(x))||S()},children:t.jsxs("div",{className:"canvas-audio-player__volume-shell",children:[t.jsx("div",{className:"canvas-audio-player__volume-slider-wrap",children:t.jsx("input",{type:"range",min:0,max:1,step:.01,value:e,onFocus:g,onPointerDown:d=>{d.stopPropagation(),b.current=!0,y(!0),g()},onChange:d=>i(Number(d.target.value)),className:"canvas-audio-player__slider canvas-audio-player__slider--volume",style:p,"aria-label":"Playback volume","aria-valuetext":`${m}%`})}),t.jsxs("span",{className:"canvas-audio-player__volume-value",children:[m,"%"]}),t.jsx(C,{content:"音量",children:t.jsx("button",{type:"button",className:"canvas-audio-player__volume-toggle",onPointerDown:d=>{d.stopPropagation(),f.current=!0},onClick:()=>{f.current=!1,M()},onFocus:()=>{f.current||g()},onBlur:()=>{f.current=!1},"aria-label":"Volume controls","aria-expanded":w,children:e<=.01?t.jsx(Ae,{size:16}):t.jsx(Se,{size:16})})})]})})},ge="asset:";function it(e){var i;return(i=e==null?void 0:e.elementId)!=null&&i.startsWith(ge)?e.elementId.slice(ge.length):null}function xe(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return`${s}:${String(c).padStart(2,"0")}`}function lt(e){var s;const i=((s=e.segments[e.segments.length-1])==null?void 0:s.endMs)||0;return xe(i/1e3)}const rt=({queue:e,activeQueueIndex:i,queueSource:s,activePlaylistId:c,playing:f=!1,activeReadingSourceId:v,onSelect:b,onPlayAllTracksItem:w})=>{const{assets:h}=Te(),{playlists:j,playlistItems:_,favoriteAssetIds:P,createPlaylist:y,addAssetToPlaylist:m,removeAssetFromPlaylist:p,toggleFavorite:u}=Le(),{contextMenu:g,openAt:M,close:S}=Je(),[d,x]=n.useState(!1),[k,E]=n.useState(""),[F,T]=n.useState(null),{noteMetas:$,loadReadingSource:Q,buildReadingQueue:K}=Ze(),[q,Y]=n.useState(s==="reading"?ue:J),V=q===ue,R=s==="playlist"&&c?c:J,L=e.filter(a=>!U(a)),ee=et(L),X=a=>{const o=it(a);if(o)return o;if(!(a!=null&&a.audioUrl))return null;const r=h.find(I=>I.type===Me.AUDIO&&I.url===a.audioUrl);return(r==null?void 0:r.id)||null},B=n.useMemo(()=>new Set(R!==J?(_[R]||[]).map(a=>a.assetId?Ee({kind:"asset",assetId:a.assetId}):null).filter(a=>!!a):[]),[_,R]),D=n.useCallback(async a=>{if(w){w(a);return}const o=await Q(a);o&&(await K(a),b(o))},[w,Q,K,b]),z=n.useMemo(()=>$.map(a=>({id:a.id,title:a.title||"未命名笔记",subtitle:new Date(a.updatedAt).toLocaleDateString("zh-CN"),canFavorite:!1,isActive:(v==null?void 0:v.includes(a.id))===!0,isPlaying:f&&(v==null?void 0:v.includes(a.id))===!0})),[$,v,f]);return s==="reading"?t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(ye,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:L.length,allTracksCount:$.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?z.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(de,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:z,onSelect:a=>void D(a.id),onTogglePlayback:a=>void D(a.id),showPlaybackIndicator:!0}):t.jsx(Z,{className:"canvas-audio-player__playlist-list audio-track-list--queue",items:e.map((a,o)=>{const r=a;return{id:r.readingSourceId,title:r.title||"朗读轨道",subtitle:lt(r),previewImageUrl:r.previewImageUrl,isActive:o===i,isPlaying:o===i,canFavorite:!1}}),onSelect:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&b(o)},onTogglePlayback:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&b(o)},showPlaybackIndicator:!0})]}):t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(ye,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:L.length,allTracksCount:$.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?z.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(de,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:z,onSelect:a=>void D(a.id),onTogglePlayback:a=>void D(a.id),showPlaybackIndicator:!0}):t.jsx(Z,{className:"canvas-audio-player__playlist-list audio-track-list--queue",items:L.map((a,o)=>{const r=X(a);return{id:`${a.audioUrl}-${o}`,title:a.title||"未命名音频",subtitle:xe(ee.get(a.audioUrl)??a.duration),previewImageUrl:a.previewImageUrl,isActive:o===i,isPlaying:o===i,isFavorite:r?P.has(r):!1,canFavorite:!!r}}),onSelect:a=>{const o=L.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&b(o)},onContextMenu:(a,o)=>{const r=L.find((H,te)=>`${H.audioUrl}-${te}`===a.id),I=X(r);I&&(o.preventDefault(),o.stopPropagation(),M(o.clientX,o.clientY,{kind:"asset",assetId:I}))},onToggleFavorite:a=>{const o=L.find((I,H)=>`${I.audioUrl}-${H}`===a.id),r=X(o);r&&u(r)},onTogglePlayback:a=>{const o=L.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&b(o)},showFavoriteButton:!0,showPlaybackIndicator:!0}),t.jsx(tt,{contextMenu:g?{x:g.x,y:g.y,item:g.payload}:null,playlists:j,playlistItems:_,favoriteAssetIds:P,selectedPlaylistId:R===J?null:R,currentPlaylistItemKeys:B,onClose:S,onToggleFavorite:a=>void u(a),onAddToPlaylist:(a,o)=>{a.kind==="asset"&&m(a.assetId,o)},onRemoveFromPlaylist:(a,o)=>{a.kind==="asset"&&p(a.assetId,o)},onCreatePlaylistAndAdd:a=>{a.kind==="asset"&&(T(a.assetId),E(""),x(!0))}}),t.jsx(Ne,{visible:d,header:"新建播放列表",onClose:()=>x(!1),onConfirm:async()=>{const a=await y(k);F&&await m(F,a.id),x(!1),E(""),T(null)},onCancel:()=>{x(!1),T(null)},confirmBtn:"确定",cancelBtn:"取消",children:t.jsx(Ce,{value:k,onChange:a=>E(String(a)),placeholder:"请输入播放列表名称"})})]})},we={sequential:t.jsx(Ge,{size:14}),"list-loop":t.jsx(Xe,{size:14}),"single-loop":t.jsx(Ke,{size:14}),shuffle:t.jsx(Qe,{size:14})},ct=Object.keys(le).map(e=>({value:e,content:le[e],prefixIcon:we[e]}));function ut(e,i){return We(i).map(s=>{const c=_e(s),f=Math.abs(s-e)<.001;return{value:s,content:f?`✓ ${c}`:c}})}function be(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return"--:--";const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return`${s}:${String(c).padStart(2,"0")}`}const mt=()=>{const e=Re(),i=n.useRef(null),[s,c]=n.useState(!1),[f,v]=n.useState(()=>{const l=oe.getToolState(pe);return(l==null?void 0:l.status)==="open"}),[b,w]=n.useState(()=>{try{return localStorage.getItem(ie.AUDIO_PLAYER_LAYOUT)==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[h,j]=n.useState(()=>typeof window<"u"?window.innerWidth:1024);n.useEffect(()=>{const l=()=>j(window.innerWidth);return window.addEventListener("resize",l),window.addEventListener("orientationchange",l),()=>{window.removeEventListener("resize",l),window.removeEventListener("orientationchange",l)}},[]);const _=h<=768?"vertical":b,[P,y]=n.useState(null),m=h<=768,{position:p,isDragging:u,wasDraggedRef:g,elementRef:M,handlePointerDown:S}=st({storageKey:ie.AUDIO_PLAYER_POSITION,enabled:!m}),d=n.useMemo(()=>!e.duration||e.duration<=0?0:Math.max(0,Math.min(100,e.currentTime/e.duration*100)),[e.currentTime,e.duration]),x=Number.isFinite(e.currentTime)?e.currentTime:0,k=Number.isFinite(e.duration)?e.duration:0,E=be(x),F=be(k),T=e.activeQueueIndex>=0?e.queue[e.activeQueueIndex]:null,$=e.activeTitle||(U(T)?T.title:void 0),Q=e.activePreviewImageUrl||(U(T)?T.previewImageUrl:void 0),K=e.activeQueueIndex>0,q=e.activeQueueIndex>=0&&e.activeQueueIndex<e.queue.length-1,Y=e.queue.length>1&&e.activeQueueIndex>=0,V=Y?`${e.activeQueueIndex+1}/${e.queue.length}`:null,R=e.queueSource==="playlist"?e.activePlaylistName||"播放列表":e.activePlaylistName||(e.queueSource==="reading"?"朗读轨道":"画布音频"),L=Y?`${R} ${e.activeQueueIndex+1} / ${e.queue.length}`:R,ee=V?`${V} · ${E} / ${F}`:`${E} / ${F}`,B=e.queueSource==="reading"&&(!!e.activeReadingSourceId||T!==null&&U(T))||!!e.activeAudioUrl,D=e.mediaType==="audio",z=e.mediaType==="reading"?"reading":"audio",a=le[e.playbackMode],o=we[e.playbackMode],r=n.useMemo(()=>ut(e.effectivePlaybackRate,z),[e.effectivePlaybackRate,z]),I=_e(e.effectivePlaybackRate),H=`${e.mediaType==="reading"?"语音速度":"播放速度"} ${I}`,te={"--canvas-audio-progress":`${d}%`},Pe=n.useCallback(()=>{w(l=>{const A=l==="horizontal"?"vertical":"horizontal";try{localStorage.setItem(ie.AUDIO_PLAYER_LAYOUT,A)}catch{}return A})},[]),Ie=n.useCallback(async()=>{try{e.playing?e.pausePlayback():await e.resumePlayback()}catch{}},[e]);if(n.useEffect(()=>{if(!B){c(!1),y(null);return}let l=0;const A=()=>{const ce=document.querySelector(".ai-input-bar__container");if(!(ce instanceof HTMLElement)){y(null);return}const se=ce.getBoundingClientRect(),G={left:Math.round(se.left),width:Math.round(se.width),bottom:Math.max(0,Math.round(window.innerHeight-se.top))};y(W=>W&&W.left===G.left&&W.width===G.width&&W.bottom===G.bottom?W:G)},N=()=>{window.cancelAnimationFrame(l),l=window.requestAnimationFrame(A)},ae=document.querySelector(".ai-input-bar__container"),ne=document.querySelector(".ai-input-bar"),O=typeof ResizeObserver<"u"?new ResizeObserver(()=>N()):null;return O&&ae instanceof HTMLElement&&O.observe(ae),O&&ne instanceof HTMLElement&&ne!==ae&&O.observe(ne),N(),window.addEventListener("resize",N),window.addEventListener("orientationchange",N),()=>{window.cancelAnimationFrame(l),window.removeEventListener("resize",N),window.removeEventListener("orientationchange",N),O==null||O.disconnect()}},[B]),n.useEffect(()=>{if(!s)return;const l=A=>{var N;(N=i.current)!=null&&N.contains(A.target)||c(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[s]),n.useEffect(()=>{M.current=i.current}),n.useEffect(()=>{const l=oe.observeToolStates().subscribe(()=>{const A=oe.getToolState(pe);v((A==null?void 0:A.status)==="open")});return()=>l.unsubscribe()},[]),!B||f)return null;const je=p&&!m?{left:p.x,top:p.y}:{},re={...P?{"--canvas-audio-mobile-left":`${P.left}px`,"--canvas-audio-mobile-width":`${P.width}px`,"--canvas-audio-mobile-offset":`${P.bottom}px`}:{},...je};return t.jsxs("div",{ref:i,className:he("canvas-audio-player",{"canvas-audio-player--playlist-open":s,"canvas-audio-player--positioned":!!p,"canvas-audio-player--dragging":u,"canvas-audio-player--vertical":_==="vertical"}),style:Object.keys(re).length>0?re:void 0,children:[t.jsxs("button",{type:"button",className:"canvas-audio-player__queue-trigger",onPointerDown:S,onClick:()=>{g.current||c(l=>!l)},"aria-expanded":s,"aria-label":"切换播放列表",children:[t.jsx("div",{className:"canvas-audio-player__cover",children:t.jsx(De,{src:Q,alt:$||"Audio cover",fallbackClassName:"canvas-audio-player__cover-fallback",iconSize:16})}),t.jsxs("div",{className:"canvas-audio-player__meta",children:[t.jsx("div",{className:"canvas-audio-player__title",children:$||"未命名音频"}),t.jsxs("div",{className:"canvas-audio-player__subtitle",children:[t.jsx("span",{className:"canvas-audio-player__subtitle-text canvas-audio-player__subtitle-text--desktop",children:L}),t.jsx("span",{className:"canvas-audio-player__subtitle-text canvas-audio-player__subtitle-text--mobile",children:ee})]})]}),t.jsx("span",{className:"canvas-audio-player__queue-indicator","aria-hidden":"true",children:t.jsx($e,{size:14})})]}),t.jsxs("div",{className:"canvas-audio-player__controls",children:[t.jsx(C,{content:"上一首",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--previous",onClick:()=>void e.playPrevious(),disabled:!K,children:t.jsx(ze,{size:14})})}),t.jsx(C,{content:e.playing?"暂停":"播放",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--primary",onClick:()=>void Ie(),children:e.playing?t.jsx(Oe,{size:14}):t.jsx(Ue,{size:14})})}),t.jsx(C,{content:"下一首",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--next",onClick:()=>void e.playNext(),disabled:!q,children:t.jsx(Fe,{size:14})})})]}),t.jsxs("div",{className:"canvas-audio-player__progress",children:[t.jsx("span",{className:"canvas-audio-player__time",children:E}),t.jsx("input",{type:"range",min:0,max:k||0,step:.1,value:Math.min(x,k||x),onChange:l=>{D&&e.seekTo(Number(l.target.value))},className:"canvas-audio-player__slider canvas-audio-player__slider--progress",style:te,"aria-label":D?"Audio progress":"Reading progress",disabled:!D}),t.jsx("span",{className:"canvas-audio-player__time",children:F})]}),t.jsx(ot,{volume:e.volume,onVolumeChange:e.setVolume}),t.jsx(fe,{options:r,trigger:"click",placement:"bottom",minColumnWidth:112,onClick:l=>e.setPlaybackRate(Number(l.value)),children:t.jsx(C,{content:H,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__speed-toggle","aria-label":`切换播放速度,当前${I}`,children:t.jsx(qe,{size:14})})})}),t.jsx(fe,{options:ct,trigger:"click",placement:"bottom",minColumnWidth:132,onClick:l=>e.setPlaybackMode(l.value),children:t.jsx(C,{content:a,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__mode-toggle","aria-label":`切换播放模式,当前${a}`,children:o})})}),t.jsx(C,{content:"打开播放器工具",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__player-switch canvas-audio-player__switch-toggle",onClick:()=>{ke(async()=>{const{openMusicPlayerTool:l}=await import("./startup-app-DC9IB1KI.js").then(A=>A.m8);return{openMusicPlayerTool:l}},__vite__mapDeps([0]),import.meta.url).then(({openMusicPlayerTool:l})=>{l()})},"aria-label":"打开播放器工具",children:t.jsx(Ye,{size:14})})}),t.jsx(C,{content:_==="horizontal"?"切换为垂直布局":"切换为水平布局",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__layout-toggle",onClick:Pe,style:{display:h<=768?"none":""},children:_==="horizontal"?t.jsx(Ve,{size:14}):t.jsx(Be,{size:14})})}),t.jsx(C,{content:"关闭播放器",children:t.jsx("button",{type:"button",className:"canvas-audio-player__close",onClick:e.stopPlayback,children:t.jsx(He,{size:14})})}),s?t.jsx(rt,{queue:e.queue,activeQueueIndex:e.activeQueueIndex,queueSource:e.queueSource,activePlaylistId:e.activePlaylistId,playing:e.playing,activeReadingSourceId:e.activeReadingSourceId,onSelect:l=>{U(l)?e.toggleReadingPlayback(l):e.togglePlayback(l),c(!1)}}):null]})};export{mt as CanvasAudioPlayer};
@@ -0,0 +1,11 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-B7ypM2x4.css","./editor-engines-B8u8agiX.css","./tool-windows-CDLejk69.css","./index-DmlAaIoR.css","./MediaLibrarySidebar-CNCXXhfY.css","./ChatMessagesArea-PlF5AwzD.css"])))=>i.map(i=>d[i]);
2
+ import{_ as st}from"./startup-runtime-DTmhLESk.js";import{R as ce,P as n,S as i,fN as kt,fQ as It,f9 as at,cg as Mt,a7 as Ie,kz as xt,ds as Et,kA as Tt,bc as Ct,b9 as nt,d2 as Xe,cY as X,dY as bt,dZ as At,d_ as vt,kB as Dt,kC as Rt,kD as Nt,kE as jt,cX as We,e5 as Wt,e6 as $t,dX as Lt,e2 as Pt,e3 as Ut,dt as qe,c$ as Ye,kF as zt,bG as Ft,de as Ht,ef as Gt,hH as Kt}from"./startup-app-DC9IB1KI.js";import{am as Vt,X as Bt,Y as Xt,m as qt}from"./tool-windows-Do7Od789.js";import{M as Yt}from"./ModelSelector-D7330mV9.js";import{S as Jt,i as Zt,u as Qt}from"./index-Cyi_RBqN.js";import"./video-generation-rHwGvZFJ.js";import"./canvas-insertion-BzIbRGcU.js";import"./board-utils-CpAtoKn2.js";import"./index-Dl-kSsRd.js";import"./ppt-generation-CcWMarvM.js";import"./kb-search-engine-BCA6z_98.js";import"./video-analyze-KCWkdBAl.js";const rt=ce.memo(({session:t,isActive:e,onSelect:r,onDelete:d,onRename:h})=>{const[l,c]=n.useState(!1),[o,S]=n.useState(t.title),w=n.useRef(null),g=n.useCallback(()=>{l||r()},[r,l]),v=n.useCallback(p=>{p.stopPropagation(),d()},[d]),D=n.useCallback(p=>{p.stopPropagation(),S(t.title),c(!0)},[t.title]),E=n.useCallback(()=>{const p=o.trim();p&&p!==t.title&&h(p),c(!1)},[o,t.title,h]),z=n.useCallback(()=>{S(t.title),c(!1)},[t.title]),_=n.useCallback(p=>{p.key==="Enter"?(p.preventDefault(),E()):p.key==="Escape"&&(p.preventDefault(),z())},[E,z]),M=n.useCallback(p=>{S(p.target.value)},[]);n.useEffect(()=>{l&&w.current&&(w.current.focus(),w.current.select())},[l]);const H=n.useMemo(()=>{const p=new Date(t.updatedAt),Q=new Date;return p.toDateString()===Q.toDateString()?p.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):p.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[t.updatedAt]);return i.jsxs("div",{className:`session-item ${e?"session-item--active":""} ${l?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:g,role:"button",tabIndex:0,onKeyDown:p=>!l&&p.key==="Enter"&&g(),children:[i.jsxs("div",{className:"session-item__content",children:[l?i.jsx("input",{ref:w,className:"session-item__title-input",value:o,onChange:M,onKeyDown:_,onBlur:E,onClick:p=>p.stopPropagation(),maxLength:50}):i.jsx("div",{className:"session-item__title",children:t.title}),i.jsx("div",{className:"session-item__time",children:H})]}),!l&&i.jsxs("div",{className:"session-item__actions",children:[i.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:D,"aria-label":`编辑会话标题: ${t.title}`,children:i.jsx(kt,{size:14})}),i.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:v,"aria-label":`删除会话: ${t.title}`,children:i.jsx(It,{size:14})})]})]})});rt.displayName="SessionItem";const ot=ce.memo(({sessions:t,activeSessionId:e,onSelectSession:r,onNewSession:d,onDeleteSession:h,onRenameSession:l})=>{const[c,o]=ce.useState(null),S=n.useCallback(E=>{r(E)},[r]),w=n.useCallback(E=>{o(E)},[]),g=n.useCallback(()=>{c&&(h(c),o(null))},[c,h]),v=n.useCallback(()=>{o(null)},[]),D=n.useCallback((E,z)=>{l(E,z)},[l]);return i.jsxs("div",{className:"session-list",children:[i.jsxs("div",{className:"session-list__header",children:[i.jsx("span",{className:"session-list__title",children:"会话列表"}),i.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:d,"aria-label":"新建会话",children:[i.jsx(at,{size:14}),i.jsx("span",{children:"新建"})]})]}),i.jsx("div",{className:"session-list__items",children:t.length===0?i.jsx("div",{className:"session-list__empty",children:"暂无会话"}):t.map(E=>i.jsx(rt,{session:E,isActive:E.id===e,onSelect:()=>S(E.id),onDelete:()=>w(E.id),onRename:z=>D(E.id,z)},E.id))}),i.jsx(Mt,{open:c!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:E=>{E||v()},onConfirm:g})]})});ot.displayName="SessionList";const it=ce.memo(({isOpen:t,onClick:e,drawerWidth:r})=>{const d={right:t&&r?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${r-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return i.jsx(Ie,{content:t?"收起对话":"展开对话",children:i.jsx("button",{className:`chat-drawer-trigger ${t?"chat-drawer-trigger--active":""}`,"data-track":t?"chat_click_drawer_close":"chat_click_drawer_open",onClick:e,"aria-label":t?"收起对话":"展开对话","aria-expanded":t,style:d,children:i.jsx(xt,{size:16,className:"chat-drawer-trigger__icon"})})})});it.displayName="ChatDrawerTrigger";const ct=n.forwardRef(({selectedContent:t,onSend:e,disabled:r=!1,placeholder:d="输入消息..."},h)=>{const l=n.useRef(null),c=n.useRef(null),[o,S]=n.useState(""),w=t.length>0,{addHistory:g}=Et();n.useImperativeHandle(h,()=>({setContent:_=>{var M;S(_),(M=l.current)==null||M.focus()},getContent:()=>o,focus:()=>{var _;return(_=l.current)==null?void 0:_.focus()}}),[o]);const v=n.useCallback(()=>{const _=o.trim();if(!_&&t.length===0)return;const M=[];_&&M.push({type:"text",text:_}),t.forEach((p,Q)=>{p.type==="image"||p.type==="graphics"?M.push({type:"data-file",data:{filename:`${p.type}-${Q+1}.png`,mediaType:"image/png",url:p.url||""}}):p.type==="video"&&M.push({type:"data-file",data:{filename:`video-${Q+1}.mp4`,mediaType:"video/mp4",url:p.url||""}})});const H={id:`msg_${Date.now()}`,role:"user",parts:M};_&&g(_,w,"agent"),Promise.resolve(e(H)).catch(p=>{console.error("[EnhancedChatInput] send failed:",p)}),S("")},[o,t,e,g,w]),D=n.useCallback(_=>{_.nativeEvent.isComposing||_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),v())},[v]);n.useEffect(()=>{l.current&&(l.current.style.height="auto",l.current.style.height=`${Math.min(l.current.scrollHeight,120)}px`)},[o]);const E=()=>t.length===0?null:i.jsx("div",{className:"enhanced-chat-input__selection",children:i.jsx(Jt,{items:t,language:"zh",enableHoverPreview:!0})}),z=(o.trim()||t.length>0)&&!r;return i.jsxs("div",{className:"enhanced-chat-input",ref:c,children:[E(),i.jsxs("div",{className:"enhanced-chat-input__form",children:[i.jsx("div",{className:"enhanced-chat-input__input-wrapper",children:i.jsx("textarea",{ref:l,className:"enhanced-chat-input__textarea",value:o,onChange:_=>S(_.target.value),onKeyDown:D,placeholder:w?"描述你想要的效果...":d,disabled:r,rows:4})}),i.jsx("button",{className:`enhanced-chat-input__send ${z?"enhanced-chat-input__send--active":""}`,onClick:v,disabled:!z,"aria-label":"发送",children:i.jsx(Tt,{size:20})})]})]})});ct.displayName="EnhancedChatInput";const ye={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},me={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},ge=nt.createInstance({name:me.DATABASE_NAME,storeName:me.SESSIONS_STORE}),le=nt.createInstance({name:me.DATABASE_NAME,storeName:me.MESSAGES_STORE});function lt(){return Ct()}function Ot(t){const e=t.trim().replace(/\n/g," ");return e.length<=ye.MAX_TITLE_LENGTH?e:e.slice(0,ye.MAX_TITLE_LENGTH-3)+"..."}async function es(){const t=Date.now(),e={id:lt(),title:"新对话",createdAt:t,updatedAt:t,messageCount:0};return await ge.setItem(e.id,e),e}async function Me(t){return ge.getItem(t)}async function ts(){const t=[];return await ge.iterate(e=>{t.push(e)}),await new Promise(e=>{typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(()=>e(),{timeout:50}):setTimeout(e,0)}),t.sort((e,r)=>r.updatedAt-e.updatedAt)}async function Le(t,e){const r=await Me(t);if(r){const d={...r,...e,updatedAt:Date.now()};await ge.setItem(t,d)}}async function ss(t){const e=await ut(t);for(const r of e)await le.removeItem(r.id);await ge.removeItem(t)}async function as(t){await le.setItem(t.id,t);const e=await Me(t.sessionId);if(e){const r={messageCount:e.messageCount+1,updatedAt:Date.now()};await Le(t.sessionId,r)}}async function ut(t){const e=[];return await le.iterate(r=>{r.sessionId===t&&e.push(r)}),e.sort((r,d)=>r.timestamp-d.timestamp)}async function ns(t,e){const r=await le.getItem(t);if(r){const d={...r,...e};await le.setItem(t,d)}}async function rs(t){const e=await le.getItem(t);if(e){await le.removeItem(t);const r=await Me(e.sessionId);r&&await Le(e.sessionId,{messageCount:Math.max(0,r.messageCount-1)})}}const Je={isOpen:!1,width:Math.min(ye.DRAWER_MAX_WIDTH,Math.max(ye.DRAWER_MIN_WIDTH,window.innerWidth*ye.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function dt(){try{const t=localStorage.getItem(me.DRAWER_STATE);if(t)return{...Je,...JSON.parse(t)}}catch(t){console.error("[ChatStorage] Failed to get drawer state:",t)}return Je}function os(t){try{const r={...dt(),...t};localStorage.setItem(me.DRAWER_STATE,JSON.stringify(r))}catch(e){console.error("[ChatStorage] Failed to set drawer state:",e)}}async function is(){await ge.clear(),await le.clear(),localStorage.removeItem(me.DRAWER_STATE)}const k={createSession:es,getSession:Me,getAllSessions:ts,updateSession:Le,deleteSession:ss,addMessage:as,getMessages:ut,updateMessage:ns,deleteMessage:rs,getDrawerState:dt,setDrawerState:os,clearAllData:is,generateId:lt,generateTitle:Ot};var q=(t=>(t.SENDING="sending",t.STREAMING="streaming",t.SUCCESS="success",t.FAILED="failed",t))(q||{}),J=(t=>(t.USER="user",t.ASSISTANT="assistant",t))(J||{});let ae=null;function ft(t){const e={};let r=1,d=1,h=1,l=t;return l=l.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const o=`[图片${r}]`;return e[o]=c,r++,o}),l=l.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const o=`[视频${d}]`;return e[o]=c,d++,o}),l=l.replace(/blob:[^\s"'<>]+/g,c=>{const o=`[媒体${h}]`;return e[o]=c,h++,o}),l=l.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,c=>{const o=`[图片${r}]`;return e[o]=c,r++,o}),l=l.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,c=>{const o=`[视频${d}]`;return e[o]=c,d++,o}),{sanitized:l,urlMap:e}}function cs(t,e){let r=t;for(const[d,h]of Object.entries(e))r=r.split(d).join(h);return r}async function ls(t,e={}){const r={};let d=e.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(t.filter(l=>l.status==="success"||l.status==="streaming").map(async l=>{const{sanitized:c,urlMap:o}=ft(l.content);Object.assign(r,o);const S=[{type:"text",text:c}];if(e.includeImageAttachments&&l.role===J.USER&&l.attachments&&l.attachments.length>0&&d>0){const w=await jt(l.attachments,d);d-=w.length,S.push(...w)}return{role:l.role===J.USER?"user":"assistant",content:S}})),urlMap:r}}async function us(t,e,r=[],d,h,l){return ds(t,e,r,d,h,l)}async function ds(t,e,r=[],d,h,l){ae&&ae.abort(),ae=new AbortController;const c=ae.signal,o=Date.now().toString(),S=Date.now(),w=(typeof h=="string"?h:h==null?void 0:h.modelId)||Xe.getConfig().modelName||"unknown";try{X.trackModelCall({taskId:o,taskType:"chat",model:w,promptLength:e.length,hasUploadedImage:r.length>0,startTime:S});const g=bt("text",h),v=At(g==null?void 0:g.binding),D=vt(g==null?void 0:g.binding),E=Dt(r),z=Math.max(D-E,0),{geminiMessages:_,urlMap:M}=await ls(t,{includeImageAttachments:v,maxImageCount:z}),{sanitized:H,urlMap:p}=ft(e),Q={...M,...p},O=Rt(_),F=Math.max(D-O,0),G=[{type:"text",text:H}];if(v&&r.length>0&&F>0){const N=await Nt(r,F);G.push(...N)}const R=[];l&&R.push({role:"system",content:[{type:"text",text:l}]}),R.push(..._,{role:"user",content:G});let T="";if(await Xe.sendChat(R,N=>{if(c.aborted)return;const ne=cs(N,Q);T=ne,d({type:"content",content:ne})},c,h||void 0),c.aborted)throw new Error("Request cancelled");const $=Date.now()-S;return X.trackModelSuccess({taskId:o,taskType:"chat",model:w,duration:$,resultSize:T.length}),d({type:"done"}),ae=null,T}catch(g){ae=null;const v=Date.now()-S;if(c.aborted||g.message==="Request cancelled"||g.name==="AbortError")throw X.trackTaskCancellation({taskId:o,taskType:"chat",duration:v}),d({type:"done"}),new Error("Request cancelled");const D=g instanceof Error?g.message:"Unknown error occurred";throw X.trackModelFailure({taskId:o,taskType:"chat",model:w,duration:v,error:D}),d({type:"error",error:D}),g}}function fs(){ae&&(ae.abort(),ae=null)}function ms(){return ae!==null}const Ze={sendChatMessage:us,stopGeneration:fs,isGenerating:ms},$e="[[WORKFLOW_MESSAGE]]",ps=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function gs(t){if(!ps.includes(t.name)||!Vt(t.name))return t;const e=We.get(),r=Bt(t.name,{...t.arguments},{fallbackModels:{image:e.imageModelName||Lt(),video:e.videoModelName||$t(),audio:e.audioModelName||Wt()}});return{...t,arguments:r}}function hs(t){const e=[];t.aiAnalysis&&e.push(t.aiAnalysis);const r=t.steps.filter(c=>c.status==="completed"),d=t.steps.filter(c=>c.status==="failed");if(r.length>0||d.length>0){const c=[];r.length>0&&c.push(`成功执行 ${r.length} 个工具`),d.length>0&&c.push(`${d.length} 个工具执行失败`),c.length>0&&e.push(`[执行结果: ${c.join(",")}]`)}const h=t.steps.map(c=>{const o={};for(const[S,w]of Object.entries(c.args||{}))S!=="context"&&(typeof w=="string"&&w.length>200?o[S]=w.substring(0,200)+"...":o[S]=w);return{mcp:c.mcp,args:o}}),l={content:e.join(`
3
+ `)||`已完成任务: ${t.name}`,next:h};return JSON.stringify(l)}function ws(t){const e=[{type:"text",text:t.content}];if(t.attachments&&t.attachments.length>0)for(const r of t.attachments)e.push({type:"data-file",data:{filename:r.name,mediaType:r.type,url:r.data}});return{id:t.id,role:t.role===J.USER?"user":"assistant",parts:e}}function Ss(t,e){const d=t.parts.filter(c=>c.type==="text").map(c=>c.text).join(""),l=t.parts.filter(c=>c.type==="data-file").map((c,o)=>{const S=c.data;return{id:`${t.id}-att-${o}`,name:S.filename,type:S.mediaType,size:0,data:S.url,isBlob:!1}});return{id:t.id,sessionId:e,role:t.role==="user"?J.USER:J.ASSISTANT,content:d,timestamp:Date.now(),status:q.SUCCESS,attachments:l.length>0?l:void 0}}function _s(t){return t.workflow&&t.content.startsWith($e)?{...t,content:hs(t.workflow)}:t}function Qe(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join("")}Zt();function ys(t){const{sessionId:e,temporaryModel:r,onToolCalls:d,onWorkflowUpdate:h}=t,l=n.useRef(Xt()),c=n.useRef(d);c.current=d;const o=n.useRef(h);o.current=h;const S=n.useRef(r);S.current=r;const[w,g]=n.useState([]),[v,D]=n.useState("ready"),[E,z]=n.useState(!1),_=n.useRef(null),M=n.useRef([]),H=n.useRef(!1);n.useEffect(()=>{if(!e){g([]),M.current=[];return}(async()=>{z(!0);try{const T=await k.getMessages(e);M.current=T,g(T.map(ws))}catch(T){console.error("[useChatHandler] Failed to load messages:",T),g([]),M.current=[]}finally{z(!1)}})()},[e]);const p=n.useCallback(async R=>{if(!e)return;if(H.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}H.current=!0,D("submitted");const T=Ss(R,e);await k.addMessage(T),g(L=>[...L,R]);const $=await k.getSession(e);await k.updateSession(e,{updatedAt:Date.now(),messageCount:(($==null?void 0:$.messageCount)||0)+1});const N=k.generateId();_.current=N;const ne={id:N,role:"assistant",parts:[{type:"text",text:""}]};g(L=>[...L,ne]),D("streaming");const ue=M.current.map(_s);ue.push(T),M.current=[...M.current,T];const he=Qe(R);let ee="",de=!1;try{await Ze.sendChatMessage(ue.slice(0,-1),he,T.attachments||[],L=>{if(L.type==="content"&&L.content)ee=L.content,g(V=>V.map(K=>K.id===N?{...K,parts:[{type:"text",text:ee}]}:K));else if(L.type==="done"){const V=Pt(ee),K=Ut(ee)||ee;if(V.length>0&&c.current){const te=V.map(se=>gs(se)),we=async()=>{const se=[];for(const re of te)try{const oe=await qt.executeTool(re);se.push({toolCall:re,success:oe.success,data:oe.data,error:oe.error,taskId:oe.taskId})}catch(oe){se.push({toolCall:re,success:!1,error:oe.message||"工具执行失败"})}return se},xe=`${$e}${N}`;g(se=>se.map(re=>re.id===N?{...re,parts:[{type:"text",text:xe}]}:re)),c.current(te,N,we,K)}D("ready");const I={id:N,sessionId:e,role:J.ASSISTANT,content:V.length>0?`${$e}${N}`:ee,timestamp:Date.now(),status:V.length>0?q.STREAMING:q.SUCCESS};k.addMessage(I),M.current=[...M.current,I],k.updateSession(e,{updatedAt:Date.now(),messageCount:(($==null?void 0:$.messageCount)||0)+2}),_.current=null,H.current=!1}else if(L.type==="error"&&L.error){de=!0,D("error");const V=`❌ 错误: ${L.error}`;g(I=>I.map(te=>te.id===N?{...te,parts:[{type:"text",text:V}]}:te));const K={id:N,sessionId:e,role:J.ASSISTANT,content:V,timestamp:Date.now(),status:q.FAILED,error:L.error};k.addMessage(K),M.current=[...M.current,K],_.current=null,H.current=!1}},S.current,l.current)}catch(L){if(L.message!=="Request cancelled"&&!de){D("error"),console.error("[useChatHandler] Stream error:",L);const V=`❌ 错误: ${L.message||"未知错误"}`;if(g(K=>K.map(I=>I.id===N?{...I,parts:[{type:"text",text:V}]}:I)),e&&N){const K={id:N,sessionId:e,role:J.ASSISTANT,content:V,timestamp:Date.now(),status:q.FAILED,error:L.message||"未知错误"};k.addMessage(K),M.current=[...M.current,K]}}_.current=null,H.current=!1}},[e]),Q=n.useCallback(async()=>{if(Ze.stopGeneration(),D("ready"),_.current&&e){const R=w.find(T=>T.id===_.current);if(R){const T=Qe(R),$={id:R.id,sessionId:e,role:J.ASSISTANT,content:T,timestamp:Date.now(),status:q.SUCCESS};await k.addMessage($)}_.current=null}},[e,w]),O=n.useCallback(R=>{if(w.length<2)return;const T=[...w].reverse().findIndex(ue=>ue.role==="user");if(T===-1)return;const $=w.length-1-T,N=w[$],ne=w.slice(0,$+1);g(ne),p(N)},[w,p]),F=n.useCallback((R,T)=>{g(R),T&&(M.current=T)},[]),G=n.useCallback((R,T)=>{M.current=M.current.map($=>$.id===R?{...$,workflow:T}:$)},[]);return{messages:w,status:v,sendMessage:p,stop:Q,regenerate:O,setMessages:g,setMessagesWithRaw:F,updateRawMessageWorkflow:G,isLoading:E}}const ks=ce.lazy(()=>st(()=>import("./ChatMessagesArea-CEucTOYp.js"),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)),Oe="[[WORKFLOW_MESSAGE]]";function Is(t,e){switch(t){case"generate_image":return`生成图片: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_video":return`生成视频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_audio":return`生成音频: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_text":return`生成文本: ${((e==null?void 0:e.prompt)||"").substring(0,30)}...`;case"generate_grid_image":return`生成宫格图: ${((e==null?void 0:e.theme)||"").substring(0,30)}...`;case"canvas_insertion":return"插入到画布";case"generate_mermaid":return"生成流程图";case"generate_mindmap":return"生成思维导图";default:return`执行 ${t}`}}const et="chat-drawer-width",Ms=Math.max(375,window.innerWidth*.5),tt=375,xs=n.forwardRef(({defaultOpen:t=!1,onOpenChange:e},r)=>{const[d,h]=n.useState(()=>k.getDrawerState().isOpen??t),[l,c]=n.useState([]),[o,S]=n.useState(null),[w,g]=n.useState(!1),[v,D]=n.useState(()=>{const a=localStorage.getItem(et);if(a){const s=parseInt(a,10);if(!isNaN(s)&&s>=tt)return Math.min(s,window.innerWidth-60)}return Ms}),[E,z]=n.useState(!1),_=n.useRef(null),[M,H]=n.useState(()=>qe("text").modelId),[p,Q]=n.useState(()=>{const a=qe("text");return Ye(a.profileId,a.modelId)}),[O,F]=n.useState(new Map),G=n.useRef(null),[R,T]=n.useState(null),{executeRetry:$,selectedContent:N,setIsDrawerOpen:ne,setDrawerWidth:ue}=zt();n.useEffect(()=>{ne(d)},[d,ne]),n.useEffect(()=>{ue(v)},[v,ue]);const he=ce.useRef(null),ee=ce.useRef(null),{appState:de,setAppState:L}=Ft();n.useEffect(()=>{if(!E)return;const a=f=>{const u=window.innerWidth-f.clientX,m=Math.max(tt,Math.min(u,window.innerWidth-60));D(m)},s=()=>{z(!1),localStorage.setItem(et,String(v))};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",s),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",s),document.body.style.userSelect="",document.body.style.cursor=""}},[E,v]),n.useEffect(()=>{const a=()=>{const s=window.innerWidth-60;v>s&&D(s)};return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[v]);const V=n.useCallback(a=>{a.preventDefault(),z(!0)},[]),K=n.useCallback(async(a,s,f,u)=>{var A,y;const C={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(A=a[0])!=null&&A.name.includes("video")?"video":(y=a[0])!=null&&y.name.includes("audio")?"audio":"image",prompt:u||"",aiAnalysis:u,count:a.length,steps:a.map((x,P)=>({id:`step-${P}`,mcp:x.name,status:"pending",description:Is(x.name,x.arguments),args:x.arguments}))};F(x=>{const P=new Map(x);return P.set(s,C),P}),G.current=s,k.updateMessage(s,{workflow:C});try{const x=await f();X.track("chat_tool_execution_complete",{success:!0,resultCount:x.length}),X.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:a.length,resultCount:x.length}),F(P=>{const b=new Map(P),j=b.get(s);if(j){const U={...j,steps:j.steps.map((ie,_e)=>{const B=x[_e];return{...ie,status:B!=null&&B.success?"completed":"failed",error:B==null?void 0:B.error,result:B==null?void 0:B.data}})};b.set(s,U),k.updateMessage(s,{workflow:U,status:q.SUCCESS})}return b})}catch(x){console.error("[ChatDrawer] Tool execution failed:",x),F(P=>{const b=new Map(P),j=b.get(s);if(j){const U={...j,steps:j.steps.map(ie=>({...ie,status:"failed",error:x.message||"执行失败"}))};b.set(s,U),k.updateMessage(s,{workflow:U,status:q.FAILED})}return b})}},[]),I=ys({sessionId:o,temporaryModel:p||M,onToolCalls:K}),te=n.useRef(I.sendMessage);te.current=I.sendMessage,n.useEffect(()=>{(async()=>{const s=k.getDrawerState(),f=await k.getAllSessions();c(f);let u=null;if(s.activeSessionId?(u=s.activeSessionId,S(s.activeSessionId)):f.length>0&&(u=f[0].id,S(f[0].id)),u)try{const m=await k.getMessages(u),C=new Map;for(const y of m)y.workflow&&C.set(y.id,y.workflow);F(C);const A=m.find(y=>y.workflow&&y.status===q.STREAMING);G.current=(A==null?void 0:A.id)||null}catch(m){console.error("[ChatDrawer] Failed to load workflow messages:",m)}})()},[]),n.useEffect(()=>{k.setDrawerState({isOpen:d,activeSessionId:o})},[d,o]),n.useEffect(()=>{if(o&&Z.current){const a=Z.current;Z.current=null,setTimeout(()=>{te.current(a)},100)}},[o]),n.useEffect(()=>{if(!de.openSettings&&Z.current){const a=We.get();if(a!=null&&a.apiKey){const s=Z.current;Z.current=null,o?setTimeout(()=>{te.current(s)},100):(async()=>{const f=await k.createSession();c(u=>[f,...u]),S(f.id),Z.current=s})()}}},[de.openSettings,o]),n.useEffect(()=>{const a=s=>{s.key==="Escape"&&d&&(h(!1),e==null||e(!1))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[d,e]),n.useEffect(()=>{let a=null;return(async()=>{const{workflowSubmissionService:f}=await st(async()=>{const{workflowSubmissionService:u}=await import("./workflow-submission-service-DWibArfo.js").then(m=>m.a);return{workflowSubmissionService:u}},__vite__mapDeps([0,2]),import.meta.url);a=f.subscribeToAllEvents(u=>{const m=u;F(C=>{let A=null;for(const[b,j]of C.entries())if(j.id===m.workflowId){A=b;break}if(!A)return C;const y=C.get(A);if(!y)return C;const x=new Map(C);let P;switch(m.type){case"step":{P={...y,steps:y.steps.map(b=>b.id===m.stepId?{...b,status:m.status||b.status,result:m.result??b.result,error:m.error??b.error}:b)};break}case"steps_added":{const j=(m.steps||[]).map(U=>({id:U.id,mcp:U.mcp,args:U.args,description:U.description,status:U.status}));P={...y,steps:[...y.steps,...j]};break}case"completed":case"failed":{const b=m.type==="completed"?"completed":"failed";P={...y,status:b,steps:y.steps.map(j=>{if(j.status==="running"||j.status==="pending"){const U=j.result;return U!=null&&U.taskId?j:{...j,status:b,error:m.type==="failed"?m.error:void 0}}return j})};break}default:return C}return x.set(A,P),k.updateMessage(A,{workflow:P}),x})})})().catch(f=>{console.error("[ChatDrawer] Failed to setup workflow sync:",f)}),()=>{a==null||a.unsubscribe()}},[]),n.useEffect(()=>{if(!w)return;const a=f=>{const u=f.target;u.closest(".t-dialog")===null&&he.current&&!he.current.contains(u)&&ee.current&&!ee.current.contains(u)&&g(!1)},s=setTimeout(()=>{document.addEventListener("mousedown",a)},100);return()=>{clearTimeout(s),document.removeEventListener("mousedown",a)}},[w]);const we=n.useCallback(()=>{h(a=>{const s=!a;return e==null||e(s),s})},[e]),xe=n.useCallback(()=>{h(!1),e==null||e(!1)},[e]),se=n.useCallback(async()=>{X.track("chat_session_create");const a=await k.createSession();c(s=>[a,...s]),S(a.id),g(!1),F(new Map),G.current=null,H(void 0)},[]),re=n.useCallback(()=>{g(a=>!a)},[]),oe=n.useCallback(async a=>{X.track("chat_session_select"),S(a),g(!1),H(void 0);try{const s=await k.getMessages(a),f=new Map;for(const m of s)m.workflow&&f.set(m.id,m.workflow);F(f);const u=s.find(m=>m.workflow&&m.status===q.STREAMING);G.current=(u==null?void 0:u.id)||null}catch(s){console.error("[ChatDrawer] Failed to load workflow messages:",s),F(new Map),G.current=null}},[]),mt=n.useCallback(async a=>{X.track("chat_session_delete"),await k.deleteSession(a),c(s=>{const f=s.filter(u=>u.id!==a);if(o===a){const u=f[0]||null;S((u==null?void 0:u.id)||null)}return f})},[o]),Ee=n.useCallback(async(a,s)=>{X.track("chat_session_rename"),await k.updateSession(a,{title:s}),c(f=>f.map(u=>u.id===a?{...u,title:s}:u))},[]),Z=ce.useRef(null),Se=n.useCallback(async a=>{try{X.track("chat_message_send",{hasImages:a.parts.some(f=>f.type==="image_url")}),X.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:a.parts.some(f=>f.type==="image_url"),partCount:a.parts.length,textLength:a.parts.filter(f=>f.type==="text").reduce((f,u)=>f+String(u.text||"").length,0)});const s=We.get();if(!(s!=null&&s.apiKey)){Z.current=a,L({...de,openSettings:!0});return}if(Z.current=null,!o){const f=await k.createSession();c(u=>[f,...u]),S(f.id),Z.current=a;return}await I.sendMessage(a)}catch(s){console.error("[ChatDrawer] send message failed:",s),Z.current=a}},[o,I,de,L]),Pe=n.useCallback(async a=>{var Be;const{context:s,workflow:f,textModel:u,autoOpen:m=!0}=a;m&&(h(!0),e==null||e(!0)),u&&H(u);const C=await k.createSession(),A=[];s.userInstruction&&A.push(s.userInstruction),s.selection.texts.length>0&&A.push(`
4
+ 📝 选中的文本:
5
+ ${s.selection.texts.join(`
6
+ `)}`),s.selection.texts.length===0&&!s.userInstruction&&s.finalPrompt&&A.push(`
7
+ 提示词:
8
+ ${s.finalPrompt}`);const y=[],x=s.model.isExplicit?`模型: ${s.model.id}`:`模型: ${s.model.id} (默认)`;y.push(x),s.params.count>1&&y.push(`数量: ${s.params.count}`),y.length>0&&A.push(`
9
+ ---
10
+ ${y.join(" • ")}`);const P=A.join(`
11
+ `);let b="新任务";if(s.finalPrompt)b=s.finalPrompt;else if(s.selection.texts.length>0)b=s.selection.texts[0];else if(s.userInstruction){const W=s.userInstruction.indexOf(":"),Y=s.userInstruction.indexOf(":"),je=W>=0&&Y>=0?Math.min(W,Y):Math.max(W,Y);je>=0&&je<s.userInstruction.length-1?b=s.userInstruction.substring(je+1).trim():b=s.userInstruction}else s.model.id&&(b=`模型: ${s.model.id}`);const j=b;await k.updateSession(C.id,{title:j}),C.title=j,c(W=>[C,...W]),S(C.id);const U=Date.now(),ie=`msg_${U}_user`,_e=[{type:"text",text:P}],B=[...s.selection.images,...s.selection.graphics];for(let W=0;W<B.length;W++)_e.push({type:"data-file",data:{filename:`image-${W+1}.png`,mediaType:"image/png",url:B[W]}});for(let W=0;W<s.selection.videos.length;W++)_e.push({type:"data-file",data:{filename:`video-${W+1}.mp4`,mediaType:"video/mp4",url:s.selection.videos[W]}});const _t={id:ie,role:"user",parts:_e},pe=`msg_${U}_workflow`,yt={id:pe,role:"assistant",parts:[{type:"text",text:`${Oe}${pe}`}]};F(W=>{const Y=new Map(W);return Y.set(pe,f),Y}),G.current=pe;const Ke={id:ie,sessionId:C.id,role:J.USER,content:P,timestamp:Date.now(),status:q.SUCCESS,aiContext:s,attachments:B.length>0||s.selection.videos.length>0?[...B.map((W,Y)=>({id:`${ie}-img-${Y}`,name:`image-${Y+1}.png`,type:"image/png",size:0,data:W,isBlob:!1})),...s.selection.videos.map((W,Y)=>({id:`${ie}-vid-${Y}`,name:`video-${Y+1}.mp4`,type:"video/mp4",size:0,data:W,isBlob:!1}))]:void 0};await k.addMessage(Ke);const Ve={id:pe,sessionId:C.id,role:J.ASSISTANT,content:`${Oe}${pe}`,timestamp:Date.now(),status:q.STREAMING,workflow:f};await k.addMessage(Ve),(Be=I.setMessagesWithRaw)==null||Be.call(I,[_t,yt],[Ke,Ve])},[I,e]),Ue=n.useCallback(async a=>{var f;let s=G.current;if(!s){for(const[u,m]of O.entries())if(m.id===a.id){s=u,G.current=u;break}}s&&(F(u=>{const m=new Map(u);return m.set(s,a),m}),k.updateMessage(s,{workflow:a}),(f=I.updateRawMessageWorkflow)==null||f.call(I,s,a))},[o,l,I,O]),ze=n.useCallback(a=>{const s=G.current;s&&F(f=>{var C;const u=new Map(f),m=u.get(s);if(m){const A=m.logs||[],y={...m,logs:[...A,a]};u.set(s,y),k.updateMessage(s,{workflow:y}),(C=I.updateRawMessageWorkflow)==null||C.call(I,s,y)}return u})},[I]),Te=n.useRef(null),Fe=n.useCallback(a=>{const s=G.current;s&&F(f=>{const u=new Map(f),m=u.get(s);if(m){const C=m.logs||[];let A=-1;for(let x=C.length-1;x>=0;x--)if(C[x].type==="thinking"){A=x;break}let y;if(A>=0){const x=[...C],P=x[A];x[A]={...P,content:P.content+a},y={...m,logs:x}}else y={...m,logs:[...C,{type:"thinking",timestamp:Date.now(),content:a}]};u.set(s,y),Te.current&&clearTimeout(Te.current),Te.current=setTimeout(()=>{var x;k.updateMessage(s,{workflow:y}),(x=I.updateRawMessageWorkflow)==null||x.call(I,s,y)},500)}return u})},[I]),Ce=n.useCallback(async(a,s,f)=>{if(!R){X.track("chat_workflow_retry",{stepIndex:f});try{T(a),G.current=a,await $(s,f)}finally{T(null)}}},[$,R]);n.useImperativeHandle(r,()=>({open:()=>{h(!0),e==null||e(!0)},close:()=>{h(!1),e==null||e(!1)},toggle:we,sendMessage:async a=>{h(!0),e==null||e(!0);const s={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:a}]};await Se(s)},sendWorkflowMessage:Pe,updateWorkflowMessage:Ue,appendAgentLog:ze,updateThinkingContent:Fe,isOpen:()=>d,retryWorkflowFromStep:async(a,s)=>{let f=null;for(const[u,m]of O.entries())if(m.id===a.id){f=u;break}f?await Ce(f,a,s):console.warn("[ChatDrawer] Could not find message ID for workflow retry",a.id)}}),[d,we,Se,Pe,Ue,ze,Fe,e,O,Ce]);const pt=n.useMemo(()=>({...I,sendMessage:Se}),[I,Se]),be=l.find(a=>a.id===o),fe=(be==null?void 0:be.title)||"新对话",[Ae,ve]=n.useState(!1),[De,Re]=n.useState(""),ke=n.useRef(null),gt=n.useCallback(()=>{Re(fe),ve(!0)},[fe]),Ne=n.useCallback(async()=>{const a=De.trim();a&&a!==fe&&o&&await Ee(o,a),ve(!1)},[De,fe,o,Ee]),He=n.useCallback(()=>{Re(fe),ve(!1)},[fe]),ht=n.useCallback(a=>{a.key==="Enter"?(a.preventDefault(),Ne()):a.key==="Escape"&&(a.preventDefault(),He())},[Ne,He]);n.useEffect(()=>{Ae&&ke.current&&(ke.current.focus(),ke.current.select())},[Ae]);const Ge=n.useRef(null);Qt(Ge,{enableCopy:!0,stopPropagation:!0});const[wt,St]=n.useState(!1);return n.useEffect(()=>{d&&St(!0)},[d]),i.jsxs(i.Fragment,{children:[i.jsx(it,{isOpen:d,onClick:we,drawerWidth:v}),i.jsxs("div",{className:`chat-drawer ${Ht} ${d?"chat-drawer--open":""} ${E?"chat-drawer--dragging":""}`,style:{width:v},"data-testid":"chat-drawer",children:[i.jsx("div",{ref:_,className:"chat-drawer__resize-handle",onMouseDown:V}),i.jsxs("div",{ref:Ge,className:"chat-drawer__body",children:[i.jsxs("div",{className:"chat-drawer__header",children:[i.jsxs("div",{className:"chat-drawer__header-top",children:[i.jsx(Ie,{content:"关闭",children:i.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:xe,"aria-label":"关闭对话",children:i.jsx(Gt,{size:16})})}),Ae?i.jsx("input",{ref:ke,className:"chat-drawer__title-input",value:De,onChange:a=>Re(a.target.value),onKeyDown:ht,onBlur:Ne,maxLength:50}):i.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:gt,title:"点击编辑标题",children:fe})]}),i.jsxs("div",{className:"chat-drawer__header-bottom",children:[i.jsx(Yt,{value:M,valueRef:p,onChange:(a,s)=>{H(a),Q(s||Ye(null,a))}}),i.jsxs("div",{className:"chat-drawer__session-actions",children:[i.jsx(Ie,{content:"会话列表",children:i.jsx("button",{ref:ee,className:`chat-drawer__close-btn ${w?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:re,"aria-label":"会话列表",children:i.jsx(Kt,{size:16})})}),i.jsx(Ie,{content:"新对话",children:i.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:se,"aria-label":"新对话",children:i.jsx(at,{size:16})})})]})]})]}),w&&i.jsx("div",{ref:he,children:i.jsx(ot,{sessions:l,activeSessionId:o,onSelectSession:oe,onNewSession:se,onDeleteSession:mt,onRenameSession:Ee})}),i.jsxs("div",{className:"chat-drawer__content",children:[wt&&i.jsx(n.Suspense,{fallback:i.jsx("div",{className:"chat-loading chat-loading--full",children:i.jsx("div",{className:"chat-loading__spinner"})}),children:i.jsx(ks,{handler:pt,workflowMessages:O,retryingWorkflowId:R,handleWorkflowRetry:Ce})}),i.jsx(ct,{selectedContent:N,onSend:Se,placeholder:"支持连续对话"})]})]})]})]})});xs.displayName="ChatDrawer";export{xs as ChatDrawer};
@@ -0,0 +1,8 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-B7ypM2x4.css","./tool-windows-CDLejk69.css"])))=>i.map(i=>d[i]);
2
+ import{P as d,S as e,iq as I,fP as L,gh as A,ir as T,cd as W}from"./startup-app-DC9IB1KI.js";import{_ as z}from"./startup-runtime-DTmhLESk.js";import{M as $}from"./index-eO62kWA6.js";import"./editor-engines-BtXR1R6e.js";import"./diagram-engines-BAca1QyG.js";import"./tool-windows-Do7Od789.js";/* empty css */const R=d.lazy(()=>z(()=>import("./MermaidRenderer-C2mk8jSz.js"),__vite__mapDeps([0,1]),import.meta.url).then(s=>({default:s.MermaidRenderer}))),F={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},B={pending:"待执行",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"};function D(s){const c=[],f=/```mermaid\s*([\s\S]*?)```/gi;let m=0,l;for(;(l=f.exec(s))!==null;){const o=s.slice(m,l.index);o.trim()&&c.push(e.jsx($,{markdown:o,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"chat-markdown"},`md-${c.length}`)),c.push(e.jsx(d.Suspense,{fallback:null,children:e.jsx(R,{code:l[1].trim(),className:"chat-markdown__mermaid"})},`mermaid-${c.length}`)),m=f.lastIndex}const b=s.slice(m);return(b.trim()||c.length===0)&&c.push(e.jsx($,{markdown:b,readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"chat-markdown"},`md-${c.length}`)),c}const K=({step:s,index:c,isCurrentStep:f})=>{const[m,l]=d.useState(!1),b=F[s.status],o=B[s.status],v=Object.keys(s.args).length>0,k=s.result!==void 0&&s.result!==null,n=v||k||!!s.error||s.duration!==void 0,r=i=>{if(!i)return null;const x={};for(const[u,g]of Object.entries(i))u==="context"?x[u]="[AgentExecutionContext]":typeof g=="string"&&g.length>200?x[u]=g.substring(0,200)+"...":x[u]=g;return x},p=d.useMemo(()=>v&&JSON.stringify(r(s.args),null,2)||"",[v,s.args]);return e.jsxs("div",{className:`workflow-bubble-step workflow-bubble-step--${s.status} ${f?"workflow-bubble-step--current":""}`,children:[e.jsxs("div",{className:"workflow-bubble-step__main",onClick:()=>n&&l(!m),style:{cursor:n?"pointer":"default"},children:[e.jsx("div",{className:"workflow-bubble-step__index",children:c+1}),e.jsx("div",{className:`workflow-bubble-step__status workflow-bubble-step__status--${s.status}`,children:s.status==="running"?e.jsx("span",{className:"workflow-bubble-step__spinner"}):b}),e.jsxs("div",{className:"workflow-bubble-step__content",children:[e.jsx("div",{className:"workflow-bubble-step__title",children:s.description}),e.jsx("div",{className:"workflow-bubble-step__status-text",children:o})]}),n&&e.jsx("div",{className:`workflow-bubble-step__expand ${m?"workflow-bubble-step__expand--open":""}`,children:"▼"})]}),m&&n&&e.jsxs("div",{className:"workflow-bubble-step__details",children:[e.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[e.jsx("span",{className:"workflow-bubble-step__label",children:"工具:"}),e.jsx("code",{className:"workflow-bubble-step__tool",children:s.mcp})]}),v?e.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[e.jsx("span",{className:"workflow-bubble-step__label",children:"输入参数:"}),e.jsx("pre",{className:"workflow-bubble-step__args",children:p})]}):null,s.duration!==void 0&&e.jsxs("div",{className:"workflow-bubble-step__detail-row",children:[e.jsx("span",{className:"workflow-bubble-step__label",children:"耗时:"}),e.jsxs("span",{children:[s.duration,"ms"]})]}),k?e.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[e.jsx("span",{className:"workflow-bubble-step__label",children:"执行结果:"}),e.jsx("div",{className:"workflow-bubble-step__result",children:typeof s.result=="string"?s.result:String(JSON.stringify(s.result,null,2))})]}):null,s.error&&e.jsxs("div",{className:"workflow-bubble-step__detail-row workflow-bubble-step__detail-row--block",children:[e.jsx("span",{className:"workflow-bubble-step__label",children:"错误信息:"}),e.jsx("div",{className:"workflow-bubble-step__error",children:s.error})]})]})]})},G=({log:s})=>{const[c,f]=d.useState(!1);if(s.type==="thinking"){const m=s.content,l=m.length>200,b=c?m:m.substring(0,200);return e.jsxs("div",{className:"agent-log agent-log--thinking",children:[e.jsxs("div",{className:"agent-log__header",children:[e.jsx("span",{className:"agent-log__icon",children:"💭"}),e.jsx("span",{className:"agent-log__title",children:"AI 分析"})]}),e.jsxs("div",{className:"agent-log__content",children:[e.jsxs("pre",{className:"agent-log__thinking-text",children:[b,l&&!c&&"..."]}),l&&e.jsx("button",{className:"agent-log__toggle",onClick:()=>f(!c),children:c?"收起":"展开全部"})]})]})}if(s.type==="tool_call")return e.jsxs("div",{className:"agent-log agent-log--tool-call",children:[e.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>f(!c),children:[e.jsx("span",{className:"agent-log__icon",children:"🔧"}),e.jsxs("span",{className:"agent-log__title",children:["调用工具: ",s.toolName]}),e.jsx("span",{className:`agent-log__expand ${c?"agent-log__expand--open":""}`,children:"▼"})]}),c&&e.jsx("div",{className:"agent-log__content",children:e.jsx("pre",{className:"agent-log__args",children:JSON.stringify(s.args,null,2)})})]});if(s.type==="tool_result"){const m=s.success?"success":"error",l=s.success?"✅":"❌",b=s.data!==void 0&&s.data!==null;return e.jsxs("div",{className:`agent-log agent-log--tool-result agent-log--${m}`,children:[e.jsxs("div",{className:"agent-log__header agent-log__header--clickable",onClick:()=>f(!c),children:[e.jsx("span",{className:"agent-log__icon",children:l}),e.jsxs("span",{className:"agent-log__title",children:[s.toolName," ",s.success?"执行成功":"执行失败"]}),e.jsx("span",{className:`agent-log__expand ${c?"agent-log__expand--open":""}`,children:"▼"})]}),c&&e.jsxs("div",{className:"agent-log__content",children:[s.error&&e.jsx("div",{className:"agent-log__error",children:s.error}),b&&e.jsx("pre",{className:"agent-log__data",children:typeof s.data=="string"?s.data:String(JSON.stringify(s.data,null,2))})]})]})}return s.type==="retry"?e.jsx("div",{className:"agent-log agent-log--retry",children:e.jsxs("div",{className:"agent-log__header",children:[e.jsx("span",{className:"agent-log__icon",children:"🔄"}),e.jsxs("span",{className:"agent-log__title",children:["重试 #",s.attempt,": ",s.reason]})]})}):null},J=({workflow:s,className:c="",onRetry:f,isRetrying:m=!1})=>{const l=d.useMemo(()=>s.steps.map(t=>{const a=t.result,w=!!(a!=null&&a.taskId),_=t.result!==void 0&&t.result!==null,j=t.duration!==void 0;if((t.status==="running"||t.status==="pending")&&!w){if(t.error)return{...t,status:"failed"};if(_||j)return{...t,status:"completed"}}return t}),[s.steps]),b=d.useMemo(()=>s.generationType==="image"&&l.some(t=>t.mcp==="generate_image"||t.mcp==="generate_grid_image"||t.mcp==="generate_inspiration_board"),[s.generationType,l]),o=d.useMemo(()=>{const t=l,a=t.length,w=t.filter(N=>N.status==="completed").length,_=t.filter(N=>N.status==="failed").length,j=t.filter(N=>N.status==="running").length;let h="pending";if(_>0)h="failed";else if(w===a&&a>0)if(b){const N=s.postProcessingStatus;N==="completed"?h="completed":N==="failed"?h="failed":h="running"}else h="completed";else(j>0||w>0)&&(h="running");return{status:h,totalSteps:a,completedSteps:w}},[l,s.postProcessingStatus,b]),v=o.totalSteps>0?o.completedSteps/o.totalSteps*100:0,k=d.useMemo(()=>{const t={pending:"待开始",running:"执行中",completed:"已完成",failed:"执行失败"},a=l.every(w=>w.status==="completed");return a&&b&&s.postProcessingStatus==="processing"?"正在插入画布":a&&b&&!s.postProcessingStatus?"正在处理":t[o.status]},[o.status,l,s.postProcessingStatus,b]),n=o.status==="completed",r=o.status==="failed",p=o.status==="running",i=d.useMemo(()=>{var t,a,w;if(!n)return"";for(let _=l.length-1;_>=0;_-=1){const j=(t=l[_])==null?void 0:t.result;if(j){if(typeof j=="string"){const h=j.trim();if(h)return h;continue}if(typeof j=="object"&&j!==null){const h=j,N=((a=h.data)==null?void 0:a.content)||((w=h.data)==null?void 0:w.response)||h.content||h.response;if(typeof N=="string"){const P=N.trim();if(P)return P}}}}return s.aiAnalysis||""},[n,l,s.aiAnalysis]),x=d.useMemo(()=>{const t=["generate_image","generate_video","generate_grid_image","generate_inspiration_board","generate_long_video"];return l.some(a=>t.includes(a.mcp||""))},[l]),u=d.useMemo(()=>!n&&!r?null:r?{variant:"info",icon:"❌",text:"生成失败"}:i?{variant:"markdown",icon:"✨",markdown:i}:x?{variant:"info",icon:"✅",text:"已生成"}:{variant:"info",icon:"ℹ️",text:"未生成任何内容"},[n,r,i,x]),g=d.useMemo(()=>!u||u.variant!=="markdown"?null:u.markdown,[u]),y=d.useMemo(()=>l.findIndex(t=>t.status==="running"),[l]),S=d.useMemo(()=>l.findIndex(t=>t.status==="failed"),[l]);d.useRef(null);const M=d.useRef(null);d.useEffect(()=>{p&&requestAnimationFrame(()=>{M.current&&M.current.scrollIntoView({behavior:"smooth",block:"end"})})},[y,p,l.length]);const C=r&&s.retryContext&&S>=0,E=()=>{f&&S>=0&&f(S)};return e.jsxs("div",{ref:M,className:`workflow-bubble chat-message chat-message--assistant ${c}`,children:[e.jsx("div",{className:"chat-message-avatar",children:e.jsx("span",{children:s.generationType==="image"?"🖼️":s.generationType==="video"?"🎬":s.generationType==="audio"?"🎵":"📝"})}),e.jsxs("div",{className:"workflow-bubble__content chat-message-content",children:[e.jsxs("div",{className:"workflow-bubble__header",children:[e.jsx("span",{className:"workflow-bubble__title",children:s.name}),e.jsxs("div",{className:"workflow-bubble__status-info",children:[e.jsx("span",{className:`workflow-bubble__status workflow-bubble__status--${o.status}`,children:k}),e.jsxs("span",{className:"workflow-bubble__progress-text",children:[o.completedSteps,"/",o.totalSteps]})]})]}),e.jsx("div",{className:"workflow-bubble__progress",children:e.jsx("div",{className:`workflow-bubble__progress-bar workflow-bubble__progress-bar--${o.status}`,style:{width:`${v}%`}})}),s.prompt&&e.jsxs("div",{className:"workflow-bubble__prompt",children:[e.jsx("span",{className:"workflow-bubble__label",children:"请求:"}),e.jsx("span",{className:"workflow-bubble__prompt-text",children:s.prompt.length>100?`${s.prompt.substring(0,100)}...`:s.prompt})]}),e.jsx("div",{className:"workflow-bubble__steps",children:l.map((t,a)=>e.jsx(K,{step:t,index:a,isCurrentStep:a===y&&p},t.id))}),s.logs&&s.logs.length>0&&e.jsxs("div",{className:"workflow-bubble__logs",children:[e.jsx("div",{className:"workflow-bubble__logs-header",children:e.jsx("span",{className:"workflow-bubble__logs-title",children:"执行详情"})}),e.jsx("div",{className:"workflow-bubble__logs-list",children:s.logs.map((t,a)=>e.jsx(G,{log:t},`log-${a}-${t.timestamp}`))})]}),u&&u.variant!=="markdown"&&e.jsxs("div",{className:`workflow-bubble__summary workflow-bubble__summary--${u.variant}`,children:[e.jsx("span",{className:"workflow-bubble__summary-icon",children:u.icon}),e.jsx("span",{children:u.text})]}),u&&u.variant==="markdown"&&g&&e.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--success workflow-bubble__summary--markdown",children:[e.jsx("span",{className:"workflow-bubble__summary-icon",children:u.icon}),e.jsx("div",{className:"workflow-bubble__summary-markdown",children:e.jsx("div",{className:"workflow-bubble__markdown-message",children:e.jsx("div",{className:"workflow-bubble__markdown-content",children:D(g)})})})]}),r&&e.jsxs("div",{className:"workflow-bubble__summary workflow-bubble__summary--error",children:[e.jsx("span",{className:"workflow-bubble__summary-icon",children:"❌"}),e.jsx("span",{children:"执行失败,请重试"}),C&&f&&e.jsx("button",{className:"workflow-bubble__retry-btn",onClick:E,disabled:m,children:m?"重试中...":"🔄 从失败步骤重试"})]})]})]})},U=({message:s,className:c=""})=>{const f=d.useRef(null),{text:m,meta:l,images:b}=d.useMemo(()=>{var u,g,y,S,M,C,E;let n="";const r=[];for(const t of s.parts)if(t.type==="text")n+=t.text;else if(t.type==="data-file"){const a=t.data;((u=a==null?void 0:a.mediaType)!=null&&u.startsWith("image/")||(g=a==null?void 0:a.url)!=null&&g.startsWith("data:image/"))&&r.push({url:a.url,filename:a.filename||"image"})}const p=s;if(p.aiContext){const t=p.aiContext,a=[];return(y=t.model)!=null&&y.id&&a.push({label:t.model.id,icon:e.jsx(I,{size:"12px"})}),((S=t.params)==null?void 0:S.count)>1&&a.push({label:`${t.params.count} 张`,icon:e.jsx(L,{size:"12px"})}),(M=t.params)!=null&&M.size&&a.push({label:t.params.size,icon:e.jsx(A,{size:"12px"})}),((E=(C=t.selection)==null?void 0:C.texts)==null?void 0:E.length)>0&&a.push({label:`${t.selection.texts.length} 段文本`,icon:e.jsx(T,{size:"12px"})}),{text:t.userInstruction||t.finalPrompt||n,meta:a,images:r}}let i=n;const x=[];if(i.includes(`
3
+ ---
4
+ `)){const t=i.split(`
5
+ ---
6
+ `);i=t[0],t[1].split(" • ").forEach(w=>{const _=w.replace(/模型:\s*/,"").replace(/数量:\s*/,"").replace(/尺寸:\s*/,"").trim();if(_){let j=e.jsx(I,{size:"12px"});w.includes("数量")&&(j=e.jsx(L,{size:"12px"})),w.includes("尺寸")&&(j=e.jsx(A,{size:"12px"})),x.push({label:_,icon:j})}})}else{const t=i.split(`
7
+ `),a=[];for(const w of t){const _=w.trim();if(_.startsWith("模型:")||_.startsWith("数量:")||_.startsWith("提示词:")){const j=_.replace(/.*:\s*/,"").trim();let h=e.jsx(I,{size:"12px"});_.includes("数量")&&(h=e.jsx(L,{size:"12px"})),x.push({label:j,icon:h})}else _.startsWith("📝 选中的文本:")?x.push({label:_.replace("📝 ","").trim(),icon:e.jsx(T,{size:"12px"})}):_&&!_.startsWith("💬 用户指令:")&&a.push(w)}i=a.join(`
8
+ `).trim()}if(!i&&x.length>0){const t=n.match(/💬 用户指令:\s*([\s\S]*?)(?=\n模型:|\n数量:|$)/);t&&t[1].trim()&&(i=t[1].trim())}return{text:i||n,meta:x,images:r}},[s.parts,s.aiContext]),o=d.useCallback(n=>{n.stopPropagation()},[]),v=d.useCallback(n=>{if((n.ctrlKey||n.metaKey)&&n.key==="c"){const p=window.getSelection(),i=p==null?void 0:p.toString();i&&(W(i).catch(x=>{console.error("Failed to copy text:",x)}),n.stopPropagation())}},[]);d.useEffect(()=>{const n=f.current;if(n)return n.addEventListener("pointerdown",o),n.addEventListener("pointerup",o),n.addEventListener("mousedown",o),n.addEventListener("mouseup",o),n.addEventListener("click",o),n.addEventListener("keydown",v),()=>{n.removeEventListener("pointerdown",o),n.removeEventListener("pointerup",o),n.removeEventListener("mousedown",o),n.removeEventListener("mouseup",o),n.removeEventListener("click",o),n.removeEventListener("keydown",v)}},[o,v]);const k=b.length===0&&(!l||l.length===0);return e.jsxs("div",{className:`user-bubble chat-message chat-message--user ${k?"user-bubble--text-only":""} ${c}`,children:[e.jsx("div",{className:"chat-message-avatar",children:e.jsx("span",{children:"👤"})}),e.jsxs("div",{className:"user-bubble__content chat-message-content",children:[b.length>0&&e.jsx("div",{className:`user-bubble__images user-bubble__images--${Math.min(b.length,4)}`,children:b.map((n,r)=>e.jsx("div",{className:"user-bubble__image-wrapper",children:e.jsx("img",{src:n.url,alt:n.filename,className:"user-bubble__image",loading:"lazy"})},r))}),m&&e.jsx("div",{ref:f,className:"user-bubble__text user-bubble__text--selectable",children:m}),l&&l.length>0&&e.jsx("div",{className:"user-bubble__meta-tags",children:l.map((n,r)=>e.jsxs("div",{className:"user-bubble__meta-tag",children:[e.jsx("span",{className:"user-bubble__meta-icon",children:n.icon}),e.jsx("span",{className:"user-bubble__meta-label",children:n.label})]},r))})]})]})},O="[[WORKFLOW_MESSAGE]]",ee=({handler:s,workflowMessages:c,retryingWorkflowId:f,handleWorkflowRetry:m,className:l="chat-section"})=>{const b=d.useCallback(r=>{const p=r.parts.find(i=>i.type==="text");if(p&&"text"in p){const i=p.text;if(i.startsWith(O))return i.replace(O,"")}return null},[]),o=d.useCallback(r=>r.parts.some(p=>p.type==="data-file"),[]),v=d.useCallback(r=>r.parts.filter(i=>i.type==="text"&&"text"in i).map(i=>typeof i.text=="string"?i.text:String(i.text??"")).join(""),[]),k=s.status==="submitted"||s.status==="streaming",n=s.messages.length===0&&!k;return e.jsx("div",{className:l,children:e.jsx("div",{className:"chat-messages",children:e.jsxs("div",{className:"chat-messages-list",children:[s.messages.map((r,p)=>{const i=b(r);if(i){const g=c.get(i);if(g)return e.jsx(J,{workflow:g,onRetry:y=>m(i,g,y),isRetrying:f===i},r.id)}const x=r.parts.some(g=>g.type==="text"&&"text"in g&&typeof g.text=="string"&&g.text.startsWith("❌ 错误")),u=`chat-message chat-message--${r.role} ${x?"chat-message--error":""}`;return r.role==="user"&&o(r)?e.jsx(U,{message:r},r.id):e.jsxs("div",{className:u,"data-message-id":r.id,"data-message-last":p===s.messages.length-1,children:[e.jsx("div",{className:"chat-message-avatar",children:e.jsx("span",{children:r.role==="user"?"👤":"🤖"})}),e.jsx("div",{className:"chat-message-content",children:e.jsx($,{markdown:v(r),readOnly:!0,showModeSwitch:!1,initialMode:"wysiwyg",className:"chat-markdown"})}),r.role==="assistant"&&!x&&e.jsx("div",{className:"chat-message-actions"})]},r.id)}),k&&e.jsxs("div",{className:"chat-loading",children:[e.jsx("div",{className:"chat-loading__spinner"}),e.jsx("span",{children:"思考中..."})]}),n&&e.jsxs("div",{className:"chat-empty",children:[e.jsx("h3",{children:"开始对话"}),e.jsx("p",{children:"输入消息与AI助手交流"})]})]})})})};export{ee as ChatMessagesArea,ee as default};
@@ -0,0 +1,8 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-B7ypM2x4.css"])))=>i.map(i=>d[i]);
2
+ import{ds as fs,bI as cr,P as r,i6 as qt,cY as Ae,hp as Zn,cD as tn,S as p,lE as lr,b4 as gs,b0 as Tt,b1 as dr,lH as ur,lI as pr,d2 as mr,U as hr,bs as Oo,ey as fr,eb as gr,db as Ve,lJ as Hn,cX as Cn,e7 as qn,e6 as Pt,e5 as Et,dX as pt,lk as Jn,lK as eo,lL as et,Q as to,lM as Wo,df as no,aP as oo,de as Tn,$ as ws,a0 as Is,fX as wr,_ as Ir,ay as so,a3 as yr,lN as xr,ax as _r,cT as br,kz as vr,gl as Sr,dV as ro,c2 as kr,at as Mr,lo as Cr,lu as Tr,dN as kn,lO as Qn,R as ys,iP as Pr,bE as Er,ez as lt,eQ as $n,c$ as mt,dt as kt,is as Lo,iD as Bo,iI as Ar,eJ as je,ew as Un,dD as Dr,ah as Je,bJ as Fo,bK as Rr,lP as Nr,iE as jr,h$ as zr,i0 as Or,lQ as Vn,lA as Ho,g1 as xs,ad as Gn,bt as $o,lR as Wr,dQ as _s,lS as Uo,ac as Vo,iC as Go,iB as Ko,aS as gn,b$ as Lr,a6 as Br,lx as Fr,ck as Hr,hB as $r,lg as Ur}from"./startup-app-DC9IB1KI.js";import{u as Vr,a as Gr,c as wn,b as Mt,W as Kr}from"./useWorkflowSubmission-BLZubY71.js";import{ay as Yr,aG as Xr,aH as Zr,ar as In,ap as yn,aq as qr,az as Mn,S as ao,am as Jr,R as Qr,u as xn,a as dt,aI as Yo,m as Xo,x as _n,aa as ea,i as ta,aJ as Zo,aK as na}from"./tool-windows-Do7Od789.js";import{_ as qo}from"./startup-runtime-DTmhLESk.js";import{u as oa,S as sa,i as ra}from"./index-Cyi_RBqN.js";import{u as aa,r as ia,g as ca,f as la,b as da,h as ua,i as Kn,j as pa,k as ma,P as ha}from"./ai-generation-preferences-service-B14EtlzO.js";import{setCanvasBoard as Jo}from"./canvas-insertion-BzIbRGcU.js";import{s as Qo}from"./board-utils-CpAtoKn2.js";import{s as es}from"./workflow-submission-service-DWibArfo.js";import"./skill-dsl-parser-Wxj3iyHM.js";import"./video-generation-rHwGvZFJ.js";import"./index-Dl-kSsRd.js";import"./ppt-generation-CcWMarvM.js";import"./kb-search-engine-BCA6z_98.js";import"./video-analyze-KCWkdBAl.js";const fa=({generationType:e,onSelectPrompt:n,language:t,extraActions:s,onBeforeOpenMyPrompts:d})=>{const{history:c,removeHistory:a,refreshHistory:h}=fs({deduplicateWithPresets:!1,modelTypeFilter:e==="image"||e==="video"?void 0:e}),{imageHistory:u,videoHistory:l}=aa(),{confirm:v,confirmDialog:k}=cr(),[S,I]=r.useState(!1),[,f]=r.useState(0),D=r.useRef(null),y=r.useRef(null),C=r.useRef(null),E=t==="zh"?"我的提示词":"My Prompts",P=e==="image"||e==="video"?ia({generationType:e,language:t,promptContents:ca(e,t,e==="image"?u:l),imageHistory:u,videoHistory:l}):la({generationType:e,language:t,aiInputHistory:c,imageHistory:u,videoHistory:l});r.useEffect(()=>qt.subscribeChanges(()=>{h(),f(H=>H+1)}),[h]),r.useEffect(()=>()=>{y.current&&clearTimeout(y.current),C.current&&clearTimeout(C.current)},[]);const g=r.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null),y.current=setTimeout(()=>{h(),f(H=>H+1),S||Ae.trackPromptAction({action:"open_panel",surface:"ai_input_prompt_popover",promptType:e,itemCount:P.length}),I(!0)},150)},[e,S,P.length,h]),N=r.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null),C.current=setTimeout(()=>{I(!1)},200)},[]),U=r.useCallback(H=>{n({content:H.content,modelType:H.modelType,scene:H.scene}),I(!1)},[n]),ee=r.useCallback(async H=>{const _=P.find($=>$.id===H);!_||!await v({title:t==="zh"?"确认删除提示词":"Delete Prompt",description:t==="zh"?"确定要删除这条提示词吗?此操作不可撤销。":"Are you sure you want to delete this prompt? This action cannot be undone.",confirmText:t==="zh"?"删除":"Delete",cancelText:t==="zh"?"取消":"Cancel",danger:!0})||(qt.deletePrompt(e,_.content),_.historyId&&e!=="image"&&e!=="video"?a(_.historyId):f($=>$+1))},[v,e,t,P,a]),ne=r.useCallback(H=>{const _=P.find(R=>R.id===H);_&&(qt.isPinned(e,_.content)?qt.unpinPrompt(e,_.content):qt.pinPrompt(e,_.content),f(R=>R+1))},[e,P]),ae=r.useCallback(()=>{const H=Zn.find($=>$.id==="prompt-history");if(!H){Ae.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"failed",metadata:{tool_id:"prompt-history",reason:"tool_not_found"}});return}d==null||d();const _=tn.getToolState("prompt-history");console.info("[PromptHistoryPopover] open my prompts",{generationType:e,beforeStatus:_==null?void 0:_.status,beforeInstanceId:_==null?void 0:_.instanceId,beforeIsLauncher:_==null?void 0:_.isLauncher,beforeIsPinned:_==null?void 0:_.isPinned}),Ae.trackPromptAction({action:"open_tool",surface:"ai_input_prompt_popover",promptType:e,status:"success",metadata:{tool_id:H.id}}),I(!1),tn.openTool(H,{componentProps:{initialCategory:e}});const R=tn.getToolState("prompt-history");console.info("[PromptHistoryPopover] requested my prompts open",{generationType:e,afterStatus:R==null?void 0:R.status,afterInstanceId:R==null?void 0:R.instanceId,afterIsLauncher:R==null?void 0:R.isLauncher,afterIsPinned:R==null?void 0:R.isPinned})},[e,d]);return p.jsxs("div",{ref:D,className:"prompt-history-popover",children:[p.jsxs("div",{className:"prompt-history-popover__actions",children:[p.jsx("button",{className:"prompt-history-popover__trigger",title:E,"data-track":"ai_input_click_history",onMouseEnter:g,onMouseLeave:N,children:p.jsx(lr,{size:18})}),s]}),S&&p.jsx("div",{className:"prompt-history-popover__panel-wrapper",onMouseEnter:g,onMouseLeave:N,children:p.jsx(Yr,{title:E,items:P,onSelect:U,onTogglePin:ne,onDelete:ee,onTitleClick:ae,language:t,showCount:!0,analyticsSurface:"ai_input_prompt_popover",analyticsPromptType:e})}),k]})};function ga(e){var n;return!!((n=e.params)!=null&&n.longVideoMeta)}function wa(e){var n;return((n=e.params)==null?void 0:n.longVideoMeta)||null}class At{constructor(){this.isInitialized=!1,this.batches=new Map,this.initTimestamp=0}static getInstance(){return At.instance||(At.instance=new At),At.instance}initialize(){this.isInitialized||(this.isInitialized=!0,this.initTimestamp=Date.now(),gs.observeTaskUpdates().subscribe(n=>{if(n.type==="taskUpdated"&&n.task.status===Tt.COMPLETED&&n.task.type===dr.VIDEO&&ga(n.task)){if((n.task.completedAt||0)<this.initTimestamp)return;this.handleSegmentCompleted(n.task).catch(s=>{console.error("[LongVideoChain] Error handling completed segment:",s)})}}))}async handleSegmentCompleted(n){var l;const t=wa(n);if(!t)return;const{segmentIndex:s,totalSegments:d,scripts:c,batchId:a}=t,h=(l=n.result)==null?void 0:l.url;let u=this.batches.get(a);if(u||(u={batchId:a,totalSegments:d,completedSegments:new Map,processedSegments:new Set,creatingNextFor:null,isMerging:!1,mergeCompleted:!1,scripts:c||[],characterReferenceUrls:t.characterReferenceUrls,characterDescription:t.characterDescription},this.batches.set(a,u)),!u.processedSegments.has(s)){if(u.processedSegments.add(s),h&&u.completedSegments.set(s,h),u.completedSegments.size===d){await this.mergeAndInsert(u);return}if(u.creatingNextFor!==s&&s<d){u.creatingNextFor=s;try{await this.createNextSegment(n,t,c,h,u.characterReferenceUrls,u.characterDescription)}finally{u.creatingNextFor=null}}}}async createNextSegment(n,t,s,d,c,a){const h=t.segmentIndex+1,u=s.find(k=>k.index===h);if(!u){console.error(`[LongVideoChain] Script not found for segment ${h}`);return}let l;if(d)try{l=(await ur(d)).dataUrl}catch(k){console.error("[LongVideoChain] Failed to extract last frame:",k)}const v={...t,segmentIndex:h,needsLastFrame:h<t.totalSegments,characterReferenceUrls:c??t.characterReferenceUrls,characterDescription:a??t.characterDescription};Xr(u,v,l)}async mergeAndInsert(n){if(!(n.isMerging||n.mergeCompleted)){n.isMerging=!0;try{const t=[];for(let a=1;a<=n.totalSegments;a++){const h=n.completedSegments.get(a);h&&t.push(h)}if(t.length===0){console.error("[LongVideoChain] No video URLs to merge");return}const s=this.extractTransitions(n),c=await pr(t,(a,h,u)=>{const l=u||`${h} ${a.toFixed(1)}%`},{transitions:s,transitionDuration:.5});await this.insertMergedVideo(c.url),n.mergeCompleted=!0,this.cleanupBatch(n.batchId)}catch(t){console.error("[LongVideoChain] Merge failed:",t),this.cleanupBatch(n.batchId)}finally{n.isMerging=!1}}}async insertMergedVideo(n){try{await Zr("video",n)}catch(t){console.error("[LongVideoChain] Failed to insert video to canvas:",t)}}extractTransitions(n){return!n.scripts||n.scripts.length===0?[]:n.scripts.sort((t,s)=>t.index-s.index).slice(0,-1).map(t=>t.transition_hint||"cut")}cleanupBatch(n){const t=this.batches.get(n);t&&(t.completedSegments.clear(),t.processedSegments.clear(),this.batches.delete(n))}getBatchStatus(n){const t=this.batches.get(n);return t?{completed:t.completedSegments.size,total:t.totalSegments,isMerging:t.isMerging,mergeCompleted:t.mergeCompleted}:null}}const Ia=At.getInstance();function ya(){Ia.initialize()}function ts(){return`img-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function ns(e){return new Promise((n,t)=>{const s=new Image,d=e.startsWith("http")&&!e.startsWith(location.origin);s.crossOrigin="anonymous",s.onload=()=>n(s),s.onerror=()=>{t(d?new Error("无法加载外部图片,可能是跨域 (CORS) 限制。请先下载图片到本地后再操作。"):new Error("图片加载失败,请检查图片是否有效"))},s.src=e})}function xa(e,n=.92){return e.toDataURL("image/jpeg",n)}class _a{async split(n,t){const{rows:s,cols:d}=t;if(s<1||d<1)throw new Error("Grid rows and cols must be at least 1");const c=await ns(n),a=c.naturalWidth,h=c.naturalHeight,u=Math.floor(a/d),l=Math.floor(h/s),v=[];for(let k=0;k<s;k++)for(let S=0;S<d;S++){const I=k*d+S,f=S*u,D=k*l,y=document.createElement("canvas");y.width=u,y.height=l;const C=y.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(c,f,D,u,l,0,0,u,l);const E=xa(y);v.push({id:ts(),imageData:E,originalIndex:I,width:u,height:l})}return v}async splitToBlob(n,t){const{rows:s,cols:d}=t;if(s<1||d<1)throw new Error("Grid rows and cols must be at least 1");const c=await ns(n),a=c.naturalWidth,h=c.naturalHeight,u=Math.floor(a/d),l=Math.floor(h/s),v=[];for(let k=0;k<s;k++)for(let S=0;S<d;S++){const I=k*d+S,f=S*u,D=k*l,y=document.createElement("canvas");y.width=u,y.height=l;const C=y.getContext("2d");if(!C)throw new Error("Failed to get canvas 2d context");C.drawImage(c,f,D,u,l,0,0,u,l);const E=await new Promise((g,N)=>{y.toBlob(U=>{U?g(U):N(new Error("Failed to create blob"))},"image/png",.92)}),P=URL.createObjectURL(E);v.push({id:ts(),imageData:P,originalIndex:I,width:u,height:l})}return v}revokeBlobUrls(n){for(const t of n)t.imageData.startsWith("blob:")&&URL.revokeObjectURL(t.imageData)}}const os=new _a;function Ee(e,n){return Math.random()*(n-e)+e}function bn(e){const n=[...e];for(let t=n.length-1;t>0;t--){const s=Math.floor(Math.random()*(t+1));[n[t],n[s]]=[n[s],n[t]]}return n}class ba{calculate(n,t,s,d){switch(t){case"scattered":return this.scatteredLayout(n,s,d);case"grid":return this.gridLayout(n,s);case"circular":return this.circularLayout(n,s,d);case"inspiration-board":return this.inspirationBoardLayout(n,s,d);default:return console.warn(`[LayoutEngine] Unknown layout style: ${t}, falling back to grid`),this.gridLayout(n,s)}}scatteredLayout(n,t,s){const{maxRotation:d=15,minScale:c=.85,maxScale:a=1.15,positionJitter:h=40}=s||{},{canvasWidth:u,canvasHeight:l,startX:v,startY:k,gap:S=20}=t,I=n.length,f=Math.ceil(Math.sqrt(I)),D=Math.ceil(I/f),y=Math.max(...n.map(ne=>ne.width)),C=Math.max(...n.map(ne=>ne.height)),E=u-S*2,P=l-S*2,g=E/f,N=P/D,U=Math.min((g-S)/y,(N-S)/C,1),ee=bn(n.map((ne,ae)=>ae));return n.map((ne,ae)=>{const H=Math.floor(ae/f),_=ae%f,R=v+S+_*g+g/2,$=k+S+H*N+N/2,Q=Ee(-h,h),V=Ee(-h,h),ie=Ee(-d,d),Se=Ee(c,a),Me=U*Se,Dt=ne.width*Me,nn=ne.height*Me;return{...ne,x:R+Q-Dt/2,y:$+V-nn/2,rotation:ie,scale:Me,zIndex:ee[ae]}})}gridLayout(n,t){const{canvasWidth:s,canvasHeight:d,startX:c,startY:a,gap:h=20}=t,u=n.length,l=Math.ceil(Math.sqrt(u)),v=Math.ceil(u/l),k=Math.max(...n.map(E=>E.width)),S=Math.max(...n.map(E=>E.height)),I=s-h*(l+1),f=d-h*(v+1),D=I/l,y=f/v,C=Math.min(D/k,y/S,1);return n.map((E,P)=>{const g=Math.floor(P/l),N=P%l,U=E.width*C,ee=E.height*C,ne=c+h+N*(D+h),ae=a+h+g*(y+h),H=ne+(D-U)/2,_=ae+(y-ee)/2;return{...E,x:H,y:_,rotation:0,scale:C,zIndex:P}})}circularLayout(n,t,s){const{centerIndex:d=-1,radius:c,startAngle:a=-90}=s||{},{canvasWidth:h,canvasHeight:u,startX:l,startY:v}=t,k=l+h/2,S=v+u/2,I=d>=0&&d<n.length?n.filter((_,R)=>R!==d):n,f=d>=0&&d<n.length?n[d]:null,D=Math.max(...n.map(_=>_.width)),y=Math.max(...n.map(_=>_.height)),C=Math.max(D,y),E=I.length,P=C*.8,g=E*C*1.2,N=Math.max(P,g/(2*Math.PI)),U=c||Math.min(N,Math.min(h,u)/2-C/2),ee=Math.min(h,u),ne=Math.min(ee*.25/C,1),ae=[];if(f){const _=f.width*ne*1.2,R=f.height*ne*1.2;ae.push({...f,x:k-_/2,y:S-R/2,rotation:0,scale:ne*1.2,zIndex:E})}const H=360/E;return I.forEach((_,R)=>{const Q=(a+R*H)*Math.PI/180,V=_.width*ne,ie=_.height*ne,Se=k+U*Math.cos(Q)-V/2,Me=S+U*Math.sin(Q)-ie/2;ae.push({..._,x:Se,y:Me,rotation:0,scale:ne,zIndex:R})}),ae}inspirationBoardLayout(n,t,s){const{minWidthRatio:d=In.minWidthRatio,maxWidthRatio:c=In.maxWidthRatio,maxRotation:a=In.maxRotation,gap:h=In.gap}=s||{},{canvasWidth:u,canvasHeight:l,startX:v,startY:k}=t,S=n.length,I=this.assignSizeCategories(S),f=n.reduce((N,U)=>N+U.width,0)/S,D=n.reduce((N,U)=>N+U.height,0)/S,y=u||1200,C=l||600,E=Math.min(y*.25/f,C*.4/D,1),P=this.calculateInspirationBoardPositions(S,y,C,h),g=bn(n.map((N,U)=>U));return n.map((N,U)=>{const ee=P[U],ne=I[U];let ae;switch(ne){case"large":ae=Ee(1.2,c);break;case"medium":ae=Ee(.9,1.1);break;case"small":ae=Ee(d,.85);break;default:ae=1}const H=E*ae,_=Ee(-a,a),R=Ee(-20,20),$=Ee(-15,15),Q=N.width*H,V=N.height*H;return{...N,x:v+ee.x+R-Q/2,y:k+ee.y+$-V/2,rotation:_,scale:H,zIndex:g[U]}})}assignSizeCategories(n){const t=[],s=Math.max(2,Math.floor(n*.25)),d=Math.max(2,Math.floor(n*.25)),c=n-s-d;for(let a=0;a<s;a++)t.push("large");for(let a=0;a<c;a++)t.push("medium");for(let a=0;a<d;a++)t.push("small");return bn(t)}calculateInspirationBoardPositions(n,t,s,d){const c=[],a=Math.ceil(n/4),h=Math.ceil(n/a),u=(t-d*2)/h,l=(s-d*2)/a;for(let v=0;v<n;v++){const k=Math.floor(v/h),S=v%h,I=d+S*u+u/2,f=d+k*l+l/2,D=Ee(-u*.3,u*.3),y=Ee(-l*.2,l*.2);c.push({x:I+D,y:f+y})}return bn(c)}calculateRequiredSize(n,t,s=.5){const d=n.length,c=Math.ceil(Math.sqrt(d)),a=Math.ceil(d/c),h=Math.max(...n.map(I=>I.width)),u=Math.max(...n.map(I=>I.height)),l=20,v=t==="scattered"?60:40,k=c*h*s+(c+1)*l+v*2,S=a*u*s+(a+1)*l+v*2;return{width:k,height:S}}}const ss=new ba;class va{constructor(){this.board=null}setBoard(n){this.board=n}getBoard(){return this.board}async generate(n){const{theme:t,gridConfig:s=yn.gridConfig,layoutStyle:d=yn.layoutStyle,imageSize:c=yn.imageSize,imageQuality:a=yn.imageQuality}=n;try{const h=this.buildPrompt(t,s),u=await mr.generateImage(h,{size:c,quality:a,response_format:"url"});if(!u.data||u.data.length===0)throw new Error("AI 生成图片失败:未返回图片数据");const l=u.data[0].url||u.data[0].b64_json,v=l&&hr(String(l));if(!v)throw new Error("AI 生成图片失败:未返回图片 URL");const k=await Oo.getImageForAI(v),S=k.type==="base64"?k.value:v,I=await os.split(S,s),f=this.calculateLayoutParams(I),D=ss.calculate(I,d,f);return{success:!0,originalImageUrl:v,elements:D}}catch(h){return console.error("[GridImageService] Generation failed:",h),{success:!1,error:h.message||"宫格图生成失败"}}}async processExistingImage(n,t,s="scattered"){try{const d=await Oo.getImageForAI(n),c=d.type==="base64"?d.value:n,a=await os.split(c,t),h=this.calculateLayoutParams(a),u=ss.calculate(a,s,h);return{success:!0,originalImageUrl:n,elements:u}}catch(d){return console.error("[GridImageService] Processing failed:",d),{success:!1,error:d.message||"宫格图处理失败"}}}async insertToBoard(n,t){if(!this.board)throw new Error("画板未初始化,请先调用 setBoard");let s=(t==null?void 0:t[0])??100,d=t==null?void 0:t[1];if(d===void 0){const a=fr(this.board);d=(a==null?void 0:a[1])??100,s=(a==null?void 0:a[0])??s}const c=[...n].sort((a,h)=>a.zIndex-h.zIndex);for(const a of c){const h=s+a.x,u=d+a.y,l={url:a.imageData,width:a.width*a.scale,height:a.height*a.scale};gr.insertImage(this.board,l,[h,u])}}async generateAndInsert(n,t){const s=await this.generate(n);return s.success&&s.elements&&await this.insertToBoard(s.elements,t),s}buildPrompt(n,t){const s=qr.zh;return s(n,t.rows,t.cols)}calculateLayoutParams(n){const t=n.reduce((I,f)=>I+f.width,0),s=n.reduce((I,f)=>I+f.height,0),d=n.length,c=Math.ceil(Math.sqrt(d)),a=Math.ceil(d/c),h=t/d,u=s/d,l=30,v=50,k=c*h+(c+1)*l+v*2,S=a*u+(a+1)*l+v*2;return{canvasWidth:k,canvasHeight:S,startX:0,startY:0,gap:l}}}const rs=new va;function Sa(e){return{cleanText:e,selectedAudioModel:null,selectedImageModel:null,selectedVideoModel:null,selectedParams:[],selectedCount:null}}function ka(){const e=Cn.get();return(e==null?void 0:e.imageModelName)||pt()}function Ma(){const e=Cn.get();return(e==null?void 0:e.videoModelName)||Pt()}function Ca(){const e=Cn.get();return(e==null?void 0:e.audioModelName)||Et()}function as(){const e=Cn.get();return(e==null?void 0:e.textModelName)||qn()}function Ta(e,n,t){if(n.length>0)return n.join(`
3
+ `);if(e){if(t===1)return"请仔细分析这张图片的内容、风格、构图、色调和艺术特点,推测生成这张图片可能使用的原始提示词,然后基于你推测的提示词重新生成一张全新的、风格相似但内容不完全相同的图片。不要直接复制原图。";if(t>1)return"请分析这些图片的主题、风格和视觉元素,找出它们之间的共同点或关联性,然后创造性地将它们融合成一张全新的、和谐统一的图片。融合时请保持各图片的精华元素,确保最终作品在构图、色调和风格上协调一致。"}return""}function Jt(e){return e.replace(":","x").toLowerCase()}function Pa(e,n,t){const s=n.texts.length>0||n.images.length>0||n.videos.length>0||n.graphics.length>0,d=n.texts,c=n.images.length+n.graphics.length,a=Sa(e),h=a.cleanText.trim().length>0;let u=(t==null?void 0:t.generationType)||"image",l,v=!1;if(t!=null&&t.modelId){const g=Ve(t.modelId);t.generationType||((g==null?void 0:g.type)==="video"?u="video":(g==null?void 0:g.type)==="audio"?u="audio":(g==null?void 0:g.type)==="text"?u="text":u="image"),l=t.modelId,v=!0}else a.selectedAudioModel?(u="audio",l=a.selectedAudioModel,v=!0):a.selectedVideoModel?(u="video",l=a.selectedVideoModel,v=!0):a.selectedImageModel?(u="image",l=a.selectedImageModel,v=!0):!s&&h&&!(t!=null&&t.generationType)?(u="agent",l=as()):u==="video"?l=Ma():u==="audio"?l=Ca():u==="text"||u==="agent"?l=as():l=ka();let k;(t==null?void 0:t.generationType)==="image"||(t==null?void 0:t.generationType)==="video"||(t==null?void 0:t.generationType)==="audio"||(t==null?void 0:t.generationType)==="text"?k="direct_generation":(t==null?void 0:t.generationType)==="agent"?k="agent_flow":k=h?"agent_flow":"direct_generation";const S=a.cleanText.trim(),I=d.join(`
4
+ `).trim();let f;if(I&&S?f=`${I}
5
+
6
+ ${S}`:S?f=S:I?f=I:s&&c>0?f=u==="text"?"":Ta(s,[],c):f="",l.startsWith("mj")&&(t!=null&&t.params)){const g=da(t.params);g&&(f=[f,g].filter(Boolean).join(" "))}const D=(t==null?void 0:t.count)||a.selectedCount||1;let y,C,E;if(t!=null&&t.params){u!=="audio"&&u!=="text"&&u!=="agent"&&!l.startsWith("mj")&&t.params.size&&(y=Jt(t.params.size)),t.params.duration&&(C=t.params.duration);const g={};for(const[N,U]of Object.entries(t.params))N!=="size"&&N!=="duration"&&U&&(g[N]=U);Object.keys(g).length>0&&(E=g)}if(!y&&(t!=null&&t.size)&&t.size!=="auto"&&(y=Jt(t.size)),!y&&(t==null?void 0:t.size)!=="auto"){for(const g of a.selectedParams)if(g.id==="size"){y=Jt(g.value);break}}if(!C){for(const g of a.selectedParams)if(g.id==="duration"){C=g.value;break}}if(!y&&(t==null?void 0:t.size)!=="auto"&&u!=="text"&&u!=="agent"&&u!=="audio"){const g=Ve(l);if((g==null?void 0:g.type)==="image"&&g.imageDefaults)y="1x1";else if((g==null?void 0:g.type)==="video"&&g.videoDefaults){const N=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params);y=Jt(N.size||g.videoDefaults.size),C||(C=N.duration||g.videoDefaults.duration)}else if(u==="image")y="1x1";else if(u==="video"){const N=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params);y=Jt(N.size),C||(C=N.duration)}}!C&&u==="video"&&(C=Hn(l,(t==null?void 0:t.modelRef)||l,t==null?void 0:t.params).duration);const P=a.cleanText.trim();return{scenario:k,generationType:u,modelId:l,modelRef:(t==null?void 0:t.modelRef)||null,defaultModels:t==null?void 0:t.defaultModels,defaultModelRefs:t==null?void 0:t.defaultModelRefs,isModelExplicit:v,prompt:f,userInstruction:P,rawInput:e,count:D,size:y,duration:C,extraParams:E,parseResult:a,hasExtraContent:h,selection:n}}const Yn={id:et,name:"自动"},is=Jn.map(e=>({id:e.id,name:e.name,isSystem:!0,mcpTool:e.mcpTool,outputType:e.outputType})),Ea=({value:e,onSelect:n,onSelectSkill:t,onAddSkill:s,disabled:d=!1})=>{const[c,a]=r.useState(!1),[h,u]=r.useState([]),[l,v]=r.useState([]),[k,S]=r.useState(""),[I,f]=r.useState(0),D=r.useRef(null),y=r.useRef(null),C=r.useCallback(async()=>{try{const R=(await Mn.getAllDirectories()).find(ie=>ie.name==="Skill");if(!R)return;const $=await Mn.getNoteMetasByDirectory(R.id),Q=new Set(Jn.map(ie=>ie.id)),V=$.filter(ie=>!Q.has(ie.id)).map(ie=>{var Se;return{id:ie.id,name:ie.title,outputType:((Se=ie.metadata)==null?void 0:Se.outputType)||void 0}});u(V)}catch{}},[]),E=r.useCallback(async()=>{try{const _=await eo.getAllExternalSkillsMeta(),R=new Set(Jn.map(Q=>Q.id)),$=_.filter(Q=>!R.has(Q.id)).map(Q=>({id:Q.id,name:Q.name,isExternal:!0,source:Q.source,outputType:Q.outputType}));v($)}catch{}},[]);r.useEffect(()=>{if(c){C(),E(),S("");const R=[Yn,...is,...l,...h].findIndex($=>$.id===e);f(R>=0?R:0),setTimeout(()=>{var $;return($=y.current)==null?void 0:$.focus()},50)}},[c,e]),r.useEffect(()=>{if(c&&D.current){const _=D.current.children[I];_&&_.scrollIntoView({block:"nearest"})}},[I,c]);const P=r.useCallback(_=>{_.preventDefault(),!d&&a(R=>!R)},[d]),g=r.useCallback(_=>{n(_.id),t==null||t(_),a(!1)},[n,t]),N=r.useCallback(_=>{_.stopPropagation(),a(!1),s()},[s]),U=[Yn,...is,...l,...h],ee=k.trim()?U.filter(_=>_.name.toLowerCase().includes(k.toLowerCase())||_.id.toLowerCase().includes(k.toLowerCase())):U,ne=U.length>15,ae=r.useCallback(_=>_==="Escape"?(a(!1),!0):_==="ArrowDown"?(f(R=>R<ee.length-1?R+1:0),!0):_==="ArrowUp"?(f(R=>R>0?R-1:ee.length-1),!0):_==="Enter"||_===" "||_==="Tab"?(I<ee.length&&g(ee[I]),!0):!1,[I,ee,g]),H=ee.find(_=>_.id===e)||Yn;return p.jsx(ao,{isOpen:c,setIsOpen:a,disabled:d,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:ae,children:({containerRef:_,menuRef:R,portalPosition:$,handleTriggerKeyDown:Q})=>p.jsxs("div",{className:"skill-dropdown",ref:_,children:[p.jsxs("button",{className:`skill-dropdown__trigger ${c?"skill-dropdown__trigger--open":""}`,onMouseDown:P,onKeyDown:Q,disabled:d,type:"button",title:`Skill: ${H.name}`,children:[p.jsx("span",{className:"skill-dropdown__icon-prefix",children:p.jsx(Wo,{size:14})}),p.jsx("span",{className:"skill-dropdown__label",children:H.name}),p.jsx(no,{size:14,className:`skill-dropdown__chevron ${c?"skill-dropdown__chevron--open":""}`})]}),c&&to.createPortal(p.jsxs("div",{ref:R,className:`skill-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:$.left,bottom:window.innerHeight-$.top+8},onMouseDown:V=>V.stopPropagation(),onClick:V=>V.stopPropagation(),children:[p.jsxs("div",{className:"skill-dropdown__header",children:[p.jsx(Wo,{size:14}),p.jsx("span",{children:"Skill"})]}),ne&&p.jsx("div",{className:"skill-dropdown__search",children:p.jsx("input",{ref:y,type:"text",className:"skill-dropdown__search-input",placeholder:"搜索 Skill...",value:k,onChange:V=>{S(V.target.value),f(0)},onMouseDown:V=>V.stopPropagation(),onKeyDown:V=>V.stopPropagation()})}),p.jsx("div",{ref:D,className:"skill-dropdown__list",children:ee.map((V,ie)=>{const Se=V.id===e,Me=ie===I;return p.jsxs("div",{className:`skill-dropdown__item ${Se?"skill-dropdown__item--selected":""} ${Me?"skill-dropdown__item--highlighted":""}`,onClick:()=>g(V),onMouseEnter:()=>f(ie),children:[p.jsx("span",{className:"skill-dropdown__item-label",children:V.name}),V.outputType==="image"&&p.jsx(ws,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="video"&&p.jsx(Is,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="ppt"&&p.jsx(wr,{size:12,className:"skill-dropdown__item-image-icon"}),V.outputType==="audio"&&p.jsx(Ir,{size:12,className:"skill-dropdown__item-image-icon"}),V.isSystem&&p.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),V.isExternal&&p.jsx("span",{className:"skill-dropdown__item-badge",children:"系统"}),Se&&p.jsx(so,{size:14,className:"skill-dropdown__item-check"})]},V.id)})}),p.jsx("div",{className:"skill-dropdown__divider"}),p.jsxs("div",{className:"skill-dropdown__add-btn",onClick:N,onMouseDown:V=>V.preventDefault(),children:[p.jsx(yr,{size:14}),p.jsx("span",{children:"添加 Skill"})]})]}),document.body)]})})},cs=["image","video","audio"];function Aa(e){if(e==="image"||e==="video"||e==="audio")return e}function Ct(e){if(!e)return[];const n=Aa(e.outputType);if(n)return[n];if(e.outputType==="text")return[];const t=new Set,s=Jr(e.mcpTool);s&&t.add(s);const d=[e.id,e.name,e.description,e.content].filter(Boolean).join(`
7
+ `);if(d)for(const c of cs)Da(c).some(h=>d.includes(h))&&t.add(c);return cs.filter(c=>t.has(c))}function Da(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 We=(e=>(e.VIDEO="视频创作",e.IMAGE="图片生成",e.MINDMAP="思维导图",e.FLOWCHART="流程图",e.GRID="宫格图",e.SVG="SVG矢量图",e))(We||{});const Qt=3,ls=[{id:"grid-emoji",title:"智能拆分宫格图",description:"宫格图,风格统一",prompt:"生成16宫格猫咪表情包",category:We.GRID,imageUrl:"https://tuziphoto.codernote.club/aitu/gonggetu.jpg",badgeColor:"badge--grid"},{id:"flowchart-process",title:"业务流程图",description:"使用 Mermaid 语法生成清晰的流程图",prompt:"绘制一个用户注册登录的流程图,包含邮箱验证、密码校验、短信验证码、登录成功/失败等节点",category:We.FLOWCHART,imageUrl:"https://tuziphoto.codernote.club/aitu/liuchengtu.png",badgeColor:"badge--flowchart"},{id:"mindmap-project",title:"项目规划脑图",description:"快速生成结构化的思维导图,梳理项目计划",prompt:"创建一个关于「移动应用开发」的思维导图,包含需求分析、UI设计、前端开发、后端开发、测试上线等主要分支",category:We.MINDMAP,imageUrl:"https://tuziphoto.codernote.club/aitu/siweidaotu.png",badgeColor:"badge--mindmap"}],Ra={[We.VIDEO]:{bg:"#fce7f3",text:"#be185d"},[We.IMAGE]:{bg:"#dbeafe",text:"#1d4ed8"},[We.MINDMAP]:{bg:"#dcfce7",text:"#15803d"},[We.FLOWCHART]:{bg:"#fef3c7",text:"#b45309"},[We.GRID]:{bg:"#f3e8ff",text:"#7c3aed"},[We.SVG]:{bg:"#e0e7ff",text:"#4338ca"}},Na=({template:e,onClick:n})=>{const t=Ra[e.category],s=d=>{d.preventDefault()};return p.jsxs("div",{className:"inspiration-card",onMouseDown:s,onClick:n,"data-track":`inspiration_click_${e.id}`,children:[p.jsxs("div",{className:"inspiration-card__image-wrapper",children:[p.jsx("img",{src:e.imageUrl,alt:e.title,className:"inspiration-card__image",loading:"lazy"}),p.jsx("span",{className:"inspiration-card__badge",style:{backgroundColor:t.bg,color:t.text},children:e.category}),p.jsx("div",{className:"inspiration-card__hover-overlay",children:p.jsx("div",{className:"inspiration-card__arrow",children:p.jsx(xr,{size:16})})})]}),p.jsxs("div",{className:"inspiration-card__content",children:[p.jsx("h3",{className:"inspiration-card__title",children:e.title}),p.jsx("p",{className:"inspiration-card__description",children:e.description})]})]})},ds="aitu_hide_inspiration_board",ja=({isCanvasEmpty:e,onSelectPrompt:n,onOpenPromptTool:t,visible:s=!0,className:d=""})=>{const[c,a]=r.useState(0),[h,u]=r.useState(!1);r.useEffect(()=>{localStorage.getItem(ds)==="true"&&u(!0)},[]);const l=Math.ceil(ls.length/Qt),v=l>1,k=ls.slice(c*Qt,(c+1)*Qt),S=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),a(C=>(C-1+l)%l)},[l]),I=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),a(C=>(C+1)%l)},[l]),f=r.useCallback(y=>{n({prompt:y,modelType:"agent"})},[n]),D=r.useCallback(y=>{y.preventDefault(),y.stopPropagation(),u(!0),localStorage.setItem(ds,"true")},[]);return!e||!s||h?null:p.jsxs("div",{className:`inspiration-board ${d}`,children:[p.jsxs("div",{className:"inspiration-board__header",children:[p.jsx("h3",{className:"inspiration-board__title",children:"灵感创意"}),p.jsxs("button",{className:"inspiration-board__hide-btn",onClick:D,onMouseDown:y=>y.preventDefault(),title:"不再提示","data-track":"inspiration_click_hide",children:[p.jsx(_r,{size:14}),p.jsx("span",{children:"不再提示"})]}),t&&p.jsxs("button",{className:"inspiration-board__prompt-btn",onClick:t,onMouseDown:y=>y.preventDefault(),title:"提示词工具","data-track":"inspiration_click_prompt_tool",children:[p.jsx(br,{size:14}),p.jsx("span",{children:"提示词"})]}),v&&p.jsxs("div",{className:"inspiration-board__pagination",children:[p.jsxs("span",{className:"inspiration-board__page-indicator",children:[c+1," / ",l]}),p.jsxs("div",{className:"inspiration-board__nav-buttons",children:[p.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:y=>y.preventDefault(),onClick:S,"aria-label":"上一页","data-track":"inspiration_click_prev",children:p.jsx(vr,{size:16})}),p.jsx("button",{className:"inspiration-board__nav-btn",onMouseDown:y=>y.preventDefault(),onClick:I,"aria-label":"下一页","data-track":"inspiration_click_next",children:p.jsx(Sr,{size:16})})]})]})]}),p.jsxs("div",{className:"inspiration-board__grid",children:[k.map(y=>p.jsx(Na,{template:y,onClick:()=>f(y.prompt)},y.id)),k.length<Qt&&Array.from({length:Qt-k.length}).map((y,C)=>p.jsx("div",{className:"inspiration-card inspiration-card--placeholder"},`placeholder-${C}`))]})]})},ut=[{value:"image",label:"图片",icon:p.jsx(ws,{size:14}),zh:"图片",en:"Image"},{value:"video",label:"视频",icon:p.jsx(Is,{size:14}),zh:"视频",en:"Video"},{value:"audio",label:"音频",icon:p.jsx(Mr,{size:14}),zh:"音频",en:"Audio"},{value:"text",label:"文本",icon:p.jsx(Cr,{size:14}),zh:"文本",en:"Text"},{value:"agent",label:"Agent",icon:p.jsx(Tr,{size:14}),zh:"Agent",en:"Agent"}],za=({value:e,onSelect:n,disabled:t=!1})=>{const[s,d]=r.useState(!1),{language:c}=ro(),[a,h]=r.useState(0),u=r.useRef(null);r.useEffect(()=>{if(s){const I=ut.findIndex(f=>f.value===e);h(I>=0?I:0)}},[s,e]),r.useEffect(()=>{if(s&&u.current){const I=u.current.children[a];I&&I.scrollIntoView({block:"nearest"})}},[a,s]);const l=r.useCallback(I=>{I.preventDefault(),!t&&d(f=>!f)},[t]),v=r.useCallback(I=>{n(I),d(!1)},[n]),k=r.useCallback(I=>I==="Escape"?(d(!1),!0):I==="ArrowDown"?(h(f=>f<ut.length-1?f+1:0),!0):I==="ArrowUp"?(h(f=>f>0?f-1:ut.length-1),!0):I==="Enter"||I===" "||I==="Tab"?(v(ut[a].value),!0):!1,[a,v]),S=ut.find(I=>I.value===e)||ut[0];return p.jsx(ao,{isOpen:s,setIsOpen:d,disabled:t,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:k,children:({containerRef:I,menuRef:f,portalPosition:D,handleTriggerKeyDown:y})=>p.jsxs("div",{className:"generation-type-dropdown",ref:I,children:[p.jsxs("button",{className:`generation-type-dropdown__trigger ${s?"generation-type-dropdown__trigger--open":""}`,onMouseDown:l,onKeyDown:y,disabled:t,type:"button",title:`${c==="zh"?"生成类型":"Type"}: ${c==="zh"?S.zh:S.en} (↑↓ Tab)`,children:[p.jsx("span",{className:"generation-type-dropdown__icon-prefix",children:S.icon}),p.jsx("span",{className:"generation-type-dropdown__label",children:c==="zh"?S.zh:S.en}),p.jsx(no,{size:14,className:`generation-type-dropdown__chevron ${s?"generation-type-dropdown__chevron--open":""}`})]}),s&&to.createPortal(p.jsxs("div",{ref:f,className:`generation-type-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:D.left,bottom:window.innerHeight-D.top+8},onMouseDown:C=>C.stopPropagation(),onClick:C=>C.stopPropagation(),children:[p.jsxs("div",{className:"generation-type-dropdown__header",children:[p.jsx(kr,{size:14}),p.jsx("span",{children:c==="zh"?"生成类型 (↑↓ Tab)":"Generation type (↑↓ Tab)"})]}),p.jsx("div",{ref:u,className:"generation-type-dropdown__list",children:ut.map((C,E)=>{const P=C.value===e,g=E===a;return p.jsxs("div",{className:`generation-type-dropdown__item ${P?"generation-type-dropdown__item--selected":""} ${g?"generation-type-dropdown__item--highlighted":""}`,onClick:()=>v(C.value),onMouseEnter:()=>h(E),children:[p.jsx("span",{className:"generation-type-dropdown__item-icon",children:C.icon}),p.jsx("span",{className:"generation-type-dropdown__item-label",children:c==="zh"?C.zh:C.en}),P&&p.jsx(so,{size:14,className:"generation-type-dropdown__item-check"})]},C.value)})})]}),document.body)]})})},en=[1,2,3,4,5,10,20],Oa=({value:e,onSelect:n,disabled:t=!1,isOpen:s,onOpenChange:d})=>{const{value:c,setValue:a}=Qr({controlledValue:s,defaultValue:!1,onChange:d}),{language:h}=ro(),[u,l]=r.useState(0),v=r.useRef(null);r.useEffect(()=>{if(c){const f=en.indexOf(e);l(f>=0?f:0)}},[c,e]),r.useEffect(()=>{if(c&&v.current){const f=v.current.children[u];f&&f.scrollIntoView({block:"nearest"})}},[u,c]);const k=r.useCallback(f=>{f.preventDefault(),!t&&a(!c)},[t,c,a]),S=r.useCallback(f=>{n(f),a(!1)},[n]),I=r.useCallback(f=>f==="Escape"?(a(!1),!0):f==="ArrowDown"?(l(D=>D<en.length-1?D+1:0),!0):f==="ArrowUp"?(l(D=>D>0?D-1:en.length-1),!0):f==="Enter"||f===" "||f==="Tab"?(S(en[u]),!0):!1,[u,S]);return p.jsx(ao,{isOpen:c,setIsOpen:a,disabled:t,openKeys:["Enter"," ","ArrowDown","ArrowUp"],onOpenKey:I,children:({containerRef:f,menuRef:D,portalPosition:y,handleTriggerKeyDown:C})=>p.jsxs("div",{className:"count-dropdown",ref:f,children:[p.jsxs("button",{className:`count-dropdown__trigger ${c?"count-dropdown__trigger--open":""}`,onMouseDown:k,onKeyDown:C,disabled:t,type:"button",title:`${h==="zh"?"生成数量":"Count"}: ${e} (↑↓ Tab)`,children:[p.jsxs("span",{className:"count-dropdown__label",children:[e,h==="zh"?"个":""]}),p.jsx(no,{size:14,className:`count-dropdown__chevron ${c?"count-dropdown__chevron--open":""}`})]}),c&&to.createPortal(p.jsxs("div",{ref:D,className:`count-dropdown__menu ${Tn}`,style:{position:"fixed",zIndex:oo.DROPDOWN_PORTAL,left:y.left,bottom:window.innerHeight-y.top+8},onMouseDown:E=>E.stopPropagation(),onClick:E=>E.stopPropagation(),children:[p.jsx("div",{className:"count-dropdown__header",children:p.jsx("span",{children:h==="zh"?"生成数量 (↑↓ Tab)":"Count (↑↓ Tab)"})}),p.jsx("div",{ref:v,className:"count-dropdown__list",children:en.map((E,P)=>{const g=E===e,N=P===u;return p.jsxs("div",{className:`count-dropdown__item ${g?"count-dropdown__item--selected":""} ${N?"count-dropdown__item--highlighted":""}`,onClick:()=>S(E),onMouseEnter:()=>l(P),children:[p.jsxs("span",{className:"count-dropdown__item-label",children:[E,h==="zh"?"个":E>1?" items":" item"]}),g&&p.jsx(so,{size:14,className:"count-dropdown__item-check"})]},E)})})]}),document.body)]})})},bs=["right","bottom","left","top"],vn=4;function Wa(e,n,t,s,d=32){const c=s<=2?s:s<=4?2:3,a=Math.floor(t/c),h=t%c;return[e[0]+h*(n.width+d),e[1]+a*(n.height+d)]}function vs(e,n){const{ignoreElementIds:t=[],ignoreTypes:s=["workzone"],extraOccupiedRects:d=[]}=n;return[...e.children.filter(La).filter(c=>!s.includes(c.type??"")&&!t.includes(c.id??"")).map(c=>({...kn.getRectangleByPoints(c.points),id:c.id,type:c.type})),...d]}function La(e){return typeof e=="object"&&e!==null&&Array.isArray(e.points)&&e.points.length===2}function Ss(e,n,t){return e.x<n.x+n.width+t&&e.x+e.width+t>n.x&&e.y<n.y+n.height+t&&e.y+e.height+t>n.y}function Ba(e,n,t,s){const d=[e];for(let c=1;c<=s;c+=1)d.push([e[0]+n*c,e[1]],[e[0],e[1]+t*c],[e[0]+n*c,e[1]+t*c],[e[0]-n*c,e[1]],[e[0]-n*c,e[1]+t*c],[e[0],e[1]-t*c],[e[0]+n*c,e[1]-t*c],[e[0]-n*c,e[1]-t*c]);return d}function Fa(e,n,t,s,d){const c=Math.max(d,32),a=Math.max(Math.round(Math.min(n.width,n.height)*.16),28),h=Math.max(Math.round(Math.min(n.width,n.height)*.12),18),u=n.width+a,l=n.height+a,v=[];for(let k=0;k<t;k+=1){const S=Math.floor(k/vn),I=k%vn,f=Math.min(vn,t-S*vn),D=I-(f-1)/2,y=e.x+e.width/2-n.width/2,C=e.y+e.height/2-n.height/2,E=Math.abs(D)*h;let P=y,g=C;switch(s){case"right":P=e.x+e.width+c+S*u+E,g=C+D*(n.height+a);break;case"left":P=e.x-c-n.width-S*u-E,g=C+D*(n.height+a);break;case"top":P=y+D*(n.width+a),g=e.y-c-n.height-S*l-E;break;case"bottom":default:P=y+D*(n.width+a),g=e.y+e.height+c+S*l+E;break}v.push([Math.round(P),Math.round(g)])}return v}function us(e,n,t,s,d){return e.reduce((a,h)=>{const u={x:h[0],y:h[1],width:n.width,height:n.height};return a+t.filter(l=>Ss(u,l,s)).length},0)*1e3+bs.indexOf(d)*10}function Ha(e,n,t,s,d){var l;const{gap:c=40,padding:a=16}=d,h=vs(e,d),u=bs.map(v=>({side:v,positions:Fa(n,t,s,v,c)}));return u.sort((v,k)=>us(v.positions,t,h,a,v.side)-us(k.positions,t,h,a,k.side)),((l=u[0])==null?void 0:l.positions)??[]}function $a(e,n,t,s,d={}){const{frameRect:c,extraOccupiedRects:a=[],...h}=d,u={...h,extraOccupiedRects:a},l=c?Ha(e,c,t,s,u):Array.from({length:s},(k,S)=>Wa(n,t,S,s,u.gap)),v=[...a];return l.map(k=>{const S=Ua(e,k,t,{...u,extraOccupiedRects:v});return v.push({x:S[0],y:S[1],width:t.width,height:t.height}),S})}function Ua(e,n,t,s={}){const{gap:d=40,padding:c=16,maxSearchRadius:a=6}=s,h=vs(e,s),u=t.width+d,l=t.height+d,v=Ba(n,u,l,a);for(const k of v){const S={x:k[0],y:k[1],width:t.width,height:t.height};if(!h.some(f=>Ss(S,f,c)))return k}return[n[0],n[1]+l*(a+1)]}function ht(e){return typeof e=="string"&&e.trim()?e.trim():null}function Va(e){return e==="image"||e==="video"||e==="audio"||e==="text"||e==="agent"}function Ga(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.modelId=="string"&&n.modelId.trim().length>0&&(n.profileId===null||typeof n.profileId=="string")&&(n.providerIdHint===null||typeof n.providerIdHint=="string")&&(n.vendorHint===null||typeof n.vendorHint=="string")&&typeof n.updatedAt=="number"&&Number.isFinite(n.updatedAt)}function io(){try{const e=window.localStorage.getItem(Qn);if(!e)return{};const n=JSON.parse(e);if(!n||typeof n!="object")return{};const t={};return Object.entries(n).forEach(([s,d])=>{Va(s)&&Ga(d)&&(t[s]={modelId:d.modelId.trim(),profileId:ht(d.profileId),providerIdHint:ht(d.providerIdHint),vendorHint:ht(d.vendorHint),updatedAt:d.updatedAt})}),t}catch{return{}}}function ks(e){try{if(!Object.values(e).some(Boolean)){window.localStorage.removeItem(Qn);return}window.localStorage.setItem(Qn,JSON.stringify(e))}catch{}}function Ka(e){const n=io();return n[e]?n[e]||null:e==="agent"&&n.text||null}function ps(e,n){var d;const t=ht(n.modelId);if(!t){Ms(e);return}const s=io();s[e]={modelId:t,profileId:ht((d=n.modelRef)==null?void 0:d.profileId),providerIdHint:ht(n.providerIdHint),vendorHint:ht(n.vendorHint),updatedAt:Date.now()},ks(s)}function Ms(e){const n=io();n[e]&&(delete n[e],ks(n))}function Qe(e,n,t,s){var c;const d=e.metadata||{};return{id:e.id,name:e.name,generationType:e.generationType,prompt:d.prompt||((c=n==null?void 0:n.aiContext)==null?void 0:c.finalPrompt)||"",aiAnalysis:e.aiAnalysis,count:d.count,createdAt:e.createdAt,status:e.status,steps:e.steps.map(a=>({id:a.id,description:a.description,status:a.status,mcp:a.mcp,args:a.args,result:a.result,error:a.error,duration:a.duration,options:a.options})),retryContext:n,postProcessingStatus:t,insertedCount:s}}function Ya(e,n){return e==="generate_image"?"image":e==="generate_video"||e==="generate_long_video"?"video":e==="generate_audio"?"audio":e==="generate_text"?"text":n.scenarioType==="skill_flow"||n.generationType==="agent"?"agent":n.generationType==="image"||n.generationType==="video"||n.generationType==="audio"||n.generationType==="text"?n.generationType:"agent"}function Xa(e,n){const t=typeof n.args.prompt=="string"?n.args.prompt.trim():e.metadata.prompt.trim(),s=(e.metadata.rawInput||e.metadata.userInstruction||e.metadata.prompt||t).trim().slice(0,2e3),d=e.scenarioType==="skill_flow"?e.name.trim():void 0,c=Ya(n.mcp,e);return{initialPrompt:s,sentPrompt:t.slice(0,2e3),category:c,skillId:e.skillId,skillName:d,tags:[c,d].filter(Boolean)}}function Sn(e,n){return n.args.promptMeta||!["generate_image","generate_video","generate_long_video","generate_audio","generate_text"].includes(n.mcp)?n:{...n,args:{...n.args,promptMeta:Xa(e,n)}}}let ms=!1;ms||(ra(),ya(),eo.initialize().catch(e=>{console.warn("[AIInputBar] 外部 Skill 服务初始化失败(非致命):",e)}),ms=!0);function Cs(e){return e.selectionKey||(e.sourceProfileId?`${e.sourceProfileId}::${e.id}`:e.id)}function ze(e,n){return n!=null&&n.profileId?`${n.profileId}::${e}`:e}function Oe(e){return e?mt(e.sourceProfileId||null,e.id):null}function Xn(e){return e<=0?"0":e<=20?"1-20":e<=100?"21-100":e<=300?"101-300":e<=800?"301-800":"800+"}const Za=1,Ts=4,qa=6,Ja=1.5;function hs(e,n){const t=window.getComputedStyle(e),s=Number.parseFloat(t.fontSize)||15,d=Number.parseFloat(t.lineHeight)||s*Ja,c=Number.parseFloat(t.paddingTop)+Number.parseFloat(t.paddingBottom),a=Number.parseFloat(t.borderTopWidth)+Number.parseFloat(t.borderBottomWidth);return Math.ceil(d*n+c+a)}function Qa(e,n){if(!e)return;if(!n){e.style.height="",e.style.overflowY="";return}const t=hs(e,Ts),s=hs(e,qa);e.style.height="auto";const d=e.scrollHeight,c=Math.min(Math.max(d,t),s);e.style.height=`${c}px`,e.style.overflowY=d>s?"auto":"hidden"}function xe(e,n,t){if(!n)return;const s=ze(n,t),d=(t==null?void 0:t.profileId)||null;return e.find(c=>Cs(c)===s)||e.find(c=>c.id===n&&(c.sourceProfileId||null)===d)||(d===null?e.find(c=>c.id===n&&!c.sourceProfileId):void 0)||e.find(c=>c.id===n)}function ei(e,n){return e==="agent"&&n==="text"?"agent":n}function ti(e){if(!e)return!1;const n=e.toLowerCase();return n.includes("#video")?!0:[".mp4",".webm",".mov",".avi",".mkv",".m4v",".flv",".wmv"].some(s=>n.includes(s))}const Ps=ys.memo(({language:e,onSelectionChange:n,externalBoardRef:t,onCanvasEmptyChange:s,isDataReady:d,onFrameSelected:c})=>{const a=$r(),h=r.useRef(a);h.current=a,r.useEffect(()=>(Zo(a),Jo(a),Qo(a),es(a),rs.setBoard(a),t&&(t.current=a),()=>{Zo(null),Jo(null),Qo(null),es(null),rs.setBoard(null),t&&(t.current=null)}),[a,t]);const u=r.useRef(s);u.current=s,r.useEffect(()=>{if(!a||!u.current||!d)return;const S=setInterval(()=>{var f;const I=a.children||[];(f=u.current)==null||f.call(u,I.length===0)},500);return()=>{clearInterval(S)}},[a,d]);const l=r.useRef(n);l.current=n;const v=r.useRef(c);return v.current=c,r.useEffect(()=>{const k=async()=>{var D,y,C,E;const I=h.current;if(!I)return;const f=xs(I);if(f.length===1&&_s(f[0])){const P=f[0],g=kn.getRectangleByPoints(P.points);(D=v.current)==null||D.call(v,{id:P.id,width:g.width,height:g.height})}else(y=v.current)==null||y.call(v,null);if(f.length===0){l.current([]);return}try{const P=await Ur(I),g=[];P.graphicsImage&&g.push({url:P.graphicsImage,name:e==="zh"?"图形元素":"Graphics",type:"graphics",width:(C=P.graphicsImageDimensions)==null?void 0:C.width,height:(E=P.graphicsImageDimensions)==null?void 0:E.height});for(const N of P.remainingImages){const U=N.url||"",ee=ti(U);g.push({url:U,name:N.name||(ee?`video-${Date.now()}`:`image-${Date.now()}`),type:ee?"video":"image",width:N.width,height:N.height})}P.remainingText&&P.remainingText.trim()&&g.push({type:"text",text:P.remainingText.trim(),name:e==="zh"?"文字内容":"Text Content"}),l.current(g)}catch(P){console.error("Failed to process selected content:",P),l.current([])}};k();const S=()=>{setTimeout(k,50)};return document.addEventListener("mouseup",S),()=>{document.removeEventListener("mouseup",S)}},[e]),null});Ps.displayName="SelectionWatcher";const Es=ys.memo(({className:e,isDataReady:n,onEnableToolWindows:t})=>{const{language:s}=ro(),d=xn("image"),c=xn("video"),a=xn("audio"),h=xn("text"),u=Pr(),l=Vr(),{addHistory:v}=fs(),{addAsset:k}=Er(),S=r.useRef(u.sendWorkflowMessage);S.current=u.sendWorkflowMessage;const I=r.useRef(u.updateWorkflowMessage);I.current=u.updateWorkflowMessage;const f=r.useRef(u.appendAgentLog);f.current=u.appendAgentLog;const D=r.useRef(u.updateThinkingContent);D.current=u.updateThinkingContent;const y=r.useRef(u.setSelectedContent);y.current=u.setSelectedContent;const C=r.useRef(u.registerRetryHandler);C.current=u.registerRetryHandler;const E=r.useRef(null),P=r.useRef([]),g=r.useRef(null),N=ua(),U=r.useCallback((o,i,m)=>{if(!o)return;const w=P.current,b=(m!=null&&m.workflowId&&(m!=null&&m.batchId)&&typeof m.batchIndex=="number"?lt.getAnchorByBatchSlot(o,{workflowId:m.workflowId,batchId:m.batchId,batchIndex:m.batchIndex}):null)||(m!=null&&m.workflowId?lt.getAnchorByWorkflowId(o,m.workflowId):null)||(w[0]?lt.getAnchorById(o,w[0]):null);if(!b)return;const T=b.taskIds.includes(i)?b.taskIds:[...b.taskIds,i];lt.updateAnchor(o,b.id,{taskIds:T,primaryTaskId:b.primaryTaskId||i})},[]),ee=r.useCallback((o,i,m)=>{const w=P.current;w.length===0||!o||w.forEach(b=>{lt.updateAnchor(o,b,$n(i,m))})},[]),ne=r.useCallback(o=>{const i=P.current;i.length===0||!o||(i.forEach(m=>{lt.removeAnchor(o,m)}),P.current=[])},[]),ae=r.useCallback((o,i)=>{const m=Ka(o);if(!m)return;const w=xe(i,m.modelId,mt(m.profileId,m.modelId));if(w)return w;Ms(o)},[]),H=r.useCallback((o,i)=>{const m=ae(o,i);if(m)return m;const b=kt(o==="video"?"video":o==="audio"?"audio":o==="text"||o==="agent"?"text":"image"),T=xe(i,b.modelId,mt(b.profileId,b.modelId));if(T)return T;const B=o==="video"?Pt():o==="audio"?Et():o==="text"||o==="agent"?qn():pt();return xe(i,B,null)||i[0]},[ae]),_=N.generationType,$=H(_,_==="video"?c:_==="audio"?a:_==="text"||_==="agent"?h:d)||Ve(N.selectedModel)||Ve(_==="video"?Pt():_==="audio"?Et():_==="text"||_==="agent"?qn():pt()),Q=H("image",d)||Ve(pt()),V=H("video",c)||Ve(Pt()),ie=H("audio",a)||Ve(Et()),Se=kt("image"),Me=(Q==null?void 0:Q.id)||Se.modelId||pt(),Dt=Oe(Q)||mt(Se.profileId,Se.modelId),nn=ze(($==null?void 0:$.id)||Me,Oe($)||Dt),co=_==="agent"?{}:Kn(_,($==null?void 0:$.id)||Me,nn,N.selectedParams),[fe,tt]=r.useState(""),[As,Ds]=r.useState(!1),[Pn,En]=r.useState([]),[Rt,ft]=r.useState([]),[Le,nt]=r.useState(!1),we=r.useRef(null),[Nt,ot]=r.useState(!1),[Rs,Ns]=r.useState(null),[x,Be]=r.useState(_),[Ie,An]=r.useState(N.selectedSkillId||et),[O,lo]=r.useState(($==null?void 0:$.id)||Me),[L,uo]=r.useState(Oe($)||Dt),[Fe,po]=r.useState((Q==null?void 0:Q.id)||pt()),[Ge,mo]=r.useState(Oe(Q)),[He,ho]=r.useState((V==null?void 0:V.id)||Pt()),[Ke,fo]=r.useState(Oe(V)),[$e,go]=r.useState((ie==null?void 0:ie.id)||Et()),[Ye,wo]=r.useState(Oe(ie)),[Dn,Xe]=r.useState([]),on=r.useMemo(()=>{if(x!=="image"||xe(d,O,L))return d;const i=dt("image",O,L);return i?[i,...d]:d},[x,d,O,L]),sn=r.useMemo(()=>{if(x!=="video"||xe(c,O,L))return c;const i=dt("video",O,L);return i?[i,...c]:c},[x,O,L,c]),rn=r.useMemo(()=>{if(x!=="audio"||xe(a,O,L))return a;const i=dt("audio",O,L);return i?[i,...a]:a},[a,x,O,L]),an=r.useMemo(()=>{if(x!=="text"&&x!=="agent"||xe(h,O,L))return h;const i=dt("text",O,L);return i?[i,...h]:h},[x,O,L,h]),jt=r.useMemo(()=>{if(xe(d,Fe,Ge))return d;const i=dt("image",Fe,Ge);return i?[i,...d]:d},[d,Fe,Ge]),zt=r.useMemo(()=>{if(xe(c,He,Ke))return c;const i=dt("video",He,Ke);return i?[i,...c]:c},[He,Ke,c]),Ot=r.useMemo(()=>{if(xe(a,$e,Ye))return a;const i=dt("audio",$e,Ye);return i?[i,...a]:a},[a,$e,Ye]),[Ce,cn]=r.useState(()=>{if(_==="agent")return{};const o=($==null?void 0:$.id)||Me,i=Lo(o).find(m=>m.id==="size");return{...co,...o.startsWith("mj")||!i?{}:{size:co.size||Bo(o)}}}),Wt=r.useRef(Ce),Io=r.useRef(_==="agent"?"agent":`${_}:${nn}`);r.useEffect(()=>{Wt.current=Ce},[Ce]);const[Lt,yo]=r.useState(N.selectedCount),[xo,Rn]=r.useState(!1),[_o,Nn]=r.useState(!1),[bo,jn]=r.useState(!1),st=r.useRef(null),js=r.useCallback(o=>{Rn(o),o||(st.current=null)},[]),zs=r.useCallback(o=>{Nn(o),o||(st.current=null)},[]),Os=r.useCallback(o=>{jn(o),o||(st.current=null)},[]),[vo,Bt]=r.useState(!1),ce=r.useMemo(()=>[...Rt,...Pn],[Rt,Pn]),rt=r.useMemo(()=>({invalidFile:s==="zh"?"请上传图片文件":"Please upload image files",fileTooLarge:s==="zh"?"图片大小不能超过 25MB":"Image size cannot exceed 25MB",loadFailed:s==="zh"?"加载图片失败":"Failed to load image",compressionFailed:s==="zh"?"图片压缩失败":"Image compression failed",compressing:o=>s==="zh"?`正在压缩图片 (${o.toFixed(1)}MB)...`:`Compressing image (${o.toFixed(1)}MB)...`,compressed:(o,i)=>s==="zh"?`压缩完成: ${o.toFixed(1)}MB → ${i.toFixed(1)}MB`:`Compressed: ${o.toFixed(1)}MB → ${i.toFixed(1)}MB`}),[s]);r.useEffect(()=>{const o=x==="video"?sn:x==="audio"?rn:x==="text"||x==="agent"?an:on,m=xe(o,O,L)||H(x,o);if(m){const w=ze(O,L),b=Cs(m);w!==b&&(lo(m.id),uo(Oe(m)))}x!=="agent"&&An(et),(x==="agent"||x==="text"||x==="audio")&&yo(1)},[rn,x,on,H,O,L,an,sn]),r.useEffect(()=>{const o=(i,m,w,b,T,B)=>{if(xe(m,w,b))return;const z=H(i,m);z&&(T(z.id),B(Oe(z)))};o("image",jt,Fe,Ge,po,mo),o("video",zt,He,Ke,ho,fo),o("audio",Ot,$e,Ye,go,wo)},[H,$e,Ye,Fe,Ge,He,Ke,Ot,jt,zt]);const ln=r.useMemo(()=>x==="video"?sn:x==="audio"?rn:x==="text"||x==="agent"?an:on,[rn,x,on,an,sn]);r.useEffect(()=>{let o=!1;return(async()=>{var B;if(x!=="agent"||Ie===et){Xe([]);return}const m=Vn(Ie);if(m){Xe(Ct(m));return}const w=Ho(Ie);if(w){Xe(Ct(w));return}const b=await eo.getSkillById(Ie);if(o)return;if(b){Xe(Ct(b));return}const T=await Mn.getNoteById(Ie);o||Xe(T?Ct({id:T.id,name:T.title,content:T.content,outputType:(B=T.metadata)==null?void 0:B.outputType}):[])})().catch(()=>{o||Xe([])}),()=>{o=!0}},[x,Ie]);const Ft=r.useMemo(()=>{var m;if(x==="agent")return[];if(x==="video")return Ar(O,L||O,Ce);const o=Lo(O);return x!=="audio"?o:(Ce.sunoAction||((m=o.find(w=>w.id==="sunoAction"))==null?void 0:m.defaultValue)||"music")==="lyrics"?o.filter(w=>w.id==="sunoAction"||w.id==="mv"||w.id==="title"||w.id==="tags"):o},[x,O,L,Ce]);r.useEffect(()=>{if(!Nt)return;const o=i=>{const m=i.target;un.current&&!un.current.contains(m)&&ot(!1)};return document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[Nt]),r.useEffect(()=>()=>{we.current&&clearTimeout(we.current)},[]),r.useEffect(()=>{const o=i=>{var m;((m=i.detail)==null?void 0:m.type)!=="image"&&(we.current&&(clearTimeout(we.current),we.current=null),nt(!1))};return window.addEventListener("ai-generation-complete",o),()=>{window.removeEventListener("ai-generation-complete",o)}},[]),r.useEffect(()=>{const o=gs.observeTaskUpdates().subscribe(i=>{var z,Y;const m=i.task,w=l.getWorkflow();if(!w)return;const b=w.steps.find(F=>{const q=F.result;return(q==null?void 0:q.taskId)===m.id});if(!b)return;let T=b.status,B=b.result,Z=b.error;switch(m.status){case Tt.PENDING:case Tt.PROCESSING:T="running";break;case Tt.COMPLETED:T="completed",B={...typeof B=="object"?B:{},taskId:m.id,result:m.result};break;case Tt.FAILED:T="failed",Z=((z=m.error)==null?void 0:z.message)||"任务执行失败";break;case Tt.CANCELLED:T="skipped";break}if(T!==b.status){if(l.updateStep(b.id,T,B,Z),T==="failed"){const q=(Y=b.options)==null?void 0:Y.batchId;q&&w.steps.forEach(oe=>{var ye;oe.id!==b.id&&((ye=oe.options)==null?void 0:ye.batchId)===q&&oe.status==="running"&&l.updateStep(oe.id,"skipped",void 0,"前置任务失败")})}const F=l.getWorkflow();if(F){const q=Qe(F,E.current||void 0);I.current(q);const oe=g.current,ye=De.current;oe&&ye&&je.updateWorkflow(ye,oe,q)}}});return()=>o.unsubscribe()},[l]);const So=r.useRef(void 0),dn=r.useRef(void 0);r.useEffect(()=>{const o=Un.observeCompletionEvents().subscribe(i=>{const m=l.getWorkflow(),w=m==null?void 0:m.steps.find(B=>{const Z=B.result;return(Z==null?void 0:Z.taskId)===i.taskId});let b,T;switch(i.type){case"postProcessingStarted":b="processing";break;case"postProcessingCompleted":b="completed",T=i.result.insertedCount;break;case"postProcessingFailed":b="failed";break}if(So.current=b,T!==void 0&&(dn.current=(dn.current||0)+T),m&&w){const B=l.getWorkflow();if(B){const Z=Qe(B,E.current||void 0,b,dn.current);I.current(Z);const z=g.current,Y=De.current;z&&Y&&je.updateWorkflow(Y,z,Z)}}if(i.type==="postProcessingCompleted"){const B=i.result.firstElementPosition;we.current&&(clearTimeout(we.current),we.current=null),nt(!1),setTimeout(async()=>{var Y;u.closeChatDrawer();const Z=g.current,z=De.current;if(Z&&z){const F=l.getWorkflow();if(F==null?void 0:F.steps.every(oe=>oe.status==="completed"||oe.status==="failed"||oe.status==="skipped")){const{workflowCompletionService:oe}=await qo(async()=>{const{workflowCompletionService:te}=await import("./startup-app-DC9IB1KI.js").then(ke=>ke.m9);return{workflowCompletionService:te}},__vite__mapDeps([0]),import.meta.url);(F==null?void 0:F.steps.every(te=>{const ke=te.result;return ke!=null&&ke.taskId?oe.isPostProcessingCompleted(ke.taskId):!0}))&&(je.removeWorkZone(z,Z),g.current=null)}}if(B&&z){const F=(Y=z.host)==null?void 0:Y.getBoundingClientRect();if(F){const q=z.viewport.zoom,oe=B[0]-F.width/(2*q),ye=B[1]-F.height/(2*q);Dr.updateViewport(z,[oe,ye],q)}}},500),So.current=void 0,dn.current=void 0}});return()=>o.unsubscribe()},[l,u]);const De=r.useRef(null),{submitWorkflow:ko}=Gr({boardRef:De,workZoneIdRef:g}),Te=r.useRef(null),un=r.useRef(null),Mo=r.useRef(null);oa(Te,{enableCopy:!0,stopPropagation:!0}),r.useEffect(()=>{const o=i=>{const m=i.detail;if(m!=null&&m.generationType&&Be(m.generationType),m!=null&&m.skillId){An(m.skillId);const w=Vn(m.skillId);w&&Xe(Ct(w))}ot(!0),requestAnimationFrame(()=>{var w;(w=Te.current)==null||w.focus()})};return window.addEventListener(Yo,o),()=>{window.removeEventListener(Yo,o)}},[]);const Ws=r.useCallback(o=>{var i;tt(o.prompt),Be("agent"),(i=Te.current)==null||i.focus(),Ae.track("inspiration_selected",{promptLength:o.prompt.length,modelType:o.modelType})},[]),Ls=r.useCallback(o=>{var i;tt(o.content),o.modelType&&(o.modelType==="image"?Be("image"):o.modelType==="video"?Be("video"):o.modelType==="audio"?Be("audio"):o.modelType==="text"?Be("text"):o.modelType==="agent"&&Be("agent")),(i=Te.current)==null||i.focus()},[]),Bs=r.useCallback(()=>{const o=Zn.find(i=>i.id==="knowledge-base");o&&(window.__kbPendingNavigation={directoryName:"Skill",autoCreateNote:!0},tn.openTool(o),setTimeout(()=>{window.dispatchEvent(new CustomEvent("kb:navigate",{detail:{directoryName:"Skill",autoCreateNote:!0}}))},300))},[]),Co=r.useCallback((o="ai_input_bar")=>{const i=Zn.find(m=>m.id==="banana-prompt");if(!i){console.warn("[AIInputBar] Banana prompt tool not found"),Ae.trackPromptAction({action:"open_tool",surface:o,promptType:x,prompt:fe,source:o,status:"failed",metadata:{tool_id:"banana-prompt",reason:"tool_not_found"}});return}Ae.trackPromptAction({action:"open_tool",surface:o,promptType:x,prompt:fe,source:o,status:"success",metadata:{tool_id:i.id,tool_type:"external_prompt_library"}}),tn.openTool(i)},[x,fe]),Fs=r.useCallback(()=>{Co("inspiration_board")},[Co]),Hs=r.useCallback(async o=>{try{const i=new Image;i.onload=()=>{const m={type:"image",url:o.url,name:o.name||`素材-${Date.now()}`,width:i.naturalWidth||void 0,height:i.naturalHeight||void 0};ft(w=>[...w,m]),Bt(!1)},i.onerror=()=>{const m={type:"image",url:o.url,name:o.name||`素材-${Date.now()}`};ft(w=>[...w,m]),Bt(!1)},i.src=o.url}catch(i){console.error("Failed to select asset from library:",i),Bt(!1)}},[]),$s=r.useCallback(()=>{var o;(o=Mo.current)==null||o.click()},[]),To=r.useCallback(o=>new Promise((i,m)=>{const w=new FileReader;w.onload=()=>{const b=w.result,T=new Image;T.onload=()=>{i({url:b,width:T.naturalWidth,height:T.naturalHeight})},T.onerror=()=>{i({url:b,width:0,height:0})},T.src=b},w.onerror=m,w.readAsDataURL(o)}),[]),pn=r.useCallback(async o=>{const i=Array.from(o);if(i.length===0)return;const m=[];for(const[w,b]of i.entries()){if(!b.type.startsWith("image/")){Je.error(rt.invalidFile);continue}if(b.size>25*1024*1024){Je.error(rt.fileTooLarge);continue}try{let T=b;if(b.size>10*1024*1024){const{compressImageBlob:F,getCompressionStrategy:q}=await qo(async()=>{const{compressImageBlob:te,getCompressionStrategy:ke}=await import("./startup-app-DC9IB1KI.js").then(Ue=>Ue.lU);return{compressImageBlob:te,getCompressionStrategy:ke}},__vite__mapDeps([0]),import.meta.url),oe=q(b.size/(1024*1024)),ye=Je.loading({content:rt.compressing(b.size/(1024*1024)),duration:0,placement:"top"});try{T=await F(b,oe.targetSizeMB),Je.close(ye),Je.success({content:rt.compressed(b.size/(1024*1024),T.size/(1024*1024)),duration:2})}catch(te){Je.close(ye),console.error("[AIInputBar] Failed to compress image:",te),Je.error(rt.compressionFailed);continue}}const B=T instanceof File?T:new File([T],b.name||`pasted-image-${Date.now()}.png`,{type:T.type||b.type||"image/png"});k(B,Fo.IMAGE,Rr.LOCAL,B.name).catch(F=>{console.warn("[AIInputBar] Failed to add asset to library:",F)});const{url:Z,width:z,height:Y}=await To(B);m.push({type:"image",url:Z,name:B.name||`上传图片 ${w+1}`,width:z||void 0,height:Y||void 0})}catch(T){console.error("[AIInputBar] Failed to import local image:",T),Je.error(rt.loadFailed)}}m.length>0&&ft(w=>[...w,...m])},[k,To,rt]),Us=r.useCallback(async o=>{const i=o.target.files;!i||i.length===0||(await pn(i),o.target.value="")},[pn]),Vs=r.useCallback(o=>{En(o)},[]),Po=r.useRef(null),Gs=r.useCallback(o=>{if(Po.current=o,!o)return;const i=Nr(o.width,o.height,O);i&&cn(m=>({...m,size:i}))},[O]),Ks=r.useCallback(o=>{o<Rt.length&&ft(i=>i.filter((m,w)=>w!==o))},[Rt.length]);r.useEffect(()=>{y.current(ce.map(o=>({type:o.type,url:o.url,text:o.text,name:o.name})))},[ce]),r.useEffect(()=>{const o=i=>{var z,Y;const m=(z=i.clipboardData)==null?void 0:z.items;if(!m||m.length===0||!Array.from(m).some(F=>F.type.startsWith("image/")))return;const b=document.activeElement,T=un.current;if(!(!!T&&(T.contains(b)||Nt&&(b===document.body||(b==null?void 0:b.tagName)==="BODY"))))return;const Z=[];for(const F of Array.from(m)){if(!F.type.startsWith("image/"))continue;const q=F.getAsFile();q&&Z.push(q)}Z.length!==0&&(i.preventDefault(),pn(Z),(Y=Te.current)==null||Y.focus())};return document.addEventListener("paste",o),()=>{document.removeEventListener("paste",o)}},[pn,Nt]);const gt=r.useCallback(()=>{if(st.current!==null){const o=st.current;tt(i=>i.substring(0,o)+i.substring(o+1)),st.current=null}},[]),mn=r.useCallback(o=>{const i=ei(x,o.type);Ae.track("ai_input_change_model",{model:o.id,type:o.type,profileId:o.sourceProfileId||null}),gt(),Be(i),lo(o.id);const m=Oe(o);uo(m),ps(i,{modelId:o.id,modelRef:m,providerIdHint:o.sourceProfileId||(m==null?void 0:m.profileId),vendorHint:o.vendor}),cn(i==="agent"?{}:Kn(i,o.id,ze(o.id,m))),Rn(!1),setTimeout(()=>{var w;return(w=Te.current)==null?void 0:w.focus()},0)},[gt,x]),Ys=r.useCallback(o=>{const i=xe(ln,o,L)||xe(ln,o,null)||Ve(o);i&&mn(i)},[mn,ln,L]),Xs=r.useCallback(o=>{mn(o)},[mn]),hn=r.useCallback((o,i)=>{const m=Oe(i);o==="image"?(po(i.id),mo(m)):o==="video"?(ho(i.id),fo(m)):(go(i.id),wo(m)),ps(o,{modelId:i.id,modelRef:m,providerIdHint:i.sourceProfileId||(m==null?void 0:m.profileId),vendorHint:i.vendor}),Ae.track("ai_input_change_agent_media_model",{model:i.id,type:o,profileId:i.sourceProfileId||null})},[]),zn=r.useCallback((o,i,m)=>{const w=o==="image"?jt:o==="video"?zt:Ot,b=xe(w,i,m||null)||xe(w,i,null)||Ve(i);b&&hn(o,b)},[hn,Ot,jt,zt]),On=r.useCallback((o,i)=>{hn(o,i)},[hn]),Zs=r.useCallback(o=>{Xe(Ct(o))},[]),Eo=r.useMemo(()=>({image:Fe,video:He,audio:$e}),[$e,Fe,He]),Ao=r.useMemo(()=>({image:Ge,video:Ke,audio:Ye}),[Ye,Ge,Ke]);r.useEffect(()=>{const o=(z,Y)=>{const F=Object.keys(z),q=Object.keys(Y);return F.length!==q.length?!1:F.every(oe=>z[oe]===Y[oe])},i=x==="agent"?"agent":`${x}:${ze(O,L)}`,m=x==="agent"?{}:Io.current===i?Wt.current||{}:Kn(x,O,ze(O,L),Wt.current),w={},b=Ft.find(z=>z.id==="size"),T=m.size,B=!T||!(b!=null&&b.options)||b.options.some(z=>z.value===T);!O.startsWith("mj")&&b&&(w.size=T&&B?T:b.defaultValue||Bo(O)),Ft.forEach(z=>{if(z.id==="size")return;const Y=m[z.id],F=!Y||z.valueType!=="enum"||!z.options||z.options.some(q=>q.value===Y);Y&&F?w[z.id]=Y:z.defaultValue&&(w[z.id]=z.defaultValue)});const Z=jr(O,w);o(Wt.current||{},Z)||(cn(Z),Wt.current=Z),Io.current=i},[x,O,L,Ft]),r.useEffect(()=>{pa({generationType:x,selectedModel:O,selectedParams:Ce,selectedCount:Lt,selectedSkillId:Ie}),x!=="agent"&&ma(x,O,Ce,ze(O,L))},[x,O,L,Ce,Lt,Ie]);const qs=r.useCallback((o,i,m)=>{gt(),cn(w=>{const b={...w};return i===void 0||i===""?delete b[o]:b[o]=i,b}),m!=null&&m.keepOpen||(Nn(!1),setTimeout(()=>{var w;return(w=Te.current)==null?void 0:w.focus()},0))},[gt]),Js=r.useCallback(o=>{gt(),yo(o),jn(!1),setTimeout(()=>{var i;return(i=Te.current)==null?void 0:i.focus()},0)},[gt]),Wn=r.useCallback(async o=>{var B,Z,z,Y,F,q,oe,ye;const i=fe.trim();if(!i&&ce.length===0||Le)return;const m=Date.now(),w=i.length,b={trigger:o,source:"ai_input_bar",generationType:x,generation_type:x,model:O,profileId:(L==null?void 0:L.profileId)||null,profile_id:(L==null?void 0:L.profileId)||null,hasAttachedContent:ce.length>0,has_attached_content:ce.length>0,attachedCount:ce.length,attached_count:ce.length,promptLength:w,prompt_length:w,promptLengthBucket:Xn(w),prompt_length_bucket:Xn(w)},T=(te,ke={})=>{const Ue=Date.now()-m;Ae.track("ai_input_submit",{...b,status:te,durationMs:Ue,duration_ms:Ue,...ke})};T("start"),nt(!0);try{if(!zr(x==="video"?"video":x==="audio"?"audio":x==="text"||x==="agent"?"text":"image",L||O)&&!await Or()){T("cancelled",{reason:"missing_api_key",submitMode:"preflight",submit_mode:"preflight"}),nt(!1);return}const Ue=ce.filter(M=>M.type==="image"&&M.url),Ht=ce.filter(M=>M.type==="graphics"&&M.url),A=[...Ue,...Ht].map(M=>{if(M.width&&M.height)return{width:M.width,height:M.height}}).filter(M=>M!==void 0),J={texts:ce.filter(M=>M.type==="text"&&M.text).map(M=>M.text),images:Ue.map(M=>M.url),videos:ce.filter(M=>M.type==="video"&&M.url).map(M=>M.url),graphics:Ht.map(M=>M.url),imageDimensions:A},W=Pa(fe,J,{modelId:O,modelRef:L,params:Ce,generationType:x,count:Lt,defaultModels:x==="agent"?Eo:void 0,defaultModelRefs:x==="agent"?Ao:void 0}),se=[...J.images,...J.graphics];let j;if(x==="agent"&&Ie!==et){const M=Vn(Ie);if(M)try{j=await wn(W,M,se)}catch(X){console.warn("[AIInputBar] 系统 Skill 工作流转换失败,降级到通用工作流:",X),j=Mt(W,se)}else{const X=Ho(Ie);if(X)try{j=await wn(W,{id:X.id,name:X.name,type:"external",content:X.content,outputType:X.outputType},se)}catch(K){console.warn("[AIInputBar] 外部 Skill 工作流转换失败,降级到角色扮演:",K),j=await wn(W,{id:X.id,name:X.name,type:"external",content:X.content,outputType:X.outputType},se).catch(()=>Mt(W,se))}else try{const K=await Mn.getNoteById(Ie);if(K){const le=((B=K.metadata)==null?void 0:B.outputType)||void 0;j=await wn(W,{id:K.id,name:K.title,type:"user",content:K.content,outputType:le},se)}else j=Mt(W,se)}catch{j=Mt(W,se)}}j||(console.warn("[AIInputBar] Skill 工作流未能生成,降级到通用工作流"),j=Mt(W,se))}else j=Mt(W,se);const G=De.current;if(G){const le=(Z=G.host)==null?void 0:Z.getBoundingClientRect(),me=((z=G.viewport)==null?void 0:z.zoom)||1,he=((F=(Y=G.viewport)==null?void 0:Y.origination)==null?void 0:F[0])||0,Re=((oe=(q=G.viewport)==null?void 0:q.origination)==null?void 0:oe[1])||0,Gt=G.children.filter(ge=>ge.type!=="workzone"),fn=he+((le==null?void 0:le.width)||0)/2/me,_t=Re+((le==null?void 0:le.height)||0)/2/me;let be=fn-200,re=_t,bt=be,qe=_t-240/2;if(Gt.length>0){const ge=xs(G);let de=!1;if(ge.length>0)try{const ue=Gn(G,ge,!1);ge.every(ve=>$o.isDrawElement(ve)&&$o.isImage(ve)||Wr(ve))&&ue.width>ue.height?(be=ue.x+ue.width+50,re=ue.y):(be=ue.x,re=ue.y+ue.height+50),bt=be,qe=re,de=!0}catch(ue){console.warn("[AIInputBar] Failed to calculate position for selected elements:",ue)}if(!de){let ue=null,Yt=-1/0;for(const ve of Gt)try{const St=Gn(G,[ve],!1),Xt=St.y+St.height;Xt>Yt&&(Yt=Xt,ue=ve)}catch(St){console.warn("[AIInputBar] Failed to get rectangle for element:",St)}if(ue){const ve=Gn(G,[ue],!1);be=ve.x,re=ve.y+ve.height+50,bt=be,qe=re}}}const it=Qe(j),vt=Po.current;let Kt,ct,No;if(vt){const ge=G.children.find(de=>de.id===vt.id);if(ge&&_s(ge)){Kt=vt.id,ct={width:vt.width,height:vt.height};const de=kn.getRectangleByPoints(ge.points);No=de,be=de.x,re=de.y}}if(W.generationType==="image"){const ge=Math.max(W.count??1,1),de=ge>1,ue=de?void 0:Kt,Yt=de?void 0:ct,ve=[],St=`wf_batch_${j.id}`,Xt=ue?null:$a(G,[be,re],Uo({workflowId:j.id,expectedInsertPosition:[be,re],requestedSize:W.size,requestedCount:1,zoom:me,title:it.name||"图片生成",...$n("submitted")}).size??{width:320,height:180},ge,{frameRect:de?No:void 0});for(let Ne=0;Ne<ge;Ne+=1){let Zt=Uo({workflowId:j.id,expectedInsertPosition:[be,re],targetFrameId:ue,targetFrameDimensions:Yt,frameAffinityId:de?Kt:void 0,frameAffinityDimensions:de?ct:void 0,requestedSize:W.size,requestedCount:de?1:ge,batchId:de?St:void 0,batchIndex:de?Ne+1:void 0,batchTotal:de?ge:void 0,zoom:me,title:it.name||"图片生成",...$n("submitted")});if(!ue){const zo=Xt?Xt[Ne]??Zt.position:Zt.position;Zt={...Zt,position:zo,expectedInsertPosition:zo}}const ir=lt.insertAnchor(G,Zt);ve.push(ir)}P.current=ve.map(Ne=>Ne.id),g.current=null;const[jo]=ve;jo&&setTimeout(()=>{const Ne=kn.getRectangleByPoints(jo.points);Vo(G,[Ne.x+Ne.width/2,Ne.y+Ne.height/2],100)},100)}else{const ge=je.insertWorkZone(G,{workflow:it,position:[bt,qe],size:{width:360,height:240},expectedInsertPosition:[be,re],targetFrameId:Kt,targetFrameDimensions:ct,zoom:me});g.current=ge.id,P.current=[],setTimeout(()=>{const de=bt+180,ue=qe+240/2;Vo(G,[de,ue],100)},100)}}const wt=kt("image"),It=kt("video"),yt=kt("audio"),xt={rawInput:fe,userInstruction:W.userInstruction,model:{id:W.modelId,type:W.generationType,isExplicit:W.isModelExplicit},modelRef:W.modelRef,defaultModels:W.defaultModels||{audio:yt.modelId||Et(),image:wt.modelId||pt(),video:It.modelId||Pt()},defaultModelRefs:W.defaultModelRefs||{audio:mt(yt.profileId,yt.modelId),image:mt(wt.profileId,wt.modelId),video:mt(It.profileId,It.modelId)},params:{count:W.count,size:W.size,duration:W.duration},selection:J,finalPrompt:W.prompt},Bn=kt("text").modelId,$t={aiContext:xt,referenceImages:se,textModel:Bn};E.current=$t;try{const M=Date.now(),{usedSW:X}=await ko(W,se,$t,j);if(X){if(T("success",{submitMode:"service_worker",submit_mode:"service_worker",workflowId:j.id,workflow_id:j.id,stepCount:j.steps.length,step_count:j.steps.length}),x==="image"&&ee(G,"accepted"),fe.trim()){const K=fe.trim(),le=ce.length>0;v(K,le,x),x==="image"?Go(K):x==="video"&&Ko(K)}tt(""),En([]),ft([]),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{nt(!1),we.current=null},1e3);return}}catch(M){console.warn("[AIInputBar] SW execution failed, falling back to main thread:",M)}if(x==="image"&&ee(G,"handoff"),fe.trim()){const M=fe.trim(),X=ce.length>0;v(M,X,x),x==="image"?Go(M):x==="video"&&Ko(M)}tt(""),En([]),ft([]),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{nt(!1),we.current=null},1e3);const pe=[],Ze=[],Ut=(M,X)=>({onChunk:K=>{D.current(K)},onAddSteps:K=>{l.updateStep(M.id,"completed",{analysis:"completed"},void 0,Date.now()-X);const le=K.map((he,Re)=>Sn(j,{...he,status:he.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:Re+1,batchTotal:K.length,globalIndex:Re+1}}));l.addSteps(le),Ze.push(...le),K.forEach(he=>{f.current({type:"tool_call",timestamp:Date.now(),toolName:he.mcp,args:he.args})});const me=Qe(l.getWorkflow(),E.current||void 0);I.current(me),g.current&&G&&je.updateWorkflow(G,g.current,me)},onUpdateStep:(K,le,me,he)=>{l.updateStep(K,le,me,he),f.current({type:"tool_result",timestamp:Date.now(),toolName:K,success:le==="completed",data:me,error:he});const Re=Qe(l.getWorkflow(),E.current||void 0);I.current(Re),g.current&&G&&je.updateWorkflow(G,g.current,Re)}});let Pe=!1;const Vt=()=>{const M=Qe(l.getWorkflow(),E.current||void 0);I.current(M),g.current&&G&&je.updateWorkflow(G,g.current,M)},Fn=async M=>{var le,me,he,Re,Gt,fn;const X=Date.now(),K=Ze.length;l.updateStep(M.id,"running"),Vt();try{const _t={...M.options,...Ut(M,X)},be=Sn(j,M),re=await Xo.executeTool({name:be.mcp,arguments:be.args},_t),bt=(me=(le=l.getWorkflow())==null?void 0:le.steps.find(qe=>qe.id===M.id))==null?void 0:me.status;if(re.success){if(re.taskId)pe.push(re.taskId),l.updateStep(M.id,"running",{taskId:re.taskId}),U(G,re.taskId,{workflowId:j.id,batchId:(he=M.options)==null?void 0:he.batchId,batchIndex:(Re=M.options)==null?void 0:Re.batchIndex});else if(bt==="running"){const qe=re.type==="text"&&re.data&&typeof re.data=="object"&&"content"in re.data?{content:re.data.content}:re.data;l.updateStep(M.id,"completed",qe,void 0,Date.now()-X);const it=M.mcp==="generate_text"?(Gt=re.data)==null?void 0:Gt.content:M.mcp==="ai_analyze"?(fn=re.data)==null?void 0:fn.response:void 0;if((M.mcp==="generate_text"||M.mcp==="ai_analyze")&&it&&it.trim()&&Ze.length===K){const ct={id:`${M.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:it}]},description:M.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};l.addSteps([ct]),Ze.push(ct)}}}else return l.updateStep(M.id,"failed",void 0,re.error||"执行失败",Date.now()-X),!1;return!0}catch(_t){return l.updateStep(M.id,"failed",void 0,String(_t)),!1}finally{Vt()}};for(const M of j.steps){if(Pe){l.updateStep(M.id,"skipped"),Vt();continue}await Fn(M)||(Pe=!0)}if(!Pe&&Ze.length>0){const M=l.getWorkflow();for(const X of Ze){if(Pe){l.updateStep(X.id,"skipped"),Vt();continue}const K=(ye=l.getWorkflow())==null?void 0:ye.steps.find(me=>me.id===X.id);if(!K){console.warn(`[AIInputBar] Step ${X.id} not found in workflow!`);continue}if(K.status==="completed")continue;await Fn(K)||(Pe=!0)}}const _e=l.getWorkflow(),rr=_e==null?void 0:_e.steps.every(M=>M.status==="completed"||M.status==="failed"||M.status==="skipped"),ar=pe.length>0;if(rr&&!ar){const M=g.current,X=P.current,K=De.current;(M||X.length>0)&&K&&(_e!=null&&_e.steps.every(me=>{const he=me.result;return he!=null&&he.taskId?Un.isPostProcessingCompleted(he.taskId):!0}))&&setTimeout(()=>{M&&(je.removeWorkZone(K,M),g.current=null),X.length>0&&(ee(K,"completed"),ne(K))},1500)}T(Pe?"failed":"success",{submitMode:"main_thread",submit_mode:"main_thread",workflowId:j.id,workflow_id:j.id,stepCount:(_e==null?void 0:_e.steps.length)||j.steps.length,step_count:(_e==null?void 0:_e.steps.length)||j.steps.length,createdTaskCount:pe.length,created_task_count:pe.length,failureReason:Pe?"workflow_step_failed":void 0,failure_reason:Pe?"workflow_step_failed":void 0})}catch(te){console.error("Failed to create generation task:",te),T("failed",{submitMode:"setup",submit_mode:"setup",error:te instanceof Error?te.message:String(te)}),x==="image"&&ee(De.current,"failed",{error:te instanceof Error?te.message:"创建图片任务失败"}),l.abortWorkflow(),nt(!1)}},[fe,ce,Le,O,L,l,ko,v,Ce,Eo,Ao,x,Lt,U,ee,ne]),Ln=r.useCallback(async(o,i,m)=>{var Ht;const w=o.retryContext;if(!w){console.error("[AIInputBar] No retry context available for workflow");return}m&&(g.current=m);const b={id:o.id,name:o.name,description:`重试: ${o.name}`,scenarioType:o.steps.some(A=>A.mcp==="ai_analyze")?"agent_flow":"direct_generation",generationType:o.generationType,steps:o.steps.map((A,J)=>({id:A.id,mcp:A.mcp,args:A.args,description:A.description,status:J<i?A.status:"pending",result:J<i?A.result:void 0,error:J<i?A.error:void 0,duration:J<i?A.duration:void 0,options:A.options})),metadata:{prompt:o.prompt,userInstruction:w.aiContext.userInstruction,rawInput:w.aiContext.rawInput,modelId:w.aiContext.model.id,modelRef:w.aiContext.modelRef,defaultModels:w.aiContext.defaultModels,defaultModelRefs:w.aiContext.defaultModelRefs,isModelExplicit:w.aiContext.model.isExplicit,count:o.count,size:w.aiContext.params.size,duration:w.aiContext.params.duration,referenceImages:w.referenceImages,selection:w.aiContext.selection},createdAt:Date.now()};l.startWorkflow(b),f.current({type:"retry",timestamp:Date.now(),reason:`从步骤 ${i+1} 开始重试`,attempt:1});const T=De.current,B=()=>{const A=Qe(l.getWorkflow(),w);I.current(A),g.current&&T&&je.updateWorkflow(T,g.current,A)},Z=Qe(b,w);I.current(Z),g.current&&T&&je.updateWorkflow(T,g.current,Z);const z=(A,J)=>({onChunk:W=>{D.current(W)},onAddSteps:W=>{l.updateStep(A.id,"completed",{analysis:"completed"},void 0,Date.now()-J);const se=W.map((j,G)=>Sn(b,{...j,status:j.status==="completed"?"completed":"pending",options:{mode:"queue",batchId:`agent_${Date.now()}`,batchIndex:G+1,batchTotal:W.length,globalIndex:G+1}}));l.addSteps(se),Y.push(...se),W.forEach(j=>{f.current({type:"tool_call",timestamp:Date.now(),toolName:j.mcp,args:j.args})}),B()},onUpdateStep:(W,se,j,G)=>{l.updateStep(W,se,j,G),f.current({type:"tool_result",timestamp:Date.now(),toolName:W,success:se==="completed",data:j,error:G}),B()}}),Y=[];let F=!1;const q=new Map;o.steps.forEach(A=>{var W;const J=(W=A.result)==null?void 0:W.taskId;J&&q.set(A.id,J)});const oe=async A=>{var se,j,G,wt,It,yt;const J=Date.now(),W=Y.length;l.updateStep(A.id,"running"),B();try{const xt=q.get(A.id),Bn={...A.options,...z(A,J),...xt?{retryTaskId:xt}:{}},$t=Sn(b,A),pe=await Xo.executeTool({name:$t.mcp,arguments:$t.args},Bn),Ze=(j=(se=l.getWorkflow())==null?void 0:se.steps.find(Ut=>Ut.id===A.id))==null?void 0:j.status;if(pe.success){if(pe.taskId)l.updateStep(A.id,"running",{taskId:pe.taskId}),U(T,pe.taskId,{workflowId:o.id,batchId:(G=A.options)==null?void 0:G.batchId,batchIndex:(wt=A.options)==null?void 0:wt.batchIndex});else if(Ze==="running"){const Ut=pe.type==="text"&&pe.data&&typeof pe.data=="object"&&"content"in pe.data?{content:pe.data.content}:pe.data;l.updateStep(A.id,"completed",Ut,void 0,Date.now()-J);const Pe=A.mcp==="generate_text"?(It=pe.data)==null?void 0:It.content:A.mcp==="ai_analyze"?(yt=pe.data)==null?void 0:yt.response:void 0;if((A.mcp==="generate_text"||A.mcp==="ai_analyze")&&Pe&&Pe.trim()&&Y.length===W){const _e={id:`${A.id}-insert-text`,mcp:"insert_to_canvas",args:{items:[{type:"text",content:Pe}]},description:A.mcp==="generate_text"?"将生成文本插入画布":"将 AI 回复插入画布",status:"pending"};l.addSteps([_e]),Y.push(_e)}}}else return l.updateStep(A.id,"failed",void 0,pe.error||"执行失败",Date.now()-J),!1;return!0}catch(xt){return l.updateStep(A.id,"failed",void 0,String(xt)),!1}finally{B()}},ye=b.steps.slice(i);for(const A of ye){if(F){l.updateStep(A.id,"skipped"),B();continue}await oe(A)||(F=!0)}if(!F&&Y.length>0)for(const A of Y){if(F){l.updateStep(A.id,"skipped"),B();continue}const J=(Ht=l.getWorkflow())==null?void 0:Ht.steps.find(se=>se.id===A.id);if(!J||J.status==="completed")continue;await oe(J)||(F=!0)}const te=l.getWorkflow(),ke=te==null?void 0:te.steps.every(A=>A.status==="completed"||A.status==="failed"||A.status==="skipped"),Ue=te==null?void 0:te.steps.some(A=>{var J;return(J=A.result)==null?void 0:J.taskId});if(ke&&!Ue){const A=g.current,J=De.current;A&&J&&(te!=null&&te.steps.every(se=>{const j=se.result;return j!=null&&j.taskId?Un.isPostProcessingCompleted(j.taskId):!0}))&&setTimeout(()=>{je.removeWorkZone(J,A),g.current=null},1500)}},[l,U]);r.useEffect(()=>{C.current(Ln);const o=De.current;o&&(o.__executeWorkflowRetry=Ln)},[Ln]);const Qs=r.useCallback(o=>{var i;if(!o.nativeEvent.isComposing&&!(o.key==="Enter"&&(o.shiftKey||o.altKey))){if((xo||_o||bo)&&(o.key==="Enter"||o.key==="Tab")){o.preventDefault();return}if(o.key==="Enter"){o.preventDefault(),Ae.track("ai_input_submit_keyboard"),Wn("keyboard");return}if(o.key==="Escape"){ot(!1),(i=Te.current)==null||i.blur();return}}},[Wn]),er=r.useCallback(()=>{Ae.track("ai_input_focus_textarea"),ot(!0)},[]),tr=r.useCallback(()=>{Ae.track("ai_input_blur_textarea"),ot(!1)},[]),nr=r.useCallback(o=>{const i=o.target.value,m=o.target.selectionStart||i.length;if(tt(i),m>0){const w=i[m-1],b=m>1?i[m-2]:" ";w==="#"&&(b===" "||b===`
8
+ `||m===1)&&(st.current=m-1,Rn(!0),Nn(!1),jn(!1))}},[]),or=r.useMemo(()=>JSON.stringify({generationType:x,model:O,profileId:(L==null?void 0:L.profileId)||null,hasAttachedContent:ce.length>0,attachedCount:ce.length,promptLengthBucket:Xn(fe.trim().length)}),[ce.length,x,fe,O,L==null?void 0:L.profileId]),Do=fe.trim().length>0||ce.length>0,Ro=Rs===!0,sr=Pn.some(o=>{var i;return o.type==="text"&&((i=o.text)==null?void 0:i.trim())}),at=Nt||ce.length>0||As;return r.useLayoutEffect(()=>{Qa(Te.current,at)},[at,fe]),p.jsxs("div",{ref:un,className:gn("ai-input-bar",Tn,e,{"ai-input-bar--with-inspiration":Ro}),"data-testid":"ai-input-bar",children:[p.jsx(Ps,{language:s,onSelectionChange:Vs,externalBoardRef:De,onCanvasEmptyChange:Ns,isDataReady:n,onFrameSelected:Gs}),p.jsx(ja,{isCanvasEmpty:Ro,onSelectPrompt:Ws,onOpenPromptTool:Fs}),p.jsxs("div",{className:gn("ai-input-bar__container",{"ai-input-bar__container--expanded":at}),children:[p.jsxs("div",{className:"ai-input-bar__bottom-bar",children:[p.jsx("input",{ref:Mo,type:"file",accept:"image/*",multiple:!0,onChange:Us,style:{display:"none"}}),p.jsx("button",{className:"ai-input-bar__upload-btn",onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:$s,title:s==="zh"?"上传图片":"Upload images","data-track":"ai_input_click_upload",children:p.jsx(Lr,{size:18})}),p.jsx("button",{className:"ai-input-bar__library-btn",onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:()=>Bt(!0),title:s==="zh"?"从素材库选择":"Select from library","data-track":"ai_input_click_library",children:p.jsx(Br,{size:18})}),p.jsx(za,{value:x,onSelect:Be,disabled:Le}),x==="agent"&&p.jsx(Ea,{value:Ie,onSelect:An,onSelectSkill:Zs,onAddSkill:Bs,disabled:Le}),p.jsx(_n,{selectedModel:O,selectedSelectionKey:ze(O,L),onSelect:Ys,onSelectModel:Xs,language:s,models:ln,header:s==="zh"?x==="agent"?"选择文本模型 (↑↓ Tab)":"选择模型 (↑↓ Tab)":x==="agent"?"Select text model (↑↓ Tab)":"Select model (↑↓ Tab)",isOpen:xo,onOpenChange:js}),x==="agent"&&Ie!==et&&Dn.includes("image")&&p.jsx(_n,{selectedModel:Fe,selectedSelectionKey:ze(Fe,Ge),onSelect:(o,i)=>zn("image",o,i),onSelectModel:o=>On("image",o),language:s,models:jt,header:s==="zh"?"选择图片模型 (↑↓ Tab)":"Select image model (↑↓ Tab)"}),x==="agent"&&Ie!==et&&Dn.includes("video")&&p.jsx(_n,{selectedModel:He,selectedSelectionKey:ze(He,Ke),onSelect:(o,i)=>zn("video",o,i),onSelectModel:o=>On("video",o),language:s,models:zt,header:s==="zh"?"选择视频模型 (↑↓ Tab)":"Select video model (↑↓ Tab)"}),x==="agent"&&Ie!==et&&Dn.includes("audio")&&p.jsx(_n,{selectedModel:$e,selectedSelectionKey:ze($e,Ye),onSelect:(o,i)=>zn("audio",o,i),onSelectModel:o=>On("audio",o),language:s,models:Ot,header:s==="zh"?"选择音频模型 (↑↓ Tab)":"Select audio model (↑↓ Tab)"}),x!=="agent"&&Ft.length>0&&p.jsx(ha,{selectedParams:Ce,onParamChange:qs,compatibleParams:Ft,modelId:O,language:s,isOpen:_o,onOpenChange:zs},O),x!=="agent"&&x!=="text"&&x!=="audio"&&p.jsx(Oa,{value:Lt,onSelect:Js,disabled:Le,isOpen:bo,onOpenChange:Os}),p.jsx("div",{className:"ai-input-bar__bottom-spacer"}),p.jsx("button",{className:`ai-input-bar__send-btn ${Do?"active":""} ${Le?"loading":""}`,onMouseDown:o=>{o.preventDefault(),o.stopPropagation()},onClick:()=>Wn("button"),disabled:!Do||Le,"data-track":"ai_input_click_send","data-track-params":or,"data-testid":"ai-send-btn",children:p.jsx(Fr,{size:18})})]}),p.jsxs("div",{className:gn("ai-input-bar__input-area",{"ai-input-bar__input-area--expanded":at}),children:[ce.length>0&&p.jsx("div",{className:"ai-input-bar__content-preview",children:p.jsx(sa,{items:ce,language:s,enableHoverPreview:!0,onRemove:Ks,removableStartIndex:Rt.length})}),p.jsxs("div",{className:"ai-input-bar__prompt-row",children:[p.jsx("div",{className:"ai-input-bar__rich-input",children:p.jsx("textarea",{ref:Te,className:gn("ai-input-bar__input",{"ai-input-bar__input--focused":at}),value:fe,onChange:nr,onKeyDown:Qs,onFocus:er,onBlur:tr,placeholder:x==="agent"?s==="zh"?"输入指令,让 Agent 为你工作...":"Type instructions for Agent...":x==="text"?s==="zh"?"输入你想生成的文本内容、文章、摘要或 Markdown":"Describe the text, article, summary, or markdown you want":x==="audio"?sr?s==="zh"?"已有文本,无需额外提示词,直接发送":"Text already selected. No extra prompt needed, just send":s==="zh"?"描述你想要生成的音乐、风格、歌词或情绪":"Describe the music, style, lyrics, or mood you want":s==="zh"?`描述你想要创建的${x==="image"?"图片":"视频"}`:`Describe the ${x==="image"?"image":"video"} you want to create`,rows:at?Ts:Za,disabled:Le,"data-testid":"ai-input-textarea"})}),p.jsx(fa,{generationType:x,onSelectPrompt:Ls,language:s,onBeforeOpenMyPrompts:t,extraActions:at?p.jsx(ea,{className:"prompt-history-popover__action-btn",originalPrompt:fe,language:s,scenarioId:`ai-input.${x}`,disabled:Le,allowStructuredMode:!0,onOpenChange:Ds,onMouseDown:o=>{o.preventDefault(),o.stopPropagation(),ot(!0)},onApply:o=>{tt(o),ot(!0),requestAnimationFrame(()=>{var i;(i=Te.current)==null||i.focus()})}}):null})]})]})]}),vo&&p.jsx(ta,{isOpen:vo,onClose:()=>Bt(!1),mode:Hr.SELECT,filterType:Fo.IMAGE,onSelect:Hs})]})});Es.displayName="AIInputBar";function Ii({isDataReady:e,activationKey:n,onEnableToolWindows:t}){const s=r.useRef(null);return r.useEffect(()=>{if(n<=0)return;const d=window.setTimeout(()=>{var a;const c=(a=s.current)==null?void 0:a.querySelector('[data-testid="ai-input-textarea"]');c==null||c.focus()},0);return()=>{window.clearTimeout(d)}},[n]),p.jsx(Kr,{children:p.jsx(na,{children:p.jsx("div",{ref:s,children:p.jsx(Es,{isDataReady:e,onEnableToolWindows:t})})})})}export{Ii as DeferredAIInputBar,Ii as default};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-B7ypM2x4.css","./tool-windows-CDLejk69.css"])))=>i.map(i=>d[i]);
2
+ import{_ as s}from"./startup-runtime-DTmhLESk.js";import{bG as M,S as t,P as n}from"./startup-app-DC9IB1KI.js";const F=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.b5),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.ProjectDrawer}))),U=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.b6),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.ToolboxDrawer}))),W=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.b7),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.DeferredMediaLibraryModal}))),G=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.b8),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.BackupRestoreDialog}))),b=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.b9),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.VersionUpdatePrompt}))),q=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.ba),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.PerformancePanel}))),H=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.bb),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.DeferredSyncSettings}))),J=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.bc),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.CommandPalette}))),K=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.bd),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.CanvasSearch}))),N=n.lazy(()=>s(()=>import("./tool-windows-Do7Od789.js").then(e=>e.be),__vite__mapDeps([0,1]),import.meta.url).then(e=>({default:e.ToolWinBoxManager})));function Y({board:e,value:i,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(G,{open:h,onOpenChange:V,container:o.current,onBeforeImport:async()=>{await x()},onSwitchBoard:async(a,S)=>{const{workspaceService:w}=await s(async()=>{const{workspaceService:z}=await import("./startup-app-DC9IB1KI.js").then(B=>B.ma);return{workspaceService:z}},__vite__mapDeps([0]),import.meta.url),c=await w.switchBoard(a);c&&r&&(S&&(c.viewport=S),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(b,{})}),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(a=>({...a,openCommandPalette:!1}))},board:e,container:o.current})}),E&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(K,{open:E,onClose:()=>{d(a=>({...a,openCanvasSearch:!1}))},board:e})}),D&&t.jsx(n.Suspense,{fallback:null,children:t.jsx(q,{container:o.current,onCreateProject:R,elements:(e==null?void 0:e.children)||i})}),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{Y as DrawnixDeferredFeatures,Y as default};