@codeyam-editor/codeyam-editor 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/app-port-drift.js +23 -0
- package/npm/fleet-add-failure-evidence.js +309 -0
- package/npm/fleet-add-failure.js +51 -311
- package/npm/fleet-build-data.js +47 -20
- package/npm/fleet-preview-health.js +156 -0
- package/npm/fleet-revision.js +50 -0
- package/npm/fleet-sticky-fields.js +124 -0
- package/npm/launch-config.js +43 -142
- package/npm/scenario-check.js +68 -383
- package/npm/scenario-issues.js +47 -0
- package/npm/scenario-launch.js +349 -0
- package/npm/scenario-playwright.js +42 -321
- package/npm/scenario-targeting.js +338 -0
- package/npm/vm-forwards.js +158 -0
- package/package.json +5 -5
- package/ui/dist/assets/{ContainerInspector-Ceop11Fv.js → ContainerInspector-Cig2PDjT.js} +1 -1
- package/ui/dist/assets/{EditorShell-DjI5cEF_.js → EditorShell-DOuUJNSm.js} +76 -74
- package/ui/dist/assets/{ScenarioDataPanel-D-nWT7xD.js → ScenarioDataPanel-BRUYhl1o.js} +10 -10
- package/ui/dist/assets/{ScenarioDataPanelFullPage-ZNFZcTQU.js → ScenarioDataPanelFullPage-DjwRM8HJ.js} +1 -1
- package/ui/dist/assets/ScenarioRenderer-CcbccxCW.js +26 -0
- package/ui/dist/assets/{index-ClrdYzlw.js → index-Bkrhkuf5.js} +6 -6
- package/ui/dist/assets/index-Dw4EB88N.css +1 -0
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/ScenarioRenderer-BW6QLGFW.js +0 -26
- package/ui/dist/assets/index-B3SMxYUB.css +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{j as s}from"./markdown-C9tbsVHX.js";import{b as c}from"./react-nrLBr15I.js";import{a as
|
|
1
|
+
import{j as s}from"./markdown-C9tbsVHX.js";import{b as c}from"./react-nrLBr15I.js";import{a as cn,u as ln,d as Qr,C as Re,c as Zr}from"./useServerIdentity-CVuHTzjg.js";import{u as es}from"./useEvents-DNb1olaj.js";import{r as ts,a as ns}from"./xterm--24IGk-x.js";import{l as V,n as rs}from"./index-Bkrhkuf5.js";const se=e=>typeof e=="string"?e:null;function ss(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.error=="string")return{error:t.error};const n=se(t.title);if(n===null)return null;const r=Array.isArray(t.designAssets)?t.designAssets:[],a=Array.isArray(t.designSystems)?t.designSystems:[];return{title:n,brief:se(t.brief),descriptionPrompt:se(t.descriptionPrompt),exampleDescriptions:Array.isArray(t.exampleDescriptions)?t.exampleDescriptions.filter(o=>typeof o=="string"):[],provider:se(t.provider),designSystem:se(t.designSystem),designAssets:r.flatMap(o=>{const i=o??{},l=se(i.file);return l===null?[]:[{file:l,description:se(i.description)??"",storedAs:se(i.storedAs),thumbnailUrl:se(i.thumbnailUrl)}]}),designSystems:a.flatMap(o=>{const i=o??{},l=se(i.id);return l===null?[]:[{id:l,name:se(i.name)??l}]}),hasHouseDesign:t.hasHouseDesign===!0}}const as=["claude","codex","gemini","opencode","muse"];function Vi(e){return e===null||os(e)||e.provider===null?null:as.find(t=>t===e.provider)??null}function os(e){return e!==null&&"error"in e}const is={webkitdirectory:""};function cs(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 ls={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 bt({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:{...ls,background:n?"var(--bg-input)":"transparent"},children:e})}const Xi=Object.freeze(Object.defineProperty({__proto__:null,AssetPickerMenuItem:bt},Symbol.toStringTag,{value:"Module"}));function un({onChooseFiles:e,onChooseFolder:t,onClose:n,triggerRef:r,placement:a="below"}){const o=c.useRef(null);return cs(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(bt,{label:"Files…",onSelect:()=>{e(),n()}}),s.jsx(bt,{label:"Folder…",onSelect:()=>{t(),n()}})]})}const Ji=Object.freeze(Object.defineProperty({__proto__:null,AssetPickerMenu:un},Symbol.toStringTag,{value:"Module"})),us=350;function Se(e,t={}){const{minPendingMs:n=us}=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 dn="Connected to the editor server at ";function fn(e){const t=e===null?null:e?"in the cloud container":"on this machine";return t?`, running ${t}.`:"."}function ds(e,t){return e===null?null:`${dn}${e}${fn(t)}`}function fs({headline:e,explanation:t,nextAction:n,diagnostics:r,connection:a}){const o=[`CodeYam editor — ${e}`,`What happened
|
|
2
2
|
${t}`,`What to do
|
|
3
3
|
${n}`],i=r==null?void 0:r.trim();i&&o.push(`Details
|
|
4
4
|
${i}`);const l=a==null?void 0:a.trim();return l&&o.push(`Connection
|
|
5
5
|
${l}`),o.join(`
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
7
|
+
`)}function gt(e){return typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(gt).join(""):""}const ps={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 pn({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(cn,{variant:"subtle",text:n,label:r,ariaLabel:`Copy this report: ${e}`})]})}const Gi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeHeader:pn},Symbol.toStringTag,{value:"Module"}));function hn({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 qi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeNextAction:hn},Symbol.toStringTag,{value:"Module"}));function mn({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 Qi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeDiagnostics:mn},Symbol.toStringTag,{value:"Module"}));function bn({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 Zi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeActions:bn},Symbol.toStringTag,{value:"Module"}));function fe({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}=ln(),x=ps[i],v=b?ds(u,m):null,p=fs({headline:e,explanation:r??gt(t),nextAction:a??gt(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(pn,{headline:e,palette:x,report:p,copyLabel:f}),s.jsx("p",{style:{color:"var(--text-dim)"},children:t}),s.jsx(hn,{nextAction:n,palette:x}),o?s.jsx(mn,{diagnostics:o,testId:g?`${g}-diagnostics`:void 0}):null,s.jsx(bn,{actions:l,palette:x,actionFeedback:d}),u!==null&&b?s.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:[dn,s.jsx("code",{children:u}),fn(m)]}):null]})}const ec=Object.freeze(Object.defineProperty({__proto__:null,ErrorNotice:fe},Symbol.toStringTag,{value:"Module"})),hs=500,Me=new Set;let Ne=null,He=null;async function xt(){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(Me.size!==0){He=e;for(const t of[...Me])t(e)}}function ms(e){return Me.add(e),He&&e(He),Ne===null&&(Ne=setInterval(()=>{xt()},hs),xt()),()=>{Me.delete(e),Me.size===0&&Ne!==null&&(clearInterval(Ne),Ne=null,He=null)}}function bs(){xt()}function gn(){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 tc=Object.freeze(Object.defineProperty({__proto__:null,CaptureChatPlaceholder:gn},Symbol.toStringTag,{value:"Module"})),Ot="claude";function gs(e){return e==="claude"}function xs(e){return e!=="gemini"}function ys(e){return e==="muse"}function vs(e){return e==="muse"?"Meta":je(e)}function je(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";case"opencode":return"OpenCode";case"muse":return"Muse";default:return"Claude"}}const ws=1e3;let yt=0;function nc(){yt=Date.now()}function vt(){return yt===0?1/0:Date.now()-yt}function rc(){return vt()<ws}const xn=5e3,zt=6e4,_s=50;function Kt(e,t=xn){return e<t}function Ss(e,t=xn){return Math.max(_s,t-e)}const Te=new Map;async function js(e,t,n,r){if(r!=null&&r.aborted)return null;if(!Kt(vt()))return e;const a=Te.get(t);if(a)return a.label=e,V("dispatch-rename-superseded",{caller:n,label:e}),null;const o={label:e};Te.set(t,o);let i=0;for(;;){if(r!=null&&r.aborted)return Te.delete(t),V("dispatch-rename-cancelled",{caller:n,label:o.label,waitedMs:i}),null;const l=vt();if(!Kt(l))break;const d=Ss(l);if(i+d>zt)return Te.delete(t),V("dispatch-rename-abandoned",{caller:n,label:o.label,msSinceKeystroke:l,waitedMs:i,capMs:zt}),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 Te.delete(t),o.label}const ks=40;function Cs(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,ks).replace(/-+$/,"")||"session"}const Ue=new Map;function Ie(e,t){const n=Ue.get(e);if(!n){let r;try{r=t()}catch(a){return Promise.reject(a)}return r instanceof Promise?Ht(e,r):Promise.resolve()}return Ht(e,n.then(()=>t()))}function Ht(e,t){const n=t.catch(()=>{});return Ue.set(e,n),n.then(()=>{Ue.get(e)===n&&Ue.delete(e)}),t}let we=0,xe=[];function sc(){if(we+=1,we===1&&xe.length>0){const e=xe;xe=[];for(const t of e)t()}}function ac(){we>0&&(we-=1)}function Ns(){return we>0}function Ts(e){return we>0?Promise.resolve(!0):new Promise(t=>{let n=!1;const r=()=>{n||(n=!0,t(!0))};xe.push(r),setTimeout(()=>{n||(n=!0,xe=xe.filter(a=>a!==r),t(!1))},e)})}const ke="build",wt="miniagent",Ut=3e3;function Mt(e,t=!1){return Ns()?e():Ts(Ut).then(n=>{if(n)return e();const r=`no terminal-send-input listener attached within ${Ut}ms`;if(t)throw new Es(r);console.warn(`[terminal] dropped programmatic injection: ${r}`)})}class Es extends Error{constructor(t){super(t),this.name="TerminalInputDroppedError"}}function _e(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}function oc(e){Ie(ke,()=>Mt(()=>_e(e)))}function ic(e){return Ie(ke,()=>Mt(()=>_e(e),!0))}const ye=50;function cc(e){return Ie(ke,()=>Mt(()=>new Promise(t=>{_e(e),setTimeout(()=>{_e("\r"),t()},ye)}),!0))}function yn(e,t=_e,n=ke){return Ie(n,()=>new Promise(r=>{t(e),setTimeout(()=>{t("\r"),r()},ye)}))}const at=3e3;function vn(e){return e==="codex"?"codex":e==="gemini"?"gemini":e==="opencode"?"opencode":e==="muse"?"muse":"claude"}function wn(e,t,n,r,a){const o=vn(e),i=r?As(n,r):o;if(o!=="claude")return i;const l=t?" --permission-mode auto":"",d=a?` --session-id ${Pt(n,a)}`:"";return`${i}${l}${d}`}function As(e,t){const n=Pt(e,t);return e==="powershell"?`& ${n}`:n}function Pt(e,t){return`'${e==="powershell"?t.replaceAll("'","''"):t.replaceAll("'","'\\''")}'`}function Os(e,t,n=!0,r="posix",a=null,o=null){const i=Pt(r,t);return e==="opencode"?`opencode${n?" --auto":""} --prompt ${i}\r`:e==="muse"?`muse --trust-workspace${n?" --disable-approval":""} ${i}\r`:`${wn(e,n,r,a,o)} ${i}\r`}async function Ms(e,t=_e,n=ke,r="dispatch-rename-launch",a){const o=await js(Cs(e),n,r,a);return o===null?!1:(await yn(`/rename ${o}`,t,n),!0)}function Ps(e,t,n,r=ke,a){V("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:at}),setTimeout(()=>{V("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:at}),Ms(e,n,r,t).then(o=>a==null?void 0:a(o?"fired":"superseded"),()=>a==null?void 0:a("failed"))},at)}const Rt=".codeyam/tmp/inline-prompt.md";function Rs(e){return e.split(`
|
|
8
8
|
`).map(t=>t.startsWith("'@")?` ${t}`:t).join(`
|
|
9
|
-
`)}function
|
|
9
|
+
`)}function Is(e){return`mkdir -p .codeyam/tmp && cat > ${Rt} << 'INLINE_PROMPT_EOF'
|
|
10
10
|
${e}
|
|
11
|
-
INLINE_PROMPT_EOF\r`}function
|
|
12
|
-
${
|
|
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=`
|
|
11
|
+
INLINE_PROMPT_EOF\r`}function Ds(e){return`New-Item -ItemType Directory -Force -Path .codeyam/tmp | Out-Null; @'
|
|
12
|
+
${Rs(e)}
|
|
13
|
+
'@ | Set-Content -LiteralPath ${Rt} -Encoding utf8\r`}function Ls(e,t,n=!0,r="posix",a=null,o=null){const i=wn(e,n,r,a,o),l=r==="powershell"?Ds(t):Is(t),d=`${i} "Read the file at '${Rt}' for your instructions."\r`;return[l,d]}function _n(e){return e>=500?"transient":"rejected"}function Sn({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=vs(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(_n(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."]}),ys(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:[vn(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 lc=Object.freeze(Object.defineProperty({__proto__:null,ApiKeyFlow:Sn,classifyApiKeySaveFailure:_n},Symbol.toStringTag,{value:"Module"}));function ge({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 uc=Object.freeze(Object.defineProperty({__proto__:null,RecoveryActions:ge},Symbol.toStringTag,{value:"Module"}));function jn({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(ge,{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 dc=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthInstallProgress:jn},Symbol.toStringTag,{value:"Module"}));function Fs(e){return new Promise(t=>{e.file(n=>t(n),()=>t(null))})}function $s(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 Bs(e){return e.split("/").some(t=>t.startsWith("."))}async function kn(e,t,n){if(e.name.startsWith("."))return 0;const r=t?`${t}/${e.name}`:e.name;if(e.isFile){const a=await Fs(e);return a?(n.push({file:a,relativePath:r}),0):1}if(e.isDirectory){const a=await $s(e.createReader());let o=0;for(const i of a)o+=await kn(i,r,n);return o}return 0}async function zs(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 kn(i,"",a);return{files:a,skipped:o,expandedViaEntryApi:!0}}function Ks(e){return Array.from(e).map(t=>({file:t,relativePath:t.webkitRelativePath||t.name})).filter(({relativePath:t})=>!Bs(t))}function Hs(e){return e.size===0&&e.type===""}const Us="Folders can't be read in this browser — open the folder and drop the files inside it.";function Ws(e,t,n){const r=[];let a=null;for(const o of e){if(!t&&Hs(o.file)){a=Us;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 Ys(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 Vs=200;function Xs(e){for(const{relativePath:t}of e){const n=t.indexOf("/");if(n>0)return t.slice(0,n)}return null}function Js(e,t=Vs){if(e.length<=t)return null;const n=e.length.toLocaleString("en-US"),r=Xs(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 It=1024*1024*1024;function Cn(e){return e.map(t=>({file:t,relativePath:t.name}))}function Dt(e,t,n){const r=Js(e);if(r)return{files:[],error:r};const{valid:a,rejection:o}=Ws(e,t,n);return{files:a,error:o}}async function Gs(e,t=It){const n=await zs(e),r=Dt(n.files,n.expandedViaEntryApi,t);return r.files.length===n.files.length?{files:r.files,error:Ys(n)}:r}function qs(e,t=It){return Dt(Cn(Array.from(e??[])),!1,t)}function Qs(e,t=It){const n=Ks(e??[]);return n.length===0?{files:[],error:"No files found in that folder."}:Dt(n,!0,t)}const Ge=c.createContext({openPicker:()=>{},registerFileSink:()=>{}});function Zs({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"?Qs(u.files):qs(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(Ge.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",...is,onChange:g=>void d(g,"folder"),style:{display:"none"},"data-testid":"global-folder-picker-input"})]})}function Nn(){return c.useContext(Ge)}function ea(e,t){const{registerFileSink:n}=c.useContext(Ge);c.useEffect(()=>{if(t)return n(e),()=>n(null)},[n,e,t])}function Tn(){const{registerFileSink:e}=c.useContext(Ge);return{registerFileSink:e}}const fc=Object.freeze(Object.defineProperty({__proto__:null,FilePickerProvider:Zs,useFilePicker:Nn,useFilePickerChannel:Tn,useRegisterFilePickerSink:ea},Symbol.toStringTag,{value:"Module"}));async function En(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}const An=4e3;async function On({attempts:e=3,intervalMs:t=1500,timeoutMs:n=An}={}){for(let r=0;r<e;r++)if(r>0&&t>0&&await new Promise(a=>setTimeout(a,t)),await En(n))return!1;return!0}function Mn(e,t){let n=!1,r=null;async function a(){if(!n){if(await En(An)){n||t();return}n||(r=setTimeout(a,e))}}return r=setTimeout(a,e),()=>{n=!0,r&&(clearTimeout(r),r=null)}}const ta=3e3;function na({onUnreachable:e,onReachable:t,onReturned:n,confirmStopped:r=On,pollUntilAlive:a=Mn,returnPollMs:o=ta}){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 ra={binaryMismatch:!1,configMissingAtLaunch:!1},_t={state:"unknown",provider:Ot,credsPresent:!0,cliInstalled:!0,cliRunnable:null,cliFailure:null,scannedDirs:[],reason:null,source:null,shellShare:null,storeDurability:"unobserved",claudeLaunch:ra,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function sa(e){if(e==null)return{..._t,backendFieldAbsent:!0};if(typeof e!="object")return _t;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 aa=1e3,oa=5e3,ia=2e4,ca=6e4;function la(e,t){return e.state==="unknown"||e.probeInFlight?aa:e.state==="needs-login"?t<ca?oa:ia:null}let Pe=_t,Pn=0,Ee=null,ot=0;const Ve=new Set;function St(e){Pe=e,Ve.forEach(t=>t())}function Wt(e){return Ve.add(e),()=>Ve.delete(e)}function ua(){return Pe}let Xe=!1;function Yt(e){Xe!==e&&(Xe=e,Ve.forEach(t=>t()))}function da(){return Xe}const it=na({onUnreachable:()=>Yt(!0),onReachable:()=>Yt(!1),onReturned:()=>void le()});function le(){if(Ee)return Ee;const e=ot;return Ee=(async()=>{try{const t=await fetch("/api/config");if(!t.ok){e===ot&&it.noteFailure();return}const n=await t.json();Pn=Date.now(),it.reset(),Xe=!1,St(sa(n.providerAuth))}catch{it.noteFailure()}finally{Ee=null}})(),Ee}function fa(e){Date.now()-Pn<e/2||le()}function pc(){window.dispatchEvent(new CustomEvent("agent-auth-resolved"))}function pa(){const e=c.useSyncExternalStore(Wt,ua),t=c.useSyncExternalStore(Wt,da),n=c.useRef(Date.now());c.useEffect(()=>{le()},[]);const r=la(e,Date.now()-n.current);return c.useEffect(()=>{if(r===null)return;const a=window.setInterval(()=>fa(r),r);return()=>window.clearInterval(a)},[r]),c.useEffect(()=>{const a=()=>{Pe.state!=="authenticated"&&le()};return window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[]),c.useEffect(()=>{const a=()=>{St({...Pe,state:"needs-login"}),le()};return window.addEventListener("agent-auth-required",a),()=>window.removeEventListener("agent-auth-required",a)},[]),c.useEffect(()=>{const a=()=>{St({...Pe,state:"authenticated"}),le()};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:le}}var ha=ts(),ma=ns();function ba(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 ga=3e3;function Rn(){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:ba(f.previewDedicatedOriginHint),onManagedFleetVm:f.onManagedFleetVm??!1,previewSessionHandoff:f.previewSessionHandoff??null,previewSessionHandoffProbe:f.previewSessionHandoffProbe??null,starterContext:ss(f.starterContext)},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()},ga);return()=>clearInterval(d)},[l]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:n,error:a,refetch:l}}const xa="capture-origin-spawn-refused";function In(){return typeof window<"u"&&window.__codeyamCapture===!0}function Vt(){return In()&&window.__codeyamCaptureLiveSocket!==!0}function ya(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 va=20,wa=1;function _a(e,t){const n=t===wa?e:e/va;return Math.trunc(n)||Math.sign(n)}function Sa(){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 ja(e,t,n={}){const r=n.isMac??Sa(),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(Xt("copy",v)),!1}if(x){try{e.clearSelection()}catch{}o==null||o()}else a==null||a(Ca("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(Xt("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=ct("Copy",w,!v,()=>{l(v),h()}),S=ct("Paste",j,!1,()=>{f(),h()}),k=ct("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),ka(p,b,x);const A=_=>{p.contains(_.target)||h()},D=_=>{_.key==="Escape"&&(_.preventDefault(),h())};document.addEventListener("mousedown",A,!0),document.addEventListener("keydown",D,!0),i={root:p,onDocumentClick:A,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 ct(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 ka(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 Xt(e,t){const n=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${n}`}function Ca(e){return`Clipboard ${e} blocked by the browser.`}function Na(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 ze=new Set(["│","┃","║","|"]);function Ta(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&&ze.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&&ze.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(!ze.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(!ze.has(b))break;u=m}}return{topRow:h,bottomRow:u,leftBorderCol:f,rightBorderCol:g}}function Ea(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 Aa=200;function Oa(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=Ta(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=>Ea(o,B,y,S),A=o.cursorY<p.topRow||o.cursorY>p.bottomRow,D=A?p.bottomRow:o.cursorY,_=A?S:o.cursorX,O=m!==D;let C=null;if(O&&(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(O&&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 $=Na(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($)>Aa)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 Jt=1;function Ma(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>Jt||j>Jt){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,O=_.cursorY,C={};for(let I=-2;I<=2;I++){const R=O+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:O,cursorX:_.cursorX,viewportY:_.viewportY,baseY:_.baseY,rows:C})}catch{}let S=null;const k=_=>{S=_,y&&console.log("[click-cursor] result",_)},A=Oa({click:{clientX:v.clientX,clientY:v.clientY},terminal:e,cellSurface:d,debug:k});if(A){if(S){const _=S,O=_.box!==null&&_.targetRow!==_.cursorY;if(O&&g){y&&console.log("[click-cursor] suppressed by verification-disabled");return}O&&_.predictedCursorY!==null&&_.predictedCursorX!==null&&(h={y:_.predictedCursorY,x:_.predictedCursorX})}n(A)}}return d.addEventListener("mousedown",b),d.addEventListener("mouseup",x),()=>{d.removeEventListener("mousedown",b),d.removeEventListener("mouseup",x),u==null||u.dispose()}}function Pa(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 Gt=20*1024*1024,Ra=3e4,Ia=3e3;function Da(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 La(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Fa(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function $a(e,{file:t,relativePath:n},r){return JSON.stringify({type:"drop",id:e,name:n||t.name||"unnamed",mime:t.type||"application/octet-stream",data:r})}function Dn(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 Ba(e,t){function n(r){const a=Dn(r.clipboardData);a.length!==0&&(r.preventDefault(),r.stopPropagation(),t(a))}return e.addEventListener("paste",n,!0),()=>e.removeEventListener("paste",n,!0)}function za(){window.focus()}function Ka(e,t){za(),e==null||e.focus({preventScroll:!0}),t()}function Ha(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 hc({viewportY:e,baseY:t}){return!Number.isFinite(e)||!Number.isFinite(t)?!1:e>=t}function Ua({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 Wa(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 Ya(e,t){const{cellWidth:n,cellHeight:r}=Wa(e);return Ua({width:(t==null?void 0:t.clientWidth)??NaN,height:(t==null?void 0:t.clientHeight)??NaN,cellWidth:n,cellHeight:r})}function Ln(){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 mc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropOverlay:Ln},Symbol.toStringTag,{value:"Module"}));function Fn({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 bc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropToast:Fn},Symbol.toStringTag,{value:"Module"}));let $n=!1;function lt(e){$n=e}function Va(){return $n}const Xa=800,Bn="codeyam.miniAgent.deliveredSeed.";function zn(e,t){try{window.sessionStorage.setItem(Bn+e,t)}catch{}}function Ja(e,t){try{return window.sessionStorage.getItem(Bn+e)===t}catch{return!1}}const Ga=5e3,qa="*";function ut(e,t){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:{text:e,chatName:t}}))}const Qa=250,Kn="";function Za(e){return`\x1B[200~${e}\x1B[201~`}function gc(e,t){const n=t.replace(/[\r\n]+$/,"");if(!e(Kn))return null;e(Za(n));const r=window.setTimeout(()=>e("\r"),Qa);return()=>window.clearTimeout(r)}function Hn(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 eo(e,t="plan"){return Hn("miniagent-agent-idle",e,n=>{const r=n.detail;return(r==null?void 0:r.chatName)===t})}function to(e){return Va()?Promise.resolve():Hn("miniagent-ws-open",e)}async function no(e,t){return Ja(t,e)?(V("seed-suppressed-on-reattach",{chatName:t}),!1):(zn(t,e),await to(Ga),await eo(Xa,t),ut(Kn,t),ut(e,t),await new Promise(n=>setTimeout(n,ye)),ut("\r",t),!0)}function Un(){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 xc=Object.freeze(Object.defineProperty({__proto__:null,TerminalConnectingHint:Un},Symbol.toStringTag,{value:"Module"}));function Wn({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 yc=Object.freeze(Object.defineProperty({__proto__:null,TerminalReconnectingBanner:Wn},Symbol.toStringTag,{value:"Module"}));function Yn({onRefresh:e}){const{phase:t,attempts:n,retry:r}=Se(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(fe,{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 vc=Object.freeze(Object.defineProperty({__proto__:null,TerminalFailedBanner:Yn},Symbol.toStringTag,{value:"Module"}));function Vn({onReload:e,onDismiss:t}){const{phase:n,attempts:r,retry:a}=Se(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(fe,{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 wc=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerStoppedBanner:Vn},Symbol.toStringTag,{value:"Module"}));function Xn({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(cn,{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 _c=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerErrorBanner:Xn},Symbol.toStringTag,{value:"Module"}));function Jn({onRefresh:e}){const{phase:t,attempts:n,retry:r}=Se(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(fe,{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 Sc=Object.freeze(Object.defineProperty({__proto__:null,TerminalEdgeUnreachableBanner:Jn},Symbol.toStringTag,{value:"Module"}));function Gn({canRetry:e=!1,onRefresh:t}){const{phase:n,attempts:r,retry:a}=Se(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(fe,{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 jc=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionStaleBanner:Gn},Symbol.toStringTag,{value:"Module"}));function ro(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 qn({report:e,onRefresh:t}){const{phase:n,attempts:r,retry:a}=Se(t),o=ro(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(fe,{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 kc=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionDiedBanner:qn},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(Un,{}):e.kind==="reconnecting"?s.jsx(Wn,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t,label:r}):e.kind==="server-stopped"?s.jsx(Vn,{onReload:n,onDismiss:a}):e.kind==="server-error"?s.jsx(Xn,{message:e.message,onRefresh:n}):e.kind==="edge-unreachable"?s.jsx(Jn,{onRefresh:n}):e.kind==="session-died"?s.jsx(qn,{report:e.report,onRefresh:n}):e.kind==="session-stale"?s.jsx(Gn,{canRetry:e.canRetry,onRefresh:n}):s.jsx(Yn,{onRefresh:n})}const Cc=Object.freeze(Object.defineProperty({__proto__:null,TerminalDisconnectOverlay:Qn},Symbol.toStringTag,{value:"Module"}));function Zn(){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 Nc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchRetryingHint:Zn},Symbol.toStringTag,{value:"Module"}));function so(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=je(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 er({failure:e=null,onRetry:t}){const{phase:n,attempts:r,retry:a}=Se(t),o=so(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(fe,{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 Tc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchFailed:er},Symbol.toStringTag,{value:"Module"}));function tr({status:e,failure:t=null,onRetry:n}){return e==="retrying"?s.jsx(Zn,{}):e==="failed"?s.jsx(er,{failure:t,onRetry:n}):null}const Ec=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchOverlay:tr},Symbol.toStringTag,{value:"Module"}));function ao(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}const oo=e=>{typeof fetch=="function"&&fetch("/api/launch-trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ao(e)),keepalive:!0}).catch(()=>{})};let io=oo;function nr(e){io(e)}function Je(){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 rr(e){return e?e==="initial-design"?"design":e==="design-tweak"?"design-tweak":e==="plan"||e.startsWith("edit-plan-")?"plan":"other":"build"}function sr(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 jt=null;function Ac(e){jt=e}function co(){const e=jt;return jt=null,e}function Oc(e){return e??co()??Je()}function lo(e){return e==="fired"?{event:"rename-fired"}:e==="superseded"?{event:"rename-skipped",reason:"superseded"}:{event:"rename-failed"}}function uo({attempt:e,sawOutput:t}){return t?e===1?"extend":"ready":e===1?"retry":"fail"}function fo({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 po=350,ho=4e3,qt=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 mo(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=Je()):(l.current=null,i.current=o.current??Je(),o.current=null),(I=v.current)==null||I.call(v,{launchId:i.current,retryOf:l.current});const A=m.current;nr({event:"armed",launchId:i.current,retryOf:l.current,role:rr(b.current),command:sr(u.current),promptLen:typeof A=="string"?A.length:void 0});const D=u.current;if(D&&!xs(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 O(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}))}),gs(h.current)?d.current?w({event:"rename-skipped",reason:"already-scheduled"}):(d.current=!0,w({event:"rename-queued"}),Ps(b.current,"mini-agent-chat",$=>x.current($),wt,$=>w(lo($)))):w({event:"rename-skipped",reason:"provider-unsupported"}),setTimeout(()=>C(R),qt))}function C(R){if(!_())return;const $=f.current>g.current;switch(uo({attempt:R,sawOutput:$})){case"retry":O(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),qt);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})}}fo({idleMs:po,ceilingMs:ho}).then(()=>{_()&&O(1)})}const bo=500,go=5e3;function xo(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),A=c.useRef(t),D=c.useRef(i),_=c.useRef(l),O=c.useRef(null),C=c.useCallback(N=>{O.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(()=>{A.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=Je()),z.current),[]),Z=c.useCallback((N,K={})=>{const J=B.current;J&&nr({...N,...K,launchId:J,retryOf:G.current,role:rr(k.current),command:sr(y.current)})},[]),U=c.useRef(0),te=c.useRef(!1),q=c.useRef(0),ae=c.useRef(0),W=c.useRef(0);c.useEffect(()=>{const N=()=>{ae.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 Ie(wt,()=>{const he=_.current??"posix";if(J){const ie=Os(A.current,J,D.current,he,O.current,I.current),$e=dt(ie);return N($e),new Promise(E=>{setTimeout(()=>{K()&&N("\r"),E()},ye)})}const[Le,me]=Ls(A.current,ne??"",D.current,he,O.current,I.current),be=dt(Le),Fe=dt(me);return N(be),new Promise(ie=>{setTimeout(()=>{if(!K())return ie();N("\r"),setTimeout(()=>{if(!K())return ie();N(Fe),setTimeout(()=>{K()&&N("\r"),ie()},ye)},bo)},ye)})})},[]),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:A.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:A.current,slashCommand:y.current,reason:N,verified:!1,elapsedMs:ne})},go)},[v,Z]),oe=c.useCallback(N=>mo(N,{epochRef:U,attemptStartTsRef:q,agentAliveRef:p,pendingLaunchIdRef:z,launchIdRef:B,retryOfRef:G,renameScheduledRef:te,outputCountRef:ae,outputCountAtLaunchRef:W,providerRef:A,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:A.current,slashCommand:N,inAgent:!0}),await((J=w.current)==null?void 0:J.call(w).catch(()=>{})),U.current===K&&(await yn(N,ne=>j.current(ne),wt),U.current===K&&Q("relaunch-in-agent"))},[Q,v]),T=c.useCallback(()=>{te.current=!1,oe("arm")},[oe]),H=c.useCallback(()=>{const N=y.current;if(p.current&&N){P(N);return}oe("retry")},[oe,P]),F=c.useCallback(()=>{U.current!==0&&b.current!=="armed"&&Q("banner")},[Q]),pe=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:A.current,slashCommand:y.current,reason:"slash-command-rejected",command:N,elapsedMs:J})},[v,Z]),rt=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]),st=c.useCallback(()=>{U.current++,v("confirmed"),V(re.reattached,{provider:A.current,chatName:k.current})},[v]);return c.useEffect(()=>()=>{U.current++},[]),{status:g,failure:u,peekLaunchId:ee,arm:T,retry:H,onBannerReady:F,onRejected:pe,onStartupFailed:rt,onReattached:st,setLaunchProgram:C,setLaunchSessionId:R}}function dt(e){return e.endsWith("\r")?e.slice(0,-1):e}const qe=c.createContext({registerSender:()=>{},setReady:()=>{},sendToAgent:()=>!1,agentReady:!1});function yo({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(qe.Provider,{value:l,children:e})}function vo(){const{sendToAgent:e,agentReady:t}=c.useContext(qe);return{sendToAgent:e,agentReady:t}}function wo(e,t){const{registerSender:n,setReady:r}=c.useContext(qe);c.useEffect(()=>(n(e),()=>n(null)),[n,e]),c.useEffect(()=>(r(t),()=>r(!1)),[r,t])}function ar(){const{registerSender:e,setReady:t}=c.useContext(qe);return{registerSender:e,setReady:t}}const Mc=Object.freeze(Object.defineProperty({__proto__:null,AgentInputProvider:yo,useAgentInput:vo,useAgentInputChannel:ar,useRegisterAgentInput:wo},Symbol.toStringTag,{value:"Module"})),kt=new Map,Ct=new Set;function Pc(e){return kt.get(e)??null}function Qt(e,t){const n=kt.get(e)??null;if(!(t&&n&&t.length===n.length&&t.every((r,a)=>r===n[a]))&&!(t===null&&n===null)){kt.set(e,t);for(const r of Ct)r()}}function Rc(e){return Ct.add(e),()=>Ct.delete(e)}function _o({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),Ia);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>Gt)throw new Error(`File too large (max ${Gt/(1024*1024)} MB)`);const k=e.current;if(!k||k.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const A=await Da(y),D=La(),_=new Promise((O,C)=>{const I=window.setTimeout(()=>{i.current.delete(D)&&C(new Error("Timed out waiting for save to complete"))},Ra);i.current.set(D,{resolve:R=>{window.clearTimeout(I),O(R)},reject:R=>{window.clearTimeout(I),C(new Error(R))}})});return k.send($a(D,{file:y,relativePath:S},A)),_},[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(A){const D=A instanceof Error?A.message:String(A);d(`Attach failed: ${D}`);return}t(S.map(Fa).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 Gs(y.dataTransfer);k&&d(k),await m(S)},[m,d]),w=c.useCallback(y=>m(Cn(y)),[m]),j=c.useCallback(async y=>{const S=Dn(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 So(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 or(e){const t=c.useRef(e);return t.current=e,t}function jo({wsRef:e,insertInput:t}){const n=_o({wsRef:e,insertInput:t}),r=or(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=So(e,r);return{drops:n,dropCallbacksRef:r,sendToAgent:a,acceptPickedFiles:o}}const ko="The editor server closed the terminal connection with no further detail.";function Co(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return ko}const Ae=15;function No(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:Co(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:Ae}),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,Ae),maxAttempts:Ae});const h=await On();if(!a){if(h){n({kind:"server-stopped"}),i==null||i(),i=Mn(2e3,()=>{a||window.location.reload()});return}if(!(e.diagnoseClose&&await e.diagnoseClose(l)))if(o<Ae){const b=o<4?1e3*Math.pow(2,o):1e4;o++,n({kind:"reconnecting",attempt:o,maxAttempts:Ae}),setTimeout(()=>{a||d()},b)}else n({kind:"failed"})}}}return l}function To(){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=>No({...f,wsRef:e,setWsStatus:n,dismissServerStoppedRef:o}),[]);return{wsRef:e,wsStatus:t,setWsStatus:n,pulseKey:r,bumpPulse:i,dismissServerStopped:l,openSocket:d}}function Eo(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 ir({className:e=""}){const{openPicker:t}=Nn(),[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(un,{onChooseFiles:()=>t("files"),onChooseFolder:()=>t("folder"),onClose:()=>r(!1),triggerRef:a})]})}const Ic=Object.freeze(Object.defineProperty({__proto__:null,AttachFileButton:ir},Symbol.toStringTag,{value:"Module"}));function ft(e,t,n){if(!Ya(e,t))return!1;try{return n.fit(),!0}catch{return!1}}function cr({chatName:e,prompt:t,slashCommand:n,seedText:r,height:a=400,onClose:o,beforeRelaunch:i,binding:l,onInputChannel:d,onScreen:f}){const g=or(l),h=c.useRef(null),{wsRef:u,wsStatus:m,pulseKey:b,bumpPulse:x,dismissServerStopped:v,openSocket:p}=To(),w=c.useRef(null),j=c.useRef(null);c.useRef(t);const{config:y}=Rn(),S=(y==null?void 0:y.provider)??"claude",[k,A]=c.useState(()=>Vt()),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:O,sendToAgent:C,acceptPickedFiles:I}=jo({wsRef:u,insertInput:D}),{registerSender:R,setReady:$}=ar(),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}=Tn();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)),Ka(h.current,()=>{var T;return(T=j.current)==null?void 0:T.focus()})},[R,$,C,ee,I]),{shellDialect:U}=ln(),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}))},[]),ae=xo({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(ae);c.useEffect(()=>{W.current=ae});const Y=c.useRef(e);c.useEffect(()=>{Y.current=e});const Q=c.useRef(r),oe=c.useRef(n);return c.useEffect(()=>{Q.current=r,oe.current=n}),c.useEffect(()=>{const P=h.current;if(!P||Vt())return;const T=new ha.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 ma.FitAddon;T.loadAddon(H),T.open(P);const F=ja(T,P,{onError:E=>console.warn("[MiniAgentChat]",E)}),pe=Ma(T,{sendInput:E=>{const M=u.current;(M==null?void 0:M.readyState)===WebSocket.OPEN&&M.send(JSON.stringify({type:"input",data:E}))}}),rt=Ba(P,E=>{O.current.handleImageFiles(E)}),st=requestAnimationFrame(()=>{if(!ft(T,P,H))return;me=!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,ce;N=void 0;const E=Eo(T);Qt(Y.current,E),(X=(M=g.current)==null?void 0:M.onScreen)==null||X.call(M,E),(ce=G.current)==null||ce.call(G,E)},300)},J={current:"inline"},ne={current:null},he={current:!1},Le={current:!1};let me=!1;const be=p({announceConnecting:!0,buildUrl:()=>ya({mode:J.current,sessionId:ne.current??void 0,chatKey:e,launchId:te.current??W.current.peekLaunchId(),cols:me?T.cols:void 0,rows:me?T.rows:void 0,capture:In()}),onOpen:E=>{lt(!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,ce,Ce;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===xa){be.end(),A(!0);return}if(L.type==="error"){be.failWithServerError(L);return}if(L.type==="drop-complete"){O.current.resolveDrop(L.id,L.path);return}if(L.type==="drop-error"){O.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){he.current=!0,W.current.onReattached(),(Ce=(ce=g.current)==null?void 0:ce.onReattached)==null||Ce.call(ce,!!Q.current);const Be=Q.current,Bt=oe.current;Be&&Bt&&!Le.current&&(Le.current=!0,no(Bt,Y.current));return}if(!he.current){he.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 Be=oe.current;Q.current&&Be&&zn(Y.current,Be)}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:()=>{lt(!1),O.current.cancelAllDrops("Not connected")}});me=ft(T,P,H),be.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 Fe(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 Ce=_a(E.deltaY,E.deltaMode);Ce!==0&&(M.scrollLines(Ce),E.preventDefault(),E.stopPropagation())}P.addEventListener("wheel",Fe,{passive:!1});function ie(){var E;Pa(P)||(E=j.current)==null||E.focus()}window.addEventListener("terminal-focus",ie);function $e(E){const M=E.detail,X=u.current;((M==null?void 0:M.chatName)===Y.current||(M==null?void 0:M.chatName)===qa)&&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",$e),()=>{var M,X;N!==void 0&&window.clearTimeout(N),Qt(Y.current,null),(M=G.current)==null||M.call(G,null),be.dispose(),lt(!1),window.removeEventListener("terminal-focus",ie),window.removeEventListener("miniagent-send-input",$e),P.removeEventListener("wheel",Fe),cancelAnimationFrame(st),F(),pe(),rt();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]),Ha(h,()=>{const P=j.current,T=w.current;if(!P||!T||!ft(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:je(S)}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ir,{}),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(gn,{}):s.jsxs(s.Fragment,{children:[s.jsx(Qn,{status:m,pulseKey:b,onRefresh:()=>window.location.reload(),onDismissServerStopped:v}),s.jsx(tr,{status:ae.status,failure:ae.failure,onRetry:ae.retry}),_.dragActive&&s.jsx(Ln,{}),_.errorToast&&s.jsx(Fn,{message:_.errorToast})]})})]})}const Dc=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentChat:cr},Symbol.toStringTag,{value:"Module"}));function Lc(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 Fc(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 $c(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 Bc(e){return e!=="connected"&&e!=="signed-in-not-stored"}function zc(e){return e==="needs-login"||e==="signed-in-not-stored"}function Zt(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 Ao=500,Oo=75e3,Mo=3e5,Po=`
|
|
14
14
|
|
|
15
15
|
--- transcript tail ---
|
|
16
|
-
`,
|
|
16
|
+
`,Ro=`
|
|
17
17
|
|
|
18
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-
|
|
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};
|
|
19
|
+
`;function lr(e){const t=[{delimiter:Po,label:"Login transcript (what claude actually printed)"},{delimiter:Ro,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 ur({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 O=await _.json();n(O),O.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 O=await _.json().catch(()=>({}));n({state:"failed",error:O.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(),Ao);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),Oo);return()=>window.clearTimeout(_)},[y]),c.useEffect(()=>{if(!j){u(!1);return}const _=window.setTimeout(()=>u(!0),Mo);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 O=await _.json().catch(()=>({}));n({state:"failed",error:O.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]),A=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(ge,{onRetry:()=>void k(),onRecheck:()=>void A(),rechecking:m,retryTestId:"claude-oauth-timeout-retry",recheckTestId:"claude-oauth-timeout-recheck"})]});if(j)return s.jsx(jn,{timedOut:h,onRetry:()=>void k(),onRecheck:()=>void A(),rechecking:m});if(t.state==="failed"){const{headline:_,tail:O,tailLabel:C}=lr(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:_}),O&&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:O})]}),s.jsx(ge,{onRetry:()=>void k(),onRecheck:()=>void A(),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(ge,{onRetry:()=>void k(),onRecheck:()=>void A(),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(ge,{onRetry:()=>void k(),onRecheck:()=>void A(),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 Kc=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthFlow:ur,splitTranscriptTail:lr},Symbol.toStringTag,{value:"Module"}));function dr({provider:e,onAuthenticated:t,onClose:n}){const r=je(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(ur,{onAuthenticated:t}):s.jsx(Sn,{provider:e,onAuthenticated:t})]})})}const Hc=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthModal:dr},Symbol.toStringTag,{value:"Module"}));function Io(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 fr({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=je(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(Zt(_))}catch{v(Zt(null))}},[]),w=n==="stale-verdict",j=e==="claude"&&!t,y=r?` (token expired ${Io(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.":"",A=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:A}),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(dr,{provider:e,onAuthenticated:m,onClose:()=>f(!1)}):null]})}const Uc=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthenticateCta:fr},Symbol.toStringTag,{value:"Module"}));let pt=!1;function pr(e){const{state:t,provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:i,refresh:l}=pa(),[d]=c.useState(()=>pt);return c.useEffect(()=>{t==="authenticated"?pt=!0:t==="needs-login"&&(pt=!1)},[t]),t==="needs-login"?s.jsx(fr,{provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:i,onAuthenticated:()=>void l(),onAuthorized:()=>{}}):t==="authenticated"||d?s.jsx(cr,{...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 Wc=Object.freeze(Object.defineProperty({__proto__:null,GatedAgentChat:pr},Symbol.toStringTag,{value:"Module"})),ht=4e3;function en(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>ht?`${t.slice(0,ht)}
|
|
20
|
+
… (truncated, ${t.length-ht} more chars)`:t}function Do({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(en(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(en(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 Nt=new Set;let Ke=null;const Lo=150;function Yc(e){return Nt.add(e),()=>{Nt.delete(e)}}function ve(){Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{Ke=null;for(const e of Nt)e()},Lo)}const Tt=new Set;function Vc(e){for(const t of Tt)t(e)}function Fo(e){return Tt.add(e),()=>{Tt.delete(e)}}function $o({onSelect:e,onFocus:t}){c.useEffect(()=>Fo(({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 Bo(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 tn(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 zo(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 Ko(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 ue(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function Ho(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 Uo(e,t,n){const r=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:ue(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 Wo(){const[e,t]=c.useState(null),[n,r]=c.useState(null),a=c.useRef(null);return c.useEffect(()=>ms(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}`);bs()}catch(i){r(i instanceof Error?i.message:String(i))}}}}function Yo(e){const[t,n]=c.useState([]),[r,a]=c.useState(null),[o,i]=c.useState(!1),[l,d]=c.useState(null),{events:f}=es(),{status:g}=Wo(),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 Bo(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 tn(e,p),await u())},[e,u]),b=c.useCallback(async p=>{e&&(p.scope.kind==="scenario"?await tn(e,{routeKey:p.routeKey,status:p.status,body:p.body,headers:p.headers}):await Ho({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 zo(e,p),await u())},[e,u]),v=c.useCallback(async p=>{e&&(await Ko(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 Vo(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 Xo(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 Jo(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 Go(e,t){return e.length>0?Object.keys(e[0]):t?t.map(n=>n.name):[]}function qo(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?Jo(t[0][o]):"text");return a}function Qo(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 Zo(e,t){const{_metadata:n,...r}=t,a=r.localStorage&&typeof r.localStorage=="object"&&!Array.isArray(r.localStorage)?Vo(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&&Xo(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)||ei(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 nn(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function ei(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function ti(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 ni(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 ri(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 si(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 ai(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=Zo(Array.isArray(r)?r:[],a);n({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:ri(o.data,o.tabs),shares:si(a),props:ti(a),browserState:ni(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 Lt(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function oi(e){const t=await fetch(Lt(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 ii(e){const t=await fetch(Lt(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function ci(e){const t=await fetch(Lt(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function li({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 oi(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 ii(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 ci(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 ui={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},di={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 hr(e){return ui[e]??e}function fi(e){return di[e]??null}function de(e){return`${e.method} ${e.pathPattern}`}const pi={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 Ft({source:e}){const t=fi(e);return s.jsx("span",{className:`px-1.5 py-0.5 rounded border ${pi[e]}`,title:t??`source: ${e}`,children:hr(e)})}const Xc=Object.freeze(Object.defineProperty({__proto__:null,MockSourceBadge:Ft},Symbol.toStringTag,{value:"Module"}));function mr({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 Jc=Object.freeze(Object.defineProperty({__proto__:null,SidebarGroupOverrideHeader:mr},Symbol.toStringTag,{value:"Module"}));function br({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 Gc=Object.freeze(Object.defineProperty({__proto__:null,SidebarInheritedSection:br},Symbol.toStringTag,{value:"Module"}));function gr({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 qc=Object.freeze(Object.defineProperty({__proto__:null,MockSharedSlugBadge:gr},Symbol.toStringTag,{value:"Module"})),hi={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function xr({entry:e,routeKey:t,active:n,onSelect:r}){const a=hi[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(gr,{slug:e.sharedSlug})]})}const Qc=Object.freeze(Object.defineProperty({__proto__:null,SidebarMockEntryRow:xr},Symbol.toStringTag,{value:"Module"})),mi=["scenario","shared","default","catalog-only","passthrough"];function yr({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(We,{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(We,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:a?{scenarioCount:a.scenarioSeedCount,inheritedCount:a.inheritedSeedCount,renderInherited:()=>rn({tabs:a.inheritedSeedTabs,selection:n,onSelect:r})}:void 0,children:rn({tabs:e,selection:n,onSelect:r})}),s.jsx(We,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:a?{scenarioCount:a.scenarioMockCount,inheritedCount:a.inheritedMockCount,renderInherited:()=>sn({entries:a.inheritedMockEntries,selection:n,onSelect:r})}:void 0,children:sn({entries:t,grouped:o,selection:n,onSelect:r})})]})}function rn({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 sn({entries:e,grouped:t,selection:n,onSelect:r}){const a=t??bi(e);return mi.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:[hr(o),s.jsx(Ft,{source:o})]},`hdr-${o}`),...i.map(l=>{const d=de(l),f=(n==null?void 0:n.kind)==="mock"&&n.routeKey===d;return s.jsx(xr,{entry:l,routeKey:d,active:f,onSelect:()=>r({kind:"mock",routeKey:d})},d)})]})}function bi(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 We({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(mr,{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(br,{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 Zc=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateButton:Oe,ScenarioDataPanelSidebar:yr,SidebarGroup:We,routeKeyFor:de},Symbol.toStringTag,{value:"Module"}));function gi({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:de(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:de(t[0])})},[n,t,e,r,a])}function vr(){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 el=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEmptyState:vr},Symbol.toStringTag,{value:"Module"}));function wr({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 tl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelCloseButton:wr},Symbol.toStringTag,{value:"Module"}));function _r({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 nl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEditChatButton:_r},Symbol.toStringTag,{value:"Module"})),Et=new Set,At=new Set;let Sr={isActive:!1,previewSlug:null};function xi(){for(const e of Et)e()}function rl(e){return Et.add(e),()=>{Et.delete(e)}}function sl(e){Sr=e;for(const t of At)t(e)}function yi(e){return At.add(e),()=>{At.delete(e)}}function an(){return Sr}function vi(){const[e,t]=c.useState(()=>an());return c.useEffect(()=>(t(an()),yi(t)),[]),e}function jr({panelSlug:e,scenarioState:t}){const n=vi(),{isActive:r,previewSlug:a}=t??n;return a!==e?null:s.jsxs("button",{type:"button","aria-pressed":r,onClick:()=>xi(),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 al=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelInspectButton:jr},Symbol.toStringTag,{value:"Module"}));function kr({variant:e,slug:t}){const n=()=>window.open(rs(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 ol=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelOpenInNewButton:kr},Symbol.toStringTag,{value:"Module"}));function Cr(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 Nr({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:Cr(e)}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(Re,{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 il=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDraftBar:Nr,summarizeDraftDiff:Cr},Symbol.toStringTag,{value:"Module"}));function Tr({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=je(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(_r,{variant:o,providerLabel:b,chatOpen:r,onToggleChat:a}),s.jsx(jr,{panelSlug:t}),s.jsx(kr,{variant:o,slug:t}),i&&s.jsx(wr,{variant:o,onClose:i})]})]}),x&&u&&m&&s.jsx(Nr,{diff:d??null,saving:f??!1,cancelling:g??!1,error:h??null,onSave:u,onCancel:m})]})}const cl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelHeader:Tr},Symbol.toStringTag,{value:"Module"}));function wi(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 Er({body:e,onBodyChange:t}){const{copied:n,copy:r}=Zr();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 ll=Object.freeze(Object.defineProperty({__proto__:null,JsonBodyActions:Er},Symbol.toStringTag,{value:"Module"}));function De(e){return JSON.stringify(e)}function Ar(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function _i(e){const t=new Set;function n(r,a){if(r!==null&&typeof r=="object")if(t.add(De(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 Si(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 ji(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function ki(e){return e===null?"null":typeof e=="string"?e:String(e)}function Ci(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 Ze(e){return JSON.parse(JSON.stringify(e))}function Ni(e,t,n){if(t.length===0)return n;const r=Ze(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 $t(e,t){if(t.length===0)return e;const n=Ze(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 Ti(e,t){const n=Ze(e);let r=n;for(const a of t)r=r[a];return Array.isArray(r)&&r.push(null),n}function Ei(e,t,n){const r=Ze(e);let a=r;for(const o of t)a=a[o];return a&&typeof a=="object"&&!Array.isArray(a)&&(a[n]=""),r}function Ai(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 Oi(e,t){c.useEffect(()=>{if(!e)return;const n=Ai(e);n&&t(r=>{const a=new Set(r);for(let o=0;o<n.length;o++)a.add(De(n.slice(0,o)));return a})},[e,t])}function et({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 ul=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNodeLine:et},Symbol.toStringTag,{value:"Module"}));function Or(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:i}=e,l=De(n),d=Ar(a,l),f=t.length>0;return s.jsxs("div",{children:[s.jsxs(et,{collapsible:f,isOpen:d,onToggle:()=>o(l),parentKey:r,readOnly:i,onRemove:n.length>0?()=>e.onValueChange($t(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(tt,{...e,key:h,value:g,path:[...n,h],parentKey:h,isLast:h===t.length-1})),!i&&s.jsx("button",{type:"button",onClick:()=>e.onValueChange(Ti(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 dl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeArrayNode:Or},Symbol.toStringTag,{value:"Module"}));function Mr({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 fl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeAddKeyInput:Mr},Symbol.toStringTag,{value:"Module"}));function Pr(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:i,addingKeyAtPath:l,onStartAddKey:d,onStopAddKey:f}=e,g=De(n),h=Ar(a,g),u=Object.entries(t),m=u.length>0,b=l===g;return s.jsxs("div",{children:[s.jsxs(et,{collapsible:m,isOpen:h,onToggle:()=>o(g),parentKey:r,readOnly:i,onRemove:n.length>0?()=>e.onValueChange($t(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(tt,{...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(Mr,{onSave:x=>{x.trim()&&e.onValueChange(Ei(e.rootValue,n,x.trim())),f()},onCancel:f})]}),h&&s.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}const pl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeObjectNode:Pr},Symbol.toStringTag,{value:"Module"}));function Rr({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 hl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveEditor:Rr},Symbol.toStringTag,{value:"Module"}));function Ir(e){const{value:t,path:n,parentKey:r,readOnly:a,editingPath:o,onStartEdit:i,onStopEdit:l}=e,d=De(n),f=o===d;return s.jsx(et,{collapsible:!1,isOpen:!1,parentKey:r,readOnly:a,onToggle:()=>{},onRemove:n.length>0?()=>e.onValueChange($t(e.rootValue,n)):null,children:f?s.jsx(Rr,{initial:ki(t),onSave:g=>{const h=Ci(g);e.onValueChange(Ni(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 ${Si(t)} text-left font-mono`,title:a?void 0:"Click to edit",children:ji(t)})})}const ml=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveNode:Ir},Symbol.toStringTag,{value:"Module"}));function tt(e){const{value:t}=e;return Array.isArray(t)?s.jsx(Or,{...e,value:t}):t!==null&&typeof t=="object"?s.jsx(Pr,{...e,value:t}):s.jsx(Ir,{...e})}const bl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNode:tt},Symbol.toStringTag,{value:"Module"}));function nt({value:e,onChange:t,readOnly:n=!1,focusJsonPath:r}){const[a,o]=c.useState(()=>_i(e)),[i,l]=c.useState(null),[d,f]=c.useState(null);Oi(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(tt,{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 gl=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeEditor:nt},Symbol.toStringTag,{value:"Module"}));function Dr({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 xl=Object.freeze(Object.defineProperty({__proto__:null,MockBodyHeadersEditor:Dr},Symbol.toStringTag,{value:"Module"})),mt=5;function Mi(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,mt).join(", "),a=e.length>mt?`, +${e.length-mt} more`:"";return`Affects ${e.length} ${n}: ${r}${a}`}function Pi(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 Ri(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 Ii(e,t,n){const[r,a]=c.useState({}),o=n.map(i=>ue(i.scope)).join("|");return c.useEffect(()=>{let i=!1;return(async()=>{const d={};for(const f of n)d[ue(f.scope)]="loading";a(d);for(const f of n)try{const g=await Uo(e,t,f.scope);if(i)return;a(h=>({...h,[ue(f.scope)]:g}))}catch{if(i)return;a(g=>({...g,[ue(f.scope)]:[]}))}})(),()=>{i=!0}},[e,t,o]),r}function Lr({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 yl=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeChoiceRow:Lr},Symbol.toStringTag,{value:"Module"}));function Fr({entry:e,scenarioSlug:t,routeKey:n,onCancel:r,onConfirm:a}){const o=Pi(e),[i,l]=c.useState(()=>Ri(e,o)),d=Ii(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(Lr,{choice:b,selected:i===x,impactLabel:Mi(d[ue(b.scope)],b.scope),onSelect:()=>l(x)},ue(b.scope)))}),h&&s.jsx(Re,{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 vl=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeModal:Fr},Symbol.toStringTag,{value:"Module"}));function $r({entry:e,routeKey:t,scenarioSlug:n,onSave:r,focusJsonPath:a}){const o=wi(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(Re,{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(Dr,{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(Er,{body:o.body,onBodyChange:o.setBody})]}),s.jsx(nt,{value:o.body,onChange:o.setBody,focusJsonPath:a},t)]}),g&&s.jsx(Fr,{entry:e,scenarioSlug:n,routeKey:t,onCancel:()=>h(!1),onConfirm:async b=>{await u(b),h(!1)}})]})}const wl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockEditable:$r},Symbol.toStringTag,{value:"Module"}));function Di(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 on={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 Li(e){return on[e]??on.GET}function Br({entry:e,scenarioHasDefaultFallback:t,onSave:n,onRemove:r,onPassthrough:a}){const o=`${e.method} ${e.pathPattern}`,i=Li(e.method),l=e.status??e.lastObservedStatus,d=c.useMemo(()=>e.lastObservedMs?Di(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(Ft,{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 _l=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockHeader:Br},Symbol.toStringTag,{value:"Module"}));function zr({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(nt,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}const Sl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockReadOnly:zr},Symbol.toStringTag,{value:"Module"}));function Kr({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(Br,{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($r,{entry:e,routeKey:l,scenarioSlug:t,onSave:r,focusJsonPath:i}):s.jsx(zr,{entry:e})})]})}const jl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMock:Kr},Symbol.toStringTag,{value:"Module"}));function Fi({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]:nn(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(()=>{ve(),r&&r()}).catch(()=>{})}l(null)}}async function p(w,j,y){const S=[...a];S[w]={...S[w],[j]:nn(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})}),ve(),r&&r()}catch{}}return{rows:a,editingCell:i,editValue:d,handleEditCell:m,handleEditValueChange:b,handleSave:x,handleCancelEdit:v}}function Hr({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 kl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCategoryBadge:Hr},Symbol.toStringTag,{value:"Module"}));function Ur({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 Cl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCellEditor:Ur},Symbol.toStringTag,{value:"Module"}));function Wr({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(Yr,{name:o,type:t[o],isPk:o===n},o))]})}),s.jsx("tbody",{children:r.map((o,i)=>s.jsx(Vr,{row:o,rowIndex:i,columns:e,pkCol:n,onEditCell:a},i))})]})})}function Yr({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 Vr({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(Xr,{value:e[o],isPk:o===r,onEdit:()=>a(t,o)},o))]})}function Xr({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 Nl=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCell:Xr,DataViewerColumnHeader:Yr,DataViewerRow:Vr,DataViewerTable:Wr},Symbol.toStringTag,{value:"Module"}));function Jr({slug:e,tab:t,initialRows:n,onCellEdited:r}){const{rows:a,editingCell:o,editValue:i,handleEditCell:l,handleEditValueChange:d,handleSave:f,handleCancelEdit:g}=Fi({slug:e,tab:t,initialRows:n,onCellEdited:r}),h=Go(a,t.schemaFields),u=qo(h,a,t.schemaFields),m=Qo(h,t.schemaFields);return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Hr,{tab:t}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(Wr,{columns:h,colTypes:u,pkCol:m,rows:a,onEditCell:l})}),o&&s.jsx(Ur,{editingCell:o,editValue:i,onEditValueChange:d,onSave:f,onCancel:g})]})}const Tl=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainTable:Jr},Symbol.toStringTag,{value:"Module"}));function $i({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)})}),ve(),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 Gr({slug:e,browserState:t,tab:n,onCellEdited:r}){const{value:a,handleChange:o,label:i,description:l}=$i({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(nt,{value:a,onChange:o})})]})}const El=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateTab:Gr},Symbol.toStringTag,{value:"Module"}));function Ye({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 Al=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataBadge:Ye},Symbol.toStringTag,{value:"Module"}));function qr({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(Ye,{label:"This Page",active:t.kind==="this-page",onClick:()=>n({kind:"this-page"})}),e.map(r=>s.jsx(Ye,{label:r,active:t.kind==="share"&&t.slug===r,onClick:()=>n({kind:"share",slug:r})},r)),s.jsx(Ye,{label:"Defaults",active:t.kind==="defaults",onClick:()=>n({kind:"defaults"})})]})}const Ol=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataStrip:qr},Symbol.toStringTag,{value:"Module"}));function Bi({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}=ai(e),{entries:u,loading:m,error:b,upsertScoped:x,remove:v,setPassthrough:p}=Yo(e),{config:w}=Rn(),j=(w==null?void 0:w.provider)??"claude",y=li({slug:e,onPreviewReload:ve}),S=c.useCallback(()=>{y.markDirty(),ve()},[y]),k=c.useCallback(async F=>{await x(F),S()},[x,S]),A=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(),ve()},[y]),O=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}),[]);$o({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]);gi({seedTabs:te,mockEntries:q,initialSection:n,selection:C,setSelection:I});const ae=c.useMemo(()=>{const F=new Set;for(const pe of u)pe.source==="default"&&F.add(de(pe));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=>de(F)===C.routeKey)??null:null,Q=W&&o?o[W.dataKey]??[]:[],oe=c.useMemo(()=>Do({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(Tr,{title:P,slug:e,provider:j,chatOpen:z,onToggleChat:()=>B(F=>!F),variant:a,onClose:r?O: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(qr,{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(pr,{chatName:`edit-data-${e}`,prompt:oe,height:360,onClose:()=>B(!1)})}),s.jsxs("div",{className:"flex flex-1 min-h-0",children:[s.jsx(yr,{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(Re,{text:`Seed error: ${h}`,className:"text-xs text-red-400",rowClassName:"p-4"}),b&&s.jsx(Re,{text:`Mocks error: ${b}`,className:"text-xs text-red-400",rowClassName:"p-4"}),!U&&!T&&s.jsx(vr,{}),W&&s.jsx(Jr,{slug:e,tab:W,initialRows:Q,onCellEdited:_}),Y&&s.jsx(Kr,{entry:Y,scenarioSlug:e,scenarioHasDefaultFallback:ae.has(de(Y)),onSave:k,onRemove:A,onPassthrough:D,focusJsonPath:R}),(C==null?void 0:C.kind)==="browser"&&s.jsx(Gr,{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:O,"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 Ml=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanel:Bi},Symbol.toStringTag,{value:"Module"}));export{Nr as $,yo as A,Jn as B,dn as C,Xn as D,bn as E,Zs as F,We as G,Vr as H,Yr as I,Xr as J,Gr as K,Oe as L,Dr as M,tr as N,cr as O,Ir as P,Rr as Q,ge as R,Bi as S,qn as T,Pr as U,et as V,tt as W,nt as X,Or as Y,Mr as Z,Er as _,Ft as a,cl as a$,gr as a0,xr as a1,Fr as a2,Lr as a3,yr as a4,qr as a5,Ye as a6,kr as a7,Br as a8,Kr as a9,Kc as aA,lc as aB,jc as aC,kc as aD,wc as aE,_c as aF,yc as aG,vc as aH,Sc as aI,bc as aJ,mc as aK,Cc as aL,xc as aM,Qc as aN,Gc as aO,Jc as aP,il as aQ,Zc as aR,ol as aS,Ol as aT,Al as aU,Tl as aV,Sl as aW,_l as aX,wl as aY,jl as aZ,al as a_,jr as aa,Tr as ab,vr as ac,_r as ad,wr as ae,Wr as af,Ur as ag,Hr as ah,br as ai,mr as aj,Vn as ak,Yn as al,Wn as am,Un as an,Qn as ao,Fn as ap,Ln as aq,Sn as ar,ur as as,dr as at,pr as au,fr as av,fc as aw,Mc as ax,uc as ay,dc as az,ir as b,ut as b$,el as b0,nl as b1,tl as b2,Ml as b3,vl as b4,yl as b5,Uc as b6,Hc as b7,Xc as b8,qc as b9,Xi as bA,Ji as bB,os as bC,is as bD,Se as bE,ms as bF,fs as bG,ds as bH,_n as bI,je as bJ,It as bK,Gs as bL,qs as bM,Qs as bN,Cn as bO,Rn as bP,Je as bQ,nr as bR,Ac as bS,$c as bT,Lc as bU,Fc as bV,Bc as bW,zc as bX,pa as bY,pc as bZ,vo as b_,xl as ba,Nc as bb,Ec as bc,Tc as bd,Dc as be,ml as bf,hl as bg,pl as bh,ul as bi,bl as bj,gl as bk,dl as bl,fl as bm,ll as bn,Wc as bo,qi as bp,Gi as bq,Qi as br,Zi as bs,ec as bt,Nl as bu,Cl as bv,kl as bw,tc as bx,El as by,Ic as bz,Tn as c,Pc as c0,Rc as c1,gc as c2,Vi as c3,_e as c4,Ms as c5,gs as c6,at as c7,cs as c8,yn as c9,rc as cA,Ts as cB,Ut as cC,Ns as cD,ye as cE,cc as cF,ic as cG,Es as cH,Ws as cI,zs as cJ,Ys as cK,Ks as cL,qa as cM,Wo as cN,Yc as cO,sl as cP,rl as cQ,Vc as cR,Ot as cS,to as cT,eo as cU,Ga as cV,Ia as cW,Gt as cX,Da as cY,Fa as cZ,oc as ca,To as cb,or as cc,jo as cd,ea as ce,Ha as cf,ha as cg,ma as ch,ja as ci,Ma as cj,hc as ck,Eo as cl,Ta as cm,ya as cn,Oc as co,sc as cp,Ka as cq,In as cr,Dn as cs,Pa as ct,za as cu,nc as cv,Ya as cw,ac as cx,Hn as cy,Xa as cz,Jr as d,ve as e,Di as f,$r as g,zr as h,li as i,ai as j,Yo as k,fn as l,gn as m,jn as n,bt as o,nn as p,Zn as q,de as r,er as s,mn as t,wo as u,hn as v,pn as w,fe as x,un as y,Gn as z};
|