openmagic 0.37.0 → 0.38.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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var OpenMagicToolbar=(()=>{var
|
|
2
|
+
"use strict";var OpenMagicToolbar=(()=>{var Ie=`
|
|
3
3
|
:host {
|
|
4
4
|
all: initial;
|
|
5
5
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
@@ -372,48 +372,48 @@
|
|
|
372
372
|
.om-msg:hover .om-copy-btn { opacity: 1; }
|
|
373
373
|
.om-copy-btn:hover { color: #ccc; background: rgba(0,0,0,0.5); }
|
|
374
374
|
.om-msg { position: relative; }
|
|
375
|
-
`;var
|
|
376
|
-
`);
|
|
377
|
-
${
|
|
375
|
+
`;var W=null,B=new Map,ae=[],ke=[],oe=!1,Oe=!1,ve=null,we=0;function Se(){return Math.random().toString(36).slice(2)+Date.now().toString(36)}function $e(t,e){return Oe=!0,new Promise((s,n)=>{let a=!1,i=setTimeout(()=>{a||(a=!0,n(new Error("Handshake timeout")),W?.close())},1e4);try{let r=window.location.hostname||"127.0.0.1",p=window.location.protocol==="https:"?"wss:":"ws:";W=new WebSocket(`${p}//${r}:${t}/__openmagic__/ws`),W.onopen=()=>{let d=Se();W.send(JSON.stringify({id:d,type:"handshake",payload:{token:e}})),B.set(d,m=>{if(m.type==="handshake.ok"){clearTimeout(i),oe=!0,we=0;for(let u of ke)W?.send(u);ke=[],a||(a=!0,s())}else m.type==="error"&&(clearTimeout(i),a||(a=!0,n(new Error(m.payload?.message||"Handshake failed"))))})},W.onmessage=d=>{try{let m=JSON.parse(d.data);m.id&&B.has(m.id)&&(B.get(m.id)(m),(m.type==="llm.done"||m.type==="llm.error"||!m.type.startsWith("llm."))&&B.delete(m.id));for(let u of ae)u(m)}catch{}},W.onclose=()=>{let d=oe;if(oe=!1,B.forEach((m,u)=>{m({type:"error",id:u,payload:{message:"Connection lost"}})}),B.clear(),!d&&!a){clearTimeout(i),a=!0,n(new Error("WebSocket closed before handshake"));return}if(d&&Oe&&!ve){let m=Math.min(2e3*Math.pow(1.5,we),3e4);we++,ve=setTimeout(()=>{ve=null,$e(t,e).then(()=>{for(let u of ae)u({type:"reconnected",payload:{}})}).catch(()=>{})},m)}},W.onerror=()=>{!oe&&!a&&(clearTimeout(i),a=!0,n(new Error("WebSocket connection failed")))}}catch(r){clearTimeout(i),a||(a=!0,n(r))}})}function De(t){let e=JSON.stringify(t);W&&W.readyState===WebSocket.OPEN&&oe?W.send(e):ke.push(e)}function A(t,e){return new Promise((s,n)=>{let a=Se(),i=setTimeout(()=>{B.delete(a),n(new Error("Request timeout"))},3e4);B.set(a,r=>{clearTimeout(i),r.type==="error"?n(new Error(r.payload?.message||"Unknown error")):s(r)}),De({id:a,type:t,payload:e})})}function qe(t,e,s){return new Promise((n,a)=>{let i=Se(),r=3e5,p=setTimeout(d,r);function d(){B.delete(i),a(new Error("Stream timeout"))}function m(){clearTimeout(p),p=setTimeout(d,r)}B.set(i,u=>{u.type==="llm.chunk"?(m(),s(u.payload?.delta||"")):u.type==="llm.done"?(clearTimeout(p),B.delete(i),n(u.payload)):(u.type==="llm.error"||u.type==="error")&&(clearTimeout(p),B.delete(i),a(new Error(u.payload?.message||"Stream error")))}),De({id:i,type:t,payload:e})})}function je(t){return ae.push(t),()=>{ae=ae.filter(e=>e!==t)}}function Ee(){return oe}var ze=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","box-shadow","flex-direction","justify-content","align-items","gap","grid-template-columns","grid-template-rows","overflow","opacity","z-index","text-align","line-height","letter-spacing"];function Be(t){let e=window.getComputedStyle(t),s={};for(let y of ze)s[y]=e.getPropertyValue(y);let n=t.getBoundingClientRect(),a={};if(t.parentElement&&t.parentElement!==document.body){let y=window.getComputedStyle(t.parentElement);for(let M of ze)a[M]=y.getPropertyValue(M)}let i=[];if(t.parentElement){let y=Array.from(t.parentElement.children),M=y.indexOf(t),P=Math.max(0,M-3),T=Math.min(y.length,M+4);P>0&&i.push(`... ${P} elements before ...`);for(let N=P;N<T;N++){let R=y[N],V=R.tagName.toLowerCase(),K=(R.className||"").toString().slice(0,60);R===t?i.push(`[SELECTED] <${V} class="${K}">`):i.push(`<${V} class="${K}">`)}T<y.length&&i.push(`... ${y.length-T} elements after ...`)}let r=[],p=Array.from(t.children).slice(0,12);for(let y=0;y<p.length;y++){let M=p[y],P=M.getBoundingClientRect(),T=window.getComputedStyle(M),N=null;if(y<p.length-1){let R=p[y+1].getBoundingClientRect();N={vertical:Math.round(R.top-P.bottom),horizontal:Math.round(R.left-P.right)}}r.push({tag:M.tagName.toLowerCase(),className:(M.className||"").toString().slice(0,80),rect:{x:Math.round(P.x),y:Math.round(P.y),width:Math.round(P.width),height:Math.round(P.height)},gapToNext:N,margin:T.margin,padding:T.padding})}let d=mt(t),m=ht(t,d),u={};for(let y of Array.from(t.attributes))(y.name.startsWith("aria-")||y.name==="role"||y.name==="tabindex")&&(u[y.name]=y.value);let w=[];for(let y of Array.from(t.attributes))y.name.startsWith("on")&&w.push(y.name);let k=ut(t),l=document.documentElement,g=window.getComputedStyle(l),f={};for(let y of Object.keys(l.dataset))f[y]=l.dataset[y]||"";let h={darkMode:l.classList.contains("dark")||l.dataset.theme==="dark"||l.dataset.mode==="dark"||window.matchMedia("(prefers-color-scheme: dark)").matches,colorScheme:g.colorScheme||"",htmlDataAttributes:f},c={};try{for(let M of d){let P=M.matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let T of P){let N=T[1];c[N]||(c[N]=e.getPropertyValue(N).trim()||"(unset)")}}let y=(t.getAttribute("style")||"").matchAll(/var\((--[a-zA-Z0-9_-]+)/g);for(let M of y)c[M[1]]||(c[M[1]]=e.getPropertyValue(M[1]).trim()||"(unset)")}catch{}let $=e.zIndex,E=e.position!=="static"&&$!=="auto"||e.opacity!=="1"||e.transform!=="none"||e.filter!=="none",I=t.parentElement?window.getComputedStyle(t.parentElement).zIndex:"auto",D={zIndex:$,createsContext:E,parentZIndex:I},Q=n.top<window.innerHeight&&n.bottom>0&&n.left<window.innerWidth&&n.right>0,b=!0;try{b=t.checkVisibility?.({checkOpacity:!0,checkVisibilityCSS:!0})??!0}catch{b=e.display!=="none"&&e.visibility!=="hidden"}let v=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth,S={isVisible:b,isInViewport:Q,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft,isScrollable:v},H=[],L=["(max-width: 639px)","(min-width: 640px)","(min-width: 768px)","(min-width: 1024px)","(min-width: 1280px)","(min-width: 1536px)","(prefers-color-scheme: dark)","(prefers-reduced-motion: reduce)"];for(let y of L)try{window.matchMedia(y).matches&&H.push(y)}catch{}let j="",z="";try{j=window.getComputedStyle(t,"::before").content||""}catch{}try{z=window.getComputedStyle(t,"::after").content||""}catch{}let G={before:j,after:z},ee=null;return(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLButtonElement)&&(ee={disabled:t.disabled||!1,readOnly:t.readOnly||!1,invalid:t.checkValidity?!t.checkValidity():!1}),{tagName:t.tagName.toLowerCase(),id:t.id||"",className:t.className||"",textContent:(t.textContent||"").trim().slice(0,200),outerHTML:ct(t),cssSelector:dt(t),xpath:pt(t),computedStyles:s,ancestry:rt(t),componentHint:lt(t),rect:{x:n.x,y:n.y,width:n.width,height:n.height},parentStyles:a,siblings:i,childrenLayout:r,matchedCssRules:d,resolvedClasses:m,viewport:{width:window.innerWidth,height:window.innerHeight},ariaAttributes:u,eventHandlers:w,reactProps:k,themeState:h,cssVariables:c,stackingContext:D,visibilityState:S,activeBreakpoints:H,pseudoElements:G,formState:ee}}function rt(t,e=5){let s=[],n=t.parentElement;for(;n&&n!==document.body&&s.length<e;){let a=n.tagName.toLowerCase(),i=(typeof n.className=="string"?n.className:"").split(/\s+/).filter(r=>r.length>1&&!r.startsWith("_")).slice(0,3).join(".");s.push(i?`${a}.${i}`:a),n=n.parentElement}return s}function lt(t){let e=t;for(;e&&e!==document.body;){let s=e.getAttribute("data-component")||e.getAttribute("data-testid")||e.getAttribute("data-cy");if(s)return s;let n=Object.keys(e);for(let a of n)if(a.startsWith("__reactFiber")||a.startsWith("__reactInternalInstance"))try{let i=e[a],r=i?.type?.name||i?.type?.displayName||i?.return?.type?.name||i?.return?.type?.displayName;if(r&&r!=="div"&&r!=="span"&&r.length>1)return r}catch{}e=e.parentElement}return""}function ct(t){let e=t.cloneNode(!0);e.querySelectorAll("script, style, svg").forEach(a=>a.remove());let n=e.outerHTML;if(n.length>2e3){let a=t.tagName.toLowerCase(),i=Array.from(t.attributes).map(p=>`${p.name}="${p.value}"`).join(" "),r=Array.from(t.children).slice(0,5).map(p=>`<${p.tagName.toLowerCase()} .../>`).join(`
|
|
376
|
+
`);n=`<${a} ${i}>
|
|
377
|
+
${r}
|
|
378
378
|
${t.children.length>5?`<!-- +${t.children.length-5} more children -->`:""}
|
|
379
|
-
</${a}>`}return
|
|
379
|
+
</${a}>`}return n}function dt(t){if(t.id)return`#${CSS.escape(t.id)}`;let e=[],s=t;for(;s&&s!==document.body;){let n=s.tagName.toLowerCase();if(s.id){e.unshift(`#${CSS.escape(s.id)}`);break}if(s.className&&typeof s.className=="string"){let i=s.className.trim().split(/\s+/).filter(r=>!r.startsWith("__")&&r.length<30).slice(0,2).map(r=>CSS.escape(r));i.length>0&&(n+="."+i.join("."))}let a=s.parentElement;if(a){let i=Array.from(a.children).filter(r=>r.tagName===s.tagName);if(i.length>1){let r=i.indexOf(s)+1;n+=`:nth-of-type(${r})`}}e.unshift(n),s=s.parentElement}return e.join(" > ")}function pt(t){let e=[],s=t;for(;s&&s!==document;){if(s.nodeType===Node.ELEMENT_NODE){let n=s,a=1,i=n.previousElementSibling;for(;i;)i.tagName===n.tagName&&a++,i=i.previousElementSibling;e.unshift(`${n.tagName.toLowerCase()}[${a}]`)}s=s.parentNode}return"/"+e.join("/")}function mt(t){let e=[];try{for(let s of Array.from(document.styleSheets))try{let n=s.cssRules||s.rules;if(!n)continue;for(let a of Array.from(n))if(a instanceof CSSStyleRule)try{if(t.matches(a.selectorText)){let i=a.cssText;i.length>10&&i.length<500&&e.push(i)}}catch{}}catch{}}catch{}return e.slice(0,15)}function ut(t){try{let e=Object.keys(t);for(let s of e)if(s.startsWith("__reactFiber")||s.startsWith("__reactInternalInstance")){let n=t[s];if(!n?.memoizedProps)continue;let a=n.memoizedProps,i={},r=0;for(let[p,d]of Object.entries(a)){if(r>=10)break;if(p==="children")continue;let m=typeof d;m==="string"||m==="number"||m==="boolean"||d===null?(i[p]=d,r++):m==="function"?(i[p]="[function]",r++):Array.isArray(d)&&(i[p]=`[Array(${d.length})]`,r++)}return Object.keys(i).length>0?i:null}}catch{}return null}function ht(t,e){let s=[],n=(t.className||"").toString().trim().split(/\s+/).filter(Boolean);for(let a of n){let i=CSS.escape(a);for(let r of e)if(r.includes(`.${i}`)&&r.length<200){s.push({className:a,css:r});break}if(s.length>=20)break}return s}var F=null;function Fe(t){F||(F=document.createElement("div"),F.style.cssText=`
|
|
380
380
|
position: fixed;
|
|
381
381
|
pointer-events: none;
|
|
382
382
|
z-index: 2147483646;
|
|
383
383
|
border: 2px solid #6c5ce7;
|
|
384
384
|
background: rgba(108, 92, 231, 0.1);
|
|
385
385
|
transition: all 0.1s ease;
|
|
386
|
-
`,
|
|
387
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${
|
|
386
|
+
`,F.dataset.openmagic="highlight",document.body.appendChild(F)),F.style.left=`${t.x}px`,F.style.top=`${t.y}px`,F.style.width=`${t.width}px`,F.style.height=`${t.height}px`,F.style.display="block"}function We(){F&&(F.style.display="none")}async function Ue(t){try{let e=t||document.body,s=await gt(e);if(s)return{data:s}}catch{}try{let e=await ft(t);if(e)return{data:e}}catch(e){return{data:null,error:`Screenshot failed: ${e.message||"unknown error"}. Try using the image attachment button instead.`}}return{data:null,error:"Screenshot capture not available on this page. Try pasting or dragging an image instead."}}async function gt(t){let e=t.getBoundingClientRect(),s=Math.min(e.width||window.innerWidth,1920),n=Math.min(e.height||window.innerHeight,1080),a=Ke(t,0,4);if(!a)return null;let i=`
|
|
387
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${n}">
|
|
388
388
|
<foreignObject width="100%" height="100%">
|
|
389
|
-
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${
|
|
389
|
+
<div xmlns="http://www.w3.org/1999/xhtml" style="width:${s}px;height:${n}px;overflow:hidden;">
|
|
390
390
|
${a.outerHTML}
|
|
391
391
|
</div>
|
|
392
392
|
</foreignObject>
|
|
393
|
-
</svg>`,i=new Blob([r],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(i);return new Promise(c=>{let p=new Image,m=document.createElement("canvas"),k=Math.min(window.devicePixelRatio||1,2);m.width=s*k,m.height=o*k,p.onload=()=>{URL.revokeObjectURL(u);let S=m.getContext("2d");if(!S){c(null);return}S.scale(k,k),S.drawImage(p,0,0);try{if(m.width>1280){let y=1280/m.width,b=document.createElement("canvas");b.width=1280,b.height=Math.round(m.height*y);let g=b.getContext("2d");if(g){g.drawImage(m,0,0,b.width,b.height),c(b.toDataURL("image/jpeg",.8));return}}c(m.toDataURL("image/jpeg",.8))}catch{c(null)}},p.onerror=()=>{URL.revokeObjectURL(u),c(null)},setTimeout(()=>{URL.revokeObjectURL(u),c(null)},5e3),p.src=u})}async function mt(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),o=document.createElement("canvas");o.width=400,o.height=300;let a=o.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${e.tagName.toLowerCase()}>`,20,30),a.fillStyle="#888",a.font="12px system-ui",a.fillText(`Size: ${Math.round(s.width)}x${Math.round(s.height)}`,20,55),a.fillText(`Classes: ${(e.className||"").toString().slice(0,40)}`,20,75),a.fillText(`Page: ${window.location.pathname}`,20,95),a.fillStyle="#6c5ce7",a.font="11px system-ui",a.fillText("(Full screenshot unavailable \u2014 context sent as metadata)",20,130),o.toDataURL("image/png")):null}function Fe(t,e,s){if(e>s)return null;try{let o=t.cloneNode(!1);if(o.tagName==="SCRIPT"||o.tagName==="STYLE"||o.tagName==="SVG"||o.tagName==="CANVAS"||o.tagName==="VIDEO"||o.tagName==="IFRAME")return null;let a=window.getComputedStyle(t),r=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","flex-direction","justify-content","align-items","gap","grid-template-columns","text-align","overflow"],i="";for(let u of r){let c=a.getPropertyValue(u);c&&c!=="normal"&&c!=="none"&&c!=="auto"&&c!=="0px"&&(i+=`${u}:${c};`)}o.setAttribute("style",i);for(let u=0;u<t.children.length&&u<20;u++){let c=Fe(t.children[u],e+1,s);c&&o.appendChild(c)}return o}catch{return null}}var ce=[];var We=!1;function Ge(){if(We)return;We=!0;let t=window.fetch;window.fetch=async function(...o){let a=new Request(...o),r={method:a.method,url:a.url,timestamp:Date.now()};try{let i=await t.apply(this,o);return r.status=i.status,r.duration=Date.now()-r.timestamp,Ee(r),i}catch(i){throw r.status=0,r.duration=Date.now()-r.timestamp,Ee(r),i}};let e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(o,a,...r){return this.__om_method=o,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[o,a,...r])},XMLHttpRequest.prototype.send=function(...o){return this.addEventListener("loadend",()=>{Ee({method:this.__om_method||"GET",url:this.__om_url||"",status:this.status,duration:Date.now()-(this.__om_start||Date.now()),timestamp:this.__om_start||Date.now()})}),s.apply(this,o)}}function Ee(t){t.url.includes("__openmagic__")||(ce.push(t),ce.length>50&&ce.shift())}function pe(){return[...ce]}var de=[],ut=100,Ue=!1;function Ve(){if(Ue)return;Ue=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...o){de.push({level:e,args:o.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),de.length>ut&&de.shift(),s.apply(console,o)}}}function me(){return[...de]}function Ke(t,e){return{selectedElement:t?{tagName:t.tagName,id:t.id,className:t.className,textContent:t.textContent,outerHTML:t.outerHTML,cssSelector:t.cssSelector,computedStyles:t.computedStyles}:void 0,screenshot:e||void 0,networkLogs:pe().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:me().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var T={sparkle:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.582a.5.5 0 0 1 0 .962L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>',crosshair:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',camera:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',chat:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',settings:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',send:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',x:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',externalLink:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',check:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',copy:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',grip:'<svg width="7" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg>',network:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',activity:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',bug:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m8 2 1.88 1.88M14.12 3.88 16 2M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>',paperclip:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',trash:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',minus:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>'},X={"claude-code":{name:"Claude Code (CLI)",keyPlaceholder:"not required",local:!0,models:[{id:"claude-code",name:"Claude Code"}]},"codex-cli":{name:"Codex CLI",keyPlaceholder:"not required",local:!0,models:[{id:"codex-cli",name:"Codex CLI"}]},"gemini-cli":{name:"Gemini CLI",keyPlaceholder:"not required",local:!0,models:[{id:"gemini-cli",name:"Gemini CLI"}]},openai:{name:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",keyPlaceholder:"sk-...",models:[{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.2",name:"GPT-5.2 Thinking"},{id:"o3",name:"o3"},{id:"o4-mini",name:"o4-mini"},{id:"gpt-4.1",name:"GPT-4.1"},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini"}]},anthropic:{name:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",keyPlaceholder:"sk-ant-...",models:[{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5"}]},google:{name:"Google Gemini",keyUrl:"https://aistudio.google.com/apikey",keyPlaceholder:"AIza...",models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro"},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash"},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash"}]},xai:{name:"xAI (Grok)",keyUrl:"https://console.x.ai/team/default/api-keys",keyPlaceholder:"xai-...",models:[{id:"grok-4.20-0309-reasoning",name:"Grok 4.20 Reasoning"},{id:"grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast"}]},deepseek:{name:"DeepSeek",keyUrl:"https://platform.deepseek.com/api_keys",keyPlaceholder:"sk-...",models:[{id:"deepseek-chat",name:"DeepSeek V3.2"},{id:"deepseek-reasoner",name:"DeepSeek R1"}]},mistral:{name:"Mistral",keyUrl:"https://console.mistral.ai/api-keys",keyPlaceholder:"...",models:[{id:"mistral-large-3-25-12",name:"Mistral Large 3"},{id:"codestral-2508",name:"Codestral"},{id:"devstral-2-25-12",name:"Devstral 2"}]},groq:{name:"Groq",keyUrl:"https://console.groq.com/keys",keyPlaceholder:"gsk_...",models:[{id:"meta-llama/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout"},{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B"}]},minimax:{name:"MiniMax",keyUrl:"https://platform.minimax.chat/user-center/basic-information/interface-key",keyPlaceholder:"MiniMax key...",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7"},{id:"MiniMax-M2.5",name:"MiniMax M2.5"}]},moonshot:{name:"Kimi (Moonshot)",keyUrl:"https://platform.moonshot.cn/console/api-keys",keyPlaceholder:"Moonshot key...",models:[{id:"kimi-k2.5",name:"Kimi K2.5"},{id:"kimi-k2-thinking",name:"Kimi K2 Thinking"}]},qwen:{name:"Qwen (Alibaba)",keyUrl:"https://dashscope.console.aliyun.com/apiKey",keyPlaceholder:"DashScope key...",models:[{id:"qwen3.5-plus",name:"Qwen 3.5 Plus"},{id:"qwen-max",name:"Qwen Max"}]},zhipu:{name:"Zhipu AI (GLM)",keyUrl:"https://open.bigmodel.cn/usercenter/apikeys",keyPlaceholder:"Zhipu key...",models:[{id:"glm-5",name:"GLM-5"},{id:"glm-4.7",name:"GLM-4.7"}]},doubao:{name:"Doubao (ByteDance)",keyUrl:"https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey",keyPlaceholder:"Volcano key...",models:[{id:"doubao-seed-2-0-pro",name:"Doubao Seed 2.0 Pro"},{id:"doubao-seed-2-0-code",name:"Doubao Seed 2.0 Code"}]},ollama:{name:"Ollama (Local)",keyPlaceholder:"not required",local:!0,models:[]},openrouter:{name:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",keyPlaceholder:"sk-or-...",models:[]}};function he(t){let e=new TextEncoder().encode(t),s="";for(let o=0;o<e.length;o+=32768)s+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(s)}function Q(t){let e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);return new TextDecoder().decode(s)}var He="0.37.0",n={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},detectedClis:[],roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},I,D,J,et,Pe,W;function ht(){try{let t=n.messages;t.length>50&&(t=[...t.slice(0,5),...t.slice(-45)]);let e=t.map(s=>{if(s.content.startsWith("__DIFF__")&&s.content.length>500)try{let o=JSON.parse(Q(s.content.slice(8)));return{...s,content:`Applied ${o.type||"edit"} to ${o.file||"file"}`}}catch{return s}return s});sessionStorage.setItem("__om_state__",JSON.stringify({messages:e,provider:n.provider,model:n.model,panelOpen:n.panelOpen,activePanel:n.activePanel}))}catch{}}function gt(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(n.messages=t.messages),t.provider&&(n.provider=t.provider),t.model&&(n.model=t.model),t.panelOpen&&(n.panelOpen=t.panelOpen,n.activePanel=t.activePanel||"")}catch{}}function Xe(){if(document.querySelector("openmagic-toolbar"))return;gt();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",I=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Re,I.appendChild(e);let s=document.createElement("div");I.appendChild(s),s.innerHTML=ft(),D=s.querySelector(".om-toolbar"),J=s.querySelector(".om-prompt-input"),et=s.querySelector(".om-prompt-context"),Pe=s.querySelector(".om-panel"),W=s.querySelector(".om-panel-body"),document.body.appendChild(t),yt(s),Tt();try{let i=JSON.parse(localStorage.getItem("__om_pos__")||"");i?.left&&i?.top&&(D.style.left=i.left,D.style.top=i.top,D.style.right="auto",D.style.bottom="auto")}catch{}Ge(),Ve(),Pt();let a=document.querySelector("script[data-openmagic-token]")?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,r=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);a&&Se(r,a).then(()=>(n.connected=!0,ge(),A("config.get"))).then(i=>{n.detectedClis=i.payload?.detectedClis||[];let u=i.payload?.provider||"",c=i.payload?.model||"";n.provider=n.provider||u,n.model=n.model||c,n.configuredProviders=i.payload?.apiKeys||{};for(let m of n.detectedClis)m.installed&&m.authenticated&&(n.configuredProviders[m.id]=!0);let p=X[n.provider];n.hasApiKey=!!(n.configuredProviders[n.provider]||p?.local),n.roots=i.payload?.roots||[],n.panelOpen&&n.activePanel?Z(n.activePanel):(!n.provider||!n.hasApiKey&&!Object.values(n.configuredProviders).some(Boolean)&&!p?.local)&&Z("settings"),ie()}).catch(()=>{n.connected=!1,ge()})}function ft(){return`
|
|
393
|
+
</svg>`,r=new Blob([i],{type:"image/svg+xml;charset=utf-8"}),p=URL.createObjectURL(r);return new Promise(d=>{let m=new Image,u=document.createElement("canvas"),w=Math.min(window.devicePixelRatio||1,2);u.width=s*w,u.height=n*w,m.onload=()=>{URL.revokeObjectURL(p);let k=u.getContext("2d");if(!k){d(null);return}k.scale(w,w),k.drawImage(m,0,0);try{if(u.width>1280){let g=1280/u.width,f=document.createElement("canvas");f.width=1280,f.height=Math.round(u.height*g);let h=f.getContext("2d");if(h){h.drawImage(u,0,0,f.width,f.height),d(f.toDataURL("image/jpeg",.8));return}}d(u.toDataURL("image/jpeg",.8))}catch{d(null)}},m.onerror=()=>{URL.revokeObjectURL(p),d(null)},setTimeout(()=>{URL.revokeObjectURL(p),d(null)},5e3),m.src=p})}async function ft(t){let e=t||document.documentElement,s=e.getBoundingClientRect(),n=document.createElement("canvas");n.width=400,n.height=300;let a=n.getContext("2d");return a?(a.fillStyle="#1a1a2e",a.fillRect(0,0,400,300),a.fillStyle="#e0e0e0",a.font="14px system-ui",a.fillText(`Element: <${e.tagName.toLowerCase()}>`,20,30),a.fillStyle="#888",a.font="12px system-ui",a.fillText(`Size: ${Math.round(s.width)}x${Math.round(s.height)}`,20,55),a.fillText(`Classes: ${(e.className||"").toString().slice(0,40)}`,20,75),a.fillText(`Page: ${window.location.pathname}`,20,95),a.fillStyle="#6c5ce7",a.font="11px system-ui",a.fillText("(Full screenshot unavailable \u2014 context sent as metadata)",20,130),n.toDataURL("image/png")):null}function Ke(t,e,s){if(e>s)return null;try{let n=t.cloneNode(!1);if(n.tagName==="SCRIPT"||n.tagName==="STYLE"||n.tagName==="SVG"||n.tagName==="CANVAS"||n.tagName==="VIDEO"||n.tagName==="IFRAME")return null;let a=window.getComputedStyle(t),i=["display","position","width","height","margin","padding","color","background-color","background","font-size","font-weight","font-family","border","border-radius","flex-direction","justify-content","align-items","gap","grid-template-columns","text-align","overflow"],r="";for(let p of i){let d=a.getPropertyValue(p);d&&d!=="normal"&&d!=="none"&&d!=="auto"&&d!=="0px"&&(r+=`${p}:${d};`)}n.setAttribute("style",r);for(let p=0;p<t.children.length&&p<20;p++){let d=Ke(t.children[p],e+1,s);d&&n.appendChild(d)}return n}catch{return null}}var de=[];var Ge=!1;function Xe(){if(Ge)return;Ge=!0;let t=window.fetch;window.fetch=async function(...n){let a=new Request(...n),i={method:a.method,url:a.url,timestamp:Date.now()};try{let r=await t.apply(this,n);return i.status=r.status,i.duration=Date.now()-i.timestamp,Me(i),r}catch(r){throw i.status=0,i.duration=Date.now()-i.timestamp,Me(i),r}};let e=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(n,a,...i){return this.__om_method=n,this.__om_url=a,this.__om_start=Date.now(),e.apply(this,[n,a,...i])},XMLHttpRequest.prototype.send=function(...n){return this.addEventListener("loadend",()=>{Me({method:this.__om_method||"GET",url:this.__om_url||"",status:this.status,duration:Date.now()-(this.__om_start||Date.now()),timestamp:this.__om_start||Date.now()})}),s.apply(this,n)}}function Me(t){t.url.includes("__openmagic__")||(de.push(t),de.length>50&&de.shift())}function me(){return[...de]}var pe=[],yt=100,Ve=!1;function Je(){if(Ve)return;Ve=!0;let t=["log","warn","error","info","debug"];for(let e of t){let s=console[e];console[e]=function(...n){pe.push({level:e,args:n.map(a=>{try{return typeof a=="object"?JSON.stringify(a).slice(0,500):String(a)}catch{return String(a)}}),timestamp:Date.now()}),pe.length>yt&&pe.shift(),s.apply(console,n)}}}function ue(){return[...pe]}function Ze(t,e){return{selectedElement:t?{tagName:t.tagName,id:t.id,className:t.className,textContent:t.textContent,outerHTML:t.outerHTML,cssSelector:t.cssSelector,computedStyles:t.computedStyles}:void 0,screenshot:e||void 0,networkLogs:me().map(s=>({method:s.method,url:s.url,status:s.status,duration:s.duration,timestamp:s.timestamp})),consoleLogs:ue().map(s=>({level:s.level,args:s.args,timestamp:s.timestamp}))}}var C={sparkle:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.582a.5.5 0 0 1 0 .962L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg>',crosshair:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="22" y1="12" x2="18" y2="12"/><line x1="6" y1="12" x2="2" y2="12"/><line x1="12" y1="6" x2="12" y2="2"/><line x1="12" y1="22" x2="12" y2="18"/></svg>',camera:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',chat:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',settings:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',send:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',x:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',externalLink:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',check:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',copy:'<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',grip:'<svg width="7" height="14" viewBox="0 0 8 14" fill="currentColor"><circle cx="2" cy="2" r="1.2"/><circle cx="6" cy="2" r="1.2"/><circle cx="2" cy="7" r="1.2"/><circle cx="6" cy="7" r="1.2"/><circle cx="2" cy="12" r="1.2"/><circle cx="6" cy="12" r="1.2"/></svg>',network:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',activity:'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>',bug:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m8 2 1.88 1.88M14.12 3.88 16 2M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>',paperclip:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',image:'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',trash:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>',minus:'<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg>'},Z={"claude-code":{name:"Claude Code (CLI)",keyPlaceholder:"not required",local:!0,models:[{id:"claude-code",name:"Claude Code"}]},"codex-cli":{name:"Codex CLI",keyPlaceholder:"not required",local:!0,models:[{id:"codex-cli",name:"Codex CLI"}]},"gemini-cli":{name:"Gemini CLI",keyPlaceholder:"not required",local:!0,models:[{id:"gemini-cli",name:"Gemini CLI"}]},openai:{name:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",keyPlaceholder:"sk-...",models:[{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.2",name:"GPT-5.2 Thinking"},{id:"o3",name:"o3"},{id:"o4-mini",name:"o4-mini"},{id:"gpt-4.1",name:"GPT-4.1"},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini"}]},anthropic:{name:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",keyPlaceholder:"sk-ant-...",models:[{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5"}]},google:{name:"Google Gemini",keyUrl:"https://aistudio.google.com/apikey",keyPlaceholder:"AIza...",models:[{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro"},{id:"gemini-3-flash-preview",name:"Gemini 3 Flash"},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash"}]},xai:{name:"xAI (Grok)",keyUrl:"https://console.x.ai/team/default/api-keys",keyPlaceholder:"xai-...",models:[{id:"grok-4.20-0309-reasoning",name:"Grok 4.20 Reasoning"},{id:"grok-4-1-fast-non-reasoning",name:"Grok 4.1 Fast"}]},deepseek:{name:"DeepSeek",keyUrl:"https://platform.deepseek.com/api_keys",keyPlaceholder:"sk-...",models:[{id:"deepseek-chat",name:"DeepSeek V3.2"},{id:"deepseek-reasoner",name:"DeepSeek R1"}]},mistral:{name:"Mistral",keyUrl:"https://console.mistral.ai/api-keys",keyPlaceholder:"...",models:[{id:"mistral-large-3-25-12",name:"Mistral Large 3"},{id:"codestral-2508",name:"Codestral"},{id:"devstral-2-25-12",name:"Devstral 2"}]},groq:{name:"Groq",keyUrl:"https://console.groq.com/keys",keyPlaceholder:"gsk_...",models:[{id:"meta-llama/llama-4-scout-17b-16e-instruct",name:"Llama 4 Scout"},{id:"llama-3.3-70b-versatile",name:"Llama 3.3 70B"}]},minimax:{name:"MiniMax",keyUrl:"https://platform.minimax.chat/user-center/basic-information/interface-key",keyPlaceholder:"MiniMax key...",models:[{id:"MiniMax-M2.7",name:"MiniMax M2.7"},{id:"MiniMax-M2.5",name:"MiniMax M2.5"}]},moonshot:{name:"Kimi (Moonshot)",keyUrl:"https://platform.moonshot.cn/console/api-keys",keyPlaceholder:"Moonshot key...",models:[{id:"kimi-k2.5",name:"Kimi K2.5"},{id:"kimi-k2-thinking",name:"Kimi K2 Thinking"}]},qwen:{name:"Qwen (Alibaba)",keyUrl:"https://dashscope.console.aliyun.com/apiKey",keyPlaceholder:"DashScope key...",models:[{id:"qwen3.5-plus",name:"Qwen 3.5 Plus"},{id:"qwen-max",name:"Qwen Max"}]},zhipu:{name:"Zhipu AI (GLM)",keyUrl:"https://open.bigmodel.cn/usercenter/apikeys",keyPlaceholder:"Zhipu key...",models:[{id:"glm-5",name:"GLM-5"},{id:"glm-4.7",name:"GLM-4.7"}]},doubao:{name:"Doubao (ByteDance)",keyUrl:"https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey",keyPlaceholder:"Volcano key...",models:[{id:"doubao-seed-2-0-pro",name:"Doubao Seed 2.0 Pro"},{id:"doubao-seed-2-0-code",name:"Doubao Seed 2.0 Code"}]},ollama:{name:"Ollama (Local)",keyPlaceholder:"not required",local:!0,models:[]},openrouter:{name:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",keyPlaceholder:"sk-or-...",models:[]}};function ge(t){let e=new TextEncoder().encode(t),s="";for(let n=0;n<e.length;n+=32768)s+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(s)}function te(t){let e=atob(t),s=new Uint8Array(e.length);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return new TextDecoder().decode(s)}var _e="0.38.0",o={connected:!1,panelOpen:!1,activePanel:"",selecting:!1,selectedElement:null,screenshot:null,messages:[],streaming:!1,streamContent:"",provider:"",model:"",hasApiKey:!1,configuredProviders:{},detectedClis:[],roots:[],updateAvailable:!1,latestVersion:"",saveStatus:"",networkCapture:!1,attachments:[],groundedFiles:[],minimized:!1},_,q,J,st,Re,U;function bt(){try{let t=o.messages;t.length>50&&(t=[...t.slice(0,5),...t.slice(-45)]);let e=t.map(s=>{if(s.content.startsWith("__DIFF__")&&s.content.length>500)try{let n=JSON.parse(te(s.content.slice(8)));return{...s,content:`Applied ${n.type||"edit"} to ${n.file||"file"}`}}catch{return s}return s});sessionStorage.setItem("__om_state__",JSON.stringify({messages:e,provider:o.provider,model:o.model,panelOpen:o.panelOpen,activePanel:o.activePanel}))}catch{}}function xt(){try{let t=JSON.parse(sessionStorage.getItem("__om_state__")||"{}");t.messages?.length&&(o.messages=t.messages),t.provider&&(o.provider=t.provider),t.model&&(o.model=t.model),t.panelOpen&&(o.panelOpen=t.panelOpen,o.activePanel=t.activePanel||"")}catch{}}function Ye(){if(document.querySelector("openmagic-toolbar"))return;xt();let t=document.createElement("openmagic-toolbar");t.dataset.openmagic="true",_=t.attachShadow({mode:"closed"});let e=document.createElement("style");e.textContent=Ie,_.appendChild(e);let s=document.createElement("div");_.appendChild(s),s.innerHTML=vt(),q=s.querySelector(".om-toolbar"),J=s.querySelector(".om-prompt-input"),st=s.querySelector(".om-prompt-context"),Re=s.querySelector(".om-panel"),U=s.querySelector(".om-panel-body"),document.body.appendChild(t),wt(s),_t();try{let r=JSON.parse(localStorage.getItem("__om_pos__")||"");r?.left&&r?.top&&(q.style.left=r.left,q.style.top=r.top,q.style.right="auto",q.style.bottom="auto")}catch{}Xe(),Je(),At();let a=document.querySelector("script[data-openmagic-token]")?.dataset.openmagicToken||window.__OPENMAGIC_TOKEN__,i=parseInt(window.location.port,10)||(window.location.protocol==="https:"?443:80);a&&$e(i,a).then(()=>(o.connected=!0,fe(),A("config.get"))).then(r=>{o.detectedClis=r.payload?.detectedClis||[];let p=r.payload?.provider||"",d=r.payload?.model||"";o.provider=o.provider||p,o.model=o.model||d,o.configuredProviders=r.payload?.apiKeys||{};for(let u of o.detectedClis)u.installed&&u.authenticated&&(o.configuredProviders[u.id]=!0);let m=Z[o.provider];o.hasApiKey=!!(o.configuredProviders[o.provider]||m?.local),o.roots=r.payload?.roots||[],o.panelOpen&&o.activePanel?Y(o.activePanel):(!o.provider||!o.hasApiKey&&!Object.values(o.configuredProviders).some(Boolean)&&!m?.local)&&Y("settings"),ce()}).catch(()=>{o.connected=!1,fe()})}function vt(){return`
|
|
394
394
|
<div class="om-toolbar">
|
|
395
395
|
<div class="om-toolbar-header">
|
|
396
|
-
<span class="om-grab">${
|
|
396
|
+
<span class="om-grab">${C.grip}</span>
|
|
397
397
|
<span class="om-pill-brand">
|
|
398
398
|
<span class="om-pill-text">\u2728OpenMagic\u{1FA84}</span>
|
|
399
399
|
</span>
|
|
400
400
|
<span class="om-pill-divider"></span>
|
|
401
|
-
<button class="om-pill-btn" data-action="select" title="Select element">${
|
|
402
|
-
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${
|
|
403
|
-
<button class="om-pill-btn" data-action="network" title="Network & Performance">${
|
|
401
|
+
<button class="om-pill-btn" data-action="select" title="Select element">${C.crosshair}</button>
|
|
402
|
+
<button class="om-pill-btn" data-action="screenshot" title="Screenshot">${C.camera}</button>
|
|
403
|
+
<button class="om-pill-btn" data-action="network" title="Network & Performance">${C.activity}</button>
|
|
404
404
|
<span class="om-pill-divider"></span>
|
|
405
|
-
<button class="om-pill-btn" data-action="chat" title="Chat">${
|
|
406
|
-
<button class="om-pill-btn" data-action="settings" title="Settings">${
|
|
407
|
-
<button class="om-pill-btn" data-action="minimize" title="Minimize">${
|
|
405
|
+
<button class="om-pill-btn" data-action="chat" title="Chat">${C.chat}</button>
|
|
406
|
+
<button class="om-pill-btn" data-action="settings" title="Settings">${C.settings}</button>
|
|
407
|
+
<button class="om-pill-btn" data-action="minimize" title="Minimize">${C.minus}</button>
|
|
408
408
|
<span class="om-status-dot disconnected"></span>
|
|
409
409
|
</div>
|
|
410
410
|
<div class="om-panel om-hidden">
|
|
411
411
|
<div class="om-panel-header">
|
|
412
412
|
<span class="om-panel-title"></span>
|
|
413
|
-
<span class="om-panel-version">v${
|
|
414
|
-
<button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${
|
|
415
|
-
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${
|
|
416
|
-
<button class="om-panel-close" data-action="close-panel">${
|
|
413
|
+
<span class="om-panel-version">v${_e}</span>
|
|
414
|
+
<button class="om-panel-bug" data-action="report-issue" title="Report a bug on GitHub">${C.bug}</button>
|
|
415
|
+
<button class="om-panel-clear" data-action="clear-chat" title="Clear chat">${C.trash}</button>
|
|
416
|
+
<button class="om-panel-close" data-action="close-panel">${C.x}</button>
|
|
417
417
|
</div>
|
|
418
418
|
<div class="om-panel-body"></div>
|
|
419
419
|
</div>
|
|
@@ -427,39 +427,41 @@
|
|
|
427
427
|
<div class="om-prompt-attachments"></div>
|
|
428
428
|
<div class="om-prompt-row">
|
|
429
429
|
<div class="om-prompt-context"></div>
|
|
430
|
-
<button class="om-prompt-attach" data-action="attach-image" title="Attach image">${
|
|
430
|
+
<button class="om-prompt-attach" data-action="attach-image" title="Attach image">${C.paperclip}</button>
|
|
431
431
|
<input class="om-prompt-input" type="text" placeholder="Describe what to change..." autocomplete="off" />
|
|
432
|
-
<button class="om-prompt-send" data-action="prompt-send">${
|
|
432
|
+
<button class="om-prompt-send" data-action="prompt-send">${C.send}</button>
|
|
433
433
|
<input type="file" class="om-file-input om-hidden" accept="image/*" multiple />
|
|
434
434
|
</div>
|
|
435
|
-
</div>`}function
|
|
436
|
-
`).map(
|
|
437
|
-
`)
|
|
438
|
-
|
|
439
|
-
`)
|
|
440
|
-
|
|
435
|
+
</div>`}function wt(t){t.addEventListener("click",n=>{let a=n.target.closest("[data-action]");if(!a)return;n.preventDefault(),n.stopPropagation();let i=a.dataset.action;nt(i,a)}),t.addEventListener("change",n=>{let a=n.target,i=a.dataset.field;i&&(i==="provider"?(o.provider=a.value,o.model=Z[o.provider]?.models[0]?.id||"",o.hasApiKey=o.configuredProviders[o.provider]||Z[o.provider]?.local||!1,o.saveStatus="",O()):i==="model"&&(o.model=a.value))}),J.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),He())});let e=t.querySelector(".om-file-input");e&&e.addEventListener("change",()=>{Te(e.files),e.value=""});let s=t.querySelector(".om-prompt-row");s&&(s.addEventListener("dragover",n=>{n.preventDefault(),s.style.borderColor="rgba(108, 92, 231, 0.5)"}),s.addEventListener("dragleave",()=>{s.style.borderColor=""}),s.addEventListener("drop",n=>{n.preventDefault(),s.style.borderColor="";let a=n.dataTransfer;a?.files?.length&&Te(a.files)}),J.addEventListener("paste",n=>{let a=n.clipboardData?.items;if(a){for(let i=0;i<a.length;i++)if(a[i].type.startsWith("image/")){let r=a[i].getAsFile();if(r){let p=new DataTransfer;p.items.add(r),Te(p.files)}}}})),je(n=>{n.type==="reconnected"&&(o.connected=!0,fe())}),document.addEventListener("keydown",n=>{if((n.ctrlKey||n.metaKey)&&n.shiftKey&&(n.key==="O"||n.key==="o")){if(n.preventDefault(),o.minimized){o.minimized=!1,q.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot").forEach(r=>r.style.display="");let i=_.querySelector(".om-prompt-row");i&&i.classList.remove("om-hidden")}else o.panelOpen?ye():Y("chat");return}if((n.ctrlKey||n.metaKey)&&(n.key==="k"||n.key==="K")&&!n.shiftKey){n.preventDefault(),o.panelOpen||Y("chat"),J.focus();return}if((n.ctrlKey||n.metaKey)&&(n.key==="z"||n.key==="Z")&&!n.shiftKey&&(_.activeElement||o.panelOpen)){let a=_.querySelector('[data-action="undo-diff"]');if(a){n.preventDefault(),at(a);return}}if((n.ctrlKey||n.metaKey)&&n.key==="."){let a=_.querySelector('[data-action="apply-all"]');if(a&&!_.querySelector(".om-apply-bar.om-hidden")){n.preventDefault(),nt("apply-all",a);return}}if(n.key==="Escape"){if(o.selecting)return;o.panelOpen&&(ye(),n.preventDefault())}}),J.addEventListener("keydown",n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),He())})}function Ae(t){return o.roots.length>0?o.roots[0]+"/"+t:t}function kt(t,e){let s=e.split(`
|
|
436
|
+
`),n=s.map(l=>l.trim()).filter(l=>l.length>0);if(n.length===0)return null;let a=t.split(`
|
|
437
|
+
`);for(let l=0;l<=a.length-n.length;l++){let g=!0,f=0,h=0;for(let c=l;c<a.length&&h<n.length;c++){if(a[c].trim()===""){f++;continue}if(a[c].trim()!==n[h]){g=!1;break}h++,f++}if(g&&h===n.length)return Le(t,a,l,f)}let i=s.map(l=>l.trimStart());for(let l=0;l<=a.length-i.length;l++){let g=!0;for(let f=0;f<i.length;f++)if(i[f]!==""&&a[l+f].trimStart()!==i[f].trimEnd()){g=!1;break}if(g)return Le(t,a,l,i.length)}let r=n.join(`
|
|
438
|
+
`).toLowerCase(),p=n.length,d=0,m=-1,u=0,w=Math.max(1,Math.floor(p*.8)),k=Math.min(a.length,Math.ceil(p*1.2));for(let l=w;l<=k;l++)for(let g=0;g<=a.length-l;g++){let f=a.slice(g,g+l).map(c=>c.trim()).filter(c=>c).join(`
|
|
439
|
+
`).toLowerCase(),h=St(r,f);h>d&&(d=h,m=g,u=l)}return d>=.8&&m>=0?Le(t,a,m,u):null}function Le(t,e,s,n){let a=0;for(let r=0;r<s;r++)a+=e[r].length+1;let i=a;for(let r=s;r<s+n;r++)i+=e[r].length+1;return i>0&&i<=t.length&&t[i-1]===`
|
|
440
|
+
`&&i--,{start:a,end:i}}function St(t,e){if(t===e)return 1;if(!t||!e)return 0;let s=new Set,n=new Set;for(let i=0;i<=t.length-3;i++)s.add(t.slice(i,i+3));for(let i=0;i<=e.length-3;i++)n.add(e.slice(i,i+3));if(s.size===0||n.size===0)return 0;let a=0;for(let i of s)n.has(i)&&a++;return a/(s.size+n.size-a)}async function Qe(t){let e=t.dataset.file,s=t.dataset.search,n=t.dataset.replace;if(!e||!s||!n)return;t.disabled=!0,t.innerHTML='<span class="om-spinner"></span>',t.style.opacity="0.5",t.style.pointerEvents="none";let a=t.closest(".om-diff-card");if(a){let d=a.querySelector(".om-diff-actions");d&&(d.innerHTML='<span class="om-spinner"></span> Applying...')}await new Promise(d=>requestAnimationFrame(d));let i,r;try{i=te(s),r=te(n)}catch{o.messages.push({role:"system",content:`Failed to decode diff data for ${e}`}),O();return}let p=Ae(e);try{if(!i&&r){if((await A("fs.write",{path:p,content:r}))?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e}`});else{let f=a?.dataset.diffIdx;f!==void 0?o.messages[parseInt(f)]={role:"system",content:`Created ${e}`}:o.messages.push({role:"system",content:`Created ${e}`})}O(),se();return}let d,m=p,u=[p];e!==p&&u.push(e);let w=e.split("/").pop()||e,k=o.roots[0]||"",l=k?`${k}/${w}`:w;l!==p&&l!==e&&u.push(l);for(let g of u){let h=(await A("fs.read",{path:g}).catch(()=>null))?.payload?.content;if(h!=null&&String(h).length>0){d=String(h),m=g;break}}if(!d)o.messages.push({role:"system",content:`Could not read ${e} \u2014 tried: ${u.join(", ")}`});else{let g=d.split(i).length-1;if(g===1){let f=await A("fs.write",{path:m,content:d.replace(i,r)});if(f?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e} - ${f.payload?.error||"unknown"}`});else{let h=a?.dataset.diffIdx;h!==void 0?o.messages[parseInt(h)]={role:"system",content:`Applied change to ${e}. Reloading...`}:o.messages.push({role:"system",content:`Applied change to ${e}. Reloading...`})}}else if(g>1)o.messages.push({role:"system",content:`Found ${g} exact matches in ${e} \u2014 expected 1. Edit not applied.`});else{let f=kt(d,i);if(f){let h=d.slice(0,f.start)+r+d.slice(f.end),c=await A("fs.write",{path:m,content:h});if(c?.payload?.ok===!1)o.messages.push({role:"system",content:`Write failed: ${e} - ${c.payload?.error||"unknown"}`});else{let $=a?.dataset.diffIdx;$!==void 0?o.messages[parseInt($)]={role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`}:o.messages.push({role:"system",content:`Applied change to ${e} (fuzzy match). Reloading...`})}}else o.messages.push({role:"system",content:`No matching code found in ${e}. The file may have changed since the suggestion.`})}}}catch(d){o.messages.push({role:"system",content:`Failed to apply: ${e} \u2014 ${d.message}`})}O(),se(),setTimeout(()=>{window.location.reload()},1500)}function et(t){t.disabled=!0,t.style.opacity="0.5";let e=t.dataset.idx;if(e!==void 0){let s=parseInt(e);try{let n=JSON.parse(te(o.messages[s]?.content.slice(8)||"")),a=(n.search||"").split(`
|
|
441
|
+
`)[0].slice(0,80),i=(n.replace||"").split(`
|
|
442
|
+
`)[0].slice(0,80);o.messages[s]={role:"system",content:`Rejected change to ${n.file||"file"}: "${a}" \u2192 "${i}"`}}catch{o.messages[s]={role:"system",content:"Change rejected"}}}O(),se()}function $t(t){let e=_.querySelector(".om-apply-bar");if(e)if(t>0){e.classList.remove("om-hidden");let s=e.querySelector(".om-apply-bar-text");s&&(s.textContent=`${t} change${t>1?"s":""} ready`)}else e.classList.add("om-hidden")}function tt(){let t=_.querySelector(".om-apply-bar");t&&t.classList.add("om-hidden")}async function at(t){let e=t.dataset.file;if(!e)return;let s=Ae(e);try{(await A("fs.undo",{path:s}))?.payload?.ok?o.messages.push({role:"system",content:`Reverted change to ${e}`}):o.messages.push({role:"system",content:`No backup found for ${e}`})}catch{o.messages.push({role:"system",content:`Could not revert ${e} \u2014 backup may not exist`})}O()}async function nt(t,e){switch(t){case"select":Ht();break;case"screenshot":Pt();break;case"chat":Ce("chat");break;case"settings":Ce("settings");break;case"close-panel":ye();break;case"prompt-send":He();break;case"save-settings":Lt();break;case"get-key":{let s=e.dataset.url;s&&window.open(s,"_blank","noopener");break}case"change-key":{let s=_.querySelector("[data-key-change]");s&&s.classList.remove("om-hidden"),e.style.display="none";break}case"network":Ce("chat"),Ct();break;case"attach-image":Tt();break;case"remove-attachment":{let s=parseInt(e.dataset.idx||"0",10);o.attachments.splice(s,1),Ne();break}case"apply-diff":Qe(e);break;case"reject-diff":et(e);break;case"apply-all":{let s=Array.from(_.querySelectorAll('[data-action="apply-diff"]'));if(s.length===0)break;let n=new Set;for(let r of s){let p=r.dataset.file;p&&n.add(Ae(p))}let a=new Map;for(let r of n)try{let p=await A("fs.read",{path:r}).catch(()=>null);p?.payload?.content&&a.set(r,String(p.payload.content))}catch{}let i=!1;for(let r of s)try{await Qe(r)}catch{i=!0;break}if(i&&a.size>0){for(let[r,p]of a)try{await A("fs.write",{path:r,content:p})}catch{}o.messages.push({role:"system",content:"Batch apply failed \u2014 all changes reverted."}),O()}tt();break}case"reject-all":{let s=_.querySelectorAll('[data-action="reject-diff"]');for(let n of Array.from(s))et(n);tt();break}case"undo-diff":at(e);break;case"clear-chat":{o.messages=[];try{sessionStorage.removeItem("__om_state__")}catch{}O();break}case"copy-msg":{let s=parseInt(e.dataset.idx||"0",10);e.innerHTML='<span class="om-spinner"></span>',ot(s).then(n=>{try{navigator.clipboard.writeText(n)}catch{}e.innerHTML=C.check,setTimeout(()=>{e.innerHTML=C.copy},1500)});break}case"report-issue":{e.innerHTML='<span class="om-spinner"></span>',ot().then(s=>{try{navigator.clipboard.writeText(s)}catch{}e.innerHTML=C.bug,window.open("https://github.com/Kalmuraee/OpenMagic/issues/new?template=bug_report.yml","_blank","noopener"),o.messages.push({role:"system",content:"Debug info copied to clipboard. Paste it in the Debug Info field on GitHub."}),o.panelOpen&&O()});break}case"clear-element":o.selectedElement=null,le();break;case"clear-screenshot":o.screenshot=null,le();break;case"minimize":{o.minimized=!o.minimized;let s=_.querySelector(".om-panel"),n=_.querySelector(".om-prompt-row"),a=_.querySelector(".om-prompt-attachments"),i=q.querySelectorAll(".om-pill-btn:not([data-action='minimize']), .om-pill-divider, .om-status-dot");o.minimized?(s&&s.classList.add("om-hidden"),n&&n.classList.add("om-hidden"),a&&a.classList.add("om-hidden"),i.forEach(r=>r.style.display="none")):(n&&n.classList.remove("om-hidden"),a&&a.classList.remove("om-hidden"),i.forEach(r=>r.style.display=""),o.panelOpen&&o.activePanel&&s&&s.classList.remove("om-hidden"));break}}}function fe(){let t=_.querySelector(".om-status-dot");if(t){let e=o.updateAvailable?"outdated":o.connected?"connected":"disconnected";t.className=`om-status-dot ${e}`,t.setAttribute("title",o.updateAvailable?`v${o.latestVersion} available \u2014 run npx openmagic@latest`:o.connected?"Connected":"Disconnected")}}function ce(){_.querySelectorAll(".om-pill-btn").forEach(t=>{let e=t.dataset.action;t.classList.toggle("active",e===o.activePanel||e==="select"&&o.selecting)})}function le(){let t=[];o.selectedElement&&t.push(`<span class="om-prompt-chip">${o.selectedElement.tagName}${o.selectedElement.id?"#"+o.selectedElement.id:""} <button class="om-prompt-chip-x" data-action="clear-element">${C.x}</button></span>`),o.screenshot&&t.push(`<span class="om-prompt-chip">Screenshot <button class="om-prompt-chip-x" data-action="clear-screenshot">${C.x}</button></span>`),o.attachments.length&&t.push(`<span class="om-prompt-chip">${o.attachments.length} image${o.attachments.length>1?"s":""}</span>`),o.groundedFiles.length&&t.push(`<span class="om-prompt-chip">${o.groundedFiles.length} files grounded</span>`),st.innerHTML=t.join("")}function Y(t){o.panelOpen=!0,o.activePanel=t,Re.classList.remove("om-hidden");let e=_.querySelector(".om-panel-title");e&&(e.textContent=t==="settings"?"Settings":"Chat"),O(),ce()}function ye(){o.panelOpen=!1,o.activePanel="",Re.classList.add("om-hidden"),ce()}function Ce(t){o.panelOpen&&o.activePanel===t?ye():Y(t)}function O(){o.activePanel==="settings"?U.innerHTML=Et():o.activePanel==="chat"&&(U.innerHTML=Mt(),se()),bt()}function Et(){let t=Object.entries(Z).map(([l,g])=>{let f=o.detectedClis.find(c=>c.id===l),h="";return f?f.installed&&f.authenticated?h=" \u2713 ready":f.installed?h=" (not logged in)":h=" (not installed)":h=o.configuredProviders[l]||g.local?" \u2713":"",`<option value="${l}" ${o.provider===l?"selected":""}>${g.name}${h}</option>`}).join(""),e=Z[o.provider],s=e?e.models.map(l=>`<option value="${l.id}" ${o.model===l.id?"selected":""}>${l.name}</option>`).join(""):'<option value="">Select provider first</option>',n=e?.local||!1,a=e?.keyUrl||"",i=e?.keyPlaceholder||"Enter API key...",r=o.configuredProviders[o.provider]||!1,p=o.updateAvailable?`<div class="om-update-banner">v${o.latestVersion} available <code class="om-update-cmd">npx openmagic@latest</code></div>`:"",d=r||n?`<div class="om-status om-status-success">${C.check} ${e?.name||"Provider"} connected</div>`:"",m=o.saveStatus==="saving"?'<span class="om-spinner"></span> Saving...':o.saveStatus==="saved"?`${C.check} Saved`:"Save",u=o.saveStatus==="saving"?"om-btn om-btn-saving":o.saveStatus==="saved"?"om-btn om-btn-saved":"om-btn",w=o.saveStatus==="saving"?"disabled":"",k="";return!n&&o.provider&&(r?k=`
|
|
441
443
|
<div class="om-field">
|
|
442
444
|
<label class="om-label">API Key</label>
|
|
443
445
|
<div class="om-key-configured">
|
|
444
|
-
${
|
|
446
|
+
${C.check} <span>Key configured</span>
|
|
445
447
|
<button class="om-btn-change-key" data-action="change-key">Change</button>
|
|
446
448
|
</div>
|
|
447
449
|
<div class="om-key-change-row om-hidden" data-key-change>
|
|
448
450
|
<div class="om-key-row">
|
|
449
|
-
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${
|
|
450
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
451
|
+
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${i}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
|
452
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${C.externalLink} Get key</button>`:""}
|
|
451
453
|
</div>
|
|
452
454
|
</div>
|
|
453
|
-
</div>`:
|
|
455
|
+
</div>`:k=`
|
|
454
456
|
<div class="om-field">
|
|
455
457
|
<label class="om-label">API Key</label>
|
|
456
458
|
<div class="om-key-row">
|
|
457
|
-
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${
|
|
458
|
-
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${
|
|
459
|
+
<input type="text" class="om-input om-key-input" data-field="apiKey" placeholder="${i}" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore="true" data-form-type="other" />
|
|
460
|
+
${a?`<button class="om-btn-get-key" data-action="get-key" data-url="${a}">${C.externalLink} Get key</button>`:""}
|
|
459
461
|
</div>
|
|
460
462
|
${a?`<div class="om-key-hint"><a data-action="get-key" data-url="${a}">Get your ${e?.name||""} API key here</a></div>`:""}
|
|
461
463
|
</div>`),`
|
|
462
|
-
${
|
|
464
|
+
${p}
|
|
463
465
|
<div class="om-settings">
|
|
464
466
|
<div class="om-field">
|
|
465
467
|
<label class="om-label">Provider</label>
|
|
@@ -469,31 +471,31 @@
|
|
|
469
471
|
<label class="om-label">Model</label>
|
|
470
472
|
<select class="om-select" data-field="model"><option value="">Select Model...</option>${s}</select>
|
|
471
473
|
</div>
|
|
472
|
-
${
|
|
473
|
-
<button class="${
|
|
474
|
-
${
|
|
475
|
-
</div>`}function
|
|
476
|
-
<div class="om-diff-file">${
|
|
477
|
-
${
|
|
478
|
-
<div class="om-diff-added">${
|
|
474
|
+
${k}
|
|
475
|
+
<button class="${u}" data-action="save-settings" ${w}>${m}</button>
|
|
476
|
+
${d}
|
|
477
|
+
</div>`}function Mt(){if(!o.provider||!o.hasApiKey&&!Z[o.provider]?.local)return'<div class="om-status om-status-error">Configure your provider in Settings first</div>';let t=o.messages.map((n,a)=>{if(n.content.startsWith("__DIFFGROUP__"))return"";if(n.content.startsWith("__DIFF__"))try{let r=JSON.parse(te(n.content.slice(8))),p=r.type==="create"||!r.search&&r.replace,d=ge(r.search||""),m=ge(r.replace||"");return`<div class="om-diff-card" data-diff-idx="${a}">
|
|
478
|
+
<div class="om-diff-file">${X(p?"Create new file":"Edit")}: ${X(r.file)}</div>
|
|
479
|
+
${r.search?`<div class="om-diff-removed">${X(r.search.slice(0,200))}</div>`:""}
|
|
480
|
+
<div class="om-diff-added">${X((r.replace||"").slice(0,300))}</div>
|
|
479
481
|
<div class="om-diff-actions">
|
|
480
|
-
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${
|
|
482
|
+
<button class="om-btn om-btn-sm" data-action="apply-diff" data-file="${X(r.file)}" data-search="${d}" data-replace="${m}">Apply</button>
|
|
481
483
|
<button class="om-btn-secondary om-btn-sm" data-action="reject-diff" data-idx="${a}">Reject</button>
|
|
482
484
|
</div>
|
|
483
|
-
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(
|
|
484
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
485
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
486
|
-
// [TRUNCATED]`),$.push({path:
|
|
487
|
-
// [FILE TRUNCATED \u2014 showing ${
|
|
488
|
-
/* [TRUNCATED] */`),$.push({path:
|
|
489
|
-
All network requests (${
|
|
490
|
-
Fetch/XHR requests (${a.length}):`);for(let
|
|
491
|
-
Console errors: ${
|
|
492
|
-
Slowest resources:`);for(let
|
|
493
|
-
`)}),
|
|
485
|
+
</div>`}catch{return'<div class="om-msg om-msg-system">Malformed diff data</div>'}if(n.content.startsWith("Applied change to ")){let r=n.content.replace("Applied change to ","").replace(/ \(fuzzy match.*?\)/g,"").replace(". Reloading...","");return`<div class="om-msg om-msg-system">${X(n.content)} <button class="om-undo-btn" data-action="undo-diff" data-file="${X(r)}">Undo</button></div>`}let i=n.role==="user"||n.role==="assistant"?`<button class="om-copy-btn" data-action="copy-msg" data-idx="${a}" title="Copy">${C.copy}</button>`:"";return n.role==="assistant"?`<div class="om-msg om-msg-assistant">${Rt(n.content)}${i}</div>`:`<div class="om-msg om-msg-${n.role}">${X(n.content)}${i}</div>`}).join(""),e=o.streaming?'<div class="om-msg om-msg-assistant"><span class="om-spinner"></span> Generating response...</div>':"";return`<div class="om-chat-messages">${!o.messages.length&&!o.streaming?'<div class="om-chat-empty">Select an element or type below to start</div>':""}${t}${e}</div>`}function se(){requestAnimationFrame(()=>{let t=U.querySelector(".om-chat-messages");t&&(t.scrollTop=t.scrollHeight)})}async function Lt(){let e=U.querySelector('[data-field="apiKey"]')?.value||"";if(!o.provider){o.saveStatus="error",he(),setTimeout(()=>{o.saveStatus="",O()},2e3);return}if(!Ee()){o.saveStatus="error",he();let n=U.querySelector('[data-action="save-settings"]');n&&(n.innerHTML="Not connected - check terminal"),setTimeout(()=>{o.saveStatus="",O()},3e3);return}let s={provider:o.provider,model:o.model};e&&(s.apiKey=e),o.saveStatus="saving",he();try{let n=await Promise.race([A("config.set",s),new Promise((a,i)=>setTimeout(()=>i(new Error("Save timed out")),8e3))]);e&&o.provider&&(o.configuredProviders[o.provider]=!0),o.hasApiKey=!!(e||o.configuredProviders[o.provider]),o.saveStatus="saved",he(),setTimeout(()=>{o.saveStatus="",o.activePanel==="settings"&&Y("chat")},1200)}catch(n){o.saveStatus="error";let a=U.querySelector('[data-action="save-settings"]'),i=(n?.message||"").includes("timeout")?"Connection timeout - is the CLI running?":(n?.message||"").includes("connected")?"Not connected to OpenMagic server":`Save failed: ${n?.message||"Unknown error"}`;a&&(a.innerHTML=i,a.className="om-btn",a.disabled=!1),setTimeout(()=>{o.saveStatus="",O()},4e3)}}function he(){let t=U.querySelector('[data-action="save-settings"]');t&&(o.saveStatus==="saving"?(t.innerHTML='<span class="om-spinner"></span> Saving...',t.className="om-btn om-btn-saving",t.disabled=!0):o.saveStatus==="saved"?(t.innerHTML=`${C.check} Saved`,t.className="om-btn om-btn-saved",t.disabled=!1):o.saveStatus==="error"?(t.innerHTML="Save failed - try again",t.className="om-btn",t.disabled=!1):(t.innerHTML="Save",t.className="om-btn",t.disabled=!1))}async function He(){let t=J.value.trim();if(!t||o.streaming)return;if(!o.provider||!o.hasApiKey&&!Z[o.provider]?.local){Y("settings");return}o.messages.push({role:"user",content:t}),o.streaming=!0,o.streamContent="",J.value="",Y("chat");let e=Ze(o.selectedElement,o.screenshot);e.pageUrl=window.location.href,e.pageTitle=document.title,o.attachments.length>0&&(e.screenshot||(e.screenshot=o.attachments[0]),e.attachments=[...o.attachments]);let s=8,n=48e3,a=/\.(?:[cm]?[jt]sx?|svelte|vue|astro|html?|css|scss|less|php|py)$/i,i=U.querySelector(".om-msg-assistant:last-child");i&&(i.innerHTML='<span class="om-spinner"></span> Reading project files...');try{let m=await A("fs.list",{});m?.payload?.projectTree&&(e.projectTree=m.payload.projectTree);let w=(m?.payload?.files||[]).filter(b=>b.type==="file"&&a.test(b.path)),k=[t];if(o.selectedElement&&(o.selectedElement.id&&k.push(o.selectedElement.id),o.selectedElement.className&&k.push(o.selectedElement.className),o.selectedElement.textContent&&k.push(o.selectedElement.textContent.slice(0,100)),o.selectedElement.componentHint&&k.push(o.selectedElement.componentHint),o.selectedElement.ancestry))for(let b of o.selectedElement.ancestry)k.push(b);let l=k.filter(Boolean).join(" ").toLowerCase().split(/[^a-z0-9_-]+/).filter(b=>b.length>=2&&!["the","to","in","of","and","div","span","class","style"].includes(b)),f=window.location.pathname.split("/").filter(b=>b.length>1&&!/^\d+$/.test(b)),h="";if(o.selectedElement?.componentHint||f.length){let b=(o.selectedElement?.componentHint||"").toLowerCase(),v=new Map;for(let H of w){let L=H.path.split("/")[0];if(!L||L.includes("."))continue;let j=H.path.toLowerCase(),z=v.get(L)||0;b&&j.includes(b)&&(z+=10);for(let G of f)j.includes(G.toLowerCase())&&(z+=5);/(component|page|route|layout)/.test(j)&&(z+=1),v.set(L,z)}let S=0;for(let[H,L]of v)L>S&&(S=L,h=H)}let c=w.map(b=>{let v=0,S=b.path.toLowerCase(),H=S.replace(/\([^)]+\)\//g,"");if(h){let L=b.path.split("/")[0];L===h?v+=20:L!==h&&!b.path.includes("/")?v+=0:v-=15}for(let L of f)H.includes(L.toLowerCase())&&(v+=15);if(o.selectedElement?.componentHint){let L=o.selectedElement.componentHint.toLowerCase();S.includes(L)&&(v+=12)}for(let L of l)S.includes(L)&&(v+=5);return/(component|page|route|layout|template|view)/.test(S)&&(v+=3),/page\.[jt]sx?$|layout\.[jt]sx?$|\+page\.svelte$/.test(S)&&(v+=5),{...b,score:v}}).sort((b,v)=>v.score-b.score),$=[],x=new Set,E=0,I=c.slice(0,s).filter(b=>b.score>0),D=o.roots[0]||"",Q=await Promise.all(I.map(b=>{let v=D?`${D}/${b.path}`:b.path;return A("fs.read",{path:v}).catch(()=>null)}));for(let b=0;b<I.length;b++){let v=I[b];if(E>=n)break;try{let S=String(Q[b]?.payload?.content||"");if(!S)continue;let H=Math.min(12e3,n-E),L=S.slice(0,H);S.length>H&&(L+=`
|
|
486
|
+
// [FILE TRUNCATED \u2014 showing ${H} of ${S.length} chars]`),$.push({path:v.path,content:L}),x.add(v.path),E+=L.length;let j=v.path.replace(/\.[^.]+$/,""),z=[".module.css",".module.scss",".css",".scss",".styles.ts"];for(let ee of z){let y=j+ee;if(x.has(y)||E>=n)continue;if(w.find(P=>P.path===y)){try{let P=await A("fs.read",{path:D?`${D}/${y}`:y}),T=String(P?.payload?.content||"");if(T){let N=Math.min(4e3,n-E),R=T.slice(0,N);T.length>N&&(R+=`
|
|
487
|
+
// [FILE TRUNCATED \u2014 showing ${N} of ${T.length} chars]`),$.push({path:y,content:R}),x.add(y),E+=R.length}}catch{}break}}if($.length<=2&&E<n){let ee=["layout.tsx","layout.jsx","layout.js","layout.ts"],y=v.path.replace(/\/[^/]+$/,""),M=0;for(;y&&M<4&&E<n;){let P=!1;for(let N of ee){let R=`${y}/${N}`;if(x.has(R)){P=!0;break}try{let V=await A("fs.read",{path:D?`${D}/${R}`:R}).catch(()=>null),K=String(V?.payload?.content||"");if(K){let ne=Math.min(4e3,n-E),xe=K.slice(0,ne);K.length>ne&&(xe+=`
|
|
488
|
+
// [TRUNCATED]`),$.push({path:R,content:xe}),x.add(R),E+=xe.length,P=!0;break}}catch{}}let T=y.replace(/\/[^/]+$/,"");if(T===y||!T)break;y=T,M++}}let G=S.matchAll(/(?:import|from)\s+['"]\.?\.\/([\w/.-]+)['"]/g);for(let ee of G){if(E>=n)break;let y=ee[1],M=v.path.replace(/\/[^/]+$/,""),P=[`${M}/${y}`,`${M}/${y}.tsx`,`${M}/${y}.ts`,`${M}/${y}.jsx`,`${M}/${y}.js`,`${M}/${y}/index.tsx`,`${M}/${y}/index.ts`];for(let T of P){if(x.has(T))break;if(w.find(R=>R.path===T)){try{let R=await A("fs.read",{path:D?`${D}/${T}`:T}),V=String(R?.payload?.content||"");if(V){let K=Math.min(8e3,n-E),ne=V.slice(0,K);V.length>K&&(ne+=`
|
|
489
|
+
// [FILE TRUNCATED \u2014 showing ${K} of ${V.length} chars]`),$.push({path:T,content:ne}),x.add(T),E+=ne.length}}catch{}break}}}}catch{}}if(E<n)try{let b=o.roots[0]||"",v=await A("fs.read",{path:b?`${b}/package.json`:"package.json"}),S=String(v?.payload?.content||"");if(S)try{let H=JSON.parse(S),L={...H.dependencies,...H.devDependencies},j=JSON.stringify(L,null,2);$.push({path:"package.json (dependencies)",content:j.slice(0,2e3)})}catch{$.push({path:"package.json",content:S.slice(0,2e3)})}}catch{}if(E<n){let b=o.roots[0]||"",v=["tailwind.config.ts","tailwind.config.js","tailwind.config.mjs","src/app/globals.css","src/styles/globals.css","styles/globals.css","app/globals.css","src/index.css","src/global.css","tsconfig.json","tsconfig.app.json","next.config.js","next.config.mjs","next.config.ts","vite.config.ts","vite.config.js","astro.config.mjs","astro.config.ts"];for(let S of v)if(!(E>=n||x.has(S)))try{let H=b?`${b}/${S}`:S,L=await A("fs.read",{path:H}).catch(()=>null),j=String(L?.payload?.content||"");if(j){let z=Math.min(12e3,n-E),G=j.slice(0,z);j.length>z&&(G+=`
|
|
490
|
+
/* [TRUNCATED] */`),$.push({path:S,content:G}),x.add(S),E+=G.length}}catch{}}if($.length){e.files=$;let b=$.map(v=>v.path.split("/").pop()).join(", ");i&&(i.innerHTML=`<span class="om-spinner"></span> Thinking... (${$.length} files: ${b})`)}o.groundedFiles=$.map(b=>b.path)}catch{}let r=4,p=0,d=new Set;try{for(;p<=r;){o.streamContent="";let m=await qe("llm.chat",{provider:o.provider,model:o.model,messages:o.messages.map(c=>({role:c.role,content:c.content})),context:e},c=>{o.streamContent+=c}),u=o.streamContent||m?.content||"",w=u;try{let c=JSON.parse(u);c.explanation&&(w=c.explanation)}catch{let c=u.match(/```(?:json)?\s*([\s\S]*?)```/);if(c)try{let $=JSON.parse(c[1]);$.explanation&&(w=$.explanation)}catch{}}let k=m?.modifications?.some(c=>c.type==="edit"&&c.file&&c.search&&c.replace||c.type==="create"&&c.file&&c.content),l=!k&&(w.match(/NEED_FILE:\s*"?([^\s"}\]]+)"?/)||w.match(/(?:need|provide|show|read|see|contents?\s+of)\s+(?:the\s+)?(?:file\s+)?[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||w.match(/(?:source\s+(?:file|code)\s+(?:for|of|at))\s+[`"']?([a-zA-Z0-9_/.@-]+\.[a-z]{1,5})[`"']?/i)||u.match(/NEED_FILE:\s*\\?"?([^\s"\\}\]]+)"?/));if(l&&p<r&&!d.has(l[1].trim())){let c=l[1].trim();d.add(c),p++;let $=U.querySelector(".om-msg-assistant:last-child");$&&($.innerHTML=`<span class="om-spinner"></span> Reading ${c}...`);try{let x=o.roots[0]||"",E=x?`${x}/${c}`:c,I,D=[E];c!==E&&D.push(c);let Q=c.split("/").pop()||c,b=x?`${x}/${Q}`:Q;b!==E&&b!==c&&D.push(b);for(let v of D){let S=await A("fs.read",{path:v}).catch(()=>null);if(S?.payload?.content){I=String(S.payload.content);break}}if(I){e.files||(e.files=[]);let v=e.files.findIndex(H=>H.path===c||H.path.endsWith("/"+c)||c.endsWith("/"+H.path)),S=I.slice(0,16e3);v>=0?e.files[v]={path:c,content:S}:e.files.push({path:c,content:S})}else{o.messages.push({role:"system",content:`Could not read ${c}`});break}}catch{o.messages.push({role:"system",content:`File not found: ${c}`});break}continue}let g=!k&&(w.match(/SEARCH_FILES:\s*"([^"]+)"(?:\s+in\s+(\S+))?/)||u.match(/SEARCH_FILES:\s*\\?"([^"\\]+)\\?"(?:\s+in\s+(\S+))?/)),f=e.searchResults?.some(c=>c.query===g?.[1]);if(g&&p<r&&!f){let c=g[1],$=g[2]||"";p++;let x=U.querySelector(".om-msg-assistant:last-child");x&&(x.innerHTML=`<span class="om-spinner"></span> Searching: "${c}"...`);try{let I=(await Promise.race([A("fs.grep",{pattern:c,path:$}),new Promise((D,Q)=>setTimeout(()=>Q(new Error("grep timeout")),5e3))]))?.payload?.results||[];I.length&&(e.searchResults||(e.searchResults=[]),e.searchResults.push({query:c,matches:I}))}catch{}continue}let h=w.replace(/^NEED_FILE:\s*\S+\s*/gm,"").replace(/^SEARCH_FILES:\s*"[^"]*"(?:\s+in\s+\S+)?\s*/gm,"").trim();if(h||(h="I couldn't determine the exact change from the available files. Try selecting a more specific element or giving more detail."),o.messages.push({role:"assistant",content:h}),m?.modifications?.length){let c=Math.random().toString(36).slice(2),$=m.modifications.filter(x=>x.type==="edit"&&x.file&&x.search&&x.replace||x.type==="create"&&x.file&&x.content);$t($.length);for(let x of m.modifications)if(x.type==="edit"&&x.file&&x.search&&x.replace){let E=Math.random().toString(36).slice(2),I=JSON.stringify({id:E,file:x.file,search:x.search,replace:x.replace,groupId:c});o.messages.push({role:"system",content:`__DIFF__${ge(I)}`})}else if(x.type==="create"&&x.file&&x.content){let E=Math.random().toString(36).slice(2),I=JSON.stringify({id:E,file:x.file,search:"",replace:x.content,type:"create",groupId:c});o.messages.push({role:"system",content:`__DIFF__${ge(I)}`})}else x.type==="delete"&&x.file&&o.messages.push({role:"system",content:`LLM proposed deleting ${x.file} \u2014 skipped (use edit with search/replace instead)`})}break}}catch(m){o.streamContent.trim().length>20?(o.messages.push({role:"assistant",content:o.streamContent.trim()}),o.messages.push({role:"system",content:`Response interrupted: ${m.message}. Partial response shown above.`})):o.messages.push({role:"system",content:`Error: ${m.message}`})}o.streaming=!1,o.streamContent="",o.attachments=[],Ne(),O(),se()}function Ct(){let t=window.performance,e=t.getEntriesByType("navigation")[0],s=t.getEntriesByType("paint"),n=t.getEntriesByType("resource").slice(-20),a=me(),i=ue(),r=[];r.push("--- Network & Performance Capture ---"),e&&(r.push(`Page load: ${Math.round(e.loadEventEnd-e.startTime)}ms`),r.push(`DOM ready: ${Math.round(e.domContentLoadedEventEnd-e.startTime)}ms`),r.push(`TTFB: ${Math.round(e.responseStart-e.startTime)}ms`));let p=s.find(d=>d.name==="first-contentful-paint");if(p&&r.push(`FCP: ${Math.round(p.startTime)}ms`),n.length){let d=n.filter(u=>u.initiatorType==="fetch"||u.initiatorType==="xmlhttprequest"),m=d.length>0?d:n;r.push(`
|
|
491
|
+
All network requests (${m.length}):`);for(let u of m.slice(-30)){let w=u.name.length>80?"..."+u.name.slice(-77):u.name,k=u.responseStatus||"";r.push(` ${Math.round(u.duration)}ms ${k?`[${k}]`:""} ${w}`)}}if(a.length){r.push(`
|
|
492
|
+
Fetch/XHR requests (${a.length}):`);for(let d of a.slice(-20))r.push(` ${d.method} ${d.url.slice(0,80)} \u2192 ${d.status||"pending"} (${d.duration||"?"}ms)`)}if(i.length){let d=i.filter(u=>u.level==="error"),m=i.filter(u=>u.level==="warn");d.length&&r.push(`
|
|
493
|
+
Console errors: ${d.length}`),m.length&&r.push(`Console warnings: ${m.length}`)}if(n.length>5){let d=[...n].sort((m,u)=>u.duration-m.duration).slice(0,5);r.push(`
|
|
494
|
+
Slowest resources:`);for(let m of d)r.push(` ${Math.round(m.duration)}ms \u2014 ${m.name.split("/").pop()?.slice(0,60)}`)}o.messages.push({role:"system",content:r.join(`
|
|
495
|
+
`)}),O(),se(),le()}function Tt(){let t=_.querySelector(".om-file-input");t&&t.click()}function Te(t){if(t)for(let e=0;e<t.length&&o.attachments.length<5;e++){let s=t[e];if(!s.type.startsWith("image/")||s.size>10*1024*1024)continue;let n=new FileReader;n.onload=()=>{typeof n.result=="string"&&(o.attachments.push(n.result),Ne())},n.readAsDataURL(s)}}function Ne(){let t=_.querySelector(".om-prompt-attachments");if(t){if(!o.attachments.length){t.innerHTML="",t.classList.add("om-hidden");return}t.classList.remove("om-hidden"),t.innerHTML=o.attachments.map((e,s)=>`<div class="om-attachment-thumb">
|
|
494
496
|
<img src="${e}" alt="attachment" />
|
|
495
|
-
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${
|
|
496
|
-
</div>`).join("")}}var
|
|
497
|
-
`),s=
|
|
498
|
-
`)}function
|
|
497
|
+
<button class="om-attachment-remove" data-action="remove-attachment" data-idx="${s}">${C.x}</button>
|
|
498
|
+
</div>`).join("")}}var ie=null,re=null;function Ht(){o.selecting?Pe():be()}function be(){o.selecting=!0,document.body.style.cursor="crosshair",ce(),re=e=>{let s=e.target;if(s.closest("openmagic-toolbar")||s.dataset?.openmagic)return;let n=s.getBoundingClientRect();Fe({x:n.x,y:n.y,width:n.width,height:n.height})},ie=e=>{e.preventDefault(),e.stopPropagation();let s=e.target;s.closest("openmagic-toolbar")||s.dataset?.openmagic||(o.selectedElement=Be(s),Pe(),le(),J.focus())};let t=e=>{e.key==="Escape"&&Pe()};document.addEventListener("mousemove",re,!0),document.addEventListener("click",ie,!0),document.addEventListener("keydown",t,!0),be._escHandler=t}function Pe(){o.selecting=!1,document.body.style.cursor="",We(),re&&(document.removeEventListener("mousemove",re,!0),re=null),ie&&(document.removeEventListener("click",ie,!0),ie=null);let t=be._escHandler;t&&(document.removeEventListener("keydown",t,!0),be._escHandler=null),ce()}async function Pt(){let t;try{let n=o.selectedElement?.cssSelector?.trim();n&&(t=document.querySelector(n)||void 0)}catch{}let e=await Ue(t||void 0);e.data&&e.data.length>5e3?(o.screenshot=e.data,le(),J.focus()):(o.messages.push({role:"system",content:"Take a screenshot manually (Cmd+Shift+4 on Mac, Win+Shift+S on Windows), then paste it here (Ctrl+V) or drag it onto the prompt bar."}),Y("chat"),O())}function _t(){let t=!1,e=0,s=0,n=0,a=0;q.addEventListener("mousedown",i=>{let r=i.target;if(r.closest("[data-action]")||!r.closest(".om-grab")&&!r.closest(".om-pill-brand"))return;t=!0,e=i.clientX,s=i.clientY;let p=q.getBoundingClientRect();n=p.left,a=p.top,i.preventDefault()}),document.addEventListener("mousemove",i=>{t&&(q.style.left=n+i.clientX-e+"px",q.style.top=a+i.clientY-s+"px",q.style.right="auto",q.style.bottom="auto")}),document.addEventListener("mouseup",()=>{if(t){t=!1;try{localStorage.setItem("__om_pos__",JSON.stringify({left:q.style.left,top:q.style.top}))}catch{}}})}function X(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}function Rt(t){let e=t.replace(/\\n/g,`
|
|
499
|
+
`),s=X(e);return s=s.replace(/```(\w*)\n([\s\S]*?)```/g,'<pre class="om-code-block"><code>$2</code></pre>'),s=s.replace(/`([^`]+)`/g,'<code class="om-inline-code">$1</code>'),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/([^*]|^)\*([^*]+)\*([^*]|$)/g,"$1<em>$2</em>$3"),s=s.replace(/^- (.+)$/gm,"• $1"),s=s.replace(/\n/g,"<br>"),s}async function ot(t){let e=[],s=null;try{Ee()&&(s=(await Promise.race([A("debug.logs"),new Promise((g,f)=>setTimeout(()=>f(new Error("timeout")),3e3))]))?.payload||null)}catch{}e.push("## Environment"),e.push(""),e.push(`- **OpenMagic**: v${_e}${o.updateAvailable?` (v${o.latestVersion} available)`:""}`),e.push(`- **Browser**: ${navigator.userAgent}`),e.push(`- **Platform**: ${navigator.platform}`),e.push(`- **Viewport**: ${window.innerWidth}x${window.innerHeight} (devicePixelRatio: ${window.devicePixelRatio})`),e.push(`- **Page URL**: ${window.location.href}`),e.push(`- **Page Title**: ${document.title}`),s&&(e.push(`- **Node.js**: ${s.nodeVersion} (${s.platform}/${s.arch})`),e.push(`- **Server PID**: ${s.pid}`),e.push(`- **Server Uptime**: ${s.uptime}s`),e.push(`- **Server Memory**: ${s.memoryMB}MB RSS`),e.push(`- **Server CWD**: ${s.cwd}`)),e.push(""),e.push("## Configuration"),e.push(""),e.push(`- **WebSocket**: ${o.connected?"connected":"disconnected"}`),e.push(`- **Provider**: ${Z[o.provider]?.name||o.provider||"not set"}`),e.push(`- **Model**: ${o.model||"not set"}`),e.push(`- **API Key Set**: ${o.hasApiKey?"yes":"no"}`);let n=Object.entries(o.configuredProviders).filter(([,l])=>l).map(([l])=>Z[l]?.name||l);if(n.length&&e.push(`- **Configured Providers**: ${n.join(", ")}`),o.roots.length&&e.push(`- **Project Roots**: ${o.roots.join(", ")}`),o.selectedElement){let l=o.selectedElement;e.push(""),e.push("## Selected Element"),e.push(""),e.push(`- **Selector**: \`${l.cssSelector||""}\``),e.push(`- **Tag**: \`${l.tagName}\``),l.id&&e.push(`- **ID**: \`${l.id}\``),l.className&&e.push(`- **Class**: \`${l.className}\``),l.componentHint&&e.push(`- **Component**: \`${l.componentHint}\``),l.ancestry?.length&&e.push(`- **Ancestry**: ${l.ancestry.join(" > ")}`),l.textContent&&e.push(`- **Text**: ${l.textContent.slice(0,150)}`)}if(o.groundedFiles.length){e.push(""),e.push("## Files Sent to LLM"),e.push("");for(let l of o.groundedFiles)e.push(`- \`${l}\``)}let a=[];for(let l of o.messages)if(l.content.startsWith("__DIFF__"))try{let g=JSON.parse(te(l.content.slice(8)));a.push({file:g.file,type:g.type||"edit"})}catch{}if(a.length){e.push(""),e.push("## Proposed Changes"),e.push("");for(let l of a)e.push(`- \`${l.file}\` (${l.type})`)}let i=o.messages.filter(l=>l.role==="system"&&(l.content.startsWith("Applied change to ")||l.content.startsWith("Rejected change to ")||l.content.startsWith("Reverted change to ")||l.content.startsWith("Created ")||l.content.startsWith("Change rejected")||l.content.startsWith("No matching code")||l.content.startsWith("Write failed")||l.content.startsWith("Could not read")));if(i.length){e.push(""),e.push("## Applied/Rejected Changes"),e.push("");for(let l of i)e.push(`- ${l.content.slice(0,200)}`)}let r=window.performance,p=r.getEntriesByType("navigation")[0],d=r.getEntriesByType("paint");if(p){e.push(""),e.push("## Page Performance"),e.push(""),e.push(`- **Page Load**: ${Math.round(p.loadEventEnd-p.startTime)}ms`),e.push(`- **DOM Ready**: ${Math.round(p.domContentLoadedEventEnd-p.startTime)}ms`),e.push(`- **TTFB**: ${Math.round(p.responseStart-p.startTime)}ms`);let l=d.find(g=>g.name==="first-contentful-paint");l&&e.push(`- **FCP**: ${Math.round(l.startTime)}ms`)}let m=ue();if(m.length){let l=m.filter(h=>h.level==="error"),g=m.filter(h=>h.level==="warn"),f=m.filter(h=>h.level==="log"||h.level==="info"||h.level==="debug");if(e.push(""),e.push("## Browser Console"),e.push(""),e.push(`Total: ${m.length} entries (${l.length} errors, ${g.length} warnings, ${f.length} log/info/debug)`),l.length){e.push(""),e.push(`### Errors (${l.length})`),e.push("```");for(let h of l.slice(-15))e.push(`[${new Date(h.timestamp).toISOString()}] ${h.args.map(c=>String(c)).join(" ").slice(0,300)}`);e.push("```")}if(g.length){e.push(""),e.push(`### Warnings (${g.length})`),e.push("```");for(let h of g.slice(-10))e.push(`[${new Date(h.timestamp).toISOString()}] ${h.args.map(c=>String(c)).join(" ").slice(0,200)}`);e.push("```")}if(f.length){e.push(""),e.push("<details><summary>Log/Info/Debug ("+f.length+" entries)</summary>"),e.push(""),e.push("```");for(let h of f.slice(-30))e.push(`[${new Date(h.timestamp).toISOString()}] [${h.level}] ${h.args.map(c=>String(c)).join(" ").slice(0,200)}`);e.push("```"),e.push("</details>")}}let u=me(),w=u.filter(l=>l.status&&l.status>=400),k=u.filter(l=>l.duration&&l.duration>2e3);if(w.length||k.length){if(e.push(""),e.push("## Network Issues"),e.push(""),w.length){e.push(`### Failed Requests (${w.length})`),e.push("```");for(let l of w.slice(-15))e.push(`${l.method} ${l.url.slice(0,120)} \u2192 ${l.status} (${l.duration||"?"}ms)`);e.push("```")}if(k.length){e.push(`### Slow Requests >2s (${k.length})`),e.push("```");for(let l of k.slice(-10))e.push(`${l.method} ${l.url.slice(0,120)} \u2192 ${l.status} (${l.duration}ms)`);e.push("```")}}if(s?.logs?.length){let l=s.logs,g=l.filter(c=>c.level==="error"),f=l.filter(c=>c.level==="warn"),h=l.filter(c=>c.level==="log"||c.level==="info");if(e.push(""),e.push("## Server Logs (Terminal)"),e.push(""),e.push(`Total: ${l.length} entries (${g.length} errors, ${f.length} warnings, ${h.length} log/info)`),g.length){e.push(""),e.push(`### Server Errors (${g.length})`),e.push("```");for(let c of g.slice(-15))e.push(`[${new Date(c.ts).toISOString()}] ${c.msg.slice(0,300)}`);e.push("```")}if(f.length){e.push(""),e.push(`### Server Warnings (${f.length})`),e.push("```");for(let c of f.slice(-10))e.push(`[${new Date(c.ts).toISOString()}] ${c.msg.slice(0,200)}`);e.push("```")}e.push(""),e.push("<details><summary>All server logs ("+l.length+" entries)</summary>"),e.push(""),e.push("```");for(let c of l.slice(-50))e.push(`[${new Date(c.ts).toISOString()}] [${c.level}] ${c.msg.slice(0,200)}`);e.push("```"),e.push("</details>")}if(o.messages.length){e.push(""),e.push("## Chat History"),e.push(""),e.push("<details><summary>Full conversation ("+o.messages.length+" messages)</summary>"),e.push(""),e.push("```");for(let l of o.messages)if(!l.content.startsWith("__DIFFGROUP__")){if(l.content.startsWith("__DIFF__")){try{let g=JSON.parse(te(l.content.slice(8)));e.push(`[diff] ${g.type||"edit"}: ${g.file}`),g.search&&e.push(` - search: ${g.search.slice(0,100)}...`),g.replace&&e.push(` + replace: ${g.replace.slice(0,100)}...`)}catch{e.push("[diff] (parse error)")}continue}e.push(`[${l.role}] ${l.content.slice(0,500)}`)}e.push("```"),e.push("</details>")}if(t!==void 0){let l=o.messages[t];l&&(e.push(""),e.push("## Copied Message"),e.push(""),e.push("```"),e.push(`[${l.role}] ${l.content.slice(0,2e3)}`),e.push("```"))}return e.join(`
|
|
500
|
+
`)}function At(){fetch("https://registry.npmjs.org/openmagic/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)}).then(t=>t.ok?t.json():null).then(t=>{if(!t||typeof t.version!="string"||!/^\d+\.\d+\.\d+/.test(t.version))return;let e=t.version.split(".").map(Number),s=_e.split(".").map(Number);for(let n=0;n<3;n++){if((e[n]||0)>(s[n]||0)){o.updateAvailable=!0,o.latestVersion=t.version,Nt();return}if((e[n]||0)<(s[n]||0))return}}).catch(()=>{})}function Nt(){fe()}typeof window<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ye):Ye());})();
|
|
499
501
|
//# sourceMappingURL=index.global.js.map
|