@codeyam-editor/codeyam-editor 0.1.14 → 0.1.15

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.
@@ -0,0 +1,21 @@
1
+ import{j as s}from"./markdown-C9tbsVHX.js";import{b as c}from"./react-nrLBr15I.js";import{a as on,u as cn,d as qr,C as Pe,c as Qr}from"./useServerIdentity-CVuHTzjg.js";import{u as Zr}from"./useEvents-DNb1olaj.js";import{r as es,a as ts}from"./xterm--24IGk-x.js";import{l as V,n as ns}from"./index-ClrdYzlw.js";const rs={webkitdirectory:""};function ss(e,t,n){c.useEffect(()=>{const r=o=>{const i=o.target;e.current&&e.current.contains(i)||n!=null&&n.current&&n.current.contains(i)||t()},a=o=>{o.key==="Escape"&&t()};return document.addEventListener("mousedown",r),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("keydown",a)}},[e,t,n])}const as={display:"block",width:"100%",padding:"var(--spacing-xs, 4px) var(--spacing-sm, 8px)",fontSize:"var(--text-xs, 12px)",color:"var(--text-primary)",border:"none",borderRadius:4,cursor:"pointer",textAlign:"left",whiteSpace:"nowrap"};function mt({label:e,onSelect:t}){const[n,r]=c.useState(!1);return s.jsx("button",{type:"button",role:"menuitem",onClick:t,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),style:{...as,background:n?"var(--bg-input)":"transparent"},children:e})}const Ki=Object.freeze(Object.defineProperty({__proto__:null,AssetPickerMenuItem:mt},Symbol.toStringTag,{value:"Module"}));function ln({onChooseFiles:e,onChooseFolder:t,onClose:n,triggerRef:r,placement:a="below"}){const o=c.useRef(null);return ss(o,n,r),s.jsxs("div",{ref:o,role:"menu",style:{position:"absolute",...a==="above"?{bottom:"100%",marginBottom:"var(--spacing-xs, 4px)"}:{top:"100%",marginTop:"var(--spacing-xs, 4px)"},left:0,minWidth:140,padding:"var(--spacing-xs, 4px)",background:"var(--bg-elevated, #222)",border:"1px solid var(--border-default)",borderRadius:8,boxShadow:"0 8px 24px rgba(0, 0, 0, 0.4)",zIndex:50},children:[s.jsx(mt,{label:"Files…",onSelect:()=>{e(),n()}}),s.jsx(mt,{label:"Folder…",onSelect:()=>{t(),n()}})]})}const Hi=Object.freeze(Object.defineProperty({__proto__:null,AssetPickerMenu:ln},Symbol.toStringTag,{value:"Module"})),os=350;function _e(e,t={}){const{minPendingMs:n=os}=t,[r,a]=c.useState("idle"),[o,i]=c.useState(0),l=c.useRef(!0);c.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const d=c.useCallback(()=>{a("pending"),i(h=>h+1);let f;try{f=Promise.resolve(e())}catch{f=Promise.resolve()}const g=new Promise(h=>setTimeout(h,n));Promise.allSettled([f,g]).then(()=>{l.current&&a("unchanged")})},[e,n]);return{phase:r,attempts:o,retry:d}}const un="Connected to the editor server at ";function dn(e){const t=e===null?null:e?"in the cloud container":"on this machine";return t?`, running ${t}.`:"."}function is(e,t){return e===null?null:`${un}${e}${dn(t)}`}function cs({headline:e,explanation:t,nextAction:n,diagnostics:r,connection:a}){const o=[`CodeYam editor — ${e}`,`What happened
2
+ ${t}`,`What to do
3
+ ${n}`],i=r==null?void 0:r.trim();i&&o.push(`Details
4
+ ${i}`);const l=a==null?void 0:a.trim();return l&&o.push(`Connection
5
+ ${l}`),o.join(`
6
+
7
+ `)}function bt(e){return typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(bt).join(""):""}const ls={error:{accent:"var(--accent-red, #dc2626)",surface:"var(--bg-base)",label:"Error"},warning:{accent:"var(--accent-amber, #d97706)",surface:"var(--bg-base)",label:"Warning"},blocked:{accent:"var(--accent-primary, #2563eb)",surface:"var(--bg-base)",label:"Blocked"}};function fn({headline:e,palette:t,report:n,copyLabel:r}){return s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:t.label}),s.jsx("h2",{className:"text-base font-semibold leading-snug",children:e})]}),s.jsx(on,{variant:"subtle",text:n,label:r,ariaLabel:`Copy this report: ${e}`})]})}const Ui=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeHeader:fn},Symbol.toStringTag,{value:"Module"}));function pn({nextAction:e,palette:t}){return s.jsxs("div",{className:"rounded border-l-2 pl-3",style:{borderLeftColor:t.accent},children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:"What to do"}),s.jsx("div",{style:{color:"var(--text-primary)"},children:e})]})}const Wi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeNextAction:pn},Symbol.toStringTag,{value:"Module"}));function hn({diagnostics:e,testId:t}){return s.jsx("pre",{"data-testid":t,className:"m-0 max-h-48 overflow-auto whitespace-pre-wrap rounded px-3 py-2 font-mono text-xs leading-snug",style:{background:"var(--bg-surface)",color:"var(--text-secondary)"},children:e})}const Yi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeDiagnostics:hn},Symbol.toStringTag,{value:"Module"}));function mn({actions:e,palette:t,actionFeedback:n}){return e.length===0&&!n?null:s.jsxs(s.Fragment,{children:[e.length>0?s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.map(r=>s.jsx("button",{type:"button",onClick:r.onClick,disabled:r.pending,"aria-label":r.ariaLabel,"data-testid":r.testId,className:"rounded px-3 py-1.5 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-70",style:r.variant==="secondary"?{border:"1px solid var(--border-default)",color:"var(--text-primary)"}:{background:t.accent,color:"var(--bg-base)"},children:r.pending?r.pendingLabel??`${r.label}…`:r.label},r.label))}):null,n?s.jsx("div",{className:"text-xs",style:{color:"var(--text-dim)"},children:n}):null]})}const Vi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeActions:mn},Symbol.toStringTag,{value:"Module"}));function de({headline:e,explanation:t,nextAction:n,explanationText:r,nextActionText:a,diagnostics:o,severity:i="error",actions:l=[],actionFeedback:d,copyLabel:f="Copy this report",testId:g,className:h}){const{projectDir:u,inContainer:m,loaded:b}=cn(),x=ls[i],v=b?is(u,m):null,p=cs({headline:e,explanation:r??bt(t),nextAction:a??bt(n),diagnostics:o,connection:v});return s.jsxs("div",{role:"alert","aria-label":e,"data-testid":g,className:h??"flex w-full max-w-2xl flex-col gap-3 rounded-lg border border-l-4 p-5 text-sm shadow-lg",style:{background:x.surface,borderColor:"var(--border-default)",borderLeftColor:x.accent,color:"var(--text-primary)"},children:[s.jsx(fn,{headline:e,palette:x,report:p,copyLabel:f}),s.jsx("p",{style:{color:"var(--text-dim)"},children:t}),s.jsx(pn,{nextAction:n,palette:x}),o?s.jsx(hn,{diagnostics:o,testId:g?`${g}-diagnostics`:void 0}):null,s.jsx(mn,{actions:l,palette:x,actionFeedback:d}),u!==null&&b?s.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:[un,s.jsx("code",{children:u}),dn(m)]}):null]})}const Xi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNotice:de},Symbol.toStringTag,{value:"Module"})),us=500,Ae=new Set;let Ce=null,Ke=null;async function gt(){let e;try{const t=await fetch("/api/editor-dev-server");t.ok?e={ok:!0,data:await t.json()}:e={ok:!1,error:`Failed to fetch dev server status: ${t.statusText}`}}catch(t){e={ok:!1,error:t instanceof Error?t.message:String(t)}}if(Ae.size!==0){Ke=e;for(const t of[...Ae])t(e)}}function ds(e){return Ae.add(e),Ke&&e(Ke),Ce===null&&(Ce=setInterval(()=>{gt()},us),gt()),()=>{Ae.delete(e),Ae.size===0&&Ce!==null&&(clearInterval(Ce),Ce=null,Ke=null)}}function fs(){gt()}function bn(){return s.jsx("div",{"data-codeyam-capture-placeholder":"MiniAgentChat",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 16px",textAlign:"center",color:"#8a8a8a",fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",fontSize:12,lineHeight:1.6},children:"No agent session is started in a captured screenshot."})}const Ji=Object.freeze(Object.defineProperty({__proto__:null,CaptureChatPlaceholder:bn},Symbol.toStringTag,{value:"Module"})),Ot="claude";function ps(e){return e==="claude"}function hs(e){return e!=="gemini"}function ms(e){return e==="muse"}function bs(e){return e==="muse"?"Meta":Se(e)}function Se(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";case"opencode":return"OpenCode";case"muse":return"Muse";default:return"Claude"}}const gs=1e3;let xt=0;function Gi(){xt=Date.now()}function yt(){return xt===0?1/0:Date.now()-xt}function qi(){return yt()<gs}const gn=5e3,Bt=6e4,xs=50;function zt(e,t=gn){return e<t}function ys(e,t=gn){return Math.max(xs,t-e)}const Ne=new Map;async function vs(e,t,n,r){if(r!=null&&r.aborted)return null;if(!zt(yt()))return e;const a=Ne.get(t);if(a)return a.label=e,V("dispatch-rename-superseded",{caller:n,label:e}),null;const o={label:e};Ne.set(t,o);let i=0;for(;;){if(r!=null&&r.aborted)return Ne.delete(t),V("dispatch-rename-cancelled",{caller:n,label:o.label,waitedMs:i}),null;const l=yt();if(!zt(l))break;const d=ys(l);if(i+d>Bt)return Ne.delete(t),V("dispatch-rename-abandoned",{caller:n,label:o.label,msSinceKeystroke:l,waitedMs:i,capMs:Bt}),null;V("dispatch-rename-deferred",{caller:n,label:o.label,msSinceKeystroke:l,retryInMs:d,waitedMs:i}),await new Promise(f=>setTimeout(f,d)),i+=d}return Ne.delete(t),o.label}const ws=40;function _s(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,ws).replace(/-+$/,"")||"session"}const He=new Map;function Re(e,t){const n=He.get(e);if(!n){let r;try{r=t()}catch(a){return Promise.reject(a)}return r instanceof Promise?Kt(e,r):Promise.resolve()}return Kt(e,n.then(()=>t()))}function Kt(e,t){const n=t.catch(()=>{});return He.set(e,n),n.then(()=>{He.get(e)===n&&He.delete(e)}),t}let ve=0,ge=[];function Qi(){if(ve+=1,ve===1&&ge.length>0){const e=ge;ge=[];for(const t of e)t()}}function Zi(){ve>0&&(ve-=1)}function Ss(){return ve>0}function js(e){return ve>0?Promise.resolve(!0):new Promise(t=>{let n=!1;const r=()=>{n||(n=!0,t(!0))};ge.push(r),setTimeout(()=>{n||(n=!0,ge=ge.filter(a=>a!==r),t(!1))},e)})}const je="build",vt="miniagent",Ht=3e3;function At(e,t=!1){return Ss()?e():js(Ht).then(n=>{if(n)return e();const r=`no terminal-send-input listener attached within ${Ht}ms`;if(t)throw new ks(r);console.warn(`[terminal] dropped programmatic injection: ${r}`)})}class ks extends Error{constructor(t){super(t),this.name="TerminalInputDroppedError"}}function we(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}function ec(e){Re(je,()=>At(()=>we(e)))}function tc(e){return Re(je,()=>At(()=>we(e),!0))}const xe=50;function nc(e){return Re(je,()=>At(()=>new Promise(t=>{we(e),setTimeout(()=>{we("\r"),t()},xe)}),!0))}function xn(e,t=we,n=je){return Re(n,()=>new Promise(r=>{t(e),setTimeout(()=>{t("\r"),r()},xe)}))}const st=3e3;function yn(e){return e==="codex"?"codex":e==="gemini"?"gemini":e==="opencode"?"opencode":e==="muse"?"muse":"claude"}function vn(e,t,n,r,a){const o=yn(e),i=r?Cs(n,r):o;if(o!=="claude")return i;const l=t?" --permission-mode auto":"",d=a?` --session-id ${Mt(n,a)}`:"";return`${i}${l}${d}`}function Cs(e,t){const n=Mt(e,t);return e==="powershell"?`& ${n}`:n}function Mt(e,t){return`'${e==="powershell"?t.replaceAll("'","''"):t.replaceAll("'","'\\''")}'`}function Ns(e,t,n=!0,r="posix",a=null,o=null){const i=Mt(r,t);return e==="opencode"?`opencode${n?" --auto":""} --prompt ${i}\r`:e==="muse"?`muse --trust-workspace${n?" --disable-approval":""} ${i}\r`:`${vn(e,n,r,a,o)} ${i}\r`}async function Ts(e,t=we,n=je,r="dispatch-rename-launch",a){const o=await vs(_s(e),n,r,a);return o===null?!1:(await xn(`/rename ${o}`,t,n),!0)}function Es(e,t,n,r=je,a){V("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:st}),setTimeout(()=>{V("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:st}),Ts(e,n,r,t).then(o=>a==null?void 0:a(o?"fired":"superseded"),()=>a==null?void 0:a("failed"))},st)}const Pt=".codeyam/tmp/inline-prompt.md";function Os(e){return e.split(`
8
+ `).map(t=>t.startsWith("'@")?` ${t}`:t).join(`
9
+ `)}function As(e){return`mkdir -p .codeyam/tmp && cat > ${Pt} << 'INLINE_PROMPT_EOF'
10
+ ${e}
11
+ INLINE_PROMPT_EOF\r`}function Ms(e){return`New-Item -ItemType Directory -Force -Path .codeyam/tmp | Out-Null; @'
12
+ ${Os(e)}
13
+ '@ | Set-Content -LiteralPath ${Pt} -Encoding utf8\r`}function Ps(e,t,n=!0,r="posix",a=null,o=null){const i=vn(e,n,r,a,o),l=r==="powershell"?Ms(t):As(t),d=`${i} "Read the file at '${Pt}' for your instructions."\r`;return[l,d]}function wn(e){return e>=500?"transient":"rejected"}function _n({provider:e,onAuthenticated:t}){const[n,r]=c.useState(""),[a,o]=c.useState(!1),[i,l]=c.useState(null),[d,f]=c.useState(!1),g=bs(e),h=c.useCallback(async()=>{if(n.trim()){o(!0),l(null),f(!1);try{const u=await fetch("/api/auth/api-key",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({provider:e,key:n.trim()})});if(!u.ok){if(wn(u.status)==="transient"){f(!0),l(`The editor was briefly unreachable (HTTP ${u.status}). Your key wasn't rejected — try again.`);return}const m=await u.json().catch(()=>({}));l(m.error??`Could not save the key (HTTP ${u.status}).`);return}r(""),t()}catch{f(!0),l("Could not reach the editor to save the key. Try again.")}finally{o(!1)}}},[n,e,t]);return s.jsxs("div",{"data-testid":"api-key-flow",className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Paste your ",g," API key. It is stored locally in",s.jsx("code",{className:"mx-1 text-[#D7FF63]",children:".codeyam/editor.local.json"}),"and never committed."]}),ms(e)&&s.jsxs("p",{"data-testid":"api-key-flow-cli-login-note",className:"text-sm text-[#8E8E8E]",children:["Already signed in with",s.jsxs("code",{className:"mx-1 text-[#D7FF63]",children:[yn(e)," login"]}),"on this machine? You don't need a key — that sign-in counts."]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"password",value:n,onChange:u=>r(u.target.value),placeholder:`${g} API key`,className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),s.jsx("button",{onClick:()=>void h(),disabled:a||!n.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:a?"Saving…":"Save"})]}),i?s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:i}),d?s.jsx("button",{"data-testid":"api-key-flow-retry",onClick:()=>void h(),disabled:a||!n.trim(),className:"px-3 py-1.5 text-sm rounded-md border border-[#3A3A3A] text-white font-medium cursor-pointer disabled:opacity-50",children:a?"Saving…":"Retry"}):null]}):null]})}const rc=Object.freeze(Object.defineProperty({__proto__:null,ApiKeyFlow:_n,classifyApiKeySaveFailure:wn},Symbol.toStringTag,{value:"Module"}));function be({onRetry:e,onRecheck:t,rechecking:n,retryLabel:r="Retry",retryTestId:a,recheckTestId:o}){return s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("button",{onClick:e,"data-testid":a,className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:r}),s.jsx("button",{onClick:t,"data-testid":o,disabled:n,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:n?"Rechecking…":"I already logged in — recheck"})]})}const sc=Object.freeze(Object.defineProperty({__proto__:null,RecoveryActions:be},Symbol.toStringTag,{value:"Module"}));function Sn({timedOut:e,onRetry:t,onRecheck:n,rechecking:r}){return e?s.jsxs("div",{"data-testid":"claude-oauth-install-timeout",className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Installing the Claude command-line tool is taking longer than expected. Try again, or install it yourself in a terminal with"," ",s.jsx("code",{className:"text-white",children:"npm install -g @anthropic-ai/claude-code"})," ","and then retry."]}),s.jsx(be,{onRetry:t,onRecheck:n,rechecking:r,retryTestId:"claude-oauth-install-timeout-retry",recheckTestId:"claude-oauth-install-timeout-recheck"})]}):s.jsx("p",{"data-testid":"claude-oauth-installing",className:"text-sm text-[#8E8E8E]",children:"Installing the Claude command-line tool… this can take a minute."})}const ac=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthInstallProgress:Sn},Symbol.toStringTag,{value:"Module"}));function Rs(e){return new Promise(t=>{e.file(n=>t(n),()=>t(null))})}function Is(e){return new Promise(t=>{const n=[],r=()=>{e.readEntries(a=>{if(a.length===0){t(n);return}n.push(...a),r()},()=>t(n))};r()})}function Ds(e){return e.split("/").some(t=>t.startsWith("."))}async function jn(e,t,n){if(e.name.startsWith("."))return 0;const r=t?`${t}/${e.name}`:e.name;if(e.isFile){const a=await Rs(e);return a?(n.push({file:a,relativePath:r}),0):1}if(e.isDirectory){const a=await Is(e.createReader());let o=0;for(const i of a)o+=await jn(i,r,n);return o}return 0}async function Ls(e){const t=e.items;if(!(!!t&&t.length>0&&typeof t[0].webkitGetAsEntry=="function"))return{files:Array.from(e.files).map(i=>({file:i,relativePath:i.name})),skipped:0,expandedViaEntryApi:!1};const r=[];for(const i of Array.from(t)){const l=i.webkitGetAsEntry();l&&r.push(l)}const a=[];let o=0;for(const i of r)o+=await jn(i,"",a);return{files:a,skipped:o,expandedViaEntryApi:!0}}function Fs(e){return Array.from(e).map(t=>({file:t,relativePath:t.webkitRelativePath||t.name})).filter(({relativePath:t})=>!Ds(t))}function $s(e){return e.size===0&&e.type===""}const Bs="Folders can't be read in this browser — open the folder and drop the files inside it.";function zs(e,t,n){const r=[];let a=null;for(const o of e){if(!t&&$s(o.file)){a=Bs;continue}if(o.file.size>n){a=`${o.relativePath} is larger than the ${n/(1024*1024*1024)}GB safety ceiling`;continue}r.push(o)}return{valid:r,rejection:a}}function Ks(e){const{files:t,skipped:n,expandedViaEntryApi:r}=e;return n>0&&t.length===0?"Couldn't read any of the files in that folder.":t.length===0&&r?"No files found in that folder.":n>0?`${n} item(s) couldn't be read and were skipped.`:null}const Hs=200;function Us(e){for(const{relativePath:t}of e){const n=t.indexOf("/");if(n>0)return t.slice(0,n)}return null}function Ws(e,t=Hs){if(e.length<=t)return null;const n=e.length.toLocaleString("en-US"),r=Us(e);return`${r?`"${r}" has ${n} files`:`That's ${n} files`}, more than the ${t} you can attach at once. Pick a smaller folder.`}const Rt=1024*1024*1024;function kn(e){return e.map(t=>({file:t,relativePath:t.name}))}function It(e,t,n){const r=Ws(e);if(r)return{files:[],error:r};const{valid:a,rejection:o}=zs(e,t,n);return{files:a,error:o}}async function Ys(e,t=Rt){const n=await Ls(e),r=It(n.files,n.expandedViaEntryApi,t);return r.files.length===n.files.length?{files:r.files,error:Ks(n)}:r}function Vs(e,t=Rt){return It(kn(Array.from(e??[])),!1,t)}function Xs(e,t=Rt){const n=Fs(e??[]);return n.length===0?{files:[],error:"No files found in that folder."}:It(n,!0,t)}const Je=c.createContext({openPicker:()=>{},registerFileSink:()=>{}});function Js({fallbackUpload:e,onError:t,children:n}){const r=c.useRef(null),a=c.useRef(null),o=c.useRef(null),i=c.useCallback(g=>{o.current=g},[]),l=c.useCallback((g="files")=>{var h;(h=(g==="folder"?a:r).current)==null||h.click()},[]),d=c.useCallback(async(g,h)=>{const u=g.target,{files:m,error:b}=h==="folder"?Xs(u.files):Vs(u.files);if(u.value="",b&&(t==null||t(b)),m.length===0)return;const x=o.current;x&&await x(m)||e(m)},[e,t]),f=c.useMemo(()=>({openPicker:l,registerFileSink:i}),[l,i]);return s.jsxs(Je.Provider,{value:f,children:[n,s.jsx("input",{ref:r,type:"file",multiple:!0,onChange:g=>void d(g,"files"),style:{display:"none"},"data-testid":"global-file-picker-input"}),s.jsx("input",{ref:a,type:"file",...rs,onChange:g=>void d(g,"folder"),style:{display:"none"},"data-testid":"global-folder-picker-input"})]})}function Cn(){return c.useContext(Je)}function Gs(e,t){const{registerFileSink:n}=c.useContext(Je);c.useEffect(()=>{if(t)return n(e),()=>n(null)},[n,e,t])}function Nn(){const{registerFileSink:e}=c.useContext(Je);return{registerFileSink:e}}const oc=Object.freeze(Object.defineProperty({__proto__:null,FilePickerProvider:Js,useFilePicker:Cn,useFilePickerChannel:Nn,useRegisterFilePickerSink:Gs},Symbol.toStringTag,{value:"Module"}));async function Tn(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}const En=4e3;async function On({attempts:e=3,intervalMs:t=1500,timeoutMs:n=En}={}){for(let r=0;r<e;r++)if(r>0&&t>0&&await new Promise(a=>setTimeout(a,t)),await Tn(n))return!1;return!0}function An(e,t){let n=!1,r=null;async function a(){if(!n){if(await Tn(En)){n||t();return}n||(r=setTimeout(a,e))}}return r=setTimeout(a,e),()=>{n=!0,r&&(clearTimeout(r),r=null)}}const qs=3e3;function Qs({onUnreachable:e,onReachable:t,onReturned:n,confirmStopped:r=On,pollUntilAlive:a=An,returnPollMs:o=qs}){let i=!1,l=null,d=0;function f(){d+=1,i=!1,l==null||l(),l=null}function g(){if(i||l)return;i=!0;const h=d;r().then(u=>{if(h===d){if(i=!1,!u){t();return}e(),l=a(o,()=>{l=null,n()})}})}return{noteFailure:g,reset:f}}const Zs={binaryMismatch:!1,configMissingAtLaunch:!1},wt={state:"unknown",provider:Ot,credsPresent:!0,cliInstalled:!0,cliRunnable:null,cliFailure:null,scannedDirs:[],reason:null,source:null,shellShare:null,storeDurability:"unobserved",claudeLaunch:Zs,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function ea(e){if(e==null)return{...wt,backendFieldAbsent:!0};if(typeof e!="object")return wt;const t=e,n=t.state==="authenticated"||t.state==="needs-login"||t.state==="unknown"?t.state:"unknown",r=t.provider==="claude"||t.provider==="codex"||t.provider==="gemini"||t.provider==="opencode"||t.provider==="muse"?t.provider:Ot,a=typeof t.credsPresent=="boolean"?t.credsPresent:!0,o=typeof t.cliInstalled=="boolean"?t.cliInstalled:!0,i=typeof t.cliRunnable=="boolean"?t.cliRunnable:null,l=i===!1&&typeof t.cliFailure=="string"?t.cliFailure:null,d=Array.isArray(t.scannedDirs)?t.scannedDirs.filter(w=>typeof w=="string"):[],f=t.reason==="token-expired"||t.reason==="api-401"||t.reason==="no-credentials"||t.reason==="probe-timeout"||t.reason==="config-corrupt"||t.reason==="cli-not-found"||t.reason==="credentials-not-persisted"||t.reason==="stale-verdict"?t.reason:null,g=typeof t.source=="string"?t.source:null,h=t.shellShare==="available"||t.shellShare==="shared"?t.shellShare:null,u=t.storeDurability==="persisted"||t.storeDurability==="did-not-persist"?t.storeDurability:"unobserved",m=typeof t.claudeLaunch=="object"&&t.claudeLaunch!==null?t.claudeLaunch:{},b={binaryMismatch:m.binaryMismatch===!0,configMissingAtLaunch:m.configMissingAtLaunch===!0},x=typeof t.tokenExpiresAt=="string"?t.tokenExpiresAt:typeof t.expiresAt=="string"?t.expiresAt:null,v=typeof t.probeInFlight=="boolean"?t.probeInFlight:!1,p=typeof t.probeAttempts=="number"&&Number.isFinite(t.probeAttempts)&&t.probeAttempts>=0?t.probeAttempts:0;return{state:n,provider:r,credsPresent:a,cliInstalled:o,cliRunnable:i,cliFailure:l,scannedDirs:d,reason:f,source:g,shellShare:h,storeDurability:u,claudeLaunch:b,expiresAt:x,probeInFlight:v,probeAttempts:p,backendFieldAbsent:!1}}const ta=1e3,na=5e3,ra=2e4,sa=6e4;function aa(e,t){return e.state==="unknown"||e.probeInFlight?ta:e.state==="needs-login"?t<sa?na:ra:null}let Me=wt,Mn=0,Te=null,at=0;const Ye=new Set;function _t(e){Me=e,Ye.forEach(t=>t())}function Ut(e){return Ye.add(e),()=>Ye.delete(e)}function oa(){return Me}let Ve=!1;function Wt(e){Ve!==e&&(Ve=e,Ye.forEach(t=>t()))}function ia(){return Ve}const ot=Qs({onUnreachable:()=>Wt(!0),onReachable:()=>Wt(!1),onReturned:()=>void ce()});function ce(){if(Te)return Te;const e=at;return Te=(async()=>{try{const t=await fetch("/api/config");if(!t.ok){e===at&&ot.noteFailure();return}const n=await t.json();Mn=Date.now(),ot.reset(),Ve=!1,_t(ea(n.providerAuth))}catch{ot.noteFailure()}finally{Te=null}})(),Te}function ca(e){Date.now()-Mn<e/2||ce()}function ic(){window.dispatchEvent(new CustomEvent("agent-auth-resolved"))}function la(){const e=c.useSyncExternalStore(Ut,oa),t=c.useSyncExternalStore(Ut,ia),n=c.useRef(Date.now());c.useEffect(()=>{ce()},[]);const r=aa(e,Date.now()-n.current);return c.useEffect(()=>{if(r===null)return;const a=window.setInterval(()=>ca(r),r);return()=>window.clearInterval(a)},[r]),c.useEffect(()=>{const a=()=>{Me.state!=="authenticated"&&ce()};return window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[]),c.useEffect(()=>{const a=()=>{_t({...Me,state:"needs-login"}),ce()};return window.addEventListener("agent-auth-required",a),()=>window.removeEventListener("agent-auth-required",a)},[]),c.useEffect(()=>{const a=()=>{_t({...Me,state:"authenticated"}),ce()};return window.addEventListener("agent-auth-resolved",a),()=>window.removeEventListener("agent-auth-resolved",a)},[]),{state:e.state,provider:e.provider,credsPresent:e.credsPresent,cliInstalled:e.cliInstalled,cliRunnable:e.cliRunnable,cliFailure:e.cliFailure,scannedDirs:e.scannedDirs,reason:e.reason,source:e.source,shellShare:e.shellShare,storeDurability:e.storeDurability,claudeLaunch:e.claudeLaunch,expiresAt:e.expiresAt,probeInFlight:e.probeInFlight,probeAttempts:e.probeAttempts,backendFieldAbsent:e.backendFieldAbsent,serverUnreachable:t,refresh:ce}}var ua=es(),da=ts();function fa(e){if(typeof e!="object"||e===null)return null;const{provider:t,stanza:n,file:r,setupCommand:a}=e;return typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"?null:{provider:t,stanza:n,file:r,setupCommand:a}}const pa=3e3;function Pn(){const[e,t]=c.useState(null),[n,r]=c.useState(!0),[a,o]=c.useState(null),i=c.useRef(null),l=c.useCallback(async()=>{try{const d=await fetch("/api/config");if(!d.ok)throw new Error(`HTTP ${d.status}`);const f=await d.json(),g={projectTitle:f.projectTitle??null,projectDescription:f.projectDescription??null,provider:f.provider??Ot,providerDeclared:f.providerDeclared??!1,port:f.port??3e3,previewOrigin:f.previewOrigin??null,screenSizes:f.screenSizes??{},defaultScreenSize:f.defaultScreenSize??null,apps:f.apps??[],admin:f.admin??!1,mobileTerminalCommands:f.mobileTerminalCommands??[],launcherUrl:f.launcherUrl??null,projectCount:f.projectCount??0,setupBrowserEnabled:f.setupBrowserEnabled??!1,claudePermissionModeAuto:f.claudePermissionModeAuto??!0,previewDedicatedOriginUnavailable:f.previewDedicatedOriginUnavailable??!1,previewDedicatedOriginHint:fa(f.previewDedicatedOriginHint),onManagedFleetVm:f.onManagedFleetVm??!1,previewSessionHandoff:f.previewSessionHandoff??null,previewSessionHandoffProbe:f.previewSessionHandoffProbe??null},h=JSON.stringify(g);h!==i.current&&(i.current=h,t(g)),o(null)}catch(d){o(d instanceof Error?d.message:"Failed to load config")}finally{r(!1)}},[]);return c.useEffect(()=>{l();const d=setInterval(()=>{l()},pa);return()=>clearInterval(d)},[l]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:n,error:a,refetch:l}}const ha="capture-origin-spawn-refused";function Rn(){return typeof window<"u"&&window.__codeyamCapture===!0}function Yt(){return Rn()&&window.__codeyamCaptureLiveSocket!==!0}function ma(e){const t=window.location.protocol==="https:"?"wss:":"ws:",n=new URL(`${t}//${window.location.host}/ws/terminal`);return e!=null&&e.provider&&n.searchParams.set("provider",e.provider),e!=null&&e.mode&&n.searchParams.set("mode",e.mode),e!=null&&e.sessionId&&n.searchParams.set("sessionId",e.sessionId),e!=null&&e.chatKey&&n.searchParams.set("chatKey",e.chatKey),e!=null&&e.launchId&&n.searchParams.set("launchId",e.launchId),e!=null&&e.launch&&n.searchParams.set("launch","1"),e!=null&&e.capture&&n.searchParams.set("capture","1"),e!=null&&e.cols&&e.cols>0&&n.searchParams.set("cols",String(e.cols)),e!=null&&e.rows&&e.rows>0&&n.searchParams.set("rows",String(e.rows)),n.toString()}const ba=20,ga=1;function xa(e,t){const n=t===ga?e:e/ba;return Math.trunc(n)||Math.sign(n)}function ya(){if(typeof navigator>"u")return!1;const e=navigator.platform??"";return e?/Mac|iPhone|iPad|iPod/i.test(e):/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent??"")}function va(e,t,n={}){const r=n.isMac??ya(),a=n.onError,o=n.onCopy;let i=null;async function l(b){if(!b)return!1;let x=!1;try{x=await qr(b)}catch(v){return a==null||a(Vt("copy",v)),!1}if(x){try{e.clearSelection()}catch{}o==null||o()}else a==null||a(_a("copy"));return x}async function d(){return e.hasSelection()?l(e.getSelection()):!1}async function f(){try{const b=await navigator.clipboard.readText();b&&e.paste(b)}catch(b){a==null||a(Vt("paste",b))}}function g(b){return b.type!=="keydown"?!0:r?(b.metaKey&&!b.ctrlKey&&!b.altKey&&b.key.toLowerCase()==="c"||b.ctrlKey&&!b.metaKey&&!b.altKey&&!b.shiftKey&&b.key.toLowerCase()==="c")&&e.hasSelection()?(d(),!1):!0:(b.ctrlKey&&b.shiftKey&&!b.metaKey&&!b.altKey&&b.key.toLowerCase()==="c"||b.ctrlKey&&!b.shiftKey&&!b.metaKey&&!b.altKey&&b.key.toLowerCase()==="c")&&e.hasSelection()?(d(),!1):!0}e.attachCustomKeyEventHandler(g);function h(){if(!i)return;const{root:b,onDocumentClick:x,onKeyDown:v}=i;document.removeEventListener("mousedown",x,!0),document.removeEventListener("keydown",v,!0),b.remove(),i=null}function u(b,x,v){h();const p=document.createElement("div");p.setAttribute("data-terminal-clipboard-menu","true"),p.style.position="fixed",p.style.left=`${b}px`,p.style.top=`${x}px`,p.style.zIndex="1000",p.style.minWidth="180px",p.style.padding="4px 0",p.style.background="var(--bg-card)",p.style.border="1px solid var(--border-subtle)",p.style.borderRadius="6px",p.style.boxShadow="0 8px 24px rgba(0, 0, 0, 0.35)",p.style.fontSize="12px",p.style.color="var(--text-primary)",p.style.userSelect="none";const w=r?"⌘C":"Ctrl+Shift+C",j=r?"⌘V":"Ctrl+Shift+V",y=it("Copy",w,!v,()=>{l(v),h()}),S=it("Paste",j,!1,()=>{f(),h()}),k=it("Select All","",!1,()=>{try{e.selectAll()}catch{}const _=e.hasSelection()?e.getSelection():"";l(_),h()});p.appendChild(y),p.appendChild(S),p.appendChild(k),document.body.appendChild(p),wa(p,b,x);const O=_=>{p.contains(_.target)||h()},D=_=>{_.key==="Escape"&&(_.preventDefault(),h())};document.addEventListener("mousedown",O,!0),document.addEventListener("keydown",D,!0),i={root:p,onDocumentClick:O,onKeyDown:D}}function m(b){b.preventDefault();const x=e.hasSelection()?e.getSelection():"";u(b.clientX,b.clientY,x)}return t.addEventListener("contextmenu",m),()=>{t.removeEventListener("contextmenu",m),h(),e.attachCustomKeyEventHandler(()=>!0)}}function it(e,t,n,r){const a=document.createElement("button");a.type="button",a.disabled=n,a.style.display="flex",a.style.justifyContent="space-between",a.style.alignItems="center",a.style.gap="16px",a.style.width="100%",a.style.padding="6px 12px",a.style.border="none",a.style.background="transparent",a.style.textAlign="left",a.style.fontSize="12px",a.style.cursor=n?"default":"pointer",a.style.color=n?"var(--text-dim)":"var(--text-primary)";const o=document.createElement("span");if(o.textContent=e,a.appendChild(o),t){const i=document.createElement("span");i.textContent=t,i.style.color="var(--text-dim)",i.style.fontSize="11px",a.appendChild(i)}return n||(a.addEventListener("mouseenter",()=>{a.style.background="var(--border-subtle)"}),a.addEventListener("mouseleave",()=>{a.style.background="transparent"}),a.addEventListener("click",()=>r())),a}function wa(e,t,n){const r=typeof window<"u"?window.innerWidth:0,a=typeof window<"u"?window.innerHeight:0;if(!r||!a)return;const o=e.getBoundingClientRect(),i=4;let l=t,d=n;o.width&&t+o.width+i>r&&(l=Math.max(i,r-o.width-i)),o.height&&n+o.height+i>a&&(d=Math.max(i,a-o.height-i)),e.style.left=`${l}px`,e.style.top=`${d}px`}function Vt(e,t){const n=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${n}`}function _a(e){return`Clipboard ${e} blocked by the browser.`}function Sa(e,t,n,r,a,o){const i=e.leftBorderCol+1;if(t===r)return a-n;if(r<t){let f=n-i;f+=1;for(let h=r+1;h<t;h++){const u=o(h);if(u===null)return null;f+=Math.max(1,u-i+1)}const g=o(r);return g===null?null:(f+=Math.max(0,g-a),-f)}const l=o(t);if(l===null)return null;let d=Math.max(0,l-n)+1;for(let f=t+1;f<r;f++){const g=o(f);if(g===null)return null;d+=Math.max(1,g-i+1)}return d+=a-i,d}const Be=new Set(["│","┃","║","|"]);function ja(e,t,n,r){const a=e.baseY,o=(m,b)=>{const x=e.getLine(a+m);if(!x)return null;const v=x.getCell(b);return v?v.getChars():null},i=m=>{let b=-1;for(let v=0;v<n;v++){const p=o(m,v);if(p!==null&&Be.has(p)){b=v;break}}if(b===-1)return null;let x=-1;for(let v=n-1;v>b;v--){const p=o(m,v);if(p!==null&&Be.has(p)){x=v;break}}return x===-1?null:{leftBorderCol:b,rightBorderCol:x}};let l=t,d=i(t);if(!d){const m=i(t-1);if(m)l=t-1,d=m;else{const b=i(t+1);b&&(l=t+1,d=b)}}if(!d)return null;const{leftBorderCol:f,rightBorderCol:g}=d;let h=l;for(let m=l-1;m>=0;m--){const b=o(m,f);if(b===null)break;if(!(b===""||b===" ")){if(!Be.has(b))break;h=m}}let u=l;for(let m=l+1;m<r;m++){const b=o(m,f);if(b===null)break;if(!(b===""||b===" ")){if(!Be.has(b))break;u=m}}return{topRow:h,bottomRow:u,leftBorderCol:f,rightBorderCol:g}}function ka(e,t,n,r){const a=e.getLine(e.baseY+t);if(!a)return null;for(let o=r;o>=n;o--){const i=a.getCell(o);if(!i)continue;const l=i.getChars();if(l!==""&&l!==" ")return o}return n-1}const Ca=200;function Na(e){const{click:t,terminal:n,cellSurface:r,debug:a}=e,o=n.buffer.active,i=y=>{a==null||a({cursorY:o.cursorY,cursorX:o.cursorX,originalTargetCol:y.originalTargetCol??y.targetCol,snapped:y.snapped??!1,...y})};if(o.type==="alternate")return i({targetRow:-1,targetCol:-1,box:null,rejected:"alt-screen",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(o.viewportY!==o.baseY)return i({targetRow:-1,targetCol:-1,box:null,rejected:"scrollback",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const l=r.getBoundingClientRect();if(l.width===0||l.height===0)return i({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const d=t.clientX-l.left,f=t.clientY-l.top;if(d<0||f<0||d>=l.width||f>=l.height)return i({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const g=l.width/n.cols,h=l.height/n.rows,u=Math.floor(d/g),m=Math.floor(f/h),b=n.modes.applicationCursorKeysMode,x=b?"\x1BOC":"\x1B[C",v=b?"\x1BOD":"\x1B[D",p=ja(o,o.cursorY,n.cols,n.rows);if(p){if(m<p.topRow||m>p.bottomRow)return i({targetRow:m,targetCol:u,box:p,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(u<=p.leftBorderCol||u>=p.rightBorderCol)return i({targetRow:m,targetCol:u,box:p,rejected:"border",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const y=p.leftBorderCol+1,S=p.rightBorderCol-1,k=B=>ka(o,B,y,S),O=o.cursorY<p.topRow||o.cursorY>p.bottomRow,D=O?p.bottomRow:o.cursorY,_=O?S:o.cursorX,A=m!==D;let C=null;if(A&&(C=k(m),C===null))return i({targetRow:m,targetCol:u,originalTargetCol:u,snapped:!1,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;let I=u,R=!1;if(A&&C!==null){const B=Math.max(y,C);u>B&&(I=B,R=!0)}if(m===D&&I===_)return i({targetRow:m,targetCol:I,originalTargetCol:u,snapped:R,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const $=Sa(p,D,_,m,I,k);if($===null)return i({targetRow:m,targetCol:I,originalTargetCol:u,snapped:R,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if($===0)return i({targetRow:m,targetCol:I,originalTargetCol:u,snapped:R,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(Math.abs($)>Ca)return i({targetRow:m,targetCol:I,originalTargetCol:u,snapped:R,box:p,rejected:"emit-cap",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const z=$<0?v.repeat(-$):x.repeat($);return i({targetRow:m,targetCol:I,originalTargetCol:u,snapped:R,box:p,rejected:null,emittedDirection:$<0?"left":"right",emittedByteCount:z.length,predictedCursorY:m,predictedCursorX:I}),z}if(m!==o.cursorY)return i({targetRow:m,targetCol:u,box:null,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const w=u-o.cursorX;if(w===0)return i({targetRow:m,targetCol:u,box:null,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const j=w<0?v.repeat(-w):x.repeat(w);return i({targetRow:m,targetCol:u,box:null,rejected:null,emittedDirection:w<0?"left":"right",emittedByteCount:j.length,predictedCursorY:m,predictedCursorX:u}),j}const Xt=1;function Ta(e,t){const{sendInput:n,pixelThreshold:r=3,timeThresholdMs:a=300,now:o=()=>Date.now(),onVerificationDisable:i}=t,l=e.element;if(!l)return()=>{};const d=l.querySelector(".xterm-screen")??l;let f=null,g=!1,h=null,u=null;const m=typeof e.onRender=="function"?e.onRender.bind(e):null;m&&(u=m(()=>{const v=h;if(!v)return;h=null;const p=e.buffer.active,w=Math.abs(p.cursorY-v.y),j=Math.abs(p.cursorX-v.x);if(w>Xt||j>Xt){g=!0;const y={predicted:v,actual:{y:p.cursorY,x:p.cursorX}};i?i(y):console.warn("[click-cursor] disabled — cursor diverged from prediction",y)}}));function b(v){if(v.button!==0||v.altKey||v.shiftKey||v.metaKey||v.ctrlKey){f=null;return}f={clientX:v.clientX,clientY:v.clientY,at:o()}}function x(v){var D;const p=f;if(f=null,!p)return;const w=v.clientX-p.clientX,j=v.clientY-p.clientY;if(Math.hypot(w,j)>r||o()-p.at>a)return;const y=typeof window<"u"&&((D=window.localStorage)==null?void 0:D.getItem("codeyam.terminalClickDebug"))==="1";if(y)try{const _=e.buffer.active,A=_.cursorY,C={};for(let I=-2;I<=2;I++){const R=A+I,$=_.getLine(_.baseY+R);if(!$)continue;const z=[];for(let B=0;B<e.cols;B++){const G=$.getCell(B);z.push(G?G.getChars():"")}C[`row${R}`]=z.join("|")}console.log("[click-cursor] buffer dump",{cursorY:A,cursorX:_.cursorX,viewportY:_.viewportY,baseY:_.baseY,rows:C})}catch{}let S=null;const k=_=>{S=_,y&&console.log("[click-cursor] result",_)},O=Na({click:{clientX:v.clientX,clientY:v.clientY},terminal:e,cellSurface:d,debug:k});if(O){if(S){const _=S,A=_.box!==null&&_.targetRow!==_.cursorY;if(A&&g){y&&console.log("[click-cursor] suppressed by verification-disabled");return}A&&_.predictedCursorY!==null&&_.predictedCursorX!==null&&(h={y:_.predictedCursorY,x:_.predictedCursorX})}n(O)}}return d.addEventListener("mousedown",b),d.addEventListener("mouseup",x),()=>{d.removeEventListener("mousedown",b),d.removeEventListener("mouseup",x),u==null||u.dispose()}}function Ea(e){const t=document.activeElement;return!(t instanceof HTMLElement)||!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable)?!1:!((e==null?void 0:e.contains(t))??!1)}const Jt=20*1024*1024,Oa=3e4,Aa=3e3;function Ma(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;if(typeof a!="string"){n(new Error("Unexpected FileReader result"));return}const o=a.indexOf(",");t(o===-1?a:a.slice(o+1))},r.onerror=()=>n(r.error??new Error("read failed")),r.readAsDataURL(e)})}function Pa(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Ra(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function In(e){const t=e==null?void 0:e.items;if(!t)return[];const n=[];for(const r of Array.from(t)){if(r.kind!=="file"||!r.type.startsWith("image/"))continue;const a=r.getAsFile();a&&n.push(a)}return n}function Ia(e,t){function n(r){const a=In(r.clipboardData);a.length!==0&&(r.preventDefault(),r.stopPropagation(),t(a))}return e.addEventListener("paste",n,!0),()=>e.removeEventListener("paste",n,!0)}function Da(){window.focus()}function La(e,t){Da(),e==null||e.focus({preventScroll:!0}),t()}function Fa(e,t,n=50){const r=c.useRef(t);r.current=t,c.useEffect(()=>{const a=e.current;if(!a)return;let o=null;const i=new ResizeObserver(l=>{o&&clearTimeout(o);const d=l[0];d&&(o=setTimeout(()=>{r.current(d)},n))});return i.observe(a),()=>{o&&clearTimeout(o),i.disconnect()}},[e,n])}function cc({viewportY:e,baseY:t}){return!Number.isFinite(e)||!Number.isFinite(t)?!1:e>=t}function $a({width:e,height:t,cellWidth:n,cellHeight:r}){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?!1:e>=n&&t>=r}function Ba(e){var t,n,r,a;try{const o=(a=(r=(n=(t=e._core)==null?void 0:t._renderService)==null?void 0:n.dimensions)==null?void 0:r.css)==null?void 0:a.cell;return{cellWidth:(o==null?void 0:o.width)??NaN,cellHeight:(o==null?void 0:o.height)??NaN}}catch{return{cellWidth:NaN,cellHeight:NaN}}}function za(e,t){const{cellWidth:n,cellHeight:r}=Ba(e);return $a({width:(t==null?void 0:t.clientWidth)??NaN,height:(t==null?void 0:t.clientHeight)??NaN,cellWidth:n,cellHeight:r})}function Dn(){return s.jsx("div",{"data-testid":"terminal-drop-overlay",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(30, 30, 30, 0.85)",color:"#D7FF63",fontFamily:"'IBM Plex Mono', monospace",fontSize:14,border:"2px dashed #D7FF63",borderRadius:6,pointerEvents:"none",zIndex:5},children:"Drop file to attach"})}const lc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropOverlay:Dn},Symbol.toStringTag,{value:"Module"}));function Ln({message:e}){return s.jsx("div",{"data-testid":"terminal-drop-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#3a1f1f",color:"#ff9494",border:"1px solid #7a3939",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:e})}const uc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropToast:Ln},Symbol.toStringTag,{value:"Module"}));let Fn=!1;function ct(e){Fn=e}function Ka(){return Fn}const Ha=800,$n="codeyam.miniAgent.deliveredSeed.";function Bn(e,t){try{window.sessionStorage.setItem($n+e,t)}catch{}}function Ua(e,t){try{return window.sessionStorage.getItem($n+e)===t}catch{return!1}}const Wa=5e3,Ya="*";function lt(e,t){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:{text:e,chatName:t}}))}const Va=250,zn="";function Xa(e){return`\x1B[200~${e}\x1B[201~`}function dc(e,t){const n=t.replace(/[\r\n]+$/,"");if(!e(zn))return null;e(Xa(n));const r=window.setTimeout(()=>e("\r"),Va);return()=>window.clearTimeout(r)}function Kn(e,t,n){return new Promise(r=>{let a=!1;const o=()=>{a||(a=!0,window.removeEventListener(e,i),clearTimeout(l),r())},i=d=>{n&&!n(d)||o()},l=setTimeout(o,t);window.addEventListener(e,i)})}function Ja(e,t="plan"){return Kn("miniagent-agent-idle",e,n=>{const r=n.detail;return(r==null?void 0:r.chatName)===t})}function Ga(e){return Ka()?Promise.resolve():Kn("miniagent-ws-open",e)}async function qa(e,t){return Ua(t,e)?(V("seed-suppressed-on-reattach",{chatName:t}),!1):(Bn(t,e),await Ga(Wa),await Ja(Ha,t),lt(zn,t),lt(e,t),await new Promise(n=>setTimeout(n,xe)),lt("\r",t),!0)}function Hn(){return s.jsx("div",{"data-testid":"terminal-connecting-hint",className:"absolute top-2 right-3 text-xs font-mono text-[#aaa] pointer-events-none z-10 select-none",children:"Connecting…"})}const fc=Object.freeze(Object.defineProperty({__proto__:null,TerminalConnectingHint:Hn},Symbol.toStringTag,{value:"Module"}));function Un({attempt:e,maxAttempts:t,pulseKey:n,label:r="Reconnecting…"}){return s.jsx("div",{"data-testid":"terminal-reconnecting-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/40",children:s.jsxs("div",{"data-testid":"terminal-reconnecting-banner-label",className:"px-4 py-2 rounded font-mono text-sm shadow terminal-disconnect-pulse bg-amber-500/90 text-black",children:[r," (attempt ",e," of ",t,")"]},n)})}const pc=Object.freeze(Object.defineProperty({__proto__:null,TerminalReconnectingBanner:Un},Symbol.toStringTag,{value:"Module"}));function Wn({onRefresh:e}){const{phase:t,attempts:n,retry:r}=_e(e);return s.jsx("div",{"data-testid":"terminal-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:"error",testId:"terminal-failed-notice",headline:"The terminal lost its connection",explanation:"The terminal tried to reconnect several times and couldn't get through. Either the editor restarted underneath it, or the connection between your browser and this machine dropped. Your files and your work are untouched — it's only the live terminal view that stopped.",nextAction:"Refresh the page to start a fresh terminal. If this keeps happening, copy this report and send it to whoever set up this machine.",actions:[{label:"Refresh page",onClick:r,pending:t==="pending",pendingLabel:"Refreshing…",testId:"terminal-failed-banner-refresh"}],actionFeedback:t==="unchanged"?s.jsxs("span",{"data-testid":"terminal-failed-banner-unchanged",children:["Tried just now — the terminal still isn’t back",n>1?` (${n} tries)`:"","."]}):null})})}const hc=Object.freeze(Object.defineProperty({__proto__:null,TerminalFailedBanner:Wn},Symbol.toStringTag,{value:"Module"}));function Yn({onReload:e,onDismiss:t}){const{phase:n,attempts:r,retry:a}=_e(e),o=[{label:"Reload page",onClick:a,pending:n==="pending",pendingLabel:"Checking…",testId:"terminal-server-stopped-banner-reload"}];return t&&o.push({label:"Dismiss — keep trying to reconnect",onClick:t,variant:"secondary",ariaLabel:"Dismiss the lost-contact notice and keep trying to reconnect",testId:"terminal-server-stopped-banner-dismiss"}),s.jsx("div",{"data-testid":"terminal-server-stopped-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:"error",testId:"terminal-server-stopped-notice",headline:"Lost contact with the editor",explanation:"This page stopped hearing from the editor. The editor may have been closed, or the connection may just be slow — the agent can still be working behind this notice. Nothing you were working on is lost.",nextAction:"If the editor was closed, start it again — this page comes back by itself once it's reachable, so you don't need to keep clicking. Reload page only checks early. If you can see the agent still working, dismiss this to keep reconnecting.",actions:o,actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-server-stopped-banner-unchanged",children:["Checked just now — the editor still isn’t answering",r>1?` (${r} tries)`:"","."]}):null})})}const mc=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerStoppedBanner:Yn},Symbol.toStringTag,{value:"Module"}));function Vn({message:e,onRefresh:t}){return s.jsx("div",{"data-testid":"terminal-server-error-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:s.jsxs("div",{className:"px-4 py-3 rounded font-mono text-sm shadow flex items-start gap-3 max-w-2xl bg-amber-500/95 text-black border border-amber-700",children:[s.jsx("pre",{"data-testid":"terminal-server-error-banner-message",className:"whitespace-pre-wrap break-words flex-1 m-0 font-mono text-xs leading-snug",children:e}),s.jsxs("div",{className:"flex items-start gap-2 self-start shrink-0",children:[s.jsx(on,{variant:"subtle",text:e,label:"Copy",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"}),s.jsx("button",{type:"button",onClick:t,"data-testid":"terminal-server-error-banner-refresh",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50",children:"Refresh"})]})]})})}const bc=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerErrorBanner:Vn},Symbol.toStringTag,{value:"Module"}));function Xn({onRefresh:e}){const{phase:t,attempts:n,retry:r}=_e(e);return s.jsx("div",{"data-testid":"terminal-edge-unreachable-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:"warning",testId:"terminal-edge-unreachable-notice",headline:"The terminal can't reach this machine",explanation:"The editor itself is loading fine and you're signed in — it's the terminal's own live connection that isn't getting through. Nothing you did caused this, and your work isn't lost.",nextAction:"Try Retry. If it keeps failing, this one isn't yours to fix — copy this report and send it to whoever set up this machine.",actions:[{label:"Retry",onClick:r,pending:t==="pending",pendingLabel:"Reconnecting…",testId:"terminal-edge-unreachable-banner-retry"}],actionFeedback:t==="unchanged"?s.jsxs("span",{"data-testid":"terminal-edge-unreachable-banner-unchanged",children:["Checked just now — still not connecting",n>1?` (${n} tries)`:"","."]}):null,diagnostics:"The editor answers over HTTP and the session is valid, but the terminal's live connection channel does not complete. Typically the network path in front of this machine is not carrying it."})})}const gc=Object.freeze(Object.defineProperty({__proto__:null,TerminalEdgeUnreachableBanner:Xn},Symbol.toStringTag,{value:"Module"}));function Jn({canRetry:e=!1,onRefresh:t}){const{phase:n,attempts:r,retry:a}=_e(t);return s.jsx("div",{"data-testid":"terminal-session-stale-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:"warning",testId:"terminal-session-stale-notice",headline:e?"Couldn't get this tab signed back in":"Signing this tab back in",explanation:e?"The editor restarted, which signed this tab out. It tried to sign back in automatically and couldn't.":"The editor restarted, which signed this tab out. It's signing back in and reconnecting the terminal now.",nextAction:e?"Use Retry to try again. If that doesn't take, reload the page — that always gets a fresh session.":"Nothing, unless this sticks around. If the terminal hasn't come back after about ten seconds, reload the page.",actions:e?[{label:"Retry",onClick:a,pending:n==="pending",pendingLabel:"Retrying…",testId:"terminal-session-stale-banner-retry"}]:[],actionFeedback:e&&n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-session-stale-banner-unchanged",children:["Tried just now — still signed out",r>1?` (${r} tries)`:"",". Reloading the page will fix it."]}):null})})}const xc=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionStaleBanner:Jn},Symbol.toStringTag,{value:"Module"}));function Qa(e){if(e.oomSignature)return{headline:"This session was killed because the machine ran out of memory.",body:"The agent did not stop on its own and did not crash — the system killed it to reclaim memory, so nothing it was in the middle of was saved. Free some memory before starting a new session, or the same thing will happen again.",retryLikelyHelps:!1};if(e.externalDeath)return{headline:`This session was stopped from outside the editor (${e.signal??"an external signal"}).`,body:"Something other than the editor ended the agent process. Nothing it was in the middle of was saved. Starting a new session is safe, but if this keeps happening the cause is outside the editor.",retryLikelyHelps:!0};if(e.origin==="broker-initiated")return{headline:"This session was stopped.",body:"The editor ended the agent process — this is what you get after Stop Building, or after a session sits unused long enough to be cleaned up. Start a new session whenever you are ready.",retryLikelyHelps:!0};const t=e.exitCode;return{headline:t===null?"The agent process ended.":`The agent process ended on its own (exit code ${t}).`,body:"The agent was not killed — it exited by itself, so whatever it printed above is the best evidence for why. Starting a new session is safe.",retryLikelyHelps:!0}}function Gn({report:e,onRefresh:t}){const{phase:n,attempts:r,retry:a}=_e(t),o=Qa(e);return s.jsx("div",{"data-testid":"terminal-session-died-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:o.retryLikelyHelps?"warning":"error",testId:"terminal-session-died-notice",headline:o.headline,explanation:o.body,nextAction:o.retryLikelyHelps?"Start a new session when you're ready. Reloading the page gets you a clean one.":"Free up memory first — close other work on this machine — then reload the page to start a new session.",actions:[{label:"Reload",onClick:a,pending:n==="pending",pendingLabel:"Reloading…",testId:"terminal-session-died-banner-reload"}],actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-session-died-banner-unchanged",children:["Tried just now — still no session",r>1?` (${r} tries)`:"","."]}):null})})}const yc=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionDiedBanner:Gn},Symbol.toStringTag,{value:"Module"}));function qn({status:e,pulseKey:t,onRefresh:n,reconnectingLabel:r,onDismissServerStopped:a}){return e.kind==="open"||e.kind==="ended"?null:e.kind==="connecting"?s.jsx(Hn,{}):e.kind==="reconnecting"?s.jsx(Un,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t,label:r}):e.kind==="server-stopped"?s.jsx(Yn,{onReload:n,onDismiss:a}):e.kind==="server-error"?s.jsx(Vn,{message:e.message,onRefresh:n}):e.kind==="edge-unreachable"?s.jsx(Xn,{onRefresh:n}):e.kind==="session-died"?s.jsx(Gn,{report:e.report,onRefresh:n}):e.kind==="session-stale"?s.jsx(Jn,{canRetry:e.canRetry,onRefresh:n}):s.jsx(Wn,{onRefresh:n})}const vc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDisconnectOverlay:qn},Symbol.toStringTag,{value:"Module"}));function Qn(){return s.jsx("div",{"data-testid":"mini-agent-launch-retrying",className:"absolute inset-x-0 top-2 z-10 flex justify-center pointer-events-none",children:s.jsx("span",{className:"font-mono text-xs italic text-[var(--text-dim)] bg-black/40 px-2 py-1 rounded",children:"Launch slow — retrying…"})})}const wc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchRetryingHint:Qn},Symbol.toStringTag,{value:"Module"}));function Za(e){if((e==null?void 0:e.kind)==="rejected")return{headline:`The agent didn't recognize ${e.command}`,explanation:`The build agent started, but it doesn't have the ${e.command} command installed, so nothing began. Nothing in your code has been touched.`,nextAction:"Use Retry — it installs the command again and sends it to the agent that is already running. If it is rejected again, copy this report and send it on.",unchangedAfterRetry:`Tried just now — the agent still didn't recognize ${e.command}`};if((e==null?void 0:e.kind)==="unsupported"){const t=Se(e.provider);return{headline:`This chat isn't available with ${t}`,explanation:`This chat runs through the ${e.command} command, and ${t} can't run CodeYam's commands. Nothing was started and nothing in your code has been touched.`,nextAction:"Switch the build agent to Claude, Codex, or OpenCode in settings to use this chat, or continue without it.",unchangedAfterRetry:`Tried just now — ${t} still can't run ${e.command}`}}return{headline:"The build agent didn't start",explanation:"CodeYam opened a shell to start the build agent and it never became ready. This is the agent failing to start, not your project — nothing in your code has been touched.",nextAction:"Use Retry. If it fails again, copy this report and send it on — a shell that will not come up is a setup problem on this machine rather than something to fix in your project.",unchangedAfterRetry:"Tried just now — the agent still didn’t start"}}function Zn({failure:e=null,onRetry:t}){const{phase:n,attempts:r,retry:a}=_e(t),o=Za(e);return s.jsx("div",{"data-testid":"mini-agent-launch-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(de,{severity:"error",testId:"mini-agent-launch-failed-notice",headline:o.headline,explanation:o.explanation,nextAction:o.nextAction,actions:(e==null?void 0:e.kind)==="unsupported"?[]:[{label:"Retry",onClick:a,pending:n==="pending",pendingLabel:"Starting…",testId:"mini-agent-launch-failed-retry"}],actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"mini-agent-launch-failed-unchanged",children:[o.unchangedAfterRetry,r>1?` (${r} tries)`:"","."]}):null})})}const _c=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchFailed:Zn},Symbol.toStringTag,{value:"Module"}));function er({status:e,failure:t=null,onRetry:n}){return e==="retrying"?s.jsx(Qn,{}):e==="failed"?s.jsx(Zn,{failure:t,onRetry:n}):null}const Sc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchOverlay:er},Symbol.toStringTag,{value:"Module"}));function eo(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}const to=e=>{typeof fetch=="function"&&fetch("/api/launch-trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(eo(e)),keepalive:!0}).catch(()=>{})};let no=to;function tr(e){no(e)}function Xe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=()=>Math.floor(Math.random()*4294967296).toString(16);return`${e()}-${e()}-${e()}-${e()}`}function nr(e){return e?e==="initial-design"?"design":e==="design-tweak"?"design-tweak":e==="plan"||e.startsWith("edit-plan-")?"plan":"other":"build"}function rr(e){const t=e==null?void 0:e.trim().split(/\s+/)[0];return t&&/^\/[a-z0-9-]{1,64}$/.test(t)?t:void 0}let St=null;function jc(e){St=e}function ro(){const e=St;return St=null,e}function kc(e){return e??ro()??Xe()}function so(e){return e==="fired"?{event:"rename-fired"}:e==="superseded"?{event:"rename-skipped",reason:"superseded"}:{event:"rename-failed"}}function ao({attempt:e,sawOutput:t}){return t?e===1?"extend":"ready":e===1?"retry":"fail"}function oo({idleMs:e,ceilingMs:t}){return new Promise(n=>{let r=null,a=null,o=!1;function i(){o||(o=!0,r!==null&&clearTimeout(r),a!==null&&clearTimeout(a),window.removeEventListener("miniagent-output",d),n())}function l(){r!==null&&clearTimeout(r),r=setTimeout(i,e)}function d(){l()}window.addEventListener("miniagent-output",d),a=setTimeout(i,t),l()})}const io=350,co=4e3,Gt=8e3,re={armed:"mini-agent-launch-armed",fired:"mini-agent-launch-fired",ready:"mini-agent-launch-ready",confirmed:"mini-agent-launch-confirmed",relaunch:"mini-agent-relaunch",failed:"mini-agent-launch-failed",reattached:"mini-agent-launch-reattached"};function lo(e,t){var I;const{epochRef:n,attemptStartTsRef:r,agentAliveRef:a,pendingLaunchIdRef:o,launchIdRef:i,retryOfRef:l,renameScheduledRef:d,outputCountRef:f,outputCountAtLaunchRef:g,providerRef:h,slashCommandRef:u,promptRef:m,chatNameRef:b,sendInputRef:x,onLaunchAttemptRef:v,setStatus:p,trace:w,sendLaunchPayload:j,enterReady:y}=t,S=++n.current,k=Date.now();r.current=k,a.current=!1,e==="retry"&&i.current?(l.current=i.current,i.current=Xe()):(l.current=null,i.current=o.current??Xe(),o.current=null),(I=v.current)==null||I.call(v,{launchId:i.current,retryOf:l.current});const O=m.current;tr({event:"armed",launchId:i.current,retryOf:l.current,role:nr(b.current),command:rr(u.current),promptLen:typeof O=="string"?O.length:void 0});const D=u.current;if(D&&!hs(h.current)){p("failed",{kind:"unsupported",command:D.split(/\s+/)[0],provider:h.current}),w({event:"prompt-rejected",reason:"skill-invocation-unsupported"}),V(re.failed,{launchId:i.current,provider:h.current,slashCommand:D,reason:"skill-invocation-unsupported",elapsedMs:0});return}g.current=f.current,p("armed"),V(re.armed,{launchId:i.current,provider:h.current,slashCommand:u.current,chatName:b.current,hasPrompt:typeof m.current=="string"});function _(){return n.current===S}function A(R){_()&&(p(R===1?"firing":"retrying"),w({event:"fired"},{attempt:R,elapsedMs:Date.now()-k}),V(R===1?re.fired:re.relaunch,{launchId:i.current,provider:h.current,slashCommand:u.current,chatName:b.current,attempt:R,elapsedMs:Date.now()-k}),j(x.current,_).then(()=>{_()&&(g.current=f.current,w({event:"prompt-written",kind:"ui-payload"},{attempt:R,elapsedMs:Date.now()-k}))}),ps(h.current)?d.current?w({event:"rename-skipped",reason:"already-scheduled"}):(d.current=!0,w({event:"rename-queued"}),Es(b.current,"mini-agent-chat",$=>x.current($),vt,$=>w(so($)))):w({event:"rename-skipped",reason:"provider-unsupported"}),setTimeout(()=>C(R),Gt))}function C(R){if(!_())return;const $=f.current>g.current;switch(ao({attempt:R,sawOutput:$})){case"retry":A(2);return;case"extend":V(re.relaunch,{launchId:i.current,provider:h.current,slashCommand:u.current,attempt:2,sawOutput:!0,resent:!1,elapsedMs:Date.now()-k}),setTimeout(()=>C(2),Gt);return;case"ready":y("output-without-banner");return;case"fail":p("failed"),w({event:"prompt-rejected",reason:"banner-timeout"},{attempt:R,elapsedMs:Date.now()-k}),V(re.failed,{launchId:i.current,provider:h.current,slashCommand:u.current,reason:"banner-timeout",sawOutput:!1,elapsedMs:Date.now()-k})}}oo({idleMs:io,ceilingMs:co}).then(()=>{_()&&A(1)})}const uo=500,fo=5e3;function po(e){const{provider:t,slashCommand:n,prompt:r,chatName:a,sendInput:o,permissionModeAuto:i=!0,shellDialect:l=null,onLaunchAttempt:d,beforeRelaunch:f}=e,[g,h]=c.useState("idle"),[u,m]=c.useState(null),b=c.useRef("idle"),x=c.useRef(null),v=c.useCallback((N,K=null)=>{b.current=N,x.current=K,h(N),m(K)},[]),p=c.useRef(!1),w=c.useRef(f);c.useEffect(()=>{w.current=f},[f]);const j=c.useRef(o),y=c.useRef(n),S=c.useRef(r),k=c.useRef(a),O=c.useRef(t),D=c.useRef(i),_=c.useRef(l),A=c.useRef(null),C=c.useCallback(N=>{A.current=N},[]),I=c.useRef(null),R=c.useCallback(N=>{I.current=N},[]);c.useEffect(()=>{j.current=o},[o]),c.useEffect(()=>{D.current=i},[i]),c.useEffect(()=>{_.current=l},[l]),c.useEffect(()=>{y.current=n},[n]),c.useEffect(()=>{S.current=r},[r]),c.useEffect(()=>{k.current=a},[a]),c.useEffect(()=>{O.current=t},[t]);const $=c.useRef(d);c.useEffect(()=>{$.current=d},[d]);const z=c.useRef(null),B=c.useRef(null),G=c.useRef(null),ee=c.useCallback(()=>(z.current??(z.current=Xe()),z.current),[]),Z=c.useCallback((N,K={})=>{const J=B.current;J&&tr({...N,...K,launchId:J,retryOf:G.current,role:nr(k.current),command:rr(y.current)})},[]),U=c.useRef(0),te=c.useRef(!1),q=c.useRef(0),se=c.useRef(0),W=c.useRef(0);c.useEffect(()=>{const N=()=>{se.current+=1};return window.addEventListener("miniagent-output",N),()=>window.removeEventListener("miniagent-output",N)},[]);const Y=c.useCallback((N,K)=>{const J=y.current,ne=S.current;return Re(vt,()=>{const pe=_.current??"posix";if(J){const oe=Ns(O.current,J,D.current,pe,A.current,I.current),Fe=ut(oe);return N(Fe),new Promise(E=>{setTimeout(()=>{K()&&N("\r"),E()},xe)})}const[De,he]=Ps(O.current,ne??"",D.current,pe,A.current,I.current),me=ut(De),Le=ut(he);return N(me),new Promise(oe=>{setTimeout(()=>{if(!K())return oe();N("\r"),setTimeout(()=>{if(!K())return oe();N(Le),setTimeout(()=>{K()&&N("\r"),oe()},xe)},uo)},xe)})})},[]),Q=c.useCallback(N=>{const K=b.current;if(K==="ready"||K==="confirmed"||x.current)return;const J=++U.current;p.current=!0,v("ready"),V(re.ready,{launchId:B.current,provider:O.current,slashCommand:y.current,reason:N,elapsedMs:Date.now()-q.current}),setTimeout(()=>{if(U.current!==J)return;v("confirmed");const ne=Date.now()-q.current;Z({event:"prompt-accepted",reason:N},{elapsedMs:ne}),V(re.confirmed,{launchId:B.current,provider:O.current,slashCommand:y.current,reason:N,verified:!1,elapsedMs:ne})},fo)},[v,Z]),ae=c.useCallback(N=>lo(N,{epochRef:U,attemptStartTsRef:q,agentAliveRef:p,pendingLaunchIdRef:z,launchIdRef:B,retryOfRef:G,renameScheduledRef:te,outputCountRef:se,outputCountAtLaunchRef:W,providerRef:O,slashCommandRef:y,promptRef:S,chatNameRef:k,sendInputRef:j,onLaunchAttemptRef:$,setStatus:v,trace:Z,sendLaunchPayload:Y,enterReady:Q}),[Y,Q,v,Z]),P=c.useCallback(async N=>{var J;const K=++U.current;q.current=Date.now(),v("retrying"),V(re.relaunch,{launchId:B.current,provider:O.current,slashCommand:N,inAgent:!0}),await((J=w.current)==null?void 0:J.call(w).catch(()=>{})),U.current===K&&(await xn(N,ne=>j.current(ne),vt),U.current===K&&Q("relaunch-in-agent"))},[Q,v]),T=c.useCallback(()=>{te.current=!1,ae("arm")},[ae]),H=c.useCallback(()=>{const N=y.current;if(p.current&&N){P(N);return}ae("retry")},[ae,P]),F=c.useCallback(()=>{U.current!==0&&b.current!=="armed"&&Q("banner")},[Q]),fe=c.useCallback(N=>{var ne;if(U.current===0)return;const K=b.current;if(K==="confirmed"||K==="idle"||((ne=x.current)==null?void 0:ne.kind)==="rejected")return;U.current++,p.current=!0,v("failed",{kind:"rejected",command:N});const J=Date.now()-q.current;Z({event:"prompt-rejected",reason:"slash-command-rejected"},{elapsedMs:J}),V(re.failed,{launchId:B.current,provider:O.current,slashCommand:y.current,reason:"slash-command-rejected",command:N,elapsedMs:J})},[v,Z]),nt=c.useCallback(()=>{if(U.current===0)return;U.current++,p.current=!1,v("failed");const N=Date.now()-q.current;Z({event:"prompt-rejected",reason:"startup-failed"},{elapsedMs:N}),V(re.failed,{launchId:B.current,reason:"startup-failed",elapsedMs:N})},[v,Z]),rt=c.useCallback(()=>{U.current++,v("confirmed"),V(re.reattached,{provider:O.current,chatName:k.current})},[v]);return c.useEffect(()=>()=>{U.current++},[]),{status:g,failure:u,peekLaunchId:ee,arm:T,retry:H,onBannerReady:F,onRejected:fe,onStartupFailed:nt,onReattached:rt,setLaunchProgram:C,setLaunchSessionId:R}}function ut(e){return e.endsWith("\r")?e.slice(0,-1):e}const Ge=c.createContext({registerSender:()=>{},setReady:()=>{},sendToAgent:()=>!1,agentReady:!1});function ho({children:e}){const t=c.useRef(null),[n,r]=c.useState(!1),a=c.useCallback(d=>{t.current=d},[]),o=c.useCallback(d=>{r(d)},[]),i=c.useCallback(d=>{const f=t.current;return f?f(d):!1},[]),l=c.useMemo(()=>({registerSender:a,setReady:o,sendToAgent:i,agentReady:n}),[a,o,i,n]);return s.jsx(Ge.Provider,{value:l,children:e})}function mo(){const{sendToAgent:e,agentReady:t}=c.useContext(Ge);return{sendToAgent:e,agentReady:t}}function bo(e,t){const{registerSender:n,setReady:r}=c.useContext(Ge);c.useEffect(()=>(n(e),()=>n(null)),[n,e]),c.useEffect(()=>(r(t),()=>r(!1)),[r,t])}function sr(){const{registerSender:e,setReady:t}=c.useContext(Ge);return{registerSender:e,setReady:t}}const Cc=Object.freeze(Object.defineProperty({__proto__:null,AgentInputProvider:ho,useAgentInput:mo,useAgentInputChannel:sr,useRegisterAgentInput:bo},Symbol.toStringTag,{value:"Module"})),jt=new Map,kt=new Set;function Nc(e){return jt.get(e)??null}function qt(e,t){const n=jt.get(e)??null;if(!(t&&n&&t.length===n.length&&t.every((r,a)=>r===n[a]))&&!(t===null&&n===null)){jt.set(e,t);for(const r of kt)r()}}function Tc(e){return kt.add(e),()=>kt.delete(e)}function go({wsRef:e,insertInput:t}){const[n,r]=c.useState(!1),[a,o]=c.useState(null),i=c.useRef(new Map),l=c.useRef(0);c.useEffect(()=>{if(a===null)return;const y=window.setTimeout(()=>o(null),Aa);return()=>window.clearTimeout(y)},[a]);const d=c.useCallback(y=>{o(y)},[]),f=c.useCallback((y,S)=>{const k=i.current.get(y);k&&(i.current.delete(y),k.resolve(S))},[]),g=c.useCallback((y,S)=>{const k=i.current.get(y);k&&(i.current.delete(y),k.reject(S))},[]),h=c.useCallback(y=>{for(const[,S]of i.current)S.reject(y);i.current.clear()},[]),u=c.useCallback(async({file:y,relativePath:S})=>{if(y.size>Jt)throw new Error(`File too large (max ${Jt/(1024*1024)} MB)`);const k=e.current;if(!k||k.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const O=await Ma(y),D=Pa(),_=new Promise((A,C)=>{const I=window.setTimeout(()=>{i.current.delete(D)&&C(new Error("Timed out waiting for save to complete"))},Oa);i.current.set(D,{resolve:R=>{window.clearTimeout(I),A(R)},reject:R=>{window.clearTimeout(I),C(new Error(R))}})});return k.send(JSON.stringify({type:"drop",id:D,name:S||y.name||"unnamed",mime:y.type||"application/octet-stream",data:O})),_},[e]),m=c.useCallback(async y=>{if(y.length===0)return;const S=[];for(const k of y)try{S.push(await u(k))}catch(O){const D=O instanceof Error?O.message:String(O);d(`Attach failed: ${D}`);return}t(S.map(Ra).join(" ")+" ")},[u,d,t]),b=c.useCallback(y=>{y.dataTransfer.types.includes("Files")&&(y.preventDefault(),l.current+=1,r(!0))},[]),x=c.useCallback(y=>{y.dataTransfer.types.includes("Files")&&y.preventDefault()},[]),v=c.useCallback(y=>{y.dataTransfer.types.includes("Files")&&(l.current=Math.max(0,l.current-1),l.current===0&&r(!1))},[]),p=c.useCallback(async y=>{if(!y.dataTransfer.types.includes("Files"))return;y.preventDefault(),l.current=0,r(!1);const{files:S,error:k}=await Ys(y.dataTransfer);k&&d(k),await m(S)},[m,d]),w=c.useCallback(y=>m(kn(y)),[m]),j=c.useCallback(async y=>{const S=In(y.clipboardData);S.length!==0&&(y.preventDefault(),await w(S))},[w]);return{dragActive:n,errorToast:a,dropHandlers:{onDragEnter:b,onDragOver:x,onDragLeave:v,onDrop:p},pasteHandler:j,handleImageFiles:w,handleAttachedFiles:m,resolveDrop:f,rejectDrop:g,cancelAllDrops:h,showError:d}}function xo(e,t){return c.useCallback(async n=>{var r;return((r=e.current)==null?void 0:r.readyState)!==WebSocket.OPEN?!1:(await t.current.handleAttachedFiles(n),!0)},[e,t])}function ar(e){const t=c.useRef(e);return t.current=e,t}function yo({wsRef:e,insertInput:t}){const n=go({wsRef:e,insertInput:t}),r=ar(n),a=c.useCallback(i=>{var l;return((l=e.current)==null?void 0:l.readyState)===WebSocket.OPEN?(e.current.send(JSON.stringify({type:"input",data:i})),!0):!1},[e]),o=xo(e,r);return{drops:n,dropCallbacksRef:r,sendToAgent:a,acceptPickedFiles:o}}const vo="The editor server closed the terminal connection with no further detail.";function wo(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return vo}const Ee=15;function _o(e){const{wsRef:t,setWsStatus:n,dismissServerStoppedRef:r}=e;let a=!1,o=0,i=null;const l={connect:d,isEnded:()=>a,end:()=>{a=!0},failWithServerError:g=>{a=!0,n({kind:"server-error",message:wo(g)})},dispose:()=>{a=!0,i==null||i(),i=null,r.current=null}};r.current=()=>{i==null||i(),i=null,o=0,e.announceReconnectOnDismiss&&n({kind:"reconnecting",attempt:1,maxAttempts:Ee}),d()};function d(){var g;if(e.announceConnecting&&n({kind:"connecting"}),(g=e.onBeforeConnect)==null||g.call(e),!e.catchConnectErrors){f();return}try{f()}catch{n({kind:"failed"})}}function f(){const g=new WebSocket(e.buildUrl());t.current=g,g.binaryType="arraybuffer",g.onmessage=h=>e.onMessage(h),g.onopen=()=>{var h;o=0,n({kind:"open"}),(h=e.onOpen)==null||h.call(e,g)},g.onerror=()=>{},g.onclose=async()=>{var u,m;if((u=e.onClose)==null||u.call(e,{reconnectAttempts:o}),a){n(b=>b.kind==="server-error"?b:{kind:"ended"}),(m=e.onEnded)==null||m.call(e);return}n({kind:"reconnecting",attempt:Math.min(o+1,Ee),maxAttempts:Ee});const h=await On();if(!a){if(h){n({kind:"server-stopped"}),i==null||i(),i=An(2e3,()=>{a||window.location.reload()});return}if(!(e.diagnoseClose&&await e.diagnoseClose(l)))if(o<Ee){const b=o<4?1e3*Math.pow(2,o):1e4;o++,n({kind:"reconnecting",attempt:o,maxAttempts:Ee}),setTimeout(()=>{a||d()},b)}else n({kind:"failed"})}}}return l}function So(){const e=c.useRef(null),[t,n]=c.useState({kind:"connecting"}),[r,a]=c.useState(0),o=c.useRef(null),i=c.useCallback(()=>a(f=>f+1),[]),l=c.useCallback(()=>{var f;return(f=o.current)==null?void 0:f.call(o)},[]),d=c.useCallback(f=>_o({...f,wsRef:e,setWsStatus:n,dismissServerStoppedRef:o}),[]);return{wsRef:e,wsStatus:t,setWsStatus:n,pulseKey:r,bumpPulse:i,dismissServerStopped:l,openSocket:d}}function jo(e){var r;const t=e.buffer.active,n=[];for(let a=0;a<e.rows;a++)n.push(((r=t.getLine(t.baseY+a))==null?void 0:r.translateToString(!0))??"");return n}function or({className:e=""}){const{openPicker:t}=Cn(),[n,r]=c.useState(!1),a=c.useRef(null);return s.jsxs("span",{className:"relative inline-flex",children:[s.jsxs("button",{ref:a,type:"button",onClick:()=>r(o=>!o),title:"Attach files or a folder","aria-label":"Attach files or a folder","aria-haspopup":"menu","aria-expanded":n,"data-testid":"attach-file-button",className:`inline-flex items-center gap-1 text-xs font-medium cursor-pointer bg-transparent border-none text-[var(--text-dim)] hover:text-[var(--text-primary)] transition ${e}`,children:[s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),"Attach"]}),n&&s.jsx(ln,{onChooseFiles:()=>t("files"),onChooseFolder:()=>t("folder"),onClose:()=>r(!1),triggerRef:a})]})}const Ec=Object.freeze(Object.defineProperty({__proto__:null,AttachFileButton:or},Symbol.toStringTag,{value:"Module"}));function dt(e,t,n){if(!za(e,t))return!1;try{return n.fit(),!0}catch{return!1}}function ir({chatName:e,prompt:t,slashCommand:n,seedText:r,height:a=400,onClose:o,beforeRelaunch:i,binding:l,onInputChannel:d,onScreen:f}){const g=ar(l),h=c.useRef(null),{wsRef:u,wsStatus:m,pulseKey:b,bumpPulse:x,dismissServerStopped:v,openSocket:p}=So(),w=c.useRef(null),j=c.useRef(null);c.useRef(t);const{config:y}=Pn(),S=(y==null?void 0:y.provider)??"claude",[k,O]=c.useState(()=>Yt()),D=c.useCallback(P=>{const T=u.current;(T==null?void 0:T.readyState)===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:P}))},[]),{drops:_,dropCallbacksRef:A,sendToAgent:C,acceptPickedFiles:I}=yo({wsRef:u,insertInput:D}),{registerSender:R,setReady:$}=sr(),z=m.kind==="open";c.useEffect(()=>(z&&R(C),()=>R(null)),[R,C,z]),c.useEffect(()=>{var P,T;(T=(P=g.current)==null?void 0:P.onSender)==null||T.call(P,z?C:null)},[C,z]),c.useEffect(()=>($(z),()=>$(!1)),[$,z]);const B=c.useRef(d),G=c.useRef(f);c.useEffect(()=>{B.current=d,G.current=f}),c.useEffect(()=>{var P;if(z)return(P=B.current)==null||P.call(B,C),()=>{var T;return(T=B.current)==null?void 0:T.call(B,null)}},[C,z]);const{registerFileSink:ee}=Nn();c.useEffect(()=>(z&&ee(I),()=>ee(null)),[ee,I,z]);const Z=c.useCallback(()=>{var P;((P=u.current)==null?void 0:P.readyState)===WebSocket.OPEN&&(R(C),$(!0),ee(I)),La(h.current,()=>{var T;return(T=j.current)==null?void 0:T.focus()})},[R,$,C,ee,I]),{shellDialect:U}=cn(),te=c.useRef(null),q=c.useCallback(({launchId:P,retryOf:T})=>{te.current=P;const H=u.current;(H==null?void 0:H.readyState)===WebSocket.OPEN&&H.send(JSON.stringify({type:"launch-attempt",launchId:P,retryOf:T}))},[]),se=po({provider:S,slashCommand:n,prompt:t,chatName:e,sendInput:D,permissionModeAuto:(y==null?void 0:y.claudePermissionModeAuto)??!0,shellDialect:U,onLaunchAttempt:q,beforeRelaunch:i}),W=c.useRef(se);c.useEffect(()=>{W.current=se});const Y=c.useRef(e);c.useEffect(()=>{Y.current=e});const Q=c.useRef(r),ae=c.useRef(n);return c.useEffect(()=>{Q.current=r,ae.current=n}),c.useEffect(()=>{const P=h.current;if(!P||Yt())return;const T=new ua.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),H=new da.FitAddon;T.loadAddon(H),T.open(P);const F=va(T,P,{onError:E=>console.warn("[MiniAgentChat]",E)}),fe=Ta(T,{sendInput:E=>{const M=u.current;(M==null?void 0:M.readyState)===WebSocket.OPEN&&M.send(JSON.stringify({type:"input",data:E}))}}),nt=Ia(P,E=>{A.current.handleImageFiles(E)}),rt=requestAnimationFrame(()=>{if(!dt(T,P,H))return;he=!0;const E=u.current;(E==null?void 0:E.readyState)===WebSocket.OPEN&&E.send(JSON.stringify({type:"resize",cols:T.cols,rows:T.rows}))});j.current=T,w.current=H;let N;const K=()=>{N!==void 0&&window.clearTimeout(N),N=window.setTimeout(()=>{var M,X,ie;N=void 0;const E=jo(T);qt(Y.current,E),(X=(M=g.current)==null?void 0:M.onScreen)==null||X.call(M,E),(ie=G.current)==null||ie.call(G,E)},300)},J={current:"inline"},ne={current:null},pe={current:!1},De={current:!1};let he=!1;const me=p({announceConnecting:!0,buildUrl:()=>ma({mode:J.current,sessionId:ne.current??void 0,chatKey:e,launchId:te.current??W.current.peekLaunchId(),cols:he?T.cols:void 0,rows:he?T.rows:void 0,capture:Rn()}),onOpen:E=>{ct(!0),window.dispatchEvent(new CustomEvent("miniagent-ws-open")),E.send(JSON.stringify({type:"resize",cols:T.cols,rows:T.rows}))},onMessage:E=>{var M,X,ie,ke;if(E.data instanceof ArrayBuffer){T.write(new Uint8Array(E.data)),K(),window.dispatchEvent(new CustomEvent("miniagent-output"));return}try{const L=JSON.parse(E.data);if(L.type==="error"&&L.reason===ha){me.end(),O(!0);return}if(L.type==="error"){me.failWithServerError(L);return}if(L.type==="drop-complete"){A.current.resolveDrop(L.id,L.path);return}if(L.type==="drop-error"){A.current.rejectDrop(L.id,L.message);return}if(L.type==="session-id"){if(typeof L.sessionId=="string"&&((X=(M=g.current)==null?void 0:M.onSessionId)==null||X.call(M,L.sessionId)),L.sessionId&&(ne.current=L.sessionId,J.current="resume"),L.reattached===!0){pe.current=!0,W.current.onReattached(),(ke=(ie=g.current)==null?void 0:ie.onReattached)==null||ke.call(ie,!!Q.current);const $e=Q.current,$t=ae.current;$e&&$t&&!De.current&&(De.current=!0,qa($t,Y.current));return}if(!pe.current){pe.current=!0,W.current.setLaunchProgram(typeof L.launchProgram=="string"?L.launchProgram:null),W.current.setLaunchSessionId(typeof L.launchSessionId=="string"?L.launchSessionId:null),W.current.arm();const $e=ae.current;Q.current&&$e&&Bn(Y.current,$e)}return}if(L.type==="agent-idle"||L.type==="claude-idle"||L.type==="agent-blocked"){window.dispatchEvent(new CustomEvent("miniagent-agent-idle",{detail:{chatName:Y.current}}));return}if(L.type==="agent-active"||L.type==="claude-active"){window.dispatchEvent(new CustomEvent("miniagent-agent-active",{detail:{chatName:Y.current}}));return}if(L.type==="agent-banner-ready"){W.current.onBannerReady();return}if(L.type==="launch-rejected"){W.current.onRejected(String(L.command??""));return}if(L.type==="agent-auth-required"){window.dispatchEvent(new CustomEvent("agent-auth-required"));return}if(L.type==="startup-failed"){W.current.onStartupFailed();return}}catch{T.write(E.data),K(),window.dispatchEvent(new CustomEvent("miniagent-output"))}},onClose:()=>{ct(!1),A.current.cancelAllDrops("Not connected")}});he=dt(T,P,H),me.connect(),T.onData(E=>{const M=u.current;(M==null?void 0:M.readyState)===WebSocket.OPEN?M.send(JSON.stringify({type:"input",data:E})):x()});function Le(E){const M=j.current;if(!M)return;const X=E.target;if(X!=null&&X.closest(".xterm-viewport")||M.buffer.active.length<=M.rows)return;const ke=xa(E.deltaY,E.deltaMode);ke!==0&&(M.scrollLines(ke),E.preventDefault(),E.stopPropagation())}P.addEventListener("wheel",Le,{passive:!1});function oe(){var E;Ea(P)||(E=j.current)==null||E.focus()}window.addEventListener("terminal-focus",oe);function Fe(E){const M=E.detail,X=u.current;((M==null?void 0:M.chatName)===Y.current||(M==null?void 0:M.chatName)===Ya)&&typeof M.text=="string"&&(X==null?void 0:X.readyState)===WebSocket.OPEN&&X.send(JSON.stringify({type:"input",data:M.text}))}return window.addEventListener("miniagent-send-input",Fe),()=>{var M,X;N!==void 0&&window.clearTimeout(N),qt(Y.current,null),(M=G.current)==null||M.call(G,null),me.dispose(),ct(!1),window.removeEventListener("terminal-focus",oe),window.removeEventListener("miniagent-send-input",Fe),P.removeEventListener("wheel",Le),cancelAnimationFrame(rt),F(),fe(),nt();const E=u.current;(E==null?void 0:E.readyState)===WebSocket.OPEN&&E.close(),(X=j.current)==null||X.dispose(),w.current=null}},[S,p,x]),Fa(h,()=>{const P=j.current,T=w.current;if(!P||!T||!dt(P,h.current,T))return;const H=u.current;(H==null?void 0:H.readyState)===WebSocket.OPEN&&H.send(JSON.stringify({type:"resize",cols:P.cols,rows:P.rows}))}),s.jsxs("div",{"data-codeyam-hydrated":"MiniAgentChat",className:"mt-2 border border-[var(--border-subtle)] rounded-lg overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[var(--bg-card)]",children:[s.jsx("span",{className:"text-xs font-medium text-[var(--accent-active)]",children:Se(S)}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(or,{}),o&&s.jsx("button",{onClick:o,className:"text-[var(--text-dim)] hover:text-[var(--text-primary)] text-xs bg-transparent border-none cursor-pointer",children:"Close"})]})]}),s.jsx("div",{ref:h,className:"mini-agent-terminal",tabIndex:-1,onPointerDown:Z,onClick:Z,onDragEnter:_.dropHandlers.onDragEnter,onDragOver:_.dropHandlers.onDragOver,onDragLeave:_.dropHandlers.onDragLeave,onDrop:_.dropHandlers.onDrop,style:{height:a,background:"#1a1a1a",padding:"6px 10px",position:"relative",overflow:"hidden",outline:"none"},children:k?s.jsx(bn,{}):s.jsxs(s.Fragment,{children:[s.jsx(qn,{status:m,pulseKey:b,onRefresh:()=>window.location.reload(),onDismissServerStopped:v}),s.jsx(er,{status:se.status,failure:se.failure,onRetry:se.retry}),_.dragActive&&s.jsx(Dn,{}),_.errorToast&&s.jsx(Ln,{message:_.errorToast})]})})]})}const Oc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentChat:ir},Symbol.toStringTag,{value:"Module"}));function Ac(e,t){switch(e){case"connected":return`${t} is connected.`;case"settling":return`Checking your ${t} sign-in…`;case"signed-in-not-stored":return`Your ${t} sign-in worked, but it wasn't saved on this machine.`;case"needs-login":return`You are not signed into ${t} yet.`}}function Mc(e,t){return e==="did-not-persist"?`The folder ${t} keeps its sign-in in was empty after a restart, so signing in again here would be lost the same way. Somewhere that keeps its files between restarts will hold it.`:`${t} reported a successful sign-in, but nothing was saved where it keeps credentials — so the chat still can't use it.`}function Pc(e,t){return e.binaryMismatch?`The chat started a different copy of ${t} than the one you signed in with, so it may ask you to sign in again.`:e.configMissingAtLaunch?`The chat started ${t} before its settings were ready, so it may have shown its own sign-in screen. Reopening the chat should go straight in.`:null}function Rc(e){return e!=="connected"&&e!=="signed-in-not-stored"}function Ic(e){return e==="needs-login"||e==="signed-in-not-stored"}function Qt(e){return e===null?"Couldn't reach the editor to set that up.":e.ok?"Done. Open a new Shell and `claude` there will use this sign-in.":`Couldn't set that up: ${e.error??"unknown error"}`}const ko=500,Co=75e3,No=3e5,To=`
14
+
15
+ --- transcript tail ---
16
+ `,Eo=`
17
+
18
+ --- installer output ---
19
+ `;function cr(e){const t=[{delimiter:To,label:"Login transcript (what claude actually printed)"},{delimiter:Eo,label:"Installer output (what npm printed)"}];for(const{delimiter:n,label:r}of t){const a=e.indexOf(n);if(a!==-1)return{headline:e.slice(0,a),tail:e.slice(a+n.length),tailLabel:r}}return{headline:e}}function lr({onAuthenticated:e}){const[t,n]=c.useState({state:"starting"}),[r,a]=c.useState(""),[o,i]=c.useState(!1),[l,d]=c.useState(!1),[f,g]=c.useState(!1),[h,u]=c.useState(!1),[m,b]=c.useState(!1),x=c.useRef(!1),v=c.useRef(e);v.current=e;const p=c.useCallback(async()=>{try{const _=await fetch("/api/auth/status");if(!_.ok)return;const A=await _.json();n(A),A.state==="authenticated"&&!x.current&&(x.current=!0,v.current())}catch{}},[]),w=c.useCallback(async()=>{x.current=!1,g(!1),u(!1),n({state:"starting"});try{const _=await fetch("/api/auth/start",{method:"POST"});if(_.ok)(await _.json().catch(()=>({}))).installing&&n({state:"installing"});else{const A=await _.json().catch(()=>({}));n({state:"failed",error:A.error??"Could not start the login process."})}}catch{n({state:"failed",error:"Could not start the login process."})}},[]);c.useEffect(()=>{w()},[w]),c.useEffect(()=>{const _=window.setInterval(()=>void p(),ko);return()=>window.clearInterval(_)},[p]);const j=t.state==="installing",y=t.state!=="failed"&&t.state!=="idle"&&t.state!=="authenticated"&&t.state!=="url-ready"&&!j;c.useEffect(()=>{if(!y){g(!1);return}const _=window.setTimeout(()=>g(!0),Co);return()=>window.clearTimeout(_)},[y]),c.useEffect(()=>{if(!j){u(!1);return}const _=window.setTimeout(()=>u(!0),No);return()=>window.clearTimeout(_)},[j]);const S=c.useCallback(async()=>{if(r.trim()){i(!0);try{const _=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:r.trim()})});if(_.ok)a("");else{const A=await _.json().catch(()=>({}));n({state:"failed",error:A.error??"Code not accepted — check the value and try again."})}}catch{n({state:"failed",error:"Could not submit the code."})}finally{i(!1)}}},[r]),k=c.useCallback(async()=>{try{await fetch("/api/auth/cancel",{method:"POST"})}catch{}w()},[w]),O=c.useCallback(async()=>{b(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),e()}catch{}finally{b(!1)}},[e]),D=c.useCallback(()=>{var _;t.url&&((_=navigator.clipboard)==null||_.writeText(t.url),d(!0),window.setTimeout(()=>d(!1),1500))},[t.url]);if(f&&y)return s.jsxs("div",{"data-testid":"claude-oauth-timeout",className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Login link preparation timed out — the backend may be wedged. Try again, recheck if you already authenticated elsewhere, or open a terminal and run ",s.jsx("code",{className:"text-white",children:"claude /login"})," ","directly."]}),s.jsx(be,{onRetry:()=>void k(),onRecheck:()=>void O(),rechecking:m,retryTestId:"claude-oauth-timeout-retry",recheckTestId:"claude-oauth-timeout-recheck"})]});if(j)return s.jsx(Sn,{timedOut:h,onRetry:()=>void k(),onRecheck:()=>void O(),rechecking:m});if(t.state==="failed"){const{headline:_,tail:A,tailLabel:C}=cr(t.error??"Login failed.");return s.jsxs("div",{"data-testid":"claude-oauth-failed",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:_}),A&&s.jsxs("details",{open:!0,"data-testid":"claude-oauth-failed-transcript",children:[s.jsx("summary",{className:"cursor-pointer text-xs text-[#9CA3AF]",children:C}),s.jsx("pre",{className:"mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded bg-[#1A1A1A] p-2 font-mono text-[11px] leading-relaxed text-[#9CA3AF]",children:A})]}),s.jsx(be,{onRetry:()=>void k(),onRecheck:()=>void O(),rechecking:m,retryLabel:"Try again",recheckTestId:"claude-oauth-failed-recheck"})]})}return t.state==="idle"?s.jsxs("div",{"data-testid":"claude-oauth-idle",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:"No login is running — the login process stopped before it could start. Try again, or recheck if you already authenticated elsewhere."}),s.jsx(be,{onRetry:()=>void k(),onRecheck:()=>void O(),rechecking:m,retryTestId:"claude-oauth-idle-retry",recheckTestId:"claude-oauth-idle-recheck"})]}):t.state==="authenticated"?s.jsx("p",{"data-testid":"claude-oauth-authenticated",className:"text-sm text-[#D7FF63]",children:"Connected. Opening Build…"}):t.state==="url-ready"&&!t.url?s.jsxs("div",{"data-testid":"claude-oauth-url-missing",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:"The login process reported that a link was ready but did not send a usable one. Try again, or recheck if you already authenticated elsewhere."}),s.jsx(be,{onRetry:()=>void k(),onRecheck:()=>void O(),rechecking:m,retryTestId:"claude-oauth-url-missing-retry",recheckTestId:"claude-oauth-url-missing-recheck"})]}):t.state==="url-ready"&&t.url?s.jsxs("div",{"data-testid":"claude-oauth-url-ready",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#8E8E8E]",children:"Open this URL in your browser, approve access, then paste the code back here:"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"flex-1 min-w-0 truncate px-2 py-1.5 rounded bg-black text-[#D7FF63] text-xs",children:t.url}),s.jsx("button",{onClick:D,className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:l?"Copied":"Copy"}),s.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:"Open"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:r,onChange:_=>a(_.target.value),placeholder:"Paste the code from the browser here",className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),s.jsx("button",{onClick:()=>void S(),disabled:o||!r.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:o?"Submitting…":"Submit"})]})]}):s.jsx("p",{"data-testid":"claude-oauth-starting",className:"text-sm text-[#8E8E8E]",children:"Preparing the login link…"})}const Dc=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthFlow:lr,splitTranscriptTail:cr},Symbol.toStringTag,{value:"Module"}));function ur({provider:e,onAuthenticated:t,onClose:n}){const r=Se(e);return s.jsx("div",{"data-testid":"provider-auth-modal",className:"fixed inset-0 z-[100] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},onMouseDown:a=>{a.target===a.currentTarget&&n()},children:s.jsxs("div",{className:"w-[32rem] max-w-[90vw] rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-6 space-y-4",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("h2",{className:"text-base font-medium text-white",children:["Connect your ",r," account"]}),s.jsx("button",{onClick:n,"aria-label":"Close",className:"text-[#8E8E8E] hover:text-white cursor-pointer",children:"✕"})]}),e==="claude"?s.jsx(lr,{onAuthenticated:t}):s.jsx(_n,{provider:e,onAuthenticated:t})]})})}const Lc=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthModal:ur},Symbol.toStringTag,{value:"Module"}));function Oo(e){const t=new Date(e).getTime()-Date.now(),n=Math.abs(Math.round(t/36e5));if(n<1)return t<0?"just now":"very soon";if(n<48)return t<0?`${n} h ago`:`in ${n} h`;const r=Math.round(n/24);return t<0?`${r} d ago`:`in ${r} d`}function dr({provider:e,credsPresent:t=!0,reason:n=null,expiresAt:r=null,shellShare:a=null,sessionOngoing:o=!1,onAuthenticated:i,onAuthorized:l}){const[d,f]=c.useState(!1),[g,h]=c.useState(!1),u=Se(e),m=c.useCallback(()=>{f(!1),i(),l==null||l()},[i,l]),b=c.useCallback(async()=>{h(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),i()}catch{}finally{h(!1)}},[i]),[x,v]=c.useState(null),p=c.useCallback(async()=>{try{const _=await(await fetch("/api/auth/share-store-with-shell",{method:"POST"})).json();v(Qt(_))}catch{v(Qt(null))}},[]),w=n==="stale-verdict",j=e==="claude"&&!t,y=r?` (token expired ${Oo(r)})`:"",S=j?`${u} credentials file is missing`:w?`Couldn't confirm your ${u} sign-in`:n==="token-expired"?`Your ${u} token has expired`:n==="api-401"?`${u} authentication rejected (401)`:`Connect your ${u} account`,k=o?" Your Build session stays open — you can finish logging in here or directly in the Build terminal.":"",O=j?"The editor couldn't find ~/.claude/.credentials.json on this machine — likely deleted between editor restarts (operator-side action, a Reconfigure, or a stale image). Re-seed by clicking Authenticate to run OAuth, or — on a fleet VM — copy the file from a donor VM through the dashboard.":w?`The editor couldn't reach ${u} to check, so this is the last answer it had — not a fresh one. If you've already signed in, click Recheck. If not, click Authenticate.${k}`:n==="token-expired"?`Your ${u} token has expired${y} — click Authenticate to refresh it. On a fleet VM the dashboard can copy a fresh token from a donor VM.${k}`:n==="api-401"?`The ${u} server rejected your credentials (401)${y}. This usually means the token was revoked or expired. Click Authenticate to re-connect.${k}`:o?"You can finish logging in here or directly in the Build terminal — your session stays open either way. On a cloud VM the dashboard usually does this for you; locally you connect once here.":`Authentication used to happen inside the Build terminal. Now it lives here, out of your way. Connect ${u} to unlock the Build tab. On a cloud VM the dashboard usually does this for you; locally you connect once here.`;return s.jsxs("div",{"data-testid":"provider-auth-gate","data-auth-variant":j?"creds-missing":w?"stale-verdict":"needs-login","data-auth-card":!0,className:"m-4 rounded-lg border border-[#D7FF63]/40 bg-[#1E1E1E] p-5 space-y-3",children:[s.jsx("h2",{className:"text-base font-medium text-white",children:S}),s.jsx("p",{className:"text-sm text-[#8E8E8E]",children:O}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsx("button",{onClick:()=>f(!0),className:w?"order-2 px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer":"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),s.jsx("button",{onClick:()=>void b(),"data-testid":"provider-auth-gate-recheck",disabled:g,className:w?"order-1 px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50":"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:g?"Rechecking…":w?"Recheck":"Already logged in? Recheck"})]}),e==="claude"&&a==="available"?s.jsxs("div",{className:"space-y-1",children:[s.jsx("button",{onClick:()=>void p(),"data-testid":"provider-auth-share-with-shell",disabled:x!==null,className:"text-sm text-[#D7FF63] underline cursor-pointer disabled:opacity-50",children:"Also use this sign-in in the Shell"}),x?s.jsx("p",{className:"text-xs text-[#8E8E8E]",children:x}):null]}):null,d?s.jsx(ur,{provider:e,onAuthenticated:m,onClose:()=>f(!1)}):null]})}const Fc=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthenticateCta:dr},Symbol.toStringTag,{value:"Module"}));let ft=!1;function fr(e){const{state:t,provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:i,refresh:l}=la(),[d]=c.useState(()=>ft);return c.useEffect(()=>{t==="authenticated"?ft=!0:t==="needs-login"&&(ft=!1)},[t]),t==="needs-login"?s.jsx(dr,{provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:i,onAuthenticated:()=>void l(),onAuthorized:()=>{}}):t==="authenticated"||d?s.jsx(ir,{...e}):s.jsxs("div",{"data-testid":"gated-agent-chat-checking",className:"mt-2 flex items-center gap-3 rounded-lg border border-[var(--border-subtle)] px-3 py-4",children:[s.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[var(--text-dim)] border-t-transparent animate-spin"}),s.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"Checking your account…"})]})}const $c=Object.freeze(Object.defineProperty({__proto__:null,GatedAgentChat:fr},Symbol.toStringTag,{value:"Module"})),pt=4e3;function Zt(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>pt?`${t.slice(0,pt)}
20
+ … (truncated, ${t.length-pt} more chars)`:t}function Ao({slug:e,scenarioName:t,seedTabs:n,mockEntries:r,selectedMock:a,selectedSeedTab:o,selectedSeedRows:i}){const l=[],d=t??e;if(l.push(`# Edit Scenario Data: "${d}"`),l.push(""),l.push(`**Slug**: ${e}`),l.push(`**Scenario file**: .codeyam/scenarios/${e}.json`),l.push(""),l.push("## Scenario overview"),n.length>0){l.push("### Seed & Local tables");for(const f of n){const g=f.category?` (${f.category})`:"";l.push(`- **${f.label}**${g} — dataKey \`${f.dataKey}\``)}l.push("")}if(r.length>0){l.push("### HTTP mocks");const f=new Map;for(const g of r){const h=f.get(g.source)??[];h.push(g),f.set(g.source,h)}for(const[g,h]of f){l.push(`**${g}** (${h.length}):`);for(const u of h)l.push(`- \`${u.method} ${u.pathPattern}\``)}l.push("")}if(a){const f=`${a.method} ${a.pathPattern}`;l.push(`## Currently viewing: mock \`${f}\``),l.push(`- **Source**: ${a.source}`),a.status!==void 0&&l.push(`- **Status**: ${a.status}`);const g=a.headers??{},h=Object.entries(g);if(h.length>0){l.push("- **Headers**:");for(const[u,m]of h)l.push(` - \`${u}: ${m}\``)}a.body!==void 0&&a.body!==null?(l.push("- **Body**:"),l.push("```json"),l.push(Zt(a.body)),l.push("```")):l.push("- **Body**: (empty)"),l.push("")}else if(o){if(l.push(`## Currently viewing: seed table **${o.label}**`),l.push(`- **dataKey**: \`${o.dataKey}\``),o.category&&l.push(`- **Category**: ${o.category}`),o.description&&l.push(`- **Description**: ${o.description}`),o.schemaFields&&o.schemaFields.length>0){l.push("- **Schema**:");for(const f of o.schemaFields){const g=f.isId?" (PK)":"";l.push(` - \`${f.name}\`: ${f.type}${g}`)}}i&&i.length>0?(l.push(`- **Rows** (${i.length}):`),l.push("```json"),l.push(Zt(i)),l.push("```")):l.push("- **Rows**: (none yet)"),l.push("")}return l.push("## Your task"),l.push("The user is looking at the Scenario Data Panel and wants your help adjusting its data. Ask what change they'd like to make."),l.push(""),l.push("Typical edits:"),l.push('- Tweak an HTTP mock body, status, or headers → update `mocks.http["METHOD /path"]` in the scenario JSON'),l.push("- Add or remove seed rows → update the `seed` section"),l.push("- Adjust `localStorage` values → update the `localStorage` section"),l.push(""),l.push("To save changes:"),l.push("1. Write the updated scenario JSON to `.codeyam/tmp/scenario.json`"),l.push("2. Run: `codeyam-editor editor register @.codeyam/tmp/scenario.json`"),l.push("3. The editor will reload automatically and the panel will reflect the new data."),l.join(`
21
+ `)}const Ct=new Set;let ze=null;const Mo=150;function Bc(e){return Ct.add(e),()=>{Ct.delete(e)}}function ye(){ze&&clearTimeout(ze),ze=setTimeout(()=>{ze=null;for(const e of Ct)e()},Mo)}const Nt=new Set;function zc(e){for(const t of Nt)t(e)}function Po(e){return Nt.add(e),()=>{Nt.delete(e)}}function Ro({onSelect:e,onFocus:t}){c.useEffect(()=>Po(({routeKey:n,jsonPath:r})=>{e(n),t(r)}),[e,t])}async function qe(e){try{const t=await e.json();if(t.error)return t.error}catch{}return`Request failed (${e.status})`}async function Io(e,t=null){const n=t!=null?`?since_ms=${encodeURIComponent(t)}`:"",a=await(await fetch(`/api/mock-panel/${encodeURIComponent(e)}${n}`)).json();if("error"in a)throw new Error(a.error);return a}async function en(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t.routeKey)}`,r=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t.status,body:t.body,headers:t.headers})});if(!r.ok)throw new Error(await qe(r))}async function Do(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}`,r=await fetch(n,{method:"DELETE"});if(!r.ok)throw new Error(await qe(r))}async function Lo(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}/passthrough`,r=await fetch(n,{method:"POST"});if(!r.ok)throw new Error(await qe(r))}function le(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function Fo(e){const t=await fetch("/api/mocks/save-scoped",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok||"success"in n&&n.success===!1)throw new Error("error"in n?n.error:`Save failed (${t.status})`);return n}async function $o(e,t,n){const r=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:le(n)}),a=await fetch(`/api/mocks/save-scope-impact?${r.toString()}`);if(!a.ok)throw new Error(await qe(a));return(await a.json()).impactedScenarios??[]}function Bo(){const[e,t]=c.useState(null),[n,r]=c.useState(null),a=c.useRef(null);return c.useEffect(()=>ds(i=>{if(!i.ok){r(i.error);return}const l=i.data,d=JSON.stringify(l);if(d===a.current){r(null);return}a.current=d,t(l),r(null)}),[]),{status:e,error:n,restart:async()=>{try{const i=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})});if(!i.ok)throw new Error(`Failed to restart dev server: ${i.statusText}`);fs()}catch(i){r(i instanceof Error?i.message:String(i))}}}}function zo(e){const[t,n]=c.useState([]),[r,a]=c.useState(null),[o,i]=c.useState(!1),[l,d]=c.useState(null),{events:f}=Zr(),{status:g}=Bo(),h=(g==null?void 0:g.lastIframeLoadedAtMs)??null,u=c.useCallback(async()=>{if(!e){n([]),a(null);return}i(!0),d(null);try{const p=await Io(e,h);n(p.entries),a(p.defaultSlug)}catch(p){d(p instanceof Error?p.message:"Failed to load mocks")}finally{i(!1)}},[e,h]);c.useEffect(()=>{u()},[u]),c.useEffect(()=>{const p=f[f.length-1];!p||p.type!=="http_request"||u()},[f,u]);const m=c.useCallback(async p=>{e&&(await en(e,p),await u())},[e,u]),b=c.useCallback(async p=>{e&&(p.scope.kind==="scenario"?await en(e,{routeKey:p.routeKey,status:p.status,body:p.body,headers:p.headers}):await Fo({scenarioSlug:e,routeKey:p.routeKey,scope:p.scope,status:p.status,body:p.body,headers:p.headers}),await u())},[e,u]),x=c.useCallback(async p=>{e&&(await Do(e,p),await u())},[e,u]),v=c.useCallback(async p=>{e&&(await Lo(e,p),await u())},[e,u]);return{entries:t,defaultSlug:r,loading:o,error:l,refresh:u,upsert:m,upsertScoped:b,remove:x,setPassthrough:v}}function Ko(e){const t={};for(const[n,r]of Object.entries(e))if(typeof r=="string")try{const a=JSON.parse(r);Array.isArray(a)?t[n]=a:typeof a=="object"&&a!==null&&(t[n]=[a])}catch{}else Array.isArray(r)&&(t[n]=r);return t}function Ho(e,t){return e.length===0||t.length===0?!1:e.filter(r=>t.includes(r)).length>=Math.min(e.length,t.length)*.5}function Uo(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function Wo(e,t){return e.length>0?Object.keys(e[0]):t?t.map(n=>n.name):[]}function Yo(e,t,n){const r=new Map((n||[]).map(o=>[o.name,o.type])),a={};for(const o of e)a[o]=r.get(o)||(t.length>0?Uo(t[0][o]):"text");return a}function Vo(e,t){var n;return((n=t==null?void 0:t.find(r=>r.isId))==null?void 0:n.name)||e.find(r=>r==="id")||null}function Xo(e,t){const{_metadata:n,...r}=t,a=r.localStorage&&typeof r.localStorage=="object"&&!Array.isArray(r.localStorage)?Ko(r.localStorage):{},o={};if(r.seed&&typeof r.seed=="object"&&!Array.isArray(r.seed))for(const[u,m]of Object.entries(r.seed))Array.isArray(m)&&(o[u]=m);const i={},l=[],d=new Set,f=new Set,g=new Set;for(const u of e){const m=u.name.charAt(0).toLowerCase()+u.name.slice(1),b=u.fields.map(p=>p.name);let x=null,v=[];for(const p of[u.name,m,`${m}s`])if(p in r&&Array.isArray(r[p])){x=p,v=r[p],f.add(p);break}if(!x){for(const p of[u.name,m,`${m}s`])if(p in o){x=p,v=o[p],g.add(p),p in a&&d.add(p);break}}if(!x){for(const p of[u.name,m,`${m}s`])if(p in a){x=m,v=a[p],d.add(p);break}}if(!x){for(const[p,w]of Object.entries(a))if(!d.has(p)&&w.length>0&&Ho(b,Object.keys(w[0]))){x=m,v=w,d.add(p);break}}x||(x=m),i[x]=v,l.push({label:u.name,dataKey:x,category:u.category,description:u.description,schemaFields:u.fields.map(p=>({name:p.name,type:p.type,isId:p.isId??!1}))})}const h=new Set(["name","id","url","dimensions","componentName","scenarioType","pageFilePath","routeName","description","props","env"]);for(const[u,m]of Object.entries(r))u==="_metadata"||u==="localStorage"||u==="seed"||u==="type"||u==="mocks"||h.has(u)||f.has(u)||Jo(m)&&(i[u]=m,l.push({label:u,dataKey:u}));for(const[u,m]of Object.entries(o))g.has(u)||(i[u]=m,l.push({label:u,dataKey:u}));for(const[u,m]of Object.entries(a))d.has(u)||(i[u]=m,l.push({label:u,dataKey:u}));return{data:i,tabs:l}}function tn(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function Jo(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function Go(e){if(typeof e!="object"||e===null||!("props"in e))return null;const t=e.props;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function qo(e){if(typeof e!="object"||e===null||!("browserState"in e))return null;const t=e.browserState;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Qo(e,t){const n=new Set;for(const r of t){const a=e[r.dataKey];Array.isArray(a)&&a.length>0&&n.add(r.dataKey)}return n}function Zo(e){if(typeof e=="object"&&e!==null&&"shares"in e){const t=e.shares;if(Array.isArray(t))return t.filter(n=>typeof n=="string")}return[]}function ei(e){const[t,n]=c.useState({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!0,error:null});return c.useEffect(()=>{n(r=>({...r,loading:!0,error:null})),Promise.all([fetch("/api/data-structure").then(r=>r.json()).catch(()=>[]),fetch(`/api/scenarios/${encodeURIComponent(e)}`).then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()})]).then(([r,a])=>{const o=Xo(Array.isArray(r)?r:[],a);n({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:Qo(o.data,o.tabs),shares:Zo(a),props:Go(a),browserState:qo(a),loading:!1,error:null})}).catch(r=>n({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!1,error:r instanceof Error?r.message:"Failed to load"}))},[e]),t}function Dt(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function ti(e){const t=await fetch(Dt(e,"/status"));if(!t.ok)return{isDirty:!1,diffSummary:null};const n=await t.json();return{isDirty:!!n.isDirty,diffSummary:n.diffSummary??null}}async function ni(e){const t=await fetch(Dt(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function ri(e){const t=await fetch(Dt(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function si({slug:e,onPreviewReload:t}){const[n,r]=c.useState(!1),[a,o]=c.useState(null),[i,l]=c.useState(!1),[d,f]=c.useState(!1),[g,h]=c.useState(null),u=c.useRef(null),m=c.useCallback(async()=>{if(!e){r(!1),o(null);return}try{const w=await ti(e);r(w.isDirty),o(w.diffSummary)}catch{}},[e]);c.useEffect(()=>{m()},[m]),c.useEffect(()=>{if(!n)return;const w=j=>{j.preventDefault(),j.returnValue=""};return window.addEventListener("beforeunload",w),()=>window.removeEventListener("beforeunload",w)},[n]);const b=c.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{m()},100)},[m]),x=c.useCallback(async()=>{if(e){l(!0),h(null);try{await ni(e),r(!1),o(null),t&&t()}catch(w){h(w instanceof Error?w.message:"Save failed")}finally{l(!1)}}},[e,t]),v=c.useCallback(async()=>{if(e){f(!0),h(null);try{await ri(e),r(!1),o(null),t&&t()}catch(w){h(w instanceof Error?w.message:"Cancel failed")}finally{f(!1)}}},[e,t]),p=c.useCallback(w=>n?window.confirm(w):!0,[n]);return{isDirty:n,saving:i,cancelling:d,error:g,diffSummary:a,save:x,cancel:v,markDirty:b,confirmIfDirty:p}}const ai={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},oi={scenario:null,shared:null,default:null,"catalog-only":"Observed during live traffic but not mocked yet. Promote it to a scenario mock to capture and edit the response.",passthrough:null};function pr(e){return ai[e]??e}function ii(e){return oi[e]??null}function ue(e){return`${e.method} ${e.pathPattern}`}const ci={scenario:"bg-emerald-500/15 text-emerald-300 border-emerald-500/40",shared:"bg-violet-500/15 text-violet-300 border-violet-500/40",default:"bg-[#D7FF63]/15 text-[#D7FF63] border-[#D7FF63]/40","catalog-only":"bg-slate-500/15 text-slate-300 border-slate-500/40",passthrough:"bg-zinc-500/15 text-zinc-300 border-zinc-500/40"};function Lt({source:e}){const t=ii(e);return s.jsx("span",{className:`px-1.5 py-0.5 rounded border ${ci[e]}`,title:t??`source: ${e}`,children:pr(e)})}const Kc=Object.freeze(Object.defineProperty({__proto__:null,MockSourceBadge:Lt},Symbol.toStringTag,{value:"Module"}));function hr({label:e,scenarioCount:t,inheritedCount:n,expanded:r,onToggle:a}){const o=n===0;return s.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)]",children:[s.jsx("div",{className:"mb-0.5",children:e}),s.jsxs("div",{className:"flex items-center gap-1 normal-case tracking-normal font-normal",children:[s.jsxs("span",{children:[t," scenario-specific"]}),s.jsx("span",{"aria-hidden":!0,children:"·"}),s.jsxs("button",{type:"button",onClick:a,disabled:o,"aria-expanded":r,className:`inline-flex items-center gap-0.5 ${o?"cursor-default text-[var(--text-dim)]":"cursor-pointer hover:text-[var(--text-primary)]"}`,children:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px]",children:o?"":r?"▾":"▸"}),s.jsxs("span",{children:[n," inherited from default"]})]})]})]})}const Hc=Object.freeze(Object.defineProperty({__proto__:null,SidebarGroupOverrideHeader:hr},Symbol.toStringTag,{value:"Module"}));function mr({children:e}){return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mx-3 my-1 border-t border-[var(--border-subtle)]"}),s.jsx("div",{className:"px-3 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)]",children:"Inherited from default"}),e]})}const Uc=Object.freeze(Object.defineProperty({__proto__:null,SidebarInheritedSection:mr},Symbol.toStringTag,{value:"Module"}));function br({slug:e}){return s.jsx("span",{className:"px-1 py-0.5 rounded border text-[9px] font-mono bg-violet-500/10 text-violet-300 border-violet-500/30",title:`from shared-data set: ${e}`,children:e})}const Wc=Object.freeze(Object.defineProperty({__proto__:null,MockSharedSlugBadge:br},Symbol.toStringTag,{value:"Module"})),li={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function gr({entry:e,routeKey:t,active:n,onSelect:r}){const a=li[e.method]??"text-[var(--text-muted)]";return s.jsxs("button",{onClick:r,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${n?"bg-[var(--accent-blue)]/10 border-[var(--accent-blue)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,title:t,children:[s.jsx("span",{className:`font-mono text-[9px] font-semibold ${a}`,children:e.method}),s.jsx("span",{className:"truncate flex-1 font-mono",children:e.pathPattern}),e.source==="shared"&&e.sharedSlug&&s.jsx(br,{slug:e.sharedSlug})]})}const Yc=Object.freeze(Object.defineProperty({__proto__:null,SidebarMockEntryRow:gr},Symbol.toStringTag,{value:"Module"})),ui=["scenario","shared","default","catalog-only","passthrough"];function xr({seedTabs:e,mockEntries:t,selection:n,onSelect:r,overrides:a}){const o=new Map;for(const i of t){const l=o.get(i.source)??[];l.push(i),o.set(i.source,l)}return s.jsxs("nav",{className:"w-56 shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-deep)] overflow-y-auto",children:[s.jsxs(Ue,{label:"Browser Environment",count:4,emptyHint:"",children:[s.jsx(Oe,{label:"Cookies",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="cookies",onSelect:()=>r({kind:"browser",tab:"cookies"})}),s.jsx(Oe,{label:"Local Storage",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="localStorage",onSelect:()=>r({kind:"browser",tab:"localStorage"})}),s.jsx(Oe,{label:"Session Storage",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="sessionStorage",onSelect:()=>r({kind:"browser",tab:"sessionStorage"})}),s.jsx(Oe,{label:"Request Headers",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="headers",onSelect:()=>r({kind:"browser",tab:"headers"})})]}),s.jsx(Ue,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:a?{scenarioCount:a.scenarioSeedCount,inheritedCount:a.inheritedSeedCount,renderInherited:()=>nn({tabs:a.inheritedSeedTabs,selection:n,onSelect:r})}:void 0,children:nn({tabs:e,selection:n,onSelect:r})}),s.jsx(Ue,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:a?{scenarioCount:a.scenarioMockCount,inheritedCount:a.inheritedMockCount,renderInherited:()=>rn({entries:a.inheritedMockEntries,selection:n,onSelect:r})}:void 0,children:rn({entries:t,grouped:o,selection:n,onSelect:r})})]})}function nn({tabs:e,selection:t,onSelect:n}){return e.map(r=>{const a=(t==null?void 0:t.kind)==="seed"&&t.dataKey===r.dataKey;return s.jsxs("button",{onClick:()=>n({kind:"seed",dataKey:r.dataKey}),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${a?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[s.jsx("span",{className:"truncate flex-1",children:r.label}),r.category&&s.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:r.category==="mock-api"?"API":r.category})]},r.dataKey)})}function Oe({label:e,active:t,onSelect:n}){return s.jsxs("button",{onClick:n,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${t?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[s.jsx("span",{className:"truncate flex-1",children:e}),s.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:"ENV"})]})}function rn({entries:e,grouped:t,selection:n,onSelect:r}){const a=t??di(e);return ui.flatMap(o=>{const i=a.get(o)??[];return i.length===0?[]:[s.jsxs("div",{className:"px-3 pt-2 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)] font-semibold flex items-center gap-1.5",children:[pr(o),s.jsx(Lt,{source:o})]},`hdr-${o}`),...i.map(l=>{const d=ue(l),f=(n==null?void 0:n.kind)==="mock"&&n.routeKey===d;return s.jsx(gr,{entry:l,routeKey:d,active:f,onSelect:()=>r({kind:"mock",routeKey:d})},d)})]})}function di(e){const t=new Map;for(const n of e){const r=t.get(n.source)??[];r.push(n),t.set(n.source,r)}return t}function Ue({label:e,count:t,emptyHint:n,children:r,override:a}){const[o,i]=c.useState(!1);if(a){const{scenarioCount:l,inheritedCount:d,renderInherited:f}=a,g=l+(o?d:0);return s.jsxs("section",{className:"py-2",children:[s.jsx(hr,{label:e,scenarioCount:l,inheritedCount:d,expanded:o,onToggle:()=>i(h=>!h)}),g===0?s.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:n}):s.jsxs("div",{children:[r,o&&d>0&&s.jsx(mr,{children:f()})]})]})}return s.jsxs("section",{className:"py-2",children:[s.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)] flex items-center justify-between",children:[s.jsx("span",{children:e}),s.jsx("span",{children:t})]}),t===0?s.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:n}):s.jsx("div",{children:r})]})}const Vc=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateButton:Oe,ScenarioDataPanelSidebar:xr,SidebarGroup:Ue,routeKeyFor:ue},Symbol.toStringTag,{value:"Module"}));function fi({seedTabs:e,mockEntries:t,initialSection:n,selection:r,setSelection:a}){c.useEffect(()=>{if(r)return;const o=n==="mocks",i=n==="seed";if(o&&t.length>0){a({kind:"mock",routeKey:ue(t[0])});return}if(i&&e.length>0){a({kind:"seed",dataKey:e[0].dataKey});return}e.length>0?a({kind:"seed",dataKey:e[0].dataKey}):t.length>0&&a({kind:"mock",routeKey:ue(t[0])})},[n,t,e,r,a])}function yr(){return s.jsx("div",{className:"flex h-full items-center justify-center p-6",children:s.jsxs("div",{className:"max-w-xs text-center space-y-2",children:[s.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No scenario data yet."}),s.jsx("p",{className:"text-xs text-[var(--text-dim)]",children:"Seed data and HTTP mocks will appear here as the scenario captures them, or add them with the scenario editor."})]})})}const Xc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEmptyState:yr},Symbol.toStringTag,{value:"Module"}));function vr({variant:e,onClose:t}){return e!=="slideOver"?null:s.jsx("button",{onClick:t,className:"rounded border border-[var(--border-default)] bg-transparent px-2 py-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Close"})}const Jc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelCloseButton:vr},Symbol.toStringTag,{value:"Module"}));function wr({variant:e,providerLabel:t,chatOpen:n,onToggleChat:r}){const a=e==="inline",o=a?"flex items-center gap-1.5 px-3 py-1.5 rounded border text-xs font-medium cursor-pointer transition-colors":"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors",i=n?"border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":a?"border-[var(--accent-active)] bg-[var(--accent-active)] text-black hover:bg-[var(--accent-active)]/90":"border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40";return s.jsxs("button",{type:"button",onClick:r,className:`${o} ${i}`,title:`Open a chat with ${t} seeded with this scenario's context`,children:[s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),"Edit with ",t]})}const Gc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEditChatButton:wr},Symbol.toStringTag,{value:"Module"})),Tt=new Set,Et=new Set;let _r={isActive:!1,previewSlug:null};function pi(){for(const e of Tt)e()}function qc(e){return Tt.add(e),()=>{Tt.delete(e)}}function Qc(e){_r=e;for(const t of Et)t(e)}function hi(e){return Et.add(e),()=>{Et.delete(e)}}function sn(){return _r}function mi(){const[e,t]=c.useState(()=>sn());return c.useEffect(()=>(t(sn()),hi(t)),[]),e}function Sr({panelSlug:e,scenarioState:t}){const n=mi(),{isActive:r,previewSlug:a}=t??n;return a!==e?null:s.jsxs("button",{type:"button","aria-pressed":r,onClick:()=>pi(),title:r?"Exit inspect data source":"Inspect data source — click a value in the live preview to see its mock",className:r?"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40",children:[s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),r?"Inspecting…":"Inspect data"]})}const Zc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelInspectButton:Sr},Symbol.toStringTag,{value:"Module"}));function jr({variant:e,slug:t}){const n=()=>window.open(ns(t),"_blank");return e==="slideOver"?s.jsx("button",{type:"button",onClick:n,className:"p-1.5 rounded text-[var(--text-dim)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-card)] transition-colors cursor-pointer",title:"Open in new window",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),s.jsx("polyline",{points:"15 3 21 3 21 9"}),s.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}):e==="inline"?s.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-[var(--border-default)] bg-transparent text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40 transition-colors cursor-pointer",title:"Open the full data editor in a new browser tab",children:[s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),s.jsx("polyline",{points:"15 3 21 3 21 9"}),s.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),"Open in new tab"]}):null}const el=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelOpenInNewButton:jr},Symbol.toStringTag,{value:"Module"}));function kr(e){if(!e)return"Unsaved changes";const t=[];e.mocks.length>0&&t.push(`${e.mocks.length} mock${e.mocks.length===1?"":"s"}`);const n=e.seed.length;return n>0&&t.push(`${n} seed ${n===1?"table":"tables"}`),t.length>0?`Unsaved changes (${t.join(", ")})`:"Unsaved changes"}function Cr({diff:e,saving:t,cancelling:n,error:r,onSave:a,onCancel:o}){return s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded border border-amber-500/40 bg-amber-500/10 px-2 py-1.5","data-testid":"scenario-draft-bar",children:[s.jsx("span",{className:"text-xs text-amber-300 font-medium",children:kr(e)}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(Pe,{text:r,className:"text-xs text-red-400"}),s.jsx("button",{type:"button",onClick:o,disabled:n||t,className:"px-2 py-0.5 text-xs rounded border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--text-primary)] hover:bg-[var(--bg-input)] disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:n?"Discarding…":"Cancel"}),s.jsx("button",{type:"button",onClick:a,disabled:n||t,className:"px-3 py-0.5 text-xs rounded border border-[var(--accent-blue)] bg-[var(--accent-blue)]/20 text-[var(--accent-blue)] hover:bg-[var(--accent-blue)]/30 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:t?"Saving…":"Save"})]})]})}const tl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDraftBar:Cr,summarizeDraftDiff:kr},Symbol.toStringTag,{value:"Module"}));function Nr({title:e,slug:t,provider:n,chatOpen:r,onToggleChat:a,variant:o,onClose:i,draftDirty:l,draftDiff:d,draftSaving:f,draftCancelling:g,draftError:h,onSave:u,onCancel:m}){const b=Se(n),x=!!l&&!!u&&!!m;return s.jsxs("header",{className:"flex flex-col gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"min-w-0",children:s.jsxs("h2",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:["Scenario data: ",e]})}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(wr,{variant:o,providerLabel:b,chatOpen:r,onToggleChat:a}),s.jsx(Sr,{panelSlug:t}),s.jsx(jr,{variant:o,slug:t}),i&&s.jsx(vr,{variant:o,onClose:i})]})]}),x&&u&&m&&s.jsx(Cr,{diff:d??null,saving:f??!1,cancelling:g??!1,error:h??null,onSave:u,onCancel:m})]})}const nl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelHeader:Nr},Symbol.toStringTag,{value:"Module"}));function bi(e,t){const[n,r]=c.useState(e.status??200),[a,o]=c.useState(e.body??null),[i,l]=c.useState(()=>Object.entries(e.headers??{}).map(([h,u])=>({name:h,value:u})));c.useEffect(()=>{r(e.status??200),o(e.body??null),l(Object.entries(e.headers??{}).map(([h,u])=>({name:h,value:u})))},[t,e.status,e.body,e.headers]);const d=c.useMemo(()=>e.headers??{},[e.headers]),f=c.useMemo(()=>{if((e.status??200)!==n||JSON.stringify(e.body??null)!==JSON.stringify(a))return!0;const h={};for(const x of i)x.name.trim()&&(h[x.name.trim()]=x.value);const u=d,m=Object.keys(u),b=Object.keys(h);if(m.length!==b.length)return!0;for(const x of b)if(u[x]!==h[x])return!0;return!1},[n,a,i,e.status,e.body,d]);return{status:n,setStatus:r,body:a,setBody:o,headers:i,setHeaders:l,isDirty:f,buildPayload:()=>{const h={};for(const u of i)u.name.trim()&&(h[u.name.trim()]=u.value);return{status:n,body:a,headers:h}}}}function Tr({body:e,onBodyChange:t}){const{copied:n,copy:r}=Qr();async function a(){try{const i=await navigator.clipboard.readText(),l=JSON.parse(i);t(l)}catch{}}function o(){r(JSON.stringify(e,null,2))}return s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void a(),className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Paste"}),s.jsx("button",{type:"button",onClick:o,className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:n?"Copied":"Copy"})]})}const rl=Object.freeze(Object.defineProperty({__proto__:null,JsonBodyActions:Tr},Symbol.toStringTag,{value:"Module"}));function Ie(e){return JSON.stringify(e)}function Er(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function gi(e){const t=new Set;function n(r,a){if(r!==null&&typeof r=="object")if(t.add(Ie(a)),Array.isArray(r))r.forEach((o,i)=>n(o,[...a,i]));else for(const[o,i]of Object.entries(r))n(i,[...a,o])}return n(e,[]),t}function xi(e){return e===null?"text-slate-400 italic":typeof e=="string"?"text-emerald-300":typeof e=="number"?"text-amber-300":typeof e=="boolean"?"text-[#D7FF63]":"text-[var(--text-primary)]"}function yi(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function vi(e){return e===null?"null":typeof e=="string"?e:String(e)}function wi(e){const t=e.trim();if(t==="")return"";if(t==="null")return null;if(t==="true")return!0;if(t==="false")return!1;try{return JSON.parse(t)}catch{return e}}function Qe(e){return JSON.parse(JSON.stringify(e))}function _i(e,t,n){if(t.length===0)return n;const r=Qe(e);let a=r;for(let o=0;o<t.length-1;o++)a=a[t[o]];return a[t[t.length-1]]=n,r}function Ft(e,t){if(t.length===0)return e;const n=Qe(e);let r=n;for(let o=0;o<t.length-1;o++)r=r[t[o]];const a=t[t.length-1];return Array.isArray(r)?r.splice(a,1):delete r[a],n}function Si(e,t){const n=Qe(e);let r=n;for(const a of t)r=r[a];return Array.isArray(r)&&r.push(null),n}function ji(e,t,n){const r=Qe(e);let a=r;for(const o of t)a=a[o];return a&&typeof a=="object"&&!Array.isArray(a)&&(a[n]=""),r}function ki(e){if(typeof e!="string"||e.length===0||e!=="$"&&!e.startsWith("$.")&&!e.startsWith("$["))return null;const t=[];let n=e[0]==="$"?1:0;for(;n<e.length;){const r=e[n];if(r==="."){n+=1;const a=n;for(;n<e.length&&e[n]!=="."&&e[n]!=="[";)n+=1;const o=e.slice(a,n);if(o.length===0)return null;t.push(o)}else if(r==="["){const a=e.indexOf("]",n);if(a===-1)return null;const o=e.slice(n+1,a);if(o.length===0)return null;const i=Number(o);if(!Number.isInteger(i)||i<0)return null;t.push(i),n=a+1}else return null}return t}function Ci(e,t){c.useEffect(()=>{if(!e)return;const n=ki(e);n&&t(r=>{const a=new Set(r);for(let o=0;o<n.length;o++)a.add(Ie(n.slice(0,o)));return a})},[e,t])}function Ze({collapsible:e,isOpen:t,onToggle:n,parentKey:r,readOnly:a,onRemove:o,children:i}){return s.jsxs("div",{className:"group/row flex items-center gap-1 min-h-[1.5em] hover:bg-[var(--bg-card)]/30 rounded px-1",children:[e?s.jsx("button",{type:"button",onClick:n,className:"w-4 h-4 flex items-center justify-center text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer p-0","aria-label":t?"Collapse":"Expand",children:s.jsx("span",{className:"text-[10px]",children:t?"▾":"▸"})}):s.jsx("span",{className:"w-4"}),r!==null&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-cyan-300",children:typeof r=="number"?`[${r}]`:r}),s.jsx("span",{className:"text-[var(--text-dim)]",children:":"})]}),s.jsx("div",{className:"flex-1 min-w-0 flex items-center gap-1",children:i}),!a&&o&&s.jsx("button",{type:"button",onClick:o,className:"opacity-0 group-hover/row:opacity-100 text-[10px] text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer px-1",title:"Remove",children:"×"})]})}const sl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNodeLine:Ze},Symbol.toStringTag,{value:"Module"}));function Or(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:i}=e,l=Ie(n),d=Er(a,l),f=t.length>0;return s.jsxs("div",{children:[s.jsxs(Ze,{collapsible:f,isOpen:d,onToggle:()=>o(l),parentKey:r,readOnly:i,onRemove:n.length>0?()=>e.onValueChange(Ft(e.rootValue,n)):null,children:[s.jsx("span",{className:"text-[var(--text-dim)]",children:"["}),!d&&s.jsxs(s.Fragment,{children:[f&&s.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",t.length," item",t.length===1?"":"s"," "]}),s.jsx("span",{className:"text-[var(--text-dim)]",children:"]"})]})]}),d&&s.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[t.map((g,h)=>c.createElement(et,{...e,key:h,value:g,path:[...n,h],parentKey:h,isLast:h===t.length-1})),!i&&s.jsx("button",{type:"button",onClick:()=>e.onValueChange(Si(e.rootValue,n)),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add item"})]}),d&&s.jsx("div",{className:"text-[var(--text-dim)]",children:"]"})]})}const al=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeArrayNode:Or},Symbol.toStringTag,{value:"Module"}));function Ar({onSave:e,onCancel:t}){const[n,r]=c.useState("");return s.jsxs("div",{className:"flex items-center gap-1 py-0.5",children:[s.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"+ key:"}),s.jsx("input",{autoFocus:!0,value:n,onChange:a=>r(a.target.value),onBlur:()=>e(n),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),e(n)):a.key==="Escape"&&(a.preventDefault(),t())},placeholder:"keyName",className:"rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)] min-w-[6rem]"})]})}const ol=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeAddKeyInput:Ar},Symbol.toStringTag,{value:"Module"}));function Mr(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:i,addingKeyAtPath:l,onStartAddKey:d,onStopAddKey:f}=e,g=Ie(n),h=Er(a,g),u=Object.entries(t),m=u.length>0,b=l===g;return s.jsxs("div",{children:[s.jsxs(Ze,{collapsible:m,isOpen:h,onToggle:()=>o(g),parentKey:r,readOnly:i,onRemove:n.length>0?()=>e.onValueChange(Ft(e.rootValue,n)):null,children:[s.jsx("span",{className:"text-[var(--text-dim)]",children:"{"}),!h&&s.jsxs(s.Fragment,{children:[m&&s.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",u.length," key",u.length===1?"":"s"," "]}),s.jsx("span",{className:"text-[var(--text-dim)]",children:"}"})]})]}),h&&s.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[u.map(([x,v],p)=>c.createElement(et,{...e,key:x,value:v,path:[...n,x],parentKey:x,isLast:p===u.length-1})),!i&&!b&&s.jsx("button",{type:"button",onClick:()=>d(g),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add key"}),!i&&b&&s.jsx(Ar,{onSave:x=>{x.trim()&&e.onValueChange(ji(e.rootValue,n,x.trim())),f()},onCancel:f})]}),h&&s.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}const il=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeObjectNode:Mr},Symbol.toStringTag,{value:"Module"}));function Pr({initial:e,onSave:t,onCancel:n}){const[r,a]=c.useState(e);return s.jsx("input",{autoFocus:!0,value:r,onChange:o=>a(o.target.value),onBlur:()=>t(r),onKeyDown:o=>{o.key==="Enter"?(o.preventDefault(),t(r)):o.key==="Escape"&&(o.preventDefault(),n())},className:"flex-1 min-w-[4rem] rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)]"})}const cl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveEditor:Pr},Symbol.toStringTag,{value:"Module"}));function Rr(e){const{value:t,path:n,parentKey:r,readOnly:a,editingPath:o,onStartEdit:i,onStopEdit:l}=e,d=Ie(n),f=o===d;return s.jsx(Ze,{collapsible:!1,isOpen:!1,parentKey:r,readOnly:a,onToggle:()=>{},onRemove:n.length>0?()=>e.onValueChange(Ft(e.rootValue,n)):null,children:f?s.jsx(Pr,{initial:vi(t),onSave:g=>{const h=wi(g);e.onValueChange(_i(e.rootValue,n,h)),l()},onCancel:l}):s.jsx("button",{type:"button",onClick:a?void 0:()=>i(d),disabled:a,className:`${a?"":"hover:bg-[var(--bg-card)] cursor-pointer"} bg-transparent border-none px-1 py-0 rounded ${xi(t)} text-left font-mono`,title:a?void 0:"Click to edit",children:yi(t)})})}const ll=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveNode:Rr},Symbol.toStringTag,{value:"Module"}));function et(e){const{value:t}=e;return Array.isArray(t)?s.jsx(Or,{...e,value:t}):t!==null&&typeof t=="object"?s.jsx(Mr,{...e,value:t}):s.jsx(Rr,{...e})}const ul=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNode:et},Symbol.toStringTag,{value:"Module"}));function tt({value:e,onChange:t,readOnly:n=!1,focusJsonPath:r}){const[a,o]=c.useState(()=>gi(e)),[i,l]=c.useState(null),[d,f]=c.useState(null);Ci(r,o);function g(h){o(u=>{const m=new Set(u);return m.has(h)?m.delete(h):m.add(h),m})}return s.jsx("div",{className:"flex flex-col h-full min-h-0",children:s.jsx("div",{className:"flex-1 min-h-0 overflow-auto font-mono text-xs leading-relaxed text-[var(--text-primary)] bg-[var(--bg-input)] border border-[var(--border-default)] rounded p-3",children:s.jsx(et,{value:e,path:[],parentKey:null,isLast:!0,readOnly:n,expanded:a,editingPath:i,addingKeyAtPath:d,onToggle:g,onStartEdit:l,onStopEdit:()=>l(null),onStartAddKey:f,onStopAddKey:()=>f(null),onValueChange:t,rootValue:e})})})}const dl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeEditor:tt},Symbol.toStringTag,{value:"Module"}));function Ir({headers:e,onChange:t}){function n(o,i){t(e.map((l,d)=>d===o?{...l,...i}:l))}function r(){t([...e,{name:"",value:""}])}function a(o){t(e.filter((i,l)=>l!==o))}return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Headers"}),s.jsx("button",{type:"button",onClick:r,className:"text-xs text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer",children:"+ Add"})]}),e.length===0&&s.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No headers"}),e.map((o,i)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{value:o.name,onChange:l=>n(i,{name:l.target.value}),placeholder:"Name",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),s.jsx("input",{value:o.value,onChange:l=>n(i,{value:l.target.value}),placeholder:"Value",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),s.jsx("button",{type:"button",onClick:()=>a(i),className:"px-2 text-xs text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer",children:"×"})]},i))]})}const fl=Object.freeze(Object.defineProperty({__proto__:null,MockBodyHeadersEditor:Ir},Symbol.toStringTag,{value:"Module"})),ht=5;function Ni(e,t){if(e==="loading")return"Computing impact…";if(e==null)return"";if(t.kind==="scenario")return"Affects only this scenario.";if(e.length===0)return"Affects no other scenarios.";const n=e.length===1?"scenario":"scenarios",r=e.slice(0,ht).join(", "),a=e.length>ht?`, +${e.length-ht} more`:"";return`Affects ${e.length} ${n}: ${r}${a}`}function Ti(e){const t=[{label:"This scenario only",description:"Write to this scenario's mocks file. The row's source flips to scenario.",scope:{kind:"scenario"}}];return e.source==="shared"&&e.sharedSlug&&t.push({label:`Shared data set "${e.sharedSlug}"`,description:"Write to the shared set this row came from. Affects every scenario opted into it.",scope:{kind:"shared",slug:e.sharedSlug}}),(e.source==="default"||e.source==="shared")&&t.push({label:"Defaults",description:"Write to _default.json. Affects every scenario that falls through to defaults for this route.",scope:{kind:"default"}}),t}function Ei(e,t){if(e.source==="default"){const n=t.findIndex(r=>r.scope.kind==="default");if(n>=0)return n}if(e.source==="shared"){const n=t.findIndex(r=>r.scope.kind==="shared"&&r.scope.slug===(e.sharedSlug??""));if(n>=0)return n}return 0}function Oi(e,t,n){const[r,a]=c.useState({}),o=n.map(i=>le(i.scope)).join("|");return c.useEffect(()=>{let i=!1;return(async()=>{const d={};for(const f of n)d[le(f.scope)]="loading";a(d);for(const f of n)try{const g=await $o(e,t,f.scope);if(i)return;a(h=>({...h,[le(f.scope)]:g}))}catch{if(i)return;a(g=>({...g,[le(f.scope)]:[]}))}})(),()=>{i=!0}},[e,t,o]),r}function Dr({choice:e,selected:t,impactLabel:n,onSelect:r}){return s.jsxs("label",{className:`flex cursor-pointer flex-col rounded border p-3 text-xs transition-colors ${t?"border-violet-500 bg-violet-500/10":"border-[var(--border-subtle)] hover:bg-[var(--bg-elevated)]"}`,children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"radio",name:"save-scope",checked:t,onChange:r}),s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:e.label})]}),s.jsx("span",{className:"mt-1 pl-6 text-[var(--text-muted)]",children:e.description}),s.jsx("span",{className:"mt-1 pl-6 text-[var(--text-dim)] italic",children:n})]})}const pl=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeChoiceRow:Dr},Symbol.toStringTag,{value:"Module"}));function Lr({entry:e,scenarioSlug:t,routeKey:n,onCancel:r,onConfirm:a}){const o=Ti(e),[i,l]=c.useState(()=>Ei(e,o)),d=Oi(t,n,o),[f,g]=c.useState(!1),[h,u]=c.useState(null),m=async()=>{const b=o[i];if(b){g(!0),u(null);try{await a(b.scope)}catch(x){u(x instanceof Error?x.message:"Save failed")}finally{g(!1)}}};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"save-scope-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onMouseDown:b=>{b.target===b.currentTarget&&r()},children:s.jsxs("div",{className:"w-[28rem] max-w-[90vw] rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-xl",children:[s.jsx("h2",{id:"save-scope-modal-title",className:"text-sm font-semibold text-[var(--text-primary)]",children:"Where should this save land?"}),s.jsx("p",{className:"mt-1 text-xs text-[var(--text-muted)]",children:n}),s.jsx("div",{className:"mt-4 space-y-2",children:o.map((b,x)=>s.jsx(Dr,{choice:b,selected:i===x,impactLabel:Ni(d[le(b.scope)],b.scope),onSelect:()=>l(x)},le(b.scope)))}),h&&s.jsx(Pe,{text:h,className:"text-xs text-red-400",rowClassName:"mt-3"}),s.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:r,disabled:f,className:"rounded border border-[var(--border-default)] px-3 py-1.5 text-xs text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] disabled:opacity-50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void m(),disabled:f,className:"rounded bg-violet-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:f?"Saving…":"Save"})]})]})})}const hl=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeModal:Lr},Symbol.toStringTag,{value:"Module"}));function Fr({entry:e,routeKey:t,scenarioSlug:n,onSave:r,focusJsonPath:a}){const o=bi(e,t),[i,l]=c.useState(null),[d,f]=c.useState(!1),[g,h]=c.useState(!1);c.useEffect(()=>{l(null),h(!1)},[t]);const u=async b=>{f(!0),l(null);try{const x=o.buildPayload();await r({routeKey:t,...x,scope:b})}catch(x){throw l(x instanceof Error?x.message:"Save failed"),x}finally{f(!1)}},m=async()=>{if(o.isDirty){if(e.source==="scenario"){try{await u({kind:"scenario"})}catch{}return}h(!0)}};return s.jsxs("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[i&&s.jsx(Pe,{text:i,className:"text-xs text-red-400"}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Status"}),s.jsx("input",{type:"number",value:o.status,onChange:b=>o.setStatus(Number(b.target.value)),className:"w-20 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),s.jsx("div",{className:"flex-1"}),s.jsx("button",{type:"button",onClick:()=>void m(),disabled:!o.isDirty||d,className:"rounded bg-violet-500 px-3 py-1 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:d?"Saving…":o.isDirty?"Save changes":"Saved"})]}),s.jsx(Ir,{headers:o.headers,onChange:o.setHeaders}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Body"}),s.jsx(Tr,{body:o.body,onBodyChange:o.setBody})]}),s.jsx(tt,{value:o.body,onChange:o.setBody,focusJsonPath:a},t)]}),g&&s.jsx(Lr,{entry:e,scenarioSlug:n,routeKey:t,onCancel:()=>h(!1),onConfirm:async b=>{await u(b),h(!1)}})]})}const ml=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockEditable:Fr},Symbol.toStringTag,{value:"Module"}));function Ai(e,t){if(e==null)return"never";const n=Math.max(0,Math.floor((t-e)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}const an={GET:"text-emerald-400 border-emerald-400/40",POST:"text-[#D7FF63] border-[#D7FF63]/40",PUT:"text-amber-400 border-amber-400/40",PATCH:"text-purple-400 border-purple-400/40",DELETE:"text-red-400 border-red-400/40"};function Mi(e){return an[e]??an.GET}function $r({entry:e,scenarioHasDefaultFallback:t,onSave:n,onRemove:r,onPassthrough:a}){const o=`${e.method} ${e.pathPattern}`,i=Mi(e.method),l=e.status??e.lastObservedStatus,d=c.useMemo(()=>e.lastObservedMs?Ai(e.lastObservedMs,Date.now()):null,[e.lastObservedMs]),f="px-3 py-1 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer text-xs";return s.jsxs("header",{className:"border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3 space-y-2 flex-shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`px-2 py-0.5 rounded border font-mono text-xs ${i}`,children:e.method}),s.jsx("span",{className:"font-mono text-sm text-[var(--text-primary)] break-all",children:e.pathPattern}),s.jsx(Lt,{source:e.source}),l!==void 0&&s.jsx("span",{className:"px-1.5 py-0.5 rounded border border-[var(--border-default)] text-[var(--text-muted)] font-mono text-xs",children:l}),e.observedCount>0&&s.jsxs("span",{className:"ml-auto text-xs text-[var(--text-dim)]",children:[e.observedCount,"× ",d?`· ${d}`:""]})]}),e.variants.length>1&&s.jsxs("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:["variants: ",e.variants.filter(g=>g!==o).join(", ")]}),s.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.source==="scenario"&&t&&s.jsx("button",{onClick:()=>void r(o),className:f,title:"Remove this scenario mock and fall back to the default",children:"Revert to default"}),e.source==="scenario"&&s.jsx("button",{onClick:()=>void a(o),className:f,children:"Mark passthrough"}),e.source==="default"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void n({routeKey:o,status:e.status??200,body:e.body,headers:e.headers??{},scope:{kind:"scenario"}}),className:"px-3 py-1 rounded border border-emerald-500/50 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20 cursor-pointer text-xs",title:"Copy default body into this scenario",children:"Promote to scenario"}),s.jsx("button",{onClick:()=>void a(o),className:f,children:"Mark passthrough"})]}),e.source==="passthrough"&&s.jsx("button",{onClick:()=>void r(o),className:f,children:"Undo passthrough"})]})]})}const bl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockHeader:$r},Symbol.toStringTag,{value:"Module"}));function Br({entry:e}){const t=Object.entries(e.headers??{}),n=e.body!==void 0&&e.body!==null;return!n&&t.length===0?s.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:e.source==="catalog-only"?"No mock body yet — this endpoint has only been observed, not mocked. Promote it to a scenario to start editing.":e.source==="passthrough"?"This endpoint passes through to the upstream service.":"No body configured."}):s.jsxs("div",{className:"space-y-3 h-full min-h-0 flex flex-col",children:[t.length>0&&s.jsxs("section",{className:"space-y-1 flex-shrink-0",children:[s.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Headers"}),s.jsx("dl",{className:"text-xs font-mono space-y-0.5",children:t.map(([r,a])=>s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("dt",{className:"text-[var(--text-muted)]",children:[r,":"]}),s.jsx("dd",{className:"text-[var(--text-primary)] break-all",children:a})]},r))})]}),n&&s.jsxs("section",{className:"flex-1 min-h-0 flex flex-col",children:[s.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)] pb-1",children:"Body"}),s.jsx(tt,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}const gl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockReadOnly:Br},Symbol.toStringTag,{value:"Module"}));function zr({entry:e,scenarioSlug:t,scenarioHasDefaultFallback:n,onSave:r,onRemove:a,onPassthrough:o,focusJsonPath:i}){const l=`${e.method} ${e.pathPattern}`,d=e.source==="scenario"||e.source==="default"||e.source==="shared";return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx($r,{entry:e,scenarioHasDefaultFallback:n,onSave:r,onRemove:a,onPassthrough:o}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:d?s.jsx(Fr,{entry:e,routeKey:l,scenarioSlug:t,onSave:r,focusJsonPath:i}):s.jsx(Br,{entry:e})})]})}const xl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMock:zr},Symbol.toStringTag,{value:"Module"}));function Pi({slug:e,tab:t,initialRows:n,onCellEdited:r}){const[a,o]=c.useState(n),[i,l]=c.useState(null),[d,f]=c.useState(""),[g,h]=c.useState(""),u=c.useRef(null);c.useEffect(()=>{o(n),l(null)},[t.dataKey,n]);function m(w,j){const y=a[w];l({row:w,col:j});const S=y[j]===null?"":typeof y[j]=="object"?JSON.stringify(y[j]):String(y[j]);f(S),h(S)}function b(w){if(f(w),u.current&&clearTimeout(u.current),!i)return;const j=i;u.current=setTimeout(()=>{p(j.row,j.col,w)},600)}function x(){i&&(u.current&&clearTimeout(u.current),p(i.row,i.col,d),l(null))}function v(){if(u.current&&clearTimeout(u.current),!!i){if(d!==g){const w=[...a];w[i.row]={...w[i.row],[i.col]:tn(g)},o(w),fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:i.row,column:i.col,value:g})}).then(()=>{ye(),r&&r()}).catch(()=>{})}l(null)}}async function p(w,j,y){const S=[...a];S[w]={...S[w],[j]:tn(y)},o(S);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:w,column:j,value:y})}),ye(),r&&r()}catch{}}return{rows:a,editingCell:i,editValue:d,handleEditCell:m,handleEditValueChange:b,handleSave:x,handleCancelEdit:v}}function Kr({tab:e}){return!e.description&&!e.category?null:s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[var(--bg-deep)] border-b border-[var(--border-subtle)]",children:[e.category&&s.jsx("span",{className:`text-[9px] rounded px-1.5 py-0 border ${e.category==="datastore"?"text-[var(--accent-active)]/80 bg-[var(--accent-active)]/10 border-[var(--accent-active)]/30":e.category==="mock-api"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":"text-[var(--text-muted)] bg-[var(--bg-surface)]/30 border-[var(--text-dim)]/30"}`,children:e.category==="mock-api"?"API Mock":e.category}),e.description&&s.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:e.description})]})}const yl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCategoryBadge:Kr},Symbol.toStringTag,{value:"Module"}));function Hr({editingCell:e,editValue:t,onEditValueChange:n,onSave:r,onCancel:a}){return s.jsxs("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-3 py-2",children:[s.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:s.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["Editing"," ",s.jsx("strong",{className:"text-[var(--text-secondary)]",children:e.col})," ","in row ",e.row+1]})}),s.jsx("textarea",{value:t,onChange:o=>n(o.target.value),className:"w-full px-2 py-1.5 text-[11px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:t.length>100?4:2,onKeyDown:o=>{o.key==="Escape"&&a(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&r()}}),s.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[s.jsx("button",{onClick:r,className:"px-3 py-1 text-[10px] font-medium text-[var(--bg-deep)] bg-[var(--accent-active)] rounded cursor-pointer border-none hover:bg-[var(--accent-active)]/80 transition-colors",children:"Save"}),s.jsx("button",{onClick:a,className:"px-3 py-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer",children:"Cancel"}),s.jsxs("span",{className:"text-[9px] text-[var(--text-dim)] ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]})}const vl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCellEditor:Hr},Symbol.toStringTag,{value:"Module"}));function Ur({columns:e,colTypes:t,pkCol:n,rows:r,onEditCell:a}){return e.length===0?s.jsx("div",{className:"px-3 py-4 text-[10px] text-[var(--text-dim)] text-center",children:"No columns defined for this table"}):s.jsx("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:s.jsxs("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-[var(--bg-deep)] sticky top-0 z-10",children:[s.jsx("th",{className:"text-right text-[var(--text-dim)] font-normal px-2 py-1.5 border-b border-[var(--border-default)] w-8",children:"#"}),e.map(o=>s.jsx(Wr,{name:o,type:t[o],isPk:o===n},o))]})}),s.jsx("tbody",{children:r.map((o,i)=>s.jsx(Yr,{row:o,rowIndex:i,columns:e,pkCol:n,onEditCell:a},i))})]})})}function Wr({name:e,type:t,isPk:n}){return s.jsxs("th",{className:"text-left px-2 py-1.5 border-b border-[var(--border-default)] whitespace-nowrap overflow-hidden",children:[n&&s.jsx("span",{className:"inline-block text-[8px] font-bold text-[var(--bg-deep)] bg-[var(--accent-active)] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),s.jsx("span",{className:"text-[var(--text-secondary)] font-medium",children:e}),s.jsx("span",{className:"text-[var(--text-dim)] font-normal ml-1",children:t})]})}function Yr({row:e,rowIndex:t,columns:n,pkCol:r,onEditCell:a}){return s.jsxs("tr",{className:"border-b border-[var(--border-subtle)] hover:bg-[var(--bg-card)] group/row",children:[s.jsx("td",{className:"text-right text-[var(--text-dim)] px-2 py-1.5 w-8 select-none",children:t+1}),n.map(o=>s.jsx(Vr,{value:e[o],isPk:o===r,onEdit:()=>a(t,o)},o))]})}function Vr({value:e,isPk:t,onEdit:n}){return s.jsxs("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${t?"text-[var(--accent-active)] font-medium":"text-[var(--text-secondary)]"}`,title:String(e??""),children:[s.jsx("span",{className:"truncate block whitespace-nowrap",children:e===null?s.jsx("span",{className:"text-[var(--text-dim)] italic",children:"null"}):typeof e=="object"?s.jsx("span",{className:"text-[var(--text-dim)]",children:JSON.stringify(e)}):typeof e=="number"?s.jsx("span",{className:"text-amber-400",children:String(e)}):String(e)}),s.jsx("button",{onClick:r=>{r.stopPropagation(),n()},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-[var(--bg-card)] border border-[var(--border-default)] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:s.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]})}const wl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCell:Vr,DataViewerColumnHeader:Wr,DataViewerRow:Yr,DataViewerTable:Ur},Symbol.toStringTag,{value:"Module"}));function Xr({slug:e,tab:t,initialRows:n,onCellEdited:r}){const{rows:a,editingCell:o,editValue:i,handleEditCell:l,handleEditValueChange:d,handleSave:f,handleCancelEdit:g}=Pi({slug:e,tab:t,initialRows:n,onCellEdited:r}),h=Wo(a,t.schemaFields),u=Yo(h,a,t.schemaFields),m=Vo(h,t.schemaFields);return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Kr,{tab:t}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(Ur,{columns:h,colTypes:u,pkCol:m,rows:a,onEditCell:l})}),o&&s.jsx(Hr,{editingCell:o,editValue:i,onEditValueChange:d,onSave:f,onCancel:g})]})}const _l=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainTable:Xr},Symbol.toStringTag,{value:"Module"}));function Ri({slug:e,browserState:t,tab:n,onCellEdited:r}){const a=c.useMemo(()=>{if(!t)return{};switch(n){case"cookies":return t.cookies??{};case"localStorage":return t.localStorage??{};case"sessionStorage":return t.sessionStorage??{};case"headers":return t.requestHeaders??{};default:return{}}},[t,n]),o=c.useCallback(async d=>{const f=n==="headers"?"browserState.requestHeaders":`browserState.${n}`;try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:f,value:JSON.stringify(d)})}),ye(),r&&r()}catch{}},[e,n,r]),i=c.useMemo(()=>{switch(n){case"cookies":return"Cookies";case"localStorage":return"Local Storage";case"sessionStorage":return"Session Storage";case"headers":return"Request Headers"}},[n]),l=c.useMemo(()=>{switch(n){case"cookies":return"Cookies injected via Set-Cookie headers on the scenario's initial response.";case"localStorage":return"localStorage items set before the app's JavaScript executes.";case"sessionStorage":return"sessionStorage items set before the app's JavaScript executes.";case"headers":return"Custom headers added to every outbound HTTP request from the iframe."}},[n]);return{value:a,handleChange:o,label:i,description:l}}function Jr({slug:e,browserState:t,tab:n,onCellEdited:r}){const{value:a,handleChange:o,label:i,description:l}=Ri({slug:e,browserState:t,tab:n,onCellEdited:r});return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-[var(--border-subtle)]",children:[s.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)]",children:i}),s.jsx("p",{className:"text-xs text-[var(--text-dim)] mt-1",children:l})]}),s.jsx("div",{className:"flex-1 min-h-0 p-4 overflow-auto",children:s.jsx(tt,{value:a,onChange:o})})]})}const Sl=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateTab:Jr},Symbol.toStringTag,{value:"Module"}));function We({label:e,active:t,onClick:n}){return s.jsx("button",{type:"button",onClick:n,className:`px-2 py-0.5 rounded-full border text-[10px] font-mono transition-colors cursor-pointer ${t?"bg-violet-500/25 text-violet-100 border-violet-400/70":"bg-violet-500/10 text-violet-300 border-violet-500/40 hover:bg-violet-500/20"}`,"aria-pressed":t,children:e})}const jl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataBadge:We},Symbol.toStringTag,{value:"Module"}));function Gr({shares:e,activeBadge:t,onSelect:n}){return s.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-2","data-testid":"scenario-mock-data-strip",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-[var(--text-dim)] font-semibold",children:"Mock Data:"}),s.jsx(We,{label:"This Page",active:t.kind==="this-page",onClick:()=>n({kind:"this-page"})}),e.map(r=>s.jsx(We,{label:r,active:t.kind==="share"&&t.slug===r,onClick:()=>n({kind:"share",slug:r})},r)),s.jsx(We,{label:"Defaults",active:t.kind==="defaults",onClick:()=>n({kind:"defaults"})})]})}const kl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataStrip:Gr},Symbol.toStringTag,{value:"Module"}));function Ii({slug:e,scenarioName:t,initialSection:n,onClose:r,variant:a="slideOver"}){const{data:o,tableTabs:i,scenarioOwnedDataKeys:l,shares:d,browserState:f,loading:g,error:h}=ei(e),{entries:u,loading:m,error:b,upsertScoped:x,remove:v,setPassthrough:p}=zo(e),{config:w}=Pn(),j=(w==null?void 0:w.provider)??"claude",y=si({slug:e,onPreviewReload:ye}),S=c.useCallback(()=>{y.markDirty(),ye()},[y]),k=c.useCallback(async F=>{await x(F),S()},[x,S]),O=c.useCallback(async F=>{await v(F),S()},[v,S]),D=c.useCallback(async F=>{await p(F),S()},[p,S]),_=c.useCallback(()=>{y.markDirty(),ye()},[y]),A=c.useCallback(()=>{r&&y.confirmIfDirty("Discard unsaved changes to this scenario?")&&r()},[r,y]),[C,I]=c.useState(null),[R,$]=c.useState(null),[z,B]=c.useState(!1),G=c.useCallback(F=>I({kind:"mock",routeKey:F}),[]);Ro({onSelect:G,onFocus:$});const[ee,Z]=c.useState({kind:"this-page"}),U=g||m,te=c.useMemo(()=>a==="inline"?i.filter(F=>l.has(F.dataKey)):i,[a,i,l]),q=c.useMemo(()=>{if(a!=="inline")return u;switch(ee.kind){case"this-page":return u.filter(F=>F.consumedThisPageLoad);case"defaults":return u.filter(F=>F.source==="default");case"share":return u.filter(F=>F.source==="shared"&&F.sharedSlug===ee.slug)}},[a,u,ee]);fi({seedTabs:te,mockEntries:q,initialSection:n,selection:C,setSelection:I});const se=c.useMemo(()=>{const F=new Set;for(const fe of u)fe.source==="default"&&F.add(ue(fe));return F},[u]),W=(C==null?void 0:C.kind)==="seed"?te.find(F=>F.dataKey===C.dataKey)??null:null,Y=(C==null?void 0:C.kind)==="mock"?q.find(F=>ue(F)===C.routeKey)??null:null,Q=W&&o?o[W.dataKey]??[]:[],ae=c.useMemo(()=>Ao({slug:e,scenarioName:t,seedTabs:te,mockEntries:q,selectedMock:Y,selectedSeedTab:W,selectedSeedRows:Q}),[e,t,te,q,Y,W,Q]),P=t??e,T=te.length>0||q.length>0,H=s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Nr,{title:P,slug:e,provider:j,chatOpen:z,onToggleChat:()=>B(F=>!F),variant:a,onClose:r?A:void 0,draftDirty:y.isDirty,draftDiff:y.diffSummary,draftSaving:y.saving,draftCancelling:y.cancelling,draftError:y.error,onSave:()=>void y.save(),onCancel:()=>void y.cancel()}),a==="inline"&&s.jsx(Gr,{shares:d,activeBadge:ee,onSelect:Z}),z&&s.jsx("div",{className:"flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)]",children:s.jsx(fr,{chatName:`edit-data-${e}`,prompt:ae,height:360,onClose:()=>B(!1)})}),s.jsxs("div",{className:"flex flex-1 min-h-0",children:[s.jsx(xr,{seedTabs:te,mockEntries:q,selection:C,onSelect:I}),s.jsx("main",{className:"flex-1 min-w-0 min-h-0 bg-[var(--bg-deep)] flex flex-col",children:s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[h&&s.jsx(Pe,{text:`Seed error: ${h}`,className:"text-xs text-red-400",rowClassName:"p-4"}),b&&s.jsx(Pe,{text:`Mocks error: ${b}`,className:"text-xs text-red-400",rowClassName:"p-4"}),!U&&!T&&s.jsx(yr,{}),W&&s.jsx(Xr,{slug:e,tab:W,initialRows:Q,onCellEdited:_}),Y&&s.jsx(zr,{entry:Y,scenarioSlug:e,scenarioHasDefaultFallback:se.has(ue(Y)),onSave:k,onRemove:O,onPassthrough:D,focusJsonPath:R}),(C==null?void 0:C.kind)==="browser"&&s.jsx(Jr,{slug:e,browserState:f,tab:C.tab,onCellEdited:_}),!W&&!Y&&(C==null?void 0:C.kind)!=="browser"&&T&&!U&&s.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"Select a data source from the left to view it."}),U&&!T&&s.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"})]})})]})]});return a==="fullPage"?s.jsx("div",{className:"fixed inset-0 bg-[var(--bg-deep)] text-[var(--text-primary)]",children:H}):a==="inline"?s.jsx("div",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-deep)] max-h-[min(640px,70vh)] min-h-0 flex flex-col overflow-hidden",children:H}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:A,"aria-label":"Close scenario data panel"}),s.jsx("aside",{className:"fixed right-0 top-0 z-50 h-full w-full max-w-4xl border-l border-[var(--border-default)] bg-[var(--bg-deep)] shadow-2xl",children:H})]})}const Cl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanel:Ii},Symbol.toStringTag,{value:"Module"}));export{Cr as $,ho as A,Xn as B,un as C,Vn as D,mn as E,Js as F,Ue as G,Yr as H,Wr as I,Vr as J,Jr as K,Oe as L,Ir as M,er as N,ir as O,Rr as P,Pr as Q,be as R,Ii as S,Gn as T,Mr as U,Ze as V,et as W,tt as X,Or as Y,Ar as Z,Tr as _,Lt as a,nl as a$,br as a0,gr as a1,Lr as a2,Dr as a3,xr as a4,Gr as a5,We as a6,jr as a7,$r as a8,zr as a9,Dc as aA,rc as aB,xc as aC,yc as aD,mc as aE,bc as aF,pc as aG,hc as aH,gc as aI,uc as aJ,lc as aK,vc as aL,fc as aM,Yc as aN,Uc as aO,Hc as aP,tl as aQ,Vc as aR,el as aS,kl as aT,jl as aU,_l as aV,gl as aW,bl as aX,ml as aY,xl as aZ,Zc as a_,Sr as aa,Nr as ab,yr as ac,wr as ad,vr as ae,Ur as af,Hr as ag,Kr as ah,mr as ai,hr as aj,Yn as ak,Wn as al,Un as am,Hn as an,qn as ao,Ln as ap,Dn as aq,_n as ar,lr as as,ur as at,fr as au,dr as av,oc as aw,Cc as ax,sc as ay,ac as az,or as b,Nc as b$,Xc as b0,Gc as b1,Jc as b2,Cl as b3,hl as b4,pl as b5,Fc as b6,Lc as b7,Kc as b8,Wc as b9,Ki as bA,Hi as bB,rs as bC,_e as bD,ds as bE,cs as bF,is as bG,wn as bH,Se as bI,Rt as bJ,Ys as bK,Vs as bL,Xs as bM,kn as bN,Pn as bO,Xe as bP,tr as bQ,jc as bR,Pc as bS,Ac as bT,Mc as bU,Rc as bV,Ic as bW,la as bX,ic as bY,mo as bZ,lt as b_,fl as ba,wc as bb,Sc as bc,_c as bd,Oc as be,ll as bf,cl as bg,il as bh,sl as bi,ul as bj,dl as bk,al as bl,ol as bm,rl as bn,$c as bo,Wi as bp,Ui as bq,Yi as br,Vi as bs,Xi as bt,wl as bu,vl as bv,yl as bw,Ji as bx,Sl as by,Ec as bz,Nn as c,Tc as c0,dc as c1,we as c2,Ts as c3,ps as c4,st as c5,ss as c6,xn as c7,ec as c8,So as c9,Ht as cA,Ss as cB,xe as cC,nc as cD,tc as cE,ks as cF,zs as cG,Ls as cH,Ks as cI,Fs as cJ,Ya as cK,Bo as cL,Bc as cM,Qc as cN,qc as cO,zc as cP,Ot as cQ,Ga as cR,Ja as cS,Wa as cT,Aa as cU,Jt as cV,Ma as cW,Ra as cX,ar as ca,yo as cb,Gs as cc,Fa as cd,ua as ce,da as cf,va as cg,Ta as ch,cc as ci,jo as cj,ja as ck,ma as cl,kc as cm,Qi as cn,La as co,Rn as cp,In as cq,Ea as cr,Da as cs,Gi as ct,za as cu,Zi as cv,Kn as cw,Ha as cx,qi as cy,js as cz,Xr as d,ye as e,Ai as f,Fr as g,Br as h,si as i,ei as j,zo as k,dn as l,bn as m,Sn as n,mt as o,tn as p,Qn as q,ue as r,Zn as s,hn as t,bo as u,pn as v,fn as w,de as x,ln as y,Jn as z};
@@ -1 +1 @@
1
- import{j as c}from"./markdown-C9tbsVHX.js";import{b as o}from"./react-nrLBr15I.js";import{S as l}from"./ScenarioDataPanel-BM7COEfv.js";function m({slug:t}){const[r,i]=o.useState(void 0);return o.useEffect(()=>{let n=!1;return fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e)return;const a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):void 0;i(a),a&&(document.title=`${a} · data`)}).catch(()=>{}),()=>{n=!0}},[t]),c.jsx(l,{slug:t,scenarioName:r,variant:"fullPage"})}const p=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelFullPage:m},Symbol.toStringTag,{value:"Module"}));export{m as S,p as _};
1
+ import{j as c}from"./markdown-C9tbsVHX.js";import{b as o}from"./react-nrLBr15I.js";import{S as l}from"./ScenarioDataPanel-D-nWT7xD.js";function m({slug:t}){const[r,i]=o.useState(void 0);return o.useEffect(()=>{let n=!1;return fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e)return;const a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):void 0;i(a),a&&(document.title=`${a} · data`)}).catch(()=>{}),()=>{n=!0}},[t]),c.jsx(l,{slug:t,scenarioName:r,variant:"fullPage"})}const p=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelFullPage:m},Symbol.toStringTag,{value:"Module"}));export{m as S,p as _};