aitu-app 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/assets/{CanvasAudioPlayer-cp00LGgR.js → CanvasAudioPlayer-C_USx5uz.js} +1 -1
- package/assets/{ComicCreator-CAmJF3JX.js → ComicCreator-qGQaXp7h.js} +2 -2
- package/assets/DeferredAIInputBar-CPykEFYX.css +1 -0
- package/assets/DeferredAIInputBar-LmZGQCLT.js +107 -0
- package/assets/{DrawnixDeferredFeatures-DIznfzB7.js → DrawnixDeferredFeatures-Hy_-quZ1.js} +1 -1
- package/assets/{KnowledgeBaseContent-CxilHI-j.js → KnowledgeBaseContent-DSKNA70H.js} +8 -8
- package/assets/{MVCreator-ZrinzYPm.js → MVCreator-C3iClDLU.js} +12 -10
- package/assets/{ModelBenchmarkWorkbench-DbesnX6E.js → ModelBenchmarkWorkbench-BxwdcZ0q.js} +2 -2
- package/assets/{MusicAnalyzer-BzXD1qYH.js → MusicAnalyzer-f_T6_YPJ.js} +2 -2
- package/assets/{ParametersDropdown-DBQCDv3g.js → ParametersDropdown-CTSN3ClD.js} +1 -1
- package/assets/{PromptHistoryTool-CUCIE0Ld.js → PromptHistoryTool-DV-8RSdz.js} +2 -2
- package/assets/{ResizableDivider-CdfJF8GW.js → ResizableDivider-CUQBmPpx.js} +1 -1
- package/assets/TaskQueuePanel-CtjY1W4t.js +1 -0
- package/assets/{VideoAnalyzer-wtxorxD3.js → VideoAnalyzer-BBVBSONO.js} +3 -3
- package/assets/{VideoAnalyzer-C90c84gt.js → VideoAnalyzer-BmAjGvN8.js} +1 -1
- package/assets/{ai-chat-B5qFht2H.js → ai-chat-BO5vbKZW.js} +5 -5
- package/assets/{ai-generation-preferences-service-CvWbMxv3.js → ai-generation-preferences-service-ZmPTR-wz.js} +1 -1
- package/assets/{batch-image-generation-Bo3h_Eop.js → batch-image-generation-BLBSv-t6.js} +6 -6
- package/assets/{diagram-engines-C9ewAq_o.js → diagram-engines-CSzW_-6N.js} +2 -2
- package/assets/{editor-engines-CvxZrFyB.js → editor-engines-C573k8UM.js} +1 -1
- package/assets/{index-Dw6PsLbq.js → index-BT-rxxI3.js} +2 -2
- package/assets/{index-BCqdmg38.js → index-Dw_8lcIi.js} +1 -1
- package/assets/{index-BSlnQdcy.js → index-IHNaVKGH.js} +1 -1
- package/assets/{index-CjBeKr1R.js → index-N8asYyaz.js} +1 -1
- package/assets/{index-CylhK_f5.js → index-jxwTv7c1.js} +1 -1
- package/assets/{index.es-BKVY-J2g.js → index.es-BLXvmueB.js} +1 -1
- package/assets/{jspdf.es.min-BM9ML7Zw.js → jspdf.es.min-DxWvbkh4.js} +2 -2
- package/assets/{markdown-to-drawnix-COS1iVyq.js → markdown-to-drawnix-BVFYnimo.js} +2 -2
- package/assets/{mermaid-to-drawnix-oplawQO0.js → mermaid-to-drawnix-nGs2aeZ7.js} +2 -2
- package/assets/{model-benchmark-launcher-DD4vN0Ca.js → model-benchmark-launcher-DAWoSySc.js} +1 -1
- package/assets/{photo-wall-splitter-CbKqFOIV.js → photo-wall-splitter-CCUURzGk.js} +1 -1
- package/assets/{prompt-utils-7t-jk6n6.js → prompt-utils-MF_LILNU.js} +1 -1
- package/assets/{settings-dialog-D2yEWl8J.js → settings-dialog-Ac7R-_CG.js} +1 -1
- package/assets/{skill-dsl-parser-C-utRXFg.js → skill-dsl-parser-Do9iAYbB.js} +1 -1
- package/assets/{startup-app-DxX-P1pm.js → startup-app-eD_rQhSh.js} +531 -527
- package/assets/{task-sync-Dr7Nza2v.js → task-sync-BJVOunRa.js} +1 -1
- package/assets/{tool-windows-BIjc1zsU.js → tool-windows-CmgL3thd.js} +17 -17
- package/assets/ttd-dialog-B12v0SVY.js +6 -0
- package/assets/{ttd-dialog-submit-shortcut-yUk15rsg.js → ttd-dialog-submit-shortcut-C2lJygXA.js} +1 -1
- package/assets/useCharacters-BAKE4TeJ.js +2 -0
- package/assets/{useMediaViewer-CEvHYype.js → useMediaViewer-BGw5RkSR.js} +1 -1
- package/assets/{useWorkflowSubmission-Cxhdsl2b.js → useWorkflowSubmission-iAPmKke9.js} +6 -6
- package/assets/{video-recovery-service-CB8hyRf5.js → video-recovery-service-CW7bErP2.js} +1 -1
- package/assets/{workflow-generation-utils-JoRODaP7.js → workflow-generation-utils-DhIVnOHO.js} +2 -2
- package/assets/workflow-submission-service-Ce0cpj8E.js +4 -0
- package/changelog.json +18 -13
- package/idle-prefetch-manifest.json +306 -306
- package/manifest.json +3 -3
- package/package.json +1 -1
- package/precache-manifest.json +6 -6
- package/sw.js +1 -1
- package/version.json +6 -3
- package/assets/DeferredAIInputBar-CzMATNng.js +0 -107
- package/assets/DeferredAIInputBar-D_e6qG1y.css +0 -1
- package/assets/TaskQueuePanel-oLG4DAzJ.js +0 -1
- package/assets/ttd-dialog-CNSSc4wk.js +0 -6
- package/assets/useCharacters-DzXMuknh.js +0 -2
- package/assets/workflow-submission-service-BIGFW4s4.js +0 -4
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css","./ai-chat-DyV67c_f.css","./ParametersDropdown-b2oWAycj.css","./tool-windows-CegtMid1.css","./batch-image-generation-DgBXF-sY.css","./ttd-dialog-submit-shortcut-DyioEoKX.css","./useCharacters-DRBoWvvj.css","./character-Bo9jcTNu.css","./ResizableDivider-ClzYJk-6.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as _t}from"./startup-runtime-DTmhLESk.js";import{r as e,j as t,E as tt,c6 as Ms,er as mt,gr as Ns,am as Rs,a0 as ss,iy as Be,a4 as As,_ as zs,j9 as Ds,ie as Ls,ja as Nt,hC as ns,hN as $s,b$ as as,c0 as Vs,c2 as Os,dc as Us,gT as Fs,jb as Gs,jc as Ws,dA as Rt,bz as Ks,ck as os,dB as Ge,M as Re,bg as we,n as Bs,c7 as qs,c8 as Hs,c1 as At,h9 as Ie,d as Xs,c as Js,jd as Qs,ei as Ys,av as qe,al as ze,at as Tt,fB as Et,i3 as rs,y as he,iU as Zs,je as st,aX as De,aA as is,aC as et,jf as en,fO as Ct,jg as tn,i_ as sn,i$ as nn,jh as xt,iW as ls,ji as zt,jj as an,jk as Dt,j5 as on,a8 as Lt,jl as $t,jm as vt,jn as Vt,jo as Ot,i0 as Ut,i1 as Ft,hk as rn,bQ as ln,bq as cn,jp as dn,j7 as Gt,jq as Wt}from"./startup-app-DxX-P1pm.js";import{u as kt,r as un,g as cs,s as ds}from"./prompt-utils-7t-jk6n6.js";import{P as us}from"./ParametersDropdown-DBQCDv3g.js";import{r as mn,P as pn,U as fn,i as ms,j as Ve,l as pt,k as Ae,m as Se,K as ps,W as Kt}from"./ai-chat-B5qFht2H.js";import"./tool-windows-BIjc1zsU.js";import{u as fs,C as hn,V as gn,a as bn}from"./useCharacters-DzXMuknh.js";/* empty css */import{R as hs}from"./ResizableDivider-CdfJF8GW.js";import{c as Bt,d as xn,e as It,f as qt,g as vn}from"./ai-generation-preferences-service-CvWbMxv3.js";import{b as Ht}from"./mj-params-M-7csAp7.js";const Xt=(n,s,a)=>{const d=a==="image"?{isGenerating:n,imageLoading:s}:{isGenerating:n,videoLoading:s};window.dispatchEvent(new CustomEvent("ai-generation-state-change",{detail:d}))},gs=(n,s,a)=>{e.useEffect(()=>{const d=o=>{(o.metaKey||o.ctrlKey)&&o.key==="Enter"&&(o.preventDefault(),!n&&s.trim()&&a())};return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d)}},[n,s,a])},bs=n=>{const[s,a]=e.useState(!1),[d,o]=e.useState(!1),u=e.useCallback(_=>{a(_),Xt(_,d,n)},[d,n]),v=e.useCallback(_=>{o(_),Xt(s,_,n)},[s,n]);return{isGenerating:s,isLoading:d,updateIsGenerating:u,updateIsLoading:v}},In=(n,s,a)=>s==="image"?n==="zh"?"一只可爱的小猫坐在窗台上,阳光透过窗户洒在它的毛发上,背景是温馨的家居环境":"A cute kitten sitting on a windowsill, with sunlight streaming through the window onto its fur, with a cozy home environment in the background":a==="sora"?n==="zh"?"描述视频内容,输入 @ 可引用已创建的角色,如 @username 在海边漫步...":"Describe video content, type @ to reference created characters, e.g. @username walking on the beach...":n==="zh"?"生成一个美丽的日出场景,阳光从山峰后缓缓升起,云朵轻柔地飘动":"Generate a beautiful sunrise scene where the sun slowly rises from behind mountains with clouds gently floating",yn=[1,2,3,4,5,10,20,50,100],wn="aitu_image_generation_quantity",Sn="aitu_video_generation_quantity",yt=100,xs=({language:n,type:s,isGenerating:a,hasGenerated:d,canGenerate:o,onGenerate:u,onReset:v,leftContent:_})=>{const M=s==="video"?Sn:wn,[i,h]=e.useState(()=>{try{const l=localStorage.getItem(M);if(l){const w=parseInt(l,10);if(!isNaN(w)&&w>=1&&w<=yt)return w}}catch{}return 1}),[D,V]=e.useState(!1),[f,C]=e.useState(()=>i.toString()),N=e.useRef(null);e.useEffect(()=>{C(i.toString());try{localStorage.setItem(M,i.toString())}catch{}},[i,M]),e.useEffect(()=>{const l=w=>{N.current&&!N.current.contains(w.target)&&(V(!1),y())};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[f]);const y=()=>{let l=parseInt(f,10);(isNaN(l)||l<1)&&(l=1),l>yt&&(l=yt),C(l.toString()),h(l)},W=l=>{const w=l.target.value;(w===""||/^\d*$/.test(w))&&C(w)},Z=l=>{h(l),C(l.toString()),V(!1)},F=()=>{a||V(!D)},Y=()=>{u(i)};return t.jsxs("div",{className:"section-actions unified-action-bar",children:[_&&t.jsx("div",{className:"action-bar-left",children:_}),t.jsxs("div",{className:`unified-action-box ${a?"is-generating":""} ${o?"can-generate":""}`,children:[t.jsxs("div",{className:"quantity-section",ref:N,children:[t.jsx(tt,{content:n==="zh"?"生成数量":"Quantity",theme:"light",children:t.jsxs("div",{className:`quantity-control ${D?"is-open":""} ${a?"is-disabled":""}`,children:[t.jsx("input",{type:"text",inputMode:"numeric",value:f,onChange:W,onBlur:y,"data-track":"ai_click_quantity_input",onClick:()=>!a&&V(!0),disabled:a,className:"quantity-input"}),t.jsx("button",{type:"button","data-track":"ai_click_quantity_toggle",onClick:l=>{l.stopPropagation(),F()},disabled:a,className:"quantity-toggle",children:t.jsx(Ms,{className:`quantity-icon ${D?"is-open":""}`})})]})}),D&&t.jsxs("div",{className:"quantity-dropdown",children:[t.jsx("div",{className:"quantity-dropdown-header",children:n==="zh"?"选择数量":"Select Quantity"}),yn.map(l=>t.jsxs("button",{type:"button","data-track":"ai_click_quantity_select",onClick:()=>Z(l),className:`quantity-option ${i===l?"is-selected":""}`,children:[t.jsxs("span",{children:[l," ",s==="video"?n==="zh"?"个":l>1?"videos":"video":n==="zh"?"张":l>1?"images":"image"]}),i===l&&t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:t.jsx("polyline",{points:"20 6 9 17 4 12"})})]},l))]})]}),t.jsx("div",{className:"action-divider"}),t.jsx("button",{"data-track":"ai_click_generate",onClick:Y,disabled:a||!o,className:`generate-button ${a?"loading":""}`,children:a?n==="zh"?"生成中...":"Generating...":d?n==="zh"?"重新生成":"Regenerate":s==="video"?n==="zh"?"生成视频":"Generate Video":n==="zh"?"生成":"Generate"})]}),t.jsx(tt,{content:n==="zh"?"重置表单":"Reset form",theme:"light",children:t.jsx(mt,{"data-track":"ai_click_reset",onClick:v,disabled:a,variant:"text",shape:"circle",icon:t.jsx(Ns,{}),className:"action-button--reset-subtle"})})]})},vs=({error:n})=>n?t.jsx("div",{className:"form-error",children:n}):null,Is=({visible:n,query:s,position:a,showBelow:d=!1,selectedIndex:o,onSelect:u,onClose:v})=>{const{completedCharacters:_,isLoading:M}=fs(),i=e.useRef(null),h=e.useMemo(()=>{if(!s)return _;const f=s.toLowerCase();return _.filter(C=>C.username.toLowerCase().includes(f))},[_,s]);e.useEffect(()=>{if(!n||!i.current)return;const f=i.current.querySelector(".character-mention-popup__item--selected");f&&f.scrollIntoView({block:"nearest"})},[n,o]),e.useEffect(()=>{if(!n)return;const f=C=>{i.current&&!i.current.contains(C.target)&&v()};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[n,v]);const D=e.useCallback(f=>{Rs.track("character_used_in_prompt",{characterId:f.id,username:f.username}),u(f)},[u]);if(!n)return null;const V={position:"fixed",top:a.top,left:a.left,transform:d?"none":"translateY(-100%)",zIndex:ss.DROPDOWN_PORTAL,maxHeight:"200px",overflowY:"auto"};return M?t.jsx("div",{ref:i,className:"character-mention-popup",style:V,children:t.jsx("div",{className:"character-mention-popup__empty",children:"加载中..."})}):h.length===0?t.jsx("div",{ref:i,className:"character-mention-popup",style:V,children:t.jsx("div",{className:"character-mention-popup__empty",children:s?`未找到 "${s}" 相关角色`:"暂无可用角色"})}):t.jsx("div",{ref:i,className:"character-mention-popup",style:V,children:h.map((f,C)=>t.jsxs("div",{className:`character-mention-popup__item ${C===o?"character-mention-popup__item--selected":""}`,onClick:()=>D(f),"data-track":"character_click_mention",children:[t.jsx("div",{className:"character-mention-popup__item-avatar",children:t.jsx(hn,{characterId:f.id,profilePictureUrl:f.profilePictureUrl,alt:f.username})}),t.jsxs("span",{className:"character-mention-popup__item-name",children:["@",f.username]})]},f.id))})},Cn={visible:!1,query:"",position:{top:0,left:0},showBelow:!1,startIndex:-1,selectedIndex:0};function ys({enabled:n=!0,onPromptChange:s,prompt:a}){const[d,o]=e.useState(Cn),u=e.useRef(null),{completedCharacters:v}=fs(),_=e.useCallback(f=>{if(!u.current)return{top:0,left:0,showBelow:!1};const C=u.current,N=C.getBoundingClientRect(),y=document.createElement("div"),W=window.getComputedStyle(C),Z=["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","wordSpacing","whiteSpace","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing"];y.style.position="absolute",y.style.top="0",y.style.left="-9999px",y.style.visibility="hidden",y.style.whiteSpace="pre-wrap",y.style.overflowWrap="break-word",y.style.overflow="hidden",y.style.width=`${C.clientWidth}px`,Z.forEach(H=>{y.style[H]=W.getPropertyValue(H.replace(/([A-Z])/g,"-$1").toLowerCase())}),document.body.appendChild(y);let F=0,Y=0;try{const H=C.value.substring(0,f),X=document.createTextNode(H),oe=document.createElement("span");oe.textContent="",y.appendChild(X),y.appendChild(oe);const pe=oe.getBoundingClientRect(),U=y.getBoundingClientRect();F=pe.top-U.top,Y=pe.left-U.left}finally{document.body.removeChild(y)}const l=C.scrollTop,w=parseInt(W.lineHeight)||20;let j=N.top+F-l,I=N.left+Y;const L=240,R=window.innerWidth;I+L>R-16&&(I=R-L-16),I<16&&(I=16);const _e=j<220+16;return _e?j=j+w+4:j=j-48,{top:j,left:I,showBelow:_e}},[]),M=e.useCallback((f,C)=>{if(!n)return;const N=f.substring(0,C),y=N.lastIndexOf("@");if(y===-1){o(Y=>({...Y,visible:!1}));return}const W=y>0?f[y-1]:" ";if(!/\s/.test(W)&&y!==0){o(Y=>({...Y,visible:!1}));return}const Z=N.substring(y+1);if(Z.includes(" ")){o(Y=>({...Y,visible:!1}));return}const F=_(C);o({visible:!0,query:Z,position:{top:F.top,left:F.left},showBelow:F.showBelow,startIndex:y,selectedIndex:0})},[n,_]),i=e.useCallback(f=>{var Z;if(d.startIndex===-1)return;const C=a.substring(0,d.startIndex),N=((Z=u.current)==null?void 0:Z.selectionStart)||a.length,y=a.substring(N),W=`${C}@${f.username} ${y}`;s(W),o(F=>({...F,visible:!1})),setTimeout(()=>{if(u.current){const F=C.length+f.username.length+2;u.current.focus(),u.current.setSelectionRange(F,F)}},0)},[d.startIndex,a,s]),h=e.useCallback(f=>{if(!d.visible)return;const C=d.query?v.filter(N=>N.username.toLowerCase().includes(d.query.toLowerCase())):v;switch(f.key){case"ArrowDown":f.preventDefault(),o(N=>({...N,selectedIndex:Math.min(N.selectedIndex+1,C.length-1)}));break;case"ArrowUp":f.preventDefault(),o(N=>({...N,selectedIndex:Math.max(N.selectedIndex-1,0)}));break;case"Enter":case"Tab":C.length>0&&(f.preventDefault(),i(C[d.selectedIndex]));break;case"Escape":f.preventDefault(),o(N=>({...N,visible:!1}));break}},[d,v,i]),D=e.useCallback((f,C)=>{s(f),M(f,C)},[s,M]),V=e.useCallback(()=>{o(f=>({...f,visible:!1}))},[]);return{mentionState:d,setMentionState:o,textareaRef:u,completedCharacters:v,handleTextChange:D,handleKeyDown:h,handleCharacterSelect:i,closeMentionPopup:V,calculateMentionPosition:_}}const ws=({prompt:n,onPromptChange:s,presetPrompts:a,language:d,type:o,disabled:u=!1,onError:v,enableMention:_=!0,videoProvider:M})=>{const[i,h]=e.useState(!1),D=e.useRef(null),V=e.useRef(null),[f,C]=e.useState(null),[N,y]=e.useState(0),{imageHistory:W,videoHistory:Z}=kt();e.useEffect(()=>{if(typeof Be.subscribeChanges=="function")return Be.subscribeChanges(()=>{y(U=>U+1)})},[]);const F=e.useMemo(()=>un({generationType:o,language:d,promptContents:a,imageHistory:W,videoHistory:Z}),[W,d,o,a,N,Z]),Y=_&&o==="video"&&M==="sora",{mentionState:l,textareaRef:w,handleTextChange:j,handleKeyDown:I,handleCharacterSelect:L,closeMentionPopup:R}=ys({enabled:Y,onPromptChange:s,prompt:n}),ee=e.useCallback(()=>{if(V.current&&i){const U=V.current.getBoundingClientRect(),T=8,q=320,k=400,ge=window.innerHeight-U.top+4,se=Math.min(q,window.innerWidth-T*2),fe=window.innerWidth-U.right,Ne=window.innerWidth-se-T,ue=Math.max(Math.min(fe,Ne),T),re=Math.min(k,U.top-T,window.innerHeight*.45);C({bottom:ge,right:ue,maxHeight:re})}},[i]);e.useEffect(()=>{if(i)return ee(),window.addEventListener("scroll",ee,!0),window.addEventListener("resize",ee),()=>{window.removeEventListener("scroll",ee,!0),window.removeEventListener("resize",ee)}},[i,ee]),e.useEffect(()=>{const U=T=>{const q=T.target;if(D.current&&!D.current.contains(q)){const k=document.querySelector(".preset-prompt-panel-portal");k!=null&&k.contains(q)||h(!1)}};if(i)return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[i]);const _e=e.useCallback(U=>{const T=typeof U=="string"?U:U.content;s(T),v==null||v(null),h(!1)},[s,v]),H=e.useCallback(U=>{const T=F.find(q=>q.id===U);T&&(T.pinned?Be.unpinPrompt(o,T.content):Be.pinPrompt(o,T.content),y(q=>q+1))},[o,F]),X=e.useCallback(U=>{const T=F.find(q=>q.id===U);T&&(Be.deletePrompt(o,T.content),y(q=>q+1))},[o,F]),oe=e.useCallback(U=>{const T=U.target.value,q=U.target.selectionStart||0;j(T,q),v==null||v(null)},[j,v]);e.useEffect(()=>{o!=="video"&&R()},[o,R]);const pe=()=>{if(!i||!f)return null;const U=d==="zh"?`${o==="image"?"图片":"视频"}描述预设`:`${o==="image"?"Image":"Video"} Description Presets`,T=t.jsx("div",{className:"preset-prompt-panel-portal",style:{position:"fixed",bottom:f.bottom,right:f.right,zIndex:ss.DIALOG_POPOVER,"--panel-max-width":"calc(100vw - 16px)","--panel-max-height":`${f.maxHeight}px`},children:t.jsx(pn,{title:U,items:F,onSelect:_e,onTogglePin:H,onDelete:X,language:d,disabled:u,showCount:!0})});return zs.createPortal(T,document.body)};return t.jsxs("div",{className:"form-field form-field--prompt",children:[t.jsxs("div",{className:"form-label-with-icon",children:[t.jsx("label",{className:"form-label",children:d==="zh"?`${o==="image"?"图片":"视频"}描述`:`${o==="image"?"Image":"Video"} Description`}),t.jsx("div",{className:"textarea-with-preset",children:t.jsxs("div",{className:"preset-tooltip-container",ref:D,children:[t.jsx("button",{ref:V,type:"button",className:"preset-icon-button",disabled:u,onClick:()=>h(!i),children:t.jsx(As,{size:16})}),pe()]})})]}),t.jsxs("div",{className:"prompt-textarea-wrapper",children:[t.jsx("textarea",{ref:w,className:"form-textarea",value:n,onChange:oe,onKeyDown:I,placeholder:In(d,o,M),rows:4,disabled:u}),t.jsx(mn,{className:"prompt-optimize-button",originalPrompt:n,language:d,scenarioId:o==="image"?"tool.image":"tool.video",disabled:u,tooltipPlacement:"top",allowStructuredMode:!0,onApply:U=>{s(U),v==null||v(null)}})]}),Y&&t.jsx(Is,{visible:l.visible,query:l.query,position:l.position,showBelow:l.showBelow,selectedIndex:l.selectedIndex,onSelect:L,onClose:R})]})};function Ss(){return Ds("scene")}function Jt(n,s){return{id:Ss(),order:n,duration:s,prompt:""}}function jn(n,s,a=1){if(n.length===0)return{valid:!1,error:"至少需要一个场景"};for(const o of n){if(o.duration<a)return{valid:!1,error:`场景 ${o.order} 时长不能少于 ${a} 秒`};if(o.duration>s)return{valid:!1,error:`场景 ${o.order} 时长不能超过 ${s} 秒`}}const d=n.find(o=>!o.prompt.trim());return d?{valid:!1,error:`场景 ${d.order} 需要填写提示词`}:{valid:!0}}function _n(n){return n.sort((s,a)=>s.order-a.order).map((s,a)=>`Shot ${a+1}:
|
|
3
|
-
duration: ${s.duration}sec
|
|
4
|
-
Scene: ${s.prompt.trim()}`).join(`
|
|
5
|
-
|
|
6
|
-
`)}function Tn(n){const s=/Shot\s+(\d+):\s*\n\s*duration:\s*([\d.]+)\s*sec\s*\n\s*Scene:\s*([^\n]+(?:\n(?!Shot\s+\d+:)[^\n]*)*)/gi,a=[];let d;for(;(d=s.exec(n))!==null;){const o=parseInt(d[1],10),u=parseFloat(d[2]),v=d[3].trim();a.push({id:Ss(),order:o,duration:u,prompt:v})}return a.length===0?null:a.sort((o,u)=>o.order-u.order)}const En=({value:n,onChange:s,placeholder:a,disabled:d=!1,autoFocus:o=!1,enableMention:u=!0})=>{const{mentionState:v,textareaRef:_,handleTextChange:M,handleKeyDown:i,handleCharacterSelect:h,closeMentionPopup:D}=ys({enabled:u,onPromptChange:s,prompt:n}),V=e.useCallback(f=>{const C=f.target.value,N=f.target.selectionStart||0;M(C,N)},[M]);return e.useEffect(()=>{o&&_.current&&_.current.focus()},[o,_]),t.jsxs("div",{className:"scene-prompt-input",children:[t.jsx("textarea",{ref:_,className:"scene-prompt-input__textarea",value:n,onChange:V,onKeyDown:i,placeholder:a,disabled:d,rows:3}),u&&t.jsx(Is,{visible:v.visible,query:v.query,position:v.position,showBelow:v.showBelow,selectedIndex:v.selectedIndex,onSelect:h,onClose:D})]})},kn=({enabled:n,onEnabledChange:s,totalDuration:a,maxScenes:d,minSceneDuration:o,scenes:u,onScenesChange:v,disabled:_=!1})=>{const[M,i]=e.useState(null),h=e.useRef(null),D=u.map(l=>l.id).join("|");e.useEffect(()=>{if(!n||u.length===0)return;!(M?u.some(w=>w.id===M):!1)&&M!==u[0].id&&i(u[0].id)},[n,D,u,M]);const V=e.useCallback(()=>{if(u.length>=d)return;const l=u.reduce((L,R)=>L+R.duration,0),w=a-l;let j=Math.max(o,w/2);j=parseFloat(j.toFixed(1)),j<o&&(j=o);const I=Jt(u.length+1,j);v([...u,I]),i(I.id),setTimeout(()=>{var L;(L=h.current)==null||L.scrollIntoView({behavior:"smooth"})},100)},[u,d,a,o,v]),f=e.useCallback(l=>{var I;if(u.length<=1)return;const j=u.filter(L=>L.id!==l).map((L,R)=>({...L,order:R+1}));v(j),M===l&&i(((I=j[0])==null?void 0:I.id)||null)},[u,v,M]),C=e.useCallback(l=>{const w=u.filter(j=>j.id!==l).reduce((j,I)=>j+I.duration,0);return Math.max(o,a-w)},[u,a,o]),N=e.useCallback(l=>{const w=C(l),j=[],I=.1;for(let L=o;L<=w+.001;L+=I){const R=parseFloat(L.toFixed(1));R<=w&&j.push({label:`${R}`,value:R})}return j},[o,C]),y=e.useCallback((l,w)=>{const j=typeof w=="string"?parseFloat(w):w;if(isNaN(j))return;const I=C(l),L=u.map(R=>{if(R.id===l){const ee=Math.max(o,Math.min(j,I)),_e=parseFloat(ee.toFixed(1));return _e===R.duration?R:{...R,duration:_e}}return R});L.every((R,ee)=>R===u[ee])||v(L)},[u,o,C,v]),W=e.useCallback((l,w)=>{const j=u.find(L=>L.id===l);if((j==null?void 0:j.prompt)===w)return;const I=u.map(L=>L.id===l?{...L,prompt:w}:L);v(I)},[u,v]),Z=e.useCallback(l=>{if(s(l),l&&u.length===0){const w=Jt(1,a);v([w]),i(w.id)}},[u,a,s,v]),F=e.useCallback(l=>{i(l)},[]),Y=u.length<d;return t.jsxs("div",{className:"storyboard-editor",children:[t.jsxs("div",{className:"storyboard-editor__header",children:[t.jsxs("div",{className:"storyboard-editor__toggle",children:[t.jsx(Ls,{value:n,onChange:Z,disabled:_,size:"small"}),t.jsxs("div",{className:"storyboard-editor__title",children:[t.jsx("span",{className:"storyboard-editor__title-text",children:"故事场景模式"}),t.jsx("span",{className:"storyboard-editor__title-desc",children:"定义多个场景及其时长"})]})]}),n&&t.jsx("span",{className:"storyboard-editor__new-badge",children:"NEW"})]}),n&&t.jsxs("div",{className:"storyboard-editor__content",children:[t.jsxs("div",{className:"storyboard-editor__section-header",children:[t.jsx("span",{className:"storyboard-editor__section-title",children:"场景列表"}),t.jsxs("span",{className:"storyboard-editor__section-hint",children:["共 ",u.length," 个场景,已用 ",u.reduce((l,w)=>l+w.duration,0).toFixed(1)," 秒 / 总时长 ",a," 秒"]})]}),t.jsxs("div",{className:"storyboard-editor__scenes",children:[u.map((l,w)=>{const j=M===l.id,I=w===u.length-1;return t.jsxs("div",{className:`storyboard-editor__scene-wrapper ${j?"is-selected":""}`,children:[t.jsx("div",{className:`storyboard-editor__timeline-line ${I?"is-last":""}`}),t.jsx("div",{className:`storyboard-editor__timeline-node ${j?"is-selected":""}`,children:j?w+1:""}),!j&&t.jsxs("div",{className:"storyboard-editor__scene storyboard-editor__scene--compact",onClick:()=>F(l.id),children:[t.jsx("span",{className:"storyboard-editor__scene-index",children:w+1}),t.jsx("div",{className:"storyboard-editor__scene-preview",children:t.jsx("p",{className:"storyboard-editor__scene-preview-text",children:l.prompt||"暂无场景描述..."})}),t.jsxs("div",{className:"storyboard-editor__scene-duration-badge",children:[t.jsx(Nt,{size:"12px"}),t.jsxs("span",{children:[l.duration,"s"]})]}),t.jsx(ns,{className:"storyboard-editor__scene-arrow",size:"14px"})]}),j&&t.jsxs("div",{className:"storyboard-editor__scene storyboard-editor__scene--expanded",children:[t.jsxs("div",{className:"storyboard-editor__scene-header",children:[t.jsx("div",{className:"storyboard-editor__scene-info",children:t.jsxs("span",{className:"storyboard-editor__scene-label",children:[t.jsx("span",{className:"storyboard-editor__active-indicator"}),"场景 ",w+1]})}),t.jsxs("div",{className:"storyboard-editor__scene-controls",children:[t.jsx(Nt,{className:"storyboard-editor__time-icon"}),t.jsx($s,{value:parseFloat(l.duration.toFixed(1)),onChange:L=>y(l.id,L),disabled:_,className:"storyboard-editor__duration-select",size:"small",options:N(l.id),filterable:!0,creatable:!0,popupProps:{overlayClassName:"storyboard-editor__duration-popup"}}),u.length>1&&t.jsx(mt,{theme:"default",variant:"text",size:"small",icon:t.jsx(as,{}),onClick:L=>{L.stopPropagation(),f(l.id)},disabled:_,className:"storyboard-editor__scene-delete"})]})]}),t.jsx("div",{className:"storyboard-editor__scene-prompt",children:t.jsx(En,{value:l.prompt,onChange:L=>W(l.id,L),placeholder:`描述场景 ${w+1} 的内容,输入 @ 可引用角色`,disabled:_,autoFocus:!0,enableMention:!0})})]})]},l.id)}),t.jsx("div",{ref:h})]}),Y&&t.jsx(mt,{theme:"default",variant:"dashed",size:"medium",icon:t.jsx(Vs,{}),onClick:V,disabled:_,className:"storyboard-editor__add-btn",block:!0,children:"添加场景"})]})]})},Cs="aitu-dialog-task-list-width-",Pt=240,Mt=800,Pn=()=>{const n=Math.round(660);return Math.max(Pt,Math.min(Mt,n))},js=n=>{try{const s=localStorage.getItem(Cs+n);if(s){const a=parseInt(s,10);if(!isNaN(a)&&a>=Pt&&a<=Mt)return a}}catch{}return Pn()},Qt=(n,s)=>{try{localStorage.setItem(Cs+n,s.toString())}catch{}},_s=({isRightPanelVisible:n,onToggleRightPanel:s,onWidthChange:a,rightPanelWidth:d,minWidth:o=Pt,maxWidth:u=Mt,onResizeStart:v,onResizeEnd:_,language:M="zh",disabled:i=!1,storageKey:h="image"})=>{const[D,V]=e.useState(!1),f=e.useRef(0),C=e.useRef(0);e.useEffect(()=>(D?(document.body.style.userSelect="none",document.body.style.cursor="col-resize"):(document.body.style.userSelect="",document.body.style.cursor=""),()=>{document.body.style.userSelect="",document.body.style.cursor=""}),[D]);const N=e.useCallback(W=>{if(i||!n)return;W.preventDefault(),W.stopPropagation(),V(!0),f.current=W.clientX,C.current=d,v==null||v();const Z=Y=>{const l=f.current-Y.clientX,w=Math.max(o,Math.min(u,C.current+l));a(w)},F=()=>{V(!1),_==null||_(),C.current+(f.current-document.body.getBoundingClientRect().left),Qt(h,d),document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",F)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",F)},[i,n,d,o,u,a,v,_,h]);e.useEffect(()=>{!D&&n&&Qt(h,d)},[d,D,n,h]);const y=n?M==="zh"?"隐藏任务列表":"Hide Task List":M==="zh"?"显示任务列表":"Show Task List";return t.jsxs("div",{className:`resizable-divider ${D?"is-dragging":""} ${n?"":"is-collapsed"} ${i?"is-disabled":""}`,onMouseDown:N,children:[t.jsx("div",{className:"resizable-divider__bar"}),t.jsx(tt,{content:y,placement:"left",children:t.jsx("button",{type:"button",className:"resizable-divider__toggle",onClick:W=>{W.stopPropagation(),s()},"aria-label":y,children:n?t.jsx(ns,{size:"14px"}):t.jsx(Os,{size:"14px"})})})]})},Ts=({storageKey:n,language:s})=>{const[a,d]=e.useState(()=>{try{return localStorage.getItem(n)!=="false"}catch{return!0}}),o=e.useCallback(u=>{d(u);try{localStorage.setItem(n,String(u))}catch{}},[n]);return t.jsx(tt,{content:s==="zh"?"生成后自动插入画布":"Auto insert to canvas after generation",theme:"light",children:t.jsx(Us,{checked:a,onChange:o,className:"auto-insert-checkbox"})})};function jt(n){try{return localStorage.getItem(n)!=="false"}catch{return!0}}function Mn(n={}){const{taskType:s}=n,{tasks:a,isLoading:d}=Fs(),{retryTask:o,deleteTask:u}=Gs(),v=e.useMemo(()=>[...s?a.filter(h=>h.type===s):a].sort((h,D)=>D.createdAt-h.createdAt),[a,s]),_=e.useCallback(async()=>{},[]),M=e.useCallback(async()=>{if(Ws(),!await Rt.isAvailable())return;const h=await Rt.getAllTasks();h.length>0&&Ks.restoreTasks(h)},[]);return{tasks:v,isLoading:d,isLoadingMore:!1,hasMore:!1,totalCount:v.length,loadedCount:v.length,loadMore:_,refresh:M,retryTask:o,deleteTask:u}}const Es=({taskIds:n,taskType:s,onEditTask:a})=>{const{tasks:d,isLoading:o,isLoadingMore:u,hasMore:v,totalCount:_,loadedCount:M,loadMore:i,retryTask:h,deleteTask:D}=Mn({taskType:s}),{board:V,openDialog:f}=os(),[C,N]=e.useState(!1),[y,W]=e.useState(null),[Z,F]=e.useState(!1),[Y,l]=e.useState(0),[w,j]=e.useState("single"),[I,L]=e.useState(""),[R,ee]=e.useState(null),[_e,H]=e.useState(!1),X=e.useMemo(()=>d.filter(g=>g.status===Ge.FAILED).length,[d]),oe=e.useCallback(()=>{const g=d.filter(r=>r.status===Ge.FAILED);g.forEach(r=>D(r.id)),H(!1),Re.success(`已清除 ${g.length} 个失败任务`)},[d,D]),pe=(g,r)=>{var ae,E,je,be,de,O,le,xe,ve,Te,Ee;if(!r.trim())return!0;const S=r.toLowerCase().split(/\s+/).filter(Boolean),P={[Ge.PENDING]:"处理中",[Ge.PROCESSING]:"处理中",[Ge.COMPLETED]:"已完成",[Ge.FAILED]:"失败",[Ge.CANCELLED]:"已取消"},A=[],Q=(ae=g.params)!=null&&ae.params&&typeof g.params.params=="object"?g.params.params:null;A.push(((E=g.params)==null?void 0:E.prompt)??""),A.push(((je=g.params)==null?void 0:je.model)??""),A.push(g.id??""),A.push(P[g.status]??String(g.status)),(be=g.params)!=null&&be.batchId&&A.push(String(g.params.batchId)),(de=g.params)!=null&&de.batchIndex&&A.push(String(g.params.batchIndex)),(O=g.params)!=null&&O.batchTotal&&A.push(String(g.params.batchTotal)),typeof(Q==null?void 0:Q.model_name)=="string"&&A.push(Q.model_name),typeof(Q==null?void 0:Q.mode)=="string"&&A.push(Q.mode),typeof(Q==null?void 0:Q.klingAction2)=="string"&&A.push(Q.klingAction2),(le=g.result)!=null&&le.format&&A.push(String(g.result.format)),(xe=g.result)!=null&&xe.width&&((ve=g.result)!=null&&ve.height)?A.push(`${g.result.width}x${g.result.height}`):(Te=g.params)!=null&&Te.width&&((Ee=g.params)!=null&&Ee.height)&&A.push(`${g.params.width}x${g.params.height}`);const ne=A.join(" ").toLowerCase();return S.every(ke=>ne.includes(ke))},U=e.useMemo(()=>{let g=d;return n&&n.length>0&&(g=g.filter(r=>n.includes(r.id))),I.trim()&&(g=g.filter(r=>pe(r,I))),g.sort((r,S)=>S.createdAt-r.createdAt)},[d,n,I]),T=g=>{h(g)},q=g=>{W(g),N(!0)},k=()=>{y&&D(y),N(!1),W(null)},ge=async g=>{const r=d.find(P=>P.id===g);if(!r)return;const S=Qs(r);if(S.length!==0)try{const P=await Ys(S);P.openedCount>0&&P.downloadedCount===0?Re.success(P.openedCount>1?`已打开 ${P.openedCount} 个链接,请在新标签页下载`:"资源不支持直接下载,已打开链接"):Re.success(r.type===we.AUDIO?S.length>1?"多条音频已开始下载":"音频下载成功":S.length>1?"多图已开始下载":"下载成功")}catch(P){console.error("Download failed:",P),Re.error("下载失败,请稍后重试")}},se=async g=>{var S,P,A,Q;const r=d.find(ne=>ne.id===g);if(!((S=r==null?void 0:r.result)!=null&&S.url)&&!((A=(P=r==null?void 0:r.result)==null?void 0:P.urls)!=null&&A.length)||!V){console.warn("Cannot insert: task result or board not available"),Re.warning("无法插入:白板未就绪");return}try{if(r.type===we.IMAGE){const ne=(Q=r.result.urls)!=null&&Q.length?r.result.urls:[r.result.url];for(const ae of ne)await Xs(V,ae);Re.success(ne.length>1?"多图已插入到白板":"图片已插入到白板")}else r.type===we.VIDEO&&(await Js(V,r.result.url),Re.success("视频已插入到白板"))}catch(ne){console.error("Failed to insert to board:",ne),Re.error(`插入失败: ${ne instanceof Error?ne.message:"未知错误"}`)}},fe=g=>{var S,P,A,Q;const r=d.find(ne=>ne.id===g);if(!r){console.warn("Cannot edit: task not found");return}if(a){a(r);return}if(r.type===we.IMAGE){const ne={initialPrompt:r.params.prompt,initialWidth:r.params.width,initialHeight:r.params.height,initialImages:r.params.uploadedImages,initialResultUrl:(S=r.result)==null?void 0:S.url,initialResultUrls:(P=r.result)==null?void 0:P.urls};f(Ie.aiImageGeneration,ne)}else if(r.type===we.VIDEO){const ne={initialPrompt:r.params.prompt,initialDuration:typeof r.params.seconds=="string"?parseInt(r.params.seconds,10):r.params.seconds,initialModel:r.params.model,initialSize:r.params.size,initialImages:r.params.uploadedImages,initialResultUrl:(A=r.result)==null?void 0:A.url,initialResultUrls:(Q=r.result)==null?void 0:Q.urls};f(Ie.aiVideoGeneration,ne)}},Ne=g=>{const r=d.find(S=>S.id===g);r&&ee(r)},ue=e.useMemo(()=>{const g=new Set;return U.filter(r=>{var S,P,A,Q;return r.status!==Ge.COMPLETED||!((S=r.result)!=null&&S.url)&&!((A=(P=r.result)==null?void 0:P.urls)!=null&&A.length)||r.type!==we.IMAGE&&r.type!==we.VIDEO&&!(r.type===we.AUDIO&&((Q=r.result)==null?void 0:Q.resultKind)!=="lyrics")||g.has(r.id)?!1:(g.add(r.id),!0)})},[U]),{previewMediaItems:re,taskIdToPreviewConfig:ce}=e.useMemo(()=>{var S,P,A,Q,ne,ae;const g=[],r=new Map;for(const E of ue){const je=g.length,be=((S=E.result)==null?void 0:S.title)||E.params.title||((P=E.params.prompt)==null?void 0:P.substring(0,50))||"媒体预览";if(E.type===we.AUDIO){const O=((Q=(A=E.result)==null?void 0:A.clips)==null?void 0:Q.filter(ve=>!!ve.audioUrl).map((ve,Te)=>{var Ee,ke,Pe;return{id:ve.clipId||ve.id||`${E.id}-${Te}`,url:ve.audioUrl,type:"audio",title:ve.title||((Ee=E.result)!=null&&Ee.clips&&E.result.clips.length>1?`${be} (${Te+1}/${E.result.clips.length})`:be),posterUrl:ve.imageLargeUrl||ve.imageUrl||((ke=E.result)==null?void 0:ke.previewImageUrl),duration:typeof ve.duration=="number"?ve.duration:(Pe=E.result)==null?void 0:Pe.duration,prompt:E.params.prompt,tags:typeof E.params.tags=="string"?E.params.tags:void 0,artist:E.params.model||E.params.mv||"Aitu",album:"Aitu Generated"}}))??[],le=(ne=E.result.urls)!=null&&ne.length?E.result.urls:E.result.url?[E.result.url]:[],xe=O.length>0?O:le.map((ve,Te)=>{var Ee,ke;return{id:le.length>1?`${E.id}-${Te}`:E.id,url:ve,type:"audio",title:le.length>1?`${be} (${Te+1}/${le.length})`:be,posterUrl:(Ee=E.result)==null?void 0:Ee.previewImageUrl,duration:(ke=E.result)==null?void 0:ke.duration,prompt:E.params.prompt,tags:typeof E.params.tags=="string"?E.params.tags:void 0,artist:E.params.model||E.params.mv||"Aitu",album:"Aitu Generated"}});g.push(...xe)}else{const O=(ae=E.result.urls)!=null&&ae.length?E.result.urls:[E.result.url],le=E.type===we.VIDEO?"video":"image";for(let xe=0;xe<O.length;xe++)g.push({id:O.length>1?`${E.id}-${xe}`:E.id,url:le==="image"?Bs(O[xe]):O[xe],type:le,title:O.length>1?`${be} (${xe+1}/${O.length})`:be})}const de=g.length-je;r.set(E.id,{mode:E.type===we.AUDIO&&de>1?"compare":"single",index:E.type===we.AUDIO&&de>1?Array.from({length:Math.min(de,4)},(O,le)=>je+le):je})}return{previewMediaItems:g,taskIdToPreviewConfig:r}},[ue]),m=e.useCallback(g=>{const r=ce.get(g);r!==void 0&&(j(r.mode),l(r.index),F(!0))},[ce]),G=e.useCallback(()=>{F(!1)},[]),J=I.trim()&&U.length===0&&d.length>0,Ce=_>0?_:d.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dialog-task-list",children:[t.jsxs("div",{className:"dialog-task-list__header",children:[t.jsxs("div",{className:"dialog-task-list__header-main",children:[t.jsxs("h4",{children:["生成任务 (",Ce,")"]}),t.jsx("div",{className:"dialog-task-list__header-actions",children:X>0&&t.jsx(tt,{content:`清除全部失败任务 (${X})`,theme:"light",children:t.jsx(mt,{size:"small",variant:"text",icon:t.jsx(as,{}),onClick:()=>H(!0)})})})]}),t.jsx("div",{className:"dialog-task-list__search",children:t.jsx(qs,{value:I,onChange:g=>L(g),placeholder:"搜索任务(提示词/模型/...)",clearable:!0,prefixIcon:t.jsx(Hs,{}),size:"small"})})]}),t.jsx(gn,{tasks:U,onRetry:T,onDelete:q,onDownload:ge,onInsert:se,onEdit:fe,onPreviewOpen:m,onExtractCharacter:Ne,hasMore:v,isLoadingMore:u,onLoadMore:i,totalCount:Ce,loadedCount:M,className:"dialog-task-list__content",emptyContent:t.jsx("div",{className:"dialog-task-list__empty",children:o?t.jsx("p",{children:"加载中..."}):J?t.jsx("p",{children:"未找到匹配的任务"}):t.jsx("p",{children:"暂无生成任务"})})})]}),t.jsx(At,{open:C,title:"确认删除",description:"确定要删除此任务吗?此操作无法撤销。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:N,onConfirm:k}),t.jsx(At,{open:_e,title:"清除失败任务",description:`确定要清除全部 ${X} 个失败任务吗?此操作无法撤销。`,confirmText:"清除",cancelText:"取消",danger:!0,onOpenChange:H,onConfirm:oe}),t.jsx(fn,{visible:Z,items:re,initialMode:w,initialIndex:Y,onClose:G,showThumbnails:!0}),t.jsx(bn,{visible:!!R,task:R,onClose:()=>ee(null),onCreateComplete:g=>{ee(null)}})]})};function ks(n){if(!n)return;if(n==="auto")return st;const s=n.replace(/[xX]/g,":");return tn.some(a=>a.value===s)?s:void 0}function dt(n,s){return ks(n.size)||s||st}function Yt(n,s,a){if(n.startsWith("mj")||!a)return s;const d=a===st?"auto":Ct(a);return!d||!en(n).some(o=>o.value===d)||s.size===d?s:{...s,size:d}}const Nn=({initialPrompt:n="",initialImages:s=[],initialKnowledgeContextRefs:a=[],selectedElementIds:d=[],initialWidth:o,initialHeight:u,initialResultUrl:v,initialAspectRatio:_,targetFrameId:M,targetFrameDimensions:i,pptSlideImage:h,pptSlidePrompt:D,pptReplaceElementId:V,selectedModel:f,selectedModelRef:C,onModelChange:N,onModelRefChange:y,externalBatchId:W,assetMetadata:Z,initialAutoInsertToCanvas:F,onDraftChange:Y}={})=>{var Ye,Ze,rt;const l=ms("image"),w=qe("image"),j=Ve(l,w.modelId,ze(w.profileId,w.modelId))||pt("image",w.modelId,ze(w.profileId,w.modelId)),[I,L]=e.useState((j==null?void 0:j.id)||((Ye=l[0])==null?void 0:Ye.id)||"gemini-2.5-flash-image-vip"),[R,ee]=e.useState(Ae(j)||ze(w.profileId,w.modelId)),_e=Se((j==null?void 0:j.id)||((Ze=l[0])==null?void 0:Ze.id)||"gemini-2.5-flash-image-vip",Ae(j)||ze(w.profileId,w.modelId)),H=Bt((j==null?void 0:j.id)||((rt=l[0])==null?void 0:rt.id)||"gemini-2.5-flash-image-vip",_e),[X,oe]=e.useState(n),[pe,U]=e.useState(a),[T,q]=e.useState(H.extraParams),k=e.useMemo(()=>{if(Ve(l,I,R)||!I)return l;const $=pt("image",I,R);return $?[$,...l]:l},[I,R,l]),[ge,se]=e.useState(o||1024),[fe,Ne]=e.useState(u||1024),[ue,re]=e.useState(_||dt(H.extraParams,H.aspectRatio)),[ce,m]=e.useState(null),[G,J]=e.useState(s),[Ce,g]=e.useState(!0),[r,S]=e.useState(()=>js("image")),[P,A]=e.useState("config"),Q=e.useRef(null),{viewportWidth:ne}=Tt(),ae=ne<=768,{imageHistory:E}=kt(),[je,be]=e.useState(0),{isGenerating:de}=bs("image"),{language:O}=Et(),{createTask:le}=rs(),xe=e.useRef(!1);e.useEffect(()=>Be.subscribeChanges(()=>{be(x=>x+1)}),[]);const ve=I.startsWith("mj"),Te=he.useMemo(()=>Zs(I).length>0,[I]),[Ee,ke]=e.useState(!1);e.useEffect(()=>{if(Ee)return;const x=Bt(I,Se(I,R)),$=_?Yt(I,x.extraParams,_):x.extraParams;q($),re(dt($,_||x.aspectRatio))},[I,R,_,Ee]);const Pe=e.useCallback((x,$)=>{if(!$||$==="default"){x==="size"&&re(st),q(B=>{const K={...B};return delete K[x],K});return}x==="size"&&re(ks($)||st),q(B=>({...B,[x]:$}))},[]),ft=e.useCallback(x=>{S(x)},[]),ht=e.useCallback(()=>{g(x=>!x)},[]),ie=he.useRef("");e.useEffect(()=>{if(Ee)return;const x=JSON.stringify({prompt:n,images:s==null?void 0:s.map($=>$.url),knowledgeContextRefs:a.map($=>$.noteId),elementIds:d,width:o,height:u,result:v,aspectRatio:_,targetFrameId:M,pptSlideImage:h,pptSlidePrompt:D,pptReplaceElementId:V});ie.current!==x&&(ie.current=x,oe(n),U(a),J(s||[]),o&&se(o),u&&Ne(u),_&&(re(_),q($=>Yt(I,$,_))))},[n,s,a,d,o,u,v,_,M,h,D,V,Ee,I]);const He=e.useRef("");e.useEffect(()=>{if(!Y)return;const x={prompt:X,images:G.map(K=>({url:K.url,name:K.name})),aspectRatio:ue},$=JSON.stringify(x);if(He.current===$)return;const B=window.setTimeout(()=>{He.current!==$&&(He.current=$,Y(x))},200);return()=>{window.clearTimeout(B)}},[ue,Y,X,G]),e.useEffect(()=>{const x=$=>{var K;const B=$.imageModelName||((K=k[0])==null?void 0:K.id)||"gemini-2.5-flash-image-vip";if(B!==I){L(B);const Me=Ve(k,B,R);ee(Ae(Me)||null)}};return De.addListener(x),()=>De.removeListener(x)},[I,R,k]),e.useEffect(()=>{if(k.length===0)return;if(!Ve(k,I,R)){const $=k[0];L($.id);const B=Ae($);ee(K=>K&&B&&K.profileId===B.profileId&&K.modelId===B.modelId?K:B)}},[I,R,k]),e.useEffect(()=>{if(!f)return;const x=Se(I,R),$=Se(f,C);if(x!==$){L(f);const B=Ve(k,f,C),K=Ae(B)||C||null;ee(Me=>Me&&K&&Me.profileId===K.profileId&&Me.modelId===K.modelId?Me:K)}},[I,R,f,C,k]),e.useEffect(()=>{!Te&&Object.keys(T).length>0&&q({})},[Te,T]),e.useEffect(()=>{xn({currentModel:I,currentSelectionKey:Se(I,R),extraParams:T,aspectRatio:ue})},[I,R,T,ue]),e.useEffect(()=>(m(null),()=>{m(null)}),[]);const Xe=()=>{const x=It(I,{});oe(""),q(x),J([]),m(null),re(dt(x)),A("config"),ke(!1),window.dispatchEvent(new CustomEvent("ai-image-clear"))},nt=he.useMemo(()=>cs("image",O,E),[E,O,je]),at=!!(h||D!=null&&D.trim()),Oe=x=>{at||(ds("image",x),be($=>$+1))},ot=x=>{const $=x.params.model||I,B={...x.params.params||{},...x.params.size!==void 0?{size:x.params.size}:{},...x.params.resolution!==void 0?{resolution:x.params.resolution}:{},...x.params.quality!==void 0?{quality:x.params.quality}:{}},K=Object.keys(B).length>0?It($,B):It($,{});if(ke(!0),A("config"),oe(x.params.prompt||""),q(K),se(x.params.width||1024),Ne(x.params.height||1024),x.params.uploadedImages&&x.params.uploadedImages.length>0?J(x.params.uploadedImages):J([]),x.params.model){L(x.params.model),ee(x.params.modelRef||null);const Me=De.get();De.update({...Me,imageModelName:x.params.model})}re(dt(K,x.params.aspectRatio)),m(null)},Je=async()=>Promise.all(G.map(async x=>{if(x.file)return new Promise(($,B)=>{const K=new FileReader;K.onload=()=>{$({type:"url",url:K.result,name:x.name})},K.onerror=B,K.readAsDataURL(x.file)});if(x.url)return{type:"url",url:x.url,name:x.name};throw new Error("Invalid image data")})),Qe=async(x=1)=>{const $=x;if(!xe.current){xe.current=!0;try{if(!X||!X.trim()){m(O==="zh"?"请输入图像描述":"Please enter image description");return}if(!sn("image",R||I)&&!await nn()){m(O==="zh"?"需要 API Key 才能生成图片":"API Key is required to generate images");return}ve&&m(null);try{const B=typeof ge=="string"?parseInt(ge)||1024:ge,K=typeof fe=="string"?parseInt(fe)||1024:fe,Me=await Je();if($>1){const c=[],p=`batch_${Date.now()}`,b=I||qe("image").modelId,z=b.startsWith("mj")?[X.trim(),Ht(T)].filter(Boolean).join(" "):(X||"").trim(),te=!b.startsWith("mj")&&Object.keys(T).length>0?T:void 0,me=te!=null&&te.size?te.size:Ct(ue);for(let ye=0;ye<$;ye++){const Ue={prompt:z,knowledgeContextRefs:pe,width:B,height:K,aspectRatio:ue,size:me,model:b,modelRef:R||null,uploadedImages:Me,batchId:p,batchIndex:ye+1,batchTotal:$,assetMetadata:Z,autoInsertToCanvas:F??jt(et.AI_IMAGE_AUTO_INSERT),targetFrameId:M,targetFrameDimensions:i,pptSlideImage:h,pptSlidePrompt:D,pptReplaceElementId:V,...te?{params:te}:{}},Fe=le(Ue,we.IMAGE);Fe&&c.push(Fe.id)}c.length>0?(Re.success(O==="zh"?`已添加 ${c.length} 个任务到队列`:`Added ${c.length} tasks to queue`),Oe(z),m(null),A("tasks"),ke(!1)):m(O==="zh"?"批量任务创建失败,请稍后重试":"Failed to create batch tasks, please try again later");return}const We=I||qe("image").modelId,it=We.startsWith("mj")?[X.trim(),Ht(T)].filter(Boolean).join(" "):(X||"").trim(),Le=!We.startsWith("mj")&&Object.keys(T).length>0?T:void 0,lt=Le!=null&&Le.size?Le.size:Ct(ue),ct={prompt:it,knowledgeContextRefs:pe,width:B,height:K,aspectRatio:ue,size:lt,model:We,modelRef:R||null,uploadedImages:Me,autoInsertToCanvas:F??jt(et.AI_IMAGE_AUTO_INSERT),batchId:W||`image_single_${Date.now()}`,batchIndex:1,batchTotal:1,assetMetadata:Z,targetFrameId:M,targetFrameDimensions:i,pptSlideImage:h,pptSlidePrompt:D,pptReplaceElementId:V,...Le?{params:Le}:{}};le(ct,we.IMAGE)?(Re.success(O==="zh"?"任务已添加到队列,将在后台生成":"Task added to queue, will be generated in background"),Oe(it),m(null),A("tasks"),ke(!1)):m(O==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later")}catch(B){console.error("Failed to create task:",B);let K=O==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later";B.message&&(B.message.includes("exceed 5000 characters")?K=O==="zh"?"提示词不能超过 5000 字符":"Prompt must not exceed 5000 characters":B.message.includes("Duplicate submission")?K=O==="zh"?"请勿重复提交,请等待 5 秒后再试":"Duplicate submission. Please wait 5 seconds.":B.message.includes("Invalid parameters")&&(K=O==="zh"?`参数错误: ${B.message.replace("Invalid parameters: ","")}`:B.message)),m(K)}}finally{xe.current=!1}}};return gs(de,X,()=>Qe(1)),t.jsxs("div",{className:"ai-image-generation-container",children:[ae?t.jsxs("div",{className:"ai-generation-mobile-switcher",role:"tablist",children:[t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${P==="config"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>A("config"),children:"生成设置"}),t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${P==="tasks"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>A("tasks"),children:"生成任务"})]}):null,t.jsxs("div",{className:`main-content ${ae?"main-content--mobile-panels":""}`,ref:Q,children:[t.jsxs("div",{className:`ai-image-generation-section ${ae&&P!=="config"?"ai-generation-mobile-panel--hidden":""}`,children:[t.jsxs("div",{className:"ai-image-generation-form",children:[f!==void 0&&N&&t.jsx("div",{className:"form-header-row",children:t.jsx("div",{className:"model-selector-wrapper",children:t.jsx(is,{selectedModel:I,selectedSelectionKey:Se(I,R),onSelect:x=>{L(x),ee(null),N(x),y==null||y(null)},onSelectModel:x=>{L(x.id);const $=Ae(x);ee($),N(x.id),y==null||y($)},language:O,models:k,placement:"down",variant:"form",disabled:de})})}),Te&&t.jsx("div",{className:"model-params-row",children:t.jsx(us,{selectedParams:T,onParamChange:Pe,modelId:I,language:O,disabled:de,placement:"down"})}),t.jsx(hs,{images:G,onImagesChange:J,language:O,disabled:de,multiple:!0,label:O==="zh"?"参考图片 (可选)":"Reference Images (Optional)",onError:m}),t.jsx(ws,{prompt:X,onPromptChange:oe,presetPrompts:nt,language:O,type:"image",disabled:de,onError:m}),t.jsx(ps,{value:pe,onChange:U,disabled:de,language:O}),t.jsx(vs,{error:ce})]}),t.jsx(xs,{language:O,type:"image",isGenerating:de,hasGenerated:!1,canGenerate:!!(X&&X.trim()),onGenerate:Qe,onReset:Xe,leftContent:t.jsx(Ts,{storageKey:et.AI_IMAGE_AUTO_INSERT,language:O})})]}),ae?null:t.jsx(_s,{isRightPanelVisible:Ce,onToggleRightPanel:ht,onWidthChange:ft,rightPanelWidth:r,language:O,storageKey:"image"}),(ae||Ce)&&t.jsx("div",{className:`task-sidebar ${ae?"task-sidebar--mobile-panel":""} ${ae&&P!=="tasks"?"ai-generation-mobile-panel--hidden":""}`,style:ae?void 0:{width:r,flexShrink:0},children:t.jsx(Es,{taskType:we.IMAGE,onEditTask:ot})})]})]})};function Zt(n,s){const a=Object.keys(n),d=Object.keys(s);return a.length!==d.length?!1:a.every(o=>n[o]===s[o])}function es(n,s,a){return n.slice(0,s).map((d,o)=>({...d,slot:o,slotLabel:a[o]||`参考图${o+1}`}))}function Rn(n,s){return n.length===s.length&&n.every((a,d)=>{const o=s[d];return a.slot===o.slot&&a.slotLabel===o.slotLabel&&a.url===o.url&&a.name===o.name&&a.file===o.file})}function wt(n,s){return((n==null?void 0:n.profileId)||null)===((s==null?void 0:s.profileId)||null)&&((n==null?void 0:n.modelId)||null)===((s==null?void 0:s.modelId)||null)}function Ps(n,s){const a=ze(s==null?void 0:s.profileId,s==null?void 0:s.modelId);return(a==null?void 0:a.modelId)===(n||null)?a:null}function Ke(n,s,a){if(!s)return null;const d=Ps(s,a),o=Ve(n,s,d);return Ae(o)||d}function An(n){return n.reduce((s,a)=>(a.defaultValue&&(s[a.id]=a.defaultValue),s),{})}function St(n,s){return An(ls(n,s||n,{}))}function ut(n,s,a){return{...n,...s!=null?{duration:String(s)}:{},...a?{size:a}:{}}}function ts(n,s,a){const{duration:d,size:o,...u}=n;return{extraParams:u,duration:s,size:a}}const zn=({initialPrompt:n="",initialImage:s,initialImages:a,initialKnowledgeContextRefs:d=[],initialDuration:o,initialModel:u,initialSize:v,initialResultUrl:_,selectedModel:M,selectedModelRef:i,onModelChange:h,onModelRefChange:D,externalBatchId:V,initialAutoInsertToCanvas:f,onDraftChange:C}={})=>{var lt,ct,gt;const N=ms("video"),[y,W]=e.useState(n),[Z,F]=e.useState(d),[Y,l]=e.useState(null),[w,j]=e.useState(!0),[I,L]=e.useState(()=>js("video")),[R,ee]=e.useState("config"),_e=e.useRef(null),{viewportWidth:H}=Tt(),X=H<=768,oe=qe("video"),pe=u||oe.modelId,U=Ps(pe,u&&u===M?i:oe.modelId===pe?ze(oe.profileId,oe.modelId):null),T=Ve(N,pe,U)||pt("video",pe,U),q=Ke(N,(T==null?void 0:T.id)||pe,Ae(T)||U),[k,ge]=e.useState((T==null?void 0:T.id)||((lt=N[0])==null?void 0:lt.id)||xt("veo3")),[se,fe]=e.useState(q),Ne=Se((T==null?void 0:T.id)||((ct=N[0])==null?void 0:ct.id)||xt("veo3"),q),ue=qt((T==null?void 0:T.id)||((gt=N[0])==null?void 0:gt.id)||xt("veo3"),Ne),re=he.useMemo(()=>{if(Ve(N,k,se)||!k)return N;const p=pt("video",k,se);return p?[p,...N]:N},[k,se,N]),[ce,m]=e.useState(()=>ut(ue.extraParams,(o==null?void 0:o.toString())||ue.duration,v||ue.size)),G=he.useMemo(()=>ls(k,se||k,ce),[k,se,ce]),J=he.useMemo(()=>zt(k,se||k,ce),[k,se,ce]),Ce=he.useMemo(()=>(J.imageUpload.labels||[]).join("|"),[J.imageUpload.labels]),g=he.useMemo(()=>Ce?Ce.split("|"):[],[Ce]),r=he.useMemo(()=>({maxCount:J.imageUpload.maxCount,mode:J.imageUpload.mode,required:J.imageUpload.required,labels:g,labelsSignature:Ce}),[J.imageUpload.maxCount,J.imageUpload.mode,J.imageUpload.required,g,Ce]),S=he.useMemo(()=>{var b;const c=G.find(z=>z.id==="duration"),p=ce.duration;return p&&((b=c==null?void 0:c.options)!=null&&b.some(z=>z.value===p))?p:(c==null?void 0:c.defaultValue)||J.defaultDuration},[G,J.defaultDuration,ce.duration]),P=he.useMemo(()=>{var b;const c=G.find(z=>z.id==="size"),p=ce.size;return p&&((b=c==null?void 0:c.options)!=null&&b.some(z=>z.value===p))?p:(c==null?void 0:c.defaultValue)||J.defaultSize},[G,J.defaultSize,ce.size]),A=he.useMemo(()=>G.length>0,[G]),Q=e.useCallback((c,p)=>{if(!p||p==="default"){m(b=>{const z={...b};return delete z[c],z});return}m(b=>({...b,[c]:p}))},[]);e.useEffect(()=>{const c=G.reduce((p,b)=>{const z=ce[b.id],te=!z||b.valueType!=="enum"||!b.options||b.options.some(me=>me.value===z);return z&&te?p[b.id]=z:b.defaultValue&&(p[b.id]=b.defaultValue),p},{});Zt(ce,c)||m(c)},[G,ce]);const[ne,ae]=e.useState(()=>a&&a.length>0?a:s?[{slot:0,slotLabel:"参考图",url:s.url||"",name:s.name,file:s.file}]:[]),[E,je]=e.useState(()=>{const c=J.imageUpload.maxCount,p=J.imageUpload.labels||[];let b=[];return a&&a.length>0?b=a:s&&(b=[{slot:0,slotLabel:p[0]||"参考图",url:s.url||"",name:s.name,file:s.file}]),b.slice(0,c).map((z,te)=>({...z,slot:te,slotLabel:p[te]||`参考图${te+1}`}))}),[be,de]=e.useState(!1),[O,le]=e.useState([]),xe=he.useMemo(()=>an(k),[k]),ve=Dt(k),{videoHistory:Te}=kt(),[Ee,ke]=e.useState(0);e.useEffect(()=>Be.subscribeChanges(()=>{ke(c=>c+1)}),[]);const{isGenerating:Pe}=bs("video"),ft=e.useCallback(c=>{L(c)},[]),ht=e.useCallback(()=>{j(c=>!c)},[]),{language:ie}=Et(),{createTask:He}=rs(),Xe=e.useRef(!1),nt=M!==void 0,at=he.useRef(null),Oe=he.useRef(null);e.useEffect(()=>{if(nt)return;const c=p=>{const b=p.videoModelName||"veo3";if(b!==k){ge(b);const z=Ke(re,b,se);fe(z)}};return De.addListener(c),()=>De.removeListener(c)},[k,se,nt,M,i,re]),e.useEffect(()=>{if(re.length===0)return;const c=Ve(re,k,se),p=Ke(re,k,se);if(!c){const b=re[0],z=Ae(b);ge(b.id),fe(te=>wt(te,z)?te:z);return}fe(b=>wt(b,p)?b:p)},[k,se,re]),e.useEffect(()=>{if(!M)return;const c=Se(M,i);if(at.current===c||Oe.current&&Oe.current!==M)return;at.current=c,ge(b=>b===M?b:M);const p=Ke(re,M,i);fe(b=>wt(b,p)?b:p)},[M,i,re,u]);const[ot,Je]=e.useState(!1),[Qe,Ye]=e.useState(!1);e.useEffect(()=>{if(Qe){Ye(!1);return}const c=qt(k,Se(k,se)),p=ut(c.extraParams,o!==void 0?o.toString():c.duration,v||c.size);m(b=>Zt(b,p)?b:p),Dt(k)||(de(b=>b&&!1),le(b=>b.length>0?[]:b))},[k,se,Qe,o,v]),e.useEffect(()=>{const c=ne.length>0?es(ne,r.maxCount,r.labels):[];je(p=>Rn(p,c)?p:c)},[ne,r.labels,r.labelsSignature,r.maxCount]),e.useEffect(()=>{const c=ts(ce,S,P);vn({currentModel:k,currentSelectionKey:Se(k,se),extraParams:c.extraParams,duration:c.duration,size:c.size})},[k,se,S,P,ce]);const Ze=he.useRef("");e.useEffect(()=>{if(ot)return;const c=JSON.stringify({prompt:n,image:s==null?void 0:s.url,images:a==null?void 0:a.map(z=>z.url),knowledgeContextRefs:d.map(z=>z.noteId),duration:o,model:u,size:v,result:_});if(Ze.current===c)return;Ze.current=c,u&&(Oe.current=u,ge(u),fe(Ke(N,u,i))),W(n),F(d);let p=[];a&&a.length>0?p=a:s&&(p=[{slot:0,slotLabel:"参考图",url:s.url||"",name:s.name,file:s.file}]),ae(p);const b=es(p,r.maxCount,r.labels);je(b),(o!==void 0||v)&&m(z=>ut(z,o,v)),l(null)},[n,s,a,d,o,v,_,r.labels,r.labelsSignature,r.maxCount,ot]),e.useEffect(()=>(l(null),()=>{l(null)}),[]);const rt=()=>{W(""),ae([]),je([]),l(null),ee("config"),Je(!1),de(!1),le([]),m(St(k,se||k)),window.dispatchEvent(new CustomEvent("ai-video-clear"))},x=he.useCallback((c,p)=>c.map((b,z)=>({slot:z,slotLabel:p[z]||`参考图${z+1}`,url:b.url,name:b.name,file:b.file})),[]),$=he.useCallback(c=>c.map(p=>({url:p.url,name:p.name,file:p.file})),[]),B=he.useCallback(c=>{const p=x(c,r.labels);je(p),ae(p)},[r.labels,x]),K=he.useMemo(()=>cs("video",ie,Te),[Te,ie,Ee]),Me=c=>{ds("video",c),ke(p=>p+1)},We=e.useRef("");e.useEffect(()=>{if(!C)return;const c=Number.parseFloat(S),p={prompt:y,images:E.map(te=>({url:te.url,name:te.name})),duration:Number.isFinite(c)?c:void 0,size:P||void 0},b=JSON.stringify(p);if(We.current===b)return;const z=window.setTimeout(()=>{We.current!==b&&(We.current=b,C(p))},200);return()=>{window.clearTimeout(z)}},[S,P,C,y,E]);const it=c=>{var b,z;if(Je(!0),ee("config"),Ye(!0),c.params.model){ge(c.params.model),fe(c.params.modelRef||null);const te=De.get();De.update({...te,videoModelName:c.params.model})}if((b=c.params.storyboard)!=null&&b.enabled&&((z=c.params.storyboard)!=null&&z.scenes))de(!0),le(c.params.storyboard.scenes),W("");else{const te=c.params.prompt||"",me=Tn(te);me&&me.length>0?(de(!0),le(me),W("")):(de(!1),le([]),W(te))}const p=c.params.params&&typeof c.params.params=="object"?Object.entries(c.params.params).reduce((te,[me,ye])=>(ye!=null&&String(ye).trim()&&(te[me]=String(ye)),te),{}):{};if(m(ut(p,c.params.duration??c.params.seconds,c.params.size)),c.params.uploadedImages&&c.params.uploadedImages.length>0){ae(c.params.uploadedImages);const te=c.params.model||k,me=zt(te,c.params.modelRef||te,p),ye=me.imageUpload.maxCount,Ue=me.imageUpload.labels||[],Fe=c.params.uploadedImages.slice(0,ye).map(($e,bt)=>({...$e,slot:bt,slotLabel:Ue[bt]||`参考图${bt+1}`}));je(Fe)}else ae([]),je([]);l(null)},Le=async(c=1)=>{if(!Xe.current){Xe.current=!0;try{if(be){const p=jn(O,parseFloat(S),xe.minSceneDuration);if(!p.valid){l(p.error||"场景配置无效");return}}else if(!y||!y.trim()){l(ie==="zh"?"请输入视频描述":"Please enter video description");return}if(r.required&&!E.some(p=>p.url||p.file)){l(ie==="zh"?"请上传模型所需的参考图片":"Please upload the required reference image");return}try{const p=[];for(const me of E)if(me.file){const ye=await new Promise((Ue,Fe)=>{const $e=new FileReader;$e.onload=()=>Ue($e.result),$e.onerror=Fe,$e.readAsDataURL(me.file)});p.push({...me,url:ye,file:void 0})}else p.push({...me,file:void 0});const b=be?_n(O):(y||"").trim(),z=[],te=V||`video_batch_${Date.now()}`;for(let me=0;me<c;me++){const ye=ts(ce,S,P),Ue=Object.keys(ye.extraParams).length>0?ye.extraParams:void 0,Fe={prompt:b,knowledgeContextRefs:Z,model:k,modelRef:se||null,seconds:ye.duration,size:ye.size,uploadedImages:p,...be&&{storyboard:{enabled:!0,scenes:O,totalDuration:parseFloat(S)}},batchId:te,batchIndex:me+1,batchTotal:c,autoInsertToCanvas:f??jt(et.AI_VIDEO_AUTO_INSERT),...Ue?{params:Ue}:{}},$e=He(Fe,we.VIDEO);$e&&z.push($e.id)}z.length>0?(Re.success(ie==="zh"?c>1?`${z.length} 个视频任务已添加到队列,将在后台生成`:"视频任务已添加到队列,将在后台生成":c>1?`${z.length} video tasks added to queue, will be generated in background`:"Video task added to queue, will be generated in background"),Me(b),W(""),ae([]),je([]),de(!1),le([]),l(null),ee("tasks"),Je(!1)):l(ie==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later")}catch(p){console.error("Failed to create task:",p);let b=ie==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later";p.message&&(p.message.includes("exceed 5000 characters")?b=ie==="zh"?"提示词不能超过 5000 字符":"Prompt must not exceed 5000 characters":p.message.includes("Duplicate submission")?b=ie==="zh"?"请勿重复提交,请等待 5 秒后再试":"Duplicate submission. Please wait 5 seconds.":p.message.includes("Invalid parameters")&&(b=ie==="zh"?`参数错误: ${p.message.replace("Invalid parameters: ","")}`:p.message)),l(b)}}finally{Xe.current=!1}}};return gs(Pe,y,Le),t.jsxs("div",{className:"ai-video-generation-container",children:[X?t.jsxs("div",{className:"ai-generation-mobile-switcher",role:"tablist",children:[t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${R==="config"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>ee("config"),children:"生成设置"}),t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${R==="tasks"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>ee("tasks"),children:"生成任务"})]}):null,t.jsxs("div",{className:`main-content ${X?"main-content--mobile-panels":""}`,ref:_e,children:[t.jsxs("div",{className:`ai-image-generation-section ${X&&R!=="config"?"ai-generation-mobile-panel--hidden":""}`,children:[t.jsxs("div",{className:"ai-image-generation-form",children:[M!==void 0&&h&&t.jsx("div",{className:"form-header-row",children:t.jsx("div",{className:"model-selector-wrapper",children:t.jsx(is,{selectedModel:k,selectedSelectionKey:Se(k,se),onSelect:(c,p)=>{const b=c,z=Ke(re,b,p||null);Oe.current=null,ge(b),fe(z),m(St(b,z||b)),h(c),D==null||D(z)},onSelectModel:c=>{const p=c.id;Oe.current=null,ge(p);const b=Ke(re,p,Ae(c));fe(b),m(St(p,b||p)),h(c.id),D==null||D(b)},language:ie,models:re,placement:"down",variant:"form",placeholder:ie==="zh"?"选择视频模型":"Select Video Model",disabled:Pe})})}),A&&t.jsx("div",{className:"model-params-row",children:t.jsx(us,{selectedParams:ce,onParamChange:Q,compatibleParams:G,modelId:k,language:ie,disabled:Pe,placement:"down"})}),r.maxCount>0&&t.jsx(hs,{images:$(E),onImagesChange:B,language:ie,disabled:Pe,multiple:r.maxCount>1,maxCount:r.maxCount,slotLabels:r.mode==="frames"?r.labels:void 0,label:r.mode==="frames"?ie==="zh"?"首尾帧图片 (可选)":"Start/End Frames (Optional)":r.required?ie==="zh"?"参考图片":"Reference Images":ie==="zh"?"参考图片 (可选)":"Reference Images (Optional)"}),ve&&t.jsx(kn,{enabled:be,onEnabledChange:de,totalDuration:parseFloat(S),maxScenes:xe.maxScenes,minSceneDuration:xe.minSceneDuration,scenes:O,onScenesChange:le,disabled:Pe}),!be&&t.jsx(ws,{prompt:y,onPromptChange:W,presetPrompts:K,language:ie,type:"video",disabled:Pe,onError:l,videoProvider:J.provider}),t.jsx(ps,{value:Z,onChange:F,disabled:Pe,language:ie}),t.jsx(vs,{error:Y})]}),t.jsx(xs,{language:ie,type:"video",isGenerating:Pe,hasGenerated:!1,canGenerate:be?O.length>0:!!(y&&y.trim()),onGenerate:Le,onReset:rt,leftContent:t.jsx(Ts,{storageKey:et.AI_VIDEO_AUTO_INSERT,language:ie})})]}),X?null:t.jsx(_s,{isRightPanelVisible:w,onToggleRightPanel:ht,onWidthChange:ft,rightPanelWidth:I,language:ie,storageKey:"video"}),(X||w)&&t.jsx("div",{className:`task-sidebar ${X?"task-sidebar--mobile-panel":""} ${X&&R!=="tasks"?"ai-generation-mobile-panel--hidden":""}`,style:X?void 0:{width:I,flexShrink:0},children:t.jsx(Es,{taskType:we.VIDEO,onEditTask:it})})]})]})},Dn=e.lazy(()=>_t(()=>import("./batch-image-generation-Bo3h_Eop.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url)),Ln=e.lazy(()=>_t(()=>import("./mermaid-to-drawnix-oplawQO0.js"),__vite__mapDeps([0,5,2,1,3,6,7,8]),import.meta.url)),$n=e.lazy(()=>_t(()=>import("./markdown-to-drawnix-COS1iVyq.js"),__vite__mapDeps([0,5,2,1,3,6,7,8]),import.meta.url)),Vn=({container:n})=>{const{appState:s,openDialog:a,closeDialog:d}=os(),{language:o}=Et(),u=on(),{isMobile:v,isTablet:_}=Tt(),M=s.dialogInitialDataByType,i=(M==null?void 0:M[Ie.aiImageGeneration])??null,h=(M==null?void 0:M[Ie.aiVideoGeneration])??null,D=!v&&!_,V=e.useRef(!1),f=e.useRef(null),[C,N]=e.useState(""),[y,W]=e.useState(null),[Z,F]=e.useState(""),[Y,l]=e.useState(null),w=e.useRef(null),j=e.useRef(null),I=e.useCallback(()=>{const m=qe("image"),G=qe("video"),J=m.modelId||"gemini-3-pro-image-preview-vip",Ce=ze(m.profileId,J),g=G.modelId||"veo3",r=ze(G.profileId,g);N(S=>S===J?S:J),W(S=>Se(J,S)===Se(J,Ce)?S:Ce),F(S=>S===g?S:g),l(S=>Se(g,S)===Se(g,r)?S:r)},[]);e.useEffect(()=>{I()},[I]),e.useEffect(()=>{const m=()=>{I()};return De.addListener(m),Lt.addListener(m),()=>{De.removeListener(m),Lt.removeListener(m)}},[I]);const L=m=>{N(m)},R=m=>{F(m)},ee=m=>{W(m)},_e=m=>{l(m)};e.useEffect(()=>{if(!C)return;const m=Se(C,y);w.current!==m&&(w.current=m,$t("image",ze(y==null?void 0:y.profileId,C)))},[C,y]),e.useEffect(()=>{if(!Z)return;const m=Se(Z,Y);j.current!==m&&(j.current=m,$t("video",ze(Y==null?void 0:Y.profileId,Z)))},[Z,Y]);const[H,X]=e.useState({initialPrompt:"",initialImages:[],selectedElementIds:[]}),[oe,pe]=e.useState({initialPrompt:"",initialImage:void 0}),[U,T]=e.useState(!1),[q,k]=e.useState(()=>{try{return localStorage.getItem(vt)==="batch"?"batch":"single"}catch{return"single"}});e.useEffect(()=>{!D&&q==="batch"&&k("single")},[D,q]);const ge=e.useCallback(m=>{k(m),m==="batch"&&(T(!0),setTimeout(()=>T(!1),50));try{localStorage.setItem(vt,m)}catch(G){console.warn("Failed to save image mode:",G)}},[]);e.useEffect(()=>{if(s.openDialogTypes.has(Ie.aiImageGeneration)){if(H.initialImages&&H.initialImages.length>0||H.initialPrompt&&H.initialPrompt.trim()!==""){T(!1);return}try{localStorage.getItem(vt)==="batch"&&(T(!0),setTimeout(()=>T(!1),50))}catch{T(!1)}}},[s.openDialogTypes,H.initialImages,H.initialPrompt]);const se=e.useRef(!1),fe=e.useRef(i),Ne=e.useRef(!1),ue=e.useRef(h);e.useEffect(()=>{if(!u)return;const m=s.openDialogTypes.has(Ie.aiImageGeneration),G=m&&!se.current,J=fe.current!==i;if(se.current=m,fe.current=i,!m||!G&&!J||V.current)return;(async()=>{V.current=!0,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{console.warn("Processing timeout, resetting processing state"),V.current=!1},1e4);try{if(i){X({initialPrompt:i.initialPrompt||i.prompt||"",initialImages:i.initialImages||i.uploadedImages||[],selectedElementIds:[],initialResultUrl:i.initialResultUrl||i.resultUrl,initialAspectRatio:i.initialAspectRatio,targetFrameId:i.targetFrameId,targetFrameDimensions:i.targetFrameDimensions,pptSlideImage:i.pptSlideImage,pptSlidePrompt:i.pptSlidePrompt,pptReplaceElementId:i.pptReplaceElementId}),i.initialModel&&N(i.initialModel),i.initialModelRef!==void 0&&W(i.initialModelRef);return}const g=s.lastSelectedElementIds||[];let r,S,P;const A=rn(u);if(A.length===1&&ln(A[0])){const ae=A[0],E=cn.getRectangleByPoints(ae.points);r=dn(E.width,E.height),S=ae.id,P={width:E.width,height:E.height}}const Q=await Gt(u,g),ne=[];Q.remainingImages.forEach(ae=>{ne.push({url:ae.url,name:ae.name||`selected-image-${Date.now()}.png`})}),Q.graphicsImage&&ne.push({url:Q.graphicsImage,name:`graphics-combined-${Date.now()}.png`}),X({initialPrompt:Q.remainingText||"",initialImages:ne,selectedElementIds:g,initialAspectRatio:r,targetFrameId:S,targetFrameDimensions:P})}catch(g){console.warn("Error processing selected content for AI:",g);const r=Wt(u),S=r.images.map(P=>({url:P.url,name:P.name||`selected-image-${Date.now()}.png`}));X({initialPrompt:r.text||"",initialImages:S,selectedElementIds:[]})}finally{V.current=!1,f.current&&(clearTimeout(f.current),f.current=null)}})()},[s.lastSelectedElementIds,s.openDialogTypes,u,i]),e.useEffect(()=>{if(!u)return;const m=s.openDialogTypes.has(Ie.aiVideoGeneration),G=m&&!Ne.current,J=ue.current!==h;if(Ne.current=m,ue.current=h,!m||!G&&!J||V.current)return;(async()=>{V.current=!0,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{console.warn("Video processing timeout, resetting processing state"),V.current=!1},1e4);try{if(h){pe({initialPrompt:h.initialPrompt||h.prompt||"",initialImage:h.initialImage||h.uploadedImage,initialImages:h.initialImages||h.uploadedImages,initialDuration:h.initialDuration||h.duration,initialModel:h.initialModel||h.model,initialSize:h.initialSize||h.size,initialResultUrl:h.initialResultUrl||h.resultUrl});const P=h.initialModel||h.model;P&&F(P),h.initialModelRef!==void 0&&l(h.initialModelRef);return}const g=s.lastSelectedElementIds||[],r=await Gt(u,g),S=[];r.remainingImages.length>0?r.remainingImages.forEach((P,A)=>{S.push({url:P.url,name:P.name||`selected-image-${A+1}-${Date.now()}.png`})}):r.graphicsImage&&S.push({url:r.graphicsImage,name:`graphics-combined-${Date.now()}.png`}),pe({initialPrompt:r.remainingText||"",initialImage:S.length>0?S[0]:void 0,initialImages:S.map((P,A)=>({slot:A,slotLabel:`参考图${A+1}`,url:P.url,name:P.name}))})}catch(g){console.warn("Error processing selected content for AI video:",g);const r=Wt(u),S=r.images.map((P,A)=>({url:P.url,name:P.name||`selected-image-${A+1}-${Date.now()}.png`}));pe({initialPrompt:r.text||"",initialImage:S.length>0?S[0]:void 0,initialImages:S.map((P,A)=>({slot:A,slotLabel:`参考图${A+1}`,url:P.url,name:P.name}))})}finally{V.current=!1,f.current&&(clearTimeout(f.current),f.current=null)}})()},[s.lastSelectedElementIds,s.openDialogTypes,u,h]),e.useEffect(()=>{s.openDialogTypes.size===0&&(V.current=!1,se.current=!1,fe.current=null,Ne.current=!1,ue.current=null,f.current&&(clearTimeout(f.current),f.current=null))},[s.openDialogTypes]);const re=e.useCallback(()=>{const m=localStorage.getItem(Vt);if(m)try{const G=JSON.parse(m);G.timestamp=Date.now(),localStorage.setItem(Vt,JSON.stringify(G))}catch(G){console.warn("Failed to update cache timestamp:",G)}d(Ie.aiImageGeneration)},[d]),ce=e.useCallback(()=>{const m=localStorage.getItem(Ot);if(m)try{const G=JSON.parse(m);G.timestamp=Date.now(),localStorage.setItem(Ot,JSON.stringify(G))}catch(G){console.warn("Failed to update cache timestamp:",G)}d(Ie.aiVideoGeneration)},[d]);return t.jsxs(t.Fragment,{children:[t.jsx(Ut,{open:s.openDialogTypes.has(Ie.mermaidToDrawnix),onOpenChange:m=>{m?a(Ie.mermaidToDrawnix):d(Ie.mermaidToDrawnix)},children:t.jsx(Ft,{className:"Dialog ttd-dialog",container:n,children:t.jsx(e.Suspense,{fallback:null,children:t.jsx(Ln,{})})})}),t.jsx(Ut,{open:s.openDialogTypes.has(Ie.markdownToDrawnix),onOpenChange:m=>{m?a(Ie.markdownToDrawnix):d(Ie.markdownToDrawnix)},children:t.jsx(Ft,{className:"Dialog ttd-dialog",container:n,children:t.jsx(e.Suspense,{fallback:null,children:t.jsx($n,{})})})}),t.jsx(Kt,{id:"ai-image-dialog",visible:s.openDialogTypes.has(Ie.aiImageGeneration),title:q==="batch"?o==="zh"?"批量出图":"Batch Generation":o==="zh"?"AI 图片生成":"AI Image Generation",headerContent:D?t.jsxs("div",{className:"image-generation-mode-tabs",onMouseDown:m=>m.stopPropagation(),onTouchStart:m=>m.stopPropagation(),onPointerDown:m=>m.stopPropagation(),children:[t.jsx("button",{type:"button",className:`mode-tab ${q==="single"?"active":""}`,onClick:m=>{m.stopPropagation(),m.preventDefault(),ge("single")},children:o==="zh"?"AI 图片生成":"AI Image"}),t.jsx("button",{type:"button",className:`mode-tab ${q==="batch"?"active":""}`,onClick:m=>{m.stopPropagation(),m.preventDefault(),ge("batch")},children:o==="zh"?"批量出图":"Batch"})]}):void 0,onClose:re,width:"80%",height:"60%",minWidth:800,minHeight:500,x:"center",y:"center",modal:!1,minimizable:!1,className:"winbox-ai-generation winbox-ai-image-generation",container:n,autoMaximize:U||v,children:s.openDialogTypes.has(Ie.aiImageGeneration)&&(q==="batch"?t.jsx(e.Suspense,{fallback:t.jsx("div",{className:"loading-fallback",children:o==="zh"?"加载中...":"Loading..."}),children:t.jsx(Dn,{onSwitchToSingle:()=>ge("single"),selectedModel:C,selectedModelRef:y,onModelChange:L,onModelRefChange:ee})}):t.jsx(Nn,{initialPrompt:H.initialPrompt,initialImages:H.initialImages,initialKnowledgeContextRefs:(i==null?void 0:i.initialKnowledgeContextRefs)||(i==null?void 0:i.knowledgeContextRefs)||[],selectedElementIds:H.selectedElementIds,initialWidth:(i==null?void 0:i.initialWidth)||(i==null?void 0:i.width),initialHeight:(i==null?void 0:i.initialHeight)||(i==null?void 0:i.height),initialResultUrl:H.initialResultUrl,initialAspectRatio:H.initialAspectRatio,targetFrameId:H.targetFrameId,targetFrameDimensions:H.targetFrameDimensions,pptSlideImage:H.pptSlideImage,pptSlidePrompt:H.pptSlidePrompt,pptReplaceElementId:H.pptReplaceElementId,selectedModel:C,selectedModelRef:y,onModelChange:L,onModelRefChange:ee,externalBatchId:i==null?void 0:i.batchId,assetMetadata:i==null?void 0:i.assetMetadata,initialAutoInsertToCanvas:i==null?void 0:i.autoInsertToCanvas,onDraftChange:i==null?void 0:i.onDraftChange},(i==null?void 0:i.batchId)||"ai-image-dialog"))}),t.jsx(Kt,{id:"ai-video-dialog",visible:s.openDialogTypes.has(Ie.aiVideoGeneration),title:o==="zh"?"AI 视频生成":"AI Video Generation",onClose:ce,width:"70%",height:"60%",minWidth:800,minHeight:600,x:"center",y:"center",modal:!1,minimizable:!1,className:"winbox-ai-generation winbox-ai-video-generation",container:n,autoMaximize:v,children:s.openDialogTypes.has(Ie.aiVideoGeneration)&&t.jsx(zn,{initialPrompt:oe.initialPrompt,initialImage:oe.initialImage,initialImages:oe.initialImages,initialKnowledgeContextRefs:(h==null?void 0:h.initialKnowledgeContextRefs)||(h==null?void 0:h.knowledgeContextRefs)||[],initialDuration:oe.initialDuration,initialModel:oe.initialModel,initialSize:oe.initialSize,initialResultUrl:oe.initialResultUrl,selectedModel:Z,selectedModelRef:Y,onModelChange:R,onModelRefChange:_e,externalBatchId:h==null?void 0:h.batchId,initialAutoInsertToCanvas:h==null?void 0:h.autoInsertToCanvas,onDraftChange:h==null?void 0:h.onDraftChange},(h==null?void 0:h.batchId)||"ai-video-dialog")})]})},Qn=e.memo(Vn,(n,s)=>n.container===s.container);export{Qn as TTDDialog};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r,kn as rt,dB as P,bg as f,ko as at,j as t,kp as nt,kq as ct,y as it,kr as lt,ks as ot,gd as ut,kt as dt,km as mt,n as ht,da as pt,dc as ft,ku as gt,R as Te,P as xe,ke as qe,kf as Ee,cq as vt,kj as _t,E as se,kv as W,kw as xt,kx as jt,er as Q,hA as yt,b_ as Tt,b$ as Ct,ky as Je,e0 as je,i3 as Nt,M as Ce,cu as St,am as Ne}from"./startup-app-DxX-P1pm.js";import{i as bt,s as Et,h as wt,j as It,k as At,l as Se,n as q,o as be}from"./tool-windows-BIjc1zsU.js";import{u as Mt,V as Rt}from"./ai-chat-B5qFht2H.js";/* empty css */const Lt=({taskType:e,taskStatus:s,realProgress:g,startedAt:v,mediaUrl:u,isImageLoading:h=!1,onImageLoaded:A,onImageError:x,estimatedDuration:y=ct})=>{const[M,p]=r.useState(1),I=r.useRef(null),{displayProgress:l}=rt({taskType:e,taskStatus:s,startedAt:v,realProgress:g,mediaUrl:u,isImageLoading:h,estimatedDuration:y}),a=90,i=80,N=.5,b=1.2;if(r.useEffect(()=>{const V=I.current;if(!V)return;const K=()=>{const{width:F,height:Z}=V.getBoundingClientRect(),L=Z-10,O=F-20,B=L/a,E=O/i,J=Math.min(B,E,b);p(Math.max(J,N))};K();const R=new ResizeObserver(K);return R.observe(V),()=>R.disconnect()},[]),s!==P.PROCESSING)return null;const d=l??0,j=e===f.IMAGE?at(d,!!u,h):e===f.AUDIO?d<10?"提交任务...":d<45?"生成旋律...":d<85?"渲染音轨...":"整理结果...":d<10?"准备中...":d<50?"生成中...":d<90?"渲染中...":"即将完成...",_=["task-progress-overlay",e===f.VIDEO||e===f.AUDIO?"task-progress-overlay--video":"",u&&h?"task-progress-overlay--loading":""].filter(Boolean).join(" ");return t.jsxs("div",{ref:I,className:_,children:[t.jsx("div",{className:"task-progress-overlay__backdrop"}),t.jsx("div",{className:"task-progress-overlay__pulse"}),t.jsx("div",{className:"task-progress-overlay__dots"}),t.jsx("div",{className:"task-progress-overlay__content",style:{transform:`scale(${M})`},children:t.jsx(nt,{progress:d,progressMode:"determinate",statusText:j,tone:u&&h?"loading":"default",className:"task-progress-overlay__progress"})}),t.jsx("div",{className:"task-progress-overlay__bar",children:t.jsx("div",{className:"task-progress-overlay__bar-fill",style:{width:`${d}%`}})})]})},Dt=500;function kt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const s=Math.round(e),g=Math.floor(s/60),v=s%60;return`${g}:${String(v).padStart(2,"0")}`}function he(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function zt(e){if(!e)return!1;const s=e.toLowerCase();return s==="kling_video"||s.startsWith("kling-v")}function Pt(e){if(e==="text2video")return"文生视频";if(e==="image2video")return"图生视频"}function Ot(e){return e==="std"?"std 高性能":e==="pro"?"pro 高表现":e}function we(e){const s=e.params.videoAnalyzerAction;return s==="analyze"||s==="rewrite"?s:null}function Ut(e){const s=we(e);if(s==="analyze")return he(e.params.videoAnalyzerSourceLabel)||null;if(s==="rewrite"){const g=he(e.params.prompt);return g?g.replace(/^改编脚本:\s*/,""):null}return null}function Ht(e){const s=we(e);return s==="analyze"?"视频分析":s==="rewrite"?"脚本改编":null}function $t(e){const s=e.params.batchIndex;return typeof s!="number"||!Number.isFinite(s)?null:e.type===f.AUDIO?s+1:s>=1?s:s+1}function Vt(e){switch(e){case P.PENDING:case P.PROCESSING:return"primary";case P.COMPLETED:return"success";case P.FAILED:return"danger";case P.CANCELLED:return"default";default:return"default"}}function Ft(e){switch(e){case P.PENDING:case P.PROCESSING:return"处理中";case P.COMPLETED:return"已完成";case P.FAILED:return"失败";case P.CANCELLED:return"已取消";default:return"未知"}}const Qe=it.memo(({task:e,selectionMode:s=!1,isSelected:g=!1,isCompact:v,onSelectionChange:u,onRetry:h,onDelete:A,onDownload:x,onInsert:y,onCopy:M,onPreviewOpen:p,onEdit:I,onExtractCharacter:l})=>{var ge,fe,Ie,Ae,Me,Re,Le,De,ke,ze,Pe,Oe,Ue,He,$e,Ve,Fe,Ge,Be,We,Xe,Ke,Ye;const[a,i]=r.useState(null),[N,b]=r.useState(!1),d=r.useRef(null),j=e.status===P.COMPLETED,_=e.status===P.FAILED,V=e.status===P.CANCELLED,K=_||V,R=v!==void 0?v:N;r.useEffect(()=>{if(v!==void 0)return;const m=d.current;if(!m)return;const te=new ResizeObserver(ve=>{for(const _e of ve){const st=_e.contentRect.width;b(st<Dt)}});return te.observe(m),()=>te.disconnect()},[v]);const F=((ge=e.params.storyboard)==null?void 0:ge.enabled)===!0,Z=j&&e.type===f.VIDEO&&bt(e.remoteId)&&Et(e.params.model)&&!F,L=e.type===f.CHARACTER,O=e.type===f.AUDIO,B=e.type===f.CHAT,E=O&<(e.result),J=e.type===f.IMAGE||e.type===f.VIDEO||e.type===f.AUDIO&&!E,ne=ot(e.result),ue=ut(e.result,e.params.title||e.params.prompt),de=dt(ne),ce=mt(e.result),re=we(e),Y=Ut(e),me=Ht(e),X=$t(e),ie=L?j&&((fe=e.result)!=null&&fe.characterUsername)?`@${e.result.characterUsername}`:"角色创建中...":B?((Ie=e.result)==null?void 0:Ie.title)||e.params.prompt||((Ae=e.result)==null?void 0:Ae.chatResponse):E?ue||de||e.params.prompt:((Me=e.result)==null?void 0:Me.title)||e.params.title||e.params.prompt,n=e.params.params&&typeof e.params.params=="object"?e.params.params:null,T=e.type===f.AUDIO&&!E?kt((Re=e.result)==null?void 0:Re.duration):null,D=e.type===f.VIDEO&&zt(e.params.model),w=he(n==null?void 0:n.model_name)||((Le=e.params.model)!=null&&Le.toLowerCase().startsWith("kling-v")?e.params.model:void 0),U=Ot(he(n==null?void 0:n.mode)),le=he(n==null?void 0:n.klingAction2),ae=Pt(le);he(n==null?void 0:n.cfg_scale);const c=E?void 0:((ke=(De=e.result)==null?void 0:De.urls)==null?void 0:ke[0])||((ze=e.result)==null?void 0:ze.url),o=e.type===f.IMAGE&&c?ht(c):c,{isCached:S,cacheWarning:k}=pt(L||O?void 0:o),H=J&&!O&&!S?k||((Pe=e.result)==null?void 0:Pe.cacheWarning):void 0,G=H?`${H.message}${H.expiresHint?`
|
|
2
|
-
${H.expiresHint}`:""}`:"",z=E?0:((Ue=(Oe=e.result)==null?void 0:Oe.urls)==null?void 0:Ue.length)||((He=e.result)!=null&&He.url?1:0),$=r.useMemo(()=>JSON.stringify({taskId:e.id,taskType:e.type,taskStatus:e.status,hasMultipleResults:z>1}),[z,e.id,e.status,e.type]),C=O?E||($e=e.result)==null?void 0:$e.previewImageUrl:o,pe=Mt(C,e.type===f.IMAGE?"image":void 0,"small");r.useEffect(()=>{if(j&&C&&e.type===f.IMAGE){const m=new Image;m.onload=()=>{i({width:m.naturalWidth,height:m.naturalHeight})},m.onerror=()=>{i(null)},m.src=C}},[j,C,e.type]);const oe=m=>{const te=m.target;te.closest("button")||te.closest(".t-checkbox")||te.closest("a")||te.closest(".task-item__preview")||(s?u==null||u(e.id,!g):j&&o&&J&&(p==null||p()))},ee=m=>{m.stopPropagation(),j&&o&&J&&(p==null||p())};return t.jsxs("div",{ref:d,className:`task-item ${s?"task-item--selection-mode":""} ${g?"task-item--selected":""} ${R?"task-item--compact":"task-item--wide"} task-item--${e.status.toLowerCase()}`,onClick:oe,children:[s&&t.jsx("div",{className:"task-item__checkbox",children:t.jsx(ft,{checked:g,onChange:m=>u==null?void 0:u(e.id,m)})}),(j||_||e.status===P.PROCESSING)&&(C||L||B||e.type===f.VIDEO||e.type===f.IMAGE||e.type===f.AUDIO)&&t.jsx("div",{className:"task-item__preview-wrapper",children:t.jsx("div",{className:"task-item__preview","data-track":"task_click_preview",onClick:ee,children:_?t.jsxs("div",{className:"task-item__preview-failed",children:[t.jsx(gt,{size:"24px"}),t.jsx("span",{children:"生成失败"})]}):e.status===P.PROCESSING?B?t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:re==="analyze"?`视频分析中 ${Math.round(e.progress??0)}%`:re==="rewrite"?`脚本改编中 ${Math.round(e.progress??0)}%`:"生成文本中"})}):t.jsx(Lt,{taskType:e.type,taskStatus:e.status,realProgress:e.progress,startedAt:e.startedAt,mediaUrl:C},e.startedAt):t.jsxs(t.Fragment,{children:[e.type===f.IMAGE&&o?t.jsxs(t.Fragment,{children:[t.jsx(Te,{src:pe||o,alt:"Generated",maxRetries:5,fallback:t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:"图片加载失败"})})}),z>1&&t.jsxs("span",{className:"task-item__multi-badge",children:[z,"张"]})]}):O&&C?t.jsxs(t.Fragment,{children:[t.jsx(Te,{src:C,alt:ie||"音频封面",maxRetries:3,fallback:t.jsxs("div",{className:"task-item__preview-placeholder",children:[t.jsx(xe,{size:"24px"}),t.jsx("span",{children:"音频封面"})]})}),t.jsx("div",{className:"task-item__video-play-overlay",children:t.jsx(xe,{size:"28px"})}),z>1&&t.jsxs("span",{className:"task-item__multi-badge",children:[z,"首"]})]}):E?t.jsxs("div",{className:"task-item__preview-placeholder",children:[t.jsx(qe,{size:"24px"}),t.jsx("span",{children:"歌词"})]}):B?t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:"文本"})}):L&&((Ve=e.result)!=null&&Ve.characterProfileUrl)?t.jsx("div",{className:"task-item__character-preview",children:t.jsx(Te,{src:e.result.characterProfileUrl,alt:`@${e.result.characterUsername}`,maxRetries:5,fallback:t.jsx("div",{className:"task-item__character-fallback",children:t.jsx(Ee,{size:"32px"})})})}):o?t.jsxs(t.Fragment,{children:[t.jsx(Rt,{src:o,poster:(Fe=e.result)==null?void 0:Fe.previewImageUrl,alt:ie||"视频预览",thumbnailSize:"small",videoProps:{muted:!0,playsInline:!0,preload:"metadata"}}),t.jsx("div",{className:"task-item__video-play-overlay",children:t.jsx(xe,{size:"32px"})})]}):t.jsx("div",{className:"task-item__preview-placeholder",children:e.type===f.IMAGE?t.jsx(vt,{size:"24px"}):e.type===f.VIDEO?t.jsx(_t,{size:"24px"}):t.jsxs(t.Fragment,{children:[t.jsx(xe,{size:"24px"}),t.jsx("span",{children:"音频"})]})}),H&&t.jsx(se,{content:G,showArrow:!1,children:t.jsx("span",{className:"task-item__cache-warning-badge",children:"需下载"})})]})})}),t.jsxs("div",{className:"task-item__body",children:[t.jsxs("div",{className:"task-item__prompt-area",children:[t.jsx(se,{content:e.params.prompt,showArrow:!1,children:t.jsx("div",{className:"task-item__prompt",children:ie})}),B&&Y&&t.jsx(se,{content:Y,showArrow:!1,children:t.jsx("div",{className:"task-item__subtitle",children:Y})})]}),t.jsxs("div",{className:"task-item__info-area",children:[t.jsxs("div",{className:"task-item__content-row",children:[t.jsxs("div",{className:"task-item__meta",children:[t.jsxs("div",{className:"task-item__tags",children:[t.jsx(W,{theme:Vt(e.status),variant:"light",className:"task-item__status-tag",children:Ft(e.status)}),e.params.model&&t.jsx(W,{variant:"outline",className:"task-item__model-tag",children:e.params.model}),B&&me&&t.jsx(W,{variant:"outline",children:me}),D&&w&&t.jsx(W,{variant:"outline",children:w}),D&&U&&t.jsx(W,{variant:"outline",children:U}),D&&ae&&t.jsx(W,{variant:"outline",children:ae}),e.type===f.VIDEO&&e.params.seconds&&t.jsxs(W,{variant:"outline",children:[e.params.seconds,"s"]}),e.type===f.VIDEO&&e.params.size&&t.jsx(W,{variant:"outline",children:e.params.size}),T&&t.jsx(W,{variant:"outline",children:T}),e.type===f.AUDIO&&e.params.mv&&!E&&t.jsx(W,{variant:"outline",children:e.params.mv}),e.type===f.AUDIO&&e.params.tags&&!E&&t.jsx(W,{variant:"outline",children:((Ge=String(e.params.tags).split(",")[0])==null?void 0:Ge.trim())||"音频"}),E&&t.jsx(W,{variant:"outline",children:"歌词"}),E&&ce[0]&&t.jsx(W,{variant:"outline",children:ce[0]}),e.params.batchId&&X!==null&&typeof e.params.batchTotal=="number"&&t.jsxs(W,{variant:"outline",children:["批量 ",X,"/",e.params.batchTotal]})]}),t.jsxs("div",{className:"task-item__details",children:[t.jsx("span",{className:"task-item__time",children:xt(e.createdAt)}),e.startedAt&&t.jsxs("span",{className:"task-item__duration",children:["·"," ",jt((e.completedAt||Date.now())-e.startedAt)]}),(()=>{var ve,_e;const m=(a==null?void 0:a.width)||((ve=e.result)==null?void 0:ve.width)||e.params.width,te=(a==null?void 0:a.height)||((_e=e.result)==null?void 0:_e.height)||e.params.height;return m&&te?t.jsxs("span",{className:"task-item__size",children:[" ","· ",m,"x",te]}):null})(),T&&t.jsxs("span",{className:"task-item__size",children:[" · ",T]}),j&&((Be=e.result)==null?void 0:Be.url)&&!E&&t.jsx("a",{href:e.result.url,target:"_blank",rel:"noopener noreferrer",className:"task-item__link","data-track":"task_click_open_link",onClick:m=>m.stopPropagation(),children:"· 打开链接"})]}),(e.type===f.VIDEO||e.type===f.AUDIO||e.type===f.CHAT&&typeof e.progress=="number")&&e.status===P.PROCESSING&&t.jsx("div",{className:"task-item__progress-container",children:t.jsx("div",{className:"task-item__progress-bar",children:t.jsx("div",{className:`task-item__progress-fill task-item__progress-fill--${e.status}`,style:{width:`${e.progress??0}%`}})})})]}),t.jsxs("div",{className:"task-item__actions",children:[t.jsxs("div",{className:"task-item__secondary-actions",children:[j&&((We=e.result)==null?void 0:We.url)&&!L&&t.jsx(se,{content:"下载",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(yt,{}),"data-track":"task_click_download","data-track-params":$,onClick:m=>{m.stopPropagation(),x==null||x(e.id)}})}),j&&E&&ne&&t.jsx(se,{content:"复制歌词",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(qe,{}),onClick:m=>{m.stopPropagation(),M==null||M(e.id)}})}),!L&&!O&&!B&&t.jsx(se,{content:"编辑",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Tt,{}),onClick:m=>{m.stopPropagation(),I==null||I(e.id)}})}),Z&&t.jsx(se,{content:"角色",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Ee,{}),onClick:m=>{m.stopPropagation(),l==null||l(e.id)}})}),t.jsx(se,{content:"删除",children:t.jsx(Q,{size:"small",variant:"text",className:"task-item__delete-btn",icon:t.jsx(Ct,{}),onClick:m=>{m.stopPropagation(),A==null||A(e.id)}})})]}),j&&((((Xe=e.result)==null?void 0:Xe.url)||((Ke=e.result)==null?void 0:Ke.chatResponse))&&!L||E)&&t.jsx(Q,{size:"small",theme:"primary",className:"task-item__primary-action","data-track":"task_click_insert","data-track-params":$,onClick:m=>{m.stopPropagation(),y==null||y(e.id)},children:"插入"}),K&&t.jsx(Q,{size:"small",theme:"primary",className:"task-item__primary-action","data-track":"task_click_retry","data-track-params":$,onClick:m=>{m.stopPropagation(),h==null||h(e.id)},children:"重试"})]})]}),_&&e.error&&t.jsx("div",{className:"task-item__error",children:t.jsxs("div",{className:"task-item__error-message",children:[e.error.message,((Ye=e.error.details)==null?void 0:Ye.originalError)&&t.jsx(se,{content:t.jsxs("div",{className:"task-item__error-details-tooltip",children:[t.jsx("div",{className:"task-item__error-details-title",children:"详细错误:"}),t.jsx("div",{className:"task-item__error-details-content",children:e.error.details.originalError})]}),theme:"light",placement:"bottom",children:t.jsx("span",{className:"task-item__error-details-link",onClick:m=>m.stopPropagation(),children:"[详情]"})})]})})]})]})]})},(e,s)=>{var g,v;return e.task.id===s.task.id&&e.task.status===s.task.status&&e.task.progress===s.task.progress&&((g=e.task.error)==null?void 0:g.message)===((v=s.task.error)==null?void 0:v.message)&&e.task.result===s.task.result&&e.isSelected===s.isSelected&&e.selectionMode===s.selectionMode&&e.isCompact===s.isCompact}),Gt=new Set,Bt=140,Ze=0,Wt=3,et=375,Xt=20,es=({tasks:e,selectionMode:s=!1,selectedTaskIds:g,onSelectionChange:v,onRetry:u,onDelete:h,onDownload:A,onInsert:x,onCopy:y,onEdit:M,onPreviewOpen:p,onExtractCharacter:I,className:l="",emptyContent:a,isCompact:i,hasMore:N=!1,isLoadingMore:b=!1,onLoadMore:d,totalCount:j,loadedCount:_,allLoadedText:V,allLoadedHint:K})=>{const R=g??Gt,F=r.useRef(null),Z=r.useRef(null),L=r.useRef(null),O=r.useRef(0),[B,E]=r.useState(()=>typeof window<"u"&&window.innerWidth<et),[J,ne]=r.useState(!1),ue=i!==void 0?i:B,de=n=>{let T=n;for(;T;){const w=getComputedStyle(T).overflowY;if((w==="auto"||w==="scroll")&&T.scrollHeight>T.clientHeight)return T;T=T.parentElement}return null};r.useEffect(()=>{if(!N||!d)return;const n=F.current;if(!n)return;const T=setTimeout(()=>{const w=n.scrollHeight>n.clientHeight?n:de(n);if(L.current=w,!w)return;const U=()=>{const{scrollTop:le,scrollHeight:ae,clientHeight:c}=w,o=ae-le-c,S=Date.now();S-O.current<500||o<300&&N&&!b&&(O.current=S,d())};w.addEventListener("scroll",U,{passive:!0}),U(),n.__loadMoreCleanup=()=>{w.removeEventListener("scroll",U)}},150);return()=>{var D;clearTimeout(T),(D=n.__loadMoreCleanup)==null||D.call(n)}},[N,b,d,e.length]),r.useEffect(()=>{const n=F.current;if(!n)return;const T=setTimeout(()=>{const w=n.scrollHeight>n.clientHeight?n:de(n);if(L.current=w,!w)return;const U=()=>{ne(w.scrollTop>w.clientHeight)};w.addEventListener("scroll",U),U(),n.__scrollCleanup=()=>{w.removeEventListener("scroll",U)}},100);return()=>{var D;clearTimeout(T),(D=n.__scrollCleanup)==null||D.call(n)}},[e.length]);const ce=()=>{const n=L.current||F.current;n&&(n.scrollTop=0)};r.useEffect(()=>{if(i!==void 0)return;const n=F.current;if(!n)return;const T=n,D=U=>{const le=U??T.getBoundingClientRect().width;E(le<et)},w=new ResizeObserver(U=>{D(U[0].contentRect.width)});return w.observe(T),D(),()=>{w.disconnect()}},[i,F.current]);const re=e.length>Xt,Y=wt({count:re?e.length:0,getScrollElement:()=>F.current,estimateSize:()=>Bt+Ze,overscan:Wt,enabled:re,measureElement:n=>n.offsetHeight});if(e.length===0)return t.jsx("div",{className:`virtual-task-list virtual-task-list--empty ${l}`,children:a});const me=e.length||_||0,X=()=>t.jsxs(t.Fragment,{children:[b&&t.jsxs("div",{className:"virtual-task-list__loading-more",children:[t.jsx("span",{className:"virtual-task-list__loading-spinner"}),t.jsx("span",{children:"加载中..."})]}),N&&!b&&j!==void 0&&j>0&&t.jsxs("div",{className:"virtual-task-list__pagination-info",children:["已加载 ",me," / ",j]}),!N&&e.length>0&&j!==void 0&&j>50&&t.jsx("div",{className:"virtual-task-list__no-more",children:K?t.jsx(se,{content:K,children:t.jsx("span",{children:V||`已加载全部 ${j} 个任务`})}):V||`已加载全部 ${j} 个任务`})]});if(!re)return t.jsxs("div",{ref:Z,className:`virtual-task-list-container ${l}`,style:{height:"100%",position:"relative",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{ref:F,className:"virtual-task-list-scrollarea",style:{flex:1,overflow:"auto"},children:[e.map(n=>t.jsx(Qe,{task:n,selectionMode:s,isSelected:R.has(n.id),isCompact:ue,onSelectionChange:v,onRetry:u,onDelete:h,onDownload:A,onInsert:x,onEdit:M,onPreviewOpen:()=>p==null?void 0:p(n.id),onExtractCharacter:I},n.id)),t.jsx(X,{})]}),J&&t.jsx(Q,{shape:"circle",variant:"base",theme:"default",icon:t.jsx(Je,{}),onClick:ce,className:"virtual-task-list__back-to-top"})]});const ie=Y.getVirtualItems();return t.jsxs("div",{ref:Z,className:`virtual-task-list-container ${l}`,style:{height:"100%",width:"100%",position:"relative",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{ref:F,className:"virtual-task-list-scrollarea",style:{flex:1,width:"100%",overflow:"auto"},children:[t.jsx("div",{style:{height:`${Y.getTotalSize()}px`,width:"100%",position:"relative"},children:ie.map(n=>{const T=e[n.index];return T?t.jsx("div",{"data-index":n.index,ref:D=>{D&&Y.measureElement(D)},style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${n.start}px)`,paddingBottom:`${Ze}px`},children:t.jsx(Qe,{task:T,selectionMode:s,isSelected:R.has(T.id),isCompact:ue,onSelectionChange:v,onRetry:u,onDelete:h,onDownload:A,onInsert:x,onCopy:y,onEdit:M,onPreviewOpen:()=>p==null?void 0:p(T.id),onExtractCharacter:I})},T.id):null})}),t.jsx(X,{})]}),J&&t.jsx(Q,{shape:"circle",variant:"base",theme:"default",icon:t.jsx(Je,{}),onClick:ce,className:"virtual-task-list__back-to-top"})]})};function Kt(e,s){const[g,v]=r.useState(s||null),[u,h]=r.useState(!1),[A,x]=r.useState(!0),[y,M]=r.useState(null),p=r.useRef("none"),I=r.useCallback(async()=>{if(x(!0),!s){v(null),h(!1),x(!1);return}const l=await je.getCachedUrl(s);l?(y&&y!==l&&URL.revokeObjectURL(y),M(l),v(l),h(!0)):s?(v(s),h(!1)):(v(null),h(!1)),x(!1)},[s,y]);return r.useEffect(()=>{I(),s&&(p.current=je.getCacheStatus(s))},[e,s]),r.useEffect(()=>je.subscribe(()=>{if(!s)return;const a=je.getCacheStatus(s),i=p.current;a!==i&&(p.current=a,(a==="cached"||a==="none")&&I())}),[s,I]),r.useEffect(()=>()=>{y&&URL.revokeObjectURL(y)},[y]),{url:g,isFromCache:u,isLoading:A}}const tt=1,ye=3,Yt=({videoUrl:e,videoDuration:s,onConfirm:g,onCancel:v,disabled:u=!1})=>{const h=r.useRef(null),A=r.useRef(null),x=r.useRef(null),y=r.useRef(null),M=r.useRef(0),[p,I]=r.useState(!0),[l,a]=r.useState(s),[i,N]=r.useState(0),[b,d]=r.useState(Math.min(ye,s)),[j,_]=r.useState(0),[V,K]=r.useState(""),[R,F]=r.useState(!1),[Z,L]=r.useState(null),[O,B]=r.useState([]),[E,J]=r.useState(!1),ne=b-i,ue=l>0?ne/l*100:100,de=l>0?i/l*100:0;r.useEffect(()=>(e&&(I(!0),K(""),B([]),F(!1),L(null)),()=>{y.current!==null&&cancelAnimationFrame(y.current)}),[e]);const ce=()=>{const c=h.current;if(c){const o=c.duration;a(o),F(!0),d(Math.min(ye,o))}},re=r.useCallback(async()=>{const c=h.current;if(!(!c||!R||l<=0||E)){J(!0);try{const S=Math.max(4,Math.ceil(l*2)),k=l/S,H=[],G=document.createElement("canvas"),z=G.getContext("2d");if(!z)return;const $=50,C=c.videoWidth/c.videoHeight||16/9,pe=Math.round($*C);G.width=pe,G.height=$;for(let oe=0;oe<S;oe++){const ee=Math.min((oe+.5)*k,l-.01);await new Promise(ge=>{const fe=()=>{c.removeEventListener("seeked",fe),ge()};c.addEventListener("seeked",fe),c.currentTime=ee}),z.drawImage(c,0,0,pe,$),H.push(G.toDataURL("image/jpeg",.5))}B(H),c.currentTime=i}catch(o){console.warn("Failed to generate frame strip:",o)}finally{J(!1)}}},[R,l,E,i]);r.useEffect(()=>{if(R&&l>0&&O.length===0&&!E){const c=setTimeout(()=>{re()},100);return()=>clearTimeout(c)}},[R,l,O.length,E,re]);const Y=r.useCallback(()=>{const c=h.current,o=A.current;if(!c||!o)return;const S=o.getContext("2d");if(S)try{o.width=c.videoWidth,o.height=c.videoHeight,S.drawImage(c,0,0,o.width,o.height);const k=o.toDataURL("image/jpeg",.8);K(k),I(!1)}catch(k){console.warn("Failed to generate frame image:",k)}},[]),me=r.useCallback(()=>{const c=h.current;c&&p&&(c.currentTime===0||Math.abs(c.currentTime-i)<.1)&&Y()},[p,i,Y]),X=r.useCallback(c=>{const o=h.current;!o||!R||Math.abs(c-M.current)<.1||(M.current=c,o.readyState>=2&&(o.currentTime=c))},[R]),ie=r.useCallback(()=>{Y()},[Y]);r.useEffect(()=>{if(R&&l>0){_(i);const c=h.current;c&&c.readyState>=2&&(c.currentTime=i)}},[R,l]);const n=r.useCallback(c=>{const o=x.current;if(!o)return 0;const S=o.getBoundingClientRect(),k=c.clientX-S.left;return Math.max(0,Math.min(1,k/S.width))*l},[l]),T=c=>{if(u||!R)return;c.preventDefault(),c.stopPropagation(),L("left");const o=b,S=H=>{const G=n(H),z=o-tt,$=Math.max(0,o-ye),C=Math.max($,Math.min(z,G));N(C),_(C),X(C)},k=()=>{L(null),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",k),X(i)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",k)},D=c=>{if(u||!R)return;c.preventDefault(),c.stopPropagation(),L("right");const o=i,S=H=>{const G=n(H),z=o+tt,$=Math.min(l,o+ye),C=Math.max(z,Math.min($,G));d(C),_(C),X(C)},k=()=>{L(null),document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",k),X(b)};document.addEventListener("mousemove",S),document.addEventListener("mouseup",k)},w=c=>{if(u||!R)return;c.preventDefault(),L("center");const o=x.current;if(!o)return;const S=o.getBoundingClientRect(),k=c.clientX,H=i,G=b-i,z=C=>{const oe=(C.clientX-k)/S.width*l;let ee=H+oe;ee=Math.max(0,Math.min(l-G,ee)),N(ee),d(ee+G),_(ee),X(ee)},$=()=>{L(null),document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",$),X(i)};document.addEventListener("mousemove",z),document.addEventListener("mouseup",$)},U=c=>{if(u||!R||Z||c.target.closest(".character-time-selector__range"))return;const S=x.current;if(!S)return;const k=S.getBoundingClientRect(),G=(c.clientX-k.left)/k.width*l,z=b-i,$=z/2;let C=G-$;C=Math.max(0,Math.min(l-z,C)),N(C),d(C+z),_(C),X(C)},le=()=>{g(Math.round(i),Math.round(b))},ae=c=>c.toFixed(1)+"s";return t.jsxs("div",{className:`character-time-selector ${Z?"is-dragging":""}`,children:[t.jsx("video",{ref:h,src:e,style:{display:"none"},muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous",onLoadedMetadata:ce,onSeeked:ie,onCanPlay:me}),t.jsx("canvas",{ref:A,style:{display:"none"}}),t.jsxs("div",{className:"character-time-selector__preview",children:[p?t.jsxs("div",{className:"character-time-selector__loading",children:[t.jsx("div",{className:"character-time-selector__spinner"}),t.jsx("span",{children:"加载中..."})]}):V?t.jsx("img",{src:V,alt:"Video frame",className:"character-time-selector__frame"}):t.jsx("div",{className:"character-time-selector__placeholder",children:"视频帧加载失败"}),t.jsx("div",{className:"character-time-selector__time-badge",children:ae(j)})]}),t.jsxs("div",{className:"character-time-selector__timeline",ref:x,onClick:U,children:[O.length>0?t.jsx("div",{className:"character-time-selector__frame-strip",children:O.map((c,o)=>t.jsx("img",{src:c,alt:"",className:"character-time-selector__frame-thumb",draggable:!1},o))}):E?t.jsx("div",{className:"character-time-selector__frame-strip character-time-selector__frame-strip--loading",children:t.jsx("div",{className:"character-time-selector__strip-shimmer"})}):t.jsx("div",{className:"character-time-selector__timeline-bg"}),t.jsxs("div",{className:`character-time-selector__range ${Z?"dragging":""}`,style:{left:`${de}%`,width:`${ue}%`},children:[t.jsx("div",{className:"character-time-selector__handle character-time-selector__handle--left",onMouseDown:T}),t.jsx("div",{className:"character-time-selector__range-content",onMouseDown:w,children:t.jsxs("span",{className:"character-time-selector__range-label",children:[ae(i)," - ",ae(b)]})}),t.jsx("div",{className:"character-time-selector__handle character-time-selector__handle--right",onMouseDown:D})]})]}),t.jsxs("div",{className:"character-time-selector__info",children:[t.jsxs("span",{children:["API参数: ",Math.round(i),", ",Math.round(b)]}),t.jsxs("span",{children:["时长: ",ne.toFixed(1),"s"]})]}),t.jsxs("div",{className:"character-time-selector__actions",children:[t.jsx(Q,{variant:"outline",onClick:v,disabled:u,children:"取消"}),t.jsx(Q,{theme:"primary",onClick:le,disabled:u||!R,children:"创建角色"})]})]})},ts=({visible:e,task:s,onClose:g,onCreateStart:v,onCreateComplete:u})=>{var b;const{createTask:h,tasks:A}=Nt(),[x,y]=r.useState(!1),M=r.useRef(!1),{url:p}=Kt((s==null?void 0:s.id)??"",(b=s==null?void 0:s.result)==null?void 0:b.url),I=r.useMemo(()=>s!=null&&s.params.seconds?parseFloat(s.params.seconds.toString()):10,[s==null?void 0:s.params.seconds]),l=r.useMemo(()=>s?A.some(d=>d.type===f.CHARACTER&&d.params.sourceLocalTaskId===s.id&&(d.status===P.PENDING||d.status===P.PROCESSING)):!1,[s,A]),a=r.useCallback(async(d,j)=>{if(!(M.current||x||l)){if(!s||!s.remoteId){Ce.error("无效的任务数据");return}M.current=!0,y(!0),v==null||v();try{const _=It(d,j),V=At(s.params.model),K=h({prompt:s.params.prompt||"角色提取",model:V,sourceVideoTaskId:s.remoteId,characterTimestamps:_,sourceLocalTaskId:s.id},f.CHARACTER);Ce.success("角色创建任务已加入队列"),u==null||u(K.id),g()}catch(_){console.error("Failed to create character task:",_);const V=_.message||"创建任务失败";Ce.error(V)}finally{M.current=!1,y(!1)}}},[l,h,x,g,u,v,s]),i=()=>{x||g()},N=()=>{x||g()};return!s||!p?null:t.jsxs(St,{visible:e,header:"角色",onClose:i,footer:null,width:560,className:"character-create-dialog",closeOnOverlayClick:!x,closeOnEscKeydown:!x,children:[t.jsxs("div",{className:"character-create-dialog__description",children:["从视频中提取角色,创建后可通过 ",t.jsx("code",{children:"@username"})," 在提示词中引用"]}),l&&t.jsx("div",{className:"character-create-dialog__warning",children:"此视频已有一个角色正在创建中"}),t.jsx(Yt,{videoUrl:p,videoDuration:I,onConfirm:a,onCancel:N,disabled:x||l})]})},ss=({characterId:e,profilePictureUrl:s,alt:g="Character",className:v,onClick:u})=>{const[h,A]=r.useState(s||null),[x,y]=r.useState(!1),[M,p]=r.useState(!0);r.useEffect(()=>{let a=!1;return(async()=>{p(!0),y(!1);const N=await Se.getCachedUrl(e);if(!a){if(N){A(N),p(!1);return}s?(A(s),Se.cacheAvatar(e,s).catch(()=>{})):y(!0),p(!1)}})(),()=>{a=!0}},[e,s]);const I=async()=>{if(h===s){const a=await Se.getCachedUrl(e);if(a&&a!==h){A(a);return}}y(!0)},l=()=>{p(!1)};return x||!h?t.jsx("div",{className:v,onClick:u,style:u?{cursor:"pointer"}:void 0,children:t.jsx(Ee,{})}):t.jsx(Te,{src:h,alt:g,className:v,onLoadFailure:()=>void I(),onLoad:l,onClick:u,style:{display:M?"none":"block",cursor:u?"pointer":void 0},showSkeleton:!1,eager:!0})};function rs(){const[e,s]=r.useState([]),[g,v]=r.useState(!0),u=r.useRef(new Map);r.useEffect(()=>{const a=q.getCharacters$().subscribe(i=>{s(i),v(!1)});return q.init(),()=>a.unsubscribe()},[]),r.useEffect(()=>{g||(async()=>{const i=q.getPendingCharacters();for(const N of i)u.current.get(N.id)||h(N)})()},[g]);const h=r.useCallback(async a=>{if(!u.current.get(a.id)){u.current.set(a.id,!0);try{const i=await be.resumePolling(a.id,{onStatusChange:async N=>{await q.updateCharacterStatus(a.id,N)}});await q.updateCharacter(a.id,{username:i.username,profilePictureUrl:i.profile_picture_url,permalink:i.permalink,status:"completed",completedAt:Date.now()})}catch(i){console.error("[useCharacters] Character polling failed:",i),await q.updateCharacterStatus(a.id,"failed",i.message)}finally{u.current.delete(a.id)}}},[]),A=r.useCallback(async a=>{var N;const i=Date.now();Ne.track("character_extract_start",{videoTaskId:a.videoTaskId,hasTimestamps:!!((N=a.characterTimestamps)!=null&&N.length)});try{const d=(await be.createCharacter(a)).id,j={id:d,username:"",profilePictureUrl:"",sourceTaskId:a.localTaskId||"",sourceVideoId:a.videoTaskId,sourcePrompt:a.sourcePrompt,characterTimestamps:a.characterTimestamps,status:"processing",createdAt:Date.now()};return await q.saveCharacter(j),u.current.set(d,!0),be.resumePolling(d,{onStatusChange:async _=>{await q.updateCharacterStatus(d,_)}}).then(async _=>{await q.updateCharacter(d,{username:_.username,profilePictureUrl:_.profile_picture_url,permalink:_.permalink,status:"completed",completedAt:Date.now()}),Ne.track("character_extract_success",{characterId:d,username:_.username,duration:Date.now()-i})}).catch(async _=>{console.error("[useCharacters] Character creation failed:",_),await q.updateCharacterStatus(d,"failed",_.message),Ne.track("character_extract_failed",{characterId:d,error:_.message,duration:Date.now()-i})}).finally(()=>{u.current.delete(d)}),j}catch(b){throw console.error("[useCharacters] Failed to create character:",b),b}},[]),x=r.useCallback(async a=>(u.current.delete(a),q.deleteCharacter(a)),[]),y=r.useCallback(async()=>{await q.init()},[]),M=r.useCallback(a=>e.find(i=>i.id===a),[e]),p=r.useCallback(a=>e.some(i=>i.sourceTaskId===a&&(i.status==="pending"||i.status==="processing")),[e]),I=e.filter(a=>a.status==="completed"),l=e.filter(a=>a.status==="pending"||a.status==="processing");return{characters:e,completedCharacters:I,pendingCharacters:l,isLoading:g,createCharacter:A,deleteCharacter:x,refreshCharacters:y,getCharacterById:M,isCreatingCharacterForTask:p}}export{ss as C,Qe as T,es as V,ts as a,rs as u};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css","./ai-chat-DyV67c_f.css","./editor-engines-B8u8agiX.css","./tool-windows-CegtMid1.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as w}from"./startup-runtime-DTmhLESk.js";import{g9 as W,aR as x,aT as R,c as M,d as P,b as T,bw as C,bv as F,bt as D,bu as X,bP as J,dH as $,dG as Q,kA as B,bg as E,kB as G,a9 as L,i_ as q,kC as U,fQ as N,hY as Z,bz as S,fK as j,dB as _,ax as b,hc as H,kD as Y,kE as z}from"./startup-app-DxX-P1pm.js";import{x as k}from"./tool-windows-BIjc1zsU.js";let v=null;function ge(m){v=m}class ee{async execute(e){const{operation:t,args:r}=e;switch(t){case"canvas_insert":return this.handleCanvasInsert(r);case"insert_to_canvas":return this.handleInsertToCanvas(r);case"insert_mermaid":return this.handleMermaid(r);case"insert_mindmap":return this.handleMindmap(r);case"insert_svg":return this.handleSvg(r);case"generate_grid_image":return this.handleGridImage(r);case"generate_inspiration_board":return this.handleInspirationBoard(r);case"split_image":return this.handleSplitImage(r);case"generate_long_video":return this.handleLongVideo(r);case"ai_analyze":return this.handleAIAnalyze(r);case"generate_image":return this.handleGenerateImage(r);case"generate_video":return this.handleGenerateVideo(r);case"generate_audio":return this.handleGenerateAudio(r);case"generate_ppt":return this.handleGeneratePPT(r);default:return{success:!1,error:`Unknown operation: ${t}`,type:"error"}}}async handleGeneratePPT(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};try{const[{setBoard:r},{generatePPT:a}]=await Promise.all([w(()=>import("./ai-chat-B5qFht2H.js").then(o=>o.$),__vite__mapDeps([0,1]),import.meta.url),w(()=>import("./ai-chat-B5qFht2H.js").then(o=>o.a0),__vite__mapDeps([0,1]),import.meta.url)]);r(t);const s=await a(e);return{success:s.success,data:s.data,error:s.error,type:s.type}}catch(r){return{success:!1,error:r.message||"PPT 生成失败",type:"error"}}}async handleGenerateAudio(e){return{success:!1,error:"SW 暂不支持直接处理音频生成,请回退到主线程执行",type:"audio"}}findWorkZoneForMCP(e,t){var s;const r=W.getAllWorkZones(e);if(r.length===0)return null;for(const o of r)if((s=o.workflow.steps)==null?void 0:s.some(i=>i.mcp===t))return o;return r.sort((o,n)=>(n.createdAt||0)-(o.createdAt||0))[0]||null}async handleInsertToCanvas(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};const{items:r,startPoint:a,verticalGap:s=50}=e;if(!r||r.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{const{parseMarkdownToCards:o}=await w(async()=>{const{parseMarkdownToCards:l}=await import("./startup-app-DxX-P1pm.js").then(g=>g.nQ);return{parseMarkdownToCards:l}},__vite__mapDeps([0]),import.meta.url),{insertCardsToCanvas:n}=await w(async()=>{const{insertCardsToCanvas:l}=await import("./startup-app-DxX-P1pm.js").then(g=>g.nR);return{insertCardsToCanvas:l}},__vite__mapDeps([0]),import.meta.url);let i=a||this.getInsertionPoint(t),c=0;for(const l of r){const{type:g,content:u,metadata:h}=l;switch(g){case"text":{const p=o(u);if(p&&p.length>0){const I=Math.round(window.innerWidth*.5);n(t,p,i,I);const A=Math.min(p.length,3),K=Math.ceil(p.length/3);i=[i[0],i[1]+K*140+s]}else x.insertText(t,i,u),i=[i[0],i[1]+100+s];c++;break}case"image":await P(t,u,i,!1,{width:400,height:400},!1,!0),i=[i[0],i[1]+400+s],c++;break;case"video":await M(t,u,i),i=[i[0],i[1]+300+s],c++;break;case"audio":await R(t,u,h,i,!1,!0),i=[i[0],i[1]+160+s],c++;break;case"svg":{const I={url:this.svgToDataUrl(u),width:400,height:400};x.insertImage(t,I,i),i=[i[0],i[1]+400+s],c++;break}}}const d=a||this.getInsertionPoint(t);return requestAnimationFrame(()=>{T(t,d)}),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"text",success:!0}})),{success:!0,data:{insertedCount:c},type:"canvas"}}catch(o){return{success:!1,error:o.message||"插入失败",type:"error"}}}async handleCanvasInsert(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};const{items:r,startPoint:a,verticalGap:s=50,horizontalGap:o=20}=e;if(!r||r.length===0)return{success:!1,error:"没有要插入的内容",type:"error"};try{let n=a||this.getInsertionPoint(t),i=0;for(const c of r){const{type:d,content:l,metadata:g}=c;switch(d){case"image":await P(t,l,n,!1,{width:400,height:400},!1,!0),n=[n[0],n[1]+400+s],i++;break;case"video":await M(t,l,n),n=[n[0],n[1]+300+s],i++;break;case"audio":await R(t,l,g,n,!1,!0),n=[n[0],n[1]+160+s],i++;break;case"text":x.insertText(t,n,l),n=[n[0],n[1]+100+s],i++;break;case"svg":const h={url:this.svgToDataUrl(l),width:400,height:400};x.insertImage(t,h,n),n=[n[0],n[1]+400+s],i++;break}}return{success:!0,data:{insertedCount:i},type:"canvas"}}catch(n){return{success:!1,error:n.message||"插入失败",type:"error"}}}async handleMermaid(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};const{mermaid:r}=e;if(!r)return{success:!1,error:"缺少 mermaid 参数",type:"error"};try{const{parseMermaidToDrawnix:a}=await w(async()=>{const{parseMermaidToDrawnix:l}=await import("./index-CylhK_f5.js");return{parseMermaidToDrawnix:l}},__vite__mapDeps([0]),import.meta.url),s=this.extractCodeBlock(r,"mermaid");let o;try{o=await a(s)}catch{o=await a(s.replace(/"/g,"'"))}const{elements:n}=o;if(!n||n.length===0)return{success:!1,error:"Mermaid 解析未生成元素",type:"error"};const i=this.findWorkZoneForMCP(t,"insert_mermaid"),c=this.getViewportCenter(t),d=this.insertElementsToCanvasAtPoint(t,n,c);return d.success&&(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(t,n.length)}),i&&setTimeout(()=>{W.removeWorkZone(t,i.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mermaid",success:!0}}))},100)),{success:d.success,data:{elementsCount:d.elementsCount},type:"canvas",error:d.error}}catch(a){return console.error("[SWCapabilities] Mermaid conversion failed:",a),{success:!1,error:`Mermaid 转换失败: ${a.message}`,type:"error"}}}async handleMindmap(e){const t=v;if(!t)return console.error("[SWCapabilities] ❌ handleMindmap: 画布未初始化"),{success:!1,error:"画布未初始化",type:"error"};const{markdown:r}=e;if(!r)return console.error("[SWCapabilities] ❌ handleMindmap: 缺少 markdown 参数"),{success:!1,error:"缺少 markdown 参数",type:"error"};try{const{parseMarkdownToDrawnix:a}=await w(async()=>{const{parseMarkdownToDrawnix:d}=await import("./index-BSlnQdcy.js");return{parseMarkdownToDrawnix:d}},__vite__mapDeps([0,2]),import.meta.url),s=this.extractCodeBlock(r,"markdown");let o;try{o=await a(s)}catch{o=await a(s.replace(/"/g,"'"))}if(!o)return{success:!1,error:"Markdown 解析未生成元素",type:"error"};o.points=[[0,0]];const n=this.findWorkZoneForMCP(t,"insert_mindmap"),i=this.getViewportCenter(t),c=this.insertElementsToCanvasAtPoint(t,[o],i);return c.success?(requestAnimationFrame(()=>{this.centerInsertedElementsInViewport(t,1)}),n&&setTimeout(()=>{W.removeWorkZone(t,n.id),window.dispatchEvent(new CustomEvent("ai-generation-complete",{detail:{type:"mindmap",success:!0}}))},100)):console.error("[SWCapabilities] ❌ Mindmap insert failed:",c.error),{success:c.success,data:{type:"mindmap",elementsCount:c.elementsCount},type:"canvas",error:c.error}}catch(a){return console.error("[SWCapabilities] ❌ Mindmap conversion failed:",a),{success:!1,error:`思维导图转换失败: ${a.message}`,type:"error"}}}async handleSvg(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};const{svg:r,width:a=400,startPoint:s}=e;if(!r)return{success:!1,error:"缺少 svg 参数",type:"error"};try{const o=this.extractSvgCode(r),n=this.normalizeSvg(o),i=this.parseSvgDimensions(n),c=Math.min(Math.max(a,100),800),d=i.height/i.width,l=c*d,g=this.svgToDataUrl(n);let u=s||this.getInsertionPoint(t);u=[u[0]-c/2,u[1]];const h={url:g,width:c,height:l};x.insertImage(t,h,u);const p=[u[0]+c/2,u[1]+l/2];return requestAnimationFrame(()=>{T(t,p)}),{success:!0,data:{width:c,height:l},type:"canvas"}}catch(o){return{success:!1,error:`SVG 插入失败: ${o.message}`,type:"error"}}}async handleGridImage(e){try{const{createGridImageTask:t}=await w(async()=>{const{createGridImageTask:a}=await import("./tool-windows-BIjc1zsU.js").then(s=>s.Z);return{createGridImageTask:a}},__vite__mapDeps([0,1,3]),import.meta.url),r=await t(e);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(t){return{success:!1,error:`宫格图生成失败: ${t.message}`,type:"error"}}}async handleInspirationBoard(e){try{const{createInspirationBoardTask:t}=await w(async()=>{const{createInspirationBoardTask:a}=await import("./tool-windows-BIjc1zsU.js").then(s=>s._);return{createInspirationBoardTask:a}},__vite__mapDeps([0,1,3]),import.meta.url),r=await t(e);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(t){return{success:!1,error:`灵感图生成失败: ${t.message}`,type:"error"}}}async handleSplitImage(e){const t=v;if(!t)return{success:!1,error:"画布未初始化",type:"error"};const{imageUrl:r}=e;if(!r)return{success:!1,error:"缺少 imageUrl 参数",type:"error"};try{const{splitAndInsertImages:a}=await w(async()=>{const{splitAndInsertImages:o}=await import("./startup-app-DxX-P1pm.js").then(n=>n.nT);return{splitAndInsertImages:o}},__vite__mapDeps([0]),import.meta.url),s=await a(t,r,{scrollToResult:!0});return{success:s.success,data:{count:s.count},type:"canvas",error:s.error}}catch(a){return{success:!1,error:`图片拆分失败: ${a.message}`,type:"error"}}}async handleLongVideo(e){try{const{createLongVideoTask:t}=await w(async()=>{const{createLongVideoTask:a}=await import("./tool-windows-BIjc1zsU.js").then(s=>s.a0);return{createLongVideoTask:a}},__vite__mapDeps([0,1,3]),import.meta.url),r=await t(e);return{success:r.success,data:r.data,type:r.type,taskId:r.taskId,error:r.error}}catch(t){return{success:!1,error:`长视频生成失败: ${t.message}`,type:"error"}}}async handleAIAnalyze(e){var t;try{const{analyzeWithAI:r}=await w(async()=>{const{analyzeWithAI:s}=await import("./tool-windows-BIjc1zsU.js").then(o=>o.$);return{analyzeWithAI:s}},__vite__mapDeps([0,1,3]),import.meta.url),a=await r(e.context,{onChunk:s=>{},onAddSteps:s=>{}},e.modelRef||null);return{success:a.success,data:{response:a.response},type:"text",addSteps:(t=a.generatedSteps)==null?void 0:t.map(s=>({id:s.id,mcp:s.mcp,args:s.args,description:s.description,status:s.status})),error:a.error}}catch(r){return{success:!1,error:`AI 分析失败: ${r.message}`,type:"error"}}}async handleGenerateImage(e){var t;try{const{createImageTask:r}=await w(async()=>{const{createImageTask:s}=await import("./startup-app-DxX-P1pm.js").then(o=>o.nL);return{createImageTask:s}},__vite__mapDeps([0]),import.meta.url),a=await r(e);return a.success?{success:!0,data:a.data,type:"image",taskId:a.taskId,taskIds:(t=a.data)==null?void 0:t.taskIds}:(console.error("[SWCapabilities] Image task creation failed:",a.error),{success:!1,error:a.error||"图片生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Image generation error:",r),{success:!1,error:`图片生成失败: ${r.message}`,type:"error"}}}async handleGenerateVideo(e){var t;try{const{createVideoTask:r}=await w(async()=>{const{createVideoTask:s}=await import("./ai-chat-B5qFht2H.js").then(o=>o._);return{createVideoTask:s}},__vite__mapDeps([0,1]),import.meta.url),a=await r(e);return a.success?{success:!0,data:a.data,type:"video",taskId:a.taskId,taskIds:(t=a.data)==null?void 0:t.taskIds}:(console.error("[SWCapabilities] Video task creation failed:",a.error),{success:!1,error:a.error||"视频生成任务创建失败",type:"error"})}catch(r){return console.error("[SWCapabilities] Video generation error:",r),{success:!1,error:`视频生成失败: ${r.message}`,type:"error"}}}getInsertionPoint(e){const t=e.appState,r=(t==null?void 0:t.lastSelectedElementIds)||[];if(r.length>0){const a=r.map(s=>e.children.find(o=>o.id===s)).filter(Boolean);if(a.length>0)try{const s=C(e,a,!1);return[s.x+s.width/2,s.y+s.height+50]}catch{}}if(e.children&&e.children.length>0){let a=0,s=100;for(const o of e.children)try{const n=C(e,[o],!1),i=n.y+n.height;i>a&&(a=i,s=n.x+n.width/2)}catch{}return[s,a+50]}return[100,100]}insertElementsToCanvas(e,t){try{const r=this.getInsertionPoint(e);return e.insertFragment({elements:JSON.parse(JSON.stringify(t))},r,F.paste),requestAnimationFrame(()=>{T(e,r)}),{success:!0,elementsCount:t.length}}catch(r){return{success:!1,error:r.message}}}insertElementsToCanvasAtPoint(e,t,r){try{return e.insertFragment({elements:JSON.parse(JSON.stringify(t))},r,F.paste),requestAnimationFrame(()=>{T(e,r)}),{success:!0,elementsCount:t.length}}catch(a){return console.error("[SWCapabilities] insertElementsToCanvasAtPoint failed:",a),{success:!1,error:a.message}}}getViewportCenter(e){try{const r=D.getBoardContainer(e).getBoundingClientRect(),a=e.viewport.zoom,s=X(e);if(!s)return[0,0];const o=s[0]+r.width/(2*a),n=s[1]+r.height/(2*a);return[o,n]}catch(t){return console.warn("[SWCapabilities] Error getting viewport center:",t),[0,0]}}centerInsertedElementsInViewport(e,t){try{const a=e.children.slice(-t);if(a.length===0){console.warn("[SWCapabilities] No inserted elements found to center");return}const s=C(e,a,!1),n=D.getBoardContainer(e).getBoundingClientRect(),i=80,c=n.width-i*2,d=n.height-i*2,l=c/s.width,g=d/s.height;let u=Math.min(l,g);u=Math.min(Math.max(u,.2),1.5);const h=s.x+s.width/2,p=s.y+s.height/2,I=h-n.width/(2*u),A=p-n.height/(2*u);J.updateViewport(e,[I,A],u)}catch(r){console.warn("[SWCapabilities] Error centering inserted elements:",r)}}extractCodeBlock(e,t){const r=new RegExp(`\`\`\`${t}\\s*\\n([\\s\\S]*?)\\n\\s*\`\`\``,"i"),a=e.match(r);if(a)return a[1].trim();const s=new RegExp(`\`\`\`${t}\\s*([\\s\\S]*?)\\s*\`\`\``,"i"),o=e.match(s);if(o)return o[1].trim();const n=new RegExp(`^${t}\\s*\\n`,"i");return n.test(e.trim())?e.trim().replace(n,"").trim():e.trim()}extractSvgCode(e){let t=this.extractCodeBlock(e,"svg");if(t===e&&(t=this.extractCodeBlock(e,"xml")),t===e&&!t.trim().startsWith("<svg")){const r=t.match(/<svg[\s\S]*?<\/svg>/i);r&&(t=r[0])}return t.trim()}normalizeSvg(e){let t=e.trim();return t.includes("xmlns=")||(t=t.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),t}parseSvgDimensions(e){const t=e.match(/viewBox=["']([^"']+)["']/i);if(t){const[,,s,o]=t[1].split(/\s+/).map(Number);if(s&&o)return{width:s,height:o}}const r=e.match(/width=["'](\d+)(?:px)?["']/i),a=e.match(/height=["'](\d+)(?:px)?["']/i);return r&&a?{width:parseInt(r[1]),height:parseInt(a[1])}:{width:400,height:400}}svgToDataUrl(e){return`data:image/svg+xml,${encodeURIComponent(e).replace(/'/g,"%27").replace(/"/g,"%22")}`}}const O=new ee,y=Q.WORKFLOWS;class te{async isAvailable(){try{return(await $()).objectStoreNames.contains(y)}catch{return!1}}async getDB(){return $()}async saveWorkflow(e){try{const t=await this.getDB();if(!t.objectStoreNames.contains(y))return;await new Promise((r,a)=>{const n=t.transaction(y,"readwrite").objectStore(y).put(e);n.onerror=()=>{r()},n.onsuccess=()=>r()})}catch{}}async getWorkflow(e){if(!e)return null;const t=await this.getDB();return new Promise((r,a)=>{const n=t.transaction(y,"readonly").objectStore(y).get(e);n.onerror=()=>a(n.error),n.onsuccess=()=>r(n.result||null)})}async deleteWorkflow(e){if(!e)return;const t=await this.getDB();return new Promise((r,a)=>{const n=t.transaction(y,"readwrite").objectStore(y).delete(e);n.onerror=()=>a(n.error),n.onsuccess=()=>r()})}close(){}}const f=new te;function re(m){const e=m.steps.find(t=>t.status==="failed");return(e==null?void 0:e.error)||"Unknown error"}function ae(m){return m.steps.filter(e=>e.status!=="pending"?!1:e.dependsOn&&e.dependsOn.length>0?e.dependsOn.every(t=>{const r=m.steps.find(a=>a.id===t);return(r==null?void 0:r.status)==="completed"}):!0)}function se(m){const e={...m.params||{}};return m.resolution!==void 0&&e.resolution===void 0&&(e.resolution=m.resolution),m.quality!==void 0&&e.quality===void 0&&(e.quality=m.quality),typeof m.count=="number"&&Number.isFinite(m.count)&&e.n===void 0&&(e.n=m.count),Object.keys(e).length>0?e:void 0}function ne(m,e){return{prompt:m,model:e.model,modelRef:e.modelRef||null,size:e.size,resolution:e.resolution,quality:e.quality,generationMode:e.generationMode,referenceImages:e.referenceImages&&e.referenceImages.length>0?e.referenceImages:void 0,maskImage:e.maskImage,inputFidelity:e.inputFidelity,background:e.background,outputFormat:e.outputFormat,outputCompression:e.outputCompression,uploadedImages:e.uploadedImages&&e.uploadedImages.length>0?e.uploadedImages:void 0,count:e.count,assetMetadata:e.assetMetadata,promptMeta:e.promptMeta,params:se(e)}}async function oe(m,e={}){var g,u;const t={prompt:m,...e},r=B(t,E.IMAGE);if(!r.valid)throw new Error(r.errors.join(", "));const a=G(t);if(await L.waitForInitialization(),!q("image",e.modelRef||e.model))throw new Error("未配置 API Key,请在设置中配置");const s=U(),o=Date.now(),n=ne(a.prompt,e),i=N("image",e.modelRef||e.model||null);await Z.createTask(s,"image",n,i),S.trackExternalTask({id:s,type:E.IMAGE,status:_.PROCESSING,params:n,createdAt:o,updatedAt:o,startedAt:o,invocationRoute:i,executionPhase:j.SUBMITTING}),(g=e.onTaskCreated)==null||g.call(e,s);const c={taskId:s,prompt:a.prompt,model:e.model,modelRef:e.modelRef||null,size:e.size,resolution:e.resolution,generationMode:e.generationMode,quality:e.quality,referenceImages:e.referenceImages,maskImage:e.maskImage,inputFidelity:e.inputFidelity,background:e.background,outputFormat:e.outputFormat,outputCompression:e.outputCompression,uploadedImages:e.uploadedImages,count:e.count,assetMetadata:e.assetMetadata,params:e.params};await(e.forceMainThread?b.getFallbackExecutor():await b.getExecutor()).generateImage(c,{signal:e.signal});const l=await H(s,{signal:e.signal,onProgress:h=>{S.syncTaskFromStorage(s,h)}});return!l.success||!l.task?{task:l.task||{id:s,type:E.IMAGE,status:_.FAILED,params:{prompt:m},createdAt:Date.now(),updatedAt:Date.now(),error:{code:"GENERATION_ERROR",message:l.error||"图片生成失败"}}}:{task:l.task,url:(u=l.task.result)==null?void 0:u.url}}async function ie(m,e={}){var l,g,u;const t={prompt:m,...e},r=B(t,E.VIDEO);if(!r.valid)throw new Error(r.errors.join(", "));const a=G(t);if(await L.waitForInitialization(),!q("video",e.modelRef||e.model))throw new Error("未配置 API Key,请在设置中配置");const s=U(),o=Date.now(),n=N("video",e.modelRef||e.model||"veo3");await Z.createTask(s,"video",{prompt:a.prompt,model:e.model||"veo3",modelRef:e.modelRef||null,duration:typeof e.duration=="string"?parseInt(e.duration,10):e.duration,size:e.size,params:e.params,promptMeta:e.promptMeta},n),S.trackExternalTask({id:s,type:E.VIDEO,status:_.PROCESSING,params:{prompt:a.prompt,model:e.model||"veo3",modelRef:e.modelRef||null,size:e.size,params:e.params,promptMeta:e.promptMeta},createdAt:o,updatedAt:o,startedAt:o,invocationRoute:n,executionPhase:j.SUBMITTING,progress:0}),(l=e.onTaskCreated)==null||l.call(e,s);const i={taskId:s,prompt:a.prompt,model:e.model||"veo3",modelRef:e.modelRef||null,duration:(g=e.duration)==null?void 0:g.toString(),size:e.size||"1280x720",inputReference:e.inputReference,inputReferences:e.inputReferences,referenceImages:e.referenceImages,params:e.params};await(e.forceMainThread?b.getFallbackExecutor():await b.getExecutor()).generateVideo(i,{signal:e.signal});const d=await H(s,{signal:e.signal,onProgress:h=>{S.syncTaskFromStorage(s,h)}});return!d.success||!d.task?{task:d.task||{id:s,type:E.VIDEO,status:_.FAILED,params:{prompt:m},createdAt:Date.now(),updatedAt:Date.now(),error:{code:"GENERATION_ERROR",message:d.error||"视频生成失败"}}}:{task:d.task,url:(u=d.task.result)==null?void 0:u.url}}class V{constructor(e={}){this.workflows=new Map,this.abortControllers=new Map,this.events$=new Y,this.options={stepTimeout:e.stepTimeout??600*1e3,continueOnError:e.continueOnError??!1,onEvent:e.onEvent??(()=>{}),executeMainThreadTool:e.executeMainThreadTool,forceFallbackExecutor:e.forceFallbackExecutor??!1},this.events$.subscribe(t=>{this.options.onEvent(t)})}async submitWorkflow(e){this.workflows.set(e.id,e);try{await f.saveWorkflow(e)}catch(r){console.warn("[WorkflowEngine] submitWorkflow: IDB 保存失败,继续执行:",r)}const t=new AbortController;this.abortControllers.set(e.id,t),this.executeWorkflow(e.id).catch(r=>{console.error(`[WorkflowEngine] Workflow ${e.id} execution error:`,r)})}async cancelWorkflow(e){const t=this.workflows.get(e);if(!t)return;const r=this.abortControllers.get(e);r==null||r.abort(),t.status="cancelled",t.updatedAt=Date.now(),await f.saveWorkflow(t),this.emitEvent({type:"status",workflowId:e,status:"cancelled"})}getWorkflow(e){return this.workflows.get(e)}async resumeWorkflow(e){if(this.workflows.has(e))return;const t=await f.getWorkflow(e);if(!t)return;const r=t.steps.some(n=>n.status==="pending"),a=t.steps.some(n=>n.status==="running"),s=t.steps.some(n=>n.status==="pending_main_thread");if(!r&&!a&&!s)return;t.steps.forEach(n=>{n.status==="running"&&(n.status="pending")}),this.workflows.set(e,t);const o=new AbortController;this.abortControllers.set(e,o),this.executeWorkflow(e).catch(n=>{console.error("[WorkflowEngine] Resume workflow failed:",e,n)})}async executeWorkflow(e){const t=this.workflows.get(e);if(!t){console.warn("[WorkflowEngine] executeWorkflow: 工作流不存在:",e);return}const r=this.abortControllers.get(e);try{t.status="running",t.updatedAt=Date.now();try{await f.saveWorkflow(t)}catch(o){console.warn("[WorkflowEngine] executeWorkflow: IDB 保存失败,继续:",o)}this.emitEvent({type:"status",workflowId:e,status:"running"}),await this.executeSteps(t,r==null?void 0:r.signal);const a=t.steps.every(o=>o.status==="completed"||o.status==="skipped");t.steps.some(o=>o.status==="failed")&&!this.options.continueOnError?(t.status="failed",t.error=re(t)):a&&(t.status="completed",t.completedAt=Date.now()),t.updatedAt=Date.now(),await f.saveWorkflow(t),t.status==="completed"?this.emitEvent({type:"completed",workflowId:e,workflow:t}):t.status==="failed"&&this.emitEvent({type:"failed",workflowId:e,error:t.error||"Unknown error"})}catch(a){t.status="failed",t.error=a.message||"Workflow execution failed",t.updatedAt=Date.now(),await f.saveWorkflow(t),this.emitEvent({type:"failed",workflowId:e,error:t.error||"Workflow execution failed"})}finally{this.abortControllers.delete(e)}}async executeSteps(e,t){for(;;){if(t!=null&&t.aborted)throw new Error("Workflow cancelled");const r=ae(e);if(r.length===0)break;await Promise.all(r.map(a=>this.executeStep(e,a,t)))}}async executeStep(e,t,r){const a=Date.now();t.status="running",e.updatedAt=Date.now(),await f.saveWorkflow(e),this.emitEvent({type:"step",workflowId:e.id,stepId:t.id,status:"running"});try{await this.executeToolStep(e,t,r),t.status="completed",t.duration=Date.now()-a,e.updatedAt=Date.now(),await f.saveWorkflow(e),this.emitEvent({type:"step",workflowId:e.id,stepId:t.id,status:"completed",result:t.result,duration:t.duration})}catch(s){if(t.status="failed",t.error=s.message||"Step execution failed",t.duration=Date.now()-a,e.updatedAt=Date.now(),await f.saveWorkflow(e),this.emitEvent({type:"step",workflowId:e.id,stepId:t.id,status:"failed",error:t.error,duration:t.duration}),!this.options.continueOnError)throw s}}async executeToolStep(e,t,r){var a,s,o;switch(t.mcp){case"generate_image":{const n=await oe(t.args.prompt,{model:t.args.model,modelRef:t.args.modelRef||null,size:t.args.size,referenceImages:t.args.referenceImages,generationMode:t.args.generationMode,maskImage:t.args.maskImage,inputFidelity:t.args.inputFidelity,background:t.args.background,outputFormat:t.args.outputFormat,outputCompression:t.args.outputCompression,count:t.args.count,promptMeta:t.args.promptMeta,params:t.args.params,forceMainThread:this.options.forceFallbackExecutor,signal:r,onTaskCreated:i=>{t.result={taskId:i},f.saveWorkflow(e)}});if(n.task.status===_.FAILED)throw new Error(((a=n.task.error)==null?void 0:a.message)||"Image generation failed");t.result={...n.task.result,taskId:n.task.id};break}case"generate_video":{const n=await ie(t.args.prompt,{model:t.args.model,modelRef:t.args.modelRef||null,duration:t.args.seconds??t.args.duration,size:t.args.size,referenceImages:t.args.referenceImages,promptMeta:t.args.promptMeta,params:t.args.params,forceMainThread:this.options.forceFallbackExecutor,signal:r,onTaskCreated:i=>{t.result={taskId:i},f.saveWorkflow(e)}});if(n.task.status===_.FAILED)throw new Error(((s=n.task.error)==null?void 0:s.message)||"Video generation failed");t.result={...n.task.result,taskId:n.task.id};break}case"generate_text":{const c=(await b.getFallbackExecutor().generateText({prompt:t.args.prompt,model:t.args.model,modelRef:t.args.modelRef||null,referenceImages:t.args.referenceImages,params:t.args.params},{signal:r})).content;t.result={content:c};const d=`${t.id}-insert-text`;if(!e.steps.find(l=>l.id===d)){const l={id:d,mcp:"insert_to_canvas",args:{items:[{type:"text",content:c}]},description:"将生成文本插入画布",status:"pending"};e.steps.push(l),await f.saveWorkflow(e),this.emitEvent({type:"steps_added",workflowId:e.id,steps:[l]})}break}case"ai_analyze":{const n=b.getFallbackExecutor(),i=t.id,c=await n.aiAnalyze({taskId:i,messages:t.args.messages,prompt:t.args.prompt,referenceImages:t.args.referenceImages,images:t.args.images,textModel:t.args.textModel,model:t.args.model,modelRef:t.args.modelRef||null},{signal:r});if(t.result={content:c.content},c.addSteps&&c.addSteps.length>0){for(const d of c.addSteps)e.steps.find(l=>l.id===d.id)||e.steps.push({id:d.id,mcp:d.mcp,args:d.args,description:d.description,status:d.status});await f.saveWorkflow(e),this.emitEvent({type:"steps_added",workflowId:e.id,steps:e.steps.filter(d=>d.status==="pending")})}else if(c.content&&c.content.trim()){const d=`${t.id}-insert-text`;if(!e.steps.find(l=>l.id===d)){const l=((o=e.metadata)==null?void 0:o.rawInput)||"",g=l.trim()?`# ${l.trim()}
|
|
3
|
-
|
|
4
|
-
`:"",u={id:d,mcp:"insert_to_canvas",args:{items:[{type:"text",content:g+c.content}]},description:"将 AI 回复插入画布",status:"pending"};e.steps.push(u),await f.saveWorkflow(e),this.emitEvent({type:"steps_added",workflowId:e.id,steps:[u]})}}break}case"generate_grid_image":case"generate_inspiration_board":case"generate_ppt":case"split_image":case"generate_long_video":case"insert_mermaid":case"insert_mindmap":case"insert_svg":case"canvas_insert":case"insert_to_canvas":{if(!this.options.executeMainThreadTool)throw new Error(`No main thread tool executor configured for: ${t.mcp}`);const n=await this.options.executeMainThreadTool(t.mcp,t.args);if(!n.success)throw new Error(n.error||`${t.mcp} failed`);t.result=n.result;break}default:throw new Error(`Unknown tool: ${t.mcp}`)}}emitEvent(e){this.events$.next(e)}destroy(){for(const[e,t]of this.abortControllers)t.abort();this.abortControllers.clear(),this.workflows.clear(),this.events$.complete()}}class ce{constructor(){this.events$=new Y,this.workflows=new Map,this.initialized=!1,this.fallbackEngine=null,this.pendingCanvasHandler=null}init(){this.initialized||(this.initialized=!0)}destroy(){this.events$.complete(),this.initialized=!1}async recoverWorkflows(){try{let e=[];if(await k.isAvailable()&&(e=await k.getAllWorkflows()),e.length===0)return[];for(const t of e){const r=this.workflows.get(t.id);(!r||t.updatedAt>(r.updatedAt||0))&&(this.workflows.set(t.id,t),t.status==="failed"&&(r==null?void 0:r.status)!=="failed"&&this.events$&&this.events$.next({type:"failed",workflowId:t.id,error:t.error||"Unknown error"}))}return e.filter(t=>t.status==="running"||t.status==="pending")}catch(e){return console.warn("[WorkflowSubmissionService] Failed to recover workflows:",e),[]}}getRunningWorkflows(){return Array.from(this.workflows.values()).filter(e=>e.status==="running"||e.status==="pending")}notifyStepUpdate(e,t,r,a,s,o){const n=this.workflows.get(e);if(n){const i=n.steps.find(c=>c.id===t);i&&(i.status=r,i.result=a,i.error=s,i.duration=o)}this.events$.next({type:"step",workflowId:e,stepId:t,status:r,result:a,error:s,duration:o})}notifyWorkflowCompleted(e,t){this.workflows.set(e,t),this.events$.next({type:"completed",workflowId:e,workflow:t})}notifyWorkflowFailed(e,t){const r=this.workflows.get(e);r&&(r.status="failed",r.error=t),this.events$.next({type:"failed",workflowId:e,error:t})}isWorkflowManagedByFallback(e){return this.fallbackEngine?this.fallbackEngine.getWorkflow(e)!==void 0:!1}getWorkflowFromFallback(e){if(!this.fallbackEngine)return;const t=this.fallbackEngine.getWorkflow(e);if(t)return{id:t.id,name:t.name,steps:t.steps.map(r=>({id:r.id,mcp:r.mcp,args:r.args,description:r.description,status:r.status,result:r.result,error:r.error,duration:r.duration,options:r.options})),status:t.status,createdAt:t.createdAt,updatedAt:t.updatedAt,completedAt:t.completedAt,error:t.error,context:t.context}}async resumeWorkflowWithFallback(e){return this.fallbackEngine||(this.fallbackEngine=new V({onEvent:t=>this.handleFallbackEngineEvent(t),executeMainThreadTool:async(t,r)=>{try{const a=await O.execute({operation:t,args:r});return{success:a.success,error:a.error}}catch(a){return{success:!1,error:a.message||"Main thread tool execution failed"}}}})),await this.fallbackEngine.resumeWorkflow(e),this.fallbackEngine.getWorkflow(e)!==void 0}createWorkflow(e,t=[]){var l,g;const r=`wf_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a=Date.now(),s=e.generationType==="video"?"generate_video":"generate_image",o={prompt:e.prompt,model:e.modelId,modelRef:e.modelRef||null};e.size&&(o.size=e.size),e.count&&e.count>1&&(o.count=e.count),e.duration&&(o.seconds=e.duration),t.length>0&&(o.referenceImages=t);const n=e.extraParams?{...e.extraParams}:void 0;e.modelId==="happyhorse-1.0-video-edit"&&((g=(l=e.selection)==null?void 0:l.videos)!=null&&g[0])?o.params={...n||{},input_video:(n==null?void 0:n.input_video)||e.selection.videos[0]}:n&&(o.params=n);const i=[],c=e.count||1;for(let u=0;u<c;u++)i.push({id:`step_${u}_${Math.random().toString(36).substr(2,9)}`,mcp:s,args:{...o,count:1},description:e.generationType==="video"?`生成视频 ${u+1}/${c}`:`生成图片 ${u+1}/${c}`,status:"pending"});return{id:r,name:e.generationType==="video"?"视频生成":"图片生成",steps:i,status:"pending",createdAt:a,updatedAt:a,context:{userInput:e.userInstruction,model:e.modelId,modelRef:e.modelRef||null,params:{count:e.count,size:e.size,duration:e.duration},referenceImages:t}}}async submit(e){if(this.workflows.set(e.id,e),k.invalidateCache(),!await this.tryFallbackEngine(e))throw this.workflows.delete(e.id),new Error("Submit workflow failed")}async tryFallbackEngine(e){try{if(!b.getFallbackExecutor())return console.warn("[WorkflowSubmissionService] tryFallbackEngine: fallback executor 不可用"),!1;this.fallbackEngine||(this.fallbackEngine=new V({onEvent:a=>this.handleFallbackEngineEvent(a),forceFallbackExecutor:!0,executeMainThreadTool:async(a,s)=>{try{const o=await O.execute({operation:a,args:s});return{success:o.success,result:o.data,error:o.error}}catch(o){return{success:!1,error:o.message||"Main thread tool execution failed"}}}}));const r={id:e.id,name:e.name,steps:e.steps.map(a=>({id:a.id,mcp:a.mcp,args:a.args,description:a.description,status:a.status,result:a.result,error:a.error,duration:a.duration,options:a.options})),status:e.status,createdAt:e.createdAt,updatedAt:e.updatedAt,completedAt:e.completedAt,error:e.error,context:e.context};return await this.fallbackEngine.submitWorkflow(r),!0}catch(t){return console.error("[WorkflowSubmissionService] Fallback engine error:",t),!1}}handleFallbackEngineEvent(e){switch(e.type){case"status":this.events$.next({type:"status",workflowId:e.workflowId,status:e.status});break;case"step":this.events$.next({type:"step",workflowId:e.workflowId,stepId:e.stepId,status:e.status,result:e.result,error:e.error,duration:e.duration});const t=this.workflows.get(e.workflowId);if(t){const a=t.steps.find(s=>s.id===e.stepId);a&&(a.status=e.status,a.result=e.result,a.error=e.error,a.duration=e.duration),t.updatedAt=Date.now()}break;case"completed":this.events$.next({type:"completed",workflowId:e.workflowId,workflow:e.workflow}),this.workflows.set(e.workflowId,e.workflow);break;case"failed":this.events$.next({type:"failed",workflowId:e.workflowId,error:e.error});const r=this.workflows.get(e.workflowId);r&&(r.status="failed",r.error=e.error,r.updatedAt=Date.now());break;case"steps_added":this.events$.next({type:"steps_added",workflowId:e.workflowId,steps:e.steps.map(a=>({id:a.id,mcp:a.mcp,args:a.args,description:a.description,status:a.status}))});break}}async cancel(e){k.invalidateCache(),this.fallbackEngine&&await this.fallbackEngine.cancelWorkflow(e)}getWorkflow(e){return this.workflows.get(e)}async queryWorkflowStatus(e){try{if(await k.isAvailable()){const t=await k.getWorkflow(e);if(t)return this.workflows.set(e,t),t}}catch(t){console.warn("[WorkflowSubmissionService] Failed to query workflow status:",t)}return this.workflows.get(e)||null}async queryAllWorkflows(){try{if(await k.isAvailable()){const e=await k.getAllWorkflows();for(const t of e)this.workflows.set(t.id,t);return e}}catch(e){console.warn("[WorkflowSubmissionService] Failed to query all workflows:",e)}return Array.from(this.workflows.values())}get events(){return this.events$.asObservable()}subscribeToWorkflow(e,t){return this.events$.pipe(z(r=>r.type==="canvas_insert"?!1:r.workflowId===e)).subscribe(t)}registerCanvasHandler(e){this.pendingCanvasHandler=e}subscribeToToolRequests(e){return this.events$.pipe(z(t=>t.type==="main_thread_tool_request")).subscribe(e)}subscribeToAllEvents(e){return this.events$.subscribe(e)}}const le=new ce,fe=Object.freeze(Object.defineProperty({__proto__:null,workflowSubmissionService:le},Symbol.toStringTag,{value:"Module"}));export{fe as a,ge as s,le as w};
|