@mevdragon/vidfarm-devcli 0.11.0 → 0.13.0

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.
@@ -42,7 +42,7 @@ ${r}`:r}var cF=48;function uF(e){return e.scrollHeight-e.scrollTop-e.clientHeigh
42
42
  `):null}function RF(e){let t=e.length-1;return e.map((n,r)=>{let o=CF(n.attachments);return{role:n.role,content:[...n.text?[{type:"text",text:n.text}]:[],...o?[{type:"text",text:o}]:[],...n.attachments.map(i=>({type:"file",data:r===t&&i.transportData||i.viewUrl,mediaType:i.contentType}))]}})}function xF(){let t=window.__vidfarmFlockPosterCache?.readSnapshot?.();if(!t)return{};let n=Array.isArray(t?.channels)?t.channels.map(r=>r&&typeof r=="object"?r:null).filter(r=>typeof r?.id=="string"&&!!r.id.trim()).map(r=>({id:String(r?.id||""),name:typeof r?.name=="string"?r.name:null,title:typeof r?.title=="string"?r.title:null,handle:typeof r?.handle=="string"?r.handle:null,platform:typeof r?.platform=="string"?r.platform:null,status:typeof r?.status=="string"?r.status:null})):[];return n.length||t?.channelsUpdatedAt?{scheduleChannels:n,scheduleChannelsUpdatedAt:t?.channelsUpdatedAt??null}:{}}function bF(){let e=window.__vidfarmLibrarySelection?.readSelectedPosts?.();return{selectedPosts:Array.isArray(e?.posts)?e.posts.map(n=>n&&typeof n=="object"?n:null).filter(n=>typeof n?.post_id=="string"&&!!n.post_id.trim()).map(n=>({post_id:String(n?.post_id||""),title:typeof n?.title=="string"?n.title:null,caption:typeof n?.caption=="string"?n.caption:null,tracer:typeof n?.tracer=="string"?n.tracer:null,status:typeof n?.status=="string"?n.status:null,share_url:typeof n?.share_url=="string"?n.share_url:null,media:Array.isArray(n?.media)?n.media.slice(0,8).map(r=>r&&typeof r=="object"?r:null).filter(Boolean).map(r=>({url:typeof r?.url=="string"?r.url:null,kind:typeof r?.kind=="string"?r.kind:null,role:typeof r?.role=="string"?r.role:null,content_type:typeof r?.content_type=="string"?r.content_type:null})):[]})):[],selectedPostsUpdatedAt:e?.updatedAt??null}}async function kF(e,t){if(!e.body)throw new Error("Chat response did not include a body.");let n=e.body.getReader(),r=new TextDecoder,o="";for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
43
43
 
44
44
  `);o=a.pop()??"";for(let l of a){let c=l.split(`
45
- `).map(h=>h.trim()).find(h=>h.startsWith("data:"));if(!c)continue;let u=c.slice(5).trim();if(u==="[DONE]")continue;let d;try{d=JSON.parse(u)}catch{continue}if(!d||typeof d!="object")continue;let p=d;if(p.type==="text-delta"&&typeof p.delta=="string")t.onDelta(p.delta);else if(p.type==="status"){let h=typeof p.status=="string"?p.status:typeof p.message=="string"?p.message:null;h&&t.onStatus&&t.onStatus(h)}else p.type==="tool-call"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolCall?t.onToolCall({toolCallId:p.toolCallId,toolName:p.toolName,args:p.args&&typeof p.args=="object"?p.args:void 0}):p.type==="tool-result"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolResult?t.onToolResult({toolCallId:p.toolCallId,toolName:p.toolName,result:p.result}):p.type==="error"&&t.onError&&t.onError?.(typeof p.errorText=="string"?p.errorText:typeof p.error?.message=="string"?p.error.message:"Unable to read assistant response.")}}}function NF(e){return{threads:`vidfarm-editor-chat-threads:${e}`,activeThread:`vidfarm-editor-chat-active-thread:${e}`}}function AF(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{try{return window.localStorage}catch{return null}}}function vR(){return`thread-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Bf(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function tr(e){let t=new Set,n=[];for(let r of e){let o=r.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}function sS(...e){return tr(e.flat())}function MF(e){let t=e.trim();return!t||t.startsWith("archived_")?t:`archived_${t}`}function uS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,"").slice(-8):Math.random().toString(16).slice(2,10).padEnd(8,"0").slice(0,8)}function PF(e){return(e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tracer").slice(0,28)}function LF(e,t){let n=PF(e),r="";do r=`${n}-${uS()}`;while(t.includes(r));return r}function OF(e,t){let n=e.trim();if(!n)return"";if(/-[a-z0-9]{8}$/i.test(n))return n;let r=`${n}-${uS()}`;for(;t.includes(r);)r=`${n}-${uS()}`;return r}function Hf(){let e=new URLSearchParams(window.location.search),t=[...e.getAll("tracers"),...e.getAll("tracer")],n=[];for(let r of t){let o=r.trim();if(!o)continue;let i=o.startsWith("[")&&o.endsWith("]")?o.slice(1,-1):o;n.push(...i.split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")))}return tr(n)}function ER(){let e=new URLSearchParams(window.location.search);return(e.get("thread_id")||e.get("threadId")||e.get("chat_id")||e.get("chatId")||"").trim()}function Of(e){let t=e.trim().replace(/\s+/g," ");return t?t.length>42?`${t.slice(0,42).trimEnd()}\u2026`:t:"New chat"}function TR(e,t){return e.map(n=>({id:n.id,templateId:n.templateId,title:n.title,createdAt:n.createdAt,updatedAt:n.updatedAt,lastMessageAt:n.lastMessageAt??null,messageCount:Math.max(n.messageCount??0,n.messages.length),tracers:n.tracers,hiddenFromView:n.hiddenFromView,messages:(n.id===t?n.messages.slice(-QU):[]).map(r=>({id:r.id,role:r.role,text:r.text,attachments:r.attachments.map(o=>({id:o.id,fileName:o.fileName,contentType:o.contentType,viewUrl:o.viewUrl})),toolExchanges:r.toolExchanges?.map(o=>({...o,args:zi(o.args),result:OR(o.result)})),httpExchanges:r.httpExchanges?.map(Ic)}))}))}function DF(e,t){if(!e)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.id=="string").map(r=>({id:r.id,templateId:typeof r.templateId=="string"&&r.templateId.trim()?r.templateId:t,title:typeof r.title=="string"&&r.title.trim()?r.title:"New chat",createdAt:typeof r.createdAt=="string"?r.createdAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:new Date().toISOString(),lastMessageAt:typeof r.lastMessageAt=="string"?r.lastMessageAt:null,messageCount:Math.max(typeof r.messageCount=="number"?r.messageCount:0,Array.isArray(r.messages)?r.messages.length:0),tracers:tr(Array.isArray(r.tracers)?r.tracers.filter(o=>typeof o=="string"):[]),hiddenFromView:r.hiddenFromView===!0,messages:Array.isArray(r.messages)?r.messages.map(o=>({id:o.id,role:o.role,text:o.text,attachments:Array.isArray(o.attachments)?o.attachments:[],toolExchanges:Array.isArray(o.toolExchanges)?o.toolExchanges:[],httpExchanges:Array.isArray(o.httpExchanges)?o.httpExchanges:[]})):[]})):[]}catch{return[]}}function IR(e,t){return!e||typeof e.id!="string"?null:{id:e.id,templateId:typeof e.templateId=="string"&&e.templateId.trim()?e.templateId:t,title:typeof e.title=="string"&&e.title.trim()?e.title:"New chat",createdAt:typeof e.createdAt=="string"?e.createdAt:new Date().toISOString(),updatedAt:typeof e.updatedAt=="string"?e.updatedAt:new Date().toISOString(),lastMessageAt:typeof e.lastMessageAt=="string"?e.lastMessageAt:null,messageCount:Math.max(typeof e.messageCount=="number"?e.messageCount:0,Array.isArray(e.messages)?e.messages.length:0),tracers:tr(Array.isArray(e.tracers)?e.tracers.filter(n=>typeof n=="string"):[]),hiddenFromView:e.hiddenFromView===!0,messages:Array.isArray(e.messages)?e.messages.map(n=>({id:n.id,role:n.role,text:n.text,attachments:Array.isArray(n.attachments)?n.attachments:[],toolExchanges:Array.isArray(n.toolExchanges)?n.toolExchanges:[],httpExchanges:Array.isArray(n.httpExchanges)?n.httpExchanges:[]})):[]}}function wR(e,t){let n=new Map;for(let r of t){let o=e.find(i=>i.id===r.id);n.set(r.id,{...r,lastMessageAt:r.lastMessageAt??o?.lastMessageAt??null,messageCount:Math.max(r.messageCount??0,o?.messageCount??0,r.messages.length,o?.messages.length??0),messages:r.messages.length?r.messages:o?.messages??[]})}for(let r of e)n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((r,o)=>Date.parse(o.updatedAt)-Date.parse(r.updatedAt))}function UF(e){return[...e].sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function Tc(e,t){return t.length?e.tracers.some(n=>t.some(r=>FF(n,r))):!0}function FF(e,t){let n=e.trim(),r=t.trim();return!n||!r?!1:n===r?!0:n.startsWith(`${r}-`)&&/-[a-z0-9]{8}$/i.test(n)}function BF(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-attachment",children:[(0,f.jsx)("span",{className:"vf-editor-chat-attachment-name",children:e.attachment.fileName}),e.onRemove?(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-attachment-remove","aria-label":"Remove attachment",onClick:e.onRemove,children:"\xD7"}):null]})}function hS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M10 3v9"}),(0,f.jsx)("path",{d:"m6.5 8.5 3.5 3.5 3.5-3.5"}),(0,f.jsx)("path",{d:"M4 16h12"})]})}function HF(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M4.2 15.8c1.6.5 3.1-.1 3.7-1.7.6-1.4 1.8-2.1 3.5-2.1"}),(0,f.jsx)("path",{d:"m10.7 11.6 5.2-5.2a1.9 1.9 0 0 0-2.7-2.7L8 8.9"}),(0,f.jsx)("path",{d:"m7.9 9 3.1 3.1"}),(0,f.jsx)("path",{d:"M3.5 16.5c1.4.5 3.6.5 4.9-.8"})]})}function gS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M8.4 11.6a3.2 3.2 0 0 0 4.5 0l2.2-2.2a3.2 3.2 0 0 0-4.5-4.5L9.4 6.1"}),(0,f.jsx)("path",{d:"M11.6 8.4a3.2 3.2 0 0 0-4.5 0L4.9 10.6a3.2 3.2 0 0 0 4.5 4.5l1.2-1.2"})]})}function yS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("rect",{x:"7",y:"7",width:"9",height:"9",rx:"2"}),(0,f.jsx)("path",{d:"M5 12H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1"})]})}function Df(e){return(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transform:e.open?"rotate(90deg)":"rotate(0deg)"},children:(0,f.jsx)("path",{d:"m7 4 6 6-6 6"})})}function VR(e){let t=e.label.trim().replace(/[\\/:*?"<>|]+/g,"-");if(t)return t;try{return new URL(e.url,window.location.href).pathname.split("/").filter(Boolean).pop()||"media"}catch{return"media"}}function CR(e,t=!1){if(typeof window>"u"||e.kind!=="image"||!e.url)return"";let n=new URL("/inpaint",window.location.origin),r=window.__vidfarmEditorTracers,i=(r?.get()??Hf())[0]||(t?r?.add()??"":"");return i&&n.searchParams.set("tracer",i),n.searchParams.set("source_image_url",e.url),n.searchParams.set("source_image_name",e.label||VR(e)),n.toString()}function $F(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),{onClose:i}=e,s=e.gallery?.length?e.gallery:[e.preview],a=Math.max(0,s.findIndex(T=>T.url===e.preview.url)),[l,c]=(0,k.useState)(a),u=s[l]||e.preview,d=s.length>1,p=u.kind==="image",h=p&&CR(u,!1)||"/inpaint";(0,k.useEffect)(()=>{n(!0)},[]),(0,k.useEffect)(()=>{o("")},[u.url]);let y=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(u.url);else{let T=document.createElement("textarea");T.value=u.url,T.style.position="fixed",T.style.opacity="0",document.body.appendChild(T),T.focus(),T.select(),document.execCommand("copy"),document.body.removeChild(T)}o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)},_=T=>{let g=CR(u,!0);if(!g){T.preventDefault();return}T.preventDefault(),window.open(g,"_blank","noopener,noreferrer")};return(0,k.useEffect)(()=>{let T=g=>{if(g.key==="Escape"){i();return}d&&(g.key==="ArrowLeft"?(g.preventDefault(),c(S=>(S-1+s.length)%s.length)):g.key==="ArrowRight"&&(g.preventDefault(),c(S=>(S+1)%s.length)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[d,s.length,i]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal",onClick:T=>T.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:u.url,target:"_blank",rel:"noopener noreferrer",children:d?`${u.label} (${l+1} of ${s.length})`:u.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[d?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T-1+s.length)%s.length),"aria-label":"Previous image",title:"Previous image",children:"\u2039"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T+1)%s.length),"aria-label":"Next image",title:"Next image",children:"\u203A"})]}):null,p?(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:h,target:"_blank",rel:"noopener noreferrer",onClick:_,"aria-label":"Open image editor",title:"Image edit",children:(0,f.jsx)(HF,{})}):null,(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:u.url,download:VR(u),"aria-label":"Download media",title:"Download",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{y()},"aria-label":r==="done"?"Media URL copied":r==="error"?"Unable to copy media URL":"Copy media URL",title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy link",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close media preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-media-modal-body",children:u.kind==="image"?(0,f.jsx)("img",{src:u.url,alt:u.label,className:"vf-editor-chat-media-modal-image"}):(0,f.jsx)("video",{src:u.url,className:"vf-editor-chat-media-modal-video",controls:!0,autoPlay:!0,playsInline:!0})})]})}),document.body):null}function zF(e){let[t,n]=(0,k.useState)(!1);return(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-message-thumb-button is-image",onClick:()=>e.onOpenModal(e.preview,e.previews),"aria-label":`Preview ${e.preview.label}`,title:e.preview.label,"data-error":t?"true":"false",children:t?(0,f.jsx)("span",{className:"vf-editor-chat-message-thumb-fallback",children:"Preview unavailable"}):(0,f.jsx)("img",{src:e.preview.url,alt:e.preview.label,className:"vf-editor-chat-message-attachment-thumb",loading:"lazy",onError:()=>n(!0)})})}function RR(e){return(0,f.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-message-thumb-button",onClick:()=>e.onOpenModal(e.preview),"aria-label":`Preview ${e.preview.label}`,children:[(0,f.jsx)("video",{src:e.preview.url,className:"vf-editor-chat-message-attachment-thumb vf-editor-chat-message-video-thumb",preload:"metadata",muted:!0,playsInline:!0}),(0,f.jsx)("span",{className:"vf-editor-chat-message-video-play","aria-hidden":"true"})]})})}function xR(e){return e.previews.length?(0,f.jsx)("div",{className:"vf-editor-chat-message-image-rail","aria-label":"Image previews",children:e.previews.map(t=>(0,f.jsx)(zF,{preview:t,previews:e.previews,onOpenModal:e.onOpenModal},t.url))}):null}function jF(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-composer-attachment-item",children:[$f(e.attachment)?(0,f.jsx)("img",{src:e.attachment.viewUrl,alt:e.attachment.fileName,className:"vf-editor-chat-composer-attachment-thumb"}):(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachment-file","aria-hidden":"true",children:e.attachment.fileName.slice(0,1).toUpperCase()}),(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachment-meta",children:(0,f.jsx)("span",{className:"vf-editor-chat-composer-attachment-name",children:e.attachment.fileName})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-composer-attachment-remove","aria-label":`Remove ${e.attachment.fileName}`,onClick:e.onRemove,children:"\xD7"})]})}function WF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),i=Uf(e.exchange.request.body),s=Uf(e.exchange.result.body),a=e.exchange.request.url,l=a.length>52?`${a.slice(0,52).trimEnd()}...`:a,c=e.exchange.result.status>=400||!!e.exchange.result.error,u=e.exchange.result.status>=200&&e.exchange.result.status<300;return(0,k.useEffect)(()=>{o(!0)},[]),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-card",children:(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-http-card-header",onClick:()=>n(!0),"aria-label":`Open HTTP details for ${e.exchange.request.method} ${a}`,children:[(0,f.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,f.jsx)("span",{className:"vf-editor-chat-http-url",title:a,children:l}),(0,f.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]}),(0,f.jsx)("span",{className:"vf-editor-chat-http-expand","aria-hidden":"true",children:"+"})]})}),r&&t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-http-modal-backdrop",onClick:()=>n(!1),children:(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal",onClick:d=>d.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal-header-main",children:[(0,f.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,f.jsx)("span",{className:"vf-editor-chat-http-modal-url",children:a}),(0,f.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-http-modal-close",onClick:()=>n(!1),"aria-label":"Close HTTP details",children:"\xD7"})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-http-card-body is-modal",children:[e.exchange.explanation?(0,f.jsx)("div",{className:"vf-editor-chat-http-note",children:e.exchange.explanation}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"URL"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:a})]}),i?(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Request"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:i})]}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Response"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:e.exchange.result.error||s||"(empty)"})]}),Object.keys(e.exchange.result.headers).length?(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Headers"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:Uf(e.exchange.result.headers)})]}):null]})]})}),document.body):null]})}function bR(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function SS(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}function Or(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-json-line",style:{paddingLeft:`${e.depth*18+12}px`},children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-copy","aria-label":"Copy line",title:"Copy line",onClick:()=>e.onCopy(e.text),children:(0,f.jsx)(yS,{})}),(0,f.jsx)("span",{className:"vf-editor-chat-json-line-text",children:e.text})]})}function dS(e){let t=e.value,n=e.isLast?"":",";if(Array.isArray(t)){let r=e.path,o=e.collapsedPaths.has(r),i=`${e.linePrefix??""}[`;return t.length?o?(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Expand JSON block",children:(0,f.jsx)(Df,{open:!1})}),(0,f.jsx)(Or,{text:`${e.linePrefix??""}[ \u2026 ]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Collapse JSON block",children:(0,f.jsx)(Df,{open:!0})}),(0,f.jsx)(Or,{text:i,depth:e.depth,onCopy:e.onCopy})]}),t.map((s,a)=>(0,f.jsx)(dS,{value:s,depth:e.depth+1,path:`${r}.${a}`,isLast:a===t.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${r}:${a}`)),(0,f.jsx)(Or,{text:`]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsx)(Or,{text:`${e.linePrefix??""}[]${n}`,depth:e.depth,onCopy:e.onCopy})}if(t&&typeof t=="object"){let r=Object.entries(t),o=e.path,i=e.collapsedPaths.has(o),s=`${e.linePrefix??""}{`;return r.length?i?(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Expand JSON block",children:(0,f.jsx)(Df,{open:!1})}),(0,f.jsx)(Or,{text:`${e.linePrefix??""}{ \u2026 }${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Collapse JSON block",children:(0,f.jsx)(Df,{open:!0})}),(0,f.jsx)(Or,{text:s,depth:e.depth,onCopy:e.onCopy})]}),r.map(([a,l],c)=>{let u=`${JSON.stringify(a)}: `;return l&&typeof l=="object"?(0,f.jsx)(dS,{value:l,depth:e.depth+1,linePrefix:u,path:`${o}.${a}`,isLast:c===r.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${o}:${a}`):(0,f.jsx)(Or,{text:`${u}${bR(l)}${c===r.length-1?"":","}`,depth:e.depth+1,onCopy:e.onCopy},`${o}:${a}`)}),(0,f.jsx)(Or,{text:`}${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsx)(Or,{text:`${e.linePrefix??""}{}${n}`,depth:e.depth,onCopy:e.onCopy})}return(0,f.jsx)(Or,{text:`${e.linePrefix??""}${bR(t)}${n}`,depth:e.depth,onCopy:e.onCopy})}function qR(e){let[t,n]=(0,k.useState)(new Set),[r,o]=(0,k.useState)(""),i=a=>{n(l=>{let c=new Set(l);return c.has(a)?c.delete(a):c.add(a),c})},s=async a=>{try{await SS(a),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1400)};return(0,f.jsxs)("div",{className:"vf-editor-chat-json-viewer",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toolbar",children:[(0,f.jsx)("span",{className:"vf-editor-chat-json-file",children:e.storageKey}),(0,f.jsx)("span",{className:"vf-editor-chat-json-copy-state","data-state":r,children:r==="done"?"Copied line":r==="error"?"Copy failed":"Hover a line to copy"})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-scroll",children:(0,f.jsx)(dS,{value:e.value,depth:0,path:"root",collapsedPaths:t,togglePath:i,onCopy:s})})]})}function GF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=BR(e.artifact.url,`${e.artifact.label}.json`),s=Uf(e.data);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await SS(s),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy JSON","aria-label":r==="done"?"JSON copied":r==="error"?"Unable to copy JSON":"Copy JSON",children:(0,f.jsx)(yS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:i,title:"Download JSON","aria-label":"Download JSON",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw JSON","aria-label":"Open raw JSON",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close JSON preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,f.jsx)(qR,{value:e.data,storageKey:e.artifact.label})})]})}),document.body):null}function VF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),d=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).json();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load JSON artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&d()},h=()=>{d(),o(!0)};return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:"JSON result"}),(0,f.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview JSON"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,f.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,f.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading JSON\u2026"}):a?(0,f.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,f.jsx)(qR,{value:i,storageKey:e.artifact.label}):null}):null]}),r&&i!==null?(0,f.jsx)(GF,{artifact:e.artifact,data:i,onClose:()=>o(!1)}):null]})}function YR(e){return e.format==="markdown"?(0,f.jsx)("div",{className:"vf-editor-chat-doc-markdown",dangerouslySetInnerHTML:{__html:UR(e.text)}}):(0,f.jsx)("pre",{className:"vf-editor-chat-doc-pre",children:e.text})}function qF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=e.artifact.format==="markdown"?".md":".txt",s=BR(e.artifact.url,`${e.artifact.label}${i}`);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await SS(e.text),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":e.artifact.format==="markdown"?"Copy markdown":"Copy text","aria-label":r==="done"?"Document copied":r==="error"?"Unable to copy document":e.artifact.format==="markdown"?"Copy markdown":"Copy text",children:(0,f.jsx)(yS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:s,title:e.artifact.format==="markdown"?"Download markdown":"Download text","aria-label":e.artifact.format==="markdown"?"Download markdown":"Download text",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw file","aria-label":"Open raw file",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close document preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,f.jsx)("div",{className:"vf-editor-chat-doc-viewer",children:(0,f.jsx)(YR,{text:e.text,format:e.artifact.format})})})]})}),document.body):null}function YF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),d=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).text();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load document artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&d()},h=()=>{d(),o(!0)};return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:e.artifact.format==="markdown"?"Markdown result":"Text result"}),(0,f.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,f.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,f.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading document\u2026"}):a?(0,f.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,f.jsx)("div",{className:"vf-editor-chat-doc-viewer is-inline",children:(0,f.jsx)(YR,{text:i,format:e.artifact.format})}):null}):null]}),r&&i!==null?(0,f.jsx)(qF,{artifact:e.artifact,text:i,onClose:()=>o(!1)}):null]})}var KF=(0,k.memo)(function(t){let n=t.message.role==="assistant",r=t.message.text.trim().length>0,o=r?UR(t.message.text):"",[i,s]=(0,k.useState)(null),a=t.message.attachments.filter($f),l=t.message.attachments.filter(lS),c=t.message.attachments.filter(_=>!$f(_)&&!lS(_)),u=r?iF(t.message.text,t.message.attachments.map(_=>_.viewUrl)):[],d=u.filter(_=>_.kind==="image"),p=u.filter(_=>_.kind==="video"),h=(t.message.httpExchanges??[]).flatMap(_=>{let T=Hi(_.result.body);return T?$R(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T),y=(t.message.httpExchanges??[]).flatMap(_=>{let T=Hi(_.result.body);return T?zR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T);return(0,f.jsxs)("div",{className:`vf-editor-chat-message ${n?"is-assistant":"is-user"}`,children:[(0,f.jsx)("div",{className:"vf-editor-chat-message-meta",children:n?"Copilot":"You"}),(0,f.jsxs)("div",{className:"vf-editor-chat-bubble","data-pending":t.message.isPending?"true":"false",children:[t.message.attachments.length?(0,f.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[c.map(_=>(0,f.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,f.jsx)("a",{className:"vf-editor-chat-message-preview-link",href:_.viewUrl,target:"_blank",rel:"noopener noreferrer",children:(0,f.jsx)(BF,{attachment:_})})},_.id)),(0,f.jsx)(xR,{previews:a.map(_=>({kind:"image",url:_.viewUrl,label:_.fileName})),onOpenModal:(_,T)=>s({preview:_,gallery:T})}),l.map(_=>(0,f.jsx)(RR,{preview:{kind:"video",url:_.viewUrl,label:_.fileName},onOpenModal:T=>s({preview:T,gallery:[T]})},_.id))]}):null,t.message.statusText?(0,f.jsxs)("div",{className:"vf-editor-chat-message-status","aria-live":"polite",children:[(0,f.jsx)("span",{className:"vf-editor-chat-status-dot"}),t.message.statusText]}):null,t.message.httpExchanges?.length?(0,f.jsx)("div",{className:"vf-editor-chat-http-list",children:t.message.httpExchanges.map((_,T)=>(0,f.jsx)(WF,{exchange:_},`${_.request.method}:${_.request.url}:${T}`))}):null,r?(0,f.jsx)("div",{className:"vf-editor-chat-message-body",dangerouslySetInnerHTML:{__html:o}}):t.message.isPending?(0,f.jsxs)("div",{className:"vf-editor-chat-message-loading","aria-hidden":"true",children:[(0,f.jsx)("span",{}),(0,f.jsx)("span",{}),(0,f.jsx)("span",{})]}):null,u.length?(0,f.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[(0,f.jsx)(xR,{previews:d,onOpenModal:(_,T)=>s({preview:_,gallery:T})}),p.map(_=>(0,f.jsx)(RR,{preview:_,onOpenModal:T=>s({preview:T,gallery:[T]})},_.url))]}):null,h.length?(0,f.jsx)("div",{className:"vf-editor-chat-json-list",children:h.map(_=>(0,f.jsx)(VF,{artifact:_},_.key))}):null,y.length?(0,f.jsx)("div",{className:"vf-editor-chat-json-list",children:y.map(_=>(0,f.jsx)(YF,{artifact:_},_.key))}):null]}),i?(0,f.jsx)($F,{preview:i.preview,gallery:i.gallery,onClose:()=>s(null)}):null]})});function kR(e){if(!e||e<=0)return"Unknown size";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=10||r===0?n.toFixed(0):n.toFixed(1)} ${t[r]}`}function NR(e){return $f(e.file)?(0,f.jsx)("img",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,alt:e.file.fileName}):lS(e.file)?(0,f.jsx)("video",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,muted:!0,playsInline:!0}):(0,f.jsx)("div",{className:"vf-editor-upload-file-icon","aria-hidden":"true",children:e.file.fileName.slice(0,1).toUpperCase()})}function fo(e){return e.split("/").map(t=>t.trim()).filter(Boolean).join("/")}function jf(e,t){return fo([e,t].filter(Boolean).join("/"))}function AR(e){let t=fo(e).split("/").filter(Boolean);return t.pop(),t.join("/")}function MR(e){return fo(e).split("/").filter(Boolean).at(-1)||"All files"}function JF(e){let t=fo(e.currentFolder),n=t?`${t}/`:"",r=new Map;for(let o of e.folders){let i=fo(o);if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,jf(t,a))}for(let o of e.files){let i=fo(o.folderPath??"");if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,jf(t,a))}return Array.from(r.entries()).map(([o,i])=>({name:o,path:i})).sort((o,i)=>o.name.localeCompare(i.name))}function aS(e){return e.name==="share"?(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M14 4h6v6"}),(0,f.jsx)("path",{d:"M10 14 20 4"}),(0,f.jsx)("path",{d:"M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4"})]}):e.name==="link"?(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L11 4.93"}),(0,f.jsx)("path",{d:"M14 11a5 5 0 0 0-7.07 0L4.81 13.12a5 5 0 0 0 7.07 7.07L13 19.07"})]}):(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M3 6h18"}),(0,f.jsx)("path",{d:"M8 6V4h8v2"}),(0,f.jsx)("path",{d:"M19 6 18 20H6L5 6"}),(0,f.jsx)("path",{d:"M10 11v5"}),(0,f.jsx)("path",{d:"M14 11v5"})]})}function XF(e){let[t,n]=(0,k.useState)("my-files"),[r,o]=(0,k.useState)([]),[i,s]=(0,k.useState)([]),[a,l]=(0,k.useState)([]),[c,u]=(0,k.useState)(()=>new Set),[d,p]=(0,k.useState)([]),[h,y]=(0,k.useState)([]),[_,T]=(0,k.useState)(()=>new Set),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(!1),[M,A]=(0,k.useState)(""),[I,N]=(0,k.useState)(null),[U,x]=(0,k.useState)(null),[$,W]=(0,k.useState)(null),[ye,K]=(0,k.useState)(null),[et,pe]=(0,k.useState)(null),fe=(0,k.useRef)(null),D=(0,k.useRef)(null),Se=(0,k.useMemo)(()=>{let P=d.map(ne=>({...ne,recentSource:"generated"}));return[...h.map(ne=>({...ne,recentSource:"temporary"})),...P].sort((ne,ae)=>{let we=ne.createdAt?Date.parse(ne.createdAt):0;return(ae.createdAt?Date.parse(ae.createdAt):0)-we})},[d,h]),J=t==="upload"?r:t==="my-files"?i.filter(P=>c.has(P.id)):t==="recents"?Se.filter(P=>_.has(P.id)):[];async function le(){let P=await vF(e.apiKey);s(P.attachments),l(P.folders)}async function Ie(P){R(!0);try{let[F,ne]=P?[await _R(e.apiKey,P),null]:await Promise.all([_R(e.apiKey),EF(e.apiKey)]);p(ae=>P?[...ae,...F.media]:F.media),ne&&y(ne.files),S(F.nextCursor),P||T(new Set)}finally{R(!1)}}(0,k.useEffect)(()=>{e.open&&(K(null),W(null),le().catch(P=>K(P instanceof Error?P.message:"Unable to load My Files.")),Ie().catch(P=>K(P instanceof Error?P.message:"Unable to load recent media.")))},[e.open]);function _e(){o([]),u(new Set),T(new Set),W(null),K(null),N(null),x(null),e.onClose()}async function ut(P){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(P);else{let F=document.createElement("textarea");F.value=P,F.style.position="fixed",F.style.opacity="0",document.body.appendChild(F),F.focus(),F.select(),document.execCommand("copy"),document.body.removeChild(F)}W("File URL copied.")}catch{K("Unable to copy file URL.")}}async function Xe(P,F){if(!P.length)return;K(null);let ne=[];for(let ae of P)try{if(W(`Uploading ${ae.name}...`),F==="upload"){let St=await GR({apiKey:e.apiKey,file:ae,folderPath:LR}),Z=await WR({attachment:St,file:ae,currentInlineBytes:jR([...r,...ne])});ne.push(Z);continue}let we=await _F({apiKey:e.apiKey,file:ae,folderPath:M,maxBytes:PR,limitLabel:"50 MB"});ne.push(we)}catch(we){K(we instanceof Error?we.message:"Upload failed.")}F==="upload"?(o(ae=>[...ae,...ne]),await Ie().catch(ae=>K(ae instanceof Error?ae.message:"Unable to refresh recent files."))):F==="my-files"&&(await le(),u(ae=>new Set([...ae,...ne.map(we=>we.id)]))),ne.length&&W(`${ne.length} file${ne.length===1?"":"s"} uploaded.`)}async function Yt(P,F){let ne=F==="my-files"?`/api/v1/user/me/attachments/${encodeURIComponent(P.id)}`:`/api/v1/user/me/temporary-files/${encodeURIComponent(P.id)}`,ae=await fetch(ne,{method:"DELETE",headers:ct(e.apiKey,"application/json")}),we=await ae.json().catch(()=>({}));if(!ae.ok)throw new Error(we.error||"Unable to delete file.");F==="my-files"&&(s(St=>St.filter(Z=>Z.id!==P.id)),u(St=>{let Z=new Set(St);return Z.delete(P.id),Z})),pe(null),W("File deleted.")}async function dt(P){if(P!=="my-files"||!U||U.mode!=="create")return;let F=jf(U.baseFolder,U.value);if(!F){K("Choose a folder name.");return}let ne=await fetch("/api/v1/user/me/attachments/folders",{method:"POST",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({folder_path:F})}),ae=await ne.json().catch(()=>({}));if(!ne.ok){K(ae.error||"Unable to create folder.");return}l(we=>Array.from(new Set([...we,F])).sort()),x(null),W("Folder created.")}async function an(P,F){if(P!=="my-files"||!U||U.mode!=="rename")return;let ne=U.value.trim(),ae=jf(AR(F),ne);if(!ae||ae===F)return;let we=await fetch("/api/v1/user/me/attachments/folders",{method:"PATCH",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({from_folder_path:F,to_folder_path:ae})}),St=await we.json().catch(()=>({}));if(!we.ok){K(St.error||"Unable to rename folder.");return}A(Z=>Z===F||Z.startsWith(`${F}/`)?`${ae}${Z.slice(F.length)}`:Z),await le(),N(null),x(null),W("Folder renamed.")}async function Tn(P,F){if(P!=="my-files")return;let ne=await fetch("/api/v1/user/me/attachments/folders",{method:"DELETE",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({folder_path:F})}),ae=await ne.json().catch(()=>({}));if(!ne.ok){K(ae.error||"Unable to delete folder.");return}A(we=>we===F||we.startsWith(`${F}/`)?AR(F):we),await le(),N(null),x(null),W("Folder deleted.")}function On(P){let F=a,ne=i,ae=M,we=A,St=JF({folders:F,files:ne,currentFolder:ae}),Z=fo(ae).split("/").filter(Boolean);return(0,f.jsxs)("div",{className:"vf-editor-upload-browser",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-browser-toolbar",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-breadcrumb","aria-label":"Current folder",children:[(0,f.jsx)("button",{type:"button","data-current":!ae,onClick:()=>we(""),children:"files"}),Z.map((Fe,me)=>{let Ve=Z.slice(0,me+1).join("/");return(0,f.jsxs)("span",{className:"vf-editor-upload-breadcrumb-segment",children:[(0,f.jsx)("span",{"aria-hidden":"true",children:"/"}),(0,f.jsx)("button",{type:"button","data-current":Ve===ae,onClick:()=>we(Ve),children:Fe})]},Ve)})]}),(0,f.jsx)("button",{type:"button",onClick:()=>x({mode:"create",scope:"my-files",baseFolder:ae,value:""}),children:"New folder"})]}),St.length?(0,f.jsx)("div",{className:"vf-editor-upload-folder-grid",children:St.map(Fe=>(0,f.jsxs)("article",{className:"vf-editor-upload-folder-row",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-folder-open",onClick:()=>we(Fe.path),children:[(0,f.jsx)("span",{className:"vf-editor-upload-folder-icon","aria-hidden":"true"}),(0,f.jsx)("span",{children:Fe.name})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-folder-menu-button","aria-label":`Folder actions for ${Fe.name}`,onClick:()=>N(I===Fe.path?null:Fe.path),children:"..."}),I===Fe.path?(0,f.jsxs)("div",{className:"vf-editor-upload-folder-menu",children:[(0,f.jsx)("button",{type:"button",onClick:()=>x({mode:"rename",scope:"my-files",folderPath:Fe.path,value:MR(Fe.path)}),children:"Rename"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>x({mode:"delete",scope:"my-files",folderPath:Fe.path,value:""}),children:"Delete"})]}):null]},Fe.path))}):null]})}function po(P,F){let ne=F==="my-files"?c.has(P.id):F==="recents"?_.has(P.id):!1,ae="s3Url"in P&&P.s3Url?P.s3Url:P.viewUrl;return(0,f.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":ne?"true":"false",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-file-select",onClick:()=>{if(F==="temporary"){ut(ae);return}(F==="recents"?T:u)(St=>{let Z=new Set(St);return Z.has(P.id)?Z.delete(P.id):Z.add(P.id),Z})},children:[(0,f.jsx)(NR,{file:P}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,f.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-meta",children:[kR(P.sizeBytes),P.folderPath?` \xB7 ${P.folderPath}`:""]})]})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-file-actions",children:[F==="my-files"||F==="recents"?(0,f.jsx)("span",{className:"vf-editor-upload-selection-indicator","data-selected":ne?"true":"false","aria-hidden":"true",children:ne?"\u2713":""}):null,(0,f.jsx)("a",{href:P.viewUrl,target:"_blank",rel:"noreferrer","aria-label":`View ${P.fileName}`,children:(0,f.jsx)(aS,{name:"share"})}),(0,f.jsx)("button",{type:"button","aria-label":`Copy URL for ${P.fileName}`,onClick:()=>{ut(ae)},children:(0,f.jsx)(aS,{name:"link"})}),F==="recents"?null:(0,f.jsx)("button",{type:"button","aria-label":`Delete ${P.fileName}`,onClick:()=>pe(et===P.id?null:P.id),children:(0,f.jsx)(aS,{name:"trash"})})]}),F!=="recents"&&et===P.id?(0,f.jsxs)("div",{className:"vf-editor-upload-popconfirm",children:[(0,f.jsx)("span",{children:"Delete this file?"}),(0,f.jsx)("button",{type:"button",onClick:()=>pe(null),children:"Cancel"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Yt(P,F)},children:"Delete"})]}):null]},P.id)}function mo(){if(!U)return null;let P=U.mode==="create"?"New folder":U.mode==="rename"?"Rename folder":"Delete folder",F=U.mode==="delete"?U.folderPath:"";return(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog",role:"dialog","aria-label":P,children:[(0,f.jsx)("div",{className:"vf-editor-upload-folder-dialog-title",children:P}),U.mode==="delete"?(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog-copy",children:["Delete ",(0,f.jsx)("strong",{children:F})," and all files inside it?"]}):(0,f.jsx)("input",{value:U.value,autoFocus:!0,placeholder:"folder-name",onChange:ne=>x({...U,value:ne.target.value}),onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),U.mode==="create"?dt(U.scope):an(U.scope,U.folderPath))}}),(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog-actions",children:[(0,f.jsx)("button",{type:"button",onClick:()=>x(null),children:"Cancel"}),U.mode==="create"?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{dt(U.scope)},children:"Create"}):U.mode==="rename"?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{an(U.scope,U.folderPath)},children:"Rename"}):(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Tn(U.scope,U.folderPath)},children:"Delete"})]})]})}if(!e.open)return null;let Gi=i.filter(P=>fo(P.folderPath??"")===fo(M));return(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-upload-drawer-backdrop",children:(0,f.jsxs)("aside",{className:"vf-editor-upload-drawer","aria-label":"Upload drawer",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-header",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-upload-title",children:"Upload"}),(0,f.jsx)("div",{className:"vf-editor-upload-subtitle",children:"Upload, attach, and copy file URLs."})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-close","aria-label":"Close upload drawer",onClick:_e,children:"\xD7"})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-tabs",role:"tablist",children:[(0,f.jsx)("button",{type:"button","data-active":t==="upload",onClick:()=>n("upload"),children:"Upload file"}),(0,f.jsx)("button",{type:"button","data-active":t==="my-files",onClick:()=>n("my-files"),children:"My Files"}),(0,f.jsx)("button",{type:"button","data-active":t==="recents",onClick:()=>n("recents"),children:"Recents"})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-body",children:[ye?(0,f.jsx)("div",{className:"vf-editor-upload-status","data-tone":"error",children:ye}):null,$?(0,f.jsx)("div",{className:"vf-editor-upload-status",children:$}):null,mo(),t==="upload"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>fe.current?.click(),children:["Upload files to chat",(0,f.jsx)("span",{children:"Stored in Recents and attached after Confirm. Images get compressed inline previews when possible; other files attach by URL. Max 100 MB each."})]}),(0,f.jsx)("input",{ref:fe,type:"file",multiple:!0,hidden:!0,onChange:P=>{Xe(Array.from(P.target.files??[]),"upload"),P.target.value=""}}),(0,f.jsx)("div",{className:"vf-editor-upload-list",children:r.map(P=>(0,f.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":"true",children:[(0,f.jsx)(NR,{file:P}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,f.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,f.jsx)("span",{className:"vf-editor-upload-file-meta",children:kR(P.sizeBytes)})]}),(0,f.jsx)("button",{type:"button",onClick:()=>o(F=>F.filter(ne=>ne.id!==P.id)),children:"\xD7"})]},P.id))})]}):t==="my-files"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>D.current?.click(),children:["Add to My Files",(0,f.jsxs)("span",{children:["Uploads into ",MR(M)," and auto-selects. Max 50 MB each."]})]}),(0,f.jsx)("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:P=>{Xe(Array.from(P.target.files??[]),"my-files"),P.target.value=""}}),On("my-files"),(0,f.jsx)("div",{className:"vf-editor-upload-list",children:Gi.length?Gi.map(P=>po(P,"my-files")):(0,f.jsx)("div",{className:"vf-editor-upload-empty",children:"No files in this folder."})})]}):t==="recents"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"vf-editor-upload-list",children:Se.length?Se.map(P=>po(P,"recents")):(0,f.jsx)("div",{className:"vf-editor-upload-empty",children:E?"Loading recent files...":"No recent files yet."})}),g?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-more",disabled:E,onClick:()=>{Ie(g).catch(P=>K(P instanceof Error?P.message:"Unable to load more recent media."))},children:E?"Loading...":"Load more generated media"}):null]}):null]}),(0,f.jsxs)("div",{className:"vf-editor-upload-footer",children:[(0,f.jsx)("button",{type:"button",onClick:_e,children:"Cancel"}),(0,f.jsxs)("div",{className:"vf-editor-upload-footer-confirm",children:[(0,f.jsxs)("span",{children:[J.length," file",J.length===1?"":"s"," selected"]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",disabled:!J.length,onClick:()=>{e.onConfirm(J),_e()},children:"Confirm"})]})]})]})}),document.body)}function KR({boot:e}){let t=e.template.templateId==="chat-brainstorm",n=t&&e.template.persistentHistorySidebar===!0,r=(0,k.useMemo)(()=>NF(e.template.templateId),[e.template.templateId]),o=(0,k.useMemo)(()=>AF(),[]),i=(0,k.useRef)(null),s=(0,k.useRef)(null),a=(0,k.useRef)(!0),l=(0,k.useRef)(!1),c=(0,k.useRef)(null),u=(0,k.useRef)(null),d=(0,k.useRef)(new Map),p=(0,k.useRef)({nextAvailableAt:0}),h=(0,k.useRef)([]),y=(0,k.useRef)(new Set),[_,T]=(0,k.useState)([]),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(null),[M,A]=(0,k.useState)(null),[I,N]=(0,k.useState)(""),[U,x]=(0,k.useState)([]),[$,W]=(0,k.useState)(null),[ye,K]=(0,k.useState)(null),[et,pe]=(0,k.useState)(null),[fe,D]=(0,k.useState)(!1),[Se,J]=(0,k.useState)(!1),[le,Ie]=(0,k.useState)(!1),[_e,ut]=(0,k.useState)(!1),[Xe,Yt]=(0,k.useState)(!1),[dt,an]=(0,k.useState)(null),[Tn,On]=(0,k.useState)(!1),[po,mo]=(0,k.useState)(null),[Gi,P]=(0,k.useState)(!1),[F,ne]=(0,k.useState)(()=>{let m=typeof window<"u"?window.__vidfarmEditorTracers:null;if(m)return m.get();if(typeof window<"u"){let v=Hf();if(v.length)return v}return tr(e.template.tracers||[])}),ae=(0,k.useMemo)(()=>{if(!e.threadsUrl)return null;let m=new URL(e.threadsUrl,window.location.origin);return t||m.searchParams.set("template_id",e.template.templateId),m.searchParams.set("include_messages","false"),m.searchParams.set("limit",t?"200":"50"),m.toString()},[e.template.templateId,e.threadsUrl,t]),we=m=>e.threadsUrl?new URL(`${e.threadsUrl.replace(/\/$/,"")}/${encodeURIComponent(m)}`,window.location.origin).toString():null;(0,k.useEffect)(()=>{let m=DF(o?.getItem(r.threads)??null,e.template.templateId),v=o?.getItem(r.activeThread)??null,w=ER(),b=window.__vidfarmEditorTracers?.get()??Hf(),B=w&&!m.some(ce=>ce.id===w)?[{id:w,templateId:e.template.templateId,title:"Loading chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastMessageAt:null,messageCount:0,tracers:b,hiddenFromView:!1,messages:[]},...m]:m,Y=B.filter(ce=>!ce.hiddenFromView),j=Y.find(ce=>Tc(ce,b));h.current=B,T(B),w&&Y.some(ce=>ce.id===w)?S(w):v&&Y.some(ce=>ce.id===v)&&(!b.length||Y.some(ce=>ce.id===v&&Tc(ce,b)))?S(v):S(j?.id??Y[0]?.id??null),D(!0)},[e.template.templateId,o,r]),(0,k.useEffect)(()=>{if(!e.vidfarmApiKey||!ae)return;let m=new AbortController;return(async()=>{try{let v=[],w=null,b=new Set;do{let B=new URL(ae);w&&B.searchParams.set("cursor",w);let Y=await fetch(B.toString(),{method:"GET",headers:ct(e.vidfarmApiKey),signal:m.signal});if(!Y.ok)return;let j=await Y.json().catch(()=>null);Array.isArray(j?.threads)&&v.push(...j.threads.map(he=>IR(he,e.template.templateId)).filter(he=>!!he));let ce=typeof j?.next_cursor=="string"&&j.next_cursor?j.next_cursor:null;!ce||b.has(ce)?w=null:(b.add(ce),w=ce)}while(w&&!m.signal.aborted);if(!v.length)return;T(B=>{let Y=wR(B,v);return h.current=Y,Y}),S(B=>B&&h.current.some(Y=>Y.id===B)?B:v[0]?.id??B)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")return}})(),()=>{m.abort()}},[e.template.templateId,e.vidfarmApiKey,ae]),(0,k.useEffect)(()=>{h.current=_},[_]);let[St,Z]=(0,k.useState)(()=>{if(typeof window>"u")return null;try{return new URL(window.location.href).searchParams.get("fork")}catch{return null}});(0,k.useEffect)(()=>{let m=()=>{try{Z(new URL(window.location.href).searchParams.get("fork"))}catch{Z(null)}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[]);async function Fe(m){if(!e.vidfarmApiKey){mo("Sign in to see forks.");return}if(!Tn&&!(!m?.force&&dt!==null)){On(!0),mo(null);try{let v=await fetch("/api/v1/compositions",{method:"GET",headers:ct(e.vidfarmApiKey)});if(!v.ok){mo(v.status===401?"Sign in to see forks.":`Failed to load forks (${v.status}).`),an([]);return}let w=await v.json().catch(()=>null),B=(Array.isArray(w?.forks)?w.forks:[]).map(Y=>{if(!Y||typeof Y!="object")return null;let j=Y,ce=typeof j.fork_id=="string"?j.fork_id:null;return ce?{forkId:ce,templateId:typeof j.template_id=="string"?j.template_id:null,parentForkId:typeof j.parent_fork_id=="string"?j.parent_fork_id:null,parentVersion:typeof j.parent_version=="number"?j.parent_version:null,title:typeof j.title=="string"?j.title:null,visibility:typeof j.visibility=="string"?j.visibility:null,latestVersion:typeof j.latest_version=="number"?j.latest_version:null,ownerCustomerId:typeof j.owner_customer_id=="string"?j.owner_customer_id:null,createdAt:typeof j.created_at=="string"?j.created_at:null,updatedAt:typeof j.updated_at=="string"?j.updated_at:null}:null}).filter(Y=>!!Y).filter(Y=>Y.templateId===e.template.templateId).sort((Y,j)=>String(j.updatedAt??"").localeCompare(String(Y.updatedAt??"")));an(B)}catch{mo("Could not load forks. Please try again."),an([])}finally{On(!1)}}}(0,k.useEffect)(()=>{Xe&&dt===null&&!Tn&&Fe()},[Xe]),(0,k.useEffect)(()=>{let m=window.__vidfarmEditorTracers;if(m)return ne(m.get()),m.subscribe(w=>ne(w));let v=()=>{let w=Hf();ne(w.length?w:tr(e.template.tracers||[]))};return v(),window.addEventListener("popstate",v),()=>{window.removeEventListener("popstate",v)}},[e.template.tracers]);let me=(0,k.useRef)(_),Ve=(0,k.useRef)(g);(0,k.useEffect)(()=>{me.current=_,Ve.current=g},[_,g]),(0,k.useEffect)(()=>{if(!fe)return;let m=window.setTimeout(()=>{try{o?.setItem(r.threads,JSON.stringify(TR(me.current,Ve.current)))}catch(v){console.warn("Unable to persist editor chat threads.",v)}},300);return()=>window.clearTimeout(m)},[g,o,fe,r,_]),(0,k.useEffect)(()=>{if(fe)try{g?o?.setItem(r.activeThread,g):o?.removeItem(r.activeThread)}catch(m){console.warn("Unable to persist active editor chat thread.",m)}},[g,o,fe,r]),(0,k.useEffect)(()=>{if(!fe||typeof window>"u")return;let m=new URL(window.location.href),v=m.searchParams.get("thread_id");if(g){if(v===g)return;m.searchParams.set("thread_id",g)}else{if(!v)return;m.searchParams.delete("thread_id")}window.history.replaceState({},"",m.toString())},[g,fe]);let re=(0,k.useMemo)(()=>_.find(m=>m.id===g)??null,[g,_]),Dn=(0,k.useMemo)(()=>_.find(m=>m.id===M?.threadId)??null,[M?.threadId,_]);(0,k.useEffect)(()=>{if(!fe||!e.vidfarmApiKey||!g)return;let m=h.current.find(j=>j.id===g);if(y.current.has(g))return;let v=ER();if(!!(m&&(m.messageCount??0)===0&&m.messages.length===0)){y.current.add(g);return}let b=we(g);if(!b)return;let B=new AbortController;return!m?.messages.length&&R(g),(async()=>{try{let j=await fetch(b,{method:"GET",headers:ct(e.vidfarmApiKey),signal:B.signal});if(!j.ok){let ue=!!(m&&g!==v),de=!!(m&&(m.messageCount??0)===0&&m.messages.length===0);j.status===404&&!ue&&!de&&W(`Chat ID ${g} was not found for this account.`),y.current.add(g);return}let ce=await j.json().catch(()=>null),he=ce?.thread?IR(ce.thread,e.template.templateId):null;if(!he)return;y.current.add(he.id),W(null),T(ue=>{let de=wR(ue,[he]);return h.current=de,de})}catch(j){if(j instanceof DOMException&&j.name==="AbortError")return}finally{B.signal.aborted||R(j=>j===g?null:j)}})(),()=>{B.abort(),R(j=>j===g?null:j)}},[g,e.vidfarmApiKey,e.threadsUrl,fe]),(0,k.useEffect)(()=>{if(!fe||re&&!re.hiddenFromView)return;let m=_.find(v=>!v.hiddenFromView&&Tc(v,F));S(m?.id??_.find(v=>!v.hiddenFromView)?.id??null)},[re,fe,_,F]);let qf=(0,k.useMemo)(()=>re?.tracers.length?re.tracers:F,[re?.tracers,F]),Yf=(0,k.useMemo)(()=>_.filter(m=>!m.hiddenFromView).sort((m,v)=>{let w=Tc(m,F),b=Tc(v,F);return w!==b?w?-1:1:Date.parse(v.updatedAt)-Date.parse(m.updatedAt)}),[_,F]),ES=qf[0]??null,Kf=re?.messages??[],TS=ye!==null,Jf=!!(g&&ye===g),IS=(0,k.useMemo)(()=>(I.trim()||U.length)&&!TS,[I,U.length,TS]);(0,k.useEffect)(()=>{!fe||!e.vidfarmApiKey||!re||!re.messages.length||gx(re)},[re,e.vidfarmApiKey,fe]);async function wc(m,v){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let w=we(m.id);w&&await fetch(w,{method:"PATCH",headers:ct(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:e.template.templateId,title:v?.title??m.title,tracers:v?.tracers??m.tracers,hidden_from_view:v?.hiddenFromView??m.hiddenFromView===!0,archived:v?.archived})}).catch(()=>{})}async function ZR(m){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let v=we(m.threadId);v&&await fetch(`${v}/exchanges`,{method:"POST",headers:ct(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:m.templateId??e.template.templateId,title:m.title||"New chat",tracers:m.tracers,messages:m.messages.map(w=>({id:w.id,role:w.role,text:w.text,attachments:w.attachments.map(b=>({id:b.id,fileName:b.fileName,contentType:b.contentType,viewUrl:b.viewUrl})),toolExchanges:w.toolExchanges,httpExchanges:w.httpExchanges?.map(Ic)}))})}).catch(()=>{})}async function ex(m){if(!e.vidfarmApiKey||!e.threadsUrl)return;let v=we(m);v&&await fetch(v,{method:"DELETE",headers:ct(e.vidfarmApiKey)}).catch(()=>{})}function wS(m){let v=new URL(window.location.href);m.length?v.searchParams.set("tracers",m.join(",")):v.searchParams.delete("tracers"),window.history.replaceState({},"",v.toString()),window.dispatchEvent(new CustomEvent("vidfarm:editor-tracers-changed",{detail:{tracers:m}}))}function fa(m){let v=tr(m),w=window.__vidfarmEditorTracers;if(w){w.set(v);return}ne(v),wS(v)}function CS(){let m=window.__vidfarmEditorTracers;if(m)return m.add();let v=LF(e.template.templateSlug,F);return fa([v,...F]),v}function RS(m){let v=window.__vidfarmEditorTracers?.get()??F,w=m?OF(m,v):null,b=window.__vidfarmEditorTracers;return b?b.add(w??void 0):w?(fa([w,...v.filter(B=>B!==w)]),w):CS()}function tx(m){let v=m.trim();if(!v)return;let w=window.__vidfarmEditorTracers;w?w.add(v):F.includes(v)||fa([v,...F]),re&&ft(re.id,b=>({...b,tracers:[v,...b.tracers.filter(B=>B!==v)],updatedAt:new Date().toISOString()}))}function nx(m){let v=window.__vidfarmEditorTracers;if(v){v.remove(m);return}let w=F.filter(b=>b!==m);fa(w)}(0,k.useEffect)(()=>{wS(F)},[F]),(0,k.useEffect)(()=>{let m=s.current;if(!m)return;let v=()=>{a.current=uF(m),a.current||(l.current=!1)};return v(),m.addEventListener("scroll",v,{passive:!0}),()=>{m.removeEventListener("scroll",v)}},[]),(0,k.useLayoutEffect)(()=>{let m=s.current;if(!m)return;let v=c.current!==g;c.current=g,(v||l.current||a.current)&&(m.scrollTo({top:m.scrollHeight,behavior:"auto"}),a.current=!0,l.current=!1)},[Kf,g]),(0,k.useEffect)(()=>()=>{u.current?.abortController.abort(),u.current=null;for(let m of d.current.values())m.timeoutId!==null&&window.clearTimeout(m.timeoutId),m.abortController?.abort();d.current.clear()},[]),(0,k.useEffect)(()=>{if(!M)return;let m=()=>A(null);return document.addEventListener("click",m),window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{document.removeEventListener("click",m),window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[M]),(0,k.useEffect)(()=>{let m=()=>{if(document.visibilityState!=="visible"||!navigator.onLine)return;let v=Date.now();for(let w of d.current.values())w.inFlight||w.nextPollAt!==null&&w.nextPollAt<=v&&w.runPoll&&Qf(w,w.runPoll,w.nextPollAt-v)};return window.addEventListener("online",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("online",m),document.removeEventListener("visibilitychange",m)}},[]);function rx(m){if(re)return re.id;let v=new Date().toISOString(),w=vR(),b={id:w,templateId:e.template.templateId,title:Of(m||""),createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:tr(F),messages:[]};return h.current=[b,...h.current],T(B=>[b,...B]),S(w),w}function Xf(m){let v=new Date().toISOString(),w=tr(m?.tracers??F),b=vR(),B={id:b,templateId:e.template.templateId,title:m?.title||"New chat",createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:w,messages:[]};return h.current=[B,...h.current],T(Y=>[B,...Y]),m?.activate!==!1&&(S(b),N(""),x([]),W(null)),A(null),b}function xS(){Xf(),ut(!1)}function ox(m){let v=_.find(b=>b.id===m);if(!v||!window.confirm(`Delete conversation "${v.title}"?`))return;let w=_.filter(b=>b.id!==m);h.current=h.current.filter(b=>b.id!==m);for(let[b,B]of d.current.entries())B.threadId===m&&pa(b);T(w),g===m&&S(w[0]?.id??null),W(null),A(null),ex(m)}function ft(m,v){let w=UF(h.current.map(b=>b.id===m?v(b):b));h.current=w,T(w)}function ix(m,v){let w=tr(v);ft(m,B=>({...B,tracers:sS(B.tracers,w),updatedAt:new Date().toISOString()}));let b=h.current.find(B=>B.id===m);b&&wc({...b,tracers:sS(b.tracers,w),updatedAt:new Date().toISOString()},{tracers:sS(b.tracers,w)})}function bS(m,v){let w=m.trim();return w?h.current.find(b=>!b.hiddenFromView&&b.id!==v&&b.tracers.includes(w))?.id??null:null}function sx(m,v){let w=bS(m);return w||Xf({tracers:[m],title:v?.title||`Tracer ${m}`,activate:v?.activate??!1})}function ax(m){let v=m.toLowerCase();return/(?:own|separate|different|new)\s+(?:tracer\s+and\s+)?chat\s+threads?/.test(v)||/chat\s+threads?.{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)||/each.{0,80}(?:own|separate|different|new).{0,80}chat\s+threads?/.test(v)||/(?:own|separate|different|new)\s+tracers?/.test(v)||/(?:each|every|per|one\s+per).{0,80}(?:own|separate|different|new).{0,80}tracers?/.test(v)||/(?:own|separate|different|new)\s+tracers?.{0,80}(?:each|every|per|outputs?|pieces?|posts?|jobs?|generations?)/.test(v)||/(?:outputs?|pieces?|posts?|jobs?|generations?).{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)}function lx(m){let v=bS(m.tracer,m.sourceThreadId);if(!v&&!m.shouldCreateThread)return null;let w=v??sx(m.tracer,{title:`Tracer ${m.tracer}`,activate:!1});if(!w||w===m.sourceThreadId)return null;let b=Bf("assistant"),B=new Date().toISOString(),Y=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?Lf(m.job):fR(m.job),j=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?null:`Job ${m.job.job_id} is being tracked. ${Zf()}`,ce={id:b,role:"assistant",text:Y,attachments:[],httpExchanges:m.httpExchange?[m.httpExchange]:[],statusText:j,isPending:!1};ft(w,ue=>({...ue,updatedAt:B,messages:[...ue.messages,ce]}));let he=h.current.find(ue=>ue.id===w);return he&&ZR({threadId:w,templateId:he.templateId,title:he.title,tracers:he.tracers,messages:[ce]}),{threadId:w,messageId:b}}function cx(m){let v=_.find(B=>B.id===m);if(!v)return;let w=window.prompt("Thread tracers, comma separated",v.tracers.join(", "));if(w===null)return;let b=tr(w.split(","));ft(m,B=>({...B,tracers:b,updatedAt:new Date().toISOString()})),wc(v,{tracers:b}),A(null)}function ux(m){let v=_.find(B=>B.id===m);if(!v||!window.confirm(`Archive conversation "${v.title}"? Its tracer links will be prefixed with archived_.`))return;let b=tr(v.tracers.map(MF));ft(m,B=>({...B,tracers:b,updatedAt:new Date().toISOString()})),wc(v,{tracers:b,archived:!0}),A(null)}function dx(m){let v=_.find(b=>b.id===m);if(!(!v||!window.confirm(`Remove conversation "${v.title}" from this frontend view? The thread and tracer links stay available; Delete removes the thread completely.`))){for(let[b,B]of d.current.entries())B.threadId===m&&pa(b);if(ft(m,b=>({...b,hiddenFromView:!0,updatedAt:new Date().toISOString()})),g===m){let b=Yf.find(B=>B.id!==m);S(b?.id??null)}A(null),W(null),wc(v,{hiddenFromView:!0})}}async function fx(m){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(m);else{let v=document.createElement("textarea");v.value=m,v.setAttribute("readonly",""),v.style.position="fixed",v.style.opacity="0",document.body.appendChild(v),v.select(),document.execCommand("copy"),document.body.removeChild(v)}W(null)}catch{W("Unable to copy chat ID.")}finally{A(null)}}function px(m,v){if(M?.threadId===m){A(null);return}let w=v.getBoundingClientRect(),b=148;A({threadId:m,top:w.bottom+6,left:Math.max(8,Math.min(window.innerWidth-b-8,w.right-b))})}function pa(m){let v=d.current.get(m);v&&(v.timeoutId!==null&&window.clearTimeout(v.timeoutId),v.abortController?.abort(),d.current.delete(m))}function ma(m,v,w){let b=d.current.get(m);b&&Qf(b,v,w)}function Qf(m,v,w){m.timeoutId!==null&&window.clearTimeout(m.timeoutId);let b=Math.max(gR,w);m.nextPollAt=Date.now()+b,m.timeoutId=window.setTimeout(()=>{m.timeoutId=null,v()},b)}function Vi(){return d.current.size>=mR?fF:pR}function qi(m=Vi()){if(m>=6e4){let v=Math.round(m/6e4);return`${v} min${v===1?"":"s"}`}return`${Math.round(m/1e3)}s`}function Zf(m=Vi()){return d.current.size>=mR?`Many renders are active, so the next check is in ${qi(m)}.`:`Checking again gently every ${qi(m)}.`}function mx(){let m=Vi();if(m===pR)return;let v=Date.now();for(let w of d.current.values()){if(w.inFlight||!w.runPoll)continue;(w.nextPollAt===null?0:w.nextPollAt-v)<m&&Qf(w,w.runPoll,m)}}function hx(m){let v=Math.max(m,p.current.nextAvailableAt);return p.current.nextAvailableAt=v+pF,v-m}function ep(m){let v=yR(m.threadId,m.assistantMessageId,m.jobId);if(d.current.has(v))return;d.current.set(v,{timeoutId:null,abortController:null,runPoll:null,inFlight:!1,nextPollAt:null,lastPollAt:null,attempts:0,threadId:m.threadId});let w=async()=>{let Y=d.current.get(v);if(!Y||Y.inFlight)return;let j=Date.now(),ce=Vi();if(Y.lastPollAt!==null&&j-Y.lastPollAt<ce){ma(v,w,ce-(j-Y.lastPollAt));return}if(Y.attempts>=hR){ft(m.threadId,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(de=>de.id===m.assistantMessageId?{...de,statusText:"Background polling stopped after multiple checks. Open the job route when you want to refresh again."}:de)})),pa(v);return}if(document.visibilityState!=="visible"||!navigator.onLine){ma(v,w,ce);return}let he=hx(Date.now());if(he>0){ma(v,w,he);return}Y.inFlight=!0,Y.lastPollAt=j,Y.nextPollAt=null,Y.attempts+=1,Y.abortController=new AbortController;try{ft(m.threadId,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===m.assistantMessageId?{...X,statusText:`Job ${m.jobId} is being tracked. ${Zf(ce)}`}:X)}));let ue=m.primitiveId||mF(m.sourceRequestUrl)?`/api/v1/primitives/jobs/${encodeURIComponent(m.jobId)}`:`/api/v1/templates/${encodeURIComponent(e.template.templateId)}/jobs/${encodeURIComponent(m.jobId)}`,de=await fetch(ue,{method:"GET",headers:ct(e.vidfarmApiKey),signal:Y.abortController.signal}),ln=await de.json().catch(()=>null),ha=Object.fromEntries(de.headers.entries()),G=Hi(ln);if(ft(m.threadId,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>{if(X.id!==m.assistantMessageId)return X;let Ee=dF(X.httpExchanges,Ic({explanation:`Automatic ${qi(ce)} job status check for ${m.jobId}`,pollJobId:m.jobId,pollMode:"automatic",request:{method:"GET",url:ue,headers:Object.fromEntries(ct(e.vidfarmApiKey).entries())},result:{status:de.status,statusText:de.statusText,headers:ha,body:ln}})),ke=G?G.status==="succeeded"?`Render ${G.job_id} succeeded.`:G.status==="failed"||G.status==="cancelled"?`Render ${G.job_id} ${G.status}.${G.error?.message?` ${G.error.message}`:""}`:`Render ${G.job_id} is ${G.status}. Next check in ${qi(ce)}.`:`Render ${m.jobId} checked. Next check in ${qi(ce)}.`;return{...X,httpExchanges:Ee,statusText:ke,text:G&&(G.status==="succeeded"||G.status==="failed"||G.status==="cancelled")?Ec(X.text,Lf(G)):X.text}})})),G&&(G.status==="succeeded"||G.status==="failed"||G.status==="cancelled")){pa(v);return}}catch(ue){if(ue instanceof DOMException&&ue.name==="AbortError")return;ft(m.threadId,de=>({...de,updatedAt:new Date().toISOString(),messages:de.messages.map(ln=>ln.id===m.assistantMessageId?{...ln,statusText:`Automatic polling paused after an error. It will retry in ${qi()}.`}:ln)}))}finally{let ue=d.current.get(v);if(!ue)return;ue.inFlight=!1,ue.abortController=null,ue.attempts<hR&&ue.timeoutId===null&&d.current.has(v)&&ma(v,w,Vi())}},b=d.current.get(v);b&&(b.runPoll=w),d.current.get(v)&&(ma(v,w,m.initialDelayMs??Vi()),mx())}function gx(m){for(let v of m.messages)if(!(v.role!=="assistant"||!v.httpExchanges?.length))for(let w of v.httpExchanges){if(w.request.method!=="POST")continue;let b=Hi(w.result.body),B=yR(m.id,v.id,b?.job_id??"");!b||ua(b.status)||d.current.has(B)||v.httpExchanges.some(j=>{let ce=Hi(j.result.body);return ce?.job_id===b.job_id&&ua(ce.status)})||ep({threadId:m.id,assistantMessageId:v.id,jobId:b.job_id,tracer:b.tracer,initialStatus:b.status,primitiveId:b.primitive_id,sourceRequestUrl:w.request.url,initialDelayMs:gR})}}async function tp(m){if(!m.length)return;W(null);let v=[],w=null;for(let b of m)try{let B=await GR({apiKey:e.vidfarmApiKey,file:b,folderPath:LR}),Y=await WR({attachment:B,file:b,currentInlineBytes:jR([...U,...v])});v.push(Y)}catch(B){w=B instanceof Error?B.message:"Unable to upload attachment."}w&&v.length===0&&W(w),v.length&&(x(b=>[...b,...v]),w&&W(w))}async function yx(m){let v=Array.from(m.target.files??[]);await tp(v),m.target.value=""}async function Sx(m){let v=Array.from(m.clipboardData.files??[]).filter(w=>w.size>0);v.length&&(m.preventDefault(),await tp(v))}async function _x(m){m.preventDefault(),J(!1);let v=Array.from(m.dataTransfer.files??[]).filter(w=>w.size>0);v.length&&await tp(v)}async function vx(m,v,w){let b=w??{},B=e.vidfarmApiKey,Y=window.location.origin,j=ct(B,"application/json"),ce=ct(B),he=X=>new Promise(Ee=>setTimeout(Ee,X)),ue=(X,Ee)=>{ft(m,ke=>({...ke,updatedAt:new Date().toISOString(),messages:ke.messages.map(Ne=>Ne.id===v?{...Ne,isPending:!1,statusText:X??Ne.statusText,text:Ee?Ec(Ne.text,Ee):Ne.text}:Ne)}))},de=async X=>{let Ee=await X.text();try{return Ee?JSON.parse(Ee):null}catch{return null}},ln=async X=>{let Ee=Date.now()+3e5;for(;;){let ke=await fetch(new URL(`/api/v1/videos/${encodeURIComponent(X)}`,Y),{headers:ce}),Ne=await de(ke),He=String(Ne?.status??"");if(He==="ready")return Ne;if(He==="failed")throw new Error(`source video download failed${Ne?.error?`: ${Ne.error}`:""}.`);if(Date.now()>Ee)throw new Error("source video download timed out.");await he(5e3)}},ha=X=>{let Ee=Te=>typeof Te=="string"&&Te.trim()?Te.trim():null,ke=X?.result&&typeof X.result=="object"?X.result:{},Ne=ke.output&&typeof ke.output=="object"?ke.output:ke,He=Ee(Ne?.primary_file_url)??Ee(Ne?.video?.file_url)??Ee(Ne?.image?.file_url)??Ee(Ne?.render?.output_url);if(He)return He;if(Array.isArray(Ne?.files))for(let Te of Ne.files){let Le=Ee(typeof Te=="string"?Te:Te?.file_url??Te?.url);if(Le)return Le}if(Array.isArray(X?.artifacts))for(let Te of X.artifacts){let Le=Ee(Te?.public_url);if(Le)return Le}return null},G=async X=>{let Ee=Date.now()+48e4;for(;;){await he(5e3);let ke=await fetch(new URL(`/api/v1/user/me/jobs/${encodeURIComponent(X)}`,Y),{headers:ce}),Ne=await de(ke),He=String(Ne?.status??""),Te=ha(Ne);if(Te)return Te;if(He==="failed"||He==="cancelled")throw new Error(`generation ${He}.`);if(Date.now()>Ee)throw new Error("generation timed out.")}},Be=async(X,Ee)=>{let ke=await(await fetch(X)).blob(),Ne=await fetch(new URL("/discover/templates/upload/presign",Y),{method:"POST",headers:j,body:JSON.stringify({file_name:"generated.mp4",content_type:"video/mp4",size_bytes:ke.size})}),He=await de(Ne);if(!Ne.ok)throw new Error(He?.error||`upload presign failed (${Ne.status})`);let Te=He?.storage_key,Le=He?.file_name||"generated.mp4";if(He?.transport==="presigned"&&He?.upload?.url){let Oe=await fetch(He.upload.url,{method:He.upload.method||"PUT",headers:He.upload.headers||{},body:ke});if(!Oe.ok)throw new Error(`upload failed (${Oe.status})`)}else{let Oe=new FormData;Oe.append("file",ke,"generated.mp4");let Kt=await fetch(new URL(He?.upload?.url||"/discover/templates/upload",Y),{method:"POST",headers:ce,body:Oe}),_t=await de(Kt);if(!Kt.ok||!_t?.storage_key)throw new Error(_t?.error||`upload failed (${Kt.status})`);Te=_t.storage_key,Le=_t.file_name||"generated.mp4"}if(!Te)throw new Error("upload did not return a storage key.");let ho=await fetch(new URL("/discover/templates",Y),{method:"POST",headers:j,body:JSON.stringify({upload:{storage_key:Te,file_name:Le},title:Ee})}),Ot=await de(ho);if(!ho.ok)throw new Error(Ot?.error||`ingest failed (${ho.status})`);return Ot};try{if(!B){ue(null,"\u26A0\uFE0F You need to be logged in to create a video.");return}let X=b.mode==="replicate"?"replicate":b.mode==="generate"?"generate":null,Ee,ke;if(X==="replicate"){let Kt=(b.source_url??"").trim();if(!/^https?:\/\//i.test(Kt)){ue(null,"\u26A0\uFE0F I need a video URL (TikTok/YouTube/Instagram/X) to replicate.");return}ke=(b.instructions??"").trim()||null,ue("Fetching the source video\u2026");let _t=await fetch(new URL("/discover/templates",Y),{method:"POST",headers:j,body:JSON.stringify({source_url:Kt})}),Dr=await de(_t);if(!_t.ok)throw new Error(Dr?.error||`couldn't fetch that URL (${_t.status})`);Ee=Dr?.status==="ready"?Dr:await ln(Dr?.inspiration_id)}else if(X==="generate"){let Kt=(b.prompt??"").trim();if(!Kt){ue(null,"\u26A0\uFE0F Tell me what the video should be about and I'll create it.");return}ke=Kt,ue("Generating your video\u2026 (this can take a couple of minutes)");let _t=await fetch(new URL("/api/v1/primitives/videos/generate",Y),{method:"POST",headers:j,body:JSON.stringify({tracer:`chat-create-${Date.now().toString(36)}`,payload:{prompt:Kt}})}),Dr=await de(_t);if(!_t.ok)throw new Error(Dr?.error||`couldn't start generation (${_t.status})`);let Ix=await G(Dr?.job_id);ue("Building an editable template from the generated video\u2026");let np=await Be(Ix,Kt.slice(0,80));Ee=np?.status==="ready"?np:await ln(np?.inspiration_id)}else{ue(null,"\u26A0\uFE0F I couldn't tell whether to generate a new video or replicate a URL \u2014 try rephrasing.");return}let Ne=Ee?.template_id,He=Ee?.inspiration_id;if(!Ne||!He)throw new Error("the template wasn't created from the video.");ue(X==="replicate"?"Recreating the scenes\u2026 (about a minute)":"Analyzing into an editable timeline\u2026");let Te=await fetch(new URL(`/api/v1/inspirations/${encodeURIComponent(He)}/decompose`,Y),{method:"POST",headers:j,body:JSON.stringify({user_prompt:ke})});if(!Te.ok){let Kt=await de(Te);throw new Error(Kt?.error||`scene analysis failed (${Te.status})`)}ue("Finalizing your editable copy\u2026");let Le=await fetch(new URL("/api/v1/compositions",Y),{method:"POST",headers:j,body:JSON.stringify({template_id:Ne})}),ho=await de(Le);if(!Le.ok)throw new Error(ho?.error||`couldn't create an editable copy (${Le.status})`);let Ot=ho?.fork_id,Oe=`${Y}/editor/${encodeURIComponent(Ne)}${Ot?`?fork=${encodeURIComponent(Ot)}`:""}`;ue("Your video is ready.",`\u2705 Your video is ready \u2014 [Open it in the editor](${Oe}).`)}catch(X){ue(null,`\u26A0\uFE0F I couldn't finish creating the video: ${X instanceof Error?X.message:String(X)}`)}}async function kS(){if(!IS)return;l.current=!0;let m=rx(I),v=new Date().toISOString(),w=h.current.find(he=>he.id===m),b={id:Bf("user"),role:"user",text:I.trim(),attachments:U},B={id:Bf("assistant"),role:"assistant",text:"",attachments:[],statusText:"Waiting for AI response\u2026",isPending:!0},Y=w?.messages??[],j=wF([...Y,b]);ft(m,he=>({...he,title:he.messages.length===0?Of(b.text):he.title,updatedAt:v,messages:[...he.messages,b,B]})),N(""),x([]),W(null),K(m),pe("Waiting for AI response\u2026");let ce=new AbortController;u.current={abortController:ce,threadId:m,assistantMessageId:B.id};try{let he=JSON.stringify({messages:RF(j),thread_id:m,thread_template_id:w?.templateId??e.template.templateId,thread_title:Y.length===0?Of(b.text):w?.title??Of(b.text),thread_tracers:qf,client_context:ZU(),user_message:{id:b.id,role:b.role,text:b.text,attachments:b.attachments.map(G=>({id:G.id,fileName:G.fileName,contentType:G.contentType,viewUrl:G.viewUrl}))},assistant_message:{id:B.id},template:{...e.template,tracers:qf,defaultRequestTracer:ES,activeTracer:ES},cached_context:{...e.cachedContext,...xF(),...bF()}});Lr("chat.send.attempt",{thread_id:m,template_id:e.template.templateId,message_count:j.length,attachment_count:b.attachments.length,text_length:b.text.length});let ue=Date.now(),de=await fetch(e.apiUrl||"/api/v1/editor-chat",{method:"POST",headers:ct(e.vidfarmApiKey,"application/json"),signal:ce.signal,body:he});if(!de.ok){let G=await de.json().catch(()=>({}));throw uo("chat.send.rejected",{thread_id:m,status:de.status,error:typeof G?.error=="string"?G.error:null}),new Error(typeof G?.error=="string"?G.error:`Chat failed with status ${de.status}.`)}Lr("chat.send.stream_open",{thread_id:m,latency_ms:Date.now()-ue});let ln=new Map,ha=ax(b.text);await kF(de,{onDelta:G=>{pe("AI is responding\u2026"),ft(m,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===B.id?{...X,text:`${X.text}${G}`,statusText:"AI is responding\u2026",isPending:!1}:X)}))},onStatus:G=>{pe(G),ft(m,Be=>({...Be,messages:Be.messages.map(X=>X.id===B.id?{...X,statusText:G,isPending:!X.text}:X)}))},onToolCall:G=>{ln.set(G.toolCallId,{toolName:G.toolName,args:G.args}),ft(m,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===B.id?{...X,toolExchanges:[...X.toolExchanges??[],{toolCallId:G.toolCallId,toolName:G.toolName,args:zi(G.args),status:"pending"}]}:X)}))},onToolResult:G=>{let Be=OR(G.result),X=ln.get(G.toolCallId);if(G.toolName==="create_video"&&vx(m,B.id,G.result),G.toolName==="frontend_action"){let Te=G.result;if(Te?.action==="add_tracer")RS(Te.tracer??void 0);else if(Te?.action==="remove_tracer"&&Te.tracer)nx(Te.tracer);else if(Te?.action==="activate_tracer"&&Te.tracer)tx(Te.tracer);else if(Te?.action==="create_thread"){let Le=Te.tracer?RS(Te.tracer):CS();Xf({tracers:Le?[Le]:[],title:Le?`Tracer ${Le}`:"New chat",activate:!1})}}let Ee=G.result,ke=Hi(Ee?.response?.body),Ne=Ee?.request&&Ee?.response?Ic({explanation:Ee.explanation??null,request:Ee.request,result:Ee.response}):void 0,He=Ee?.request?.method==="POST"&&ke?.tracer?lx({sourceThreadId:m,tracer:ke.tracer,job:ke,httpExchange:Ne,shouldCreateThread:ha}):null;He&&ke&&!ua(ke.status)&&ep({threadId:He.threadId,assistantMessageId:He.messageId,jobId:ke.job_id,tracer:ke.tracer,initialStatus:ke.status,primitiveId:ke.primitive_id,sourceRequestUrl:Ee?.request?.url}),ft(m,Te=>({...Te,updatedAt:new Date().toISOString(),messages:Te.messages.map(Le=>{if(Le.id!==B.id)return Le;let ho=(Le.toolExchanges??[]).map(_t=>_t.toolCallId===G.toolCallId?{..._t,result:Be,status:typeof G.result?.error=="string"?"error":"complete"}:_t),Ot=G.result,Oe=Hi(Ot?.response?.body),Kt=Ot?.request&&Ot?.response?[...Le.httpExchanges??[],Ic({explanation:Ot.explanation??null,request:Ot.request,result:Ot.response})]:Le.httpExchanges;if(X&&ln.delete(G.toolCallId),Ot?.request?.method==="POST"&&Oe?.tracer){let _t=window.__vidfarmEditorTracers;_t?_t.add(Oe.tracer):fa([Oe.tracer,...F.filter(Dr=>Dr!==Oe.tracer)]),ix(m,[Oe.tracer])}return Oe&&!He&&!ua(Oe.status)&&ep({threadId:m,assistantMessageId:B.id,jobId:Oe.job_id,tracer:Oe.tracer,initialStatus:Oe.status,primitiveId:Oe.primitive_id,sourceRequestUrl:Ot?.request?.url}),{...Le,toolExchanges:ho,httpExchanges:Kt,statusText:Oe&&!ua(Oe.status)?`Job ${Oe.job_id} is being tracked. ${Zf()}`:Le.statusText,isPending:!1,text:Oe&&Ot?.request?.method==="POST"&&Ot?.response?.status===202?Ec(Le.text,fR(Oe)):Oe&&ua(Oe.status)||Oe?Ec(Le.text,Lf(Oe)):Le.text}})}))},onError:G=>{uo("chat.stream.error",{thread_id:m,message:G}),W(G),pe(null),ft(m,Be=>({...Be,messages:Be.messages.filter(X=>X.id!==B.id)}))}}),Lr("chat.stream.completed",{thread_id:m,duration_ms:Date.now()-ue}),ft(m,G=>({...G,updatedAt:new Date().toISOString(),messages:G.messages.map(Be=>Be.id===B.id?{...Be,statusText:Be.statusText?.includes("being tracked")?Be.statusText:null,isPending:!1}:Be)}))}catch(he){if(he instanceof DOMException&&he.name==="AbortError"){eR("chat.send.aborted",{thread_id:m}),W(null),pe(null),ft(m,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(de=>de.id!==B.id?de:!!(de.text.trim()||de.toolExchanges?.length||de.httpExchanges?.length)?{...de,statusText:"Stopped.",isPending:!1}:{...de,text:"Stopped.",statusText:null,isPending:!1})}));return}uo("chat.send.failed",{thread_id:m,message:he instanceof Error?he.message:String(he)}),W(he instanceof Error?he.message:"Unable to send chat message."),pe(null),ft(m,ue=>({...ue,messages:ue.messages.map(de=>de.id===B.id?{...de,text:he instanceof Error?`Error: ${he.message}`:"Error: Unable to send chat message.",statusText:null,isPending:!1}:de)}))}finally{u.current?.assistantMessageId===B.id&&(u.current=null),K(he=>he===m?null:he),pe(null)}}function Ex(){pe("Stopping\u2026");let m=u.current;m&&ft(m.threadId,v=>({...v,updatedAt:new Date().toISOString(),messages:v.messages.map(w=>w.id===m.assistantMessageId?{...w,statusText:"Stopping\u2026"}:w)})),u.current?.abortController.abort()}(0,k.useEffect)(()=>()=>{u.current?.abortController.abort();for(let m of d.current.keys())pa(m);try{o?.setItem(r.threads,JSON.stringify(TR(me.current,Ve.current)))}catch{}},[o,r]);function Tx(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),kS())}let NS=(0,f.jsx)("div",{className:`vf-editor-chat-thread-list${t?" vf-editor-chat-thread-list-sidebar":""}`,role:"tablist","aria-label":"Conversation threads",children:Yf.length?Yf.map(m=>(0,f.jsxs)("div",{role:"tab","aria-selected":m.id===g,className:"vf-editor-chat-thread-chip","data-active":m.id===g?"true":"false",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-thread-chip-main",onClick:()=>{S(m.id),W(null),A(null),ut(!1),t&&Ie(!1)},children:[(0,f.jsx)("span",{className:"vf-editor-chat-thread-chip-title",children:m.title}),m.tracers.length?(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.tracers.slice(0,2).join(", "),m.tracers.length>2?` +${m.tracers.length-2}`:""]}):null]}),(0,f.jsx)("div",{className:"vf-editor-chat-thread-menu-wrap",children:(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-thread-chip-menu","aria-label":`Actions for ${m.title}`,onClick:v=>{v.stopPropagation(),px(m.id,v.currentTarget)},children:"..."})})]},m.id)):(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Start a chat to create your first conversation thread."})});return(0,f.jsxs)("div",{className:"vf-editor-chat-shell","data-mobile-open":le?"true":"false","data-layout":t?"brainstorm":"default",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-mobile-fab","aria-label":"Open chat","aria-expanded":le,onClick:()=>Ie(!0),children:(0,f.jsx)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:(0,f.jsx)("path",{d:"M20 11.5a7.5 7.5 0 0 1-9.8 7.1L4 20l1.5-5.3A7.5 7.5 0 1 1 20 11.5Z"})})}),$?(0,f.jsx)("div",{className:"vf-editor-chat-error",role:"status",children:$}):null,(0,f.jsxs)("div",{className:`${t?"vf-editor-chat-body vf-editor-chat-brainstorm-layout":"vf-editor-chat-body"}${n?" has-sidebar":""}`,"data-history-open":_e||Xe?"true":"false",children:[n?(0,f.jsxs)("aside",{className:"vf-editor-chat-history-pane",children:[(0,f.jsx)("div",{className:"vf-editor-chat-history-header",children:(0,f.jsxs)("div",{className:"vf-editor-chat-history-header-main",children:[(0,f.jsxs)("a",{className:"vf-editor-chat-back-button",href:"/discover","aria-label":"Back to Discover",children:[(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}),"Discover"]}),(0,f.jsx)("div",{className:"vf-editor-chat-history-kicker",children:"Chat history"})]})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread vf-editor-chat-new-thread-sidebar",onClick:xS,children:"New chat"}),NS]}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-thread",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-header-row",children:[(0,f.jsx)("a",{className:"vf-editor-chat-back-button vf-editor-chat-back-button--header",href:"/discover","aria-label":"Back to Discover",children:(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon","aria-label":_e?"Back to chat":"Open chat history","aria-pressed":_e,onClick:()=>{ut(m=>!m),Yt(!1)},children:_e?(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,f.jsx)("circle",{cx:"10",cy:"10",r:"7.2"}),(0,f.jsx)("path",{d:"M10 6v4l2.6 1.6"})]})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon vf-editor-chat-branches-icon","aria-label":Xe?"Back to chat":"Open template forks","aria-pressed":Xe,onClick:()=>{Yt(m=>!m),ut(!1)},children:Xe?(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,f.jsx)("circle",{cx:"5.5",cy:"4.5",r:"1.9"}),(0,f.jsx)("circle",{cx:"5.5",cy:"15.5",r:"1.9"}),(0,f.jsx)("circle",{cx:"14.5",cy:"8",r:"1.9"}),(0,f.jsx)("path",{d:"M5.5 6.4v7.2"}),(0,f.jsx)("path",{d:"M5.5 13.6c0-3.2 2.4-3.6 4.4-3.9 2-.3 4.6-.5 4.6-3.7"})]})}),(0,f.jsxs)("div",{className:"vf-editor-chat-header-titles",children:[(0,f.jsx)("div",{className:"vf-editor-chat-header-title",children:"Vidfarm"}),(0,f.jsx)("div",{className:"vf-editor-chat-header-subtitle",children:_e?"Chat history":Xe?"Template forks":e.template.templateTitle})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread",onClick:xS,children:"New chat"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-minimize","aria-label":"Minimize chat",onClick:()=>Ie(!1),children:"\xD7"})]}),M&&Dn?(0,ji.createPortal)((0,f.jsxs)("div",{className:"vf-editor-chat-thread-menu",role:"menu",style:{top:M.top,left:M.left},onClick:m=>m.stopPropagation(),children:[(0,f.jsx)("button",{type:"button",onClick:()=>fx(Dn.id),children:"Copy Chat ID"}),(0,f.jsx)("button",{type:"button",onClick:()=>cx(Dn.id),children:"Edit tracers"}),(0,f.jsx)("button",{type:"button",onClick:()=>dx(Dn.id),children:"Remove from view"}),(0,f.jsx)("button",{type:"button",onClick:()=>ux(Dn.id),children:"Archive thread"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>ox(Dn.id),children:"Delete"})]}),document.body):null]}),(0,f.jsx)("div",{className:"vf-editor-chat-viewport",ref:s,children:_e?(0,f.jsx)("div",{className:"vf-editor-chat-history-panel",children:NS}):Xe?(0,f.jsxs)("div",{className:"vf-editor-chat-history-panel vf-editor-chat-branches-panel",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-branches-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-branches-header-main",children:[(0,f.jsx)("div",{className:"vf-editor-chat-branches-kicker",children:"Forks"}),(0,f.jsxs)("div",{className:"vf-editor-chat-branches-title",children:[dt?.length??0," fork",(dt?.length??0)===1?"":"s"," of this template"]})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-branches-refresh",onClick:()=>{Fe({force:!0})},disabled:Tn,"aria-label":"Refresh forks",children:Tn?"Loading\u2026":"Refresh"})]}),po?(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",role:"status",children:po}):Tn&&!dt?(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Loading forks\u2026"}):dt&&dt.length?(0,f.jsx)("div",{className:"vf-editor-chat-thread-list",children:dt.map(m=>{let v=St===m.forkId,w=`/editor/${encodeURIComponent(e.template.templateId)}?fork=${encodeURIComponent(m.forkId)}`,b=m.title&&m.title.trim()?m.title:m.forkId,B=m.parentForkId?` \xB7 forked from ${m.parentForkId.slice(0,12)}${m.parentVersion?`#v${m.parentVersion}`:""}`:"",Y=m.latestVersion&&m.latestVersion>0?` \xB7 v${m.latestVersion}`:"";return(0,f.jsx)("div",{role:"listitem",className:"vf-editor-chat-thread-chip","data-active":v?"true":"false",children:(0,f.jsxs)("a",{className:"vf-editor-chat-thread-chip-main vf-editor-chat-branch-chip-link",href:w,target:"_blank",rel:"noopener noreferrer",children:[(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-title",children:[b,v?(0,f.jsx)("span",{className:"vf-editor-chat-branch-current-badge",children:"current"}):null]}),(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.visibility??"private",Y,B]})]})},m.forkId)})}):(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"No forks yet for this template."})]}):Kf.length?Kf.map(m=>(0,f.jsx)(KF,{message:m},m.id)):g&&E===g?(0,f.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,f.jsx)("div",{className:"vf-editor-chat-kicker",children:"Loading chat"}),(0,f.jsxs)("h2",{children:["Opening ",g]})]}):(0,f.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,f.jsx)("div",{className:"vf-editor-chat-kicker",children:"AI Copilot"}),(0,f.jsx)("h2",{children:t?"Start a new chat.":"Repurpose this video."}),(0,f.jsx)("p",{children:t?"Use the brainstorm tools to go from zero context to angles, hooks, and a strategy you can actually test.":"Use the brainstorm tools to turn this video into a native ad for your product, spot product-placement opportunities, and shape the timeline you can actually test. You can also connect from your own AI coding agent, including Claude Code or OpenAI Codex, and ask it to work against this composition."}),(0,f.jsx)("div",{className:"vf-editor-chat-empty-prompts","aria-label":"Example prompts",children:t?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{children:"I don't know where to start"}),(0,f.jsx)("div",{children:"Help me think of persuasive angles"}),(0,f.jsx)("div",{children:"Help me think of viral hooks"})]}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{children:"I don't know where to start"}),(0,f.jsx)("div",{children:"Repurpose this video into a social media native ad for my product"}),(0,f.jsx)("div",{children:"Help me identify product placement opportunities in this video for my product"})]})})]})}),(0,f.jsx)("div",{className:"vf-editor-chat-footer",hidden:_e||Xe,children:(0,f.jsxs)("div",{className:"vf-editor-chat-composer","data-drop-target":Se?"true":"false",onDragEnter:m=>{m.preventDefault(),J(!0)},onDragOver:m=>{m.preventDefault(),Se||J(!0)},onDragLeave:m=>{m.preventDefault();let v=m.relatedTarget;v instanceof Node&&m.currentTarget.contains(v)||J(!1)},onDrop:m=>{_x(m)},children:[Se?(0,f.jsx)("div",{className:"vf-editor-chat-dropzone-hint",children:"Drop files to attach"}):null,U.length?(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachments-strip",children:U.map(m=>(0,f.jsx)(jF,{attachment:m,onRemove:()=>x(v=>v.filter(w=>w.id!==m.id))},m.id))}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-composer-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-attach-button","aria-label":"Open upload drawer",onClick:()=>P(!0),children:"\u{1F4CE}"}),(0,f.jsx)("textarea",{rows:1,placeholder:t?"Describe the offer, audience, or strategy problem you want help with...":"Ask it to call a route, inspect jobs, save config, or continue this thread...",className:"vf-editor-chat-input",value:I,onChange:m=>N(m.target.value),onKeyDown:Tx,onPaste:m=>{Sx(m)}}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-send-button",onClick:()=>{if(Jf){Ex();return}kS()},disabled:Jf?!1:!IS,children:Jf?"Stop":"Send"})]}),(0,f.jsx)("input",{ref:i,type:"file",accept:"image/*,video/*,audio/*,application/pdf,text/plain,text/markdown",multiple:!0,hidden:!0,onChange:m=>{yx(m)}})]})})]})]}),(0,f.jsx)(XF,{apiKey:e.vidfarmApiKey,open:Gi,onClose:()=>P(!1),onConfirm:m=>x(v=>[...v,...m])})]})}var En=In(vc(),1);tR();function QF(){let e=document.getElementById("page-runtime-boot");return e?.textContent?JSON.parse(e.textContent):null}function Gf(e){let t=new Date;return t.setDate(t.getDate()+e),t.toISOString()}async function ZF(e){if(!e.userId)return;let t=e.store.getState();if(!e.force&&t.channels.length&&t.channelsUpdatedAt)return;let n=new URLSearchParams({start_date:Gf(-7),end_date:Gf(30)}),r=await fetch(`/u/${encodeURIComponent(e.userId)}/calendar/feed?${n.toString()}`,{headers:{accept:"application/json"}}),o=await r.json().catch(()=>null);!r.ok||!o||(e.store.getState().setCalendarData({channels:Array.isArray(o.channels)?o.channels:[],posts:Array.isArray(o.posts)?o.posts:[],rangeStart:o.startDate||Gf(-7),rangeEnd:o.endDate||Gf(30),replaceRange:!0}),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated")))}function eB({boot:e}){let t=(0,Wi.useMemo)(()=>sR(e),[e]),n=ZC(t,i=>i.boot.title),[r,o]=(0,Wi.useState)(null);return(0,Wi.useEffect)(()=>{t.getState().setHydratedAt(new Date().toISOString()),document.documentElement.dataset.reactRuntime="true",document.documentElement.dataset.reactRuntimePage=e.pageKind,document.title=n},[e.pageKind,t,n]),(0,Wi.useEffect)(()=>{if(!e.editorChat)return;let i=document.querySelector("[data-template-editor-chat-root]");o(i instanceof HTMLElement?i:null)},[e.editorChat]),e.editorChat&&r?(0,JR.createPortal)((0,En.jsx)(Ls,{fallback:(0,En.jsx)(tB,{}),children:(0,En.jsx)(KR,{boot:e.editorChat})}),r):null}function tB(){return(0,En.jsxs)("div",{style:{display:"grid",placeItems:"center",height:"100%",padding:"24px",textAlign:"center",gap:"12px",color:"#5c6a82"},children:[(0,En.jsx)("div",{style:{fontSize:"0.72rem",fontWeight:800,letterSpacing:"0.14em",textTransform:"uppercase"},children:"Chat error"}),(0,En.jsx)("div",{style:{fontSize:"0.92rem"},children:"Something went wrong loading the chat. Reload the page to try again."}),(0,En.jsx)("button",{type:"button",onClick:()=>window.location.reload(),style:{marginTop:"4px",minHeight:"34px",padding:"0 16px",border:"1px solid rgba(191, 164, 109, 0.34)",borderRadius:"999px",background:"rgba(255, 255, 255, 0.92)",color:"#243041",fontWeight:700,cursor:"pointer"},children:"Reload"})]})}var Qo=QF(),_S=document.getElementById("page-runtime-root"),vS=iR(Qo?.userId??null),Vf=null;function QR(e={}){return!e.force&&Vf||(Vf=ZF({userId:Qo?.userId??null,store:vS,force:e.force}).catch(()=>{})),Vf}window.__vidfarmFlockPosterCache={readSnapshot:()=>eS(Qo?.userId??null),ensureHydrated:QR,setChannelsData:e=>{vS.getState().setChannelsData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))},setCalendarData:e=>{vS.getState().setCalendarData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))}};QR();Lr("page_runtime.boot",{has_boot:!!Qo,has_root:!!_S,page_kind:Qo?.pageKind??null,editor_chat_template_id:Qo?.editorChat?.template?.templateId??null});Qo&&_S&&(0,XR.createRoot)(_S).render((0,En.jsx)(Ls,{fallback:(0,En.jsx)(En.Fragment,{}),onError:e=>uo("page_runtime.render_error",{message:e instanceof Error?e.message:String(e)}),children:(0,En.jsx)(eB,{boot:Qo})}));
45
+ `).map(h=>h.trim()).find(h=>h.startsWith("data:"));if(!c)continue;let u=c.slice(5).trim();if(u==="[DONE]")continue;let d;try{d=JSON.parse(u)}catch{continue}if(!d||typeof d!="object")continue;let p=d;if(p.type==="text-delta"&&typeof p.delta=="string")t.onDelta(p.delta);else if(p.type==="status"){let h=typeof p.status=="string"?p.status:typeof p.message=="string"?p.message:null;h&&t.onStatus&&t.onStatus(h)}else p.type==="tool-call"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolCall?t.onToolCall({toolCallId:p.toolCallId,toolName:p.toolName,args:p.args&&typeof p.args=="object"?p.args:void 0}):p.type==="tool-result"&&typeof p.toolCallId=="string"&&typeof p.toolName=="string"&&t.onToolResult?t.onToolResult({toolCallId:p.toolCallId,toolName:p.toolName,result:p.result}):p.type==="error"&&t.onError&&t.onError?.(typeof p.errorText=="string"?p.errorText:typeof p.error?.message=="string"?p.error.message:"Unable to read assistant response.")}}}function NF(e){return{threads:`vidfarm-editor-chat-threads:${e}`,activeThread:`vidfarm-editor-chat-active-thread:${e}`}}function AF(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{try{return window.localStorage}catch{return null}}}function vR(){return`thread-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Bf(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function tr(e){let t=new Set,n=[];for(let r of e){let o=r.trim();!o||t.has(o)||(t.add(o),n.push(o))}return n}function sS(...e){return tr(e.flat())}function MF(e){let t=e.trim();return!t||t.startsWith("archived_")?t:`archived_${t}`}function uS(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,"").slice(-8):Math.random().toString(16).slice(2,10).padEnd(8,"0").slice(0,8)}function PF(e){return(e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tracer").slice(0,28)}function LF(e,t){let n=PF(e),r="";do r=`${n}-${uS()}`;while(t.includes(r));return r}function OF(e,t){let n=e.trim();if(!n)return"";if(/-[a-z0-9]{8}$/i.test(n))return n;let r=`${n}-${uS()}`;for(;t.includes(r);)r=`${n}-${uS()}`;return r}function Hf(){let e=new URLSearchParams(window.location.search),t=[...e.getAll("tracers"),...e.getAll("tracer")],n=[];for(let r of t){let o=r.trim();if(!o)continue;let i=o.startsWith("[")&&o.endsWith("]")?o.slice(1,-1):o;n.push(...i.split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")))}return tr(n)}function ER(){let e=new URLSearchParams(window.location.search);return(e.get("thread_id")||e.get("threadId")||e.get("chat_id")||e.get("chatId")||"").trim()}function Of(e){let t=e.trim().replace(/\s+/g," ");return t?t.length>42?`${t.slice(0,42).trimEnd()}\u2026`:t:"New chat"}function TR(e,t){return e.map(n=>({id:n.id,templateId:n.templateId,title:n.title,createdAt:n.createdAt,updatedAt:n.updatedAt,lastMessageAt:n.lastMessageAt??null,messageCount:Math.max(n.messageCount??0,n.messages.length),tracers:n.tracers,hiddenFromView:n.hiddenFromView,messages:(n.id===t?n.messages.slice(-QU):[]).map(r=>({id:r.id,role:r.role,text:r.text,attachments:r.attachments.map(o=>({id:o.id,fileName:o.fileName,contentType:o.contentType,viewUrl:o.viewUrl})),toolExchanges:r.toolExchanges?.map(o=>({...o,args:zi(o.args),result:OR(o.result)})),httpExchanges:r.httpExchanges?.map(Ic)}))}))}function DF(e,t){if(!e)return[];try{let n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.id=="string").map(r=>({id:r.id,templateId:typeof r.templateId=="string"&&r.templateId.trim()?r.templateId:t,title:typeof r.title=="string"&&r.title.trim()?r.title:"New chat",createdAt:typeof r.createdAt=="string"?r.createdAt:new Date().toISOString(),updatedAt:typeof r.updatedAt=="string"?r.updatedAt:new Date().toISOString(),lastMessageAt:typeof r.lastMessageAt=="string"?r.lastMessageAt:null,messageCount:Math.max(typeof r.messageCount=="number"?r.messageCount:0,Array.isArray(r.messages)?r.messages.length:0),tracers:tr(Array.isArray(r.tracers)?r.tracers.filter(o=>typeof o=="string"):[]),hiddenFromView:r.hiddenFromView===!0,messages:Array.isArray(r.messages)?r.messages.map(o=>({id:o.id,role:o.role,text:o.text,attachments:Array.isArray(o.attachments)?o.attachments:[],toolExchanges:Array.isArray(o.toolExchanges)?o.toolExchanges:[],httpExchanges:Array.isArray(o.httpExchanges)?o.httpExchanges:[]})):[]})):[]}catch{return[]}}function IR(e,t){return!e||typeof e.id!="string"?null:{id:e.id,templateId:typeof e.templateId=="string"&&e.templateId.trim()?e.templateId:t,title:typeof e.title=="string"&&e.title.trim()?e.title:"New chat",createdAt:typeof e.createdAt=="string"?e.createdAt:new Date().toISOString(),updatedAt:typeof e.updatedAt=="string"?e.updatedAt:new Date().toISOString(),lastMessageAt:typeof e.lastMessageAt=="string"?e.lastMessageAt:null,messageCount:Math.max(typeof e.messageCount=="number"?e.messageCount:0,Array.isArray(e.messages)?e.messages.length:0),tracers:tr(Array.isArray(e.tracers)?e.tracers.filter(n=>typeof n=="string"):[]),hiddenFromView:e.hiddenFromView===!0,messages:Array.isArray(e.messages)?e.messages.map(n=>({id:n.id,role:n.role,text:n.text,attachments:Array.isArray(n.attachments)?n.attachments:[],toolExchanges:Array.isArray(n.toolExchanges)?n.toolExchanges:[],httpExchanges:Array.isArray(n.httpExchanges)?n.httpExchanges:[]})):[]}}function wR(e,t){let n=new Map;for(let r of t){let o=e.find(i=>i.id===r.id);n.set(r.id,{...r,lastMessageAt:r.lastMessageAt??o?.lastMessageAt??null,messageCount:Math.max(r.messageCount??0,o?.messageCount??0,r.messages.length,o?.messages.length??0),messages:r.messages.length?r.messages:o?.messages??[]})}for(let r of e)n.has(r.id)||n.set(r.id,r);return[...n.values()].sort((r,o)=>Date.parse(o.updatedAt)-Date.parse(r.updatedAt))}function UF(e){return[...e].sort((t,n)=>Date.parse(n.updatedAt)-Date.parse(t.updatedAt))}function Tc(e,t){return t.length?e.tracers.some(n=>t.some(r=>FF(n,r))):!0}function FF(e,t){let n=e.trim(),r=t.trim();return!n||!r?!1:n===r?!0:n.startsWith(`${r}-`)&&/-[a-z0-9]{8}$/i.test(n)}function BF(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-attachment",children:[(0,f.jsx)("span",{className:"vf-editor-chat-attachment-name",children:e.attachment.fileName}),e.onRemove?(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-attachment-remove","aria-label":"Remove attachment",onClick:e.onRemove,children:"\xD7"}):null]})}function hS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M10 3v9"}),(0,f.jsx)("path",{d:"m6.5 8.5 3.5 3.5 3.5-3.5"}),(0,f.jsx)("path",{d:"M4 16h12"})]})}function HF(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M4.2 15.8c1.6.5 3.1-.1 3.7-1.7.6-1.4 1.8-2.1 3.5-2.1"}),(0,f.jsx)("path",{d:"m10.7 11.6 5.2-5.2a1.9 1.9 0 0 0-2.7-2.7L8 8.9"}),(0,f.jsx)("path",{d:"m7.9 9 3.1 3.1"}),(0,f.jsx)("path",{d:"M3.5 16.5c1.4.5 3.6.5 4.9-.8"})]})}function gS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M8.4 11.6a3.2 3.2 0 0 0 4.5 0l2.2-2.2a3.2 3.2 0 0 0-4.5-4.5L9.4 6.1"}),(0,f.jsx)("path",{d:"M11.6 8.4a3.2 3.2 0 0 0-4.5 0L4.9 10.6a3.2 3.2 0 0 0 4.5 4.5l1.2-1.2"})]})}function yS(){return(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("rect",{x:"7",y:"7",width:"9",height:"9",rx:"2"}),(0,f.jsx)("path",{d:"M5 12H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1"})]})}function Df(e){return(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transform:e.open?"rotate(90deg)":"rotate(0deg)"},children:(0,f.jsx)("path",{d:"m7 4 6 6-6 6"})})}function VR(e){let t=e.label.trim().replace(/[\\/:*?"<>|]+/g,"-");if(t)return t;try{return new URL(e.url,window.location.href).pathname.split("/").filter(Boolean).pop()||"media"}catch{return"media"}}function CR(e,t=!1){if(typeof window>"u"||e.kind!=="image"||!e.url)return"";let n=new URL("/inpaint",window.location.origin),r=window.__vidfarmEditorTracers,i=(r?.get()??Hf())[0]||(t?r?.add()??"":"");return i&&n.searchParams.set("tracer",i),n.searchParams.set("source_image_url",e.url),n.searchParams.set("source_image_name",e.label||VR(e)),n.toString()}function $F(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),{onClose:i}=e,s=e.gallery?.length?e.gallery:[e.preview],a=Math.max(0,s.findIndex(T=>T.url===e.preview.url)),[l,c]=(0,k.useState)(a),u=s[l]||e.preview,d=s.length>1,p=u.kind==="image",h=p&&CR(u,!1)||"/inpaint";(0,k.useEffect)(()=>{n(!0)},[]),(0,k.useEffect)(()=>{o("")},[u.url]);let y=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(u.url);else{let T=document.createElement("textarea");T.value=u.url,T.style.position="fixed",T.style.opacity="0",document.body.appendChild(T),T.focus(),T.select(),document.execCommand("copy"),document.body.removeChild(T)}o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)},_=T=>{let g=CR(u,!0);if(!g){T.preventDefault();return}T.preventDefault(),window.open(g,"_blank","noopener,noreferrer")};return(0,k.useEffect)(()=>{let T=g=>{if(g.key==="Escape"){i();return}d&&(g.key==="ArrowLeft"?(g.preventDefault(),c(S=>(S-1+s.length)%s.length)):g.key==="ArrowRight"&&(g.preventDefault(),c(S=>(S+1)%s.length)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[d,s.length,i]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal",onClick:T=>T.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:u.url,target:"_blank",rel:"noopener noreferrer",children:d?`${u.label} (${l+1} of ${s.length})`:u.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[d?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T-1+s.length)%s.length),"aria-label":"Previous image",title:"Previous image",children:"\u2039"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:()=>c(T=>(T+1)%s.length),"aria-label":"Next image",title:"Next image",children:"\u203A"})]}):null,p?(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:h,target:"_blank",rel:"noopener noreferrer",onClick:_,"aria-label":"Open image editor",title:"Image edit",children:(0,f.jsx)(HF,{})}):null,(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:u.url,download:VR(u),"aria-label":"Download media",title:"Download",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{y()},"aria-label":r==="done"?"Media URL copied":r==="error"?"Unable to copy media URL":"Copy media URL",title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy link",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close media preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-media-modal-body",children:u.kind==="image"?(0,f.jsx)("img",{src:u.url,alt:u.label,className:"vf-editor-chat-media-modal-image"}):(0,f.jsx)("video",{src:u.url,className:"vf-editor-chat-media-modal-video",controls:!0,autoPlay:!0,playsInline:!0})})]})}),document.body):null}function zF(e){let[t,n]=(0,k.useState)(!1);return(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-message-thumb-button is-image",onClick:()=>e.onOpenModal(e.preview,e.previews),"aria-label":`Preview ${e.preview.label}`,title:e.preview.label,"data-error":t?"true":"false",children:t?(0,f.jsx)("span",{className:"vf-editor-chat-message-thumb-fallback",children:"Preview unavailable"}):(0,f.jsx)("img",{src:e.preview.url,alt:e.preview.label,className:"vf-editor-chat-message-attachment-thumb",loading:"lazy",onError:()=>n(!0)})})}function RR(e){return(0,f.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-message-thumb-button",onClick:()=>e.onOpenModal(e.preview),"aria-label":`Preview ${e.preview.label}`,children:[(0,f.jsx)("video",{src:e.preview.url,className:"vf-editor-chat-message-attachment-thumb vf-editor-chat-message-video-thumb",preload:"metadata",muted:!0,playsInline:!0}),(0,f.jsx)("span",{className:"vf-editor-chat-message-video-play","aria-hidden":"true"})]})})}function xR(e){return e.previews.length?(0,f.jsx)("div",{className:"vf-editor-chat-message-image-rail","aria-label":"Image previews",children:e.previews.map(t=>(0,f.jsx)(zF,{preview:t,previews:e.previews,onOpenModal:e.onOpenModal},t.url))}):null}function jF(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-composer-attachment-item",children:[$f(e.attachment)?(0,f.jsx)("img",{src:e.attachment.viewUrl,alt:e.attachment.fileName,className:"vf-editor-chat-composer-attachment-thumb"}):(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachment-file","aria-hidden":"true",children:e.attachment.fileName.slice(0,1).toUpperCase()}),(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachment-meta",children:(0,f.jsx)("span",{className:"vf-editor-chat-composer-attachment-name",children:e.attachment.fileName})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-composer-attachment-remove","aria-label":`Remove ${e.attachment.fileName}`,onClick:e.onRemove,children:"\xD7"})]})}function WF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),i=Uf(e.exchange.request.body),s=Uf(e.exchange.result.body),a=e.exchange.request.url,l=a.length>52?`${a.slice(0,52).trimEnd()}...`:a,c=e.exchange.result.status>=400||!!e.exchange.result.error,u=e.exchange.result.status>=200&&e.exchange.result.status<300;return(0,k.useEffect)(()=>{o(!0)},[]),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-card",children:(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-http-card-header",onClick:()=>n(!0),"aria-label":`Open HTTP details for ${e.exchange.request.method} ${a}`,children:[(0,f.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,f.jsx)("span",{className:"vf-editor-chat-http-url",title:a,children:l}),(0,f.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]}),(0,f.jsx)("span",{className:"vf-editor-chat-http-expand","aria-hidden":"true",children:"+"})]})}),r&&t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-http-modal-backdrop",onClick:()=>n(!1),children:(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal",onClick:d=>d.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-http-modal-header-main",children:[(0,f.jsx)("span",{className:"vf-editor-chat-http-pill",children:e.exchange.request.method}),(0,f.jsx)("span",{className:"vf-editor-chat-http-modal-url",children:a}),(0,f.jsxs)("span",{className:"vf-editor-chat-http-status","data-error":c?"true":"false","data-success":u?"true":"false",children:[e.exchange.result.status,e.exchange.result.statusText?` ${e.exchange.result.statusText}`:""]})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-http-modal-close",onClick:()=>n(!1),"aria-label":"Close HTTP details",children:"\xD7"})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-http-card-body is-modal",children:[e.exchange.explanation?(0,f.jsx)("div",{className:"vf-editor-chat-http-note",children:e.exchange.explanation}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"URL"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:a})]}),i?(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Request"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:i})]}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Response"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:e.exchange.result.error||s||"(empty)"})]}),Object.keys(e.exchange.result.headers).length?(0,f.jsxs)("div",{className:"vf-editor-chat-http-block",children:[(0,f.jsx)("div",{className:"vf-editor-chat-http-label",children:"Headers"}),(0,f.jsx)("pre",{className:"vf-editor-chat-http-pre",children:Uf(e.exchange.result.headers)})]}):null]})]})}),document.body):null]})}function bR(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function SS(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}function Or(e){return(0,f.jsxs)("div",{className:"vf-editor-chat-json-line",style:{paddingLeft:`${e.depth*18+12}px`},children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-copy","aria-label":"Copy line",title:"Copy line",onClick:()=>e.onCopy(e.text),children:(0,f.jsx)(yS,{})}),(0,f.jsx)("span",{className:"vf-editor-chat-json-line-text",children:e.text})]})}function dS(e){let t=e.value,n=e.isLast?"":",";if(Array.isArray(t)){let r=e.path,o=e.collapsedPaths.has(r),i=`${e.linePrefix??""}[`;return t.length?o?(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Expand JSON block",children:(0,f.jsx)(Df,{open:!1})}),(0,f.jsx)(Or,{text:`${e.linePrefix??""}[ \u2026 ]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(r),"aria-label":"Collapse JSON block",children:(0,f.jsx)(Df,{open:!0})}),(0,f.jsx)(Or,{text:i,depth:e.depth,onCopy:e.onCopy})]}),t.map((s,a)=>(0,f.jsx)(dS,{value:s,depth:e.depth+1,path:`${r}.${a}`,isLast:a===t.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${r}:${a}`)),(0,f.jsx)(Or,{text:`]${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsx)(Or,{text:`${e.linePrefix??""}[]${n}`,depth:e.depth,onCopy:e.onCopy})}if(t&&typeof t=="object"){let r=Object.entries(t),o=e.path,i=e.collapsedPaths.has(o),s=`${e.linePrefix??""}{`;return r.length?i?(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Expand JSON block",children:(0,f.jsx)(Df,{open:!1})}),(0,f.jsx)(Or,{text:`${e.linePrefix??""}{ \u2026 }${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsxs)("div",{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toggle-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-toggle-icon",onClick:()=>e.togglePath(o),"aria-label":"Collapse JSON block",children:(0,f.jsx)(Df,{open:!0})}),(0,f.jsx)(Or,{text:s,depth:e.depth,onCopy:e.onCopy})]}),r.map(([a,l],c)=>{let u=`${JSON.stringify(a)}: `;return l&&typeof l=="object"?(0,f.jsx)(dS,{value:l,depth:e.depth+1,linePrefix:u,path:`${o}.${a}`,isLast:c===r.length-1,collapsedPaths:e.collapsedPaths,togglePath:e.togglePath,onCopy:e.onCopy},`${o}:${a}`):(0,f.jsx)(Or,{text:`${u}${bR(l)}${c===r.length-1?"":","}`,depth:e.depth+1,onCopy:e.onCopy},`${o}:${a}`)}),(0,f.jsx)(Or,{text:`}${n}`,depth:e.depth,onCopy:e.onCopy})]}):(0,f.jsx)(Or,{text:`${e.linePrefix??""}{}${n}`,depth:e.depth,onCopy:e.onCopy})}return(0,f.jsx)(Or,{text:`${e.linePrefix??""}${bR(t)}${n}`,depth:e.depth,onCopy:e.onCopy})}function qR(e){let[t,n]=(0,k.useState)(new Set),[r,o]=(0,k.useState)(""),i=a=>{n(l=>{let c=new Set(l);return c.has(a)?c.delete(a):c.add(a),c})},s=async a=>{try{await SS(a),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1400)};return(0,f.jsxs)("div",{className:"vf-editor-chat-json-viewer",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-toolbar",children:[(0,f.jsx)("span",{className:"vf-editor-chat-json-file",children:e.storageKey}),(0,f.jsx)("span",{className:"vf-editor-chat-json-copy-state","data-state":r,children:r==="done"?"Copied line":r==="error"?"Copy failed":"Hover a line to copy"})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-scroll",children:(0,f.jsx)(dS,{value:e.value,depth:0,path:"root",collapsedPaths:t,togglePath:i,onCopy:s})})]})}function GF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=BR(e.artifact.url,`${e.artifact.label}.json`),s=Uf(e.data);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await SS(s),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":"Copy JSON","aria-label":r==="done"?"JSON copied":r==="error"?"Unable to copy JSON":"Copy JSON",children:(0,f.jsx)(yS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:i,title:"Download JSON","aria-label":"Download JSON",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw JSON","aria-label":"Open raw JSON",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close JSON preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,f.jsx)(qR,{value:e.data,storageKey:e.artifact.label})})]})}),document.body):null}function VF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),d=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).json();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load JSON artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&d()},h=()=>{d(),o(!0)};return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:"JSON result"}),(0,f.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview JSON"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,f.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,f.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading JSON\u2026"}):a?(0,f.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,f.jsx)(qR,{value:i,storageKey:e.artifact.label}):null}):null]}),r&&i!==null?(0,f.jsx)(GF,{artifact:e.artifact,data:i,onClose:()=>o(!1)}):null]})}function YR(e){return e.format==="markdown"?(0,f.jsx)("div",{className:"vf-editor-chat-doc-markdown",dangerouslySetInnerHTML:{__html:UR(e.text)}}):(0,f.jsx)("pre",{className:"vf-editor-chat-doc-pre",children:e.text})}function qF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(""),i=e.artifact.format==="markdown"?".md":".txt",s=BR(e.artifact.url,`${e.artifact.label}${i}`);(0,k.useEffect)(()=>{n(!0)},[]);let a=async()=>{try{await SS(e.text),o("done")}catch{o("error")}window.setTimeout(()=>o(""),1600)};return(0,k.useEffect)(()=>{let l=c=>{c.key==="Escape"&&e.onClose()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e]),t?(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-chat-media-modal-backdrop",onClick:e.onClose,children:(0,f.jsxs)("div",{className:"vf-editor-chat-json-modal",onClick:l=>l.stopPropagation(),children:[(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-header",children:[(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-link",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",children:e.artifact.label}),(0,f.jsxs)("div",{className:"vf-editor-chat-media-modal-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control","data-state":r,onClick:()=>{a()},title:r==="done"?"Copied":r==="error"?"Copy failed":e.artifact.format==="markdown"?"Copy markdown":"Copy text","aria-label":r==="done"?"Document copied":r==="error"?"Unable to copy document":e.artifact.format==="markdown"?"Copy markdown":"Copy text",children:(0,f.jsx)(yS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,download:s,title:e.artifact.format==="markdown"?"Download markdown":"Download text","aria-label":e.artifact.format==="markdown"?"Download markdown":"Download text",children:(0,f.jsx)(hS,{})}),(0,f.jsx)("a",{className:"vf-editor-chat-media-modal-control",href:e.artifact.url,target:"_blank",rel:"noopener noreferrer",title:"Open raw file","aria-label":"Open raw file",children:(0,f.jsx)(gS,{})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-media-modal-control",onClick:e.onClose,"aria-label":"Close document preview",title:"Close",children:"\xD7"})]})]}),(0,f.jsx)("div",{className:"vf-editor-chat-json-modal-body",children:(0,f.jsx)("div",{className:"vf-editor-chat-doc-viewer",children:(0,f.jsx)(YR,{text:e.text,format:e.artifact.format})})})]})}),document.body):null}function YF(e){let[t,n]=(0,k.useState)(!1),[r,o]=(0,k.useState)(!1),[i,s]=(0,k.useState)(null),[a,l]=(0,k.useState)(null),[c,u]=(0,k.useState)(!1),d=async()=>{if(!(i!==null||c)){u(!0),l(null);try{let _=await(await fetch(e.artifact.url,{credentials:"omit"})).text();s(_)}catch(y){l(y instanceof Error?y.message:"Unable to load document artifact.")}finally{u(!1)}}},p=()=>{let y=!t;n(y),y&&d()},h=()=>{d(),o(!0)};return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-head",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-chat-json-card-kicker",children:e.artifact.format==="markdown"?"Markdown result":"Text result"}),(0,f.jsx)("div",{className:"vf-editor-chat-json-card-title",children:e.artifact.label})]}),(0,f.jsxs)("div",{className:"vf-editor-chat-json-card-actions",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action",onClick:p,children:t?"Hide preview":"Preview"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-json-card-action is-strong",onClick:h,children:"Open"})]})]}),t?(0,f.jsx)("div",{className:"vf-editor-chat-json-card-body",children:c?(0,f.jsx)("div",{className:"vf-editor-chat-json-state",children:"Loading document\u2026"}):a?(0,f.jsx)("div",{className:"vf-editor-chat-json-state is-error",children:a}):i!==null?(0,f.jsx)("div",{className:"vf-editor-chat-doc-viewer is-inline",children:(0,f.jsx)(YR,{text:i,format:e.artifact.format})}):null}):null]}),r&&i!==null?(0,f.jsx)(qF,{artifact:e.artifact,text:i,onClose:()=>o(!1)}):null]})}var KF=(0,k.memo)(function(t){let n=t.message.role==="assistant",r=t.message.text.trim().length>0,o=r?UR(t.message.text):"",[i,s]=(0,k.useState)(null),a=t.message.attachments.filter($f),l=t.message.attachments.filter(lS),c=t.message.attachments.filter(_=>!$f(_)&&!lS(_)),u=r?iF(t.message.text,t.message.attachments.map(_=>_.viewUrl)):[],d=u.filter(_=>_.kind==="image"),p=u.filter(_=>_.kind==="video"),h=(t.message.httpExchanges??[]).flatMap(_=>{let T=Hi(_.result.body);return T?$R(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T),y=(t.message.httpExchanges??[]).flatMap(_=>{let T=Hi(_.result.body);return T?zR(T):[]}).filter((_,T,g)=>g.findIndex(S=>S.url===_.url)===T);return(0,f.jsxs)("div",{className:`vf-editor-chat-message ${n?"is-assistant":"is-user"}`,children:[(0,f.jsx)("div",{className:"vf-editor-chat-message-meta",children:n?"Copilot":"You"}),(0,f.jsxs)("div",{className:"vf-editor-chat-bubble","data-pending":t.message.isPending?"true":"false",children:[t.message.attachments.length?(0,f.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[c.map(_=>(0,f.jsx)("div",{className:"vf-editor-chat-message-attachment-row",children:(0,f.jsx)("a",{className:"vf-editor-chat-message-preview-link",href:_.viewUrl,target:"_blank",rel:"noopener noreferrer",children:(0,f.jsx)(BF,{attachment:_})})},_.id)),(0,f.jsx)(xR,{previews:a.map(_=>({kind:"image",url:_.viewUrl,label:_.fileName})),onOpenModal:(_,T)=>s({preview:_,gallery:T})}),l.map(_=>(0,f.jsx)(RR,{preview:{kind:"video",url:_.viewUrl,label:_.fileName},onOpenModal:T=>s({preview:T,gallery:[T]})},_.id))]}):null,t.message.statusText?(0,f.jsxs)("div",{className:"vf-editor-chat-message-status","aria-live":"polite",children:[(0,f.jsx)("span",{className:"vf-editor-chat-status-dot"}),t.message.statusText]}):null,t.message.httpExchanges?.length?(0,f.jsx)("div",{className:"vf-editor-chat-http-list",children:t.message.httpExchanges.map((_,T)=>(0,f.jsx)(WF,{exchange:_},`${_.request.method}:${_.request.url}:${T}`))}):null,r?(0,f.jsx)("div",{className:"vf-editor-chat-message-body",dangerouslySetInnerHTML:{__html:o}}):t.message.isPending?(0,f.jsxs)("div",{className:"vf-editor-chat-message-loading","aria-hidden":"true",children:[(0,f.jsx)("span",{}),(0,f.jsx)("span",{}),(0,f.jsx)("span",{})]}):null,u.length?(0,f.jsxs)("div",{className:"vf-editor-chat-message-attachments",children:[(0,f.jsx)(xR,{previews:d,onOpenModal:(_,T)=>s({preview:_,gallery:T})}),p.map(_=>(0,f.jsx)(RR,{preview:_,onOpenModal:T=>s({preview:T,gallery:[T]})},_.url))]}):null,h.length?(0,f.jsx)("div",{className:"vf-editor-chat-json-list",children:h.map(_=>(0,f.jsx)(VF,{artifact:_},_.key))}):null,y.length?(0,f.jsx)("div",{className:"vf-editor-chat-json-list",children:y.map(_=>(0,f.jsx)(YF,{artifact:_},_.key))}):null]}),i?(0,f.jsx)($F,{preview:i.preview,gallery:i.gallery,onClose:()=>s(null)}):null]})});function kR(e){if(!e||e<=0)return"Unknown size";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=10||r===0?n.toFixed(0):n.toFixed(1)} ${t[r]}`}function NR(e){return $f(e.file)?(0,f.jsx)("img",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,alt:e.file.fileName}):lS(e.file)?(0,f.jsx)("video",{className:"vf-editor-upload-file-thumb",src:e.file.viewUrl,muted:!0,playsInline:!0}):(0,f.jsx)("div",{className:"vf-editor-upload-file-icon","aria-hidden":"true",children:e.file.fileName.slice(0,1).toUpperCase()})}function fo(e){return e.split("/").map(t=>t.trim()).filter(Boolean).join("/")}function jf(e,t){return fo([e,t].filter(Boolean).join("/"))}function AR(e){let t=fo(e).split("/").filter(Boolean);return t.pop(),t.join("/")}function MR(e){return fo(e).split("/").filter(Boolean).at(-1)||"All files"}function JF(e){let t=fo(e.currentFolder),n=t?`${t}/`:"",r=new Map;for(let o of e.folders){let i=fo(o);if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,jf(t,a))}for(let o of e.files){let i=fo(o.folderPath??"");if(!i||t&&i===t||!i.startsWith(n))continue;let a=i.slice(n.length).split("/")[0];a&&r.set(a,jf(t,a))}return Array.from(r.entries()).map(([o,i])=>({name:o,path:i})).sort((o,i)=>o.name.localeCompare(i.name))}function aS(e){return e.name==="share"?(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M14 4h6v6"}),(0,f.jsx)("path",{d:"M10 14 20 4"}),(0,f.jsx)("path",{d:"M20 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4"})]}):e.name==="link"?(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M10 13a5 5 0 0 0 7.07 0l2.12-2.12a5 5 0 0 0-7.07-7.07L11 4.93"}),(0,f.jsx)("path",{d:"M14 11a5 5 0 0 0-7.07 0L4.81 13.12a5 5 0 0 0 7.07 7.07L13 19.07"})]}):(0,f.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[(0,f.jsx)("path",{d:"M3 6h18"}),(0,f.jsx)("path",{d:"M8 6V4h8v2"}),(0,f.jsx)("path",{d:"M19 6 18 20H6L5 6"}),(0,f.jsx)("path",{d:"M10 11v5"}),(0,f.jsx)("path",{d:"M14 11v5"})]})}function XF(e){let[t,n]=(0,k.useState)("my-files"),[r,o]=(0,k.useState)([]),[i,s]=(0,k.useState)([]),[a,l]=(0,k.useState)([]),[c,u]=(0,k.useState)(()=>new Set),[d,p]=(0,k.useState)([]),[h,y]=(0,k.useState)([]),[_,T]=(0,k.useState)(()=>new Set),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(!1),[M,A]=(0,k.useState)(""),[I,N]=(0,k.useState)(null),[U,x]=(0,k.useState)(null),[$,W]=(0,k.useState)(null),[ye,K]=(0,k.useState)(null),[et,pe]=(0,k.useState)(null),fe=(0,k.useRef)(null),D=(0,k.useRef)(null),Se=(0,k.useMemo)(()=>{let P=d.map(ne=>({...ne,recentSource:"generated"}));return[...h.map(ne=>({...ne,recentSource:"temporary"})),...P].sort((ne,ae)=>{let we=ne.createdAt?Date.parse(ne.createdAt):0;return(ae.createdAt?Date.parse(ae.createdAt):0)-we})},[d,h]),J=t==="upload"?r:t==="my-files"?i.filter(P=>c.has(P.id)):t==="recents"?Se.filter(P=>_.has(P.id)):[];async function le(){let P=await vF(e.apiKey);s(P.attachments),l(P.folders)}async function Ie(P){R(!0);try{let[F,ne]=P?[await _R(e.apiKey,P),null]:await Promise.all([_R(e.apiKey),EF(e.apiKey)]);p(ae=>P?[...ae,...F.media]:F.media),ne&&y(ne.files),S(F.nextCursor),P||T(new Set)}finally{R(!1)}}(0,k.useEffect)(()=>{e.open&&(K(null),W(null),le().catch(P=>K(P instanceof Error?P.message:"Unable to load My Files.")),Ie().catch(P=>K(P instanceof Error?P.message:"Unable to load recent media.")))},[e.open]);function _e(){o([]),u(new Set),T(new Set),W(null),K(null),N(null),x(null),e.onClose()}async function ut(P){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(P);else{let F=document.createElement("textarea");F.value=P,F.style.position="fixed",F.style.opacity="0",document.body.appendChild(F),F.focus(),F.select(),document.execCommand("copy"),document.body.removeChild(F)}W("File URL copied.")}catch{K("Unable to copy file URL.")}}async function Xe(P,F){if(!P.length)return;K(null);let ne=[];for(let ae of P)try{if(W(`Uploading ${ae.name}...`),F==="upload"){let St=await GR({apiKey:e.apiKey,file:ae,folderPath:LR}),Z=await WR({attachment:St,file:ae,currentInlineBytes:jR([...r,...ne])});ne.push(Z);continue}let we=await _F({apiKey:e.apiKey,file:ae,folderPath:M,maxBytes:PR,limitLabel:"50 MB"});ne.push(we)}catch(we){K(we instanceof Error?we.message:"Upload failed.")}F==="upload"?(o(ae=>[...ae,...ne]),await Ie().catch(ae=>K(ae instanceof Error?ae.message:"Unable to refresh recent files."))):F==="my-files"&&(await le(),u(ae=>new Set([...ae,...ne.map(we=>we.id)]))),ne.length&&W(`${ne.length} file${ne.length===1?"":"s"} uploaded.`)}async function Yt(P,F){let ne=F==="my-files"?`/api/v1/user/me/attachments/${encodeURIComponent(P.id)}`:`/api/v1/user/me/temporary-files/${encodeURIComponent(P.id)}`,ae=await fetch(ne,{method:"DELETE",headers:ct(e.apiKey,"application/json")}),we=await ae.json().catch(()=>({}));if(!ae.ok)throw new Error(we.error||"Unable to delete file.");F==="my-files"&&(s(St=>St.filter(Z=>Z.id!==P.id)),u(St=>{let Z=new Set(St);return Z.delete(P.id),Z})),pe(null),W("File deleted.")}async function dt(P){if(P!=="my-files"||!U||U.mode!=="create")return;let F=jf(U.baseFolder,U.value);if(!F){K("Choose a folder name.");return}let ne=await fetch("/api/v1/user/me/attachments/folders",{method:"POST",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({folder_path:F})}),ae=await ne.json().catch(()=>({}));if(!ne.ok){K(ae.error||"Unable to create folder.");return}l(we=>Array.from(new Set([...we,F])).sort()),x(null),W("Folder created.")}async function an(P,F){if(P!=="my-files"||!U||U.mode!=="rename")return;let ne=U.value.trim(),ae=jf(AR(F),ne);if(!ae||ae===F)return;let we=await fetch("/api/v1/user/me/attachments/folders",{method:"PATCH",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({from_folder_path:F,to_folder_path:ae})}),St=await we.json().catch(()=>({}));if(!we.ok){K(St.error||"Unable to rename folder.");return}A(Z=>Z===F||Z.startsWith(`${F}/`)?`${ae}${Z.slice(F.length)}`:Z),await le(),N(null),x(null),W("Folder renamed.")}async function Tn(P,F){if(P!=="my-files")return;let ne=await fetch("/api/v1/user/me/attachments/folders",{method:"DELETE",headers:ct(e.apiKey,"application/json"),body:JSON.stringify({folder_path:F})}),ae=await ne.json().catch(()=>({}));if(!ne.ok){K(ae.error||"Unable to delete folder.");return}A(we=>we===F||we.startsWith(`${F}/`)?AR(F):we),await le(),N(null),x(null),W("Folder deleted.")}function On(P){let F=a,ne=i,ae=M,we=A,St=JF({folders:F,files:ne,currentFolder:ae}),Z=fo(ae).split("/").filter(Boolean);return(0,f.jsxs)("div",{className:"vf-editor-upload-browser",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-browser-toolbar",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-breadcrumb","aria-label":"Current folder",children:[(0,f.jsx)("button",{type:"button","data-current":!ae,onClick:()=>we(""),children:"files"}),Z.map((Fe,me)=>{let Ve=Z.slice(0,me+1).join("/");return(0,f.jsxs)("span",{className:"vf-editor-upload-breadcrumb-segment",children:[(0,f.jsx)("span",{"aria-hidden":"true",children:"/"}),(0,f.jsx)("button",{type:"button","data-current":Ve===ae,onClick:()=>we(Ve),children:Fe})]},Ve)})]}),(0,f.jsx)("button",{type:"button",onClick:()=>x({mode:"create",scope:"my-files",baseFolder:ae,value:""}),children:"New folder"})]}),St.length?(0,f.jsx)("div",{className:"vf-editor-upload-folder-grid",children:St.map(Fe=>(0,f.jsxs)("article",{className:"vf-editor-upload-folder-row",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-folder-open",onClick:()=>we(Fe.path),children:[(0,f.jsx)("span",{className:"vf-editor-upload-folder-icon","aria-hidden":"true"}),(0,f.jsx)("span",{children:Fe.name})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-folder-menu-button","aria-label":`Folder actions for ${Fe.name}`,onClick:()=>N(I===Fe.path?null:Fe.path),children:"..."}),I===Fe.path?(0,f.jsxs)("div",{className:"vf-editor-upload-folder-menu",children:[(0,f.jsx)("button",{type:"button",onClick:()=>x({mode:"rename",scope:"my-files",folderPath:Fe.path,value:MR(Fe.path)}),children:"Rename"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>x({mode:"delete",scope:"my-files",folderPath:Fe.path,value:""}),children:"Delete"})]}):null]},Fe.path))}):null]})}function po(P,F){let ne=F==="my-files"?c.has(P.id):F==="recents"?_.has(P.id):!1,ae="s3Url"in P&&P.s3Url?P.s3Url:P.viewUrl;return(0,f.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":ne?"true":"false",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-file-select",onClick:()=>{if(F==="temporary"){ut(ae);return}(F==="recents"?T:u)(St=>{let Z=new Set(St);return Z.has(P.id)?Z.delete(P.id):Z.add(P.id),Z})},children:[(0,f.jsx)(NR,{file:P}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,f.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-meta",children:[kR(P.sizeBytes),P.folderPath?` \xB7 ${P.folderPath}`:""]})]})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-file-actions",children:[F==="my-files"||F==="recents"?(0,f.jsx)("span",{className:"vf-editor-upload-selection-indicator","data-selected":ne?"true":"false","aria-hidden":"true",children:ne?"\u2713":""}):null,(0,f.jsx)("a",{href:P.viewUrl,target:"_blank",rel:"noreferrer","aria-label":`View ${P.fileName}`,children:(0,f.jsx)(aS,{name:"share"})}),(0,f.jsx)("button",{type:"button","aria-label":`Copy URL for ${P.fileName}`,onClick:()=>{ut(ae)},children:(0,f.jsx)(aS,{name:"link"})}),F==="recents"?null:(0,f.jsx)("button",{type:"button","aria-label":`Delete ${P.fileName}`,onClick:()=>pe(et===P.id?null:P.id),children:(0,f.jsx)(aS,{name:"trash"})})]}),F!=="recents"&&et===P.id?(0,f.jsxs)("div",{className:"vf-editor-upload-popconfirm",children:[(0,f.jsx)("span",{children:"Delete this file?"}),(0,f.jsx)("button",{type:"button",onClick:()=>pe(null),children:"Cancel"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Yt(P,F)},children:"Delete"})]}):null]},P.id)}function mo(){if(!U)return null;let P=U.mode==="create"?"New folder":U.mode==="rename"?"Rename folder":"Delete folder",F=U.mode==="delete"?U.folderPath:"";return(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog",role:"dialog","aria-label":P,children:[(0,f.jsx)("div",{className:"vf-editor-upload-folder-dialog-title",children:P}),U.mode==="delete"?(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog-copy",children:["Delete ",(0,f.jsx)("strong",{children:F})," and all files inside it?"]}):(0,f.jsx)("input",{value:U.value,autoFocus:!0,placeholder:"folder-name",onChange:ne=>x({...U,value:ne.target.value}),onKeyDown:ne=>{ne.key==="Enter"&&(ne.preventDefault(),U.mode==="create"?dt(U.scope):an(U.scope,U.folderPath))}}),(0,f.jsxs)("div",{className:"vf-editor-upload-folder-dialog-actions",children:[(0,f.jsx)("button",{type:"button",onClick:()=>x(null),children:"Cancel"}),U.mode==="create"?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{dt(U.scope)},children:"Create"}):U.mode==="rename"?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",onClick:()=>{an(U.scope,U.folderPath)},children:"Rename"}):(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>{Tn(U.scope,U.folderPath)},children:"Delete"})]})]})}if(!e.open)return null;let Gi=i.filter(P=>fo(P.folderPath??"")===fo(M));return(0,ji.createPortal)((0,f.jsx)("div",{className:"vf-editor-upload-drawer-backdrop",children:(0,f.jsxs)("aside",{className:"vf-editor-upload-drawer","aria-label":"Upload drawer",children:[(0,f.jsxs)("div",{className:"vf-editor-upload-header",children:[(0,f.jsxs)("div",{children:[(0,f.jsx)("div",{className:"vf-editor-upload-title",children:"Upload"}),(0,f.jsx)("div",{className:"vf-editor-upload-subtitle",children:"Upload, attach, and copy file URLs."})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-close","aria-label":"Close upload drawer",onClick:_e,children:"\xD7"})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-tabs",role:"tablist",children:[(0,f.jsx)("button",{type:"button","data-active":t==="upload",onClick:()=>n("upload"),children:"Upload file"}),(0,f.jsx)("button",{type:"button","data-active":t==="my-files",onClick:()=>n("my-files"),children:"My Files"}),(0,f.jsx)("button",{type:"button","data-active":t==="recents",onClick:()=>n("recents"),children:"Recents"})]}),(0,f.jsxs)("div",{className:"vf-editor-upload-body",children:[ye?(0,f.jsx)("div",{className:"vf-editor-upload-status","data-tone":"error",children:ye}):null,$?(0,f.jsx)("div",{className:"vf-editor-upload-status",children:$}):null,mo(),t==="upload"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>fe.current?.click(),children:["Upload files to chat",(0,f.jsx)("span",{children:"Stored in Recents and attached after Confirm. Images get compressed inline previews when possible; other files attach by URL. Max 100 MB each."})]}),(0,f.jsx)("input",{ref:fe,type:"file",multiple:!0,hidden:!0,onChange:P=>{Xe(Array.from(P.target.files??[]),"upload"),P.target.value=""}}),(0,f.jsx)("div",{className:"vf-editor-upload-list",children:r.map(P=>(0,f.jsxs)("article",{className:"vf-editor-upload-file-card","data-selected":"true",children:[(0,f.jsx)(NR,{file:P}),(0,f.jsxs)("span",{className:"vf-editor-upload-file-main",children:[(0,f.jsx)("span",{className:"vf-editor-upload-file-name",children:P.fileName}),(0,f.jsx)("span",{className:"vf-editor-upload-file-meta",children:kR(P.sizeBytes)})]}),(0,f.jsx)("button",{type:"button",onClick:()=>o(F=>F.filter(ne=>ne.id!==P.id)),children:"\xD7"})]},P.id))})]}):t==="my-files"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-upload-drop",onClick:()=>D.current?.click(),children:["Add to My Files",(0,f.jsxs)("span",{children:["Uploads into ",MR(M)," and auto-selects. Max 50 MB each."]})]}),(0,f.jsx)("input",{ref:D,type:"file",multiple:!0,hidden:!0,onChange:P=>{Xe(Array.from(P.target.files??[]),"my-files"),P.target.value=""}}),On("my-files"),(0,f.jsx)("div",{className:"vf-editor-upload-list",children:Gi.length?Gi.map(P=>po(P,"my-files")):(0,f.jsx)("div",{className:"vf-editor-upload-empty",children:"No files in this folder."})})]}):t==="recents"?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{className:"vf-editor-upload-list",children:Se.length?Se.map(P=>po(P,"recents")):(0,f.jsx)("div",{className:"vf-editor-upload-empty",children:E?"Loading recent files...":"No recent files yet."})}),g?(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-more",disabled:E,onClick:()=>{Ie(g).catch(P=>K(P instanceof Error?P.message:"Unable to load more recent media."))},children:E?"Loading...":"Load more generated media"}):null]}):null]}),(0,f.jsxs)("div",{className:"vf-editor-upload-footer",children:[(0,f.jsx)("button",{type:"button",onClick:_e,children:"Cancel"}),(0,f.jsxs)("div",{className:"vf-editor-upload-footer-confirm",children:[(0,f.jsxs)("span",{children:[J.length," file",J.length===1?"":"s"," selected"]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-upload-confirm",disabled:!J.length,onClick:()=>{e.onConfirm(J),_e()},children:"Confirm"})]})]})]})}),document.body)}function KR({boot:e}){let t=e.template.templateId==="chat-brainstorm",n=t&&e.template.persistentHistorySidebar===!0,r=(0,k.useMemo)(()=>NF(e.template.templateId),[e.template.templateId]),o=(0,k.useMemo)(()=>AF(),[]),i=(0,k.useRef)(null),s=(0,k.useRef)(null),a=(0,k.useRef)(!0),l=(0,k.useRef)(!1),c=(0,k.useRef)(null),u=(0,k.useRef)(null),d=(0,k.useRef)(new Map),p=(0,k.useRef)({nextAvailableAt:0}),h=(0,k.useRef)([]),y=(0,k.useRef)(new Set),[_,T]=(0,k.useState)([]),[g,S]=(0,k.useState)(null),[E,R]=(0,k.useState)(null),[M,A]=(0,k.useState)(null),[I,N]=(0,k.useState)(""),[U,x]=(0,k.useState)([]),[$,W]=(0,k.useState)(null),[ye,K]=(0,k.useState)(null),[et,pe]=(0,k.useState)(null),[fe,D]=(0,k.useState)(!1),[Se,J]=(0,k.useState)(!1),[le,Ie]=(0,k.useState)(!1),[_e,ut]=(0,k.useState)(!1),[Xe,Yt]=(0,k.useState)(!1),[dt,an]=(0,k.useState)(null),[Tn,On]=(0,k.useState)(!1),[po,mo]=(0,k.useState)(null),[Gi,P]=(0,k.useState)(!1),[F,ne]=(0,k.useState)(()=>{let m=typeof window<"u"?window.__vidfarmEditorTracers:null;if(m)return m.get();if(typeof window<"u"){let v=Hf();if(v.length)return v}return tr(e.template.tracers||[])}),ae=(0,k.useMemo)(()=>{if(!e.threadsUrl)return null;let m=new URL(e.threadsUrl,window.location.origin);return t||m.searchParams.set("template_id",e.template.templateId),m.searchParams.set("include_messages","false"),m.searchParams.set("limit",t?"200":"50"),m.toString()},[e.template.templateId,e.threadsUrl,t]),we=m=>e.threadsUrl?new URL(`${e.threadsUrl.replace(/\/$/,"")}/${encodeURIComponent(m)}`,window.location.origin).toString():null;(0,k.useEffect)(()=>{let m=DF(o?.getItem(r.threads)??null,e.template.templateId),v=o?.getItem(r.activeThread)??null,w=ER(),b=window.__vidfarmEditorTracers?.get()??Hf(),B=w&&!m.some(ce=>ce.id===w)?[{id:w,templateId:e.template.templateId,title:"Loading chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),lastMessageAt:null,messageCount:0,tracers:b,hiddenFromView:!1,messages:[]},...m]:m,Y=B.filter(ce=>!ce.hiddenFromView),j=Y.find(ce=>Tc(ce,b));h.current=B,T(B),w&&Y.some(ce=>ce.id===w)?S(w):v&&Y.some(ce=>ce.id===v)&&(!b.length||Y.some(ce=>ce.id===v&&Tc(ce,b)))?S(v):S(j?.id??Y[0]?.id??null),D(!0)},[e.template.templateId,o,r]),(0,k.useEffect)(()=>{if(!e.vidfarmApiKey||!ae)return;let m=new AbortController;return(async()=>{try{let v=[],w=null,b=new Set;do{let B=new URL(ae);w&&B.searchParams.set("cursor",w);let Y=await fetch(B.toString(),{method:"GET",headers:ct(e.vidfarmApiKey),signal:m.signal});if(!Y.ok)return;let j=await Y.json().catch(()=>null);Array.isArray(j?.threads)&&v.push(...j.threads.map(he=>IR(he,e.template.templateId)).filter(he=>!!he));let ce=typeof j?.next_cursor=="string"&&j.next_cursor?j.next_cursor:null;!ce||b.has(ce)?w=null:(b.add(ce),w=ce)}while(w&&!m.signal.aborted);if(!v.length)return;T(B=>{let Y=wR(B,v);return h.current=Y,Y}),S(B=>B&&h.current.some(Y=>Y.id===B)?B:v[0]?.id??B)}catch(v){if(v instanceof DOMException&&v.name==="AbortError")return}})(),()=>{m.abort()}},[e.template.templateId,e.vidfarmApiKey,ae]),(0,k.useEffect)(()=>{h.current=_},[_]);let[St,Z]=(0,k.useState)(()=>{if(typeof window>"u")return null;try{return new URL(window.location.href).searchParams.get("fork")}catch{return null}});(0,k.useEffect)(()=>{let m=()=>{try{Z(new URL(window.location.href).searchParams.get("fork"))}catch{Z(null)}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[]);async function Fe(m){if(!e.vidfarmApiKey){mo("Sign in to see forks.");return}if(!Tn&&!(!m?.force&&dt!==null)){On(!0),mo(null);try{let v=await fetch("/api/v1/compositions",{method:"GET",headers:ct(e.vidfarmApiKey)});if(!v.ok){mo(v.status===401?"Sign in to see forks.":`Failed to load forks (${v.status}).`),an([]);return}let w=await v.json().catch(()=>null),B=(Array.isArray(w?.forks)?w.forks:[]).map(Y=>{if(!Y||typeof Y!="object")return null;let j=Y,ce=typeof j.fork_id=="string"?j.fork_id:null;return ce?{forkId:ce,templateId:typeof j.template_id=="string"?j.template_id:null,parentForkId:typeof j.parent_fork_id=="string"?j.parent_fork_id:null,parentVersion:typeof j.parent_version=="number"?j.parent_version:null,title:typeof j.title=="string"?j.title:null,visibility:typeof j.visibility=="string"?j.visibility:null,latestVersion:typeof j.latest_version=="number"?j.latest_version:null,ownerCustomerId:typeof j.owner_customer_id=="string"?j.owner_customer_id:null,createdAt:typeof j.created_at=="string"?j.created_at:null,updatedAt:typeof j.updated_at=="string"?j.updated_at:null}:null}).filter(Y=>!!Y).filter(Y=>Y.templateId===e.template.templateId).sort((Y,j)=>String(j.updatedAt??"").localeCompare(String(Y.updatedAt??"")));an(B)}catch{mo("Could not load forks. Please try again."),an([])}finally{On(!1)}}}(0,k.useEffect)(()=>{Xe&&dt===null&&!Tn&&Fe()},[Xe]),(0,k.useEffect)(()=>{let m=window.__vidfarmEditorTracers;if(m)return ne(m.get()),m.subscribe(w=>ne(w));let v=()=>{let w=Hf();ne(w.length?w:tr(e.template.tracers||[]))};return v(),window.addEventListener("popstate",v),()=>{window.removeEventListener("popstate",v)}},[e.template.tracers]);let me=(0,k.useRef)(_),Ve=(0,k.useRef)(g);(0,k.useEffect)(()=>{me.current=_,Ve.current=g},[_,g]),(0,k.useEffect)(()=>{if(!fe)return;let m=window.setTimeout(()=>{try{o?.setItem(r.threads,JSON.stringify(TR(me.current,Ve.current)))}catch(v){console.warn("Unable to persist editor chat threads.",v)}},300);return()=>window.clearTimeout(m)},[g,o,fe,r,_]),(0,k.useEffect)(()=>{if(fe)try{g?o?.setItem(r.activeThread,g):o?.removeItem(r.activeThread)}catch(m){console.warn("Unable to persist active editor chat thread.",m)}},[g,o,fe,r]),(0,k.useEffect)(()=>{if(!fe||typeof window>"u")return;let m=new URL(window.location.href),v=m.searchParams.get("thread_id");if(g){if(v===g)return;m.searchParams.set("thread_id",g)}else{if(!v)return;m.searchParams.delete("thread_id")}window.history.replaceState({},"",m.toString())},[g,fe]);let re=(0,k.useMemo)(()=>_.find(m=>m.id===g)??null,[g,_]),Dn=(0,k.useMemo)(()=>_.find(m=>m.id===M?.threadId)??null,[M?.threadId,_]);(0,k.useEffect)(()=>{if(!fe||!e.vidfarmApiKey||!g)return;let m=h.current.find(j=>j.id===g);if(y.current.has(g))return;let v=ER();if(!!(m&&(m.messageCount??0)===0&&m.messages.length===0)){y.current.add(g);return}let b=we(g);if(!b)return;let B=new AbortController;return!m?.messages.length&&R(g),(async()=>{try{let j=await fetch(b,{method:"GET",headers:ct(e.vidfarmApiKey),signal:B.signal});if(!j.ok){let ue=!!(m&&g!==v),de=!!(m&&(m.messageCount??0)===0&&m.messages.length===0);j.status===404&&!ue&&!de&&W(`Chat ID ${g} was not found for this account.`),y.current.add(g);return}let ce=await j.json().catch(()=>null),he=ce?.thread?IR(ce.thread,e.template.templateId):null;if(!he)return;y.current.add(he.id),W(null),T(ue=>{let de=wR(ue,[he]);return h.current=de,de})}catch(j){if(j instanceof DOMException&&j.name==="AbortError")return}finally{B.signal.aborted||R(j=>j===g?null:j)}})(),()=>{B.abort(),R(j=>j===g?null:j)}},[g,e.vidfarmApiKey,e.threadsUrl,fe]),(0,k.useEffect)(()=>{if(!fe||re&&!re.hiddenFromView)return;let m=_.find(v=>!v.hiddenFromView&&Tc(v,F));S(m?.id??_.find(v=>!v.hiddenFromView)?.id??null)},[re,fe,_,F]);let qf=(0,k.useMemo)(()=>re?.tracers.length?re.tracers:F,[re?.tracers,F]),Yf=(0,k.useMemo)(()=>_.filter(m=>!m.hiddenFromView).sort((m,v)=>{let w=Tc(m,F),b=Tc(v,F);return w!==b?w?-1:1:Date.parse(v.updatedAt)-Date.parse(m.updatedAt)}),[_,F]),ES=qf[0]??null,Kf=re?.messages??[],TS=ye!==null,Jf=!!(g&&ye===g),IS=(0,k.useMemo)(()=>(I.trim()||U.length)&&!TS,[I,U.length,TS]);(0,k.useEffect)(()=>{!fe||!e.vidfarmApiKey||!re||!re.messages.length||gx(re)},[re,e.vidfarmApiKey,fe]);async function wc(m,v){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let w=we(m.id);w&&await fetch(w,{method:"PATCH",headers:ct(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:e.template.templateId,title:v?.title??m.title,tracers:v?.tracers??m.tracers,hidden_from_view:v?.hiddenFromView??m.hiddenFromView===!0,archived:v?.archived})}).catch(()=>{})}async function ZR(m){if(!e.vidfarmApiKey||!e.threadsUrl||!m.messages.length)return;let v=we(m.threadId);v&&await fetch(`${v}/exchanges`,{method:"POST",headers:ct(e.vidfarmApiKey,"application/json"),body:JSON.stringify({template_id:m.templateId??e.template.templateId,title:m.title||"New chat",tracers:m.tracers,messages:m.messages.map(w=>({id:w.id,role:w.role,text:w.text,attachments:w.attachments.map(b=>({id:b.id,fileName:b.fileName,contentType:b.contentType,viewUrl:b.viewUrl})),toolExchanges:w.toolExchanges,httpExchanges:w.httpExchanges?.map(Ic)}))})}).catch(()=>{})}async function ex(m){if(!e.vidfarmApiKey||!e.threadsUrl)return;let v=we(m);v&&await fetch(v,{method:"DELETE",headers:ct(e.vidfarmApiKey)}).catch(()=>{})}function wS(m){let v=new URL(window.location.href);m.length?v.searchParams.set("tracers",m.join(",")):v.searchParams.delete("tracers"),window.history.replaceState({},"",v.toString()),window.dispatchEvent(new CustomEvent("vidfarm:editor-tracers-changed",{detail:{tracers:m}}))}function fa(m){let v=tr(m),w=window.__vidfarmEditorTracers;if(w){w.set(v);return}ne(v),wS(v)}function CS(){let m=window.__vidfarmEditorTracers;if(m)return m.add();let v=LF(e.template.templateSlug,F);return fa([v,...F]),v}function RS(m){let v=window.__vidfarmEditorTracers?.get()??F,w=m?OF(m,v):null,b=window.__vidfarmEditorTracers;return b?b.add(w??void 0):w?(fa([w,...v.filter(B=>B!==w)]),w):CS()}function tx(m){let v=m.trim();if(!v)return;let w=window.__vidfarmEditorTracers;w?w.add(v):F.includes(v)||fa([v,...F]),re&&ft(re.id,b=>({...b,tracers:[v,...b.tracers.filter(B=>B!==v)],updatedAt:new Date().toISOString()}))}function nx(m){let v=window.__vidfarmEditorTracers;if(v){v.remove(m);return}let w=F.filter(b=>b!==m);fa(w)}(0,k.useEffect)(()=>{wS(F)},[F]),(0,k.useEffect)(()=>{let m=s.current;if(!m)return;let v=()=>{a.current=uF(m),a.current||(l.current=!1)};return v(),m.addEventListener("scroll",v,{passive:!0}),()=>{m.removeEventListener("scroll",v)}},[]),(0,k.useLayoutEffect)(()=>{let m=s.current;if(!m)return;let v=c.current!==g;c.current=g,(v||l.current||a.current)&&(m.scrollTo({top:m.scrollHeight,behavior:"auto"}),a.current=!0,l.current=!1)},[Kf,g]),(0,k.useEffect)(()=>()=>{u.current?.abortController.abort(),u.current=null;for(let m of d.current.values())m.timeoutId!==null&&window.clearTimeout(m.timeoutId),m.abortController?.abort();d.current.clear()},[]),(0,k.useEffect)(()=>{if(!M)return;let m=()=>A(null);return document.addEventListener("click",m),window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{document.removeEventListener("click",m),window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[M]),(0,k.useEffect)(()=>{let m=()=>{if(document.visibilityState!=="visible"||!navigator.onLine)return;let v=Date.now();for(let w of d.current.values())w.inFlight||w.nextPollAt!==null&&w.nextPollAt<=v&&w.runPoll&&Qf(w,w.runPoll,w.nextPollAt-v)};return window.addEventListener("online",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("online",m),document.removeEventListener("visibilitychange",m)}},[]);function rx(m){if(re)return re.id;let v=new Date().toISOString(),w=vR(),b={id:w,templateId:e.template.templateId,title:Of(m||""),createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:tr(F),messages:[]};return h.current=[b,...h.current],T(B=>[b,...B]),S(w),w}function Xf(m){let v=new Date().toISOString(),w=tr(m?.tracers??F),b=vR(),B={id:b,templateId:e.template.templateId,title:m?.title||"New chat",createdAt:v,updatedAt:v,lastMessageAt:null,messageCount:0,tracers:w,messages:[]};return h.current=[B,...h.current],T(Y=>[B,...Y]),m?.activate!==!1&&(S(b),N(""),x([]),W(null)),A(null),b}function xS(){Xf(),ut(!1)}function ox(m){let v=_.find(b=>b.id===m);if(!v||!window.confirm(`Delete conversation "${v.title}"?`))return;let w=_.filter(b=>b.id!==m);h.current=h.current.filter(b=>b.id!==m);for(let[b,B]of d.current.entries())B.threadId===m&&pa(b);T(w),g===m&&S(w[0]?.id??null),W(null),A(null),ex(m)}function ft(m,v){let w=UF(h.current.map(b=>b.id===m?v(b):b));h.current=w,T(w)}function ix(m,v){let w=tr(v);ft(m,B=>({...B,tracers:sS(B.tracers,w),updatedAt:new Date().toISOString()}));let b=h.current.find(B=>B.id===m);b&&wc({...b,tracers:sS(b.tracers,w),updatedAt:new Date().toISOString()},{tracers:sS(b.tracers,w)})}function bS(m,v){let w=m.trim();return w?h.current.find(b=>!b.hiddenFromView&&b.id!==v&&b.tracers.includes(w))?.id??null:null}function sx(m,v){let w=bS(m);return w||Xf({tracers:[m],title:v?.title||`Tracer ${m}`,activate:v?.activate??!1})}function ax(m){let v=m.toLowerCase();return/(?:own|separate|different|new)\s+(?:tracer\s+and\s+)?chat\s+threads?/.test(v)||/chat\s+threads?.{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)||/each.{0,80}(?:own|separate|different|new).{0,80}chat\s+threads?/.test(v)||/(?:own|separate|different|new)\s+tracers?/.test(v)||/(?:each|every|per|one\s+per).{0,80}(?:own|separate|different|new).{0,80}tracers?/.test(v)||/(?:own|separate|different|new)\s+tracers?.{0,80}(?:each|every|per|outputs?|pieces?|posts?|jobs?|generations?)/.test(v)||/(?:outputs?|pieces?|posts?|jobs?|generations?).{0,80}(?:own|separate|different|new)\s+tracers?/.test(v)}function lx(m){let v=bS(m.tracer,m.sourceThreadId);if(!v&&!m.shouldCreateThread)return null;let w=v??sx(m.tracer,{title:`Tracer ${m.tracer}`,activate:!1});if(!w||w===m.sourceThreadId)return null;let b=Bf("assistant"),B=new Date().toISOString(),Y=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?Lf(m.job):fR(m.job),j=m.job.status==="succeeded"||m.job.status==="failed"||m.job.status==="cancelled"?null:`Job ${m.job.job_id} is being tracked. ${Zf()}`,ce={id:b,role:"assistant",text:Y,attachments:[],httpExchanges:m.httpExchange?[m.httpExchange]:[],statusText:j,isPending:!1};ft(w,ue=>({...ue,updatedAt:B,messages:[...ue.messages,ce]}));let he=h.current.find(ue=>ue.id===w);return he&&ZR({threadId:w,templateId:he.templateId,title:he.title,tracers:he.tracers,messages:[ce]}),{threadId:w,messageId:b}}function cx(m){let v=_.find(B=>B.id===m);if(!v)return;let w=window.prompt("Thread tracers, comma separated",v.tracers.join(", "));if(w===null)return;let b=tr(w.split(","));ft(m,B=>({...B,tracers:b,updatedAt:new Date().toISOString()})),wc(v,{tracers:b}),A(null)}function ux(m){let v=_.find(B=>B.id===m);if(!v||!window.confirm(`Archive conversation "${v.title}"? Its tracer links will be prefixed with archived_.`))return;let b=tr(v.tracers.map(MF));ft(m,B=>({...B,tracers:b,updatedAt:new Date().toISOString()})),wc(v,{tracers:b,archived:!0}),A(null)}function dx(m){let v=_.find(b=>b.id===m);if(!(!v||!window.confirm(`Remove conversation "${v.title}" from this frontend view? The thread and tracer links stay available; Delete removes the thread completely.`))){for(let[b,B]of d.current.entries())B.threadId===m&&pa(b);if(ft(m,b=>({...b,hiddenFromView:!0,updatedAt:new Date().toISOString()})),g===m){let b=Yf.find(B=>B.id!==m);S(b?.id??null)}A(null),W(null),wc(v,{hiddenFromView:!0})}}async function fx(m){try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(m);else{let v=document.createElement("textarea");v.value=m,v.setAttribute("readonly",""),v.style.position="fixed",v.style.opacity="0",document.body.appendChild(v),v.select(),document.execCommand("copy"),document.body.removeChild(v)}W(null)}catch{W("Unable to copy chat ID.")}finally{A(null)}}function px(m,v){if(M?.threadId===m){A(null);return}let w=v.getBoundingClientRect(),b=148;A({threadId:m,top:w.bottom+6,left:Math.max(8,Math.min(window.innerWidth-b-8,w.right-b))})}function pa(m){let v=d.current.get(m);v&&(v.timeoutId!==null&&window.clearTimeout(v.timeoutId),v.abortController?.abort(),d.current.delete(m))}function ma(m,v,w){let b=d.current.get(m);b&&Qf(b,v,w)}function Qf(m,v,w){m.timeoutId!==null&&window.clearTimeout(m.timeoutId);let b=Math.max(gR,w);m.nextPollAt=Date.now()+b,m.timeoutId=window.setTimeout(()=>{m.timeoutId=null,v()},b)}function Vi(){return d.current.size>=mR?fF:pR}function qi(m=Vi()){if(m>=6e4){let v=Math.round(m/6e4);return`${v} min${v===1?"":"s"}`}return`${Math.round(m/1e3)}s`}function Zf(m=Vi()){return d.current.size>=mR?`Many renders are active, so the next check is in ${qi(m)}.`:`Checking again gently every ${qi(m)}.`}function mx(){let m=Vi();if(m===pR)return;let v=Date.now();for(let w of d.current.values()){if(w.inFlight||!w.runPoll)continue;(w.nextPollAt===null?0:w.nextPollAt-v)<m&&Qf(w,w.runPoll,m)}}function hx(m){let v=Math.max(m,p.current.nextAvailableAt);return p.current.nextAvailableAt=v+pF,v-m}function ep(m){let v=yR(m.threadId,m.assistantMessageId,m.jobId);if(d.current.has(v))return;d.current.set(v,{timeoutId:null,abortController:null,runPoll:null,inFlight:!1,nextPollAt:null,lastPollAt:null,attempts:0,threadId:m.threadId});let w=async()=>{let Y=d.current.get(v);if(!Y||Y.inFlight)return;let j=Date.now(),ce=Vi();if(Y.lastPollAt!==null&&j-Y.lastPollAt<ce){ma(v,w,ce-(j-Y.lastPollAt));return}if(Y.attempts>=hR){ft(m.threadId,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(de=>de.id===m.assistantMessageId?{...de,statusText:"Background polling stopped after multiple checks. Open the job route when you want to refresh again."}:de)})),pa(v);return}if(document.visibilityState!=="visible"||!navigator.onLine){ma(v,w,ce);return}let he=hx(Date.now());if(he>0){ma(v,w,he);return}Y.inFlight=!0,Y.lastPollAt=j,Y.nextPollAt=null,Y.attempts+=1,Y.abortController=new AbortController;try{ft(m.threadId,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===m.assistantMessageId?{...X,statusText:`Job ${m.jobId} is being tracked. ${Zf(ce)}`}:X)}));let ue=m.primitiveId||mF(m.sourceRequestUrl)?`/api/v1/primitives/jobs/${encodeURIComponent(m.jobId)}`:`/api/v1/templates/${encodeURIComponent(e.template.templateId)}/jobs/${encodeURIComponent(m.jobId)}`,de=await fetch(ue,{method:"GET",headers:ct(e.vidfarmApiKey),signal:Y.abortController.signal}),ln=await de.json().catch(()=>null),ha=Object.fromEntries(de.headers.entries()),G=Hi(ln);if(ft(m.threadId,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>{if(X.id!==m.assistantMessageId)return X;let Ee=dF(X.httpExchanges,Ic({explanation:`Automatic ${qi(ce)} job status check for ${m.jobId}`,pollJobId:m.jobId,pollMode:"automatic",request:{method:"GET",url:ue,headers:Object.fromEntries(ct(e.vidfarmApiKey).entries())},result:{status:de.status,statusText:de.statusText,headers:ha,body:ln}})),ke=G?G.status==="succeeded"?`Render ${G.job_id} succeeded.`:G.status==="failed"||G.status==="cancelled"?`Render ${G.job_id} ${G.status}.${G.error?.message?` ${G.error.message}`:""}`:`Render ${G.job_id} is ${G.status}. Next check in ${qi(ce)}.`:`Render ${m.jobId} checked. Next check in ${qi(ce)}.`;return{...X,httpExchanges:Ee,statusText:ke,text:G&&(G.status==="succeeded"||G.status==="failed"||G.status==="cancelled")?Ec(X.text,Lf(G)):X.text}})})),G&&(G.status==="succeeded"||G.status==="failed"||G.status==="cancelled")){pa(v);return}}catch(ue){if(ue instanceof DOMException&&ue.name==="AbortError")return;ft(m.threadId,de=>({...de,updatedAt:new Date().toISOString(),messages:de.messages.map(ln=>ln.id===m.assistantMessageId?{...ln,statusText:`Automatic polling paused after an error. It will retry in ${qi()}.`}:ln)}))}finally{let ue=d.current.get(v);if(!ue)return;ue.inFlight=!1,ue.abortController=null,ue.attempts<hR&&ue.timeoutId===null&&d.current.has(v)&&ma(v,w,Vi())}},b=d.current.get(v);b&&(b.runPoll=w),d.current.get(v)&&(ma(v,w,m.initialDelayMs??Vi()),mx())}function gx(m){for(let v of m.messages)if(!(v.role!=="assistant"||!v.httpExchanges?.length))for(let w of v.httpExchanges){if(w.request.method!=="POST")continue;let b=Hi(w.result.body),B=yR(m.id,v.id,b?.job_id??"");!b||ua(b.status)||d.current.has(B)||v.httpExchanges.some(j=>{let ce=Hi(j.result.body);return ce?.job_id===b.job_id&&ua(ce.status)})||ep({threadId:m.id,assistantMessageId:v.id,jobId:b.job_id,tracer:b.tracer,initialStatus:b.status,primitiveId:b.primitive_id,sourceRequestUrl:w.request.url,initialDelayMs:gR})}}async function tp(m){if(!m.length)return;W(null);let v=[],w=null;for(let b of m)try{let B=await GR({apiKey:e.vidfarmApiKey,file:b,folderPath:LR}),Y=await WR({attachment:B,file:b,currentInlineBytes:jR([...U,...v])});v.push(Y)}catch(B){w=B instanceof Error?B.message:"Unable to upload attachment."}w&&v.length===0&&W(w),v.length&&(x(b=>[...b,...v]),w&&W(w))}async function yx(m){let v=Array.from(m.target.files??[]);await tp(v),m.target.value=""}async function Sx(m){let v=Array.from(m.clipboardData.files??[]).filter(w=>w.size>0);v.length&&(m.preventDefault(),await tp(v))}async function _x(m){m.preventDefault(),J(!1);let v=Array.from(m.dataTransfer.files??[]).filter(w=>w.size>0);v.length&&await tp(v)}async function vx(m,v,w){let b=w??{},B=e.vidfarmApiKey,Y=window.location.origin,j=ct(B,"application/json"),ce=ct(B),he=X=>new Promise(Ee=>setTimeout(Ee,X)),ue=(X,Ee)=>{ft(m,ke=>({...ke,updatedAt:new Date().toISOString(),messages:ke.messages.map(Ne=>Ne.id===v?{...Ne,isPending:!1,statusText:X??Ne.statusText,text:Ee?Ec(Ne.text,Ee):Ne.text}:Ne)}))},de=async X=>{let Ee=await X.text();try{return Ee?JSON.parse(Ee):null}catch{return null}},ln=async X=>{let Ee=Date.now()+3e5;for(;;){let ke=await fetch(new URL(`/api/v1/videos/${encodeURIComponent(X)}`,Y),{headers:ce}),Ne=await de(ke),He=String(Ne?.status??"");if(He==="ready")return Ne;if(He==="failed")throw new Error(`source video download failed${Ne?.error?`: ${Ne.error}`:""}.`);if(Date.now()>Ee)throw new Error("source video download timed out.");await he(5e3)}},ha=X=>{let Ee=Te=>typeof Te=="string"&&Te.trim()?Te.trim():null,ke=X?.result&&typeof X.result=="object"?X.result:{},Ne=ke.output&&typeof ke.output=="object"?ke.output:ke,He=Ee(Ne?.primary_file_url)??Ee(Ne?.video?.file_url)??Ee(Ne?.image?.file_url)??Ee(Ne?.render?.output_url);if(He)return He;if(Array.isArray(Ne?.files))for(let Te of Ne.files){let Le=Ee(typeof Te=="string"?Te:Te?.file_url??Te?.url);if(Le)return Le}if(Array.isArray(X?.artifacts))for(let Te of X.artifacts){let Le=Ee(Te?.public_url);if(Le)return Le}return null},G=async X=>{let Ee=Date.now()+48e4;for(;;){await he(5e3);let ke=await fetch(new URL(`/api/v1/user/me/jobs/${encodeURIComponent(X)}`,Y),{headers:ce}),Ne=await de(ke),He=String(Ne?.status??""),Te=ha(Ne);if(Te)return Te;if(He==="failed"||He==="cancelled")throw new Error(`generation ${He}.`);if(Date.now()>Ee)throw new Error("generation timed out.")}},Be=async(X,Ee)=>{let ke=await(await fetch(X)).blob(),Ne=await fetch(new URL("/discover/templates/upload/presign",Y),{method:"POST",headers:j,body:JSON.stringify({file_name:"generated.mp4",content_type:"video/mp4",size_bytes:ke.size})}),He=await de(Ne);if(!Ne.ok)throw new Error(He?.error||`upload presign failed (${Ne.status})`);let Te=He?.storage_key,Le=He?.file_name||"generated.mp4";if(He?.transport==="presigned"&&He?.upload?.url){let Oe=await fetch(He.upload.url,{method:He.upload.method||"PUT",headers:He.upload.headers||{},body:ke});if(!Oe.ok)throw new Error(`upload failed (${Oe.status})`)}else{let Oe=new FormData;Oe.append("file",ke,"generated.mp4");let Kt=await fetch(new URL(He?.upload?.url||"/discover/templates/upload",Y),{method:"POST",headers:ce,body:Oe}),_t=await de(Kt);if(!Kt.ok||!_t?.storage_key)throw new Error(_t?.error||`upload failed (${Kt.status})`);Te=_t.storage_key,Le=_t.file_name||"generated.mp4"}if(!Te)throw new Error("upload did not return a storage key.");let ho=await fetch(new URL("/discover/templates",Y),{method:"POST",headers:j,body:JSON.stringify({upload:{storage_key:Te,file_name:Le},title:Ee,origin:"raw"})}),Ot=await de(ho);if(!ho.ok)throw new Error(Ot?.error||`ingest failed (${ho.status})`);return Ot};try{if(!B){ue(null,"\u26A0\uFE0F You need to be logged in to create a video.");return}let X=b.mode==="replicate"?"replicate":b.mode==="generate"?"generate":null,Ee,ke;if(X==="replicate"){let Kt=(b.source_url??"").trim();if(!/^https?:\/\//i.test(Kt)){ue(null,"\u26A0\uFE0F I need a video URL (TikTok/YouTube/Instagram/X) to replicate.");return}ke=(b.instructions??"").trim()||null,ue("Fetching the source video\u2026");let _t=await fetch(new URL("/discover/templates",Y),{method:"POST",headers:j,body:JSON.stringify({source_url:Kt})}),Dr=await de(_t);if(!_t.ok)throw new Error(Dr?.error||`couldn't fetch that URL (${_t.status})`);Ee=Dr?.status==="ready"?Dr:await ln(Dr?.inspiration_id)}else if(X==="generate"){let Kt=(b.prompt??"").trim();if(!Kt){ue(null,"\u26A0\uFE0F Tell me what the video should be about and I'll create it.");return}ke=Kt,ue("Generating your video\u2026 (this can take a couple of minutes)");let _t=await fetch(new URL("/api/v1/primitives/videos/generate",Y),{method:"POST",headers:j,body:JSON.stringify({tracer:`chat-create-${Date.now().toString(36)}`,payload:{prompt:Kt}})}),Dr=await de(_t);if(!_t.ok)throw new Error(Dr?.error||`couldn't start generation (${_t.status})`);let Ix=await G(Dr?.job_id);ue("Building an editable template from the generated video\u2026");let np=await Be(Ix,Kt.slice(0,80));Ee=np?.status==="ready"?np:await ln(np?.inspiration_id)}else{ue(null,"\u26A0\uFE0F I couldn't tell whether to generate a new video or replicate a URL \u2014 try rephrasing.");return}let Ne=Ee?.template_id,He=Ee?.inspiration_id;if(!Ne||!He)throw new Error("the template wasn't created from the video.");ue(X==="replicate"?"Recreating the scenes\u2026 (about a minute)":"Analyzing into an editable timeline\u2026");let Te=await fetch(new URL(`/api/v1/inspirations/${encodeURIComponent(He)}/decompose`,Y),{method:"POST",headers:j,body:JSON.stringify({user_prompt:ke})});if(!Te.ok){let Kt=await de(Te);throw new Error(Kt?.error||`scene analysis failed (${Te.status})`)}ue("Finalizing your editable copy\u2026");let Le=await fetch(new URL("/api/v1/compositions",Y),{method:"POST",headers:j,body:JSON.stringify({template_id:Ne})}),ho=await de(Le);if(!Le.ok)throw new Error(ho?.error||`couldn't create an editable copy (${Le.status})`);let Ot=ho?.fork_id,Oe=`${Y}/editor/${encodeURIComponent(Ne)}${Ot?`?fork=${encodeURIComponent(Ot)}`:""}`;ue("Your video is ready.",`\u2705 Your video is ready \u2014 [Open it in the editor](${Oe}).`)}catch(X){ue(null,`\u26A0\uFE0F I couldn't finish creating the video: ${X instanceof Error?X.message:String(X)}`)}}async function kS(){if(!IS)return;l.current=!0;let m=rx(I),v=new Date().toISOString(),w=h.current.find(he=>he.id===m),b={id:Bf("user"),role:"user",text:I.trim(),attachments:U},B={id:Bf("assistant"),role:"assistant",text:"",attachments:[],statusText:"Waiting for AI response\u2026",isPending:!0},Y=w?.messages??[],j=wF([...Y,b]);ft(m,he=>({...he,title:he.messages.length===0?Of(b.text):he.title,updatedAt:v,messages:[...he.messages,b,B]})),N(""),x([]),W(null),K(m),pe("Waiting for AI response\u2026");let ce=new AbortController;u.current={abortController:ce,threadId:m,assistantMessageId:B.id};try{let he=JSON.stringify({messages:RF(j),thread_id:m,thread_template_id:w?.templateId??e.template.templateId,thread_title:Y.length===0?Of(b.text):w?.title??Of(b.text),thread_tracers:qf,client_context:ZU(),user_message:{id:b.id,role:b.role,text:b.text,attachments:b.attachments.map(G=>({id:G.id,fileName:G.fileName,contentType:G.contentType,viewUrl:G.viewUrl}))},assistant_message:{id:B.id},template:{...e.template,tracers:qf,defaultRequestTracer:ES,activeTracer:ES},cached_context:{...e.cachedContext,...xF(),...bF()}});Lr("chat.send.attempt",{thread_id:m,template_id:e.template.templateId,message_count:j.length,attachment_count:b.attachments.length,text_length:b.text.length});let ue=Date.now(),de=await fetch(e.apiUrl||"/api/v1/editor-chat",{method:"POST",headers:ct(e.vidfarmApiKey,"application/json"),signal:ce.signal,body:he});if(!de.ok){let G=await de.json().catch(()=>({}));throw uo("chat.send.rejected",{thread_id:m,status:de.status,error:typeof G?.error=="string"?G.error:null}),new Error(typeof G?.error=="string"?G.error:`Chat failed with status ${de.status}.`)}Lr("chat.send.stream_open",{thread_id:m,latency_ms:Date.now()-ue});let ln=new Map,ha=ax(b.text);await kF(de,{onDelta:G=>{pe("AI is responding\u2026"),ft(m,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===B.id?{...X,text:`${X.text}${G}`,statusText:"AI is responding\u2026",isPending:!1}:X)}))},onStatus:G=>{pe(G),ft(m,Be=>({...Be,messages:Be.messages.map(X=>X.id===B.id?{...X,statusText:G,isPending:!X.text}:X)}))},onToolCall:G=>{ln.set(G.toolCallId,{toolName:G.toolName,args:G.args}),ft(m,Be=>({...Be,updatedAt:new Date().toISOString(),messages:Be.messages.map(X=>X.id===B.id?{...X,toolExchanges:[...X.toolExchanges??[],{toolCallId:G.toolCallId,toolName:G.toolName,args:zi(G.args),status:"pending"}]}:X)}))},onToolResult:G=>{let Be=OR(G.result),X=ln.get(G.toolCallId);if(G.toolName==="create_video"&&vx(m,B.id,G.result),G.toolName==="frontend_action"){let Te=G.result;if(Te?.action==="add_tracer")RS(Te.tracer??void 0);else if(Te?.action==="remove_tracer"&&Te.tracer)nx(Te.tracer);else if(Te?.action==="activate_tracer"&&Te.tracer)tx(Te.tracer);else if(Te?.action==="create_thread"){let Le=Te.tracer?RS(Te.tracer):CS();Xf({tracers:Le?[Le]:[],title:Le?`Tracer ${Le}`:"New chat",activate:!1})}}let Ee=G.result,ke=Hi(Ee?.response?.body),Ne=Ee?.request&&Ee?.response?Ic({explanation:Ee.explanation??null,request:Ee.request,result:Ee.response}):void 0,He=Ee?.request?.method==="POST"&&ke?.tracer?lx({sourceThreadId:m,tracer:ke.tracer,job:ke,httpExchange:Ne,shouldCreateThread:ha}):null;He&&ke&&!ua(ke.status)&&ep({threadId:He.threadId,assistantMessageId:He.messageId,jobId:ke.job_id,tracer:ke.tracer,initialStatus:ke.status,primitiveId:ke.primitive_id,sourceRequestUrl:Ee?.request?.url}),ft(m,Te=>({...Te,updatedAt:new Date().toISOString(),messages:Te.messages.map(Le=>{if(Le.id!==B.id)return Le;let ho=(Le.toolExchanges??[]).map(_t=>_t.toolCallId===G.toolCallId?{..._t,result:Be,status:typeof G.result?.error=="string"?"error":"complete"}:_t),Ot=G.result,Oe=Hi(Ot?.response?.body),Kt=Ot?.request&&Ot?.response?[...Le.httpExchanges??[],Ic({explanation:Ot.explanation??null,request:Ot.request,result:Ot.response})]:Le.httpExchanges;if(X&&ln.delete(G.toolCallId),Ot?.request?.method==="POST"&&Oe?.tracer){let _t=window.__vidfarmEditorTracers;_t?_t.add(Oe.tracer):fa([Oe.tracer,...F.filter(Dr=>Dr!==Oe.tracer)]),ix(m,[Oe.tracer])}return Oe&&!He&&!ua(Oe.status)&&ep({threadId:m,assistantMessageId:B.id,jobId:Oe.job_id,tracer:Oe.tracer,initialStatus:Oe.status,primitiveId:Oe.primitive_id,sourceRequestUrl:Ot?.request?.url}),{...Le,toolExchanges:ho,httpExchanges:Kt,statusText:Oe&&!ua(Oe.status)?`Job ${Oe.job_id} is being tracked. ${Zf()}`:Le.statusText,isPending:!1,text:Oe&&Ot?.request?.method==="POST"&&Ot?.response?.status===202?Ec(Le.text,fR(Oe)):Oe&&ua(Oe.status)||Oe?Ec(Le.text,Lf(Oe)):Le.text}})}))},onError:G=>{uo("chat.stream.error",{thread_id:m,message:G}),W(G),pe(null),ft(m,Be=>({...Be,messages:Be.messages.filter(X=>X.id!==B.id)}))}}),Lr("chat.stream.completed",{thread_id:m,duration_ms:Date.now()-ue}),ft(m,G=>({...G,updatedAt:new Date().toISOString(),messages:G.messages.map(Be=>Be.id===B.id?{...Be,statusText:Be.statusText?.includes("being tracked")?Be.statusText:null,isPending:!1}:Be)}))}catch(he){if(he instanceof DOMException&&he.name==="AbortError"){eR("chat.send.aborted",{thread_id:m}),W(null),pe(null),ft(m,ue=>({...ue,updatedAt:new Date().toISOString(),messages:ue.messages.map(de=>de.id!==B.id?de:!!(de.text.trim()||de.toolExchanges?.length||de.httpExchanges?.length)?{...de,statusText:"Stopped.",isPending:!1}:{...de,text:"Stopped.",statusText:null,isPending:!1})}));return}uo("chat.send.failed",{thread_id:m,message:he instanceof Error?he.message:String(he)}),W(he instanceof Error?he.message:"Unable to send chat message."),pe(null),ft(m,ue=>({...ue,messages:ue.messages.map(de=>de.id===B.id?{...de,text:he instanceof Error?`Error: ${he.message}`:"Error: Unable to send chat message.",statusText:null,isPending:!1}:de)}))}finally{u.current?.assistantMessageId===B.id&&(u.current=null),K(he=>he===m?null:he),pe(null)}}function Ex(){pe("Stopping\u2026");let m=u.current;m&&ft(m.threadId,v=>({...v,updatedAt:new Date().toISOString(),messages:v.messages.map(w=>w.id===m.assistantMessageId?{...w,statusText:"Stopping\u2026"}:w)})),u.current?.abortController.abort()}(0,k.useEffect)(()=>()=>{u.current?.abortController.abort();for(let m of d.current.keys())pa(m);try{o?.setItem(r.threads,JSON.stringify(TR(me.current,Ve.current)))}catch{}},[o,r]);function Tx(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),kS())}let NS=(0,f.jsx)("div",{className:`vf-editor-chat-thread-list${t?" vf-editor-chat-thread-list-sidebar":""}`,role:"tablist","aria-label":"Conversation threads",children:Yf.length?Yf.map(m=>(0,f.jsxs)("div",{role:"tab","aria-selected":m.id===g,className:"vf-editor-chat-thread-chip","data-active":m.id===g?"true":"false",children:[(0,f.jsxs)("button",{type:"button",className:"vf-editor-chat-thread-chip-main",onClick:()=>{S(m.id),W(null),A(null),ut(!1),t&&Ie(!1)},children:[(0,f.jsx)("span",{className:"vf-editor-chat-thread-chip-title",children:m.title}),m.tracers.length?(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.tracers.slice(0,2).join(", "),m.tracers.length>2?` +${m.tracers.length-2}`:""]}):null]}),(0,f.jsx)("div",{className:"vf-editor-chat-thread-menu-wrap",children:(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-thread-chip-menu","aria-label":`Actions for ${m.title}`,onClick:v=>{v.stopPropagation(),px(m.id,v.currentTarget)},children:"..."})})]},m.id)):(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Start a chat to create your first conversation thread."})});return(0,f.jsxs)("div",{className:"vf-editor-chat-shell","data-mobile-open":le?"true":"false","data-layout":t?"brainstorm":"default",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-mobile-fab","aria-label":"Open chat","aria-expanded":le,onClick:()=>Ie(!0),children:(0,f.jsx)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:(0,f.jsx)("path",{d:"M20 11.5a7.5 7.5 0 0 1-9.8 7.1L4 20l1.5-5.3A7.5 7.5 0 1 1 20 11.5Z"})})}),$?(0,f.jsx)("div",{className:"vf-editor-chat-error",role:"status",children:$}):null,(0,f.jsxs)("div",{className:`${t?"vf-editor-chat-body vf-editor-chat-brainstorm-layout":"vf-editor-chat-body"}${n?" has-sidebar":""}`,"data-history-open":_e||Xe?"true":"false",children:[n?(0,f.jsxs)("aside",{className:"vf-editor-chat-history-pane",children:[(0,f.jsx)("div",{className:"vf-editor-chat-history-header",children:(0,f.jsxs)("div",{className:"vf-editor-chat-history-header-main",children:[(0,f.jsxs)("a",{className:"vf-editor-chat-back-button",href:"/discover","aria-label":"Back to Discover",children:[(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}),"Discover"]}),(0,f.jsx)("div",{className:"vf-editor-chat-history-kicker",children:"Chat history"})]})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread vf-editor-chat-new-thread-sidebar",onClick:xS,children:"New chat"}),NS]}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-thread",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-header-row",children:[(0,f.jsx)("a",{className:"vf-editor-chat-back-button vf-editor-chat-back-button--header",href:"/discover","aria-label":"Back to Discover",children:(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon","aria-label":_e?"Back to chat":"Open chat history","aria-pressed":_e,onClick:()=>{ut(m=>!m),Yt(!1)},children:_e?(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,f.jsx)("circle",{cx:"10",cy:"10",r:"7.2"}),(0,f.jsx)("path",{d:"M10 6v4l2.6 1.6"})]})}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-history-icon vf-editor-chat-branches-icon","aria-label":Xe?"Back to chat":"Open template forks","aria-pressed":Xe,onClick:()=>{Yt(m=>!m),ut(!1)},children:Xe?(0,f.jsx)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,f.jsx)("path",{d:"m12 4-6 6 6 6"})}):(0,f.jsxs)("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,f.jsx)("circle",{cx:"5.5",cy:"4.5",r:"1.9"}),(0,f.jsx)("circle",{cx:"5.5",cy:"15.5",r:"1.9"}),(0,f.jsx)("circle",{cx:"14.5",cy:"8",r:"1.9"}),(0,f.jsx)("path",{d:"M5.5 6.4v7.2"}),(0,f.jsx)("path",{d:"M5.5 13.6c0-3.2 2.4-3.6 4.4-3.9 2-.3 4.6-.5 4.6-3.7"})]})}),(0,f.jsxs)("div",{className:"vf-editor-chat-header-titles",children:[(0,f.jsx)("div",{className:"vf-editor-chat-header-title",children:"Vidfarm"}),(0,f.jsx)("div",{className:"vf-editor-chat-header-subtitle",children:_e?"Chat history":Xe?"Template forks":e.template.templateTitle})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-new-thread",onClick:xS,children:"New chat"}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-minimize","aria-label":"Minimize chat",onClick:()=>Ie(!1),children:"\xD7"})]}),M&&Dn?(0,ji.createPortal)((0,f.jsxs)("div",{className:"vf-editor-chat-thread-menu",role:"menu",style:{top:M.top,left:M.left},onClick:m=>m.stopPropagation(),children:[(0,f.jsx)("button",{type:"button",onClick:()=>fx(Dn.id),children:"Copy Chat ID"}),(0,f.jsx)("button",{type:"button",onClick:()=>cx(Dn.id),children:"Edit tracers"}),(0,f.jsx)("button",{type:"button",onClick:()=>dx(Dn.id),children:"Remove from view"}),(0,f.jsx)("button",{type:"button",onClick:()=>ux(Dn.id),children:"Archive thread"}),(0,f.jsx)("button",{type:"button","data-danger":"true",onClick:()=>ox(Dn.id),children:"Delete"})]}),document.body):null]}),(0,f.jsx)("div",{className:"vf-editor-chat-viewport",ref:s,children:_e?(0,f.jsx)("div",{className:"vf-editor-chat-history-panel",children:NS}):Xe?(0,f.jsxs)("div",{className:"vf-editor-chat-history-panel vf-editor-chat-branches-panel",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-branches-header",children:[(0,f.jsxs)("div",{className:"vf-editor-chat-branches-header-main",children:[(0,f.jsx)("div",{className:"vf-editor-chat-branches-kicker",children:"Forks"}),(0,f.jsxs)("div",{className:"vf-editor-chat-branches-title",children:[dt?.length??0," fork",(dt?.length??0)===1?"":"s"," of this template"]})]}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-branches-refresh",onClick:()=>{Fe({force:!0})},disabled:Tn,"aria-label":"Refresh forks",children:Tn?"Loading\u2026":"Refresh"})]}),po?(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",role:"status",children:po}):Tn&&!dt?(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"Loading forks\u2026"}):dt&&dt.length?(0,f.jsx)("div",{className:"vf-editor-chat-thread-list",children:dt.map(m=>{let v=St===m.forkId,w=`/editor/${encodeURIComponent(e.template.templateId)}?fork=${encodeURIComponent(m.forkId)}`,b=m.title&&m.title.trim()?m.title:m.forkId,B=m.parentForkId?` \xB7 forked from ${m.parentForkId.slice(0,12)}${m.parentVersion?`#v${m.parentVersion}`:""}`:"",Y=m.latestVersion&&m.latestVersion>0?` \xB7 v${m.latestVersion}`:"";return(0,f.jsx)("div",{role:"listitem",className:"vf-editor-chat-thread-chip","data-active":v?"true":"false",children:(0,f.jsxs)("a",{className:"vf-editor-chat-thread-chip-main vf-editor-chat-branch-chip-link",href:w,target:"_blank",rel:"noopener noreferrer",children:[(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-title",children:[b,v?(0,f.jsx)("span",{className:"vf-editor-chat-branch-current-badge",children:"current"}):null]}),(0,f.jsxs)("span",{className:"vf-editor-chat-thread-chip-tracers",children:[m.visibility??"private",Y,B]})]})},m.forkId)})}):(0,f.jsx)("div",{className:"vf-editor-chat-thread-empty",children:"No forks yet for this template."})]}):Kf.length?Kf.map(m=>(0,f.jsx)(KF,{message:m},m.id)):g&&E===g?(0,f.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,f.jsx)("div",{className:"vf-editor-chat-kicker",children:"Loading chat"}),(0,f.jsxs)("h2",{children:["Opening ",g]})]}):(0,f.jsxs)("div",{className:"vf-editor-chat-empty",children:[(0,f.jsx)("div",{className:"vf-editor-chat-kicker",children:"AI Copilot"}),(0,f.jsx)("h2",{children:t?"Start a new chat.":"Repurpose this video."}),(0,f.jsx)("p",{children:t?"Use the brainstorm tools to go from zero context to angles, hooks, and a strategy you can actually test.":"Use the brainstorm tools to turn this video into a native ad for your product, spot product-placement opportunities, and shape the timeline you can actually test. You can also connect from your own AI coding agent, including Claude Code or OpenAI Codex, and ask it to work against this composition."}),(0,f.jsx)("div",{className:"vf-editor-chat-empty-prompts","aria-label":"Example prompts",children:t?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{children:"I don't know where to start"}),(0,f.jsx)("div",{children:"Help me think of persuasive angles"}),(0,f.jsx)("div",{children:"Help me think of viral hooks"})]}):(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)("div",{children:"I don't know where to start"}),(0,f.jsx)("div",{children:"Repurpose this video into a social media native ad for my product"}),(0,f.jsx)("div",{children:"Help me identify product placement opportunities in this video for my product"})]})})]})}),(0,f.jsx)("div",{className:"vf-editor-chat-footer",hidden:_e||Xe,children:(0,f.jsxs)("div",{className:"vf-editor-chat-composer","data-drop-target":Se?"true":"false",onDragEnter:m=>{m.preventDefault(),J(!0)},onDragOver:m=>{m.preventDefault(),Se||J(!0)},onDragLeave:m=>{m.preventDefault();let v=m.relatedTarget;v instanceof Node&&m.currentTarget.contains(v)||J(!1)},onDrop:m=>{_x(m)},children:[Se?(0,f.jsx)("div",{className:"vf-editor-chat-dropzone-hint",children:"Drop files to attach"}):null,U.length?(0,f.jsx)("div",{className:"vf-editor-chat-composer-attachments-strip",children:U.map(m=>(0,f.jsx)(jF,{attachment:m,onRemove:()=>x(v=>v.filter(w=>w.id!==m.id))},m.id))}):null,(0,f.jsxs)("div",{className:"vf-editor-chat-composer-row",children:[(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-attach-button","aria-label":"Open upload drawer",onClick:()=>P(!0),children:"\u{1F4CE}"}),(0,f.jsx)("textarea",{rows:1,placeholder:t?"Describe the offer, audience, or strategy problem you want help with...":"Ask it to call a route, inspect jobs, save config, or continue this thread...",className:"vf-editor-chat-input",value:I,onChange:m=>N(m.target.value),onKeyDown:Tx,onPaste:m=>{Sx(m)}}),(0,f.jsx)("button",{type:"button",className:"vf-editor-chat-send-button",onClick:()=>{if(Jf){Ex();return}kS()},disabled:Jf?!1:!IS,children:Jf?"Stop":"Send"})]}),(0,f.jsx)("input",{ref:i,type:"file",accept:"image/*,video/*,audio/*,application/pdf,text/plain,text/markdown",multiple:!0,hidden:!0,onChange:m=>{yx(m)}})]})})]})]}),(0,f.jsx)(XF,{apiKey:e.vidfarmApiKey,open:Gi,onClose:()=>P(!1),onConfirm:m=>x(v=>[...v,...m])})]})}var En=In(vc(),1);tR();function QF(){let e=document.getElementById("page-runtime-boot");return e?.textContent?JSON.parse(e.textContent):null}function Gf(e){let t=new Date;return t.setDate(t.getDate()+e),t.toISOString()}async function ZF(e){if(!e.userId)return;let t=e.store.getState();if(!e.force&&t.channels.length&&t.channelsUpdatedAt)return;let n=new URLSearchParams({start_date:Gf(-7),end_date:Gf(30)}),r=await fetch(`/u/${encodeURIComponent(e.userId)}/calendar/feed?${n.toString()}`,{headers:{accept:"application/json"}}),o=await r.json().catch(()=>null);!r.ok||!o||(e.store.getState().setCalendarData({channels:Array.isArray(o.channels)?o.channels:[],posts:Array.isArray(o.posts)?o.posts:[],rangeStart:o.startDate||Gf(-7),rangeEnd:o.endDate||Gf(30),replaceRange:!0}),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated")))}function eB({boot:e}){let t=(0,Wi.useMemo)(()=>sR(e),[e]),n=ZC(t,i=>i.boot.title),[r,o]=(0,Wi.useState)(null);return(0,Wi.useEffect)(()=>{t.getState().setHydratedAt(new Date().toISOString()),document.documentElement.dataset.reactRuntime="true",document.documentElement.dataset.reactRuntimePage=e.pageKind,document.title=n},[e.pageKind,t,n]),(0,Wi.useEffect)(()=>{if(!e.editorChat)return;let i=document.querySelector("[data-template-editor-chat-root]");o(i instanceof HTMLElement?i:null)},[e.editorChat]),e.editorChat&&r?(0,JR.createPortal)((0,En.jsx)(Ls,{fallback:(0,En.jsx)(tB,{}),children:(0,En.jsx)(KR,{boot:e.editorChat})}),r):null}function tB(){return(0,En.jsxs)("div",{style:{display:"grid",placeItems:"center",height:"100%",padding:"24px",textAlign:"center",gap:"12px",color:"#5c6a82"},children:[(0,En.jsx)("div",{style:{fontSize:"0.72rem",fontWeight:800,letterSpacing:"0.14em",textTransform:"uppercase"},children:"Chat error"}),(0,En.jsx)("div",{style:{fontSize:"0.92rem"},children:"Something went wrong loading the chat. Reload the page to try again."}),(0,En.jsx)("button",{type:"button",onClick:()=>window.location.reload(),style:{marginTop:"4px",minHeight:"34px",padding:"0 16px",border:"1px solid rgba(191, 164, 109, 0.34)",borderRadius:"999px",background:"rgba(255, 255, 255, 0.92)",color:"#243041",fontWeight:700,cursor:"pointer"},children:"Reload"})]})}var Qo=QF(),_S=document.getElementById("page-runtime-root"),vS=iR(Qo?.userId??null),Vf=null;function QR(e={}){return!e.force&&Vf||(Vf=ZF({userId:Qo?.userId??null,store:vS,force:e.force}).catch(()=>{})),Vf}window.__vidfarmFlockPosterCache={readSnapshot:()=>eS(Qo?.userId??null),ensureHydrated:QR,setChannelsData:e=>{vS.getState().setChannelsData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))},setCalendarData:e=>{vS.getState().setCalendarData(e),window.dispatchEvent(new CustomEvent("vidfarm:flockposter-cache-updated"))}};QR();Lr("page_runtime.boot",{has_boot:!!Qo,has_root:!!_S,page_kind:Qo?.pageKind??null,editor_chat_template_id:Qo?.editorChat?.template?.templateId??null});Qo&&_S&&(0,XR.createRoot)(_S).render((0,En.jsx)(Ls,{fallback:(0,En.jsx)(En.Fragment,{}),onError:e=>uo("page_runtime.render_error",{message:e instanceof Error?e.message:String(e)}),children:(0,En.jsx)(eB,{boot:Qo})}));
46
46
  /*! Bundled license information:
47
47
 
48
48
  react/cjs/react.production.min.js: