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
|
@@ -0,0 +1,6 @@
|
|
|
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 Et}from"./startup-runtime-DTmhLESk.js";import{r as e,j as t,E as ot,c6 as As,er as ht,gr as zs,am as Ds,a0 as as,iz as Xe,a4 as Ls,_ as $s,jc as Os,ig as Vs,jd as zt,hD as rs,hO as Fs,b$ as is,c0 as Us,c2 as Gs,dc as Ks,gT as Ws,je as Bs,jf as qs,dA as gt,bz as _t,ck as ls,ee as Hs,dB as Be,M as Me,bg as Ce,n as Xs,c7 as Js,c8 as Qs,c1 as Dt,ha as xe,jg as Lt,d as Ys,c as Zs,jh as en,ei as tn,av as Je,al as Le,at as Pt,fB as Mt,i4 as cs,y as ve,iV as sn,ji as at,aX as $e,aA as ds,aC as st,jj as nn,fO as Tt,jk as on,j1 as an,j2 as rn,jl as ln,jm as cn,jn as It,iX as us,jo as $t,jp as dn,jq as Ot,j8 as un,a8 as Vt,jr as Ft,js as yt,jt as Ut,ju as Gt,i1 as Kt,i2 as Wt,hl as mn,bQ as fn,bq as pn,jv as hn,ja as Bt,jw as qt}from"./startup-app-eD_rQhSh.js";import{u as Nt,r as gn,g as ms,s as fs}from"./prompt-utils-MF_LILNU.js";import{P as ps}from"./ParametersDropdown-CTSN3ClD.js";import{r as bn,P as xn,U as vn,i as hs,j as Fe,l as bt,k as De,m as Te,K as gs,W as Ht}from"./ai-chat-BO5vbKZW.js";import"./tool-windows-CmgL3thd.js";import{u as bs,C as In,V as yn,a as wn}from"./useCharacters-BAKE4TeJ.js";/* empty css */import{R as xs}from"./ResizableDivider-CUQBmPpx.js";import{c as Xt,d as Cn,e as wt,f as Jt,g as Sn}from"./ai-generation-preferences-service-ZmPTR-wz.js";import{b as Qt}from"./mj-params-M-7csAp7.js";const Yt=(n,s,o)=>{const c=o==="image"?{isGenerating:n,imageLoading:s}:{isGenerating:n,videoLoading:s};window.dispatchEvent(new CustomEvent("ai-generation-state-change",{detail:c}))},vs=(n,s,o)=>{e.useEffect(()=>{const c=r=>{(r.metaKey||r.ctrlKey)&&r.key==="Enter"&&(r.preventDefault(),!n&&s.trim()&&o())};return document.addEventListener("keydown",c),()=>{document.removeEventListener("keydown",c)}},[n,s,o])},Is=n=>{const[s,o]=e.useState(!1),[c,r]=e.useState(!1),d=e.useCallback(_=>{o(_),Yt(_,c,n)},[c,n]),I=e.useCallback(_=>{r(_),Yt(s,_,n)},[s,n]);return{isGenerating:s,isLoading:c,updateIsGenerating:d,updateIsLoading:I}},jn=(n,s,o)=>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":o==="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",_n=[1,2,3,4,5,10,20,50,100],Tn="aitu_image_generation_quantity",kn="aitu_video_generation_quantity",Ct=100,ys=({language:n,type:s,isGenerating:o,hasGenerated:c,canGenerate:r,onGenerate:d,onReset:I,leftContent:_})=>{const E=s==="video"?kn:Tn,[a,h]=e.useState(()=>{try{const i=localStorage.getItem(E);if(i){const w=parseInt(i,10);if(!isNaN(w)&&w>=1&&w<=Ct)return w}}catch{}return 1}),[R,$]=e.useState(!1),[f,S]=e.useState(()=>a.toString()),M=e.useRef(null);e.useEffect(()=>{S(a.toString());try{localStorage.setItem(E,a.toString())}catch{}},[a,E]),e.useEffect(()=>{const i=w=>{M.current&&!M.current.contains(w.target)&&($(!1),C())};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[f]);const C=()=>{let i=parseInt(f,10);(isNaN(i)||i<1)&&(i=1),i>Ct&&(i=Ct),S(i.toString()),h(i)},G=i=>{const w=i.target.value;(w===""||/^\d*$/.test(w))&&S(w)},Z=i=>{h(i),S(i.toString()),$(!1)},K=()=>{o||$(!R)},ee=()=>{d(a)};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 ${o?"is-generating":""} ${r?"can-generate":""}`,children:[t.jsxs("div",{className:"quantity-section",ref:M,children:[t.jsx(ot,{content:n==="zh"?"生成数量":"Quantity",theme:"light",children:t.jsxs("div",{className:`quantity-control ${R?"is-open":""} ${o?"is-disabled":""}`,children:[t.jsx("input",{type:"text",inputMode:"numeric",value:f,onChange:G,onBlur:C,"data-track":"ai_click_quantity_input",onClick:()=>!o&&$(!0),disabled:o,className:"quantity-input"}),t.jsx("button",{type:"button","data-track":"ai_click_quantity_toggle",onClick:i=>{i.stopPropagation(),K()},disabled:o,className:"quantity-toggle",children:t.jsx(As,{className:`quantity-icon ${R?"is-open":""}`})})]})}),R&&t.jsxs("div",{className:"quantity-dropdown",children:[t.jsx("div",{className:"quantity-dropdown-header",children:n==="zh"?"选择数量":"Select Quantity"}),_n.map(i=>t.jsxs("button",{type:"button","data-track":"ai_click_quantity_select",onClick:()=>Z(i),className:`quantity-option ${a===i?"is-selected":""}`,children:[t.jsxs("span",{children:[i," ",s==="video"?n==="zh"?"个":i>1?"videos":"video":n==="zh"?"张":i>1?"images":"image"]}),a===i&&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"})})]},i))]})]}),t.jsx("div",{className:"action-divider"}),t.jsx("button",{"data-track":"ai_click_generate",onClick:ee,disabled:o||!r,className:`generate-button ${o?"loading":""}`,children:o?n==="zh"?"生成中...":"Generating...":c?n==="zh"?"重新生成":"Regenerate":s==="video"?n==="zh"?"生成视频":"Generate Video":n==="zh"?"生成":"Generate"})]}),t.jsx(ot,{content:n==="zh"?"重置表单":"Reset form",theme:"light",children:t.jsx(ht,{"data-track":"ai_click_reset",onClick:I,disabled:o,variant:"text",shape:"circle",icon:t.jsx(zs,{}),className:"action-button--reset-subtle"})})]})},ws=({error:n})=>n?t.jsx("div",{className:"form-error",children:n}):null,Cs=({visible:n,query:s,position:o,showBelow:c=!1,selectedIndex:r,onSelect:d,onClose:I})=>{const{completedCharacters:_,isLoading:E}=bs(),a=e.useRef(null),h=e.useMemo(()=>{if(!s)return _;const f=s.toLowerCase();return _.filter(S=>S.username.toLowerCase().includes(f))},[_,s]);e.useEffect(()=>{if(!n||!a.current)return;const f=a.current.querySelector(".character-mention-popup__item--selected");f&&f.scrollIntoView({block:"nearest"})},[n,r]),e.useEffect(()=>{if(!n)return;const f=S=>{a.current&&!a.current.contains(S.target)&&I()};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[n,I]);const R=e.useCallback(f=>{Ds.track("character_used_in_prompt",{characterId:f.id,username:f.username}),d(f)},[d]);if(!n)return null;const $={position:"fixed",top:o.top,left:o.left,transform:c?"none":"translateY(-100%)",zIndex:as.DROPDOWN_PORTAL,maxHeight:"200px",overflowY:"auto"};return E?t.jsx("div",{ref:a,className:"character-mention-popup",style:$,children:t.jsx("div",{className:"character-mention-popup__empty",children:"加载中..."})}):h.length===0?t.jsx("div",{ref:a,className:"character-mention-popup",style:$,children:t.jsx("div",{className:"character-mention-popup__empty",children:s?`未找到 "${s}" 相关角色`:"暂无可用角色"})}):t.jsx("div",{ref:a,className:"character-mention-popup",style:$,children:h.map((f,S)=>t.jsxs("div",{className:`character-mention-popup__item ${S===r?"character-mention-popup__item--selected":""}`,onClick:()=>R(f),"data-track":"character_click_mention",children:[t.jsx("div",{className:"character-mention-popup__item-avatar",children:t.jsx(In,{characterId:f.id,profilePictureUrl:f.profilePictureUrl,alt:f.username})}),t.jsxs("span",{className:"character-mention-popup__item-name",children:["@",f.username]})]},f.id))})},En={visible:!1,query:"",position:{top:0,left:0},showBelow:!1,startIndex:-1,selectedIndex:0};function Ss({enabled:n=!0,onPromptChange:s,prompt:o}){const[c,r]=e.useState(En),d=e.useRef(null),{completedCharacters:I}=bs(),_=e.useCallback(f=>{if(!d.current)return{top:0,left:0,showBelow:!1};const S=d.current,M=S.getBoundingClientRect(),C=document.createElement("div"),G=window.getComputedStyle(S),Z=["fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","wordSpacing","whiteSpace","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","boxSizing"];C.style.position="absolute",C.style.top="0",C.style.left="-9999px",C.style.visibility="hidden",C.style.whiteSpace="pre-wrap",C.style.overflowWrap="break-word",C.style.overflow="hidden",C.style.width=`${S.clientWidth}px`,Z.forEach(H=>{C.style[H]=G.getPropertyValue(H.replace(/([A-Z])/g,"-$1").toLowerCase())}),document.body.appendChild(C);let K=0,ee=0;try{const H=S.value.substring(0,f),Q=document.createTextNode(H),re=document.createElement("span");re.textContent="",C.appendChild(Q),C.appendChild(re);const ce=re.getBoundingClientRect(),F=C.getBoundingClientRect();K=ce.top-F.top,ee=ce.left-F.left}finally{document.body.removeChild(C)}const i=S.scrollTop,w=parseInt(G.lineHeight)||20;let j=M.top+K-i,y=M.left+ee;const A=240,P=window.innerWidth;y+A>P-16&&(y=P-A-16),y<16&&(y=16);const ke=j<220+16;return ke?j=j+w+4:j=j-48,{top:j,left:y,showBelow:ke}},[]),E=e.useCallback((f,S)=>{if(!n)return;const M=f.substring(0,S),C=M.lastIndexOf("@");if(C===-1){r(ee=>({...ee,visible:!1}));return}const G=C>0?f[C-1]:" ";if(!/\s/.test(G)&&C!==0){r(ee=>({...ee,visible:!1}));return}const Z=M.substring(C+1);if(Z.includes(" ")){r(ee=>({...ee,visible:!1}));return}const K=_(S);r({visible:!0,query:Z,position:{top:K.top,left:K.left},showBelow:K.showBelow,startIndex:C,selectedIndex:0})},[n,_]),a=e.useCallback(f=>{var Z;if(c.startIndex===-1)return;const S=o.substring(0,c.startIndex),M=((Z=d.current)==null?void 0:Z.selectionStart)||o.length,C=o.substring(M),G=`${S}@${f.username} ${C}`;s(G),r(K=>({...K,visible:!1})),setTimeout(()=>{if(d.current){const K=S.length+f.username.length+2;d.current.focus(),d.current.setSelectionRange(K,K)}},0)},[c.startIndex,o,s]),h=e.useCallback(f=>{if(!c.visible)return;const S=c.query?I.filter(M=>M.username.toLowerCase().includes(c.query.toLowerCase())):I;switch(f.key){case"ArrowDown":f.preventDefault(),r(M=>({...M,selectedIndex:Math.min(M.selectedIndex+1,S.length-1)}));break;case"ArrowUp":f.preventDefault(),r(M=>({...M,selectedIndex:Math.max(M.selectedIndex-1,0)}));break;case"Enter":case"Tab":S.length>0&&(f.preventDefault(),a(S[c.selectedIndex]));break;case"Escape":f.preventDefault(),r(M=>({...M,visible:!1}));break}},[c,I,a]),R=e.useCallback((f,S)=>{s(f),E(f,S)},[s,E]),$=e.useCallback(()=>{r(f=>({...f,visible:!1}))},[]);return{mentionState:c,setMentionState:r,textareaRef:d,completedCharacters:I,handleTextChange:R,handleKeyDown:h,handleCharacterSelect:a,closeMentionPopup:$,calculateMentionPosition:_}}const js=({prompt:n,onPromptChange:s,presetPrompts:o,language:c,type:r,disabled:d=!1,onError:I,enableMention:_=!0,videoProvider:E})=>{const[a,h]=e.useState(!1),R=e.useRef(null),$=e.useRef(null),[f,S]=e.useState(null),[M,C]=e.useState(0),{imageHistory:G,videoHistory:Z}=Nt();e.useEffect(()=>{if(typeof Xe.subscribeChanges=="function")return Xe.subscribeChanges(()=>{C(F=>F+1)})},[]);const K=e.useMemo(()=>gn({generationType:r,language:c,promptContents:o,imageHistory:G,videoHistory:Z}),[G,c,r,o,M,Z]),ee=_&&r==="video"&&E==="sora",{mentionState:i,textareaRef:w,handleTextChange:j,handleKeyDown:y,handleCharacterSelect:A,closeMentionPopup:P}=Ss({enabled:ee,onPromptChange:s,prompt:n}),ae=e.useCallback(()=>{if($.current&&a){const F=$.current.getBoundingClientRect(),T=8,W=320,k=400,Ie=window.innerHeight-F.top+4,oe=Math.min(W,window.innerWidth-T*2),he=window.innerWidth-F.right,Ne=window.innerWidth-oe-T,ge=Math.max(Math.min(he,Ne),T),le=Math.min(k,F.top-T,window.innerHeight*.45);S({bottom:Ie,right:ge,maxHeight:le})}},[a]);e.useEffect(()=>{if(a)return ae(),window.addEventListener("scroll",ae,!0),window.addEventListener("resize",ae),()=>{window.removeEventListener("scroll",ae,!0),window.removeEventListener("resize",ae)}},[a,ae]),e.useEffect(()=>{const F=T=>{const W=T.target;if(R.current&&!R.current.contains(W)){const k=document.querySelector(".preset-prompt-panel-portal");k!=null&&k.contains(W)||h(!1)}};if(a)return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[a]);const ke=e.useCallback(F=>{const T=typeof F=="string"?F:F.content;s(T),I==null||I(null),h(!1)},[s,I]),H=e.useCallback(F=>{const T=K.find(W=>W.id===F);T&&(T.pinned?Xe.unpinPrompt(r,T.content):Xe.pinPrompt(r,T.content),C(W=>W+1))},[r,K]),Q=e.useCallback(F=>{const T=K.find(W=>W.id===F);T&&(Xe.deletePrompt(r,T.content),C(W=>W+1))},[r,K]),re=e.useCallback(F=>{const T=F.target.value,W=F.target.selectionStart||0;j(T,W),I==null||I(null)},[j,I]);e.useEffect(()=>{r!=="video"&&P()},[r,P]);const ce=()=>{if(!a||!f)return null;const F=c==="zh"?`${r==="image"?"图片":"视频"}描述预设`:`${r==="image"?"Image":"Video"} Description Presets`,T=t.jsx("div",{className:"preset-prompt-panel-portal",style:{position:"fixed",bottom:f.bottom,right:f.right,zIndex:as.DIALOG_POPOVER,"--panel-max-width":"calc(100vw - 16px)","--panel-max-height":`${f.maxHeight}px`},children:t.jsx(xn,{title:F,items:K,onSelect:ke,onTogglePin:H,onDelete:Q,language:c,disabled:d,showCount:!0})});return $s.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:c==="zh"?`${r==="image"?"图片":"视频"}描述`:`${r==="image"?"Image":"Video"} Description`}),t.jsx("div",{className:"textarea-with-preset",children:t.jsxs("div",{className:"preset-tooltip-container",ref:R,children:[t.jsx("button",{ref:$,type:"button",className:"preset-icon-button",disabled:d,onClick:()=>h(!a),children:t.jsx(Ls,{size:16})}),ce()]})})]}),t.jsxs("div",{className:"prompt-textarea-wrapper",children:[t.jsx("textarea",{ref:w,className:"form-textarea",value:n,onChange:re,onKeyDown:y,placeholder:jn(c,r,E),rows:4,disabled:d}),t.jsx(bn,{className:"prompt-optimize-button",originalPrompt:n,language:c,scenarioId:r==="image"?"tool.image":"tool.video",disabled:d,tooltipPlacement:"top",allowStructuredMode:!0,onApply:F=>{s(F),I==null||I(null)}})]}),ee&&t.jsx(Cs,{visible:i.visible,query:i.query,position:i.position,showBelow:i.showBelow,selectedIndex:i.selectedIndex,onSelect:A,onClose:P})]})};function _s(){return Os("scene")}function Zt(n,s){return{id:_s(),order:n,duration:s,prompt:""}}function Pn(n,s,o=1){if(n.length===0)return{valid:!1,error:"至少需要一个场景"};for(const r of n){if(r.duration<o)return{valid:!1,error:`场景 ${r.order} 时长不能少于 ${o} 秒`};if(r.duration>s)return{valid:!1,error:`场景 ${r.order} 时长不能超过 ${s} 秒`}}const c=n.find(r=>!r.prompt.trim());return c?{valid:!1,error:`场景 ${c.order} 需要填写提示词`}:{valid:!0}}function Mn(n){return n.sort((s,o)=>s.order-o.order).map((s,o)=>`Shot ${o+1}:
|
|
3
|
+
duration: ${s.duration}sec
|
|
4
|
+
Scene: ${s.prompt.trim()}`).join(`
|
|
5
|
+
|
|
6
|
+
`)}function Nn(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,o=[];let c;for(;(c=s.exec(n))!==null;){const r=parseInt(c[1],10),d=parseFloat(c[2]),I=c[3].trim();o.push({id:_s(),order:r,duration:d,prompt:I})}return o.length===0?null:o.sort((r,d)=>r.order-d.order)}const Rn=({value:n,onChange:s,placeholder:o,disabled:c=!1,autoFocus:r=!1,enableMention:d=!0})=>{const{mentionState:I,textareaRef:_,handleTextChange:E,handleKeyDown:a,handleCharacterSelect:h,closeMentionPopup:R}=Ss({enabled:d,onPromptChange:s,prompt:n}),$=e.useCallback(f=>{const S=f.target.value,M=f.target.selectionStart||0;E(S,M)},[E]);return e.useEffect(()=>{r&&_.current&&_.current.focus()},[r,_]),t.jsxs("div",{className:"scene-prompt-input",children:[t.jsx("textarea",{ref:_,className:"scene-prompt-input__textarea",value:n,onChange:$,onKeyDown:a,placeholder:o,disabled:c,rows:3}),d&&t.jsx(Cs,{visible:I.visible,query:I.query,position:I.position,showBelow:I.showBelow,selectedIndex:I.selectedIndex,onSelect:h,onClose:R})]})},An=({enabled:n,onEnabledChange:s,totalDuration:o,maxScenes:c,minSceneDuration:r,scenes:d,onScenesChange:I,disabled:_=!1})=>{const[E,a]=e.useState(null),h=e.useRef(null),R=d.map(i=>i.id).join("|");e.useEffect(()=>{if(!n||d.length===0)return;!(E?d.some(w=>w.id===E):!1)&&E!==d[0].id&&a(d[0].id)},[n,R,d,E]);const $=e.useCallback(()=>{if(d.length>=c)return;const i=d.reduce((A,P)=>A+P.duration,0),w=o-i;let j=Math.max(r,w/2);j=parseFloat(j.toFixed(1)),j<r&&(j=r);const y=Zt(d.length+1,j);I([...d,y]),a(y.id),setTimeout(()=>{var A;(A=h.current)==null||A.scrollIntoView({behavior:"smooth"})},100)},[d,c,o,r,I]),f=e.useCallback(i=>{var y;if(d.length<=1)return;const j=d.filter(A=>A.id!==i).map((A,P)=>({...A,order:P+1}));I(j),E===i&&a(((y=j[0])==null?void 0:y.id)||null)},[d,I,E]),S=e.useCallback(i=>{const w=d.filter(j=>j.id!==i).reduce((j,y)=>j+y.duration,0);return Math.max(r,o-w)},[d,o,r]),M=e.useCallback(i=>{const w=S(i),j=[],y=.1;for(let A=r;A<=w+.001;A+=y){const P=parseFloat(A.toFixed(1));P<=w&&j.push({label:`${P}`,value:P})}return j},[r,S]),C=e.useCallback((i,w)=>{const j=typeof w=="string"?parseFloat(w):w;if(isNaN(j))return;const y=S(i),A=d.map(P=>{if(P.id===i){const ae=Math.max(r,Math.min(j,y)),ke=parseFloat(ae.toFixed(1));return ke===P.duration?P:{...P,duration:ke}}return P});A.every((P,ae)=>P===d[ae])||I(A)},[d,r,S,I]),G=e.useCallback((i,w)=>{const j=d.find(A=>A.id===i);if((j==null?void 0:j.prompt)===w)return;const y=d.map(A=>A.id===i?{...A,prompt:w}:A);I(y)},[d,I]),Z=e.useCallback(i=>{if(s(i),i&&d.length===0){const w=Zt(1,o);I([w]),a(w.id)}},[d,o,s,I]),K=e.useCallback(i=>{a(i)},[]),ee=d.length<c;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(Vs,{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:["共 ",d.length," 个场景,已用 ",d.reduce((i,w)=>i+w.duration,0).toFixed(1)," 秒 / 总时长 ",o," 秒"]})]}),t.jsxs("div",{className:"storyboard-editor__scenes",children:[d.map((i,w)=>{const j=E===i.id,y=w===d.length-1;return t.jsxs("div",{className:`storyboard-editor__scene-wrapper ${j?"is-selected":""}`,children:[t.jsx("div",{className:`storyboard-editor__timeline-line ${y?"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:()=>K(i.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:i.prompt||"暂无场景描述..."})}),t.jsxs("div",{className:"storyboard-editor__scene-duration-badge",children:[t.jsx(zt,{size:"12px"}),t.jsxs("span",{children:[i.duration,"s"]})]}),t.jsx(rs,{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(zt,{className:"storyboard-editor__time-icon"}),t.jsx(Fs,{value:parseFloat(i.duration.toFixed(1)),onChange:A=>C(i.id,A),disabled:_,className:"storyboard-editor__duration-select",size:"small",options:M(i.id),filterable:!0,creatable:!0,popupProps:{overlayClassName:"storyboard-editor__duration-popup"}}),d.length>1&&t.jsx(ht,{theme:"default",variant:"text",size:"small",icon:t.jsx(is,{}),onClick:A=>{A.stopPropagation(),f(i.id)},disabled:_,className:"storyboard-editor__scene-delete"})]})]}),t.jsx("div",{className:"storyboard-editor__scene-prompt",children:t.jsx(Rn,{value:i.prompt,onChange:A=>G(i.id,A),placeholder:`描述场景 ${w+1} 的内容,输入 @ 可引用角色`,disabled:_,autoFocus:!0,enableMention:!0})})]})]},i.id)}),t.jsx("div",{ref:h})]}),ee&&t.jsx(ht,{theme:"default",variant:"dashed",size:"medium",icon:t.jsx(Us,{}),onClick:$,disabled:_,className:"storyboard-editor__add-btn",block:!0,children:"添加场景"})]})]})},Ts="aitu-dialog-task-list-width-",Rt=240,At=800,zn=()=>{const n=Math.round(660);return Math.max(Rt,Math.min(At,n))},ks=n=>{try{const s=localStorage.getItem(Ts+n);if(s){const o=parseInt(s,10);if(!isNaN(o)&&o>=Rt&&o<=At)return o}}catch{}return zn()},es=(n,s)=>{try{localStorage.setItem(Ts+n,s.toString())}catch{}},Es=({isRightPanelVisible:n,onToggleRightPanel:s,onWidthChange:o,rightPanelWidth:c,minWidth:r=Rt,maxWidth:d=At,onResizeStart:I,onResizeEnd:_,language:E="zh",disabled:a=!1,storageKey:h="image"})=>{const[R,$]=e.useState(!1),f=e.useRef(0),S=e.useRef(0);e.useEffect(()=>(R?(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=""}),[R]);const M=e.useCallback(G=>{if(a||!n)return;G.preventDefault(),G.stopPropagation(),$(!0),f.current=G.clientX,S.current=c,I==null||I();const Z=ee=>{const i=f.current-ee.clientX,w=Math.max(r,Math.min(d,S.current+i));o(w)},K=()=>{$(!1),_==null||_(),S.current+(f.current-document.body.getBoundingClientRect().left),es(h,c),document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",K)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",K)},[a,n,c,r,d,o,I,_,h]);e.useEffect(()=>{!R&&n&&es(h,c)},[c,R,n,h]);const C=n?E==="zh"?"隐藏任务列表":"Hide Task List":E==="zh"?"显示任务列表":"Show Task List";return t.jsxs("div",{className:`resizable-divider ${R?"is-dragging":""} ${n?"":"is-collapsed"} ${a?"is-disabled":""}`,onMouseDown:M,children:[t.jsx("div",{className:"resizable-divider__bar"}),t.jsx(ot,{content:C,placement:"left",children:t.jsx("button",{type:"button",className:"resizable-divider__toggle",onClick:G=>{G.stopPropagation(),s()},"aria-label":C,children:n?t.jsx(rs,{size:"14px"}):t.jsx(Gs,{size:"14px"})})})]})},Ps=({storageKey:n,language:s})=>{const[o,c]=e.useState(()=>{try{return localStorage.getItem(n)!=="false"}catch{return!0}}),r=e.useCallback(d=>{c(d);try{localStorage.setItem(n,String(d))}catch{}},[n]);return t.jsx(ot,{content:s==="zh"?"生成后自动插入画布":"Auto insert to canvas after generation",theme:"light",children:t.jsx(Ks,{checked:o,onChange:r,className:"auto-insert-checkbox"})})};function kt(n){try{return localStorage.getItem(n)!=="false"}catch{return!0}}function Dn(n={}){const{taskType:s}=n,{tasks:o,isLoading:c}=Ws(),{retryTask:r,deleteTask:d}=Bs(),I=e.useMemo(()=>[...s?o.filter(h=>h.type===s):o].sort((h,R)=>R.createdAt-h.createdAt),[o,s]),_=e.useCallback(async()=>{},[]),E=e.useCallback(async()=>{if(qs(),!await gt.isAvailable())return;const h=await gt.getAllTasks();h.length>0&&_t.restoreTasks(h)},[]);return{tasks:I,isLoading:c,isLoadingMore:!1,hasMore:!1,totalCount:I.length,loadedCount:I.length,loadMore:_,refresh:E,retryTask:r,deleteTask:d}}let nt={prompt:"",imageCount:0,knowledgeContextCount:0};function Ln(n){nt={prompt:n.prompt,imageCount:n.imageCount,knowledgeContextCount:n.knowledgeContextCount}}function $n(){nt={prompt:"",imageCount:0,knowledgeContextCount:0}}function On(){return nt.prompt.trim().length>0||nt.imageCount>0||nt.knowledgeContextCount>0}const Ms=({taskIds:n,taskType:s,onEditTask:o})=>{const{tasks:c,isLoading:r,isLoadingMore:d,hasMore:I,totalCount:_,loadedCount:E,loadMore:a,retryTask:h,deleteTask:R}=Dn({taskType:s}),{board:$,openDialog:f}=ls(),{confirm:S,confirmDialog:M}=Hs(),[C,G]=e.useState(!1),[Z,K]=e.useState(null),[ee,i]=e.useState(!1),[w,j]=e.useState(0),[y,A]=e.useState("single"),[P,ae]=e.useState(""),[ke,H]=e.useState(null),[Q,re]=e.useState(!1),ce=e.useMemo(()=>c.filter(u=>u.status===Be.FAILED).length,[c]),F=e.useCallback(()=>{const u=c.filter(b=>b.status===Be.FAILED);u.forEach(b=>R(b.id)),re(!1),Me.success(`已清除 ${u.length} 个失败任务`)},[c,R]),T=(u,b)=>{var ue,v,Se,je,ze,be,ye,we,ie,Re,Ae;if(!b.trim())return!0;const J=b.toLowerCase().split(/\s+/).filter(Boolean),z={[Be.PENDING]:"处理中",[Be.PROCESSING]:"处理中",[Be.COMPLETED]:"已完成",[Be.FAILED]:"失败",[Be.CANCELLED]:"已取消"},O=[],se=(ue=u.params)!=null&&ue.params&&typeof u.params.params=="object"?u.params.params:null;O.push(((v=u.params)==null?void 0:v.prompt)??""),O.push(((Se=u.params)==null?void 0:Se.model)??""),O.push(u.id??""),O.push(z[u.status]??String(u.status)),(je=u.params)!=null&&je.batchId&&O.push(String(u.params.batchId)),(ze=u.params)!=null&&ze.batchIndex&&O.push(String(u.params.batchIndex)),(be=u.params)!=null&&be.batchTotal&&O.push(String(u.params.batchTotal)),typeof(se==null?void 0:se.model_name)=="string"&&O.push(se.model_name),typeof(se==null?void 0:se.mode)=="string"&&O.push(se.mode),typeof(se==null?void 0:se.klingAction2)=="string"&&O.push(se.klingAction2),(ye=u.result)!=null&&ye.format&&O.push(String(u.result.format)),(we=u.result)!=null&&we.width&&((ie=u.result)!=null&&ie.height)?O.push(`${u.result.width}x${u.result.height}`):(Re=u.params)!=null&&Re.width&&((Ae=u.params)!=null&&Ae.height)&&O.push(`${u.params.width}x${u.params.height}`);const de=O.join(" ").toLowerCase();return J.every(Y=>de.includes(Y))},W=e.useMemo(()=>{let u=c;return n&&n.length>0&&(u=u.filter(b=>n.includes(b.id))),P.trim()&&(u=u.filter(b=>T(b,P))),u.sort((b,J)=>J.createdAt-b.createdAt)},[c,n,P]),k=u=>{h(u)},Ie=u=>{K(u),G(!0)},oe=()=>{Z&&R(Z),G(!1),K(null)},he=async u=>{const b=c.find(z=>z.id===u);if(!b)return;const J=en(b);if(J.length!==0)try{const z=await tn(J);z.openedCount>0&&z.downloadedCount===0?Me.success(z.openedCount>1?`已打开 ${z.openedCount} 个链接,请在新标签页下载`:"资源不支持直接下载,已打开链接"):Me.success(b.type===Ce.AUDIO?J.length>1?"多条音频已开始下载":"音频下载成功":J.length>1?"多图已开始下载":"下载成功")}catch(z){console.error("Download failed:",z),Me.error("下载失败,请稍后重试")}},Ne=async u=>{var J,z,O,se;const b=c.find(de=>de.id===u);if(!((J=b==null?void 0:b.result)!=null&&J.url)&&!((O=(z=b==null?void 0:b.result)==null?void 0:z.urls)!=null&&O.length)||!$){console.warn("Cannot insert: task result or board not available"),Me.warning("无法插入:白板未就绪");return}try{if(b.type===Ce.IMAGE){const de=(se=b.result.urls)!=null&&se.length?b.result.urls:[b.result.url];for(const ue of de)await Ys($,ue);Me.success(de.length>1?"多图已插入到白板":"图片已插入到白板")}else b.type===Ce.VIDEO&&(await Zs($,b.result.url),Me.success("视频已插入到白板"))}catch(de){console.error("Failed to insert to board:",de),Me.error(`插入失败: ${de instanceof Error?de.message:"未知错误"}`)}},ge=e.useCallback(async()=>On()?S({title:"覆盖当前输入?",description:"当前 AI 图片生成窗口已有提示词或参考图,继续会覆盖当前输入。",confirmText:"覆盖当前输入",cancelText:"取消",confirmTheme:"warning"}):!0,[S]),le=async u=>{const b=await gt.getTask(u)||_t.getTask(u)||c.find(J=>J.id===u);if(!b||b.type!==Ce.IMAGE){Me.warning("未找到可回填的图片任务");return}await ge()&&(o?o(b):f(xe.aiImageGeneration,Lt(b)),Me.success("已回填历史提示词和参考图,请手动发送"))},me=async u=>{var J,z;const b=await gt.getTask(u)||_t.getTask(u)||c.find(O=>O.id===u);if(!b){console.warn("Cannot edit: task not found");return}if(o){o(b);return}if(b.type===Ce.IMAGE)f(xe.aiImageGeneration,Lt(b));else if(b.type===Ce.VIDEO){const O={initialPrompt:b.params.prompt,initialDuration:typeof b.params.seconds=="string"?parseInt(b.params.seconds,10):b.params.seconds,initialModel:b.params.model,initialSize:b.params.size,initialImages:b.params.uploadedImages,initialResultUrl:(J=b.result)==null?void 0:J.url,initialResultUrls:(z=b.result)==null?void 0:z.urls};f(xe.aiVideoGeneration,O)}},m=u=>{const b=c.find(J=>J.id===u);b&&H(b)},V=e.useMemo(()=>{const u=new Set;return W.filter(b=>{var J,z,O,se;return b.status!==Be.COMPLETED||!((J=b.result)!=null&&J.url)&&!((O=(z=b.result)==null?void 0:z.urls)!=null&&O.length)||b.type!==Ce.IMAGE&&b.type!==Ce.VIDEO&&!(b.type===Ce.AUDIO&&((se=b.result)==null?void 0:se.resultKind)!=="lyrics")||u.has(b.id)?!1:(u.add(b.id),!0)})},[W]),{previewMediaItems:te,taskIdToPreviewConfig:Ee}=e.useMemo(()=>{var J,z,O,se,de,ue;const u=[],b=new Map;for(const v of V){const Se=u.length,je=((J=v.result)==null?void 0:J.title)||v.params.title||((z=v.params.prompt)==null?void 0:z.substring(0,50))||"媒体预览";if(v.type===Ce.AUDIO){const be=((se=(O=v.result)==null?void 0:O.clips)==null?void 0:se.filter(ie=>!!ie.audioUrl).map((ie,Re)=>{var Ae,Y,Ue;return{id:ie.clipId||ie.id||`${v.id}-${Re}`,url:ie.audioUrl,type:"audio",title:ie.title||((Ae=v.result)!=null&&Ae.clips&&v.result.clips.length>1?`${je} (${Re+1}/${v.result.clips.length})`:je),posterUrl:ie.imageLargeUrl||ie.imageUrl||((Y=v.result)==null?void 0:Y.previewImageUrl),duration:typeof ie.duration=="number"?ie.duration:(Ue=v.result)==null?void 0:Ue.duration,prompt:v.params.prompt,tags:typeof v.params.tags=="string"?v.params.tags:void 0,artist:v.params.model||v.params.mv||"Aitu",album:"Aitu Generated"}}))??[],ye=(de=v.result.urls)!=null&&de.length?v.result.urls:v.result.url?[v.result.url]:[],we=be.length>0?be:ye.map((ie,Re)=>{var Ae,Y;return{id:ye.length>1?`${v.id}-${Re}`:v.id,url:ie,type:"audio",title:ye.length>1?`${je} (${Re+1}/${ye.length})`:je,posterUrl:(Ae=v.result)==null?void 0:Ae.previewImageUrl,duration:(Y=v.result)==null?void 0:Y.duration,prompt:v.params.prompt,tags:typeof v.params.tags=="string"?v.params.tags:void 0,artist:v.params.model||v.params.mv||"Aitu",album:"Aitu Generated"}});u.push(...we)}else{const be=(ue=v.result.urls)!=null&&ue.length?v.result.urls:[v.result.url],ye=v.type===Ce.VIDEO?"video":"image";for(let we=0;we<be.length;we++)u.push({id:be.length>1?`${v.id}-${we}`:v.id,url:ye==="image"?Xs(be[we]):be[we],type:ye,title:be.length>1?`${je} (${we+1}/${be.length})`:je})}const ze=u.length-Se;b.set(v.id,{mode:v.type===Ce.AUDIO&&ze>1?"compare":"single",index:v.type===Ce.AUDIO&&ze>1?Array.from({length:Math.min(ze,4)},(be,ye)=>Se+ye):Se})}return{previewMediaItems:u,taskIdToPreviewConfig:b}},[V]),fe=e.useCallback(u=>{const b=Ee.get(u);b!==void 0&&(A(b.mode),j(b.index),i(!0))},[Ee]),D=e.useCallback(()=>{i(!1)},[]),U=P.trim()&&W.length===0&&c.length>0,X=_>0?_:c.length;return t.jsxs(t.Fragment,{children:[M,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:["生成任务 (",X,")"]}),t.jsx("div",{className:"dialog-task-list__header-actions",children:ce>0&&t.jsx(ot,{content:`清除全部失败任务 (${ce})`,theme:"light",children:t.jsx(ht,{size:"small",variant:"text",icon:t.jsx(is,{}),onClick:()=>re(!0)})})})]}),t.jsx("div",{className:"dialog-task-list__search",children:t.jsx(Js,{value:P,onChange:u=>ae(u),placeholder:"搜索任务(提示词/模型/...)",clearable:!0,prefixIcon:t.jsx(Qs,{}),size:"small"})})]}),t.jsx(yn,{tasks:W,onRetry:k,onDelete:Ie,onDownload:he,onInsert:Ne,onEdit:me,onRegenerate:le,onPreviewOpen:fe,onExtractCharacter:m,hasMore:I,isLoadingMore:d,onLoadMore:a,totalCount:X,loadedCount:E,className:"dialog-task-list__content",emptyContent:t.jsx("div",{className:"dialog-task-list__empty",children:r?t.jsx("p",{children:"加载中..."}):U?t.jsx("p",{children:"未找到匹配的任务"}):t.jsx("p",{children:"暂无生成任务"})})})]}),t.jsx(Dt,{open:C,title:"确认删除",description:"确定要删除此任务吗?此操作无法撤销。",confirmText:"删除",cancelText:"取消",danger:!0,onOpenChange:G,onConfirm:oe}),t.jsx(Dt,{open:Q,title:"清除失败任务",description:`确定要清除全部 ${ce} 个失败任务吗?此操作无法撤销。`,confirmText:"清除",cancelText:"取消",danger:!0,onOpenChange:re,onConfirm:F}),t.jsx(vn,{visible:ee,items:te,initialMode:y,initialIndex:w,onClose:D,showThumbnails:!0}),t.jsx(wn,{visible:!!ke,task:ke,onClose:()=>H(null),onCreateComplete:u=>{H(null)}})]})};function Ns(n){if(!n)return;if(n==="auto")return at;const s=n.replace(/[xX]/g,":");return on.some(o=>o.value===s)?s:void 0}function ft(n,s){return Ns(n.size)||s||at}function ts(n,s,o){if(n.startsWith("mj")||!o)return s;const c=o===at?"auto":Tt(o);return!c||!nn(n).some(r=>r.value===c)||s.size===c?s:{...s,size:c}}const Vn=({initialPrompt:n="",initialImages:s=[],initialKnowledgeContextRefs:o=[],selectedElementIds:c=[],initialWidth:r,initialHeight:d,initialResultUrl:I,initialAspectRatio:_,targetFrameId:E,targetFrameDimensions:a,pptSlideImage:h,pptSlidePrompt:R,pptReplaceElementId:$,selectedModel:f,selectedModelRef:S,onModelChange:M,onModelRefChange:C,externalBatchId:G,assetMetadata:Z,initialAutoInsertToCanvas:K,onDraftChange:ee}={})=>{var et,tt,ct;const i=hs("image"),w=Je("image"),j=Fe(i,w.modelId,Le(w.profileId,w.modelId))||bt("image",w.modelId,Le(w.profileId,w.modelId)),[y,A]=e.useState((j==null?void 0:j.id)||((et=i[0])==null?void 0:et.id)||"gemini-2.5-flash-image-vip"),[P,ae]=e.useState(De(j)||Le(w.profileId,w.modelId)),ke=Te((j==null?void 0:j.id)||((tt=i[0])==null?void 0:tt.id)||"gemini-2.5-flash-image-vip",De(j)||Le(w.profileId,w.modelId)),H=Xt((j==null?void 0:j.id)||((ct=i[0])==null?void 0:ct.id)||"gemini-2.5-flash-image-vip",ke),[Q,re]=e.useState(n),[ce,F]=e.useState(o),[T,W]=e.useState(H.extraParams),k=e.useMemo(()=>{if(Fe(i,y,P)||!y)return i;const L=bt("image",y,P);return L?[L,...i]:i},[y,P,i]),[Ie,oe]=e.useState(r||1024),[he,Ne]=e.useState(d||1024),[ge,le]=e.useState(_||ft(H.extraParams,H.aspectRatio)),[me,m]=e.useState(null),[V,te]=e.useState(s),[Ee,fe]=e.useState(!0),[D,U]=e.useState(()=>ks("image")),[X,u]=e.useState("config"),b=e.useRef(null),{viewportWidth:J}=Pt(),z=J<=768,{imageHistory:O}=Nt(),[se,de]=e.useState(0),{isGenerating:ue}=Is("image"),{language:v}=Mt(),{createTask:Se}=cs(),je=e.useRef(!1);e.useEffect(()=>Xe.subscribeChanges(()=>{de(x=>x+1)}),[]);const ze=y.startsWith("mj"),be=ve.useMemo(()=>sn(y).length>0,[y]),[ye,we]=e.useState(!1);e.useEffect(()=>{if(ye)return;const x=Xt(y,Te(y,P)),L=_?ts(y,x.extraParams,_):x.extraParams;W(L),le(ft(L,_||x.aspectRatio))},[y,P,_,ye]);const ie=e.useCallback((x,L)=>{if(!L||L==="default"){x==="size"&&le(at),W(q=>{const B={...q};return delete B[x],B});return}x==="size"&&le(Ns(L)||at),W(q=>({...q,[x]:L}))},[]),Re=e.useCallback(x=>{U(x)},[]),Ae=e.useCallback(()=>{fe(x=>!x)},[]),Y=ve.useRef("");e.useEffect(()=>{if(ye)return;const x=JSON.stringify({prompt:n,images:s==null?void 0:s.map(L=>L.url),knowledgeContextRefs:o.map(L=>L.noteId),elementIds:c,width:r,height:d,result:I,aspectRatio:_,targetFrameId:E,pptSlideImage:h,pptSlidePrompt:R,pptReplaceElementId:$});Y.current!==x&&(Y.current=x,re(n),F(o),te(s||[]),r&&oe(r),d&&Ne(d),_&&(le(_),W(L=>ts(y,L,_))))},[n,s,o,c,r,d,I,_,E,h,R,$,ye,y]);const Ue=e.useRef("");e.useEffect(()=>(Ln({prompt:Q,imageCount:V.length,knowledgeContextCount:ce.length}),$n),[ce.length,Q,V.length]),e.useEffect(()=>{if(!ee)return;const x={prompt:Q,images:V.map(B=>({url:B.url,name:B.name})),aspectRatio:ge},L=JSON.stringify(x);if(Ue.current===L)return;const q=window.setTimeout(()=>{Ue.current!==L&&(Ue.current=L,ee(x))},200);return()=>{window.clearTimeout(q)}},[ge,ee,Q,V]),e.useEffect(()=>{const x=L=>{var B;const q=L.imageModelName||((B=k[0])==null?void 0:B.id)||"gemini-2.5-flash-image-vip";if(q!==y){A(q);const Pe=Fe(k,q,P);ae(De(Pe)||null)}};return $e.addListener(x),()=>$e.removeListener(x)},[y,P,k]),e.useEffect(()=>{if(k.length===0)return;if(!Fe(k,y,P)){const L=k[0];A(L.id);const q=De(L);ae(B=>B&&q&&B.profileId===q.profileId&&B.modelId===q.modelId?B:q)}},[y,P,k]),e.useEffect(()=>{if(!f)return;const x=Te(y,P),L=Te(f,S);if(x!==L){A(f);const q=Fe(k,f,S),B=De(q)||S||null;ae(Pe=>Pe&&B&&Pe.profileId===B.profileId&&Pe.modelId===B.modelId?Pe:B)}},[y,P,f,S,k]),e.useEffect(()=>{!be&&Object.keys(T).length>0&&W({})},[be,T]),e.useEffect(()=>{Cn({currentModel:y,currentSelectionKey:Te(y,P),extraParams:T,aspectRatio:ge})},[y,P,T,ge]),e.useEffect(()=>(m(null),()=>{m(null)}),[]);const Qe=()=>{const x=wt(y,{});re(""),W(x),te([]),F([]),m(null),le(ft(x)),u("config"),we(!1),window.dispatchEvent(new CustomEvent("ai-image-clear"))},rt=ve.useMemo(()=>ms("image",v,O),[O,v,se]),it=!!(h||R!=null&&R.trim()),Ge=x=>{it||(fs("image",x),de(L=>L+1))},lt=x=>{const L=x.params.model||y,q={...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}:{}},B=Object.keys(q).length>0?wt(L,q):wt(L,{});if(we(!0),u("config"),re(x.params.prompt||""),W(B),oe(x.params.width||1024),Ne(x.params.height||1024),te(ln(x)),F(cn(x)),x.params.model){A(x.params.model),ae(x.params.modelRef||null);const Pe=$e.get();$e.update({...Pe,imageModelName:x.params.model})}le(ft(B,x.params.aspectRatio)),m(null)},Ye=async()=>Promise.all(V.map(async x=>{if(x.file)return new Promise((L,q)=>{const B=new FileReader;B.onload=()=>{L({type:"url",url:B.result,name:x.name})},B.onerror=q,B.readAsDataURL(x.file)});if(x.url)return{type:"url",url:x.url,name:x.name};throw new Error("Invalid image data")})),Ze=async(x=1)=>{const L=x;if(!je.current){je.current=!0;try{if(!Q||!Q.trim()){m(v==="zh"?"请输入图像描述":"Please enter image description");return}if(!an("image",P||y)&&!await rn()){m(v==="zh"?"需要 API Key 才能生成图片":"API Key is required to generate images");return}ze&&m(null);try{const q=typeof Ie=="string"?parseInt(Ie)||1024:Ie,B=typeof he=="string"?parseInt(he)||1024:he,Pe=await Ye();if(L>1){const l=[],p=`batch_${Date.now()}`,g=y||Je("image").modelId,N=g.startsWith("mj")?[Q.trim(),Qt(T)].filter(Boolean).join(" "):(Q||"").trim(),ne=!g.startsWith("mj")&&Object.keys(T).length>0?T:void 0,pe=ne!=null&&ne.size?ne.size:Tt(ge);for(let _e=0;_e<L;_e++){const Ke={prompt:N,knowledgeContextRefs:ce,width:q,height:B,aspectRatio:ge,size:pe,model:g,modelRef:P||null,uploadedImages:Pe,batchId:p,batchIndex:_e+1,batchTotal:L,assetMetadata:Z,autoInsertToCanvas:K??kt(st.AI_IMAGE_AUTO_INSERT),targetFrameId:E,targetFrameDimensions:a,pptSlideImage:h,pptSlidePrompt:R,pptReplaceElementId:$,...ne?{params:ne}:{}},We=Se(Ke,Ce.IMAGE);We&&l.push(We.id)}l.length>0?(Me.success(v==="zh"?`已添加 ${l.length} 个任务到队列`:`Added ${l.length} tasks to queue`),Ge(N),m(null),u("tasks"),we(!1)):m(v==="zh"?"批量任务创建失败,请稍后重试":"Failed to create batch tasks, please try again later");return}const qe=y||Je("image").modelId,dt=qe.startsWith("mj")?[Q.trim(),Qt(T)].filter(Boolean).join(" "):(Q||"").trim(),Oe=!qe.startsWith("mj")&&Object.keys(T).length>0?T:void 0,ut=Oe!=null&&Oe.size?Oe.size:Tt(ge),mt={prompt:dt,knowledgeContextRefs:ce,width:q,height:B,aspectRatio:ge,size:ut,model:qe,modelRef:P||null,uploadedImages:Pe,autoInsertToCanvas:K??kt(st.AI_IMAGE_AUTO_INSERT),batchId:G||`image_single_${Date.now()}`,batchIndex:1,batchTotal:1,assetMetadata:Z,targetFrameId:E,targetFrameDimensions:a,pptSlideImage:h,pptSlidePrompt:R,pptReplaceElementId:$,...Oe?{params:Oe}:{}};Se(mt,Ce.IMAGE)?(Me.success(v==="zh"?"任务已添加到队列,将在后台生成":"Task added to queue, will be generated in background"),Ge(dt),m(null),u("tasks"),we(!1)):m(v==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later")}catch(q){console.error("Failed to create task:",q);let B=v==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later";q.message&&(q.message.includes("exceed 5000 characters")?B=v==="zh"?"提示词不能超过 5000 字符":"Prompt must not exceed 5000 characters":q.message.includes("Duplicate submission")?B=v==="zh"?"请勿重复提交,请等待 5 秒后再试":"Duplicate submission. Please wait 5 seconds.":q.message.includes("Invalid parameters")&&(B=v==="zh"?`参数错误: ${q.message.replace("Invalid parameters: ","")}`:q.message)),m(B)}}finally{je.current=!1}}};return vs(ue,Q,()=>Ze(1)),t.jsxs("div",{className:"ai-image-generation-container",children:[z?t.jsxs("div",{className:"ai-generation-mobile-switcher",role:"tablist",children:[t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${X==="config"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>u("config"),children:"生成设置"}),t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${X==="tasks"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>u("tasks"),children:"生成任务"})]}):null,t.jsxs("div",{className:`main-content ${z?"main-content--mobile-panels":""}`,ref:b,children:[t.jsxs("div",{className:`ai-image-generation-section ${z&&X!=="config"?"ai-generation-mobile-panel--hidden":""}`,children:[t.jsxs("div",{className:"ai-image-generation-form",children:[f!==void 0&&M&&t.jsx("div",{className:"form-header-row",children:t.jsx("div",{className:"model-selector-wrapper",children:t.jsx(ds,{selectedModel:y,selectedSelectionKey:Te(y,P),onSelect:x=>{A(x),ae(null),M(x),C==null||C(null)},onSelectModel:x=>{A(x.id);const L=De(x);ae(L),M(x.id),C==null||C(L)},language:v,models:k,placement:"down",variant:"form",disabled:ue})})}),be&&t.jsx("div",{className:"model-params-row",children:t.jsx(ps,{selectedParams:T,onParamChange:ie,modelId:y,language:v,disabled:ue,placement:"down"})}),t.jsx(xs,{images:V,onImagesChange:te,language:v,disabled:ue,multiple:!0,label:v==="zh"?"参考图片 (可选)":"Reference Images (Optional)",onError:m}),t.jsx(js,{prompt:Q,onPromptChange:re,presetPrompts:rt,language:v,type:"image",disabled:ue,onError:m}),t.jsx(gs,{value:ce,onChange:F,disabled:ue,language:v}),t.jsx(ws,{error:me})]}),t.jsx(ys,{language:v,type:"image",isGenerating:ue,hasGenerated:!1,canGenerate:!!(Q&&Q.trim()),onGenerate:Ze,onReset:Qe,leftContent:t.jsx(Ps,{storageKey:st.AI_IMAGE_AUTO_INSERT,language:v})})]}),z?null:t.jsx(Es,{isRightPanelVisible:Ee,onToggleRightPanel:Ae,onWidthChange:Re,rightPanelWidth:D,language:v,storageKey:"image"}),(z||Ee)&&t.jsx("div",{className:`task-sidebar ${z?"task-sidebar--mobile-panel":""} ${z&&X!=="tasks"?"ai-generation-mobile-panel--hidden":""}`,style:z?void 0:{width:D,flexShrink:0},children:t.jsx(Ms,{taskType:Ce.IMAGE,onEditTask:lt})})]})]})};function ss(n,s){const o=Object.keys(n),c=Object.keys(s);return o.length!==c.length?!1:o.every(r=>n[r]===s[r])}function ns(n,s,o){return n.slice(0,s).map((c,r)=>({...c,slot:r,slotLabel:o[r]||`参考图${r+1}`}))}function Fn(n,s){return n.length===s.length&&n.every((o,c)=>{const r=s[c];return o.slot===r.slot&&o.slotLabel===r.slotLabel&&o.url===r.url&&o.name===r.name&&o.file===r.file})}function St(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 Rs(n,s){const o=Le(s==null?void 0:s.profileId,s==null?void 0:s.modelId);return(o==null?void 0:o.modelId)===(n||null)?o:null}function He(n,s,o){if(!s)return null;const c=Rs(s,o),r=Fe(n,s,c);return De(r)||c}function Un(n){return n.reduce((s,o)=>(o.defaultValue&&(s[o.id]=o.defaultValue),s),{})}function jt(n,s){return Un(us(n,s||n,{}))}function pt(n,s,o){return{...n,...s!=null?{duration:String(s)}:{},...o?{size:o}:{}}}function os(n,s,o){const{duration:c,size:r,...d}=n;return{extraParams:d,duration:s,size:o}}const Gn=({initialPrompt:n="",initialImage:s,initialImages:o,initialKnowledgeContextRefs:c=[],initialDuration:r,initialModel:d,initialSize:I,initialResultUrl:_,selectedModel:E,selectedModelRef:a,onModelChange:h,onModelRefChange:R,externalBatchId:$,initialAutoInsertToCanvas:f,onDraftChange:S}={})=>{var ut,mt,xt;const M=hs("video"),[C,G]=e.useState(n),[Z,K]=e.useState(c),[ee,i]=e.useState(null),[w,j]=e.useState(!0),[y,A]=e.useState(()=>ks("video")),[P,ae]=e.useState("config"),ke=e.useRef(null),{viewportWidth:H}=Pt(),Q=H<=768,re=Je("video"),ce=d||re.modelId,F=Rs(ce,d&&d===E?a:re.modelId===ce?Le(re.profileId,re.modelId):null),T=Fe(M,ce,F)||bt("video",ce,F),W=He(M,(T==null?void 0:T.id)||ce,De(T)||F),[k,Ie]=e.useState((T==null?void 0:T.id)||((ut=M[0])==null?void 0:ut.id)||It("veo3")),[oe,he]=e.useState(W),Ne=Te((T==null?void 0:T.id)||((mt=M[0])==null?void 0:mt.id)||It("veo3"),W),ge=Jt((T==null?void 0:T.id)||((xt=M[0])==null?void 0:xt.id)||It("veo3"),Ne),le=ve.useMemo(()=>{if(Fe(M,k,oe)||!k)return M;const p=bt("video",k,oe);return p?[p,...M]:M},[k,oe,M]),[me,m]=e.useState(()=>pt(ge.extraParams,(r==null?void 0:r.toString())||ge.duration,I||ge.size)),V=ve.useMemo(()=>us(k,oe||k,me),[k,oe,me]),te=ve.useMemo(()=>$t(k,oe||k,me),[k,oe,me]),Ee=ve.useMemo(()=>(te.imageUpload.labels||[]).join("|"),[te.imageUpload.labels]),fe=ve.useMemo(()=>Ee?Ee.split("|"):[],[Ee]),D=ve.useMemo(()=>({maxCount:te.imageUpload.maxCount,mode:te.imageUpload.mode,required:te.imageUpload.required,labels:fe,labelsSignature:Ee}),[te.imageUpload.maxCount,te.imageUpload.mode,te.imageUpload.required,fe,Ee]),U=ve.useMemo(()=>{var g;const l=V.find(N=>N.id==="duration"),p=me.duration;return p&&((g=l==null?void 0:l.options)!=null&&g.some(N=>N.value===p))?p:(l==null?void 0:l.defaultValue)||te.defaultDuration},[V,te.defaultDuration,me.duration]),X=ve.useMemo(()=>{var g;const l=V.find(N=>N.id==="size"),p=me.size;return p&&((g=l==null?void 0:l.options)!=null&&g.some(N=>N.value===p))?p:(l==null?void 0:l.defaultValue)||te.defaultSize},[V,te.defaultSize,me.size]),u=ve.useMemo(()=>V.length>0,[V]),b=e.useCallback((l,p)=>{if(!p||p==="default"){m(g=>{const N={...g};return delete N[l],N});return}m(g=>({...g,[l]:p}))},[]);e.useEffect(()=>{const l=V.reduce((p,g)=>{const N=me[g.id],ne=!N||g.valueType!=="enum"||!g.options||g.options.some(pe=>pe.value===N);return N&&ne?p[g.id]=N:g.defaultValue&&(p[g.id]=g.defaultValue),p},{});ss(me,l)||m(l)},[V,me]);const[J,z]=e.useState(()=>o&&o.length>0?o:s?[{slot:0,slotLabel:"参考图",url:s.url||"",name:s.name,file:s.file}]:[]),[O,se]=e.useState(()=>{const l=te.imageUpload.maxCount,p=te.imageUpload.labels||[];let g=[];return o&&o.length>0?g=o:s&&(g=[{slot:0,slotLabel:p[0]||"参考图",url:s.url||"",name:s.name,file:s.file}]),g.slice(0,l).map((N,ne)=>({...N,slot:ne,slotLabel:p[ne]||`参考图${ne+1}`}))}),[de,ue]=e.useState(!1),[v,Se]=e.useState([]),je=ve.useMemo(()=>dn(k),[k]),ze=Ot(k),{videoHistory:be}=Nt(),[ye,we]=e.useState(0);e.useEffect(()=>Xe.subscribeChanges(()=>{we(l=>l+1)}),[]);const{isGenerating:ie}=Is("video"),Re=e.useCallback(l=>{A(l)},[]),Ae=e.useCallback(()=>{j(l=>!l)},[]),{language:Y}=Mt(),{createTask:Ue}=cs(),Qe=e.useRef(!1),rt=E!==void 0,it=ve.useRef(null),Ge=ve.useRef(null);e.useEffect(()=>{if(rt)return;const l=p=>{const g=p.videoModelName||"veo3";if(g!==k){Ie(g);const N=He(le,g,oe);he(N)}};return $e.addListener(l),()=>$e.removeListener(l)},[k,oe,rt,E,a,le]),e.useEffect(()=>{if(le.length===0)return;const l=Fe(le,k,oe),p=He(le,k,oe);if(!l){const g=le[0],N=De(g);Ie(g.id),he(ne=>St(ne,N)?ne:N);return}he(g=>St(g,p)?g:p)},[k,oe,le]),e.useEffect(()=>{if(!E)return;const l=Te(E,a);if(it.current===l||Ge.current&&Ge.current!==E)return;it.current=l,Ie(g=>g===E?g:E);const p=He(le,E,a);he(g=>St(g,p)?g:p)},[E,a,le,d]);const[lt,Ye]=e.useState(!1),[Ze,et]=e.useState(!1);e.useEffect(()=>{if(Ze){et(!1);return}const l=Jt(k,Te(k,oe)),p=pt(l.extraParams,r!==void 0?r.toString():l.duration,I||l.size);m(g=>ss(g,p)?g:p),Ot(k)||(ue(g=>g&&!1),Se(g=>g.length>0?[]:g))},[k,oe,Ze,r,I]),e.useEffect(()=>{const l=J.length>0?ns(J,D.maxCount,D.labels):[];se(p=>Fn(p,l)?p:l)},[J,D.labels,D.labelsSignature,D.maxCount]),e.useEffect(()=>{const l=os(me,U,X);Sn({currentModel:k,currentSelectionKey:Te(k,oe),extraParams:l.extraParams,duration:l.duration,size:l.size})},[k,oe,U,X,me]);const tt=ve.useRef("");e.useEffect(()=>{if(lt)return;const l=JSON.stringify({prompt:n,image:s==null?void 0:s.url,images:o==null?void 0:o.map(N=>N.url),knowledgeContextRefs:c.map(N=>N.noteId),duration:r,model:d,size:I,result:_});if(tt.current===l)return;tt.current=l,d&&(Ge.current=d,Ie(d),he(He(M,d,a))),G(n),K(c);let p=[];o&&o.length>0?p=o:s&&(p=[{slot:0,slotLabel:"参考图",url:s.url||"",name:s.name,file:s.file}]),z(p);const g=ns(p,D.maxCount,D.labels);se(g),(r!==void 0||I)&&m(N=>pt(N,r,I)),i(null)},[n,s,o,c,r,I,_,D.labels,D.labelsSignature,D.maxCount,lt]),e.useEffect(()=>(i(null),()=>{i(null)}),[]);const ct=()=>{G(""),z([]),se([]),i(null),ae("config"),Ye(!1),ue(!1),Se([]),m(jt(k,oe||k)),window.dispatchEvent(new CustomEvent("ai-video-clear"))},x=ve.useCallback((l,p)=>l.map((g,N)=>({slot:N,slotLabel:p[N]||`参考图${N+1}`,url:g.url,name:g.name,file:g.file})),[]),L=ve.useCallback(l=>l.map(p=>({url:p.url,name:p.name,file:p.file})),[]),q=ve.useCallback(l=>{const p=x(l,D.labels);se(p),z(p)},[D.labels,x]),B=ve.useMemo(()=>ms("video",Y,be),[be,Y,ye]),Pe=l=>{fs("video",l),we(p=>p+1)},qe=e.useRef("");e.useEffect(()=>{if(!S)return;const l=Number.parseFloat(U),p={prompt:C,images:O.map(ne=>({url:ne.url,name:ne.name})),duration:Number.isFinite(l)?l:void 0,size:X||void 0},g=JSON.stringify(p);if(qe.current===g)return;const N=window.setTimeout(()=>{qe.current!==g&&(qe.current=g,S(p))},200);return()=>{window.clearTimeout(N)}},[U,X,S,C,O]);const dt=l=>{var g,N;if(Ye(!0),ae("config"),et(!0),l.params.model){Ie(l.params.model),he(l.params.modelRef||null);const ne=$e.get();$e.update({...ne,videoModelName:l.params.model})}if((g=l.params.storyboard)!=null&&g.enabled&&((N=l.params.storyboard)!=null&&N.scenes))ue(!0),Se(l.params.storyboard.scenes),G("");else{const ne=l.params.prompt||"",pe=Nn(ne);pe&&pe.length>0?(ue(!0),Se(pe),G("")):(ue(!1),Se([]),G(ne))}const p=l.params.params&&typeof l.params.params=="object"?Object.entries(l.params.params).reduce((ne,[pe,_e])=>(_e!=null&&String(_e).trim()&&(ne[pe]=String(_e)),ne),{}):{};if(m(pt(p,l.params.duration??l.params.seconds,l.params.size)),l.params.uploadedImages&&l.params.uploadedImages.length>0){z(l.params.uploadedImages);const ne=l.params.model||k,pe=$t(ne,l.params.modelRef||ne,p),_e=pe.imageUpload.maxCount,Ke=pe.imageUpload.labels||[],We=l.params.uploadedImages.slice(0,_e).map((Ve,vt)=>({...Ve,slot:vt,slotLabel:Ke[vt]||`参考图${vt+1}`}));se(We)}else z([]),se([]);i(null)},Oe=async(l=1)=>{if(!Qe.current){Qe.current=!0;try{if(de){const p=Pn(v,parseFloat(U),je.minSceneDuration);if(!p.valid){i(p.error||"场景配置无效");return}}else if(!C||!C.trim()){i(Y==="zh"?"请输入视频描述":"Please enter video description");return}if(D.required&&!O.some(p=>p.url||p.file)){i(Y==="zh"?"请上传模型所需的参考图片":"Please upload the required reference image");return}try{const p=[];for(const pe of O)if(pe.file){const _e=await new Promise((Ke,We)=>{const Ve=new FileReader;Ve.onload=()=>Ke(Ve.result),Ve.onerror=We,Ve.readAsDataURL(pe.file)});p.push({...pe,url:_e,file:void 0})}else p.push({...pe,file:void 0});const g=de?Mn(v):(C||"").trim(),N=[],ne=$||`video_batch_${Date.now()}`;for(let pe=0;pe<l;pe++){const _e=os(me,U,X),Ke=Object.keys(_e.extraParams).length>0?_e.extraParams:void 0,We={prompt:g,knowledgeContextRefs:Z,model:k,modelRef:oe||null,seconds:_e.duration,size:_e.size,uploadedImages:p,...de&&{storyboard:{enabled:!0,scenes:v,totalDuration:parseFloat(U)}},batchId:ne,batchIndex:pe+1,batchTotal:l,autoInsertToCanvas:f??kt(st.AI_VIDEO_AUTO_INSERT),...Ke?{params:Ke}:{}},Ve=Ue(We,Ce.VIDEO);Ve&&N.push(Ve.id)}N.length>0?(Me.success(Y==="zh"?l>1?`${N.length} 个视频任务已添加到队列,将在后台生成`:"视频任务已添加到队列,将在后台生成":l>1?`${N.length} video tasks added to queue, will be generated in background`:"Video task added to queue, will be generated in background"),Pe(g),G(""),z([]),se([]),ue(!1),Se([]),i(null),ae("tasks"),Ye(!1)):i(Y==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later")}catch(p){console.error("Failed to create task:",p);let g=Y==="zh"?"任务创建失败,请检查参数或稍后重试":"Failed to create task, please check parameters or try again later";p.message&&(p.message.includes("exceed 5000 characters")?g=Y==="zh"?"提示词不能超过 5000 字符":"Prompt must not exceed 5000 characters":p.message.includes("Duplicate submission")?g=Y==="zh"?"请勿重复提交,请等待 5 秒后再试":"Duplicate submission. Please wait 5 seconds.":p.message.includes("Invalid parameters")&&(g=Y==="zh"?`参数错误: ${p.message.replace("Invalid parameters: ","")}`:p.message)),i(g)}}finally{Qe.current=!1}}};return vs(ie,C,Oe),t.jsxs("div",{className:"ai-video-generation-container",children:[Q?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:()=>ae("config"),children:"生成设置"}),t.jsx("button",{type:"button",className:`ai-generation-mobile-switcher__tab ${P==="tasks"?"ai-generation-mobile-switcher__tab--active":""}`,onClick:()=>ae("tasks"),children:"生成任务"})]}):null,t.jsxs("div",{className:`main-content ${Q?"main-content--mobile-panels":""}`,ref:ke,children:[t.jsxs("div",{className:`ai-image-generation-section ${Q&&P!=="config"?"ai-generation-mobile-panel--hidden":""}`,children:[t.jsxs("div",{className:"ai-image-generation-form",children:[E!==void 0&&h&&t.jsx("div",{className:"form-header-row",children:t.jsx("div",{className:"model-selector-wrapper",children:t.jsx(ds,{selectedModel:k,selectedSelectionKey:Te(k,oe),onSelect:(l,p)=>{const g=l,N=He(le,g,p||null);Ge.current=null,Ie(g),he(N),m(jt(g,N||g)),h(l),R==null||R(N)},onSelectModel:l=>{const p=l.id;Ge.current=null,Ie(p);const g=He(le,p,De(l));he(g),m(jt(p,g||p)),h(l.id),R==null||R(g)},language:Y,models:le,placement:"down",variant:"form",placeholder:Y==="zh"?"选择视频模型":"Select Video Model",disabled:ie})})}),u&&t.jsx("div",{className:"model-params-row",children:t.jsx(ps,{selectedParams:me,onParamChange:b,compatibleParams:V,modelId:k,language:Y,disabled:ie,placement:"down"})}),D.maxCount>0&&t.jsx(xs,{images:L(O),onImagesChange:q,language:Y,disabled:ie,multiple:D.maxCount>1,maxCount:D.maxCount,slotLabels:D.mode==="frames"?D.labels:void 0,label:D.mode==="frames"?Y==="zh"?"首尾帧图片 (可选)":"Start/End Frames (Optional)":D.required?Y==="zh"?"参考图片":"Reference Images":Y==="zh"?"参考图片 (可选)":"Reference Images (Optional)"}),ze&&t.jsx(An,{enabled:de,onEnabledChange:ue,totalDuration:parseFloat(U),maxScenes:je.maxScenes,minSceneDuration:je.minSceneDuration,scenes:v,onScenesChange:Se,disabled:ie}),!de&&t.jsx(js,{prompt:C,onPromptChange:G,presetPrompts:B,language:Y,type:"video",disabled:ie,onError:i,videoProvider:te.provider}),t.jsx(gs,{value:Z,onChange:K,disabled:ie,language:Y}),t.jsx(ws,{error:ee})]}),t.jsx(ys,{language:Y,type:"video",isGenerating:ie,hasGenerated:!1,canGenerate:de?v.length>0:!!(C&&C.trim()),onGenerate:Oe,onReset:ct,leftContent:t.jsx(Ps,{storageKey:st.AI_VIDEO_AUTO_INSERT,language:Y})})]}),Q?null:t.jsx(Es,{isRightPanelVisible:w,onToggleRightPanel:Ae,onWidthChange:Re,rightPanelWidth:y,language:Y,storageKey:"video"}),(Q||w)&&t.jsx("div",{className:`task-sidebar ${Q?"task-sidebar--mobile-panel":""} ${Q&&P!=="tasks"?"ai-generation-mobile-panel--hidden":""}`,style:Q?void 0:{width:y,flexShrink:0},children:t.jsx(Ms,{taskType:Ce.VIDEO,onEditTask:dt})})]})]})},Kn=e.lazy(()=>Et(()=>import("./batch-image-generation-BLBSv-t6.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url)),Wn=e.lazy(()=>Et(()=>import("./mermaid-to-drawnix-nGs2aeZ7.js"),__vite__mapDeps([0,5,2,1,3,6,7,8]),import.meta.url)),Bn=e.lazy(()=>Et(()=>import("./markdown-to-drawnix-BVFYnimo.js"),__vite__mapDeps([0,5,2,1,3,6,7,8]),import.meta.url)),qn=({container:n})=>{const{appState:s,openDialog:o,closeDialog:c}=ls(),{language:r}=Mt(),d=un(),{isMobile:I,isTablet:_}=Pt(),E=s.dialogInitialDataByType,a=(E==null?void 0:E[xe.aiImageGeneration])??null,h=(E==null?void 0:E[xe.aiVideoGeneration])??null,R=!I&&!_,$=e.useRef(!1),f=e.useRef(null),[S,M]=e.useState(""),[C,G]=e.useState(null),[Z,K]=e.useState(""),[ee,i]=e.useState(null),w=e.useRef(null),j=e.useRef(null),y=e.useCallback(()=>{const m=Je("image"),V=Je("video"),te=m.modelId||"gemini-3-pro-image-preview-vip",Ee=Le(m.profileId,te),fe=V.modelId||"veo3",D=Le(V.profileId,fe);M(U=>U===te?U:te),G(U=>Te(te,U)===Te(te,Ee)?U:Ee),K(U=>U===fe?U:fe),i(U=>Te(fe,U)===Te(fe,D)?U:D)},[]);e.useEffect(()=>{y()},[y]),e.useEffect(()=>{const m=()=>{y()};return $e.addListener(m),Vt.addListener(m),()=>{$e.removeListener(m),Vt.removeListener(m)}},[y]);const A=m=>{M(m)},P=m=>{K(m)},ae=m=>{G(m)},ke=m=>{i(m)};e.useEffect(()=>{if(!S)return;const m=Te(S,C);w.current!==m&&(w.current=m,Ft("image",Le(C==null?void 0:C.profileId,S)))},[S,C]),e.useEffect(()=>{if(!Z)return;const m=Te(Z,ee);j.current!==m&&(j.current=m,Ft("video",Le(ee==null?void 0:ee.profileId,Z)))},[Z,ee]);const[H,Q]=e.useState({initialPrompt:"",initialImages:[],selectedElementIds:[]}),[re,ce]=e.useState({initialPrompt:"",initialImage:void 0}),[F,T]=e.useState(!1),[W,k]=e.useState(()=>{try{return localStorage.getItem(yt)==="batch"?"batch":"single"}catch{return"single"}});e.useEffect(()=>{!R&&W==="batch"&&k("single")},[R,W]);const Ie=e.useCallback(m=>{k(m),m==="batch"&&(T(!0),setTimeout(()=>T(!1),50));try{localStorage.setItem(yt,m)}catch(V){console.warn("Failed to save image mode:",V)}},[]);e.useEffect(()=>{if(s.openDialogTypes.has(xe.aiImageGeneration)){if(H.initialImages&&H.initialImages.length>0||H.initialPrompt&&H.initialPrompt.trim()!==""){T(!1);return}try{localStorage.getItem(yt)==="batch"&&(T(!0),setTimeout(()=>T(!1),50))}catch{T(!1)}}},[s.openDialogTypes,H.initialImages,H.initialPrompt]);const oe=e.useRef(!1),he=e.useRef(a),Ne=e.useRef(!1),ge=e.useRef(h);e.useEffect(()=>{if(!d)return;const m=s.openDialogTypes.has(xe.aiImageGeneration),V=m&&!oe.current,te=he.current!==a;if(oe.current=m,he.current=a,!m||!V&&!te||$.current)return;(async()=>{$.current=!0,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{console.warn("Processing timeout, resetting processing state"),$.current=!1},1e4);try{if(a){Q({initialPrompt:a.initialPrompt||a.prompt||"",initialImages:a.initialImages||a.uploadedImages||[],initialKnowledgeContextRefs:a.initialKnowledgeContextRefs||a.knowledgeContextRefs||[],selectedElementIds:[],initialResultUrl:a.initialResultUrl||a.resultUrl,initialAspectRatio:a.initialAspectRatio,targetFrameId:a.targetFrameId,targetFrameDimensions:a.targetFrameDimensions,pptSlideImage:a.pptSlideImage,pptSlidePrompt:a.pptSlidePrompt,pptReplaceElementId:a.pptReplaceElementId}),a.initialModel&&M(a.initialModel),a.initialModelRef!==void 0&&G(a.initialModelRef);return}const fe=s.lastSelectedElementIds||[];let D,U,X;const u=mn(d);if(u.length===1&&fn(u[0])){const z=u[0],O=pn.getRectangleByPoints(z.points);D=hn(O.width,O.height),U=z.id,X={width:O.width,height:O.height}}const b=await Bt(d,fe),J=[];b.remainingImages.forEach(z=>{J.push({url:z.url,name:z.name||`selected-image-${Date.now()}.png`})}),b.graphicsImage&&J.push({url:b.graphicsImage,name:`graphics-combined-${Date.now()}.png`}),Q({initialPrompt:b.remainingText||"",initialImages:J,initialKnowledgeContextRefs:[],selectedElementIds:fe,initialAspectRatio:D,targetFrameId:U,targetFrameDimensions:X})}catch(fe){console.warn("Error processing selected content for AI:",fe);const D=qt(d),U=D.images.map(X=>({url:X.url,name:X.name||`selected-image-${Date.now()}.png`}));Q({initialPrompt:D.text||"",initialImages:U,initialKnowledgeContextRefs:[],selectedElementIds:[]})}finally{$.current=!1,f.current&&(clearTimeout(f.current),f.current=null)}})()},[s.lastSelectedElementIds,s.openDialogTypes,d,a]),e.useEffect(()=>{if(!d)return;const m=s.openDialogTypes.has(xe.aiVideoGeneration),V=m&&!Ne.current,te=ge.current!==h;if(Ne.current=m,ge.current=h,!m||!V&&!te||$.current)return;(async()=>{$.current=!0,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{console.warn("Video processing timeout, resetting processing state"),$.current=!1},1e4);try{if(h){ce({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 X=h.initialModel||h.model;X&&K(X),h.initialModelRef!==void 0&&i(h.initialModelRef);return}const fe=s.lastSelectedElementIds||[],D=await Bt(d,fe),U=[];D.remainingImages.length>0?D.remainingImages.forEach((X,u)=>{U.push({url:X.url,name:X.name||`selected-image-${u+1}-${Date.now()}.png`})}):D.graphicsImage&&U.push({url:D.graphicsImage,name:`graphics-combined-${Date.now()}.png`}),ce({initialPrompt:D.remainingText||"",initialImage:U.length>0?U[0]:void 0,initialImages:U.map((X,u)=>({slot:u,slotLabel:`参考图${u+1}`,url:X.url,name:X.name}))})}catch(fe){console.warn("Error processing selected content for AI video:",fe);const D=qt(d),U=D.images.map((X,u)=>({url:X.url,name:X.name||`selected-image-${u+1}-${Date.now()}.png`}));ce({initialPrompt:D.text||"",initialImage:U.length>0?U[0]:void 0,initialImages:U.map((X,u)=>({slot:u,slotLabel:`参考图${u+1}`,url:X.url,name:X.name}))})}finally{$.current=!1,f.current&&(clearTimeout(f.current),f.current=null)}})()},[s.lastSelectedElementIds,s.openDialogTypes,d,h]),e.useEffect(()=>{s.openDialogTypes.size===0&&($.current=!1,oe.current=!1,he.current=null,Ne.current=!1,ge.current=null,f.current&&(clearTimeout(f.current),f.current=null))},[s.openDialogTypes]);const le=e.useCallback(()=>{const m=localStorage.getItem(Ut);if(m)try{const V=JSON.parse(m);V.timestamp=Date.now(),localStorage.setItem(Ut,JSON.stringify(V))}catch(V){console.warn("Failed to update cache timestamp:",V)}c(xe.aiImageGeneration)},[c]),me=e.useCallback(()=>{const m=localStorage.getItem(Gt);if(m)try{const V=JSON.parse(m);V.timestamp=Date.now(),localStorage.setItem(Gt,JSON.stringify(V))}catch(V){console.warn("Failed to update cache timestamp:",V)}c(xe.aiVideoGeneration)},[c]);return t.jsxs(t.Fragment,{children:[t.jsx(Kt,{open:s.openDialogTypes.has(xe.mermaidToDrawnix),onOpenChange:m=>{m?o(xe.mermaidToDrawnix):c(xe.mermaidToDrawnix)},children:t.jsx(Wt,{className:"Dialog ttd-dialog",container:n,children:t.jsx(e.Suspense,{fallback:null,children:t.jsx(Wn,{})})})}),t.jsx(Kt,{open:s.openDialogTypes.has(xe.markdownToDrawnix),onOpenChange:m=>{m?o(xe.markdownToDrawnix):c(xe.markdownToDrawnix)},children:t.jsx(Wt,{className:"Dialog ttd-dialog",container:n,children:t.jsx(e.Suspense,{fallback:null,children:t.jsx(Bn,{})})})}),t.jsx(Ht,{id:"ai-image-dialog",visible:s.openDialogTypes.has(xe.aiImageGeneration),title:W==="batch"?r==="zh"?"批量出图":"Batch Generation":r==="zh"?"AI 图片生成":"AI Image Generation",headerContent:R?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 ${W==="single"?"active":""}`,onClick:m=>{m.stopPropagation(),m.preventDefault(),Ie("single")},children:r==="zh"?"AI 图片生成":"AI Image"}),t.jsx("button",{type:"button",className:`mode-tab ${W==="batch"?"active":""}`,onClick:m=>{m.stopPropagation(),m.preventDefault(),Ie("batch")},children:r==="zh"?"批量出图":"Batch"})]}):void 0,onClose:le,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:F||I,children:s.openDialogTypes.has(xe.aiImageGeneration)&&(W==="batch"?t.jsx(e.Suspense,{fallback:t.jsx("div",{className:"loading-fallback",children:r==="zh"?"加载中...":"Loading..."}),children:t.jsx(Kn,{onSwitchToSingle:()=>Ie("single"),selectedModel:S,selectedModelRef:C,onModelChange:A,onModelRefChange:ae})}):t.jsx(Vn,{initialPrompt:H.initialPrompt,initialImages:H.initialImages,initialKnowledgeContextRefs:H.initialKnowledgeContextRefs||(a==null?void 0:a.initialKnowledgeContextRefs)||(a==null?void 0:a.knowledgeContextRefs)||[],selectedElementIds:H.selectedElementIds,initialWidth:(a==null?void 0:a.initialWidth)||(a==null?void 0:a.width),initialHeight:(a==null?void 0:a.initialHeight)||(a==null?void 0:a.height),initialResultUrl:H.initialResultUrl,initialAspectRatio:H.initialAspectRatio,targetFrameId:H.targetFrameId,targetFrameDimensions:H.targetFrameDimensions,pptSlideImage:H.pptSlideImage,pptSlidePrompt:H.pptSlidePrompt,pptReplaceElementId:H.pptReplaceElementId,selectedModel:S,selectedModelRef:C,onModelChange:A,onModelRefChange:ae,externalBatchId:a==null?void 0:a.batchId,assetMetadata:a==null?void 0:a.assetMetadata,initialAutoInsertToCanvas:a==null?void 0:a.autoInsertToCanvas,onDraftChange:a==null?void 0:a.onDraftChange},(a==null?void 0:a.prefillId)||(a==null?void 0:a.batchId)||"ai-image-dialog"))},(a==null?void 0:a.prefillId)||"ai-image-window"),t.jsx(Ht,{id:"ai-video-dialog",visible:s.openDialogTypes.has(xe.aiVideoGeneration),title:r==="zh"?"AI 视频生成":"AI Video Generation",onClose:me,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:I,children:s.openDialogTypes.has(xe.aiVideoGeneration)&&t.jsx(Gn,{initialPrompt:re.initialPrompt,initialImage:re.initialImage,initialImages:re.initialImages,initialKnowledgeContextRefs:(h==null?void 0:h.initialKnowledgeContextRefs)||(h==null?void 0:h.knowledgeContextRefs)||[],initialDuration:re.initialDuration,initialModel:re.initialModel,initialSize:re.initialSize,initialResultUrl:re.initialResultUrl,selectedModel:Z,selectedModelRef:ee,onModelChange:P,onModelRefChange:ke,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")})]})},ao=e.memo(qn,(n,s)=>n.container===s.container);export{ao as TTDDialog};
|
package/assets/{ttd-dialog-submit-shortcut-yUk15rsg.js → ttd-dialog-submit-shortcut-C2lJygXA.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as s,aI as x,
|
|
1
|
+
import{j as s,aI as x,lq as v,lr as E,r as n,ls as j,lt as h,lu as D,lv as _,lw as g,lx as f,ly as p,lz as y,lA as m}from"./startup-app-eD_rQhSh.js";const w=({children:t})=>s.jsx("div",{className:"ttd-dialog-panels",children:t}),O=({label:t,children:c,panelAction:a,panelActionDisabled:r=!1,onTextSubmitInProgress:e,renderTopRight:l,renderSubmitShortcut:d,renderBottomRight:i})=>s.jsxs("div",{className:"ttd-dialog-panel",children:[s.jsxs("div",{className:"ttd-dialog-panel__header",children:[s.jsx("label",{children:t}),l==null?void 0:l()]}),c,s.jsxs("div",{className:x("ttd-dialog-panel-button-container",{invisible:!a}),style:{display:"flex",alignItems:"center"},children:[s.jsx("button",{className:"ttd-dialog-panel-button drawnix-button ","data-track":"ttd_click_panel_action",onClick:a&&a.action,disabled:r||e,children:s.jsxs("div",{className:x({invisible:e}),children:[a==null?void 0:a.label,(a==null?void 0:a.icon)&&s.jsx("span",{children:a.icon})]})}),!r&&!e&&(d==null?void 0:d()),i==null?void 0:i()]})]}),N={CTRL_OR_CMD:v||E?"metaKey":"ctrlKey",ENTER:"Enter"},b=({input:t,placeholder:c,onChange:a,onKeyboardSubmit:r})=>{const e=n.useRef(null),l=n.useRef(r);return l.current=r,n.useEffect(()=>{if(!l.current)return;const d=e.current;if(d){const i=o=>{var u;o[N.CTRL_OR_CMD]&&o.key===N.ENTER&&(o.preventDefault(),(u=l.current)==null||u.call(l))};return d.addEventListener(j.KEYDOWN,i),()=>{d.removeEventListener(j.KEYDOWN,i)}}},[]),s.jsx("textarea",{className:"ttd-dialog-input",onChange:a,value:t,placeholder:c,autoFocus:!0,ref:e})},C=({error:t})=>s.jsxs("div",{"data-testid":"ttd-dialog-output-error",className:"ttd-dialog-output-error",children:["Error! ",s.jsx("p",{children:t})]}),K=({error:t,value:c,loaded:a})=>{const r=[D,_,g,f],e={readonly:!0,hideScrollbar:!1,disabledScrollOnNonFocus:!0,themeColors:p};return s.jsxs("div",{className:"ttd-dialog-output-wrapper",children:[t&&s.jsx(C,{error:t.message}),s.jsx("div",{style:{opacity:t?"0.15":1},className:"ttd-dialog-output-canvas-container",children:s.jsx(h,{value:c,options:e,plugins:r,children:s.jsx(y,{})})})]})},k=()=>s.jsxs("div",{className:"ttd-dialog-submit-shortcut",children:[s.jsx("div",{className:"ttd-dialog-submit-shortcut__key",children:m("CtrlOrCmd")}),s.jsx("div",{className:"ttd-dialog-submit-shortcut__key",children:m("Enter")})]});export{w as T,O as a,b,K as c,k as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r,kv as nt,dB as k,bg as g,kw as ct,j as t,kx as it,ky as lt,y as ot,kz as dt,kA as ut,gd as mt,kB as ht,ku as pt,n as ft,da as gt,dc as vt,kC as _t,R as ye,P as _e,kk as Qe,kl as Se,cq as xt,kp as jt,E as ee,kD as X,kE as yt,kF as Tt,er as Q,hB as Ct,b_ as Nt,gr as bt,b$ as Et,kG as Ze,e0 as xe,i4 as St,M as Ce,cu as It,am as Ne}from"./startup-app-eD_rQhSh.js";import{i as wt,s as At,g as Mt,h as Rt,j as Lt,k as be,l as J,n as Ee}from"./tool-windows-CmgL3thd.js";import{u as Dt,V as kt}from"./ai-chat-BO5vbKZW.js";/* empty css */const zt=({taskType:e,taskStatus:s,realProgress:v,startedAt:_,mediaUrl:d,isImageLoading:f=!1,onImageLoaded:w,onImageError:y,estimatedDuration:T=lt})=>{const[A,j]=r.useState(1),C=r.useRef(null),{displayProgress:i}=nt({taskType:e,taskStatus:s,startedAt:_,realProgress:v,mediaUrl:d,isImageLoading:f,estimatedDuration:T}),a=90,n=80,N=.5,E=1.2;if(r.useEffect(()=>{const P=C.current;if(!P)return;const Y=()=>{const{width:ae,height:U}=P.getBoundingClientRect(),V=U-10,z=ae-20,G=V/a,O=z/n,R=Math.min(G,O,E);j(Math.max(R,N))};Y();const M=new ResizeObserver(Y);return M.observe(P),()=>M.disconnect()},[]),s!==k.PROCESSING)return null;const u=i??0,$=e===g.IMAGE?ct(u,!!d,f):e===g.AUDIO?u<10?"提交任务...":u<45?"生成旋律...":u<85?"渲染音轨...":"整理结果...":u<10?"准备中...":u<50?"生成中...":u<90?"渲染中...":"即将完成...",o=["task-progress-overlay",e===g.VIDEO||e===g.AUDIO?"task-progress-overlay--video":"",d&&f?"task-progress-overlay--loading":""].filter(Boolean).join(" ");return t.jsxs("div",{ref:C,className:o,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(${A})`},children:t.jsx(it,{progress:u,progressMode:"determinate",statusText:$,tone:d&&f?"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:`${u}%`}})})]})},Pt=500;function Ot(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;const s=Math.round(e),v=Math.floor(s/60),_=s%60;return`${v}:${String(_).padStart(2,"0")}`}function pe(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ut(e){if(!e)return!1;const s=e.toLowerCase();return s==="kling_video"||s.startsWith("kling-v")}function Ht(e){if(e==="text2video")return"文生视频";if(e==="image2video")return"图生视频"}function $t(e){return e==="std"?"std 高性能":e==="pro"?"pro 高表现":e}function Ie(e){const s=e.params.videoAnalyzerAction;return s==="analyze"||s==="rewrite"?s:null}function Ft(e){const s=Ie(e);if(s==="analyze")return pe(e.params.videoAnalyzerSourceLabel)||null;if(s==="rewrite"){const v=pe(e.params.prompt);return v?v.replace(/^改编脚本:\s*/,""):null}return null}function Vt(e){const s=Ie(e);return s==="analyze"?"视频分析":s==="rewrite"?"脚本改编":null}function Gt(e){const s=e.params.batchIndex;return typeof s!="number"||!Number.isFinite(s)?null:e.type===g.AUDIO?s+1:s>=1?s:s+1}function Bt(e){switch(e){case k.PENDING:case k.PROCESSING:return"primary";case k.COMPLETED:return"success";case k.FAILED:return"danger";case k.CANCELLED:return"default";default:return"default"}}function Wt(e){switch(e){case k.PENDING:case k.PROCESSING:return"处理中";case k.COMPLETED:return"已完成";case k.FAILED:return"失败";case k.CANCELLED:return"已取消";default:return"未知"}}const et=ot.memo(({task:e,selectionMode:s=!1,isSelected:v=!1,isCompact:_,onSelectionChange:d,onRetry:f,onDelete:w,onDownload:y,onInsert:T,onCopy:A,onPreviewOpen:j,onEdit:C,onRegenerate:i,onExtractCharacter:a})=>{var we,Ae,Me,Re,Le,De,ke,ze,Pe,Oe,Ue,He,$e,Fe,Ve,Ge,Be,We,Xe,Ke,Ye,qe,Je;const[n,N]=r.useState(null),[E,u]=r.useState(!1),$=r.useRef(null),o=e.status===k.COMPLETED,P=e.status===k.FAILED,Y=e.status===k.CANCELLED,M=P||Y,ae=_!==void 0?_:E;r.useEffect(()=>{if(_!==void 0)return;const h=$.current;if(!h)return;const re=new ResizeObserver(ge=>{for(const ve of ge){const at=ve.contentRect.width;u(at<Pt)}});return re.observe(h),()=>re.disconnect()},[_]);const U=((we=e.params.storyboard)==null?void 0:we.enabled)===!0,V=o&&e.type===g.VIDEO&&wt(e.remoteId)&&At(e.params.model)&&!U,z=e.type===g.CHARACTER,G=e.type===g.AUDIO,O=e.type===g.CHAT,R=G&&dt(e.result),ie=e.type===g.IMAGE,le=e.type===g.IMAGE||e.type===g.VIDEO||e.type===g.AUDIO&&!R,oe=ut(e.result),he=mt(e.result,e.params.title||e.params.prompt),de=ht(oe),Z=pt(e.result),ne=Ie(e),K=Ft(e),ue=Vt(e),me=Gt(e),l=z?o&&((Ae=e.result)!=null&&Ae.characterUsername)?`@${e.result.characterUsername}`:"角色创建中...":O?((Me=e.result)==null?void 0:Me.title)||e.params.prompt||((Re=e.result)==null?void 0:Re.chatResponse):R?he||de||e.params.prompt:((Le=e.result)==null?void 0:Le.title)||e.params.title||e.params.prompt,p=e.params.params&&typeof e.params.params=="object"?e.params.params:null,L=e.type===g.AUDIO&&!R?Ot((De=e.result)==null?void 0:De.duration):null,I=e.type===g.VIDEO&&Ut(e.params.model),H=pe(p==null?void 0:p.model_name)||((ke=e.params.model)!=null&&ke.toLowerCase().startsWith("kling-v")?e.params.model:void 0),te=$t(pe(p==null?void 0:p.mode)),c=pe(p==null?void 0:p.klingAction2),m=Ht(c);pe(p==null?void 0:p.cfg_scale);const b=R?void 0:((Pe=(ze=e.result)==null?void 0:ze.urls)==null?void 0:Pe[0])||((Oe=e.result)==null?void 0:Oe.url),x=e.type===g.IMAGE&&b?ft(b):b,{isCached:q,cacheWarning:F}=gt(z||G?void 0:x),D=le&&!G&&!q?F||((Ue=e.result)==null?void 0:Ue.cacheWarning):void 0,B=D?`${D.message}${D.expiresHint?`
|
|
2
|
+
${D.expiresHint}`:""}`:"",S=R?0:(($e=(He=e.result)==null?void 0:He.urls)==null?void 0:$e.length)||((Fe=e.result)!=null&&Fe.url?1:0),ce=r.useMemo(()=>JSON.stringify({taskId:e.id,taskType:e.type,taskStatus:e.status,hasMultipleResults:S>1}),[S,e.id,e.status,e.type]),W=G?R||(Ve=e.result)==null?void 0:Ve.previewImageUrl:x,se=Dt(W,e.type===g.IMAGE?"image":void 0,"small");r.useEffect(()=>{if(o&&W&&e.type===g.IMAGE){const h=new Image;h.onload=()=>{N({width:h.naturalWidth,height:h.naturalHeight})},h.onerror=()=>{N(null)},h.src=W}},[o,W,e.type]);const Te=h=>{const re=h.target;re.closest("button")||re.closest(".t-checkbox")||re.closest("a")||re.closest(".task-item__preview")||(s?d==null||d(e.id,!v):o&&x&&le&&(j==null||j()))},fe=h=>{h.stopPropagation(),o&&x&&le&&(j==null||j())};return t.jsxs("div",{ref:$,className:`task-item ${s?"task-item--selection-mode":""} ${v?"task-item--selected":""} ${ae?"task-item--compact":"task-item--wide"} task-item--${e.status.toLowerCase()}`,onClick:Te,children:[s&&t.jsx("div",{className:"task-item__checkbox",children:t.jsx(vt,{checked:v,onChange:h=>d==null?void 0:d(e.id,h)})}),(o||P||e.status===k.PROCESSING)&&(W||z||O||e.type===g.VIDEO||e.type===g.IMAGE||e.type===g.AUDIO)&&t.jsx("div",{className:"task-item__preview-wrapper",children:t.jsx("div",{className:"task-item__preview","data-track":"task_click_preview",onClick:fe,children:P?t.jsxs("div",{className:"task-item__preview-failed",children:[t.jsx(_t,{size:"24px"}),t.jsx("span",{children:"生成失败"})]}):e.status===k.PROCESSING?O?t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:ne==="analyze"?`视频分析中 ${Math.round(e.progress??0)}%`:ne==="rewrite"?`脚本改编中 ${Math.round(e.progress??0)}%`:"生成文本中"})}):t.jsx(zt,{taskType:e.type,taskStatus:e.status,realProgress:e.progress,startedAt:e.startedAt,mediaUrl:W},e.startedAt):t.jsxs(t.Fragment,{children:[e.type===g.IMAGE&&x?t.jsxs(t.Fragment,{children:[t.jsx(ye,{src:se||x,alt:"Generated",maxRetries:5,fallback:t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:"图片加载失败"})})}),S>1&&t.jsxs("span",{className:"task-item__multi-badge",children:[S,"张"]})]}):G&&W?t.jsxs(t.Fragment,{children:[t.jsx(ye,{src:W,alt:l||"音频封面",maxRetries:3,fallback:t.jsxs("div",{className:"task-item__preview-placeholder",children:[t.jsx(_e,{size:"24px"}),t.jsx("span",{children:"音频封面"})]})}),t.jsx("div",{className:"task-item__video-play-overlay",children:t.jsx(_e,{size:"28px"})}),S>1&&t.jsxs("span",{className:"task-item__multi-badge",children:[S,"首"]})]}):R?t.jsxs("div",{className:"task-item__preview-placeholder",children:[t.jsx(Qe,{size:"24px"}),t.jsx("span",{children:"歌词"})]}):O?t.jsx("div",{className:"task-item__preview-placeholder",children:t.jsx("span",{children:"文本"})}):z&&((Ge=e.result)!=null&&Ge.characterProfileUrl)?t.jsx("div",{className:"task-item__character-preview",children:t.jsx(ye,{src:e.result.characterProfileUrl,alt:`@${e.result.characterUsername}`,maxRetries:5,fallback:t.jsx("div",{className:"task-item__character-fallback",children:t.jsx(Se,{size:"32px"})})})}):x?t.jsxs(t.Fragment,{children:[t.jsx(kt,{src:x,poster:(Be=e.result)==null?void 0:Be.previewImageUrl,alt:l||"视频预览",thumbnailSize:"small",videoProps:{muted:!0,playsInline:!0,preload:"metadata"}}),t.jsx("div",{className:"task-item__video-play-overlay",children:t.jsx(_e,{size:"32px"})})]}):t.jsx("div",{className:"task-item__preview-placeholder",children:e.type===g.IMAGE?t.jsx(xt,{size:"24px"}):e.type===g.VIDEO?t.jsx(jt,{size:"24px"}):t.jsxs(t.Fragment,{children:[t.jsx(_e,{size:"24px"}),t.jsx("span",{children:"音频"})]})}),D&&t.jsx(ee,{content:B,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(ee,{content:e.params.prompt,showArrow:!1,children:t.jsx("div",{className:"task-item__prompt",children:l})}),O&&K&&t.jsx(ee,{content:K,showArrow:!1,children:t.jsx("div",{className:"task-item__subtitle",children:K})})]}),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(X,{theme:Bt(e.status),variant:"light",className:"task-item__status-tag",children:Wt(e.status)}),e.params.model&&t.jsx(X,{variant:"outline",className:"task-item__model-tag",children:e.params.model}),O&&ue&&t.jsx(X,{variant:"outline",children:ue}),I&&H&&t.jsx(X,{variant:"outline",children:H}),I&&te&&t.jsx(X,{variant:"outline",children:te}),I&&m&&t.jsx(X,{variant:"outline",children:m}),e.type===g.VIDEO&&e.params.seconds&&t.jsxs(X,{variant:"outline",children:[e.params.seconds,"s"]}),e.type===g.VIDEO&&e.params.size&&t.jsx(X,{variant:"outline",children:e.params.size}),L&&t.jsx(X,{variant:"outline",children:L}),e.type===g.AUDIO&&e.params.mv&&!R&&t.jsx(X,{variant:"outline",children:e.params.mv}),e.type===g.AUDIO&&e.params.tags&&!R&&t.jsx(X,{variant:"outline",children:((We=String(e.params.tags).split(",")[0])==null?void 0:We.trim())||"音频"}),R&&t.jsx(X,{variant:"outline",children:"歌词"}),R&&Z[0]&&t.jsx(X,{variant:"outline",children:Z[0]}),e.params.batchId&&me!==null&&typeof e.params.batchTotal=="number"&&t.jsxs(X,{variant:"outline",children:["批量 ",me,"/",e.params.batchTotal]})]}),t.jsxs("div",{className:"task-item__details",children:[t.jsx("span",{className:"task-item__time",children:yt(e.createdAt)}),e.startedAt&&t.jsxs("span",{className:"task-item__duration",children:["·"," ",Tt((e.completedAt||Date.now())-e.startedAt)]}),(()=>{var ge,ve;const h=(n==null?void 0:n.width)||((ge=e.result)==null?void 0:ge.width)||e.params.width,re=(n==null?void 0:n.height)||((ve=e.result)==null?void 0:ve.height)||e.params.height;return h&&re?t.jsxs("span",{className:"task-item__size",children:[" ","· ",h,"x",re]}):null})(),L&&t.jsxs("span",{className:"task-item__size",children:[" · ",L]}),o&&((Xe=e.result)==null?void 0:Xe.url)&&!R&&t.jsx("a",{href:e.result.url,target:"_blank",rel:"noopener noreferrer",className:"task-item__link","data-track":"task_click_open_link",onClick:h=>h.stopPropagation(),children:"· 打开链接"})]}),(e.type===g.VIDEO||e.type===g.AUDIO||e.type===g.CHAT&&typeof e.progress=="number")&&e.status===k.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:[o&&((Ke=e.result)==null?void 0:Ke.url)&&!z&&t.jsx(ee,{content:"下载",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Ct,{}),"data-track":"task_click_download","data-track-params":ce,onClick:h=>{h.stopPropagation(),y==null||y(e.id)}})}),o&&R&&oe&&t.jsx(ee,{content:"复制歌词",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Qe,{}),onClick:h=>{h.stopPropagation(),A==null||A(e.id)}})}),!z&&!G&&!O&&t.jsx(ee,{content:"编辑",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Nt,{}),onClick:h=>{h.stopPropagation(),C==null||C(e.id)}})}),ie&&t.jsx(ee,{content:"以当前提示词再次生成",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(bt,{}),"aria-label":"再次生成","data-track":"task_click_regenerate_prefill","data-track-params":ce,onClick:h=>{h.stopPropagation(),i==null||i(e.id)}})}),V&&t.jsx(ee,{content:"角色",children:t.jsx(Q,{size:"small",variant:"text",icon:t.jsx(Se,{}),onClick:h=>{h.stopPropagation(),a==null||a(e.id)}})}),t.jsx(ee,{content:"删除",children:t.jsx(Q,{size:"small",variant:"text",className:"task-item__delete-btn",icon:t.jsx(Et,{}),onClick:h=>{h.stopPropagation(),w==null||w(e.id)}})})]}),o&&((((Ye=e.result)==null?void 0:Ye.url)||((qe=e.result)==null?void 0:qe.chatResponse))&&!z||R)&&t.jsx(Q,{size:"small",theme:"primary",className:"task-item__primary-action","data-track":"task_click_insert","data-track-params":ce,onClick:h=>{h.stopPropagation(),T==null||T(e.id)},children:"插入"}),M&&t.jsx(Q,{size:"small",theme:"primary",className:"task-item__primary-action","data-track":"task_click_retry","data-track-params":ce,onClick:h=>{h.stopPropagation(),f==null||f(e.id)},children:"重试"})]})]}),P&&e.error&&t.jsx("div",{className:"task-item__error",children:t.jsxs("div",{className:"task-item__error-message",children:[e.error.message,((Je=e.error.details)==null?void 0:Je.originalError)&&t.jsx(ee,{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:h=>h.stopPropagation(),children:"[详情]"})})]})})]})]})]})},(e,s)=>{var v,_;return e.task.id===s.task.id&&e.task.status===s.task.status&&e.task.progress===s.task.progress&&((v=e.task.error)==null?void 0:v.message)===((_=s.task.error)==null?void 0:_.message)&&e.task.result===s.task.result&&e.isSelected===s.isSelected&&e.selectionMode===s.selectionMode&&e.isCompact===s.isCompact&&e.onRegenerate===s.onRegenerate}),Xt=new Set,Kt=140,tt=0,Yt=3,st=375,qt=20,rs=({tasks:e,selectionMode:s=!1,selectedTaskIds:v,onSelectionChange:_,onRetry:d,onDelete:f,onDownload:w,onInsert:y,onCopy:T,onEdit:A,onRegenerate:j,onPreviewOpen:C,onExtractCharacter:i,className:a="",emptyContent:n,isCompact:N,hasMore:E=!1,isLoadingMore:u=!1,onLoadMore:$,totalCount:o,loadedCount:P,allLoadedText:Y,allLoadedHint:M})=>{const ae=v??Xt,U=r.useRef(null),V=r.useRef(null),z=r.useRef(null),G=r.useRef(0),[O,R]=r.useState(()=>typeof window<"u"&&window.innerWidth<st),[ie,le]=r.useState(!1),oe=N!==void 0?N:O,he=l=>{let p=l;for(;p;){const I=getComputedStyle(p).overflowY;if((I==="auto"||I==="scroll")&&p.scrollHeight>p.clientHeight)return p;p=p.parentElement}return null};r.useEffect(()=>{if(!E||!$)return;const l=U.current;if(!l)return;const p=setTimeout(()=>{const I=l.scrollHeight>l.clientHeight?l:he(l);if(z.current=I,!I)return;const H=()=>{const{scrollTop:te,scrollHeight:c,clientHeight:m}=I,b=c-te-m,x=Date.now();x-G.current<500||b<300&&E&&!u&&(G.current=x,$())};I.addEventListener("scroll",H,{passive:!0}),H(),l.__loadMoreCleanup=()=>{I.removeEventListener("scroll",H)}},150);return()=>{var L;clearTimeout(p),(L=l.__loadMoreCleanup)==null||L.call(l)}},[E,u,$,e.length]),r.useEffect(()=>{const l=U.current;if(!l)return;const p=setTimeout(()=>{const I=l.scrollHeight>l.clientHeight?l:he(l);if(z.current=I,!I)return;const H=()=>{le(I.scrollTop>I.clientHeight)};I.addEventListener("scroll",H),H(),l.__scrollCleanup=()=>{I.removeEventListener("scroll",H)}},100);return()=>{var L;clearTimeout(p),(L=l.__scrollCleanup)==null||L.call(l)}},[e.length]);const de=()=>{const l=z.current||U.current;l&&(l.scrollTop=0)};r.useEffect(()=>{if(N!==void 0)return;const l=U.current;if(!l)return;const p=l,L=H=>{const te=H??p.getBoundingClientRect().width;R(te<st)},I=new ResizeObserver(H=>{L(H[0].contentRect.width)});return I.observe(p),L(),()=>{I.disconnect()}},[N,U.current]);const Z=e.length>qt,ne=Mt({count:Z?e.length:0,getScrollElement:()=>U.current,estimateSize:()=>Kt+tt,overscan:Yt,enabled:Z,measureElement:l=>l.offsetHeight});if(e.length===0)return t.jsx("div",{className:`virtual-task-list virtual-task-list--empty ${a}`,children:n});const K=e.length||P||0,ue=()=>t.jsxs(t.Fragment,{children:[u&&t.jsxs("div",{className:"virtual-task-list__loading-more",children:[t.jsx("span",{className:"virtual-task-list__loading-spinner"}),t.jsx("span",{children:"加载中..."})]}),E&&!u&&o!==void 0&&o>0&&t.jsxs("div",{className:"virtual-task-list__pagination-info",children:["已加载 ",K," / ",o]}),!E&&e.length>0&&o!==void 0&&o>50&&t.jsx("div",{className:"virtual-task-list__no-more",children:M?t.jsx(ee,{content:M,children:t.jsx("span",{children:Y||`已加载全部 ${o} 个任务`})}):Y||`已加载全部 ${o} 个任务`})]});if(!Z)return t.jsxs("div",{ref:V,className:`virtual-task-list-container ${a}`,style:{height:"100%",position:"relative",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{ref:U,className:"virtual-task-list-scrollarea",style:{flex:1,overflow:"auto"},children:[e.map(l=>t.jsx(et,{task:l,selectionMode:s,isSelected:ae.has(l.id),isCompact:oe,onSelectionChange:_,onRetry:d,onDelete:f,onDownload:w,onInsert:y,onEdit:A,onRegenerate:j,onPreviewOpen:()=>C==null?void 0:C(l.id),onExtractCharacter:i},l.id)),t.jsx(ue,{})]}),ie&&t.jsx(Q,{shape:"circle",variant:"base",theme:"default",icon:t.jsx(Ze,{}),onClick:de,className:"virtual-task-list__back-to-top"})]});const me=ne.getVirtualItems();return t.jsxs("div",{ref:V,className:`virtual-task-list-container ${a}`,style:{height:"100%",width:"100%",position:"relative",display:"flex",flexDirection:"column"},children:[t.jsxs("div",{ref:U,className:"virtual-task-list-scrollarea",style:{flex:1,width:"100%",overflow:"auto"},children:[t.jsx("div",{style:{height:`${ne.getTotalSize()}px`,width:"100%",position:"relative"},children:me.map(l=>{const p=e[l.index];return p?t.jsx("div",{"data-index":l.index,ref:L=>{L&&ne.measureElement(L)},style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${l.start}px)`,paddingBottom:`${tt}px`},children:t.jsx(et,{task:p,selectionMode:s,isSelected:ae.has(p.id),isCompact:oe,onSelectionChange:_,onRetry:d,onDelete:f,onDownload:w,onInsert:y,onCopy:T,onEdit:A,onRegenerate:j,onPreviewOpen:()=>C==null?void 0:C(p.id),onExtractCharacter:i})},p.id):null})}),t.jsx(ue,{})]}),ie&&t.jsx(Q,{shape:"circle",variant:"base",theme:"default",icon:t.jsx(Ze,{}),onClick:de,className:"virtual-task-list__back-to-top"})]})};function Jt(e,s){const[v,_]=r.useState(s||null),[d,f]=r.useState(!1),[w,y]=r.useState(!0),[T,A]=r.useState(null),j=r.useRef("none"),C=r.useCallback(async()=>{if(y(!0),!s){_(null),f(!1),y(!1);return}const i=await xe.getCachedUrl(s);i?(T&&T!==i&&URL.revokeObjectURL(T),A(i),_(i),f(!0)):s?(_(s),f(!1)):(_(null),f(!1)),y(!1)},[s,T]);return r.useEffect(()=>{C(),s&&(j.current=xe.getCacheStatus(s))},[e,s]),r.useEffect(()=>xe.subscribe(()=>{if(!s)return;const a=xe.getCacheStatus(s),n=j.current;a!==n&&(j.current=a,(a==="cached"||a==="none")&&C())}),[s,C]),r.useEffect(()=>()=>{T&&URL.revokeObjectURL(T)},[T]),{url:v,isFromCache:d,isLoading:w}}const rt=1,je=3,Qt=({videoUrl:e,videoDuration:s,onConfirm:v,onCancel:_,disabled:d=!1})=>{const f=r.useRef(null),w=r.useRef(null),y=r.useRef(null),T=r.useRef(null),A=r.useRef(0),[j,C]=r.useState(!0),[i,a]=r.useState(s),[n,N]=r.useState(0),[E,u]=r.useState(Math.min(je,s)),[$,o]=r.useState(0),[P,Y]=r.useState(""),[M,ae]=r.useState(!1),[U,V]=r.useState(null),[z,G]=r.useState([]),[O,R]=r.useState(!1),ie=E-n,le=i>0?ie/i*100:100,oe=i>0?n/i*100:0;r.useEffect(()=>(e&&(C(!0),Y(""),G([]),ae(!1),V(null)),()=>{T.current!==null&&cancelAnimationFrame(T.current)}),[e]);const he=()=>{const c=f.current;if(c){const m=c.duration;a(m),ae(!0),u(Math.min(je,m))}},de=r.useCallback(async()=>{const c=f.current;if(!(!c||!M||i<=0||O)){R(!0);try{const b=Math.max(4,Math.ceil(i*2)),x=i/b,q=[],F=document.createElement("canvas"),D=F.getContext("2d");if(!D)return;const B=50,S=c.videoWidth/c.videoHeight||16/9,ce=Math.round(B*S);F.width=ce,F.height=B;for(let W=0;W<b;W++){const se=Math.min((W+.5)*x,i-.01);await new Promise(Te=>{const fe=()=>{c.removeEventListener("seeked",fe),Te()};c.addEventListener("seeked",fe),c.currentTime=se}),D.drawImage(c,0,0,ce,B),q.push(F.toDataURL("image/jpeg",.5))}G(q),c.currentTime=n}catch(m){console.warn("Failed to generate frame strip:",m)}finally{R(!1)}}},[M,i,O,n]);r.useEffect(()=>{if(M&&i>0&&z.length===0&&!O){const c=setTimeout(()=>{de()},100);return()=>clearTimeout(c)}},[M,i,z.length,O,de]);const Z=r.useCallback(()=>{const c=f.current,m=w.current;if(!c||!m)return;const b=m.getContext("2d");if(b)try{m.width=c.videoWidth,m.height=c.videoHeight,b.drawImage(c,0,0,m.width,m.height);const x=m.toDataURL("image/jpeg",.8);Y(x),C(!1)}catch(x){console.warn("Failed to generate frame image:",x)}},[]),ne=r.useCallback(()=>{const c=f.current;c&&j&&(c.currentTime===0||Math.abs(c.currentTime-n)<.1)&&Z()},[j,n,Z]),K=r.useCallback(c=>{const m=f.current;!m||!M||Math.abs(c-A.current)<.1||(A.current=c,m.readyState>=2&&(m.currentTime=c))},[M]),ue=r.useCallback(()=>{Z()},[Z]);r.useEffect(()=>{if(M&&i>0){o(n);const c=f.current;c&&c.readyState>=2&&(c.currentTime=n)}},[M,i]);const me=r.useCallback(c=>{const m=y.current;if(!m)return 0;const b=m.getBoundingClientRect(),x=c.clientX-b.left;return Math.max(0,Math.min(1,x/b.width))*i},[i]),l=c=>{if(d||!M)return;c.preventDefault(),c.stopPropagation(),V("left");const m=E,b=q=>{const F=me(q),D=m-rt,B=Math.max(0,m-je),S=Math.max(B,Math.min(D,F));N(S),o(S),K(S)},x=()=>{V(null),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",x),K(n)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",x)},p=c=>{if(d||!M)return;c.preventDefault(),c.stopPropagation(),V("right");const m=n,b=q=>{const F=me(q),D=m+rt,B=Math.min(i,m+je),S=Math.max(D,Math.min(B,F));u(S),o(S),K(S)},x=()=>{V(null),document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",x),K(E)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",x)},L=c=>{if(d||!M)return;c.preventDefault(),V("center");const m=y.current;if(!m)return;const b=m.getBoundingClientRect(),x=c.clientX,q=n,F=E-n,D=S=>{const W=(S.clientX-x)/b.width*i;let se=q+W;se=Math.max(0,Math.min(i-F,se)),N(se),u(se+F),o(se),K(se)},B=()=>{V(null),document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",B),K(n)};document.addEventListener("mousemove",D),document.addEventListener("mouseup",B)},I=c=>{if(d||!M||U||c.target.closest(".character-time-selector__range"))return;const b=y.current;if(!b)return;const x=b.getBoundingClientRect(),F=(c.clientX-x.left)/x.width*i,D=E-n,B=D/2;let S=F-B;S=Math.max(0,Math.min(i-D,S)),N(S),u(S+D),o(S),K(S)},H=()=>{v(Math.round(n),Math.round(E))},te=c=>c.toFixed(1)+"s";return t.jsxs("div",{className:`character-time-selector ${U?"is-dragging":""}`,children:[t.jsx("video",{ref:f,src:e,style:{display:"none"},muted:!0,playsInline:!0,preload:"auto",crossOrigin:"anonymous",onLoadedMetadata:he,onSeeked:ue,onCanPlay:ne}),t.jsx("canvas",{ref:w,style:{display:"none"}}),t.jsxs("div",{className:"character-time-selector__preview",children:[j?t.jsxs("div",{className:"character-time-selector__loading",children:[t.jsx("div",{className:"character-time-selector__spinner"}),t.jsx("span",{children:"加载中..."})]}):P?t.jsx("img",{src:P,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:te($)})]}),t.jsxs("div",{className:"character-time-selector__timeline",ref:y,onClick:I,children:[z.length>0?t.jsx("div",{className:"character-time-selector__frame-strip",children:z.map((c,m)=>t.jsx("img",{src:c,alt:"",className:"character-time-selector__frame-thumb",draggable:!1},m))}):O?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 ${U?"dragging":""}`,style:{left:`${oe}%`,width:`${le}%`},children:[t.jsx("div",{className:"character-time-selector__handle character-time-selector__handle--left",onMouseDown:l}),t.jsx("div",{className:"character-time-selector__range-content",onMouseDown:L,children:t.jsxs("span",{className:"character-time-selector__range-label",children:[te(n)," - ",te(E)]})}),t.jsx("div",{className:"character-time-selector__handle character-time-selector__handle--right",onMouseDown:p})]})]}),t.jsxs("div",{className:"character-time-selector__info",children:[t.jsxs("span",{children:["API参数: ",Math.round(n),", ",Math.round(E)]}),t.jsxs("span",{children:["时长: ",ie.toFixed(1),"s"]})]}),t.jsxs("div",{className:"character-time-selector__actions",children:[t.jsx(Q,{variant:"outline",onClick:_,disabled:d,children:"取消"}),t.jsx(Q,{theme:"primary",onClick:H,disabled:d||!M,children:"创建角色"})]})]})},as=({visible:e,task:s,onClose:v,onCreateStart:_,onCreateComplete:d})=>{var E;const{createTask:f,tasks:w}=St(),[y,T]=r.useState(!1),A=r.useRef(!1),{url:j}=Jt((s==null?void 0:s.id)??"",(E=s==null?void 0:s.result)==null?void 0:E.url),C=r.useMemo(()=>s!=null&&s.params.seconds?parseFloat(s.params.seconds.toString()):10,[s==null?void 0:s.params.seconds]),i=r.useMemo(()=>s?w.some(u=>u.type===g.CHARACTER&&u.params.sourceLocalTaskId===s.id&&(u.status===k.PENDING||u.status===k.PROCESSING)):!1,[s,w]),a=r.useCallback(async(u,$)=>{if(!(A.current||y||i)){if(!s||!s.remoteId){Ce.error("无效的任务数据");return}A.current=!0,T(!0),_==null||_();try{const o=Rt(u,$),P=Lt(s.params.model),Y=f({prompt:s.params.prompt||"角色提取",model:P,sourceVideoTaskId:s.remoteId,characterTimestamps:o,sourceLocalTaskId:s.id},g.CHARACTER);Ce.success("角色创建任务已加入队列"),d==null||d(Y.id),v()}catch(o){console.error("Failed to create character task:",o);const P=o.message||"创建任务失败";Ce.error(P)}finally{A.current=!1,T(!1)}}},[i,f,y,v,d,_,s]),n=()=>{y||v()},N=()=>{y||v()};return!s||!j?null:t.jsxs(It,{visible:e,header:"角色",onClose:n,footer:null,width:560,className:"character-create-dialog",closeOnOverlayClick:!y,closeOnEscKeydown:!y,children:[t.jsxs("div",{className:"character-create-dialog__description",children:["从视频中提取角色,创建后可通过 ",t.jsx("code",{children:"@username"})," 在提示词中引用"]}),i&&t.jsx("div",{className:"character-create-dialog__warning",children:"此视频已有一个角色正在创建中"}),t.jsx(Qt,{videoUrl:j,videoDuration:C,onConfirm:a,onCancel:N,disabled:y||i})]})},ns=({characterId:e,profilePictureUrl:s,alt:v="Character",className:_,onClick:d})=>{const[f,w]=r.useState(s||null),[y,T]=r.useState(!1),[A,j]=r.useState(!0);r.useEffect(()=>{let a=!1;return(async()=>{j(!0),T(!1);const N=await be.getCachedUrl(e);if(!a){if(N){w(N),j(!1);return}s?(w(s),be.cacheAvatar(e,s).catch(()=>{})):T(!0),j(!1)}})(),()=>{a=!0}},[e,s]);const C=async()=>{if(f===s){const a=await be.getCachedUrl(e);if(a&&a!==f){w(a);return}}T(!0)},i=()=>{j(!1)};return y||!f?t.jsx("div",{className:_,onClick:d,style:d?{cursor:"pointer"}:void 0,children:t.jsx(Se,{})}):t.jsx(ye,{src:f,alt:v,className:_,onLoadFailure:()=>void C(),onLoad:i,onClick:d,style:{display:A?"none":"block",cursor:d?"pointer":void 0},showSkeleton:!1,eager:!0})};function cs(){const[e,s]=r.useState([]),[v,_]=r.useState(!0),d=r.useRef(new Map);r.useEffect(()=>{const a=J.getCharacters$().subscribe(n=>{s(n),_(!1)});return J.init(),()=>a.unsubscribe()},[]),r.useEffect(()=>{v||(async()=>{const n=J.getPendingCharacters();for(const N of n)d.current.get(N.id)||f(N)})()},[v]);const f=r.useCallback(async a=>{if(!d.current.get(a.id)){d.current.set(a.id,!0);try{const n=await Ee.resumePolling(a.id,{onStatusChange:async N=>{await J.updateCharacterStatus(a.id,N)}});await J.updateCharacter(a.id,{username:n.username,profilePictureUrl:n.profile_picture_url,permalink:n.permalink,status:"completed",completedAt:Date.now()})}catch(n){console.error("[useCharacters] Character polling failed:",n),await J.updateCharacterStatus(a.id,"failed",n.message)}finally{d.current.delete(a.id)}}},[]),w=r.useCallback(async a=>{var N;const n=Date.now();Ne.track("character_extract_start",{videoTaskId:a.videoTaskId,hasTimestamps:!!((N=a.characterTimestamps)!=null&&N.length)});try{const u=(await Ee.createCharacter(a)).id,$={id:u,username:"",profilePictureUrl:"",sourceTaskId:a.localTaskId||"",sourceVideoId:a.videoTaskId,sourcePrompt:a.sourcePrompt,characterTimestamps:a.characterTimestamps,status:"processing",createdAt:Date.now()};return await J.saveCharacter($),d.current.set(u,!0),Ee.resumePolling(u,{onStatusChange:async o=>{await J.updateCharacterStatus(u,o)}}).then(async o=>{await J.updateCharacter(u,{username:o.username,profilePictureUrl:o.profile_picture_url,permalink:o.permalink,status:"completed",completedAt:Date.now()}),Ne.track("character_extract_success",{characterId:u,username:o.username,duration:Date.now()-n})}).catch(async o=>{console.error("[useCharacters] Character creation failed:",o),await J.updateCharacterStatus(u,"failed",o.message),Ne.track("character_extract_failed",{characterId:u,error:o.message,duration:Date.now()-n})}).finally(()=>{d.current.delete(u)}),$}catch(E){throw console.error("[useCharacters] Failed to create character:",E),E}},[]),y=r.useCallback(async a=>(d.current.delete(a),J.deleteCharacter(a)),[]),T=r.useCallback(async()=>{await J.init()},[]),A=r.useCallback(a=>e.find(n=>n.id===a),[e]),j=r.useCallback(a=>e.some(n=>n.sourceTaskId===a&&(n.status==="pending"||n.status==="processing")),[e]),C=e.filter(a=>a.status==="completed"),i=e.filter(a=>a.status==="pending"||a.status==="processing");return{characters:e,completedCharacters:C,pendingCharacters:i,isLoading:v,createCharacter:w,deleteCharacter:y,refreshCharacters:T,getCharacterById:A,isCreatingCharacterForTask:j}}export{ns as C,et as T,rs as V,as as a,cs as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./startup-app-
|
|
1
|
+
import{r as e}from"./startup-app-eD_rQhSh.js";function M(i={}){const{showNavbar:s=!0,showToolbar:o=!0,showTitle:n=!0,videoAutoPlay:g=!0,videoLoop:p=!0,onClose:a,onIndexChange:r}=i,[u,w]=e.useState(!1),[l,x]=e.useState([]),[c,d]=e.useState(0),I=e.useCallback((t,v=0)=>{const m=Array.isArray(t)?t:[t];m.length!==0&&(x(m),d(Math.max(0,Math.min(v,m.length-1))),w(!0))},[]),h=e.useCallback(()=>{w(!1),x([]),d(0),a==null||a()},[a]),f=e.useCallback(t=>{d(t),r==null||r(t)},[r]),b=e.useMemo(()=>({visible:u,items:l,initialIndex:c,onClose:h,onIndexChange:f,showNavbar:s,showToolbar:o,showTitle:n,videoAutoPlay:g,videoLoop:p}),[u,l,c,h,f,s,o,n,g,p]);return{openViewer:I,closeViewer:h,isOpen:u,currentIndex:c,items:l,viewerProps:b}}function V(i,s="image"){return i.map((o,n)=>({url:o,type:s,alt:`${s==="image"?"Image":"Video"} ${n+1}`}))}export{V as a,M as u};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as j}from"./startup-runtime-DTmhLESk.js";import{
|
|
2
|
+
import{_ as j}from"./startup-runtime-DTmhLESk.js";import{kN as ke,kO as oe,kP as Se,aD as ye,r as S,j as We,bz as ne,dB as G,bg as le,g9 as $,kQ as he,iT as xe,aX as se}from"./startup-app-eD_rQhSh.js";import{w as F}from"./workflow-submission-service-Ce0cpj8E.js";import{q as K,H as Q,J as ce,f as Re,L as Ie}from"./ai-chat-BO5vbKZW.js";import{S as re}from"./skill-dsl-parser-Do9iAYbB.js";function be(t){if(!/\[(?:Intro|Verse|Chorus|Pre-Chorus|Bridge|Outro|Hook|Fade|Instrumental|Interlude)/i.test(t))return{lyrics:t};const e=t.split(`
|
|
3
3
|
`);let o,n;const a=[];for(const l of e){const s=l.trim();if(!o&&/^#\s+(.+)/.test(s)){o=s.replace(/^#\s+/,"").trim();continue}if(!n&&/^(?:标签|tags)\s*[::]\s*(.+)/i.test(s)){n=s.replace(/^(?:标签|tags)\s*[::]\s*/i,"").trim();continue}a.push(l)}for(;a.length>0&&a[0].trim()==="";)a.shift();for(;a.length>0&&a[a.length-1].trim()==="";)a.pop();return{title:o,tags:n,lyrics:a.join(`
|
|
4
|
-
`)}}function Y(){return`wf-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}const _e=new Set(["generate_image","generate_video","generate_long_video","generate_audio","generate_text"]);function ee(t){return ye(t)}function
|
|
4
|
+
`)}}function Y(){return`wf-${Date.now()}-${Math.random().toString(36).substring(2,8)}`}const _e=new Set(["generate_image","generate_video","generate_long_video","generate_audio","generate_text"]);function ee(t){return ye(t)}function V(t,e){return e.length===0?t:{...t,knowledgeContextRefs:e}}function ve(t,e){return e.length===0?t:t.map(o=>!_e.has(o.mcp)||o.args.knowledgeContextRefs?o:{...o,args:V(o.args,e)})}function Me(t,e,o=!1){return t.map(n=>({...n,args:Re(n.mcp,{...n.args},{defaultModels:e.defaultModels,defaultModelRefs:e.defaultModelRefs,contextModel:{id:e.modelId,type:e.generationType==="agent"?"text":e.generationType},contextModelRef:e.modelRef,overrideSpecifiedModel:o})}))}function Te(t,e){return e.length===0?t:t.map(o=>{var l;if(o.args.referenceImages)return o;const n=K.getTool(o.mcp);return o.mcp==="generate_ppt"||!!((l=n==null?void 0:n.inputSchema.properties)!=null&&l.referenceImages)?{...o,args:{...o.args,referenceImages:e}}:o})}function Ce(t,e=[]){var I;const{generationType:o,modelId:n,modelRef:a,isModelExplicit:l,prompt:s,userInstruction:x,rawInput:y,count:u,size:f,duration:_,extraParams:i,selection:r,defaultModels:d,defaultModelRefs:k,knowledgeContextRefs:C}=t,b=ee(C),c=[],h=Y(),p=`wf_batch_${h}`;for(let W=0;W<u;W++){const v=`${h}-step-${W+1}`,M={mode:"queue",batchId:p,batchIndex:W+1,batchTotal:u,globalIndex:W+1};if(o==="image"){const g=V({prompt:s,model:n,modelRef:a,workflowId:h,batchId:p,batchIndex:W+1,batchTotal:u,globalIndex:W+1},b);f&&(g.size=f),e.length>0&&(g.referenceImages=e),i&&(g.params=i),c.push({id:v,mcp:"generate_image",args:g,options:M,description:u>1?`生成图片 (${W+1}/${u})`:"生成图片",status:"pending"})}else if(o==="video"){const g=V({prompt:s,model:n,modelRef:a,seconds:_||"5",workflowId:h,batchId:p,batchIndex:W+1,batchTotal:u,globalIndex:W+1},b);f&&(g.size=f),e.length>0&&(g.referenceImages=e);const R={...i||{}};n==="happyhorse-1.0-video-edit"&&((I=r==null?void 0:r.videos)!=null&&I[0])&&!R.input_video&&(R.input_video=r.videos[0]),Object.keys(R).length>0&&(g.params=R),c.push({id:v,mcp:"generate_video",args:g,options:M,description:u>1?`生成视频 (${W+1}/${u})`:"生成视频",status:"pending"})}else if(o==="audio"){const g=typeof(i==null?void 0:i.sunoAction)=="string"?i.sunoAction:"music",R=g==="lyrics",T=V({prompt:s,model:n,modelRef:a,sunoAction:g,workflowId:h,batchId:p,batchIndex:W+1,batchTotal:u,globalIndex:W+1},b);if(!R&&s){const w=be(s);(w.title||w.tags)&&(T.prompt=w.lyrics,w.title&&!(i!=null&&i.title)&&(T.title=w.title),w.tags&&!(i!=null&&i.tags)&&(T.tags=w.tags))}i&&(T.params=i,i.notifyHook&&(T.notifyHook=i.notifyHook),!R&&i.mv&&(T.mv=i.mv),!R&&i.title&&(T.title=i.title),!R&&i.tags&&(T.tags=i.tags),!R&&i.continueClipId&&(T.continueClipId=i.continueClipId),!R&&i.continueAt!==void 0&&i.continueAt!==null&&i.continueAt!==""&&(T.continueAt=Number(i.continueAt))),c.push({id:v,mcp:"generate_audio",args:T,options:M,description:u>1?`${R?"生成歌词":"生成音频"} (${W+1}/${u})`:R?"生成歌词":"生成音频",status:"pending"})}else{const g=V({prompt:s,model:n,modelRef:a,rawInput:y,workflowId:h,batchId:p,batchIndex:W+1,batchTotal:u,globalIndex:W+1},b);e.length>0&&(g.referenceImages=e),i&&(g.params=i),c.push({id:v,mcp:"generate_text",args:g,options:M,description:"生成文本",status:"pending"})}}const m=o==="audio"&&c.every(W=>W.args.sunoAction==="lyrics");return{id:h,name:o==="image"?"图片生成":o==="video"?"视频生成":o==="text"?"文本生成":m?"歌词生成":"音频生成",description:`使用 ${n} 模型${u>1?`生成 ${u} 个`:"生成"}${o==="image"?"图片":o==="video"?"视频":o==="text"?"文本":m?"歌词":"音频"}`,scenarioType:"direct_generation",generationType:o,steps:c,metadata:{prompt:s,userInstruction:x,rawInput:y,modelId:n,modelRef:a,defaultModels:d,defaultModelRefs:k,isModelExplicit:l,count:u,size:f,duration:_,referenceImages:e.length>0?e:void 0,selection:r,knowledgeContextRefs:b.length>0?b:void 0},createdAt:Date.now()}}function Ae(t,e=[]){const{generationType:o,modelId:n,modelRef:a,isModelExplicit:l,prompt:s,userInstruction:x,rawInput:y,count:u,size:f,duration:_,extraParams:i,selection:r,defaultModels:d,defaultModelRefs:k,knowledgeContextRefs:C}=t,b=ee(C),c=Y(),h={userInstruction:x,rawInput:y,model:{id:n,type:o==="agent"?"text":o,isExplicit:l},params:{count:u,size:f,duration:_,...i},defaultModels:d,defaultModelRefs:k,selection:r,finalPrompt:s,knowledgeContextRefs:b.length>0?b:void 0},p=[...r.images||[],...r.graphics||[]];let m=Ie();p.length>0&&(m+=Q(p.length,r.imageDimensions));const I=ce(h),W=[{role:"system",content:m},{role:"user",content:I}],v=[{id:`${c}-step-analyze`,mcp:"ai_analyze",args:{context:h,messages:W,referenceImages:p.length>0?p:void 0,textModel:n,modelRef:a,knowledgeContextRefs:b.length>0?b:void 0},options:{mode:"async"},description:"AI 分析用户意图",status:"pending"}];return{id:c,name:"AI 智能生成",description:"AI 分析用户请求并执行相应操作",scenarioType:"agent_flow",generationType:o,steps:v,metadata:{prompt:s,userInstruction:x,rawInput:y,modelId:n,modelRef:a,isModelExplicit:l,count:u,size:f,duration:_,defaultModels:d,defaultModelRefs:k,referenceImages:e.length>0?e:void 0,selection:r,knowledgeContextRefs:b.length>0?b:void 0},createdAt:Date.now()}}function Ee(t){const e=[];for(const o of t){const n=K.getTool(o);if(!n)continue;const a=n.inputSchema.properties||{},l=n.inputSchema.required||[],s=n.promptGuidance,x=Object.entries(a).map(([u,f])=>{var b;const i=l.includes(u)?"(必填)":"(可选)",r=[];f.type&&r.push(`类型: ${f.type}`),f.enum&&Array.isArray(f.enum)&&r.push(`可选值: ${f.enum.map(c=>`"${c}"`).join(" | ")}`),f.default!==void 0&&r.push(`默认: "${f.default}"`);const d=r.length>0?` [${r.join(", ")}]`:"",k=(b=s==null?void 0:s.parameterGuidance)==null?void 0:b[u],C=k?`
|
|
5
5
|
💡 ${k}`:"";return` - **${u}**${i}: ${f.description||"无描述"}${d}${C}`}).join(`
|
|
6
6
|
`);let y=`### ${n.name}
|
|
7
7
|
${n.description}
|
|
@@ -13,13 +13,13 @@ ${x||" 无参数"}`;s!=null&&s.whenToUse&&(y+=`
|
|
|
13
13
|
|
|
14
14
|
---
|
|
15
15
|
|
|
16
|
-
`):""}async function tt(t,e,o=[],n){const{generationType:a,modelRef:l,modelId:s,isModelExplicit:x,prompt:y,userInstruction:u,rawInput:f,count:_,size:i,duration:r,selection:d,defaultModels:k,defaultModelRefs:C,knowledgeContextRefs:b}=t,c=ee(b),h=Y(),p=e.id,m=e.name,I=e.type==="system"?e.description:e.content,W=u||y||f,
|
|
16
|
+
`):""}async function tt(t,e,o=[],n){const{generationType:a,modelRef:l,modelId:s,isModelExplicit:x,prompt:y,userInstruction:u,rawInput:f,count:_,size:i,duration:r,selection:d,defaultModels:k,defaultModelRefs:C,knowledgeContextRefs:b}=t,c=ee(b),h=Y(),p=e.id,m=e.name,I=e.type==="system"?e.description:e.content,W=u||y||f,v={input:W,count:_,size:i,model:s},M=re.parse(I,v,h,W);if(M){const O=ve(Te(Me(M.steps,t,!0),o),c);return{id:h,name:m,description:`使用「${m}」Skill 生成内容`,scenarioType:"skill_flow",skillId:p,generationType:a,steps:O,metadata:{prompt:y,userInstruction:u,rawInput:f,modelId:s,modelRef:l,defaultModels:k,defaultModelRefs:C,isModelExplicit:x,count:_,size:i,duration:r,referenceImages:o.length>0?o:void 0,selection:d,knowledgeContextRefs:c.length>0?c:void 0,parseMethod:"regex"},createdAt:Date.now()}}const g=[...d.images||[],...d.graphics||[]],R={userInstruction:u,rawInput:f,model:{id:s,type:a==="agent"?"text":a,isExplicit:x},params:{count:_,size:i,duration:r},defaultModels:k,defaultModelRefs:C,selection:d,finalPrompt:y,knowledgeContextRefs:c.length>0?c:void 0},T=e.type==="external",w=e.type==="user",E=e.outputType==="image"?"image":"text",z=T||w&&E==="image"?ke(I,E):I,P=re.extractToolNamesFromContent(z).filter(O=>K.hasTool(O));E==="image"&&!P.includes("generate_image")&&K.hasTool("generate_image")&&P.push("generate_image");const N=P.includes("generate_image");if(P.length>0){const O=Ee(P);let U=`## 当前激活的 Skill:${m}
|
|
17
17
|
|
|
18
|
-
${z}`;
|
|
18
|
+
${z}`;O&&(U+=`
|
|
19
19
|
|
|
20
20
|
## 可用工具
|
|
21
21
|
|
|
22
|
-
${
|
|
22
|
+
${O}`),g.length>0&&(U+=Q(g.length,d.imageDimensions)),U+=`
|
|
23
23
|
|
|
24
24
|
## 响应格式(严格遵守)
|
|
25
25
|
|
|
@@ -41,4 +41,4 @@ ${F}`),g.length>0&&(U+=Q(g.length,d.imageDimensions)),U+=`
|
|
|
41
41
|
请基于以上 Skill 指令构建详细的图片描述 prompt,并使用以下 JSON 格式回复以调用图片生成工具:
|
|
42
42
|
{"content": "你的分析", "next": [{"mcp": "generate_image", "args": {"prompt": "你构建的完整 prompt"}}]}
|
|
43
43
|
|
|
44
|
-
你必须实际调用 generate_image 工具生成图片,不要仅输出文字描述。`);const V=[{role:"system",content:L},{role:"user",content:W}],pe=[{id:`${h}-step-analyze`,mcp:"ai_analyze",args:{context:R,messages:V,referenceImages:g.length>0?g:void 0,textModel:s,modelRef:l,knowledgeContextRefs:c.length>0?c:void 0},options:{mode:"async"},description:`AI 以「${m}」角色回复`,status:"pending"}];return{id:h,name:m,description:`使用「${m}」Skill 生成内容`,scenarioType:"skill_flow",skillId:p,generationType:a,steps:pe,metadata:{prompt:y,userInstruction:u,rawInput:f,modelId:s,modelRef:l,defaultModels:k,defaultModelRefs:C,isModelExplicit:x,count:_,size:i,duration:r,referenceImages:o.length>0?o:void 0,selection:d,knowledgeContextRefs:c.length>0?c:void 0,parseMethod:"agent_fallback"},createdAt:Date.now()}}function $e(t,e=[]){return t.scenario==="direct_generation"?Ce(t,e):Ae(t,e)}function Pe(t,e=0){try{let o=oe(t);if(!o){const l=Se(t),s=l.indexOf("{"),x=l.lastIndexOf("}");s>=0&&x>s&&(o=oe(l.slice(s,x+1)))}if(!o)return{content:"",steps:[]};const n=typeof o.content=="string"?o.content:"";if(!Array.isArray(o.next)||o.next.length===0)return{content:n,steps:[]};const a=o.next.filter(l=>typeof l.mcp=="string"&&typeof l.args=="object").map((l,s)=>({id:`step-${e+s+1}`,mcp:l.mcp,args:l.args,description:De(l.mcp,l.args),status:"pending"}));return{content:n,steps:a}}catch{return{content:"",steps:[]}}}function De(t,e){var o,n,a,l;switch(t){case"generate_image":return`生成图片: ${((o=e.prompt)==null?void 0:o.substring(0,30))||""}...`;case"generate_video":return`生成视频: ${((n=e.prompt)==null?void 0:n.substring(0,30))||""}...`;case"generate_audio":return`生成音频: ${((a=e.prompt)==null?void 0:a.substring(0,30))||""}...`;case"generate_text":return`生成文本: ${((l=e.prompt)==null?void 0:l.substring(0,30))||""}...`;case"ai_analyze":return"AI 分析用户意图";case"format_markdown":return"格式化输出";case"show_result":return"展示结果";default:return`执行 ${t}`}}function ze(t,e,o,n,a,l){return{...t,steps:t.steps.map(s=>s.id===e?{...s,status:o,result:n!==void 0?n:s.result,error:a,duration:l}:s)}}function Fe(t,e){const o=new Set(t.steps.map(a=>a.id)),n=e.filter(a=>!o.has(a.id));return n.length===0?t:{...t,steps:[...t.steps,...n]}}function G(t){const e=t.steps.filter(s=>s.status==="completed").length,o=t.steps.filter(s=>s.status==="failed").length,n=t.steps.find(s=>s.status==="running"),a=t.steps.filter(s=>s.status==="pending").length;let l;return o>0?l="failed":n?l="running":a===0&&e>0?l="completed":l="pending",{status:l,completedSteps:e,totalSteps:t.steps.length,currentStep:n||t.steps.find(s=>s.status==="pending")}}const ae={workflow:null,status:"idle",currentStep:null,completedSteps:0,totalSteps:0,error:null};function Oe(){const[t,e]=S.useState(ae),o=S.useRef(null),n=S.useRef(!1),a=S.useCallback(r=>{o.current=r,n.current=!1;const d=G(r);e({workflow:r,status:"running",currentStep:d.currentStep||null,completedSteps:d.completedSteps,totalSteps:d.totalSteps,error:null})},[]),l=S.useCallback(r=>{o.current=r,n.current=!1;const d=G(r);let k="running";r.status==="completed"?k="completed":(r.status==="failed"||r.status==="cancelled")&&(k="failed"),e({workflow:r,status:k,currentStep:d.currentStep||null,completedSteps:d.completedSteps,totalSteps:d.totalSteps,error:r.error||null})},[]),s=S.useCallback((r,d,k,C,b)=>{if(n.current)return;const c=o.current;if(!c)return;const h=ze(c,r,d,k,C,b);o.current=h,e(p=>{const m=G(h);let I="running";return m.status==="completed"?I="completed":m.status==="failed"&&(I="failed"),{...p,workflow:h,status:I,currentStep:m.currentStep||null,completedSteps:m.completedSteps,totalSteps:m.totalSteps,error:C||p.error}})},[]),x=S.useCallback(r=>{if(n.current||r.length===0)return;const d=o.current;if(!d)return;const k=Fe(d,r);o.current=k,e(C=>{const b=G(k);return{...C,workflow:k,currentStep:b.currentStep||C.currentStep,totalSteps:b.totalSteps}})},[]),y=S.useCallback(r=>{const d=o.current;if(!d||n.current)return{content:"",steps:[]};const k=d.steps.length,{content:C,steps:b}=Pe(r,k);return C&&!d.aiAnalysis&&(o.current={...d,aiAnalysis:C}),b.length>0&&x(b),{content:C,steps:b}},[x]),u=S.useCallback(()=>{o.current=null,n.current=!1,e(ae)},[]),f=S.useCallback(()=>{n.current=!0,e(r=>({...r,status:"failed",error:"工作流已中止"}))},[]),_=S.useCallback(()=>{n.current=!1,e(r=>({...r,status:"running",error:null}))},[]),i=S.useCallback(()=>o.current,[]);return{state:t,startWorkflow:a,restoreWorkflow:l,updateStep:s,addSteps:x,addStepsFromAIResponse:y,resetWorkflow:u,abortWorkflow:f,resumeWorkflow:_,getWorkflow:i}}const ue=S.createContext(null),ot=({children:t})=>{const e=Oe(),o=S.useMemo(()=>({state:e.state,startWorkflow:e.startWorkflow,restoreWorkflow:e.restoreWorkflow,updateStep:e.updateStep,addSteps:e.addSteps,addStepsFromAIResponse:e.addStepsFromAIResponse,resetWorkflow:e.resetWorkflow,abortWorkflow:e.abortWorkflow,resumeWorkflow:e.resumeWorkflow,getWorkflow:e.getWorkflow}),[e.state,e.startWorkflow,e.restoreWorkflow,e.updateStep,e.addSteps,e.addStepsFromAIResponse,e.resetWorkflow,e.abortWorkflow,e.resumeWorkflow,e.getWorkflow]);return We.jsx(ue.Provider,{value:o,children:t})};function Ne(){const t=S.useContext(ue);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function Le(){const t=Ne();return{startWorkflow:t.startWorkflow,restoreWorkflow:t.restoreWorkflow,updateStep:t.updateStep,addSteps:t.addSteps,addStepsFromAIResponse:t.addStepsFromAIResponse,resetWorkflow:t.resetWorkflow,abortWorkflow:t.abortWorkflow,resumeWorkflow:t.resumeWorkflow,getWorkflow:t.getWorkflow}}function D(t,e,o,n){var l;const a=t.metadata||{};return{id:t.id,name:t.name,generationType:t.generationType,prompt:a.prompt||((l=e==null?void 0:e.aiContext)==null?void 0:l.finalPrompt)||"",aiAnalysis:t.aiAnalysis,count:a.count,createdAt:t.createdAt,steps:t.steps.map(s=>({id:s.id,description:s.description,status:s.status,mcp:s.mcp,args:s.args,result:s.result,error:s.error,duration:s.duration,options:s.options})),retryContext:e,postProcessingStatus:o,insertedCount:n}}const Ue=20,ie=2e3,je=3e4;function de(t){const e=new Map;if(!t)return e;for(const o of t){const n=o.result;n!=null&&n.taskId&&e.set(n.taskId,o.id)}return e}function fe(t){var e;return t.status===B.PROCESSING?{status:"running"}:t.status===B.COMPLETED&&t.result?{status:"completed",result:{...t.result,taskId:t.id}}:t.status===B.FAILED?{status:"failed",error:typeof t.error=="string"?t.error:((e=t.error)==null?void 0:e.message)||"Task failed"}:null}function Ze(t,e,o,n,a,l){const s=o.getWorkflow(),y=de(s==null?void 0:s.steps).get(t.id);if(!y)return!1;const u=t.type!==le.IMAGE&&(s==null?void 0:s.generationType)!=="image";e.status==="running"&&o.resumeWorkflow(),o.updateStep(y,e.status,e.result,e.error);const f=o.getWorkflow();if(f){const _=D(f);n.current(_);const i=a.current,r=l.current;u&&i&&r&&$.updateWorkflow(i,r,_)}return!0}function Ve(t,e,o,n,a,l){var x;const s=a.current;if(!s||t.type===le.IMAGE)return!1;for(const y of s.children){if(!he(y))continue;const u=y;if(u.workflow.generationType==="image")continue;const _=de((x=u.workflow)==null?void 0:x.steps).get(t.id);if(!_)continue;const i=u.workflow.steps.map(d=>d.id!==_?d:{...d,status:e.status,...e.result!==void 0&&{result:e.result},...e.error!==void 0&&{error:e.error}}),r={...u.workflow,steps:i};if(e.status==="running"&&delete r.error,$.updateWorkflow(s,u.id,r),l.current=u.id,n.current(r),o.restoreWorkflow){const d={id:r.id,name:r.name||"",description:"",scenarioType:"direct_generation",generationType:r.generationType,status:e.status==="running"?"running":"failed",steps:i.map(k=>({id:k.id,mcp:k.mcp||"",args:k.args||{},description:k.description||"",status:k.status,result:k.result,error:k.error,duration:k.duration,options:k.options})),createdAt:r.createdAt||Date.now(),metadata:{prompt:r.prompt||"",userInstruction:"",rawInput:"",modelId:"",isModelExplicit:!1,count:r.count||1,selection:{texts:[],images:[],videos:[],graphics:[]}},aiAnalysis:r.aiAnalysis};o.restoreWorkflow(d)}return!0}return!1}function X(t,e,o,n,a){const l=t.task,s=fe(l);return s?!!(Ze(l,s,e,o,n,a)||Ve(l,s,e,o,n,a)):!1}function Ge(t){const{workflowControl:e,boardRef:o,workZoneIdRef:n}=t,a=S.useRef(t.updateWorkflowMessage);S.useEffect(()=>{a.current=t.updateWorkflowMessage},[t.updateWorkflowMessage]);const l=S.useRef(new Map),s=S.useRef(null),x=S.useRef(0),y=S.useRef(!1);S.useEffect(()=>{const u=i=>{const r=l.current;if(!r.has(i.task.id)&&r.size>=Ue){const d=r.keys().next().value;d&&r.delete(d)}r.set(i.task.id,i)},f=()=>{const i=new Map;for(const[r,d]of l.current.entries())X(d,e,a,o,n)||i.set(r,d);l.current=i,(i.size===0||Date.now()-x.current>je)&&(s.current&&(clearInterval(s.current),s.current=null),l.current=new Map)};if(!y.current){y.current=!0;const i=ne.getAllTasks();for(const r of i){const d=fe(r);d&&(d.status==="completed"||d.status==="failed")&&X({task:r},e,a,o,n)}}const _=ne.observeTaskUpdates().subscribe(i=>{if(i.type!=="taskUpdated")return;if(i.task.status===B.PROCESSING&&l.current.has(i.task.id)){u(i),s.current||(x.current=Date.now(),s.current=setInterval(f,ie));return}X(i,e,a,o,n)?l.current.delete(i.task.id):(u(i),s.current||(x.current=Date.now(),s.current=setInterval(f,ie)))});return()=>{_.unsubscribe(),s.current&&(clearInterval(s.current),s.current=null),l.current=new Map}},[e,o,n])}let q=null;const Be=new Promise(t=>{q=t});async function qe(t,e){const{operation:o,params:n}=e;try{const{insertImageFromUrl:a}=await j(async()=>{const{insertImageFromUrl:u}=await import("./startup-app-DxX-P1pm.js").then(f=>f.nN);return{insertImageFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{insertVideoFromUrl:l}=await j(async()=>{const{insertVideoFromUrl:u}=await import("./startup-app-DxX-P1pm.js").then(f=>f.nO);return{insertVideoFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{insertAudioFromUrl:s}=await j(async()=>{const{insertAudioFromUrl:u}=await import("./startup-app-DxX-P1pm.js").then(f=>f.nP);return{insertAudioFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{getSmartInsertionPoint:x}=await j(async()=>{const{getSmartInsertionPoint:u}=await import("./startup-app-DxX-P1pm.js").then(f=>f.nM);return{getSmartInsertionPoint:u}},__vite__mapDeps([0]),import.meta.url),y=n.position?[n.position.x,n.position.y]:x(t)||[100,100];if(o==="canvas_insert"&&n.items)for(const u of n.items)u.type==="image"&&u.url?await a(t,u.url,y):u.type==="video"&&u.url?await l(t,u.url,y):u.type==="audio"&&u.url&&await s(t,u.url,u,y);else o==="insert_image"&&n.url?await a(t,n.url,y):o==="insert_video"&&n.url?await l(t,n.url,y):o==="insert_audio"&&n.url&&await s(t,n.url,n,y)}catch(a){console.error("[useWorkflowSubmission] Failed to insert to canvas:",a)}}function Ke(t){const{boardRef:e,workZoneIdRef:o}=t,n=Le(),a=xe(),l=S.useRef(a.sendWorkflowMessage),s=S.useRef(a.updateWorkflowMessage);S.useEffect(()=>{l.current=a.sendWorkflowMessage,s.current=a.updateWorkflowMessage},[a.sendWorkflowMessage,a.updateWorkflowMessage]),Ge({workflowControl:n,updateWorkflowMessage:a.updateWorkflowMessage,boardRef:e,workZoneIdRef:o});const x=S.useRef(null),y=S.useRef([]),u=S.useRef(!1),f=S.useRef(null),_=S.useCallback(c=>c!=="image",[]),i=S.useCallback(async()=>{if(!u.current){u.current=!0;try{await O.recoverWorkflows()}catch(c){console.warn("[useWorkflowSubmission] Failed to recover workflows:",c)}finally{q==null||q()}}},[]);S.useEffect(()=>{O.init(),O.registerCanvasHandler(async(h,p)=>({success:!0}));const c=O.subscribeToAllEvents(h=>{var p,m,I,W,M,v,g,R,T;if(h.type==="recovered"&&h.workflow){const w=h.workflow,H=w.status==="running"||w.status==="pending",E=w.status==="failed"&&w.updatedAt&&Date.now()-w.updatedAt<300*1e3;if(!H&&!E)return;(p=n.restoreWorkflow)==null||p.call(n,w);const A=se.get(),z={aiContext:{rawInput:((m=w.context)==null?void 0:m.userInput)||"",userInstruction:((I=w.context)==null?void 0:I.userInput)||"",model:{id:((W=w.context)==null?void 0:W.model)||"",type:w.generationType==="video"?"video":w.generationType==="audio"?"audio":"image",isExplicit:!0},defaultModels:{image:A.imageModelName||"gemini-3-pro-image-preview-vip",video:A.videoModelName||"veo3.1",audio:A.audioModelName||"suno_music"},defaultModelRefs:void 0,params:{count:(M=w.metadata)==null?void 0:M.count,size:(v=w.metadata)==null?void 0:v.size,duration:(g=w.metadata)==null?void 0:g.duration},selection:{texts:[],images:[],videos:[],graphics:[]},finalPrompt:((R=w.metadata)==null?void 0:R.prompt)||""},referenceImages:((T=w.context)==null?void 0:T.referenceImages)||[],textModel:A.textModelName},J=D(w,z);s.current(J);const P=e.current,N=o.current;_(w.generationType)&&N&&P&&$.updateWorkflow(P,N,J);const L=O.subscribeToWorkflow(w.id,async te=>{var V;await((V=f.current)==null?void 0:V.call(f,te,w,z))});y.current.push(L)}});return y.current.push(c),i(),()=>{y.current.forEach(h=>h.unsubscribe()),y.current=[]}},[]);const r=S.useCallback(async(c,h,p)=>{const m=e.current,I=o.current,W=_(h.generationType);switch(c.type){case"step":{n.updateStep(c.stepId,c.status,c.result,c.error,c.duration);const M=n.getWorkflow();if(M){const v=D(M,p);s.current(v),W&&I&&m&&$.updateWorkflow(m,I,v)}break}case"completed":{const M=n.getWorkflow();let v=!1;M&&M.steps.forEach(R=>{const T=R.result,w=T==null?void 0:T.taskId;w&&(v=!0),(R.status==="running"||R.status==="pending")&&!w&&n.updateStep(R.id,"completed")});const g=n.getWorkflow();if(g){const R=D(g,p);if(s.current(R),W&&I&&m){if($.updateWorkflow(m,I,R),g.steps.some(w=>w.status==="pending"||w.status==="running"))break;if(!v)setTimeout(()=>{$.removeWorkZone(m,I)},1500);else{const{workflowCompletionService:w}=await j(async()=>{const{workflowCompletionService:E}=await import("./startup-app-DxX-P1pm.js").then(A=>A.nW);return{workflowCompletionService:E}},__vite__mapDeps([0]),import.meta.url);g.steps.every(E=>{const A=E.result;return A!=null&&A.taskId?w.isPostProcessingCompleted(A.taskId):!0})&&setTimeout(()=>{$.removeWorkZone(m,I)},1500)}}}break}case"failed":{n.abortWorkflow();const M=n.getWorkflow();if(M){const v=D(M,p);s.current(v),W&&I&&m&&$.updateWorkflow(m,I,v)}break}case"steps_added":{const M=c;n.addSteps(M.steps.map(g=>({id:g.id,mcp:g.mcp,args:g.args,description:g.description,status:g.status})));const v=n.getWorkflow();if(v){const g=D(v,p);s.current(g),W&&I&&m&&$.updateWorkflow(m,I,g)}break}case"canvas_insert":{m&&qe(m,c);break}}},[n,e,o,_]);S.useEffect(()=>{f.current=r},[r]);const d=S.useCallback(async(c,h,p,m)=>{var R,T,w;const I=m||$e(c,h);n.startWorkflow(I);const W=se.get(),M=W.textModelName,v=p||{aiContext:{rawInput:c.rawInput||c.userInstruction,userInstruction:c.userInstruction,model:{id:c.modelId,type:c.generationType,isExplicit:c.isModelExplicit},modelRef:c.modelRef,defaultModels:{image:((R=c.defaultModels)==null?void 0:R.image)||W.imageModelName||"gemini-3-pro-image-preview-vip",video:((T=c.defaultModels)==null?void 0:T.video)||W.videoModelName||"veo3.1",audio:((w=c.defaultModels)==null?void 0:w.audio)||W.audioModelName||"suno_music"},defaultModelRefs:c.defaultModelRefs,params:{count:c.count,size:c.size,duration:c.duration},selection:c.selection||{texts:[],images:[],videos:[],graphics:[]},finalPrompt:c.prompt,knowledgeContextRefs:c.knowledgeContextRefs},referenceImages:h,textModel:M};x.current=v;const g=D(I,v);return await l.current({context:v.aiContext,workflow:g,textModel:M,autoOpen:!1}),{workflowId:I.id,usedSW:!1}},[n]),k=S.useCallback(async c=>{await O.cancel(c),n.abortWorkflow()},[n]),C=S.useCallback(async(c,h)=>{const p=c.retryContext;if(!p){console.error("[useWorkflowSubmission] No retry context available");return}const m={prompt:c.prompt,userInstruction:p.aiContext.userInstruction,rawInput:p.aiContext.rawInput,modelId:p.aiContext.model.id,modelRef:p.aiContext.modelRef,defaultModels:p.aiContext.defaultModels,defaultModelRefs:p.aiContext.defaultModelRefs,isModelExplicit:p.aiContext.model.isExplicit,generationType:p.aiContext.model.type,count:c.count||1,size:p.aiContext.params.size,duration:p.aiContext.params.duration,scenario:p.aiContext.model.type==="agent"?"agent_flow":"direct_generation",selection:p.aiContext.selection,parseResult:{},hasExtraContent:!1};await d(m,p.referenceImages||[],p)},[d]),b=S.useCallback(()=>x.current,[]);return{submitWorkflow:d,cancelWorkflow:k,retryWorkflow:C,getRetryContext:b}}const nt=Object.freeze(Object.defineProperty({__proto__:null,toWorkflowMessageData:D,useWorkflowSubmission:Ke,workflowRecoveryPromise:Be},Symbol.toStringTag,{value:"Module"}));export{ot as W,Ke as a,$e as b,tt as c,nt as d,Le as u};
|
|
44
|
+
你必须实际调用 generate_image 工具生成图片,不要仅输出文字描述。`);const Z=[{role:"system",content:L},{role:"user",content:W}],pe=[{id:`${h}-step-analyze`,mcp:"ai_analyze",args:{context:R,messages:Z,referenceImages:g.length>0?g:void 0,textModel:s,modelRef:l,knowledgeContextRefs:c.length>0?c:void 0},options:{mode:"async"},description:`AI 以「${m}」角色回复`,status:"pending"}];return{id:h,name:m,description:`使用「${m}」Skill 生成内容`,scenarioType:"skill_flow",skillId:p,generationType:a,steps:pe,metadata:{prompt:y,userInstruction:u,rawInput:f,modelId:s,modelRef:l,defaultModels:k,defaultModelRefs:C,isModelExplicit:x,count:_,size:i,duration:r,referenceImages:o.length>0?o:void 0,selection:d,knowledgeContextRefs:c.length>0?c:void 0,parseMethod:"agent_fallback"},createdAt:Date.now()}}function $e(t,e=[]){return t.scenario==="direct_generation"?Ce(t,e):Ae(t,e)}function Pe(t,e=0){try{let o=oe(t);if(!o){const l=Se(t),s=l.indexOf("{"),x=l.lastIndexOf("}");s>=0&&x>s&&(o=oe(l.slice(s,x+1)))}if(!o)return{content:"",steps:[]};const n=typeof o.content=="string"?o.content:"";if(!Array.isArray(o.next)||o.next.length===0)return{content:n,steps:[]};const a=o.next.filter(l=>typeof l.mcp=="string"&&typeof l.args=="object").map((l,s)=>({id:`step-${e+s+1}`,mcp:l.mcp,args:l.args,description:De(l.mcp,l.args),status:"pending"}));return{content:n,steps:a}}catch{return{content:"",steps:[]}}}function De(t,e){var o,n,a,l;switch(t){case"generate_image":return`生成图片: ${((o=e.prompt)==null?void 0:o.substring(0,30))||""}...`;case"generate_video":return`生成视频: ${((n=e.prompt)==null?void 0:n.substring(0,30))||""}...`;case"generate_audio":return`生成音频: ${((a=e.prompt)==null?void 0:a.substring(0,30))||""}...`;case"generate_text":return`生成文本: ${((l=e.prompt)==null?void 0:l.substring(0,30))||""}...`;case"ai_analyze":return"AI 分析用户意图";case"format_markdown":return"格式化输出";case"show_result":return"展示结果";default:return`执行 ${t}`}}function ze(t,e,o,n,a,l){return{...t,steps:t.steps.map(s=>s.id===e?{...s,status:o,result:n!==void 0?n:s.result,error:a,duration:l}:s)}}function Oe(t,e){const o=new Set(t.steps.map(a=>a.id)),n=e.filter(a=>!o.has(a.id));return n.length===0?t:{...t,steps:[...t.steps,...n]}}function B(t){const e=t.steps.filter(s=>s.status==="completed").length,o=t.steps.filter(s=>s.status==="failed").length,n=t.steps.find(s=>s.status==="running"),a=t.steps.filter(s=>s.status==="pending").length;let l;return o>0?l="failed":n?l="running":a===0&&e>0?l="completed":l="pending",{status:l,completedSteps:e,totalSteps:t.steps.length,currentStep:n||t.steps.find(s=>s.status==="pending")}}const ae={workflow:null,status:"idle",currentStep:null,completedSteps:0,totalSteps:0,error:null};function Fe(){const[t,e]=S.useState(ae),o=S.useRef(null),n=S.useRef(!1),a=S.useCallback(r=>{o.current=r,n.current=!1;const d=B(r);e({workflow:r,status:"running",currentStep:d.currentStep||null,completedSteps:d.completedSteps,totalSteps:d.totalSteps,error:null})},[]),l=S.useCallback(r=>{o.current=r,n.current=!1;const d=B(r);let k="running";r.status==="completed"?k="completed":(r.status==="failed"||r.status==="cancelled")&&(k="failed"),e({workflow:r,status:k,currentStep:d.currentStep||null,completedSteps:d.completedSteps,totalSteps:d.totalSteps,error:r.error||null})},[]),s=S.useCallback((r,d,k,C,b)=>{if(n.current)return;const c=o.current;if(!c)return;const h=ze(c,r,d,k,C,b);o.current=h,e(p=>{const m=B(h);let I="running";return m.status==="completed"?I="completed":m.status==="failed"&&(I="failed"),{...p,workflow:h,status:I,currentStep:m.currentStep||null,completedSteps:m.completedSteps,totalSteps:m.totalSteps,error:C||p.error}})},[]),x=S.useCallback(r=>{if(n.current||r.length===0)return;const d=o.current;if(!d)return;const k=Oe(d,r);o.current=k,e(C=>{const b=B(k);return{...C,workflow:k,currentStep:b.currentStep||C.currentStep,totalSteps:b.totalSteps}})},[]),y=S.useCallback(r=>{const d=o.current;if(!d||n.current)return{content:"",steps:[]};const k=d.steps.length,{content:C,steps:b}=Pe(r,k);return C&&!d.aiAnalysis&&(o.current={...d,aiAnalysis:C}),b.length>0&&x(b),{content:C,steps:b}},[x]),u=S.useCallback(()=>{o.current=null,n.current=!1,e(ae)},[]),f=S.useCallback(()=>{n.current=!0,e(r=>({...r,status:"failed",error:"工作流已中止"}))},[]),_=S.useCallback(()=>{n.current=!1,e(r=>({...r,status:"running",error:null}))},[]),i=S.useCallback(()=>o.current,[]);return{state:t,startWorkflow:a,restoreWorkflow:l,updateStep:s,addSteps:x,addStepsFromAIResponse:y,resetWorkflow:u,abortWorkflow:f,resumeWorkflow:_,getWorkflow:i}}const ue=S.createContext(null),ot=({children:t})=>{const e=Fe(),o=S.useMemo(()=>({state:e.state,startWorkflow:e.startWorkflow,restoreWorkflow:e.restoreWorkflow,updateStep:e.updateStep,addSteps:e.addSteps,addStepsFromAIResponse:e.addStepsFromAIResponse,resetWorkflow:e.resetWorkflow,abortWorkflow:e.abortWorkflow,resumeWorkflow:e.resumeWorkflow,getWorkflow:e.getWorkflow}),[e.state,e.startWorkflow,e.restoreWorkflow,e.updateStep,e.addSteps,e.addStepsFromAIResponse,e.resetWorkflow,e.abortWorkflow,e.resumeWorkflow,e.getWorkflow]);return We.jsx(ue.Provider,{value:o,children:t})};function Ne(){const t=S.useContext(ue);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function Le(){const t=Ne();return{startWorkflow:t.startWorkflow,restoreWorkflow:t.restoreWorkflow,updateStep:t.updateStep,addSteps:t.addSteps,addStepsFromAIResponse:t.addStepsFromAIResponse,resetWorkflow:t.resetWorkflow,abortWorkflow:t.abortWorkflow,resumeWorkflow:t.resumeWorkflow,getWorkflow:t.getWorkflow}}function D(t,e,o,n){var l;const a=t.metadata||{};return{id:t.id,name:t.name,generationType:t.generationType,prompt:a.prompt||((l=e==null?void 0:e.aiContext)==null?void 0:l.finalPrompt)||"",aiAnalysis:t.aiAnalysis,count:a.count,createdAt:t.createdAt,steps:t.steps.map(s=>({id:s.id,description:s.description,status:s.status,mcp:s.mcp,args:s.args,result:s.result,error:s.error,duration:s.duration,options:s.options})),retryContext:e,postProcessingStatus:o,insertedCount:n}}const Ue=20,ie=2e3,je=3e4;function de(t){const e=new Map;if(!t)return e;for(const o of t){const n=o.result;n!=null&&n.taskId&&e.set(n.taskId,o.id)}return e}function fe(t){var e;return t.status===G.PROCESSING?{status:"running"}:t.status===G.COMPLETED&&t.result?{status:"completed",result:{...t.result,taskId:t.id}}:t.status===G.FAILED?{status:"failed",error:typeof t.error=="string"?t.error:((e=t.error)==null?void 0:e.message)||"Task failed"}:null}function Ve(t,e,o,n,a,l){const s=o.getWorkflow(),y=de(s==null?void 0:s.steps).get(t.id);if(!y)return!1;const u=t.type!==le.IMAGE&&(s==null?void 0:s.generationType)!=="image";e.status==="running"&&o.resumeWorkflow(),o.updateStep(y,e.status,e.result,e.error);const f=o.getWorkflow();if(f){const _=D(f);n.current(_);const i=a.current,r=l.current;u&&i&&r&&$.updateWorkflow(i,r,_)}return!0}function Ze(t,e,o,n,a,l){var x;const s=a.current;if(!s||t.type===le.IMAGE)return!1;for(const y of s.children){if(!he(y))continue;const u=y;if(u.workflow.generationType==="image")continue;const _=de((x=u.workflow)==null?void 0:x.steps).get(t.id);if(!_)continue;const i=u.workflow.steps.map(d=>d.id!==_?d:{...d,status:e.status,...e.result!==void 0&&{result:e.result},...e.error!==void 0&&{error:e.error}}),r={...u.workflow,steps:i};if(e.status==="running"&&delete r.error,$.updateWorkflow(s,u.id,r),l.current=u.id,n.current(r),o.restoreWorkflow){const d={id:r.id,name:r.name||"",description:"",scenarioType:"direct_generation",generationType:r.generationType,status:e.status==="running"?"running":"failed",steps:i.map(k=>({id:k.id,mcp:k.mcp||"",args:k.args||{},description:k.description||"",status:k.status,result:k.result,error:k.error,duration:k.duration,options:k.options})),createdAt:r.createdAt||Date.now(),metadata:{prompt:r.prompt||"",userInstruction:"",rawInput:"",modelId:"",isModelExplicit:!1,count:r.count||1,selection:{texts:[],images:[],videos:[],graphics:[]}},aiAnalysis:r.aiAnalysis};o.restoreWorkflow(d)}return!0}return!1}function J(t,e,o,n,a){const l=t.task,s=fe(l);return s?!!(Ve(l,s,e,o,n,a)||Ze(l,s,e,o,n,a)):!1}function Be(t){const{workflowControl:e,boardRef:o,workZoneIdRef:n}=t,a=S.useRef(t.updateWorkflowMessage);S.useEffect(()=>{a.current=t.updateWorkflowMessage},[t.updateWorkflowMessage]);const l=S.useRef(new Map),s=S.useRef(null),x=S.useRef(0),y=S.useRef(!1);S.useEffect(()=>{const u=i=>{const r=l.current;if(!r.has(i.task.id)&&r.size>=Ue){const d=r.keys().next().value;d&&r.delete(d)}r.set(i.task.id,i)},f=()=>{const i=new Map;for(const[r,d]of l.current.entries())J(d,e,a,o,n)||i.set(r,d);l.current=i,(i.size===0||Date.now()-x.current>je)&&(s.current&&(clearInterval(s.current),s.current=null),l.current=new Map)};if(!y.current){y.current=!0;const i=ne.getAllTasks();for(const r of i){const d=fe(r);d&&(d.status==="completed"||d.status==="failed")&&J({task:r},e,a,o,n)}}const _=ne.observeTaskUpdates().subscribe(i=>{if(i.type!=="taskUpdated")return;if(i.task.status===G.PROCESSING&&l.current.has(i.task.id)){u(i),s.current||(x.current=Date.now(),s.current=setInterval(f,ie));return}J(i,e,a,o,n)?l.current.delete(i.task.id):(u(i),s.current||(x.current=Date.now(),s.current=setInterval(f,ie)))});return()=>{_.unsubscribe(),s.current&&(clearInterval(s.current),s.current=null),l.current=new Map}},[e,o,n])}let q=null;const Ge=new Promise(t=>{q=t});async function qe(t,e){const{operation:o,params:n}=e;try{const{insertImageFromUrl:a}=await j(async()=>{const{insertImageFromUrl:u}=await import("./startup-app-eD_rQhSh.js").then(f=>f.nV);return{insertImageFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{insertVideoFromUrl:l}=await j(async()=>{const{insertVideoFromUrl:u}=await import("./startup-app-eD_rQhSh.js").then(f=>f.nW);return{insertVideoFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{insertAudioFromUrl:s}=await j(async()=>{const{insertAudioFromUrl:u}=await import("./startup-app-eD_rQhSh.js").then(f=>f.nX);return{insertAudioFromUrl:u}},__vite__mapDeps([0]),import.meta.url),{getSmartInsertionPoint:x}=await j(async()=>{const{getSmartInsertionPoint:u}=await import("./startup-app-eD_rQhSh.js").then(f=>f.nU);return{getSmartInsertionPoint:u}},__vite__mapDeps([0]),import.meta.url),y=n.position?[n.position.x,n.position.y]:x(t)||[100,100];if(o==="canvas_insert"&&n.items)for(const u of n.items)u.type==="image"&&u.url?await a(t,u.url,y):u.type==="video"&&u.url?await l(t,u.url,y):u.type==="audio"&&u.url&&await s(t,u.url,u,y);else o==="insert_image"&&n.url?await a(t,n.url,y):o==="insert_video"&&n.url?await l(t,n.url,y):o==="insert_audio"&&n.url&&await s(t,n.url,n,y)}catch(a){console.error("[useWorkflowSubmission] Failed to insert to canvas:",a)}}function Ke(t){const{boardRef:e,workZoneIdRef:o}=t,n=Le(),a=xe(),l=S.useRef(a.sendWorkflowMessage),s=S.useRef(a.updateWorkflowMessage);S.useEffect(()=>{l.current=a.sendWorkflowMessage,s.current=a.updateWorkflowMessage},[a.sendWorkflowMessage,a.updateWorkflowMessage]),Be({workflowControl:n,updateWorkflowMessage:a.updateWorkflowMessage,boardRef:e,workZoneIdRef:o});const x=S.useRef(null),y=S.useRef([]),u=S.useRef(!1),f=S.useRef(null),_=S.useCallback(c=>c!=="image",[]),i=S.useCallback(async()=>{if(!u.current){u.current=!0;try{await F.recoverWorkflows()}catch(c){console.warn("[useWorkflowSubmission] Failed to recover workflows:",c)}finally{q==null||q()}}},[]);S.useEffect(()=>{F.init(),F.registerCanvasHandler(async(h,p)=>({success:!0}));const c=F.subscribeToAllEvents(h=>{var p,m,I,W,v,M,g,R,T;if(h.type==="recovered"&&h.workflow){const w=h.workflow,H=w.status==="running"||w.status==="pending",E=w.status==="failed"&&w.updatedAt&&Date.now()-w.updatedAt<300*1e3;if(!H&&!E)return;(p=n.restoreWorkflow)==null||p.call(n,w);const A=se.get(),z={aiContext:{rawInput:((m=w.context)==null?void 0:m.userInput)||"",userInstruction:((I=w.context)==null?void 0:I.userInput)||"",model:{id:((W=w.context)==null?void 0:W.model)||"",type:w.generationType==="video"?"video":w.generationType==="audio"?"audio":"image",isExplicit:!0},defaultModels:{image:A.imageModelName||"gemini-3-pro-image-preview-vip",video:A.videoModelName||"veo3.1",audio:A.audioModelName||"suno_music"},defaultModelRefs:void 0,params:{count:(v=w.metadata)==null?void 0:v.count,size:(M=w.metadata)==null?void 0:M.size,duration:(g=w.metadata)==null?void 0:g.duration},selection:{texts:[],images:[],videos:[],graphics:[]},finalPrompt:((R=w.metadata)==null?void 0:R.prompt)||""},referenceImages:((T=w.context)==null?void 0:T.referenceImages)||[],textModel:A.textModelName},X=D(w,z);s.current(X);const P=e.current,N=o.current;_(w.generationType)&&N&&P&&$.updateWorkflow(P,N,X);const L=F.subscribeToWorkflow(w.id,async te=>{var Z;await((Z=f.current)==null?void 0:Z.call(f,te,w,z))});y.current.push(L)}});return y.current.push(c),i(),()=>{y.current.forEach(h=>h.unsubscribe()),y.current=[]}},[]);const r=S.useCallback(async(c,h,p)=>{const m=e.current,I=o.current,W=_(h.generationType);switch(c.type){case"step":{n.updateStep(c.stepId,c.status,c.result,c.error,c.duration);const v=n.getWorkflow();if(v){const M=D(v,p);s.current(M),W&&I&&m&&$.updateWorkflow(m,I,M)}break}case"completed":{const v=n.getWorkflow();let M=!1;v&&v.steps.forEach(R=>{const T=R.result,w=T==null?void 0:T.taskId;w&&(M=!0),(R.status==="running"||R.status==="pending")&&!w&&n.updateStep(R.id,"completed")});const g=n.getWorkflow();if(g){const R=D(g,p);if(s.current(R),W&&I&&m){if($.updateWorkflow(m,I,R),g.steps.some(w=>w.status==="pending"||w.status==="running"))break;if(!M)setTimeout(()=>{$.removeWorkZone(m,I)},1500);else{const{workflowCompletionService:w}=await j(async()=>{const{workflowCompletionService:E}=await import("./startup-app-eD_rQhSh.js").then(A=>A.o2);return{workflowCompletionService:E}},__vite__mapDeps([0]),import.meta.url);g.steps.every(E=>{const A=E.result;return A!=null&&A.taskId?w.isPostProcessingCompleted(A.taskId):!0})&&setTimeout(()=>{$.removeWorkZone(m,I)},1500)}}}break}case"failed":{n.abortWorkflow();const v=n.getWorkflow();if(v){const M=D(v,p);s.current(M),W&&I&&m&&$.updateWorkflow(m,I,M)}break}case"steps_added":{const v=c;n.addSteps(v.steps.map(g=>({id:g.id,mcp:g.mcp,args:g.args,description:g.description,status:g.status})));const M=n.getWorkflow();if(M){const g=D(M,p);s.current(g),W&&I&&m&&$.updateWorkflow(m,I,g)}break}case"canvas_insert":{m&&qe(m,c);break}}},[n,e,o,_]);S.useEffect(()=>{f.current=r},[r]);const d=S.useCallback(async(c,h,p,m)=>{var R,T,w;const I=m||$e(c,h);n.startWorkflow(I);const W=se.get(),v=W.textModelName,M=p||{aiContext:{rawInput:c.rawInput||c.userInstruction,userInstruction:c.userInstruction,model:{id:c.modelId,type:c.generationType,isExplicit:c.isModelExplicit},modelRef:c.modelRef,defaultModels:{image:((R=c.defaultModels)==null?void 0:R.image)||W.imageModelName||"gemini-3-pro-image-preview-vip",video:((T=c.defaultModels)==null?void 0:T.video)||W.videoModelName||"veo3.1",audio:((w=c.defaultModels)==null?void 0:w.audio)||W.audioModelName||"suno_music"},defaultModelRefs:c.defaultModelRefs,params:{count:c.count,size:c.size,duration:c.duration},selection:c.selection||{texts:[],images:[],videos:[],graphics:[]},finalPrompt:c.prompt,knowledgeContextRefs:c.knowledgeContextRefs},referenceImages:h,textModel:v};x.current=M;const g=D(I,M);return await l.current({context:M.aiContext,workflow:g,textModel:v,autoOpen:!1}),{workflowId:I.id,usedSW:!1}},[n]),k=S.useCallback(async c=>{await F.cancel(c),n.abortWorkflow()},[n]),C=S.useCallback(async(c,h)=>{const p=c.retryContext;if(!p){console.error("[useWorkflowSubmission] No retry context available");return}const m={prompt:c.prompt,userInstruction:p.aiContext.userInstruction,rawInput:p.aiContext.rawInput,modelId:p.aiContext.model.id,modelRef:p.aiContext.modelRef,defaultModels:p.aiContext.defaultModels,defaultModelRefs:p.aiContext.defaultModelRefs,isModelExplicit:p.aiContext.model.isExplicit,generationType:p.aiContext.model.type,count:c.count||1,size:p.aiContext.params.size,duration:p.aiContext.params.duration,scenario:p.aiContext.model.type==="agent"?"agent_flow":"direct_generation",selection:p.aiContext.selection,parseResult:{},hasExtraContent:!1};await d(m,p.referenceImages||[],p)},[d]),b=S.useCallback(()=>x.current,[]);return{submitWorkflow:d,cancelWorkflow:k,retryWorkflow:C,getRetryContext:b}}const nt=Object.freeze(Object.defineProperty({__proto__:null,toWorkflowMessageData:D,useWorkflowSubmission:Ke,workflowRecoveryPromise:Ge},Symbol.toStringTag,{value:"Module"}));export{ot as W,Ke as a,$e as b,tt as c,nt as d,Le as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e0 as u,bx as v}from"./startup-app-
|
|
1
|
+
import{e0 as u,bx as v}from"./startup-app-eD_rQhSh.js";import"./startup-runtime-DTmhLESk.js";async function h(e){if(!e||!e.children)return 0;let n=0;for(const c of e.children){const r=c.url;if(r&&r.startsWith("blob:")&&r.includes("#merged-video-")){const s=r.indexOf("#merged-video-");if(s===-1)continue;const i=r.substring(s+1),d=i.indexOf("#",1),o=d>0?i.substring(0,d):i;try{const t=await u.getCachedBlob(o);if(t){const a=URL.createObjectURL(t),f=`${a}#${o}`,l=e.children.indexOf(c);if(l===-1){URL.revokeObjectURL(a);continue}v.setNode(e,{url:f},[l]),n++}else console.warn("[VideoRecovery] Cache not found for taskId:",o)}catch(t){console.error("[VideoRecovery] Failed to recover video:",o,t)}}}return n}function y(e){e&&requestAnimationFrame(async()=>{try{await h(e)}catch(n){console.error("[VideoRecovery] Initialization failed:",n)}})}export{y as initVideoRecoveryService,h as recoverExpiredVideoUrls};
|
package/assets/{workflow-generation-utils-JoRODaP7.js → workflow-generation-utils-DhIVnOHO.js}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./startup-app-CKHrOmQ0.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{e0 as k,
|
|
3
|
-
`)}function
|
|
2
|
+
import{e0 as k,hd as z,n7 as V}from"./startup-app-eD_rQhSh.js";import{_ as b}from"./startup-runtime-DTmhLESk.js";async function j(e,t,n){if(e.size===0)throw new Error("Invalid frame blob: size is 0");const a=`/__aitu_cache__/video-frame_${t}_${n}`;return await k.cacheMediaFromBlob(a,e,"image",{metadata:{source:"video-frame",shotId:t,frameType:n}}),a}async function ee(e,t,n){const a=URL.createObjectURL(e),s=document.createElement("video");s.muted=!0,s.preload="auto";try{await new Promise((d,p)=>{s.onloadedmetadata=()=>d(),s.onerror=()=>p(new Error("Failed to load video")),s.src=a});const i=document.createElement("canvas"),u=i.getContext("2d"),o=Math.min(1,320/s.videoWidth);i.width=Math.round(s.videoWidth*o),i.height=Math.round(s.videoHeight*o);const l=[];for(let d=0;d<t.length;d++){n==null||n(d,t.length);try{const p=await S(s,i,u,t[d]);l.push(p)}catch{l.push(null)}}return n==null||n(t.length,t.length),l}finally{URL.revokeObjectURL(a),s.src=""}}async function te(e,t,n,a){const s=a||n,i=document.createElement("video");i.muted=!0,i.preload="auto",i.crossOrigin="anonymous";try{await new Promise((E,I)=>{i.onloadedmetadata=()=>E(),i.onerror=()=>I(new Error("Failed to load video")),i.src=e});const u=document.createElement("canvas"),c=u.getContext("2d"),l=Math.min(1,1280/i.videoWidth);u.width=Math.round(i.videoWidth*l),u.height=Math.round(i.videoHeight*l);const d=s==="first"?Math.min(.1,i.duration):Math.max(0,i.duration-.1),p=await S(i,u,c,d);return await j(p,t,n)}catch{return null}finally{i.src=""}}function S(e,t,n,a){return new Promise((s,i)=>{const u=Math.min(Math.max(0,a),e.duration||0);e.currentTime=u;const c=()=>{e.removeEventListener("seeked",c),n.drawImage(e,0,0,t.width,t.height),t.toBlob(o=>{o&&o.size>0?s(o):i(new Error("toBlob returned empty"))},"image/jpeg",.85)};e.addEventListener("seeked",c)})}const P=/(?:^|[^\d])(?:400|401|402|403|404|413|415|422)(?:[^\d]|$)/,X=[/invalid\s*(?:request|parameters?|argument|input|field|payload|schema)/i,/bad\s*request/i,/unprocessable/i,/unsupported\s*(?:model|parameter|size|duration|resolution|format|input|image|media)?/i,/(?:missing|required)\s*(?:parameter|field|argument|input|prompt|model|duration|size)/i,/requires?\s+(?:a\s+)?(?:reference\s+image|input|image)/i,/(?:must|should)\s+be/i,/no\s+(?:task\s+)?id\s+returned|no\s+video\s+url/i,/\b(?:invalid_argument|invalid_parameter|parameter_invalid|validation_error|bad_request|unsupported_model)\b/i,/参数(?:错误|无效|非法|不正确|校验失败|验证失败)/,/请求(?:参数|数据).*?(?:无效|错误|非法|不支持)/,/缺少(?:必填|必要|参数|字段)/,/必须(?:是|为)|仅支持/,/不支持(?:的)?(?:参数|模型|尺寸|时长|分辨率|格式|图片|视频)/,/未返回(?:任务\s*)?ID|未返回有效的视频 URL/,/(?:校验|验证)失败|格式错误|字段错误/,/内容(?:政策|审核|安全)|安全策略|违规|敏感内容|policy|safety/i,/(?:ip|intellectual\s+property|copyright|trademark)\s*(?:infringement|violation)|涉嫌(?:知识产权|版权|商标|IP)(?:侵权|违规)|知识产权侵权/i];function q(e,t){var n,a;return[(n=e==null?void 0:e.error)==null?void 0:n.code,(a=e==null?void 0:e.error)==null?void 0:a.message,t].filter(s=>typeof s=="string"&&s.trim()!=="").join(" ")}function re(e,t){var s,i;const n=q(e,t);return!n||!(P.test(n)||X.some(u=>u.test(n)))?null:((s=e==null?void 0:e.error)==null?void 0:s.message)||t||((i=e==null?void 0:e.error)==null?void 0:i.code)||"不可重试的视频生成错误"}function ne(e){const{model:t,firstFrameUrl:n,lastFrameUrl:a,extraReferenceUrls:s=[],characterReferenceUrls:i=[]}=e,u=V(t),c=[],o=[],l=(d,p)=>{!d||c.includes(d)||(c.push(d),o.push(p))};if(u.imageUpload.mode==="frames"){l(n,"首帧图:只表示视频起始画面状态,视频必须从这张图开始,优先于故事上下文。"),l(a,"尾帧图:只表示视频结束画面状态,视频应自然过渡到这张图,优先于故事上下文。");const d=c.length>0?c.slice(0,u.imageUpload.maxCount):void 0,p=d?o.slice(0,d.length):void 0,E=i.length>0?i:void 0;return{referenceImages:d,referenceImageDescriptions:p,unusedCharacterReferenceUrls:E}}for(const d of i)if(l(d,"角色参考图:仅用于锁定人物身份、脸型、发型、服装、材质和气质,不表示时间顺序、动作或剧情。"),c.length>=u.imageUpload.maxCount)break;l(n,"首帧图:只表示视频起始画面状态,视频必须从这张图开始,优先于故事上下文。");for(const d of s)if(l(d,"全局/补充参考图:仅用于主体、产品、场景、风格或色彩一致性,不表示时间顺序、动作或剧情。"),c.length>=u.imageUpload.maxCount)break;return{referenceImages:c.length>0?c:void 0,referenceImageDescriptions:o.length>0?o:void 0}}async function ie(e,t){return z(e,{interval:1e3,timeout:1800*1e3,signal:t})}function J(e){return Math.max(2,String(Math.max(e,0)).length)}function M(e,t){return String(e).padStart(t,"0")}function R(e,t,n){const a=M(e+1,n);return t==="first"?`${a}.首帧`:t==="last"?`${a}.尾帧`:`${a}.视频`}function Y(e){return["#!/bin/sh","set -eu","",'cd "$(dirname "$0")"',"",`MANIFEST_FILE=${JSON.stringify(e)}`,"",'if [ ! -f "$MANIFEST_FILE" ]; then',' echo "未找到 $MANIFEST_FILE"'," exit 1","fi","","download_if_missing() {",' file_name="$1"',' source_url="$2"',' if [ -s "$file_name" ]; then',' echo "[skip] $file_name"'," return 0"," fi",' echo "[download] $file_name"',' curl -L --fail --retry 3 --retry-delay 1 --output "$file_name.part" "$source_url"',' mv "$file_name.part" "$file_name"',"}","","emit_entries() {"," if command -v node >/dev/null 2>&1; then",` node -e 'const fs=require("fs"); const manifest=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); for (const entry of manifest.downloadEntries||[]) { if (entry?.fileName && entry?.url) process.stdout.write(String(entry.fileName)+"\\t"+String(entry.url)+"\\n"); }' "$MANIFEST_FILE"`," return 0"," fi",""," if command -v python3 >/dev/null 2>&1; then",` python3 - "$MANIFEST_FILE" <<'PY'`,"import json, sys","with open(sys.argv[1], 'r', encoding='utf-8') as fh:"," manifest = json.load(fh)","for entry in manifest.get('downloadEntries', []):"," file_name = entry.get('fileName')"," url = entry.get('url')"," if file_name and url:",' print(f"{file_name}\\t{url}")',"PY"," return 0"," fi","",' echo "需要 node 或 python3 来解析 $MANIFEST_FILE" >&2'," return 1","}","",'TMP_ENTRIES_FILE="$(mktemp -t workflow-download-entries.XXXXXX)"',`trap 'rm -f "$TMP_ENTRIES_FILE"' EXIT INT TERM`,"",'emit_entries > "$TMP_ENTRIES_FILE"',"","while IFS=' ' read -r file_name source_url; do",' [ -n "${file_name:-}" ] || continue',' [ -n "${source_url:-}" ] || continue',' download_if_missing "$file_name" "$source_url"','done < "$TMP_ENTRIES_FILE"',"",'echo "下载完成"',""].join(`
|
|
3
|
+
`)}function Z(e){return e.map(t=>({...t,generated_first_frame_url:void 0,generated_last_frame_url:void 0,generated_video_url:void 0,suppressed_generated_urls:G(t)}))}function G(e){const t={...e.suppressed_generated_urls||{}};return e.generated_first_frame_url&&(t.first=e.generated_first_frame_url),e.generated_last_frame_url&&(t.last=e.generated_last_frame_url),e.generated_video_url&&(t.video=e.generated_video_url),Object.keys(t).length>0?t:void 0}function H(e){return e.map(t=>({...t,referenceImageUrl:void 0}))}function oe(e,t){return{shots:Z(e),characters:H(t)}}function ae(e){return e.flatMap((t,n)=>{const a=[];return t.generated_first_frame_url&&a.push({url:t.generated_first_frame_url,type:"image",kind:"first",shotIndex:n}),t.generated_last_frame_url&&a.push({url:t.generated_last_frame_url,type:"image",kind:"last",shotIndex:n}),t.generated_video_url&&a.push({url:t.generated_video_url,type:"video",kind:"video",shotIndex:n}),a})}async function le(e){const{recordId:t,fileNamePrefix:n,zipBaseName:a,scriptMarkdown:s,recordMeta:i,shots:u,assets:c,audioAsset:o,onProgress:l}=e,d=new Date().toISOString(),p=J(u.length),E=M(0,p),{default:I}=await b(async()=>{const{default:r}=await import("./office-data-ByisqnCq.js").then(f=>f.j);return{default:r}},[],import.meta.url),{downloadFromBlob:L,getFileExtension:F,normalizeImageDataUrl:U,processBatchWithConcurrency:W}=await b(async()=>{const{downloadFromBlob:r,getFileExtension:f,normalizeImageDataUrl:_,processBatchWithConcurrency:h}=await import("./startup-app-eD_rQhSh.js").then(g=>g.nO);return{downloadFromBlob:r,getFileExtension:f,normalizeImageDataUrl:_,processBatchWithConcurrency:h}},__vite__mapDeps([0]),import.meta.url),{unifiedCacheService:A}=await b(async()=>{const{unifiedCacheService:r}=await import("./startup-app-eD_rQhSh.js").then(f=>f.nQ);return{unifiedCacheService:r}},__vite__mapDeps([0]),import.meta.url),N=async r=>{const f=await A.getCachedBlob(r);if(!f)throw new Error("未找到可用缓存,且网络下载失败");return f},w=new I,m={exportedAt:d,record:i,files:{script:`${E}.脚本.md`,music:null,manifest:`${E}.manifest.json`,downloadScript:`${E}.补全下载.sh`},shots:u.map((r,f)=>({index:f+1,id:r.id,label:r.label||`镜头 ${f+1}`,startTime:r.startTime,endTime:r.endTime,files:{first:null,last:null,video:null}})),errors:[],downloadEntries:[]};if(w.file(m.files.script,s),l==null||l(c.length>0||o?8:40),o!=null&&o.url){const r=o.plannedFileName||`${E}.音乐.mp3`;m.downloadEntries.push({fileName:r,url:o.url});try{const f=await N(o.url),_=F(o.url,f.type),h=_!=="bin"?_:o.fallbackExtension||"mp3",g=r.replace(/\.[^.]+$/,`.${h}`);w.file(g,f),m.files.music=g,g!==r&&(m.downloadEntries[m.downloadEntries.length-1].fileName=g)}catch(f){m.files.music=r,m.errors.push(o.downloadErrorMessage||"音乐下载失败"),console.error("[workflow-export] Failed to export audio asset:",o.url,f)}}else o!=null&&o.missingErrorMessage&&m.errors.push(o.missingErrorMessage);await W(c,async(r,f)=>{const _=r.type==="image"?U(r.url):r.url,h=m.shots[r.shotIndex],g=r.type==="image"?"png":"mp4",$=`${R(r.shotIndex,r.kind,p)}.${g}`;m.downloadEntries.push({fileName:$,url:_});try{const v=await N(_),y=F(_,v.type),D=y!=="bin"?y:g,x=`${R(r.shotIndex,r.kind,p)}.${D}`;w.file(x,v),h.files[r.kind]=x,x!==$&&(m.downloadEntries[m.downloadEntries.length-1].fileName=x)}catch(v){const y=(h==null?void 0:h.label)||`镜头 ${r.shotIndex+1}`;m.errors.push(`${y} ${r.kind} 下载失败`),h.files[r.kind]=$,console.error("[workflow-export] Failed to export asset:",_,v)}finally{const v=f+1,y=c.length>0?Math.round(v/c.length*62):62;l==null||l(8+y)}},3),w.file(m.files.downloadScript,Y(m.files.manifest),{unixPermissions:493}),w.file(m.files.manifest,JSON.stringify(m,null,2));const B=await w.generateAsync({type:"blob"},r=>l==null?void 0:l(70+Math.round(r.percent*.3))),O=t.replace(/[^a-zA-Z0-9_-]/g,""),C=d.slice(0,19).replace(/[:T]/g,"-"),T=`${a}_${O||n}_${C}.zip`;return L(B,T),l==null||l(100),{assetCount:c.length,zipFileName:T}}export{ae as a,te as b,j as c,ne as d,ee as e,le as f,re as g,oe as r,ie as w};
|