aitu-app 0.6.81 → 0.6.82

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 (61) hide show
  1. package/README.md +3 -3
  2. package/assets/{CanvasAudioPlayer-9fGci4ku.js → CanvasAudioPlayer-EQjMjqlc.js} +2 -2
  3. package/assets/{ChatDrawer-e2rH9l0h.js → ChatDrawer-CbBhCIU_.js} +6 -6
  4. package/assets/{ChatMessagesArea-3ZzACUMv.js → ChatMessagesArea-DatNDD1n.js} +2 -2
  5. package/assets/{DeferredAIInputBar-DURNAyXo.js → DeferredAIInputBar-rIx0c8Qv.js} +5 -5
  6. package/assets/DrawnixDeferredFeatures-C8aKfyQG.js +2 -0
  7. package/assets/KnowledgeBaseContent-vj5G-Ele.js +53 -0
  8. package/assets/{MVCreator-D5xlhWzm.js → MVCreator-DM_I1mJr.js} +10 -10
  9. package/assets/{ModelBenchmarkWorkbench-Be9URCRl.js → ModelBenchmarkWorkbench-CfgAcLzz.js} +3 -3
  10. package/assets/{MusicAnalyzer-D2nEg3Tk.js → MusicAnalyzer-C-ZI5UZd.js} +2 -2
  11. package/assets/{MusicAnalyzer-BIa7022Z.js → MusicAnalyzer-DcDwJ88i.js} +1 -1
  12. package/assets/PromptHistoryTool-DtvW3bCO.js +2 -0
  13. package/assets/{ResizableDivider-BWDSFS9v.js → ResizableDivider-DYCCpuYw.js} +1 -1
  14. package/assets/{TaskQueuePanel-D4QcfHIB.js → TaskQueuePanel-DE2L1_EL.js} +1 -1
  15. package/assets/{VideoAnalyzer-DNA-f64D.js → VideoAnalyzer-D2uuXL5i.js} +2 -2
  16. package/assets/{ai-generation-preferences-service-DrjKyyuV.js → ai-generation-preferences-service-BZMqxTjU.js} +1 -1
  17. package/assets/{batch-image-generation-CepQPA27.js → batch-image-generation-CNNwXxgK.js} +6 -6
  18. package/assets/{canvas-insertion-BlCq2aH3.js → canvas-insertion-C-BRaM5S.js} +3 -3
  19. package/assets/{diagram-engines-CwWz3QkB.css → diagram-engines-CGOhfK6V.css} +1 -1
  20. package/assets/{diagram-engines-D0zsaRpk.js → diagram-engines-DmAewdsu.js} +767 -1101
  21. package/assets/{editor-engines-DOeFgZem.js → editor-engines-DGOT7Xqo.js} +1 -1
  22. package/assets/{index-DsNBxclC.js → index-BDFn0Sob.js} +1 -1
  23. package/assets/{index-DH7a6bct.js → index-BVyqBBIM.js} +1 -1
  24. package/assets/{index-C2Okyhwh.js → index-BbDNsPPx.js} +2 -2
  25. package/assets/{index-DREtscFr.js → index-Bgp2wxvA.js} +2 -2
  26. package/assets/{index-C6lYWkxJ.js → index-DDzCo7oj.js} +16 -16
  27. package/assets/{index-0EUwts2b.js → index-DQQV1ik6.js} +2 -2
  28. package/assets/index-mUUunEI1.js +1 -0
  29. package/assets/{index-DYZPBW1D.js → index-o5qBH2kC.js} +6 -6
  30. package/assets/{main-Cbvfl50a.js → main-B2ZrUywM.js} +17 -17
  31. package/assets/model-benchmark-launcher-QpuZmCET.js +1 -0
  32. package/assets/{office-data-BdSQwbNL.js → office-data-2Ik8Wb2D.js} +1 -1
  33. package/assets/{photo-wall-splitter-VPjwL1DW.js → photo-wall-splitter-BD8mt52h.js} +1 -1
  34. package/assets/{ppt-generation-xbd_oT05.js → ppt-generation-BLs-dVnA.js} +4 -4
  35. package/assets/{retry-image-C73v_TSX.js → retry-image-BMMnhw_0.js} +1 -1
  36. package/assets/{settings-dialog-BUL3AK9O.js → settings-dialog-xu3d4MX_.js} +1 -1
  37. package/assets/{shared-runtime-BQ8G5UJo.js → shared-runtime-DBavnB0U.js} +2 -2
  38. package/assets/{skill-dsl-parser-DmTnn-8k.js → skill-dsl-parser-BAv2yCP9.js} +3 -3
  39. package/assets/tool-windows-DV-j2p51.js +499 -0
  40. package/assets/{ttd-dialog-DgLOAZt1.js → ttd-dialog-CwkEQ_6x.js} +3 -3
  41. package/assets/{useCharacters-DfE2Kw4B.js → useCharacters-D3PdMQMn.js} +2 -2
  42. package/assets/{useWorkflowSubmission-CLdnk3k9.js → useWorkflowSubmission-BIFN-qvq.js} +6 -6
  43. package/assets/{video-analyze-DznWVjSF.js → video-analyze-BeuyAh9W.js} +1 -1
  44. package/assets/{video-generation-Bnu5qF1C.js → video-generation-C2GITib6.js} +2 -2
  45. package/assets/{video-recovery-service-CSTgH6ZL.js → video-recovery-service-BBDuz2L1.js} +1 -1
  46. package/assets/{workflow-generation-utils-DxQkot1n.js → workflow-generation-utils-Vh2FVA3M.js} +3 -3
  47. package/assets/workflow-submission-service-BRb6CPDr.js +4 -0
  48. package/changelog.json +13 -0
  49. package/idle-prefetch-manifest.json +170 -170
  50. package/manifest.json +3 -3
  51. package/package.json +1 -1
  52. package/precache-manifest.json +6 -6
  53. package/sw.js +5 -5
  54. package/version.json +3 -10
  55. package/assets/DrawnixDeferredFeatures-Bqc5hzfo.js +0 -2
  56. package/assets/KnowledgeBaseContent-Dgi_9JmP.js +0 -53
  57. package/assets/PromptHistoryTool-Cu5Ne0CT.js +0 -2
  58. package/assets/index-CgfUrYUT.js +0 -1
  59. package/assets/model-benchmark-launcher-BQj84yC8.js +0 -1
  60. package/assets/tool-windows-DSHfJOm9.js +0 -165
  61. package/assets/workflow-submission-service-XOcxTwb1.js +0 -4
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Opentu CDN Assets v0.6.81
1
+ # Opentu CDN Assets v0.6.82
2
2
 
3
3
  > 静态资源包,不含 HTML 文件
4
4
 
5
- - unpkg: https://unpkg.com/aitu-app@0.6.81/
6
- - jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.81/
5
+ - unpkg: https://unpkg.com/aitu-app@0.6.82/
6
+ - jsdelivr: https://cdn.jsdelivr.net/npm/aitu-app@0.6.82/
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./diagram-engines-CwWz3QkB.css","./tool-windows-CqSDeXz5.css"])))=>i.map(i=>d[i]);
2
- import{_ as ke}from"./startup-runtime-BbuNXj6O.js";import{r as n,j as t,i as be,H as N,ft as Ae,db as Se,bu as Le,aq as ue,cn as Te,c4 as Ee,aM as oe,cv as Ce,eL as Ne,cy as Me,cw as Re,cx as De,cz as ze,cA as de,cB as $e,hL as Oe,hM as Ue,hN as Fe,eM as qe,cD as Ye,cE as Ve,cF as Be,cG as He}from"./diagram-engines-D0zsaRpk.js";import{ci as We,cy as Qe,cz as Xe,cA as pe,cB as J,cC as U,cD as Ke,cE as Ge,cF as fe,cG as Z,cH as Je,_ as Ze,ch as ie,cI as ye,cJ as le,cK as _e,cL as et}from"./tool-windows-DSHfJOm9.js";import{U as tt}from"./shared-runtime-BQ8G5UJo.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,h]=n.useState(!1),w=n.useRef(!1),b=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();b.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=b.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,h(!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=b.current;if(!p)return;cancelAnimationFrame(p.frameId);const u=p.activated;b.current=null,h(!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),h=n.useRef(!1),[w,b]=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(),b(!0)},M=()=>{u(),b(d=>!d)},S=()=>{u(),!(v.current||h.current)&&(c.current=window.setTimeout(()=>{b(!1)},180))};return n.useEffect(()=>{v.current=j},[j]),n.useEffect(()=>{h.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(),b(!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=()=>{h.current=!1,y(!1),v.current||(u(),c.current=window.setTimeout(()=>{b(!1)},180))};return window.addEventListener("pointerup",d),()=>window.removeEventListener("pointerup",d)},[P]),t.jsx("div",{ref:s,className:be("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(),h.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(N,{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:h,onPlayAllTracksItem:w})=>{const{assets:b}=We(),{playlists:j,playlistItems:_,favoriteAssetIds:P,createPlaylist:y,addAssetToPlaylist:m,removeAssetFromPlaylist:p,toggleFavorite:u}=Qe(),{contextMenu:g,openAt:M,close:S}=Le(),[d,x]=n.useState(!1),[k,E]=n.useState(""),[F,L]=n.useState(null),{noteMetas:z,loadReadingSource:Q,buildReadingQueue:X}=Xe(),[q,Y]=n.useState(s==="reading"?pe:J),V=q===pe,R=s==="playlist"&&c?c:J,T=e.filter(a=>!U(a)),ee=Ke(T),K=a=>{const o=it(a);if(o)return o;if(!(a!=null&&a.audioUrl))return null;const r=b.find(I=>I.type===tt.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?Ge({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 X(a),h(o))},[w,Q,X,h]),$=n.useMemo(()=>z.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})),[z,v,f]);return s==="reading"?t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(fe,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:T.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(ue,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,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&&h(o)},onTogglePlayback:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&h(o)},showPlaybackIndicator:!0})]}):t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(fe,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:T.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(ue,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,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:T.map((a,o)=>{const r=K(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=T.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&h(o)},onContextMenu:(a,o)=>{const r=T.find((H,te)=>`${H.audioUrl}-${te}`===a.id),I=K(r);I&&(o.preventDefault(),o.stopPropagation(),M(o.clientX,o.clientY,{kind:"asset",assetId:I}))},onToggleFavorite:a=>{const o=T.find((I,H)=>`${I.audioUrl}-${H}`===a.id),r=K(o);r&&u(r)},onTogglePlayback:a=>{const o=T.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&h(o)},showFavoriteButton:!0,showPlaybackIndicator:!0}),t.jsx(Je,{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"&&(L(a.assetId),E(""),x(!0))}}),t.jsx(Te,{visible:d,header:"新建播放列表",onClose:()=>x(!1),onConfirm:async()=>{const a=await y(k);F&&await m(F,a.id),x(!1),E(""),L(null)},onCancel:()=>{x(!1),L(null)},confirmBtn:"确定",cancelBtn:"取消",children:t.jsx(Ee,{value:k,onChange:a=>E(String(a)),placeholder:"请输入播放列表名称"})})]})},we={sequential:t.jsx(He,{size:14}),"list-loop":t.jsx(Be,{size:14}),"single-loop":t.jsx(Ve,{size:14}),shuffle:t.jsx(Ye,{size:14})},ct=Object.keys(le).map(e=>({value:e,content:le[e],prefixIcon:we[e]}));function ut(e,i){return et(i).map(s=>{const c=_e(s),f=Math.abs(s-e)<.001;return{value:s,content:f?`✓ ${c}`:c}})}function he(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 vt=()=>{const e=Ze(),i=n.useRef(null),[s,c]=n.useState(!1),[f,v]=n.useState(()=>{const l=ie.getToolState(ye);return(l==null?void 0:l.status)==="open"}),[h,w]=n.useState(()=>{try{return localStorage.getItem(oe.AUDIO_PLAYER_LAYOUT)==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[b,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 _=b<=768?"vertical":h,[P,y]=n.useState(null),m=b<=768,{position:p,isDragging:u,wasDraggedRef:g,elementRef:M,handlePointerDown:S}=st({storageKey:oe.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=he(x),F=he(k),L=e.activeQueueIndex>=0?e.queue[e.activeQueueIndex]:null,z=e.activeTitle||(U(L)?L.title:void 0),Q=e.activePreviewImageUrl||(U(L)?L.previewImageUrl:void 0),X=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"?"朗读轨道":"画布音频"),T=Y?`${R} ${e.activeQueueIndex+1} / ${e.queue.length}`:R,ee=V?`${V} · ${E} / ${F}`:`${E} / ${F}`,B=e.queueSource==="reading"&&(!!e.activeReadingSourceId||L!==null&&U(L))||!!e.activeAudioUrl,D=e.mediaType==="audio",$=e.mediaType==="reading"?"reading":"audio",a=le[e.playbackMode],o=we[e.playbackMode],r=n.useMemo(()=>ut(e.effectivePlaybackRate,$),[e.effectivePlaybackRate,$]),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(oe.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)},C=()=>{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(()=>C()):null;return O&&ae instanceof HTMLElement&&O.observe(ae),O&&ne instanceof HTMLElement&&ne!==ae&&O.observe(ne),C(),window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{window.cancelAnimationFrame(l),window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C),O==null||O.disconnect()}},[B]),n.useEffect(()=>{if(!s)return;const l=A=>{var C;(C=i.current)!=null&&C.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=ie.observeToolStates().subscribe(()=>{const A=ie.getToolState(ye);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:be("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(Ce,{src:Q,alt:z||"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:z||"未命名音频"}),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:T}),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(Ne,{size:14})})]}),t.jsxs("div",{className:"canvas-audio-player__controls",children:[t.jsx(N,{content:"上一首",children:t.jsx("button",{type:"button",className:"canvas-audio-player__action canvas-audio-player__action--previous",onClick:()=>void e.playPrevious(),disabled:!X,children:t.jsx(Me,{size:14})})}),t.jsx(N,{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(Re,{size:14}):t.jsx(De,{size:14})})}),t.jsx(N,{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(ze,{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(de,{options:r,trigger:"click",placement:"bottom",minColumnWidth:112,onClick:l=>e.setPlaybackRate(Number(l.value)),children:t.jsx(N,{content:H,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__speed-toggle","aria-label":`切换播放速度,当前${I}`,children:t.jsx($e,{size:14})})})}),t.jsx(de,{options:ct,trigger:"click",placement:"bottom",minColumnWidth:132,onClick:l=>e.setPlaybackMode(l.value),children:t.jsx(N,{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(N,{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("./tool-windows-DSHfJOm9.js").then(A=>A.ds);return{openMusicPlayerTool:l}},__vite__mapDeps([0,1]),import.meta.url).then(({openMusicPlayerTool:l})=>{l()})},"aria-label":"打开播放器工具",children:t.jsx(Oe,{size:14})})}),t.jsx(N,{content:_==="horizontal"?"切换为垂直布局":"切换为水平布局",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__layout-toggle",onClick:Pe,style:{display:b<=768?"none":""},children:_==="horizontal"?t.jsx(Ue,{size:14}):t.jsx(Fe,{size:14})})}),t.jsx(N,{content:"关闭播放器",children:t.jsx("button",{type:"button",className:"canvas-audio-player__close",onClick:e.stopPlayback,children:t.jsx(qe,{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{vt as CanvasAudioPlayer};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./diagram-engines-CGOhfK6V.css","./tool-windows-CqSDeXz5.css"])))=>i.map(i=>d[i]);
2
+ import{_ as ke}from"./startup-runtime-BbuNXj6O.js";import{r as n,j as t,i as be,H as N,fz as Ae,di as Se,bt as Le,aq as ue,cm as Te,c3 as Ee,aM as oe,cu as Ce,eR as Ne,cx as Me,cv as Re,cw as De,cy as ze,cz as de,cA as $e,hK as Oe,hL as Ue,hM as Fe,eS as qe,cC as Ye,cD as Ve,cE as He,cF as Be}from"./diagram-engines-DmAewdsu.js";import{co as Qe,cF as We,cG as Ke,cH as pe,cI as J,cJ as U,cK as Xe,cL as Ge,cM as fe,cN as Z,cO as Je,_ as Ze,ch as ie,cP as ye,cQ as _e,cR as le,cS as et}from"./tool-windows-DV-j2p51.js";import{U as tt}from"./shared-runtime-DBavnB0U.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,h]=n.useState(!1),w=n.useRef(!1),b=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();b.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=b.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,h(!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=b.current;if(!p)return;cancelAnimationFrame(p.frameId);const u=p.activated;b.current=null,h(!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),h=n.useRef(!1),[w,b]=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(),b(!0)},M=()=>{u(),b(d=>!d)},S=()=>{u(),!(v.current||h.current)&&(c.current=window.setTimeout(()=>{b(!1)},180))};return n.useEffect(()=>{v.current=j},[j]),n.useEffect(()=>{h.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(),b(!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=()=>{h.current=!1,y(!1),v.current||(u(),c.current=window.setTimeout(()=>{b(!1)},180))};return window.addEventListener("pointerup",d),()=>window.removeEventListener("pointerup",d)},[P]),t.jsx("div",{ref:s,className:be("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(),h.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(N,{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:h,onPlayAllTracksItem:w})=>{const{assets:b}=Qe(),{playlists:j,playlistItems:_,favoriteAssetIds:P,createPlaylist:y,addAssetToPlaylist:m,removeAssetFromPlaylist:p,toggleFavorite:u}=We(),{contextMenu:g,openAt:M,close:S}=Le(),[d,x]=n.useState(!1),[k,E]=n.useState(""),[F,L]=n.useState(null),{noteMetas:z,loadReadingSource:W,buildReadingQueue:K}=Ke(),[q,Y]=n.useState(s==="reading"?pe:J),V=q===pe,R=s==="playlist"&&c?c:J,T=e.filter(a=>!U(a)),ee=Xe(T),X=a=>{const o=it(a);if(o)return o;if(!(a!=null&&a.audioUrl))return null;const r=b.find(I=>I.type===tt.AUDIO&&I.url===a.audioUrl);return(r==null?void 0:r.id)||null},H=n.useMemo(()=>new Set(R!==J?(_[R]||[]).map(a=>a.assetId?Ge({kind:"asset",assetId:a.assetId}):null).filter(a=>!!a):[]),[_,R]),D=n.useCallback(async a=>{if(w){w(a);return}const o=await W(a);o&&(await K(a),h(o))},[w,W,K,h]),$=n.useMemo(()=>z.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})),[z,v,f]);return s==="reading"?t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(fe,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:T.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(ue,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,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&&h(o)},onTogglePlayback:a=>{const o=e.find(r=>U(r)&&r.readingSourceId===a.id);o&&h(o)},showPlaybackIndicator:!0})]}):t.jsxs("div",{className:"canvas-audio-player__playlist",children:[t.jsx(fe,{className:"canvas-audio-player__playlist-tabs",selectedPlaylistId:q,allCount:T.length,allTracksCount:z.length,playlists:j,playlistItems:_,onSelect:Y,onCreate:()=>{E(""),x(!0)}}),V?$.length===0?t.jsxs("div",{className:"canvas-audio-player__playlist-empty",children:[t.jsx(ue,{size:16}),t.jsx("span",{children:"知识库还没有笔记"})]}):t.jsx(Z,{className:"canvas-audio-player__playlist-list",items:$,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:T.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=T.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&h(o)},onContextMenu:(a,o)=>{const r=T.find((B,te)=>`${B.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=T.find((I,B)=>`${I.audioUrl}-${B}`===a.id),r=X(o);r&&u(r)},onTogglePlayback:a=>{const o=T.find((r,I)=>`${r.audioUrl}-${I}`===a.id);o&&h(o)},showFavoriteButton:!0,showPlaybackIndicator:!0}),t.jsx(Je,{contextMenu:g?{x:g.x,y:g.y,item:g.payload}:null,playlists:j,playlistItems:_,favoriteAssetIds:P,selectedPlaylistId:R===J?null:R,currentPlaylistItemKeys:H,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"&&(L(a.assetId),E(""),x(!0))}}),t.jsx(Te,{visible:d,header:"新建播放列表",onClose:()=>x(!1),onConfirm:async()=>{const a=await y(k);F&&await m(F,a.id),x(!1),E(""),L(null)},onCancel:()=>{x(!1),L(null)},confirmBtn:"确定",cancelBtn:"取消",children:t.jsx(Ee,{value:k,onChange:a=>E(String(a)),placeholder:"请输入播放列表名称"})})]})},we={sequential:t.jsx(Be,{size:14}),"list-loop":t.jsx(He,{size:14}),"single-loop":t.jsx(Ve,{size:14}),shuffle:t.jsx(Ye,{size:14})},ct=Object.keys(le).map(e=>({value:e,content:le[e],prefixIcon:we[e]}));function ut(e,i){return et(i).map(s=>{const c=_e(s),f=Math.abs(s-e)<.001;return{value:s,content:f?`✓ ${c}`:c}})}function he(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 vt=()=>{const e=Ze(),i=n.useRef(null),[s,c]=n.useState(!1),[f,v]=n.useState(()=>{const l=ie.getToolState(ye);return(l==null?void 0:l.status)==="open"}),[h,w]=n.useState(()=>{try{return localStorage.getItem(oe.AUDIO_PLAYER_LAYOUT)==="vertical"?"vertical":"horizontal"}catch{return"horizontal"}}),[b,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 _=b<=768?"vertical":h,[P,y]=n.useState(null),m=b<=768,{position:p,isDragging:u,wasDraggedRef:g,elementRef:M,handlePointerDown:S}=st({storageKey:oe.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=he(x),F=he(k),L=e.activeQueueIndex>=0?e.queue[e.activeQueueIndex]:null,z=e.activeTitle||(U(L)?L.title:void 0),W=e.activePreviewImageUrl||(U(L)?L.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"?"朗读轨道":"画布音频"),T=Y?`${R} ${e.activeQueueIndex+1} / ${e.queue.length}`:R,ee=V?`${V} · ${E} / ${F}`:`${E} / ${F}`,H=e.queueSource==="reading"&&(!!e.activeReadingSourceId||L!==null&&U(L))||!!e.activeAudioUrl,D=e.mediaType==="audio",$=e.mediaType==="reading"?"reading":"audio",a=le[e.playbackMode],o=we[e.playbackMode],r=n.useMemo(()=>ut(e.effectivePlaybackRate,$),[e.effectivePlaybackRate,$]),I=_e(e.effectivePlaybackRate),B=`${e.mediaType==="reading"?"语音速度":"播放速度"} ${I}`,te={"--canvas-audio-progress":`${d}%`},Pe=n.useCallback(()=>{w(l=>{const A=l==="horizontal"?"vertical":"horizontal";try{localStorage.setItem(oe.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(!H){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(Q=>Q&&Q.left===G.left&&Q.width===G.width&&Q.bottom===G.bottom?Q:G)},C=()=>{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(()=>C()):null;return O&&ae instanceof HTMLElement&&O.observe(ae),O&&ne instanceof HTMLElement&&ne!==ae&&O.observe(ne),C(),window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{window.cancelAnimationFrame(l),window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C),O==null||O.disconnect()}},[H]),n.useEffect(()=>{if(!s)return;const l=A=>{var C;(C=i.current)!=null&&C.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=ie.observeToolStates().subscribe(()=>{const A=ie.getToolState(ye);v((A==null?void 0:A.status)==="open")});return()=>l.unsubscribe()},[]),!H||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:be("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(Ce,{src:W,alt:z||"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:z||"未命名音频"}),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:T}),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(Ne,{size:14})})]}),t.jsxs("div",{className:"canvas-audio-player__controls",children:[t.jsx(N,{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(Me,{size:14})})}),t.jsx(N,{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(Re,{size:14}):t.jsx(De,{size:14})})}),t.jsx(N,{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(ze,{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(de,{options:r,trigger:"click",placement:"bottom",minColumnWidth:112,onClick:l=>e.setPlaybackRate(Number(l.value)),children:t.jsx(N,{content:B,children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__speed-toggle","aria-label":`切换播放速度,当前${I}`,children:t.jsx($e,{size:14})})})}),t.jsx(de,{options:ct,trigger:"click",placement:"bottom",minColumnWidth:132,onClick:l=>e.setPlaybackMode(l.value),children:t.jsx(N,{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(N,{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("./tool-windows-DV-j2p51.js").then(A=>A.dL);return{openMusicPlayerTool:l}},__vite__mapDeps([0,1]),import.meta.url).then(({openMusicPlayerTool:l})=>{l()})},"aria-label":"打开播放器工具",children:t.jsx(Oe,{size:14})})}),t.jsx(N,{content:_==="horizontal"?"切换为垂直布局":"切换为水平布局",children:t.jsx("button",{type:"button",className:"canvas-audio-player__toggle canvas-audio-player__layout-toggle",onClick:Pe,style:{display:b<=768?"none":""},children:_==="horizontal"?t.jsx(Ue,{size:14}):t.jsx(Fe,{size:14})})}),t.jsx(N,{content:"关闭播放器",children:t.jsx("button",{type:"button",className:"canvas-audio-player__close",onClick:e.stopPlayback,children:t.jsx(qe,{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{vt as CanvasAudioPlayer};
@@ -1,11 +1,11 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./diagram-engines-CwWz3QkB.css","./editor-engines-B8u8agiX.css","./tool-windows-CqSDeXz5.css","./main-CRPCRx46.css","./index-DmlAaIoR.css","./MediaLibrarySidebar-CNCXXhfY.css","./ChatMessagesArea-PlF5AwzD.css"])))=>i.map(i=>d[i]);
2
- import{_ as rt}from"./startup-runtime-BbuNXj6O.js";import{R as oe,r as s,j as r,dL as Et,dO as vt,dg as ot,H as ke,gU as Tt,dt as Ct,d$ as Dt,dy as qe,dA as At,hu as Rt,i$ as Je,eu as Nt,bn as jt,c4 as Lt,dU as Wt,j0 as $t,j1 as Pt,j2 as Ut,b7 as zt,hK as Ht,hJ as Ft,ds as Gt,j3 as Kt,ae as it,gN as Qe,cQ as Y,j4 as Vt,j5 as Bt,j6 as Xt,j7 as Ot,gS as qt,is as Jt,it as Qt,j8 as Yt,j9 as Zt,h1 as es,bV as ts,f0 as ss,cP as ns,ja as as}from"./diagram-engines-D0zsaRpk.js";import{bN as rs}from"./tool-windows-DSHfJOm9.js";import{b9 as os,F as Me,aa as ct,H as is,c as cs,ab as ls,ac as ds,g as $e,ae as us,af as fs,N as ms,r as Ye}from"./shared-runtime-BQ8G5UJo.js";import{S as ps,i as gs,u as hs}from"./index-C6lYWkxJ.js";import{c as ws}from"./main-Cbvfl50a.js";const lt=oe.memo(({session:t,isActive:e,onSelect:o,onDelete:d,onRename:w})=>{const[i,c]=s.useState(!1),[l,M]=s.useState(t.title),I=s.useRef(null),S=s.useCallback(()=>{i||o()},[o,i]),b=s.useCallback(_=>{_.stopPropagation(),d()},[d]),A=s.useCallback(_=>{_.stopPropagation(),M(t.title),c(!0)},[t.title]),y=s.useCallback(()=>{const _=l.trim();_&&_!==t.title&&w(_),c(!1)},[l,t.title,w]),z=s.useCallback(()=>{M(t.title),c(!1)},[t.title]),k=s.useCallback(_=>{_.key==="Enter"?(_.preventDefault(),y()):_.key==="Escape"&&(_.preventDefault(),z())},[y,z]),E=s.useCallback(_=>{M(_.target.value)},[]);s.useEffect(()=>{i&&I.current&&(I.current.focus(),I.current.select())},[i]);const H=s.useMemo(()=>{const _=new Date(t.updatedAt),q=new Date;return _.toDateString()===q.toDateString()?_.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):_.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[t.updatedAt]);return r.jsxs("div",{className:`session-item ${e?"session-item--active":""} ${i?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:S,role:"button",tabIndex:0,onKeyDown:_=>!i&&_.key==="Enter"&&S(),children:[r.jsxs("div",{className:"session-item__content",children:[i?r.jsx("input",{ref:I,className:"session-item__title-input",value:l,onChange:E,onKeyDown:k,onBlur:y,onClick:_=>_.stopPropagation(),maxLength:50}):r.jsx("div",{className:"session-item__title",children:t.title}),r.jsx("div",{className:"session-item__time",children:H})]}),!i&&r.jsxs("div",{className:"session-item__actions",children:[r.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:A,"aria-label":`编辑会话标题: ${t.title}`,children:r.jsx(Et,{size:14})}),r.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:b,"aria-label":`删除会话: ${t.title}`,children:r.jsx(vt,{size:14})})]})]})});lt.displayName="SessionItem";const dt=oe.memo(({sessions:t,activeSessionId:e,onSelectSession:o,onNewSession:d,onDeleteSession:w,onRenameSession:i})=>{const[c,l]=oe.useState(null),M=s.useCallback(y=>{o(y)},[o]),I=s.useCallback(y=>{l(y)},[]),S=s.useCallback(()=>{c&&(w(c),l(null))},[c,w]),b=s.useCallback(()=>{l(null)},[]),A=s.useCallback((y,z)=>{i(y,z)},[i]);return r.jsxs("div",{className:"session-list",children:[r.jsxs("div",{className:"session-list__header",children:[r.jsx("span",{className:"session-list__title",children:"会话列表"}),r.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:d,"aria-label":"新建会话",children:[r.jsx(ot,{size:14}),r.jsx("span",{children:"新建"})]})]}),r.jsx("div",{className:"session-list__items",children:t.length===0?r.jsx("div",{className:"session-list__empty",children:"暂无会话"}):t.map(y=>r.jsx(lt,{session:y,isActive:y.id===e,onSelect:()=>M(y.id),onDelete:()=>I(y.id),onRename:z=>A(y.id,z)},y.id))}),r.jsx(rs,{open:c!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:y=>{y||b()},onConfirm:S})]})});dt.displayName="SessionList";const ut=oe.memo(({isOpen:t,onClick:e,drawerWidth:o})=>{const d={right:t&&o?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${o-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return r.jsx(ke,{content:t?"收起对话":"展开对话",children:r.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:r.jsx(Tt,{size:16,className:"chat-drawer-trigger__icon"})})})});ut.displayName="ChatDrawerTrigger";function be(t){return t.sourceProfileName||ct[t.vendor]||t.id}const _s=oe.memo(({model:t})=>{const e=Ht(t.sourceProfileId,t.id);return e?r.jsx("span",{className:"model-selector__item-price",children:e}):null}),Ss=oe.memo(({model:t})=>{const e=Ft(t.sourceProfileId,t.id);return e!=null&&e.description?r.jsx("div",{className:"model-selector__item-desc",children:e.description}):null});function xs(t,e){var i;const o=be(t),d=(i=t.description)==null?void 0:i.trim(),w=(e==null?void 0:e.includeProvider)??!0;return d?!w||d.includes(o)?d:`${o} · ${d}`:w?o:""}function Ms(t){return be(t).trim().slice(0,1).toUpperCase()||"M"}const ft=oe.memo(({className:t,value:e,valueRef:o,onChange:d,variant:w="capsule"})=>{var $;const i=Ct("text"),c=(($=i[0])==null?void 0:$.id)||os,[l,M]=s.useState(c),[I,S]=s.useState(()=>Me(null,c)),b=e??l,A=o===void 0?I:o,[y,z]=s.useState(!1),[k,E]=s.useState(""),[H,_]=s.useState(null),q=s.useRef(null),X=s.useRef(null);s.useEffect(()=>{!e&&c&&l!==c&&(M(c),S(Me(null,c)))},[c,l,e]),s.useEffect(()=>{if(!y)return;const g=p=>{const U=p.target;q.current&&!q.current.contains(U)&&X.current&&!X.current.contains(U)&&(z(!1),E(""))},u=setTimeout(()=>{document.addEventListener("mousedown",g)},100);return()=>{clearTimeout(u),document.removeEventListener("mousedown",g)}},[y]);const V=s.useMemo(()=>b?Dt(b,A):null,[b,A]),j=s.useMemo(()=>{if(qe(i,b,A)||!b)return i;const u=At("text",b,A);return u?[u,...i]:i},[i,b,A]),x=s.useMemo(()=>qe(j,b,A)||j.find(g=>g.id===b),[j,b,A]),C=s.useCallback(g=>{const u=Me(g.sourceProfileId||null,g.id);e===void 0&&M(g.id),o===void 0&&S(u),d==null||d(g.id,u),z(!1),E("")},[e,o,d]),P=s.useCallback(()=>{const g=!y;z(g),g?_((x==null?void 0:x.vendor)||null):E("")},[x==null?void 0:x.vendor,y]),W=s.useMemo(()=>{const g=new Map,u=[];return j.forEach(p=>{g.has(p.vendor)||(u.push(p.vendor),g.set(p.vendor,0)),g.set(p.vendor,(g.get(p.vendor)??0)+1)}),u.map(p=>({id:p,label:ct[p],count:g.get(p)??0,icon:r.jsx(Rt,{vendor:p,size:14})}))},[j]),ae=s.useCallback(g=>{_(g)},[]),ie=s.useMemo(()=>{const g=k.toLowerCase().trim();return g?j.filter(u=>{var U,J;const p=be(u).toLowerCase();return u.id.toLowerCase().includes(g)||u.label.toLowerCase().includes(g)||((U=u.shortLabel)==null?void 0:U.toLowerCase().includes(g))||((J=u.description)==null?void 0:J.toLowerCase().includes(g))||p.includes(g)}):H?j.filter(u=>u.vendor===H):j},[k,H,j]),[O,ee]=s.useState({top:0,left:0,width:0,bottom:0,placement:"bottom",maxHeight:480});s.useLayoutEffect(()=>{if(!y)return;const g=()=>{if(!X.current)return;const u=X.current.getBoundingClientRect(),p=window.innerHeight,U=p-u.bottom,J=u.top,de=U<400&&J>U?"top":"bottom",te=de==="top"?J-16:p-u.bottom-16;ee({top:u.top,left:u.left,width:u.width,bottom:u.bottom,placement:de,maxHeight:Math.min(Math.max(te,200),600)})};return g(),window.addEventListener("resize",g),window.addEventListener("scroll",g,!0),()=>{window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0)}},[y]);const le=()=>{if(!y)return null;const g=r.jsxs("div",{ref:q,className:"model-selector__dropdown",style:{position:"fixed",zIndex:jt.DROPDOWN_PORTAL,left:O.left,top:O.placement==="bottom"?O.bottom+8:"auto",bottom:O.placement==="top"?window.innerHeight-O.top+8:"auto",minWidth:360,width:w==="form"?O.width:"auto",maxHeight:O.maxHeight,visibility:O.width===0?"hidden":"visible",transformOrigin:O.placement==="bottom"?"top left":"bottom left",display:"flex",flexDirection:"column"},onClick:u=>u.stopPropagation(),children:[r.jsx("div",{className:"model-selector__search",children:r.jsx(Lt,{value:k,onChange:E,placeholder:"搜索模型...",prefixIcon:r.jsx(Wt,{}),clearable:!0,autofocus:!0})}),r.jsx($t,{tabs:W,activeTab:H,onTabChange:ae,searchQuery:k,compact:!0,children:r.jsx("div",{className:"model-selector__list",children:ie.length===0?r.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):ie.map(u=>{const p=Pt(u),U=p===V,J=!!k.trim(),de=xs(u,{includeProvider:!J});return r.jsxs("button",{className:`model-selector__item ${U?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>C(u),children:[r.jsx("span",{className:"model-selector__item-icon model-selector__item-icon--text","aria-hidden":"true",children:Ms(u)}),r.jsxs("div",{className:"model-selector__item-content",children:[r.jsxs("div",{className:"model-selector__item-header",children:[r.jsx("span",{className:"model-selector__item-name",children:u.shortLabel||u.label}),J?r.jsx("span",{className:"model-selector__item-provider",children:be(u)}):null,r.jsx(Je,{modelId:u.id,profileId:u.sourceProfileId||null}),r.jsx(Ut,{modelId:u.id}),r.jsx(_s,{model:u})]}),de?r.jsx("div",{className:"model-selector__item-desc",children:de}):r.jsx(Ss,{model:u})]}),U&&r.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:r.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},p)})})})]});return zt.createPortal(g,document.body)};return r.jsxs("div",{className:`model-selector ${t||""} model-selector--variant-${w}`,children:[r.jsxs("button",{ref:X,className:`model-selector__trigger ${y?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:P,"aria-label":"选择模型","aria-expanded":y,children:[r.jsxs("div",{className:"model-selector__trigger-content",children:[r.jsx(Je,{modelId:(x==null?void 0:x.id)||b,profileId:(x==null?void 0:x.sourceProfileId)||null,className:"model-selector__trigger-health"}),r.jsx("span",{className:"model-selector__trigger-text",children:(x==null?void 0:x.shortLabel)||(x==null?void 0:x.label)||"选择模型"})]}),r.jsx(Nt,{size:16,className:`model-selector__trigger-icon ${y?"model-selector__trigger-icon--open":""}`})]}),le()]})});ft.displayName="ModelSelector";const mt=s.forwardRef(({selectedContent:t,onSend:e,disabled:o=!1,placeholder:d="输入消息..."},w)=>{const i=s.useRef(null),c=s.useRef(null),[l,M]=s.useState(""),I=t.length>0,{addHistory:S}=Gt();s.useImperativeHandle(w,()=>({setContent:k=>{var E;M(k),(E=i.current)==null||E.focus()},getContent:()=>l,focus:()=>{var k;return(k=i.current)==null?void 0:k.focus()}}),[l]);const b=s.useCallback(()=>{const k=l.trim();if(!k&&t.length===0)return;const E=[];k&&E.push({type:"text",text:k}),t.forEach((_,q)=>{_.type==="image"||_.type==="graphics"?E.push({type:"data-file",data:{filename:`${_.type}-${q+1}.png`,mediaType:"image/png",url:_.url||""}}):_.type==="video"&&E.push({type:"data-file",data:{filename:`video-${q+1}.mp4`,mediaType:"video/mp4",url:_.url||""}})});const H={id:`msg_${Date.now()}`,role:"user",parts:E};k&&S(k,I,"agent"),Promise.resolve(e(H)).catch(_=>{console.error("[EnhancedChatInput] send failed:",_)}),M("")},[l,t,e,S,I]),A=s.useCallback(k=>{k.nativeEvent.isComposing||k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),b())},[b]);s.useEffect(()=>{i.current&&(i.current.style.height="auto",i.current.style.height=`${Math.min(i.current.scrollHeight,120)}px`)},[l]);const y=()=>t.length===0?null:r.jsx("div",{className:"enhanced-chat-input__selection",children:r.jsx(ps,{items:t,language:"zh",enableHoverPreview:!0})}),z=(l.trim()||t.length>0)&&!o;return r.jsxs("div",{className:"enhanced-chat-input",ref:c,children:[y(),r.jsxs("div",{className:"enhanced-chat-input__form",children:[r.jsx("div",{className:"enhanced-chat-input__input-wrapper",children:r.jsx("textarea",{ref:i,className:"enhanced-chat-input__textarea",value:l,onChange:k=>M(k.target.value),onKeyDown:A,placeholder:I?"描述你想要的效果...":d,disabled:o,rows:4})}),r.jsx("button",{className:`enhanced-chat-input__send ${z?"enhanced-chat-input__send--active":""}`,onClick:b,disabled:!z,"aria-label":"发送",children:r.jsx(Kt,{size:20})})]})]})});mt.displayName="EnhancedChatInput";const Ie={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},he={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},_e=it.createInstance({name:he.DATABASE_NAME,storeName:he.SESSIONS_STORE}),pe=it.createInstance({name:he.DATABASE_NAME,storeName:he.MESSAGES_STORE});function pt(){return is()}function Is(t){const e=t.trim().replace(/\n/g," ");return e.length<=Ie.MAX_TITLE_LENGTH?e:e.slice(0,Ie.MAX_TITLE_LENGTH-3)+"..."}async function ys(){const t=Date.now(),e={id:pt(),title:"新对话",createdAt:t,updatedAt:t,messageCount:0};return await _e.setItem(e.id,e),e}async function Ee(t){return _e.getItem(t)}async function ks(){const t=[];return await _e.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,o)=>o.updatedAt-e.updatedAt)}async function Ue(t,e){const o=await Ee(t);if(o){const d={...o,...e,updatedAt:Date.now()};await _e.setItem(t,d)}}async function bs(t){const e=await gt(t);for(const o of e)await pe.removeItem(o.id);await _e.removeItem(t)}async function Es(t){await pe.setItem(t.id,t);const e=await Ee(t.sessionId);if(e){const o={messageCount:e.messageCount+1,updatedAt:Date.now()};await Ue(t.sessionId,o)}}async function gt(t){const e=[];return await pe.iterate(o=>{o.sessionId===t&&e.push(o)}),e.sort((o,d)=>o.timestamp-d.timestamp)}async function vs(t,e){const o=await pe.getItem(t);if(o){const d={...o,...e};await pe.setItem(t,d)}}async function Ts(t){const e=await pe.getItem(t);if(e){await pe.removeItem(t);const o=await Ee(e.sessionId);o&&await Ue(e.sessionId,{messageCount:Math.max(0,o.messageCount-1)})}}const Ze={isOpen:!1,width:Math.min(Ie.DRAWER_MAX_WIDTH,Math.max(Ie.DRAWER_MIN_WIDTH,window.innerWidth*Ie.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function ht(){try{const t=localStorage.getItem(he.DRAWER_STATE);if(t)return{...Ze,...JSON.parse(t)}}catch(t){console.error("[ChatStorage] Failed to get drawer state:",t)}return Ze}function Cs(t){try{const o={...ht(),...t};localStorage.setItem(he.DRAWER_STATE,JSON.stringify(o))}catch(e){console.error("[ChatStorage] Failed to set drawer state:",e)}}async function Ds(){await _e.clear(),await pe.clear(),localStorage.removeItem(he.DRAWER_STATE)}const T={createSession:ys,getSession:Ee,getAllSessions:ks,updateSession:Ue,deleteSession:bs,addMessage:Es,getMessages:gt,updateMessage:vs,deleteMessage:Ts,getDrawerState:ht,setDrawerState:Cs,clearAllData:Ds,generateId:pt,generateTitle:Is};var Z=(t=>(t.SENDING="sending",t.STREAMING="streaming",t.SUCCESS="success",t.FAILED="failed",t))(Z||{}),ne=(t=>(t.USER="user",t.ASSISTANT="assistant",t))(ne||{});let ce=null;function wt(t){const e={};let o=1,d=1,w=1,i=t;return i=i.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[图片${o}]`;return e[l]=c,o++,l}),i=i.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[视频${d}]`;return e[l]=c,d++,l}),i=i.replace(/blob:[^\s"'<>]+/g,c=>{const l=`[媒体${w}]`;return e[l]=c,w++,l}),i=i.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,c=>{const l=`[图片${o}]`;return e[l]=c,o++,l}),i=i.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,c=>{const l=`[视频${d}]`;return e[l]=c,d++,l}),{sanitized:i,urlMap:e}}function As(t,e){let o=t;for(const[d,w]of Object.entries(e))o=o.split(d).join(w);return o}async function Rs(t,e={}){const o={};let d=e.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(t.filter(i=>i.status==="success"||i.status==="streaming").map(async i=>{const{sanitized:c,urlMap:l}=wt(i.content);Object.assign(o,l);const M=[{type:"text",text:c}];if(e.includeImageAttachments&&i.role===ne.USER&&i.attachments&&i.attachments.length>0&&d>0){const I=await Ot(i.attachments,d);d-=I.length,M.push(...I)}return{role:i.role===ne.USER?"user":"assistant",content:M}})),urlMap:o}}async function Ns(t,e,o=[],d,w,i){return js(t,e,o,d,w,i)}async function js(t,e,o=[],d,w,i){ce&&ce.abort(),ce=new AbortController;const c=ce.signal,l=Date.now().toString(),M=Date.now(),I=(typeof w=="string"?w:w==null?void 0:w.modelId)||Qe.getConfig().modelName||"unknown";try{Y.trackModelCall({taskId:l,taskType:"chat",model:I,promptLength:e.length,hasUploadedImage:o.length>0,startTime:M});const S=cs("text",w),b=ls(S==null?void 0:S.binding),A=ds(S==null?void 0:S.binding),y=Vt(o),z=Math.max(A-y,0),{geminiMessages:k,urlMap:E}=await Rs(t,{includeImageAttachments:b,maxImageCount:z}),{sanitized:H,urlMap:_}=wt(e),q={...E,..._},X=Bt(k),V=Math.max(A-X,0),j=[{type:"text",text:H}];if(b&&o.length>0&&V>0){const W=await Xt(o,V);j.push(...W)}const x=[];i&&x.push({role:"system",content:[{type:"text",text:i}]}),x.push(...k,{role:"user",content:j});let C="";if(await Qe.sendChat(x,W=>{if(c.aborted)return;const ae=As(W,q);C=ae,d({type:"content",content:ae})},c,w||void 0),c.aborted)throw new Error("Request cancelled");const P=Date.now()-M;return Y.trackModelSuccess({taskId:l,taskType:"chat",model:I,duration:P,resultSize:C.length}),d({type:"done"}),ce=null,C}catch(S){ce=null;const b=Date.now()-M;if(c.aborted||S.message==="Request cancelled"||S.name==="AbortError")throw Y.trackTaskCancellation({taskId:l,taskType:"chat",duration:b}),d({type:"done"}),new Error("Request cancelled");const A=S instanceof Error?S.message:"Unknown error occurred";throw Y.trackModelFailure({taskId:l,taskType:"chat",model:I,duration:b,error:A}),d({type:"error",error:A}),S}}function Ls(){ce&&(ce.abort(),ce=null)}function Ws(){return ce!==null}const et={sendChatMessage:Ns,stopGeneration:Ls,isGenerating:Ws},Pe="[[WORKFLOW_MESSAGE]]",$s=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function Ps(t){if(!$s.includes(t.name)||!qt(t.name))return t;const e=$e.get(),o=Jt(t.name,{...t.arguments},{fallbackModels:{image:e.imageModelName||ms(),video:e.videoModelName||fs(),audio:e.audioModelName||us()}});return{...t,arguments:o}}function Us(t){const e=[];t.aiAnalysis&&e.push(t.aiAnalysis);const o=t.steps.filter(c=>c.status==="completed"),d=t.steps.filter(c=>c.status==="failed");if(o.length>0||d.length>0){const c=[];o.length>0&&c.push(`成功执行 ${o.length} 个工具`),d.length>0&&c.push(`${d.length} 个工具执行失败`),c.length>0&&e.push(`[执行结果: ${c.join(",")}]`)}const w=t.steps.map(c=>{const l={};for(const[M,I]of Object.entries(c.args||{}))M!=="context"&&(typeof I=="string"&&I.length>200?l[M]=I.substring(0,200)+"...":l[M]=I);return{mcp:c.mcp,args:l}}),i={content:e.join(`
3
- `)||`已完成任务: ${t.name}`,next:w};return JSON.stringify(i)}function zs(t){const e=[{type:"text",text:t.content}];if(t.attachments&&t.attachments.length>0)for(const o of t.attachments)e.push({type:"data-file",data:{filename:o.name,mediaType:o.type,url:o.data}});return{id:t.id,role:t.role===ne.USER?"user":"assistant",parts:e}}function Hs(t,e){const d=t.parts.filter(c=>c.type==="text").map(c=>c.text).join(""),i=t.parts.filter(c=>c.type==="data-file").map((c,l)=>{const M=c.data;return{id:`${t.id}-att-${l}`,name:M.filename,type:M.mediaType,size:0,data:M.url,isBlob:!1}});return{id:t.id,sessionId:e,role:t.role==="user"?ne.USER:ne.ASSISTANT,content:d,timestamp:Date.now(),status:Z.SUCCESS,attachments:i.length>0?i:void 0}}function Fs(t){return t.workflow&&t.content.startsWith(Pe)?{...t,content:Us(t.workflow)}:t}function tt(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join("")}gs();function Gs(t){const{sessionId:e,temporaryModel:o,onToolCalls:d,onWorkflowUpdate:w}=t,i=s.useRef(Qt()),c=s.useRef(d);c.current=d;const l=s.useRef(w);l.current=w;const M=s.useRef(o);M.current=o;const[I,S]=s.useState([]),[b,A]=s.useState("ready"),[y,z]=s.useState(!1),k=s.useRef(null),E=s.useRef([]),H=s.useRef(!1);s.useEffect(()=>{if(!e){S([]),E.current=[];return}(async()=>{z(!0);try{const C=await T.getMessages(e);E.current=C,S(C.map(zs))}catch(C){console.error("[useChatHandler] Failed to load messages:",C),S([]),E.current=[]}finally{z(!1)}})()},[e]);const _=s.useCallback(async x=>{if(!e)return;if(H.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}H.current=!0,A("submitted");const C=Hs(x,e);await T.addMessage(C),S($=>[...$,x]);const P=await T.getSession(e);await T.updateSession(e,{updatedAt:Date.now(),messageCount:((P==null?void 0:P.messageCount)||0)+1});const W=T.generateId();k.current=W;const ae={id:W,role:"assistant",parts:[{type:"text",text:""}]};S($=>[...$,ae]),A("streaming");const ie=E.current.map(Fs);ie.push(C),E.current=[...E.current,C];const O=tt(x);let ee="",le=!1;try{await et.sendChatMessage(ie.slice(0,-1),O,C.attachments||[],$=>{if($.type==="content"&&$.content)ee=$.content,S(g=>g.map(u=>u.id===W?{...u,parts:[{type:"text",text:ee}]}:u));else if($.type==="done"){const g=Yt(ee),u=Zt(ee)||ee;if(g.length>0&&c.current){const U=g.map(te=>Ps(te)),J=async()=>{const te=[];for(const ue of U)try{const fe=await es.executeTool(ue);te.push({toolCall:ue,success:fe.success,data:fe.data,error:fe.error,taskId:fe.taskId})}catch(fe){te.push({toolCall:ue,success:!1,error:fe.message||"工具执行失败"})}return te},de=`${Pe}${W}`;S(te=>te.map(ue=>ue.id===W?{...ue,parts:[{type:"text",text:de}]}:ue)),c.current(U,W,J,u)}A("ready");const p={id:W,sessionId:e,role:ne.ASSISTANT,content:g.length>0?`${Pe}${W}`:ee,timestamp:Date.now(),status:g.length>0?Z.STREAMING:Z.SUCCESS};T.addMessage(p),E.current=[...E.current,p],T.updateSession(e,{updatedAt:Date.now(),messageCount:((P==null?void 0:P.messageCount)||0)+2}),k.current=null,H.current=!1}else if($.type==="error"&&$.error){le=!0,A("error");const g=`❌ 错误: ${$.error}`;S(p=>p.map(U=>U.id===W?{...U,parts:[{type:"text",text:g}]}:U));const u={id:W,sessionId:e,role:ne.ASSISTANT,content:g,timestamp:Date.now(),status:Z.FAILED,error:$.error};T.addMessage(u),E.current=[...E.current,u],k.current=null,H.current=!1}},M.current,i.current)}catch($){if($.message!=="Request cancelled"&&!le){A("error"),console.error("[useChatHandler] Stream error:",$);const g=`❌ 错误: ${$.message||"未知错误"}`;if(S(u=>u.map(p=>p.id===W?{...p,parts:[{type:"text",text:g}]}:p)),e&&W){const u={id:W,sessionId:e,role:ne.ASSISTANT,content:g,timestamp:Date.now(),status:Z.FAILED,error:$.message||"未知错误"};T.addMessage(u),E.current=[...E.current,u]}}k.current=null,H.current=!1}},[e]),q=s.useCallback(async()=>{if(et.stopGeneration(),A("ready"),k.current&&e){const x=I.find(C=>C.id===k.current);if(x){const C=tt(x),P={id:x.id,sessionId:e,role:ne.ASSISTANT,content:C,timestamp:Date.now(),status:Z.SUCCESS};await T.addMessage(P)}k.current=null}},[e,I]),X=s.useCallback(x=>{if(I.length<2)return;const C=[...I].reverse().findIndex(ie=>ie.role==="user");if(C===-1)return;const P=I.length-1-C,W=I[P],ae=I.slice(0,P+1);S(ae),_(W)},[I,_]),V=s.useCallback((x,C)=>{S(x),C&&(E.current=C)},[]),j=s.useCallback((x,C)=>{E.current=E.current.map(P=>P.id===x?{...P,workflow:C}:P)},[]);return{messages:I,status:b,sendMessage:_,stop:q,regenerate:X,setMessages:S,setMessagesWithRaw:V,updateRawMessageWorkflow:j,isLoading:y}}const Ks=oe.lazy(()=>rt(()=>import("./ChatMessagesArea-3ZzACUMv.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),st="[[WORKFLOW_MESSAGE]]";function Vs(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 nt="chat-drawer-width",Bs=Math.max(375,window.innerWidth*.5),at=375,Xs=s.forwardRef(({defaultOpen:t=!1,onOpenChange:e},o)=>{const[d,w]=s.useState(()=>T.getDrawerState().isOpen??t),[i,c]=s.useState([]),[l,M]=s.useState(null),[I,S]=s.useState(!1),[b,A]=s.useState(()=>{const a=localStorage.getItem(nt);if(a){const n=parseInt(a,10);if(!isNaN(n)&&n>=at)return Math.min(n,window.innerWidth-60)}return Bs}),[y,z]=s.useState(!1),k=s.useRef(null),[E,H]=s.useState(()=>Ye("text").modelId),[_,q]=s.useState(()=>{const a=Ye("text");return Me(a.profileId,a.modelId)}),[X,V]=s.useState(new Map),j=s.useRef(null),[x,C]=s.useState(null),{executeRetry:P,selectedContent:W,setIsDrawerOpen:ae,setDrawerWidth:ie}=ws();s.useEffect(()=>{ae(d)},[d,ae]),s.useEffect(()=>{ie(b)},[b,ie]);const O=oe.useRef(null),ee=oe.useRef(null),{appState:le,setAppState:$}=ts();s.useEffect(()=>{if(!y)return;const a=m=>{const f=window.innerWidth-m.clientX,h=Math.max(at,Math.min(f,window.innerWidth-60));A(h)},n=()=>{z(!1),localStorage.setItem(nt,String(b))};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",n),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",n),document.body.style.userSelect="",document.body.style.cursor=""}},[y,b]),s.useEffect(()=>{const a=()=>{const n=window.innerWidth-60;b>n&&A(n)};return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[b]);const g=s.useCallback(a=>{a.preventDefault(),z(!0)},[]),u=s.useCallback(async(a,n,m,f)=>{var L,v;const R={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(L=a[0])!=null&&L.name.includes("video")?"video":(v=a[0])!=null&&v.name.includes("audio")?"audio":"image",prompt:f||"",aiAnalysis:f,count:a.length,steps:a.map((D,K)=>({id:`step-${K}`,mcp:D.name,status:"pending",description:Vs(D.name,D.arguments),args:D.arguments}))};V(D=>{const K=new Map(D);return K.set(n,R),K}),j.current=n,T.updateMessage(n,{workflow:R});try{const D=await m();Y.track("chat_tool_execution_complete",{success:!0,resultCount:D.length}),Y.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:a.length,resultCount:D.length}),V(K=>{const N=new Map(K),F=N.get(n);if(F){const B={...F,steps:F.steps.map((me,xe)=>{const Q=D[xe];return{...me,status:Q!=null&&Q.success?"completed":"failed",error:Q==null?void 0:Q.error,result:Q==null?void 0:Q.data}})};N.set(n,B),T.updateMessage(n,{workflow:B,status:Z.SUCCESS})}return N})}catch(D){console.error("[ChatDrawer] Tool execution failed:",D),V(K=>{const N=new Map(K),F=N.get(n);if(F){const B={...F,steps:F.steps.map(me=>({...me,status:"failed",error:D.message||"执行失败"}))};N.set(n,B),T.updateMessage(n,{workflow:B,status:Z.FAILED})}return N})}},[]),p=Gs({sessionId:l,temporaryModel:_||E,onToolCalls:u}),U=s.useRef(p.sendMessage);U.current=p.sendMessage,s.useEffect(()=>{(async()=>{const n=T.getDrawerState(),m=await T.getAllSessions();c(m);let f=null;if(n.activeSessionId?(f=n.activeSessionId,M(n.activeSessionId)):m.length>0&&(f=m[0].id,M(m[0].id)),f)try{const h=await T.getMessages(f),R=new Map;for(const v of h)v.workflow&&R.set(v.id,v.workflow);V(R);const L=h.find(v=>v.workflow&&v.status===Z.STREAMING);j.current=(L==null?void 0:L.id)||null}catch(h){console.error("[ChatDrawer] Failed to load workflow messages:",h)}})()},[]),s.useEffect(()=>{T.setDrawerState({isOpen:d,activeSessionId:l})},[d,l]),s.useEffect(()=>{if(l&&re.current){const a=re.current;re.current=null,setTimeout(()=>{U.current(a)},100)}},[l]),s.useEffect(()=>{if(!le.openSettings&&re.current){const a=$e.get();if(a!=null&&a.apiKey){const n=re.current;re.current=null,l?setTimeout(()=>{U.current(n)},100):(async()=>{const m=await T.createSession();c(f=>[m,...f]),M(m.id),re.current=n})()}}},[le.openSettings,l]),s.useEffect(()=>{const a=n=>{n.key==="Escape"&&d&&(w(!1),e==null||e(!1))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[d,e]),s.useEffect(()=>{let a=null;return(async()=>{const{workflowSubmissionService:m}=await rt(async()=>{const{workflowSubmissionService:f}=await import("./workflow-submission-service-XOcxTwb1.js").then(h=>h.a);return{workflowSubmissionService:f}},__vite__mapDeps([0,2]),import.meta.url);a=m.subscribeToAllEvents(f=>{const h=f;V(R=>{let L=null;for(const[N,F]of R.entries())if(F.id===h.workflowId){L=N;break}if(!L)return R;const v=R.get(L);if(!v)return R;const D=new Map(R);let K;switch(h.type){case"step":{K={...v,steps:v.steps.map(N=>N.id===h.stepId?{...N,status:h.status||N.status,result:h.result??N.result,error:h.error??N.error}:N)};break}case"steps_added":{const F=(h.steps||[]).map(B=>({id:B.id,mcp:B.mcp,args:B.args,description:B.description,status:B.status}));K={...v,steps:[...v.steps,...F]};break}case"completed":case"failed":{const N=h.type==="completed"?"completed":"failed";K={...v,status:N,steps:v.steps.map(F=>{if(F.status==="running"||F.status==="pending"){const B=F.result;return B!=null&&B.taskId?F:{...F,status:N,error:h.type==="failed"?h.error:void 0}}return F})};break}default:return R}return D.set(L,K),T.updateMessage(L,{workflow:K}),D})})})().catch(m=>{console.error("[ChatDrawer] Failed to setup workflow sync:",m)}),()=>{a==null||a.unsubscribe()}},[]),s.useEffect(()=>{if(!I)return;const a=m=>{const f=m.target;f.closest(".t-dialog")===null&&O.current&&!O.current.contains(f)&&ee.current&&!ee.current.contains(f)&&S(!1)},n=setTimeout(()=>{document.addEventListener("mousedown",a)},100);return()=>{clearTimeout(n),document.removeEventListener("mousedown",a)}},[I]);const J=s.useCallback(()=>{w(a=>{const n=!a;return e==null||e(n),n})},[e]),de=s.useCallback(()=>{w(!1),e==null||e(!1)},[e]),te=s.useCallback(async()=>{Y.track("chat_session_create");const a=await T.createSession();c(n=>[a,...n]),M(a.id),S(!1),V(new Map),j.current=null,H(void 0)},[]),ue=s.useCallback(()=>{S(a=>!a)},[]),fe=s.useCallback(async a=>{Y.track("chat_session_select"),M(a),S(!1),H(void 0);try{const n=await T.getMessages(a),m=new Map;for(const h of n)h.workflow&&m.set(h.id,h.workflow);V(m);const f=n.find(h=>h.workflow&&h.status===Z.STREAMING);j.current=(f==null?void 0:f.id)||null}catch(n){console.error("[ChatDrawer] Failed to load workflow messages:",n),V(new Map),j.current=null}},[]),_t=s.useCallback(async a=>{Y.track("chat_session_delete"),await T.deleteSession(a),c(n=>{const m=n.filter(f=>f.id!==a);if(l===a){const f=m[0]||null;M((f==null?void 0:f.id)||null)}return m})},[l]),ve=s.useCallback(async(a,n)=>{Y.track("chat_session_rename"),await T.updateSession(a,{title:n}),c(m=>m.map(f=>f.id===a?{...f,title:n}:f))},[]),re=oe.useRef(null),Se=s.useCallback(async a=>{try{Y.track("chat_message_send",{hasImages:a.parts.some(m=>m.type==="image_url")}),Y.track("ai_modality_used",{modality:"agent",action:"message_send",source:"chat_drawer",hasImages:a.parts.some(m=>m.type==="image_url"),partCount:a.parts.length,textLength:a.parts.filter(m=>m.type==="text").reduce((m,f)=>m+String(f.text||"").length,0)});const n=$e.get();if(!(n!=null&&n.apiKey)){re.current=a,$({...le,openSettings:!0});return}if(re.current=null,!l){const m=await T.createSession();c(f=>[m,...f]),M(m.id),re.current=a;return}await p.sendMessage(a)}catch(n){console.error("[ChatDrawer] send message failed:",n),re.current=a}},[l,p,le,$]),ze=s.useCallback(async a=>{var Oe;const{context:n,workflow:m,textModel:f,autoOpen:h=!0}=a;h&&(w(!0),e==null||e(!0)),f&&H(f);const R=await T.createSession(),L=[];n.userInstruction&&L.push(n.userInstruction),n.selection.texts.length>0&&L.push(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./diagram-engines-CGOhfK6V.css","./editor-engines-B8u8agiX.css","./tool-windows-CqSDeXz5.css","./main-CRPCRx46.css","./index-DmlAaIoR.css","./MediaLibrarySidebar-CNCXXhfY.css","./ChatMessagesArea-PlF5AwzD.css"])))=>i.map(i=>d[i]);
2
+ import{_ as rt}from"./startup-runtime-BbuNXj6O.js";import{R as oe,r as s,j as r,dR as vt,dU as Et,dn as ot,H as ke,gU as Tt,dA as Ct,e5 as Dt,dF as Oe,dH as At,ht as Rt,iP as Je,eA as Nt,bm as jt,c3 as Lt,d_ as Wt,iQ as $t,iR as Pt,iS as Ut,b6 as zt,hJ as Ht,hI as Ft,dz as Gt,iT as Kt,ae as it,cR as Ye,cN as Q,iU as Vt,iV as Bt,iW as Xt,iX as qt,cS as Ot,cT as Jt,bU as Yt,f6 as Qt,d0 as Zt,iY as es}from"./diagram-engines-DmAewdsu.js";import{bN as ts,cn as ss,dp as ns,dq as as,cv as rs}from"./tool-windows-DV-j2p51.js";import{b9 as os,F as Ie,aa as ct,H as is,c as cs,as as ls,at as ds,g as $e,av as us,aw as ms,N as fs,r as Qe}from"./shared-runtime-DBavnB0U.js";import{S as ps,i as gs,u as hs}from"./index-DDzCo7oj.js";import{c as ws}from"./main-B2ZrUywM.js";const lt=oe.memo(({session:t,isActive:e,onSelect:o,onDelete:d,onRename:w})=>{const[i,c]=s.useState(!1),[l,I]=s.useState(t.title),M=s.useRef(null),S=s.useCallback(()=>{i||o()},[o,i]),b=s.useCallback(_=>{_.stopPropagation(),d()},[d]),A=s.useCallback(_=>{_.stopPropagation(),I(t.title),c(!0)},[t.title]),y=s.useCallback(()=>{const _=l.trim();_&&_!==t.title&&w(_),c(!1)},[l,t.title,w]),z=s.useCallback(()=>{I(t.title),c(!1)},[t.title]),k=s.useCallback(_=>{_.key==="Enter"?(_.preventDefault(),y()):_.key==="Escape"&&(_.preventDefault(),z())},[y,z]),v=s.useCallback(_=>{I(_.target.value)},[]);s.useEffect(()=>{i&&M.current&&(M.current.focus(),M.current.select())},[i]);const H=s.useMemo(()=>{const _=new Date(t.updatedAt),O=new Date;return _.toDateString()===O.toDateString()?_.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):_.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})},[t.updatedAt]);return r.jsxs("div",{className:`session-item ${e?"session-item--active":""} ${i?"session-item--editing":""}`,"data-track":"chat_click_session_select",onClick:S,role:"button",tabIndex:0,onKeyDown:_=>!i&&_.key==="Enter"&&S(),children:[r.jsxs("div",{className:"session-item__content",children:[i?r.jsx("input",{ref:M,className:"session-item__title-input",value:l,onChange:v,onKeyDown:k,onBlur:y,onClick:_=>_.stopPropagation(),maxLength:50}):r.jsx("div",{className:"session-item__title",children:t.title}),r.jsx("div",{className:"session-item__time",children:H})]}),!i&&r.jsxs("div",{className:"session-item__actions",children:[r.jsx("button",{className:"session-item__edit","data-track":"chat_click_session_edit",onClick:A,"aria-label":`编辑会话标题: ${t.title}`,children:r.jsx(vt,{size:14})}),r.jsx("button",{className:"session-item__delete","data-track":"chat_click_session_delete",onClick:b,"aria-label":`删除会话: ${t.title}`,children:r.jsx(Et,{size:14})})]})]})});lt.displayName="SessionItem";const dt=oe.memo(({sessions:t,activeSessionId:e,onSelectSession:o,onNewSession:d,onDeleteSession:w,onRenameSession:i})=>{const[c,l]=oe.useState(null),I=s.useCallback(y=>{o(y)},[o]),M=s.useCallback(y=>{l(y)},[]),S=s.useCallback(()=>{c&&(w(c),l(null))},[c,w]),b=s.useCallback(()=>{l(null)},[]),A=s.useCallback((y,z)=>{i(y,z)},[i]);return r.jsxs("div",{className:"session-list",children:[r.jsxs("div",{className:"session-list__header",children:[r.jsx("span",{className:"session-list__title",children:"会话列表"}),r.jsxs("button",{className:"session-list__new-btn","data-track":"chat_click_session_new",onClick:d,"aria-label":"新建会话",children:[r.jsx(ot,{size:14}),r.jsx("span",{children:"新建"})]})]}),r.jsx("div",{className:"session-list__items",children:t.length===0?r.jsx("div",{className:"session-list__empty",children:"暂无会话"}):t.map(y=>r.jsx(lt,{session:y,isActive:y.id===e,onSelect:()=>I(y.id),onDelete:()=>M(y.id),onRename:z=>A(y.id,z)},y.id))}),r.jsx(ts,{open:c!==null,title:"删除会话",description:"确定删除此会话吗?删除后无法恢复。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:y=>{y||b()},onConfirm:S})]})});dt.displayName="SessionList";const ut=oe.memo(({isOpen:t,onClick:e,drawerWidth:o})=>{const d={right:t&&o?`calc(var(--aitu-toolbar-right-dock-width, 0px) + ${o-18}px)`:"var(--aitu-toolbar-right-dock-width, 0px)"};return r.jsx(ke,{content:t?"收起对话":"展开对话",children:r.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:r.jsx(Tt,{size:16,className:"chat-drawer-trigger__icon"})})})});ut.displayName="ChatDrawerTrigger";function be(t){return t.sourceProfileName||ct[t.vendor]||t.id}const _s=oe.memo(({model:t})=>{const e=Ht(t.sourceProfileId,t.id);return e?r.jsx("span",{className:"model-selector__item-price",children:e}):null}),Ss=oe.memo(({model:t})=>{const e=Ft(t.sourceProfileId,t.id);return e!=null&&e.description?r.jsx("div",{className:"model-selector__item-desc",children:e.description}):null});function xs(t,e){var i;const o=be(t),d=(i=t.description)==null?void 0:i.trim(),w=(e==null?void 0:e.includeProvider)??!0;return d?!w||d.includes(o)?d:`${o} · ${d}`:w?o:""}function Is(t){return be(t).trim().slice(0,1).toUpperCase()||"M"}const mt=oe.memo(({className:t,value:e,valueRef:o,onChange:d,variant:w="capsule"})=>{var $;const i=Ct("text"),c=(($=i[0])==null?void 0:$.id)||os,[l,I]=s.useState(c),[M,S]=s.useState(()=>Ie(null,c)),b=e??l,A=o===void 0?M:o,[y,z]=s.useState(!1),[k,v]=s.useState(""),[H,_]=s.useState(null),O=s.useRef(null),X=s.useRef(null);s.useEffect(()=>{!e&&c&&l!==c&&(I(c),S(Ie(null,c)))},[c,l,e]),s.useEffect(()=>{if(!y)return;const g=p=>{const U=p.target;O.current&&!O.current.contains(U)&&X.current&&!X.current.contains(U)&&(z(!1),v(""))},u=setTimeout(()=>{document.addEventListener("mousedown",g)},100);return()=>{clearTimeout(u),document.removeEventListener("mousedown",g)}},[y]);const V=s.useMemo(()=>b?Dt(b,A):null,[b,A]),j=s.useMemo(()=>{if(Oe(i,b,A)||!b)return i;const u=At("text",b,A);return u?[u,...i]:i},[i,b,A]),x=s.useMemo(()=>Oe(j,b,A)||j.find(g=>g.id===b),[j,b,A]),C=s.useCallback(g=>{const u=Ie(g.sourceProfileId||null,g.id);e===void 0&&I(g.id),o===void 0&&S(u),d==null||d(g.id,u),z(!1),v("")},[e,o,d]),P=s.useCallback(()=>{const g=!y;z(g),g?_((x==null?void 0:x.vendor)||null):v("")},[x==null?void 0:x.vendor,y]),W=s.useMemo(()=>{const g=new Map,u=[];return j.forEach(p=>{g.has(p.vendor)||(u.push(p.vendor),g.set(p.vendor,0)),g.set(p.vendor,(g.get(p.vendor)??0)+1)}),u.map(p=>({id:p,label:ct[p],count:g.get(p)??0,icon:r.jsx(Rt,{vendor:p,size:14})}))},[j]),ae=s.useCallback(g=>{_(g)},[]),ie=s.useMemo(()=>{const g=k.toLowerCase().trim();return g?j.filter(u=>{var U,J;const p=be(u).toLowerCase();return u.id.toLowerCase().includes(g)||u.label.toLowerCase().includes(g)||((U=u.shortLabel)==null?void 0:U.toLowerCase().includes(g))||((J=u.description)==null?void 0:J.toLowerCase().includes(g))||p.includes(g)}):H?j.filter(u=>u.vendor===H):j},[k,H,j]),[q,ee]=s.useState({top:0,left:0,width:0,bottom:0,placement:"bottom",maxHeight:480});s.useLayoutEffect(()=>{if(!y)return;const g=()=>{if(!X.current)return;const u=X.current.getBoundingClientRect(),p=window.innerHeight,U=p-u.bottom,J=u.top,de=U<400&&J>U?"top":"bottom",te=de==="top"?J-16:p-u.bottom-16;ee({top:u.top,left:u.left,width:u.width,bottom:u.bottom,placement:de,maxHeight:Math.min(Math.max(te,200),600)})};return g(),window.addEventListener("resize",g),window.addEventListener("scroll",g,!0),()=>{window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0)}},[y]);const le=()=>{if(!y)return null;const g=r.jsxs("div",{ref:O,className:"model-selector__dropdown",style:{position:"fixed",zIndex:jt.DROPDOWN_PORTAL,left:q.left,top:q.placement==="bottom"?q.bottom+8:"auto",bottom:q.placement==="top"?window.innerHeight-q.top+8:"auto",minWidth:360,width:w==="form"?q.width:"auto",maxHeight:q.maxHeight,visibility:q.width===0?"hidden":"visible",transformOrigin:q.placement==="bottom"?"top left":"bottom left",display:"flex",flexDirection:"column"},onClick:u=>u.stopPropagation(),children:[r.jsx("div",{className:"model-selector__search",children:r.jsx(Lt,{value:k,onChange:v,placeholder:"搜索模型...",prefixIcon:r.jsx(Wt,{}),clearable:!0,autofocus:!0})}),r.jsx($t,{tabs:W,activeTab:H,onTabChange:ae,searchQuery:k,compact:!0,children:r.jsx("div",{className:"model-selector__list",children:ie.length===0?r.jsx("div",{className:"model-selector__empty",children:"未找到匹配的模型"}):ie.map(u=>{const p=Pt(u),U=p===V,J=!!k.trim(),de=xs(u,{includeProvider:!J});return r.jsxs("button",{className:`model-selector__item ${U?"model-selector__item--active":""}`,"data-track":"chat_click_model_select",onClick:()=>C(u),children:[r.jsx("span",{className:"model-selector__item-icon model-selector__item-icon--text","aria-hidden":"true",children:Is(u)}),r.jsxs("div",{className:"model-selector__item-content",children:[r.jsxs("div",{className:"model-selector__item-header",children:[r.jsx("span",{className:"model-selector__item-name",children:u.shortLabel||u.label}),J?r.jsx("span",{className:"model-selector__item-provider",children:be(u)}):null,r.jsx(Je,{modelId:u.id,profileId:u.sourceProfileId||null}),r.jsx(Ut,{modelId:u.id}),r.jsx(_s,{model:u})]}),de?r.jsx("div",{className:"model-selector__item-desc",children:de}):r.jsx(Ss,{model:u})]}),U&&r.jsx("svg",{className:"model-selector__check",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:r.jsx("path",{d:"M13.3334 4L6.00002 11.3333L2.66669 8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]},p)})})})]});return zt.createPortal(g,document.body)};return r.jsxs("div",{className:`model-selector ${t||""} model-selector--variant-${w}`,children:[r.jsxs("button",{ref:X,className:`model-selector__trigger ${y?"model-selector__trigger--active":""}`,"data-track":"chat_click_model_selector",onClick:P,"aria-label":"选择模型","aria-expanded":y,children:[r.jsxs("div",{className:"model-selector__trigger-content",children:[r.jsx(Je,{modelId:(x==null?void 0:x.id)||b,profileId:(x==null?void 0:x.sourceProfileId)||null,className:"model-selector__trigger-health"}),r.jsx("span",{className:"model-selector__trigger-text",children:(x==null?void 0:x.shortLabel)||(x==null?void 0:x.label)||"选择模型"})]}),r.jsx(Nt,{size:16,className:`model-selector__trigger-icon ${y?"model-selector__trigger-icon--open":""}`})]}),le()]})});mt.displayName="ModelSelector";const ft=s.forwardRef(({selectedContent:t,onSend:e,disabled:o=!1,placeholder:d="输入消息..."},w)=>{const i=s.useRef(null),c=s.useRef(null),[l,I]=s.useState(""),M=t.length>0,{addHistory:S}=Gt();s.useImperativeHandle(w,()=>({setContent:k=>{var v;I(k),(v=i.current)==null||v.focus()},getContent:()=>l,focus:()=>{var k;return(k=i.current)==null?void 0:k.focus()}}),[l]);const b=s.useCallback(()=>{const k=l.trim();if(!k&&t.length===0)return;const v=[];k&&v.push({type:"text",text:k}),t.forEach((_,O)=>{_.type==="image"||_.type==="graphics"?v.push({type:"data-file",data:{filename:`${_.type}-${O+1}.png`,mediaType:"image/png",url:_.url||""}}):_.type==="video"&&v.push({type:"data-file",data:{filename:`video-${O+1}.mp4`,mediaType:"video/mp4",url:_.url||""}})});const H={id:`msg_${Date.now()}`,role:"user",parts:v};k&&S(k,M,"agent"),Promise.resolve(e(H)).catch(_=>{console.error("[EnhancedChatInput] send failed:",_)}),I("")},[l,t,e,S,M]),A=s.useCallback(k=>{k.nativeEvent.isComposing||k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),b())},[b]);s.useEffect(()=>{i.current&&(i.current.style.height="auto",i.current.style.height=`${Math.min(i.current.scrollHeight,120)}px`)},[l]);const y=()=>t.length===0?null:r.jsx("div",{className:"enhanced-chat-input__selection",children:r.jsx(ps,{items:t,language:"zh",enableHoverPreview:!0})}),z=(l.trim()||t.length>0)&&!o;return r.jsxs("div",{className:"enhanced-chat-input",ref:c,children:[y(),r.jsxs("div",{className:"enhanced-chat-input__form",children:[r.jsx("div",{className:"enhanced-chat-input__input-wrapper",children:r.jsx("textarea",{ref:i,className:"enhanced-chat-input__textarea",value:l,onChange:k=>I(k.target.value),onKeyDown:A,placeholder:M?"描述你想要的效果...":d,disabled:o,rows:4})}),r.jsx("button",{className:`enhanced-chat-input__send ${z?"enhanced-chat-input__send--active":""}`,onClick:b,disabled:!z,"aria-label":"发送",children:r.jsx(Kt,{size:20})})]})]})});ft.displayName="EnhancedChatInput";const Me={MAX_TITLE_LENGTH:30,DRAWER_MIN_WIDTH:320,DRAWER_MAX_WIDTH:500,DRAWER_DEFAULT_WIDTH_RATIO:.3},he={DRAWER_STATE:"aitu:chat:drawer-state",ACTIVE_SESSION:"aitu:chat:active-session",DATABASE_NAME:"aitu-chat",SESSIONS_STORE:"sessions",MESSAGES_STORE:"messages"},_e=it.createInstance({name:he.DATABASE_NAME,storeName:he.SESSIONS_STORE}),pe=it.createInstance({name:he.DATABASE_NAME,storeName:he.MESSAGES_STORE});function pt(){return is()}function Ms(t){const e=t.trim().replace(/\n/g," ");return e.length<=Me.MAX_TITLE_LENGTH?e:e.slice(0,Me.MAX_TITLE_LENGTH-3)+"..."}async function ys(){const t=Date.now(),e={id:pt(),title:"新对话",createdAt:t,updatedAt:t,messageCount:0};return await _e.setItem(e.id,e),e}async function ve(t){return _e.getItem(t)}async function ks(){const t=[];return await _e.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,o)=>o.updatedAt-e.updatedAt)}async function Ue(t,e){const o=await ve(t);if(o){const d={...o,...e,updatedAt:Date.now()};await _e.setItem(t,d)}}async function bs(t){const e=await gt(t);for(const o of e)await pe.removeItem(o.id);await _e.removeItem(t)}async function vs(t){await pe.setItem(t.id,t);const e=await ve(t.sessionId);if(e){const o={messageCount:e.messageCount+1,updatedAt:Date.now()};await Ue(t.sessionId,o)}}async function gt(t){const e=[];return await pe.iterate(o=>{o.sessionId===t&&e.push(o)}),e.sort((o,d)=>o.timestamp-d.timestamp)}async function Es(t,e){const o=await pe.getItem(t);if(o){const d={...o,...e};await pe.setItem(t,d)}}async function Ts(t){const e=await pe.getItem(t);if(e){await pe.removeItem(t);const o=await ve(e.sessionId);o&&await Ue(e.sessionId,{messageCount:Math.max(0,o.messageCount-1)})}}const Ze={isOpen:!1,width:Math.min(Me.DRAWER_MAX_WIDTH,Math.max(Me.DRAWER_MIN_WIDTH,window.innerWidth*Me.DRAWER_DEFAULT_WIDTH_RATIO)),activeSessionId:null};function ht(){try{const t=localStorage.getItem(he.DRAWER_STATE);if(t)return{...Ze,...JSON.parse(t)}}catch(t){console.error("[ChatStorage] Failed to get drawer state:",t)}return Ze}function Cs(t){try{const o={...ht(),...t};localStorage.setItem(he.DRAWER_STATE,JSON.stringify(o))}catch(e){console.error("[ChatStorage] Failed to set drawer state:",e)}}async function Ds(){await _e.clear(),await pe.clear(),localStorage.removeItem(he.DRAWER_STATE)}const T={createSession:ys,getSession:ve,getAllSessions:ks,updateSession:Ue,deleteSession:bs,addMessage:vs,getMessages:gt,updateMessage:Es,deleteMessage:Ts,getDrawerState:ht,setDrawerState:Cs,clearAllData:Ds,generateId:pt,generateTitle:Ms};var Z=(t=>(t.SENDING="sending",t.STREAMING="streaming",t.SUCCESS="success",t.FAILED="failed",t))(Z||{}),ne=(t=>(t.USER="user",t.ASSISTANT="assistant",t))(ne||{});let ce=null;function wt(t){const e={};let o=1,d=1,w=1,i=t;return i=i.replace(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[图片${o}]`;return e[l]=c,o++,l}),i=i.replace(/data:video\/[^;]+;base64,[A-Za-z0-9+/=]+/g,c=>{const l=`[视频${d}]`;return e[l]=c,d++,l}),i=i.replace(/blob:[^\s"'<>]+/g,c=>{const l=`[媒体${w}]`;return e[l]=c,w++,l}),i=i.replace(/https?:\/\/[^\s"'<>]+\.(png|jpg|jpeg|gif|webp|svg|bmp)(\?[^\s"'<>]*)?/gi,c=>{const l=`[图片${o}]`;return e[l]=c,o++,l}),i=i.replace(/https?:\/\/[^\s"'<>]+\.(mp4|webm|mov|avi|mkv)(\?[^\s"'<>]*)?/gi,c=>{const l=`[视频${d}]`;return e[l]=c,d++,l}),{sanitized:i,urlMap:e}}function As(t,e){let o=t;for(const[d,w]of Object.entries(e))o=o.split(d).join(w);return o}async function Rs(t,e={}){const o={};let d=e.maxImageCount??Number.POSITIVE_INFINITY;return{geminiMessages:await Promise.all(t.filter(i=>i.status==="success"||i.status==="streaming").map(async i=>{const{sanitized:c,urlMap:l}=wt(i.content);Object.assign(o,l);const I=[{type:"text",text:c}];if(e.includeImageAttachments&&i.role===ne.USER&&i.attachments&&i.attachments.length>0&&d>0){const M=await qt(i.attachments,d);d-=M.length,I.push(...M)}return{role:i.role===ne.USER?"user":"assistant",content:I}})),urlMap:o}}async function Ns(t,e,o=[],d,w,i){return js(t,e,o,d,w,i)}async function js(t,e,o=[],d,w,i){ce&&ce.abort(),ce=new AbortController;const c=ce.signal,l=Date.now().toString(),I=Date.now(),M=(typeof w=="string"?w:w==null?void 0:w.modelId)||Ye.getConfig().modelName||"unknown";try{Q.trackModelCall({taskId:l,taskType:"chat",model:M,promptLength:e.length,hasUploadedImage:o.length>0,startTime:I});const S=cs("text",w),b=ls(S==null?void 0:S.binding),A=ds(S==null?void 0:S.binding),y=Vt(o),z=Math.max(A-y,0),{geminiMessages:k,urlMap:v}=await Rs(t,{includeImageAttachments:b,maxImageCount:z}),{sanitized:H,urlMap:_}=wt(e),O={...v,..._},X=Bt(k),V=Math.max(A-X,0),j=[{type:"text",text:H}];if(b&&o.length>0&&V>0){const W=await Xt(o,V);j.push(...W)}const x=[];i&&x.push({role:"system",content:[{type:"text",text:i}]}),x.push(...k,{role:"user",content:j});let C="";if(await Ye.sendChat(x,W=>{if(c.aborted)return;const ae=As(W,O);C=ae,d({type:"content",content:ae})},c,w||void 0),c.aborted)throw new Error("Request cancelled");const P=Date.now()-I;return Q.trackModelSuccess({taskId:l,taskType:"chat",model:M,duration:P,resultSize:C.length}),d({type:"done"}),ce=null,C}catch(S){ce=null;const b=Date.now()-I;if(c.aborted||S.message==="Request cancelled"||S.name==="AbortError")throw Q.trackTaskCancellation({taskId:l,taskType:"chat",duration:b}),d({type:"done"}),new Error("Request cancelled");const A=S instanceof Error?S.message:"Unknown error occurred";throw Q.trackModelFailure({taskId:l,taskType:"chat",model:M,duration:b,error:A}),d({type:"error",error:A}),S}}function Ls(){ce&&(ce.abort(),ce=null)}function Ws(){return ce!==null}const et={sendChatMessage:Ns,stopGeneration:Ls,isGenerating:Ws},Pe="[[WORKFLOW_MESSAGE]]",$s=["generate_image","generate_video","generate_long_video","generate_audio","generate_grid_image","generate_photo_wall","generate_inspiration_board","generate_ppt"];function Ps(t){if(!$s.includes(t.name)||!ss(t.name))return t;const e=$e.get(),o=ns(t.name,{...t.arguments},{fallbackModels:{image:e.imageModelName||fs(),video:e.videoModelName||ms(),audio:e.audioModelName||us()}});return{...t,arguments:o}}function Us(t){const e=[];t.aiAnalysis&&e.push(t.aiAnalysis);const o=t.steps.filter(c=>c.status==="completed"),d=t.steps.filter(c=>c.status==="failed");if(o.length>0||d.length>0){const c=[];o.length>0&&c.push(`成功执行 ${o.length} 个工具`),d.length>0&&c.push(`${d.length} 个工具执行失败`),c.length>0&&e.push(`[执行结果: ${c.join(",")}]`)}const w=t.steps.map(c=>{const l={};for(const[I,M]of Object.entries(c.args||{}))I!=="context"&&(typeof M=="string"&&M.length>200?l[I]=M.substring(0,200)+"...":l[I]=M);return{mcp:c.mcp,args:l}}),i={content:e.join(`
3
+ `)||`已完成任务: ${t.name}`,next:w};return JSON.stringify(i)}function zs(t){const e=[{type:"text",text:t.content}];if(t.attachments&&t.attachments.length>0)for(const o of t.attachments)e.push({type:"data-file",data:{filename:o.name,mediaType:o.type,url:o.data}});return{id:t.id,role:t.role===ne.USER?"user":"assistant",parts:e}}function Hs(t,e){const d=t.parts.filter(c=>c.type==="text").map(c=>c.text).join(""),i=t.parts.filter(c=>c.type==="data-file").map((c,l)=>{const I=c.data;return{id:`${t.id}-att-${l}`,name:I.filename,type:I.mediaType,size:0,data:I.url,isBlob:!1}});return{id:t.id,sessionId:e,role:t.role==="user"?ne.USER:ne.ASSISTANT,content:d,timestamp:Date.now(),status:Z.SUCCESS,attachments:i.length>0?i:void 0}}function Fs(t){return t.workflow&&t.content.startsWith(Pe)?{...t,content:Us(t.workflow)}:t}function tt(t){return t.parts.filter(e=>e.type==="text").map(e=>e.text).join("")}gs();function Gs(t){const{sessionId:e,temporaryModel:o,onToolCalls:d,onWorkflowUpdate:w}=t,i=s.useRef(as()),c=s.useRef(d);c.current=d;const l=s.useRef(w);l.current=w;const I=s.useRef(o);I.current=o;const[M,S]=s.useState([]),[b,A]=s.useState("ready"),[y,z]=s.useState(!1),k=s.useRef(null),v=s.useRef([]),H=s.useRef(!1);s.useEffect(()=>{if(!e){S([]),v.current=[];return}(async()=>{z(!0);try{const C=await T.getMessages(e);v.current=C,S(C.map(zs))}catch(C){console.error("[useChatHandler] Failed to load messages:",C),S([]),v.current=[]}finally{z(!1)}})()},[e]);const _=s.useCallback(async x=>{if(!e)return;if(H.current){console.warn("[useChatHandler] Message already being sent, ignoring duplicate call");return}H.current=!0,A("submitted");const C=Hs(x,e);await T.addMessage(C),S($=>[...$,x]);const P=await T.getSession(e);await T.updateSession(e,{updatedAt:Date.now(),messageCount:((P==null?void 0:P.messageCount)||0)+1});const W=T.generateId();k.current=W;const ae={id:W,role:"assistant",parts:[{type:"text",text:""}]};S($=>[...$,ae]),A("streaming");const ie=v.current.map(Fs);ie.push(C),v.current=[...v.current,C];const q=tt(x);let ee="",le=!1;try{await et.sendChatMessage(ie.slice(0,-1),q,C.attachments||[],$=>{if($.type==="content"&&$.content)ee=$.content,S(g=>g.map(u=>u.id===W?{...u,parts:[{type:"text",text:ee}]}:u));else if($.type==="done"){const g=Ot(ee),u=Jt(ee)||ee;if(g.length>0&&c.current){const U=g.map(te=>Ps(te)),J=async()=>{const te=[];for(const ue of U)try{const me=await rs.executeTool(ue);te.push({toolCall:ue,success:me.success,data:me.data,error:me.error,taskId:me.taskId})}catch(me){te.push({toolCall:ue,success:!1,error:me.message||"工具执行失败"})}return te},de=`${Pe}${W}`;S(te=>te.map(ue=>ue.id===W?{...ue,parts:[{type:"text",text:de}]}:ue)),c.current(U,W,J,u)}A("ready");const p={id:W,sessionId:e,role:ne.ASSISTANT,content:g.length>0?`${Pe}${W}`:ee,timestamp:Date.now(),status:g.length>0?Z.STREAMING:Z.SUCCESS};T.addMessage(p),v.current=[...v.current,p],T.updateSession(e,{updatedAt:Date.now(),messageCount:((P==null?void 0:P.messageCount)||0)+2}),k.current=null,H.current=!1}else if($.type==="error"&&$.error){le=!0,A("error");const g=`❌ 错误: ${$.error}`;S(p=>p.map(U=>U.id===W?{...U,parts:[{type:"text",text:g}]}:U));const u={id:W,sessionId:e,role:ne.ASSISTANT,content:g,timestamp:Date.now(),status:Z.FAILED,error:$.error};T.addMessage(u),v.current=[...v.current,u],k.current=null,H.current=!1}},I.current,i.current)}catch($){if($.message!=="Request cancelled"&&!le){A("error"),console.error("[useChatHandler] Stream error:",$);const g=`❌ 错误: ${$.message||"未知错误"}`;if(S(u=>u.map(p=>p.id===W?{...p,parts:[{type:"text",text:g}]}:p)),e&&W){const u={id:W,sessionId:e,role:ne.ASSISTANT,content:g,timestamp:Date.now(),status:Z.FAILED,error:$.message||"未知错误"};T.addMessage(u),v.current=[...v.current,u]}}k.current=null,H.current=!1}},[e]),O=s.useCallback(async()=>{if(et.stopGeneration(),A("ready"),k.current&&e){const x=M.find(C=>C.id===k.current);if(x){const C=tt(x),P={id:x.id,sessionId:e,role:ne.ASSISTANT,content:C,timestamp:Date.now(),status:Z.SUCCESS};await T.addMessage(P)}k.current=null}},[e,M]),X=s.useCallback(x=>{if(M.length<2)return;const C=[...M].reverse().findIndex(ie=>ie.role==="user");if(C===-1)return;const P=M.length-1-C,W=M[P],ae=M.slice(0,P+1);S(ae),_(W)},[M,_]),V=s.useCallback((x,C)=>{S(x),C&&(v.current=C)},[]),j=s.useCallback((x,C)=>{v.current=v.current.map(P=>P.id===x?{...P,workflow:C}:P)},[]);return{messages:M,status:b,sendMessage:_,stop:O,regenerate:X,setMessages:S,setMessagesWithRaw:V,updateRawMessageWorkflow:j,isLoading:y}}const Ks=oe.lazy(()=>rt(()=>import("./ChatMessagesArea-DatNDD1n.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),st="[[WORKFLOW_MESSAGE]]";function Vs(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 nt="chat-drawer-width",Bs=Math.max(375,window.innerWidth*.5),at=375,Xs=s.forwardRef(({defaultOpen:t=!1,onOpenChange:e},o)=>{const[d,w]=s.useState(()=>T.getDrawerState().isOpen??t),[i,c]=s.useState([]),[l,I]=s.useState(null),[M,S]=s.useState(!1),[b,A]=s.useState(()=>{const a=localStorage.getItem(nt);if(a){const n=parseInt(a,10);if(!isNaN(n)&&n>=at)return Math.min(n,window.innerWidth-60)}return Bs}),[y,z]=s.useState(!1),k=s.useRef(null),[v,H]=s.useState(()=>Qe("text").modelId),[_,O]=s.useState(()=>{const a=Qe("text");return Ie(a.profileId,a.modelId)}),[X,V]=s.useState(new Map),j=s.useRef(null),[x,C]=s.useState(null),{executeRetry:P,selectedContent:W,setIsDrawerOpen:ae,setDrawerWidth:ie}=ws();s.useEffect(()=>{ae(d)},[d,ae]),s.useEffect(()=>{ie(b)},[b,ie]);const q=oe.useRef(null),ee=oe.useRef(null),{appState:le,setAppState:$}=Yt();s.useEffect(()=>{if(!y)return;const a=f=>{const m=window.innerWidth-f.clientX,h=Math.max(at,Math.min(m,window.innerWidth-60));A(h)},n=()=>{z(!1),localStorage.setItem(nt,String(b))};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",n),document.body.style.userSelect="none",document.body.style.cursor="ew-resize",()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",n),document.body.style.userSelect="",document.body.style.cursor=""}},[y,b]),s.useEffect(()=>{const a=()=>{const n=window.innerWidth-60;b>n&&A(n)};return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[b]);const g=s.useCallback(a=>{a.preventDefault(),z(!0)},[]),u=s.useCallback(async(a,n,f,m)=>{var L,E;const R={id:`workflow-${Date.now()}`,name:"AI 智能生成",generationType:(L=a[0])!=null&&L.name.includes("video")?"video":(E=a[0])!=null&&E.name.includes("audio")?"audio":"image",prompt:m||"",aiAnalysis:m,count:a.length,steps:a.map((D,K)=>({id:`step-${K}`,mcp:D.name,status:"pending",description:Vs(D.name,D.arguments),args:D.arguments}))};V(D=>{const K=new Map(D);return K.set(n,R),K}),j.current=n,T.updateMessage(n,{workflow:R});try{const D=await f();Q.track("chat_tool_execution_complete",{success:!0,resultCount:D.length}),Q.track("ai_modality_used",{modality:"agent",action:"tool_execution_completed",source:"chat_drawer",success:!0,toolCount:a.length,resultCount:D.length}),V(K=>{const N=new Map(K),F=N.get(n);if(F){const B={...F,steps:F.steps.map((fe,xe)=>{const Y=D[xe];return{...fe,status:Y!=null&&Y.success?"completed":"failed",error:Y==null?void 0:Y.error,result:Y==null?void 0:Y.data}})};N.set(n,B),T.updateMessage(n,{workflow:B,status:Z.SUCCESS})}return N})}catch(D){console.error("[ChatDrawer] Tool execution failed:",D),V(K=>{const N=new Map(K),F=N.get(n);if(F){const B={...F,steps:F.steps.map(fe=>({...fe,status:"failed",error:D.message||"执行失败"}))};N.set(n,B),T.updateMessage(n,{workflow:B,status:Z.FAILED})}return N})}},[]),p=Gs({sessionId:l,temporaryModel:_||v,onToolCalls:u}),U=s.useRef(p.sendMessage);U.current=p.sendMessage,s.useEffect(()=>{(async()=>{const n=T.getDrawerState(),f=await T.getAllSessions();c(f);let m=null;if(n.activeSessionId?(m=n.activeSessionId,I(n.activeSessionId)):f.length>0&&(m=f[0].id,I(f[0].id)),m)try{const h=await T.getMessages(m),R=new Map;for(const E of h)E.workflow&&R.set(E.id,E.workflow);V(R);const L=h.find(E=>E.workflow&&E.status===Z.STREAMING);j.current=(L==null?void 0:L.id)||null}catch(h){console.error("[ChatDrawer] Failed to load workflow messages:",h)}})()},[]),s.useEffect(()=>{T.setDrawerState({isOpen:d,activeSessionId:l})},[d,l]),s.useEffect(()=>{if(l&&re.current){const a=re.current;re.current=null,setTimeout(()=>{U.current(a)},100)}},[l]),s.useEffect(()=>{if(!le.openSettings&&re.current){const a=$e.get();if(a!=null&&a.apiKey){const n=re.current;re.current=null,l?setTimeout(()=>{U.current(n)},100):(async()=>{const f=await T.createSession();c(m=>[f,...m]),I(f.id),re.current=n})()}}},[le.openSettings,l]),s.useEffect(()=>{const a=n=>{n.key==="Escape"&&d&&(w(!1),e==null||e(!1))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[d,e]),s.useEffect(()=>{let a=null;return(async()=>{const{workflowSubmissionService:f}=await rt(async()=>{const{workflowSubmissionService:m}=await import("./workflow-submission-service-BRb6CPDr.js").then(h=>h.a);return{workflowSubmissionService:m}},__vite__mapDeps([0,2]),import.meta.url);a=f.subscribeToAllEvents(m=>{const h=m;V(R=>{let L=null;for(const[N,F]of R.entries())if(F.id===h.workflowId){L=N;break}if(!L)return R;const E=R.get(L);if(!E)return R;const D=new Map(R);let K;switch(h.type){case"step":{K={...E,steps:E.steps.map(N=>N.id===h.stepId?{...N,status:h.status||N.status,result:h.result??N.result,error:h.error??N.error}:N)};break}case"steps_added":{const F=(h.steps||[]).map(B=>({id:B.id,mcp:B.mcp,args:B.args,description:B.description,status:B.status}));K={...E,steps:[...E.steps,...F]};break}case"completed":case"failed":{const N=h.type==="completed"?"completed":"failed";K={...E,status:N,steps:E.steps.map(F=>{if(F.status==="running"||F.status==="pending"){const B=F.result;return B!=null&&B.taskId?F:{...F,status:N,error:h.type==="failed"?h.error:void 0}}return F})};break}default:return R}return D.set(L,K),T.updateMessage(L,{workflow:K}),D})})})().catch(f=>{console.error("[ChatDrawer] Failed to setup workflow sync:",f)}),()=>{a==null||a.unsubscribe()}},[]),s.useEffect(()=>{if(!M)return;const a=f=>{const m=f.target;m.closest(".t-dialog")===null&&q.current&&!q.current.contains(m)&&ee.current&&!ee.current.contains(m)&&S(!1)},n=setTimeout(()=>{document.addEventListener("mousedown",a)},100);return()=>{clearTimeout(n),document.removeEventListener("mousedown",a)}},[M]);const J=s.useCallback(()=>{w(a=>{const n=!a;return e==null||e(n),n})},[e]),de=s.useCallback(()=>{w(!1),e==null||e(!1)},[e]),te=s.useCallback(async()=>{Q.track("chat_session_create");const a=await T.createSession();c(n=>[a,...n]),I(a.id),S(!1),V(new Map),j.current=null,H(void 0)},[]),ue=s.useCallback(()=>{S(a=>!a)},[]),me=s.useCallback(async a=>{Q.track("chat_session_select"),I(a),S(!1),H(void 0);try{const n=await T.getMessages(a),f=new Map;for(const h of n)h.workflow&&f.set(h.id,h.workflow);V(f);const m=n.find(h=>h.workflow&&h.status===Z.STREAMING);j.current=(m==null?void 0:m.id)||null}catch(n){console.error("[ChatDrawer] Failed to load workflow messages:",n),V(new Map),j.current=null}},[]),_t=s.useCallback(async a=>{Q.track("chat_session_delete"),await T.deleteSession(a),c(n=>{const f=n.filter(m=>m.id!==a);if(l===a){const m=f[0]||null;I((m==null?void 0:m.id)||null)}return f})},[l]),Ee=s.useCallback(async(a,n)=>{Q.track("chat_session_rename"),await T.updateSession(a,{title:n}),c(f=>f.map(m=>m.id===a?{...m,title:n}:m))},[]),re=oe.useRef(null),Se=s.useCallback(async a=>{try{Q.track("chat_message_send",{hasImages:a.parts.some(f=>f.type==="image_url")}),Q.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,m)=>f+String(m.text||"").length,0)});const n=$e.get();if(!(n!=null&&n.apiKey)){re.current=a,$({...le,openSettings:!0});return}if(re.current=null,!l){const f=await T.createSession();c(m=>[f,...m]),I(f.id),re.current=a;return}await p.sendMessage(a)}catch(n){console.error("[ChatDrawer] send message failed:",n),re.current=a}},[l,p,le,$]),ze=s.useCallback(async a=>{var qe;const{context:n,workflow:f,textModel:m,autoOpen:h=!0}=a;h&&(w(!0),e==null||e(!0)),m&&H(m);const R=await T.createSession(),L=[];n.userInstruction&&L.push(n.userInstruction),n.selection.texts.length>0&&L.push(`
4
4
  📝 选中的文本:
5
5
  ${n.selection.texts.join(`
6
6
  `)}`),n.selection.texts.length===0&&!n.userInstruction&&n.finalPrompt&&L.push(`
7
7
  提示词:
8
- ${n.finalPrompt}`);const v=[],D=n.model.isExplicit?`模型: ${n.model.id}`:`模型: ${n.model.id} (默认)`;v.push(D),n.params.count>1&&v.push(`数量: ${n.params.count}`),v.length>0&&L.push(`
8
+ ${n.finalPrompt}`);const E=[],D=n.model.isExplicit?`模型: ${n.model.id}`:`模型: ${n.model.id} (默认)`;E.push(D),n.params.count>1&&E.push(`数量: ${n.params.count}`),E.length>0&&L.push(`
9
9
  ---
10
- ${v.join(" • ")}`);const K=L.join(`
11
- `);let N="新任务";if(n.finalPrompt)N=n.finalPrompt;else if(n.selection.texts.length>0)N=n.selection.texts[0];else if(n.userInstruction){const G=n.userInstruction.indexOf(":"),se=n.userInstruction.indexOf(":"),We=G>=0&&se>=0?Math.min(G,se):Math.max(G,se);We>=0&&We<n.userInstruction.length-1?N=n.userInstruction.substring(We+1).trim():N=n.userInstruction}else n.model.id&&(N=`模型: ${n.model.id}`);const F=N;await T.updateSession(R.id,{title:F}),R.title=F,c(G=>[R,...G]),M(R.id);const B=Date.now(),me=`msg_${B}_user`,xe=[{type:"text",text:K}],Q=[...n.selection.images,...n.selection.graphics];for(let G=0;G<Q.length;G++)xe.push({type:"data-file",data:{filename:`image-${G+1}.png`,mediaType:"image/png",url:Q[G]}});for(let G=0;G<n.selection.videos.length;G++)xe.push({type:"data-file",data:{filename:`video-${G+1}.mp4`,mediaType:"video/mp4",url:n.selection.videos[G]}});const kt={id:me,role:"user",parts:xe},we=`msg_${B}_workflow`,bt={id:we,role:"assistant",parts:[{type:"text",text:`${st}${we}`}]};V(G=>{const se=new Map(G);return se.set(we,m),se}),j.current=we;const Be={id:me,sessionId:R.id,role:ne.USER,content:K,timestamp:Date.now(),status:Z.SUCCESS,aiContext:n,attachments:Q.length>0||n.selection.videos.length>0?[...Q.map((G,se)=>({id:`${me}-img-${se}`,name:`image-${se+1}.png`,type:"image/png",size:0,data:G,isBlob:!1})),...n.selection.videos.map((G,se)=>({id:`${me}-vid-${se}`,name:`video-${se+1}.mp4`,type:"video/mp4",size:0,data:G,isBlob:!1}))]:void 0};await T.addMessage(Be);const Xe={id:we,sessionId:R.id,role:ne.ASSISTANT,content:`${st}${we}`,timestamp:Date.now(),status:Z.STREAMING,workflow:m};await T.addMessage(Xe),(Oe=p.setMessagesWithRaw)==null||Oe.call(p,[kt,bt],[Be,Xe])},[p,e]),He=s.useCallback(async a=>{var m;let n=j.current;if(!n){for(const[f,h]of X.entries())if(h.id===a.id){n=f,j.current=f;break}}n&&(V(f=>{const h=new Map(f);return h.set(n,a),h}),T.updateMessage(n,{workflow:a}),(m=p.updateRawMessageWorkflow)==null||m.call(p,n,a))},[l,i,p,X]),Fe=s.useCallback(a=>{const n=j.current;n&&V(m=>{var R;const f=new Map(m),h=f.get(n);if(h){const L=h.logs||[],v={...h,logs:[...L,a]};f.set(n,v),T.updateMessage(n,{workflow:v}),(R=p.updateRawMessageWorkflow)==null||R.call(p,n,v)}return f})},[p]),Te=s.useRef(null),Ge=s.useCallback(a=>{const n=j.current;n&&V(m=>{const f=new Map(m),h=f.get(n);if(h){const R=h.logs||[];let L=-1;for(let D=R.length-1;D>=0;D--)if(R[D].type==="thinking"){L=D;break}let v;if(L>=0){const D=[...R],K=D[L];D[L]={...K,content:K.content+a},v={...h,logs:D}}else v={...h,logs:[...R,{type:"thinking",timestamp:Date.now(),content:a}]};f.set(n,v),Te.current&&clearTimeout(Te.current),Te.current=setTimeout(()=>{var D;T.updateMessage(n,{workflow:v}),(D=p.updateRawMessageWorkflow)==null||D.call(p,n,v)},500)}return f})},[p]),Ce=s.useCallback(async(a,n,m)=>{if(!x){Y.track("chat_workflow_retry",{stepIndex:m});try{C(a),j.current=a,await P(n,m)}finally{C(null)}}},[P,x]);s.useImperativeHandle(o,()=>({open:()=>{w(!0),e==null||e(!0)},close:()=>{w(!1),e==null||e(!1)},toggle:J,sendMessage:async a=>{w(!0),e==null||e(!0);const n={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:a}]};await Se(n)},sendWorkflowMessage:ze,updateWorkflowMessage:He,appendAgentLog:Fe,updateThinkingContent:Ge,isOpen:()=>d,retryWorkflowFromStep:async(a,n)=>{let m=null;for(const[f,h]of X.entries())if(h.id===a.id){m=f;break}m?await Ce(m,a,n):console.warn("[ChatDrawer] Could not find message ID for workflow retry",a.id)}}),[d,J,Se,ze,He,Fe,Ge,e,X,Ce]);const St=s.useMemo(()=>({...p,sendMessage:Se}),[p,Se]),De=i.find(a=>a.id===l),ge=(De==null?void 0:De.title)||"新对话",[Ae,Re]=s.useState(!1),[Ne,je]=s.useState(""),ye=s.useRef(null),xt=s.useCallback(()=>{je(ge),Re(!0)},[ge]),Le=s.useCallback(async()=>{const a=Ne.trim();a&&a!==ge&&l&&await ve(l,a),Re(!1)},[Ne,ge,l,ve]),Ke=s.useCallback(()=>{je(ge),Re(!1)},[ge]),Mt=s.useCallback(a=>{a.key==="Enter"?(a.preventDefault(),Le()):a.key==="Escape"&&(a.preventDefault(),Ke())},[Le,Ke]);s.useEffect(()=>{Ae&&ye.current&&(ye.current.focus(),ye.current.select())},[Ae]);const Ve=s.useRef(null);hs(Ve,{enableCopy:!0,stopPropagation:!0});const[It,yt]=s.useState(!1);return s.useEffect(()=>{d&&yt(!0)},[d]),r.jsxs(r.Fragment,{children:[r.jsx(ut,{isOpen:d,onClick:J,drawerWidth:b}),r.jsxs("div",{className:`chat-drawer ${ss} ${d?"chat-drawer--open":""} ${y?"chat-drawer--dragging":""}`,style:{width:b},"data-testid":"chat-drawer",children:[r.jsx("div",{ref:k,className:"chat-drawer__resize-handle",onMouseDown:g}),r.jsxs("div",{ref:Ve,className:"chat-drawer__body",children:[r.jsxs("div",{className:"chat-drawer__header",children:[r.jsxs("div",{className:"chat-drawer__header-top",children:[r.jsx(ke,{content:"关闭",children:r.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:de,"aria-label":"关闭对话",children:r.jsx(ns,{size:16})})}),Ae?r.jsx("input",{ref:ye,className:"chat-drawer__title-input",value:Ne,onChange:a=>je(a.target.value),onKeyDown:Mt,onBlur:Le,maxLength:50}):r.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:xt,title:"点击编辑标题",children:ge})]}),r.jsxs("div",{className:"chat-drawer__header-bottom",children:[r.jsx(ft,{value:E,valueRef:_,onChange:(a,n)=>{H(a),q(n||Me(null,a))}}),r.jsxs("div",{className:"chat-drawer__session-actions",children:[r.jsx(ke,{content:"会话列表",children:r.jsx("button",{ref:ee,className:`chat-drawer__close-btn ${I?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:ue,"aria-label":"会话列表",children:r.jsx(as,{size:16})})}),r.jsx(ke,{content:"新对话",children:r.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:te,"aria-label":"新对话",children:r.jsx(ot,{size:16})})})]})]})]}),I&&r.jsx("div",{ref:O,children:r.jsx(dt,{sessions:i,activeSessionId:l,onSelectSession:fe,onNewSession:te,onDeleteSession:_t,onRenameSession:ve})}),r.jsxs("div",{className:"chat-drawer__content",children:[It&&r.jsx(s.Suspense,{fallback:r.jsx("div",{className:"chat-loading chat-loading--full",children:r.jsx("div",{className:"chat-loading__spinner"})}),children:r.jsx(Ks,{handler:St,workflowMessages:X,retryingWorkflowId:x,handleWorkflowRetry:Ce})}),r.jsx(mt,{selectedContent:W,onSend:Se,placeholder:"支持连续对话"})]})]})]})]})});Xs.displayName="ChatDrawer";export{Xs as C,ft as M,dt as S,ut as a,lt as b};
10
+ ${E.join(" • ")}`);const K=L.join(`
11
+ `);let N="新任务";if(n.finalPrompt)N=n.finalPrompt;else if(n.selection.texts.length>0)N=n.selection.texts[0];else if(n.userInstruction){const G=n.userInstruction.indexOf(":"),se=n.userInstruction.indexOf(":"),We=G>=0&&se>=0?Math.min(G,se):Math.max(G,se);We>=0&&We<n.userInstruction.length-1?N=n.userInstruction.substring(We+1).trim():N=n.userInstruction}else n.model.id&&(N=`模型: ${n.model.id}`);const F=N;await T.updateSession(R.id,{title:F}),R.title=F,c(G=>[R,...G]),I(R.id);const B=Date.now(),fe=`msg_${B}_user`,xe=[{type:"text",text:K}],Y=[...n.selection.images,...n.selection.graphics];for(let G=0;G<Y.length;G++)xe.push({type:"data-file",data:{filename:`image-${G+1}.png`,mediaType:"image/png",url:Y[G]}});for(let G=0;G<n.selection.videos.length;G++)xe.push({type:"data-file",data:{filename:`video-${G+1}.mp4`,mediaType:"video/mp4",url:n.selection.videos[G]}});const kt={id:fe,role:"user",parts:xe},we=`msg_${B}_workflow`,bt={id:we,role:"assistant",parts:[{type:"text",text:`${st}${we}`}]};V(G=>{const se=new Map(G);return se.set(we,f),se}),j.current=we;const Be={id:fe,sessionId:R.id,role:ne.USER,content:K,timestamp:Date.now(),status:Z.SUCCESS,aiContext:n,attachments:Y.length>0||n.selection.videos.length>0?[...Y.map((G,se)=>({id:`${fe}-img-${se}`,name:`image-${se+1}.png`,type:"image/png",size:0,data:G,isBlob:!1})),...n.selection.videos.map((G,se)=>({id:`${fe}-vid-${se}`,name:`video-${se+1}.mp4`,type:"video/mp4",size:0,data:G,isBlob:!1}))]:void 0};await T.addMessage(Be);const Xe={id:we,sessionId:R.id,role:ne.ASSISTANT,content:`${st}${we}`,timestamp:Date.now(),status:Z.STREAMING,workflow:f};await T.addMessage(Xe),(qe=p.setMessagesWithRaw)==null||qe.call(p,[kt,bt],[Be,Xe])},[p,e]),He=s.useCallback(async a=>{var f;let n=j.current;if(!n){for(const[m,h]of X.entries())if(h.id===a.id){n=m,j.current=m;break}}n&&(V(m=>{const h=new Map(m);return h.set(n,a),h}),T.updateMessage(n,{workflow:a}),(f=p.updateRawMessageWorkflow)==null||f.call(p,n,a))},[l,i,p,X]),Fe=s.useCallback(a=>{const n=j.current;n&&V(f=>{var R;const m=new Map(f),h=m.get(n);if(h){const L=h.logs||[],E={...h,logs:[...L,a]};m.set(n,E),T.updateMessage(n,{workflow:E}),(R=p.updateRawMessageWorkflow)==null||R.call(p,n,E)}return m})},[p]),Te=s.useRef(null),Ge=s.useCallback(a=>{const n=j.current;n&&V(f=>{const m=new Map(f),h=m.get(n);if(h){const R=h.logs||[];let L=-1;for(let D=R.length-1;D>=0;D--)if(R[D].type==="thinking"){L=D;break}let E;if(L>=0){const D=[...R],K=D[L];D[L]={...K,content:K.content+a},E={...h,logs:D}}else E={...h,logs:[...R,{type:"thinking",timestamp:Date.now(),content:a}]};m.set(n,E),Te.current&&clearTimeout(Te.current),Te.current=setTimeout(()=>{var D;T.updateMessage(n,{workflow:E}),(D=p.updateRawMessageWorkflow)==null||D.call(p,n,E)},500)}return m})},[p]),Ce=s.useCallback(async(a,n,f)=>{if(!x){Q.track("chat_workflow_retry",{stepIndex:f});try{C(a),j.current=a,await P(n,f)}finally{C(null)}}},[P,x]);s.useImperativeHandle(o,()=>({open:()=>{w(!0),e==null||e(!0)},close:()=>{w(!1),e==null||e(!1)},toggle:J,sendMessage:async a=>{w(!0),e==null||e(!0);const n={id:`msg_${Date.now()}`,role:"user",parts:[{type:"text",text:a}]};await Se(n)},sendWorkflowMessage:ze,updateWorkflowMessage:He,appendAgentLog:Fe,updateThinkingContent:Ge,isOpen:()=>d,retryWorkflowFromStep:async(a,n)=>{let f=null;for(const[m,h]of X.entries())if(h.id===a.id){f=m;break}f?await Ce(f,a,n):console.warn("[ChatDrawer] Could not find message ID for workflow retry",a.id)}}),[d,J,Se,ze,He,Fe,Ge,e,X,Ce]);const St=s.useMemo(()=>({...p,sendMessage:Se}),[p,Se]),De=i.find(a=>a.id===l),ge=(De==null?void 0:De.title)||"新对话",[Ae,Re]=s.useState(!1),[Ne,je]=s.useState(""),ye=s.useRef(null),xt=s.useCallback(()=>{je(ge),Re(!0)},[ge]),Le=s.useCallback(async()=>{const a=Ne.trim();a&&a!==ge&&l&&await Ee(l,a),Re(!1)},[Ne,ge,l,Ee]),Ke=s.useCallback(()=>{je(ge),Re(!1)},[ge]),It=s.useCallback(a=>{a.key==="Enter"?(a.preventDefault(),Le()):a.key==="Escape"&&(a.preventDefault(),Ke())},[Le,Ke]);s.useEffect(()=>{Ae&&ye.current&&(ye.current.focus(),ye.current.select())},[Ae]);const Ve=s.useRef(null);hs(Ve,{enableCopy:!0,stopPropagation:!0});const[Mt,yt]=s.useState(!1);return s.useEffect(()=>{d&&yt(!0)},[d]),r.jsxs(r.Fragment,{children:[r.jsx(ut,{isOpen:d,onClick:J,drawerWidth:b}),r.jsxs("div",{className:`chat-drawer ${Qt} ${d?"chat-drawer--open":""} ${y?"chat-drawer--dragging":""}`,style:{width:b},"data-testid":"chat-drawer",children:[r.jsx("div",{ref:k,className:"chat-drawer__resize-handle",onMouseDown:g}),r.jsxs("div",{ref:Ve,className:"chat-drawer__body",children:[r.jsxs("div",{className:"chat-drawer__header",children:[r.jsxs("div",{className:"chat-drawer__header-top",children:[r.jsx(ke,{content:"关闭",children:r.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_drawer_close",onClick:de,"aria-label":"关闭对话",children:r.jsx(Zt,{size:16})})}),Ae?r.jsx("input",{ref:ye,className:"chat-drawer__title-input",value:Ne,onChange:a=>je(a.target.value),onKeyDown:It,onBlur:Le,maxLength:50}):r.jsx("h2",{className:"chat-drawer__title chat-drawer__title--editable",onClick:xt,title:"点击编辑标题",children:ge})]}),r.jsxs("div",{className:"chat-drawer__header-bottom",children:[r.jsx(mt,{value:v,valueRef:_,onChange:(a,n)=>{H(a),O(n||Ie(null,a))}}),r.jsxs("div",{className:"chat-drawer__session-actions",children:[r.jsx(ke,{content:"会话列表",children:r.jsx("button",{ref:ee,className:`chat-drawer__close-btn ${M?"chat-drawer__close-btn--active":""}`,"data-track":"chat_click_sessions_toggle",onClick:ue,"aria-label":"会话列表",children:r.jsx(es,{size:16})})}),r.jsx(ke,{content:"新对话",children:r.jsx("button",{className:"chat-drawer__close-btn","data-track":"chat_click_new_session",onClick:te,"aria-label":"新对话",children:r.jsx(ot,{size:16})})})]})]})]}),M&&r.jsx("div",{ref:q,children:r.jsx(dt,{sessions:i,activeSessionId:l,onSelectSession:me,onNewSession:te,onDeleteSession:_t,onRenameSession:Ee})}),r.jsxs("div",{className:"chat-drawer__content",children:[Mt&&r.jsx(s.Suspense,{fallback:r.jsx("div",{className:"chat-loading chat-loading--full",children:r.jsx("div",{className:"chat-loading__spinner"})}),children:r.jsx(Ks,{handler:St,workflowMessages:X,retryingWorkflowId:x,handleWorkflowRetry:Ce})}),r.jsx(ft,{selectedContent:W,onSend:Se,placeholder:"支持连续对话"})]})]})]})]})});Xs.displayName="ChatDrawer";export{Xs as C,mt as M,dt as S,ut as a,lt as b};
@@ -1,7 +1,7 @@
1
- import{r as d,j as e,h8 as P,js as I,dN as L,ee as T,jt as W}from"./diagram-engines-D0zsaRpk.js";import{M as $}from"./index-C2Okyhwh.js";import{a3 as z}from"./shared-runtime-BQ8G5UJo.js";import"./startup-runtime-BbuNXj6O.js";import"./editor-engines-DOeFgZem.js";import"./tool-windows-DSHfJOm9.js";/* empty css */import"./main-Cbvfl50a.js";const R={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},F={pending:"待执行",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"};function B(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(P,{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 D=({step:s,index:c,isCurrentStep:f})=>{const[m,l]=d.useState(!1),b=R[s.status],o=F[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,_]of Object.entries(i))u==="context"?x[u]="[AgentExecutionContext]":typeof _=="string"&&_.length>200?x[u]=_.substring(0,200)+"...":x[u]=_;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})]})]})]})},K=({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},G=({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),g=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(g||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,g=t.filter(N=>N.status==="failed").length,j=t.filter(N=>N.status==="running").length;let h="pending";if(g>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 g=l.length-1;g>=0;g-=1){const j=(t=l[g])==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 A=N.trim();if(A)return A}}}}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]),_=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(D,{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(K,{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"&&_&&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:B(_)})})})]}),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?"重试中...":"🔄 从失败步骤重试"})]})]})]})},J=({message:s,className:c=""})=>{const f=d.useRef(null),{text:m,meta:l,images:b}=d.useMemo(()=>{var u,_,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/")||(_=a==null?void 0:a.url)!=null&&_.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(T,{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(W,{size:"12px"})}),{text:t.userInstruction||t.finalPrompt||n,meta:a,images:r}}let i=n;const x=[];if(i.includes(`
1
+ import{r as d,j as e,h7 as P,je as I,dT as L,ek as A,jf as W}from"./diagram-engines-DmAewdsu.js";import{M as $}from"./index-BbDNsPPx.js";import{a3 as z}from"./shared-runtime-DBavnB0U.js";import"./startup-runtime-BbuNXj6O.js";import"./editor-engines-DGOT7Xqo.js";import"./tool-windows-DV-j2p51.js";/* empty css */import"./main-B2ZrUywM.js";const R={pending:"○",running:"◉",completed:"✓",failed:"✗",skipped:"⊘"},F={pending:"待执行",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"};function B(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(P,{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 D=({step:s,index:c,isCurrentStep:f})=>{const[m,l]=d.useState(!1),b=R[s.status],o=F[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,_]of Object.entries(i))u==="context"?x[u]="[AgentExecutionContext]":typeof _=="string"&&_.length>200?x[u]=_.substring(0,200)+"...":x[u]=_;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})]})]})]})},K=({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},G=({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),g=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(g||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,g=t.filter(N=>N.status==="failed").length,j=t.filter(N=>N.status==="running").length;let h="pending";if(g>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 g=l.length-1;g>=0;g-=1){const j=(t=l[g])==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 T=N.trim();if(T)return T}}}}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]),_=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(D,{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(K,{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"&&_&&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:B(_)})})})]}),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?"重试中...":"🔄 从失败步骤重试"})]})]})]})},J=({message:s,className:c=""})=>{const f=d.useRef(null),{text:m,meta:l,images:b}=d.useMemo(()=>{var u,_,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/")||(_=a==null?void 0:a.url)!=null&&_.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(W,{size:"12px"})}),{text:t.userInstruction||t.finalPrompt||n,meta:a,images:r}}let i=n;const x=[];if(i.includes(`
2
2
  ---
3
3
  `)){const t=i.split(`
4
4
  ---
5
- `);i=t[0],t[1].split(" • ").forEach(w=>{const g=w.replace(/模型:\s*/,"").replace(/数量:\s*/,"").replace(/尺寸:\s*/,"").trim();if(g){let j=e.jsx(I,{size:"12px"});w.includes("数量")&&(j=e.jsx(L,{size:"12px"})),w.includes("尺寸")&&(j=e.jsx(T,{size:"12px"})),x.push({label:g,icon:j})}})}else{const t=i.split(`
5
+ `);i=t[0],t[1].split(" • ").forEach(w=>{const g=w.replace(/模型:\s*/,"").replace(/数量:\s*/,"").replace(/尺寸:\s*/,"").trim();if(g){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:g,icon:j})}})}else{const t=i.split(`
6
6
  `),a=[];for(const w of t){const g=w.trim();if(g.startsWith("模型:")||g.startsWith("数量:")||g.startsWith("提示词:")){const j=g.replace(/.*:\s*/,"").trim();let h=e.jsx(I,{size:"12px"});g.includes("数量")&&(h=e.jsx(L,{size:"12px"})),x.push({label:j,icon:h})}else g.startsWith("📝 选中的文本:")?x.push({label:g.replace("📝 ","").trim(),icon:e.jsx(W,{size:"12px"})}):g&&!g.startsWith("💬 用户指令:")&&a.push(w)}i=a.join(`
7
7
  `).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&&(z(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 _=c.get(i);if(_)return e.jsx(G,{workflow:_,onRetry:y=>m(i,_,y),isRetrying:f===i},r.id)}const x=r.parts.some(_=>_.type==="text"&&"text"in _&&typeof _.text=="string"&&_.text.startsWith("❌ 错误")),u=`chat-message chat-message--${r.role} ${x?"chat-message--error":""}`;return r.role==="user"&&o(r)?e.jsx(J,{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};