"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),p=require("react"),kn=require("react-dom/client"),y=require("../chunks/index-BtqYNH_S.js"),x=require("../chunks/switch-fIkmwzUt.js"),Ye=require("../data-app-builder-browser-runtime/index.cjs"),Nn=require("../chunks/save-D3YYinDz.js");function Fr(t){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const d=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,a,d.get?d:{enumerable:!0,get:()=>t[a]})}}return s.default=t,Object.freeze(s)}const An=Fr(p),Cn=Fr(kn);/**
 * @license lucide-react v0.453.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Rn=x.createLucideIcon("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/**
 * @license lucide-react v0.453.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bn=x.createLucideIcon("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
 * @license lucide-react v0.453.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Dn=x.createLucideIcon("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/**
 * @license lucide-react v0.453.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $n=x.createLucideIcon("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/**
 * @license lucide-react v0.453.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Pn=x.createLucideIcon("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]),Fn=[{id:"customer-health",title:"Customer health workspace",description:"KPI cards, customer table, and segment filters for account health review.",datasets:["customers","orders"],prompt:"Build a customer health data app with KPI cards, segment and region filters, a revenue trend, and a customer health table."},{id:"revenue-command",title:"Revenue command center",description:"Revenue, margin, and order trends with top accounts and category drilldowns.",datasets:["orders","customers"],prompt:"Create a revenue command center with revenue and margin KPIs, a monthly trend chart, a segment performance section, and a top customers table."},{id:"operations-overview",title:"Operations overview",description:"Operational throughput, exceptions, and detail tables for daily review.",datasets:["orders","inventory"],prompt:"Create an operations dashboard with throughput KPIs, exception tables, trend charts, and filters for date, region, and status."}],Mn=[{id:"context",label:"Context",detail:"Read the current app files and workspace capabilities.",state:"idle"},{id:"generate",label:"Generate",detail:"Call the hosted model to produce the next React revision.",state:"idle"},{id:"edit",label:"Edit",detail:"Apply source changes through the local bridge.",state:"idle"},{id:"typecheck",label:"Typecheck",detail:"Run the local workspace validation command.",state:"idle"},{id:"repair",label:"Repair",detail:"Use diagnostics for a bounded repair pass if needed.",state:"idle"},{id:"preview",label:"Preview",detail:"Refresh the iframe once the dev server has updated.",state:"idle"}],$t=[{id:"gpt-5.5-low",label:"GPT-5.5 fast",model:"gpt-5.5",reasoningEffort:"low"},{id:"gpt-5.5-medium",label:"GPT-5.5 balanced",model:"gpt-5.5",reasoningEffort:"medium"},{id:"gpt-5.4-mini-minimal",label:"GPT-5.4 mini fast",model:"gpt-5.4-mini",reasoningEffort:"low"},{id:"gpt-4.1-mini",label:"GPT-4.1 mini",model:"gpt-4.1-mini"}],Sr="semaphor-data-app-builder-transcript",kr="semaphor-data-app-builder-preview-url",Nr="semaphor-data-app-builder-bridge-url",Ar="semaphor-data-app-builder-project-dir",At="http://semaphor-data-app.localhost:8088",Cr="http://localhost:8787",Ct="/Users/rohit/code/sandbox/semaphor-data-apps/data-app",Te=3,Tn=18,Rt=12;function ce(t,s){return`${t}:${s}`}function ue(t){return`${t}-${Date.now()}-${Math.random().toString(16).slice(2)}`}function En(t){return $t.find(s=>s.id===t)||$t[0]}async function O(t,s){const a=await t.text();if(!a.trim())return{};try{return JSON.parse(a)}catch{const d=a.replace(/\s+/g," ").trim().slice(0,500);throw new Error(`${s} returned ${t.status} ${t.statusText} with non-JSON response: ${d}`)}}function Mr(t,s){const a=t==null?void 0:t.trim().replace(/\/$/,"");return a?`${a.endsWith("/api")?a:`${a}/api`}/data-app-builder${s}`:`/api/data-app-builder${s}`}function xe(t,s){const a=t==null?void 0:t.trim().replace(/\/$/,"");return a?`${a.endsWith("/api")?a:`${a}/api`}/data-apps${s}`:`/api/data-apps${s}`}function Se(t){return t?{Authorization:`Bearer ${t}`}:{}}function ke(t){return t?"omit":"include"}function Ee(t){if(Array.isArray(t))return t.map(Ee);if(!t||typeof t!="object")return t;const s={};return Object.entries(t).forEach(([a,d])=>{if(a!=="contentsBase64"){if(a==="assets"&&Array.isArray(d)){s.assets=d.map(l=>{if(!l||typeof l!="object")return l;const{contentsBase64:u,...h}=l;return Ee(h)});return}s[a]=Ee(d)}}),s}async function On({apiServiceUrl:t,accessToken:s,signal:a}){const d=await fetch(Mr(t,"/status"),{cache:"no-store",headers:s?{Authorization:`Bearer ${s}`}:void 0,signal:a}),l=await O(d,"Data App Builder status");return d.ok?l:{ok:!1,error:l.error||d.statusText}}async function Ln(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){const u=await fetch(Mr(s,"/turn"),{method:"POST",signal:d,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify({...t,stream:!0})}),h=u.headers.get("content-type")||"";if(u.body&&h.includes("text/event-stream"))return In(u,l);const g=await O(u,"Data App Builder turn");if(!u.ok||!g.ok||!g.turn)throw new Error(g.error||"Data App Builder could not run the turn.");return g.turn}async function In(t,s){var N,f,R;const a=(N=t.body)==null?void 0:N.getReader();if(!a)throw new Error("Data App Builder turn stream was empty.");const d=new TextDecoder;let l="";const u={status:t.status,ok:t.ok},h=j=>{var L;const B=j.split(`
`),b=((L=B.find(F=>F.startsWith("event:")))==null?void 0:L.slice(6).trim())||"message",E=B.filter(F=>F.startsWith("data:")).map(F=>F.slice(5).trim()).join(`
`);if(!E)return;const z=JSON.parse(E);if(b==="progress"){s==null||s(z);return}b==="result"&&(u.status=typeof z.status=="number"?z.status:u.status,u.ok=z.ok===!0,u.result=z.body)};for(;;){const{done:j,value:B}=await a.read();if(j)break;l+=d.decode(B,{stream:!0});let b=l.indexOf(`

`);for(;b>=0;){const E=l.slice(0,b).trim();l=l.slice(b+2),E&&h(E),b=l.indexOf(`

`)}}const g=l.trim();if(g&&h(g),!u.ok||!((f=u.result)!=null&&f.ok)||!u.result.turn)throw new Error(((R=u.result)==null?void 0:R.error)||`Data App Builder could not run the turn (${u.status}).`);return u.result.turn}async function zn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var R,j,B;const l=t.dataAppId,u=l?xe(s,`/${l}/draft`):xe(s,""),h=l?{title:t.title,description:t.description,manifest:t.manifest,sourceSnapshot:t.sourceSnapshot,sourceRevision:t.sourceRevision,validationStatus:t.validationStatus,bridgeWorkspaceHint:t.bridgeWorkspaceHint}:{projectId:t.projectId,title:t.title,description:t.description,manifest:t.manifest,sourceSnapshot:t.sourceSnapshot,sourceRevision:t.sourceRevision,validationStatus:t.validationStatus,bridgeWorkspaceHint:t.bridgeWorkspaceHint},g=await fetch(u,{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify(h)}),N=await O(g,"Data App save draft");if(!g.ok)throw new Error(N.error||"Data App draft could not be saved.");const f=l||((R=N.dataApp)==null?void 0:R.id);if(!f)throw new Error("Data App save draft response did not include an app id.");return{dataAppId:f,draftId:(j=N.draft)==null?void 0:j.id,savedAt:((B=N.draft)==null?void 0:B.updatedAt)||new Date().toISOString()}}async function Wn(t,{apiServiceUrl:s,accessToken:a,signal:d}){var h;const l=await fetch(xe(s,`/${t.dataAppId}`),{cache:"no-store",credentials:ke(a),signal:d,headers:Se(a)}),u=await O(l,"Data App load");if(!l.ok||!((h=u.dataApp)!=null&&h.id))throw new Error(u.error||"Data App could not be loaded.");return u.dataApp}async function Hn(t,{apiServiceUrl:s,accessToken:a,signal:d,onProgress:l}){var f,R,j,B;if(!t.draftId||!((f=t.sourceRevision)!=null&&f.snapshotHash))throw new Error("Data App publish requires a saved draft and matching source revision.");const u=Ee(t.validationStatus);l==null||l({phase:"start",label:"Starting publish session",detail:"Creating a versioned publish record in Semaphor."});const h=await fetch(xe(s,`/${t.dataAppId}/publish/start`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({draftId:t.draftId,sourceRevisionSnapshotHash:(R=t.sourceRevision)==null?void 0:R.snapshotHash,validationStatus:u})}),g=await O(h,"Data App publish start");if(!h.ok||!((j=g.publishSession)!=null&&j.versionId))throw new Error(g.error||"Data App publish session could not be started.");const N=g.publishSession.versionId;try{l==null||l({phase:"build",label:"Building app locally",detail:"The local bridge is running the app build."});const b=await t.buildArtifacts({signal:d,onProgress:l}),E=Ee(b.validationStatus);for(const[F,W]of b.assets.entries()){l==null||l({phase:"upload",label:`Uploading asset ${F+1} of ${b.assets.length}`,detail:W.path,assetIndex:F+1,assetCount:b.assets.length});const ge=await fetch(xe(s,`/${t.dataAppId}/publish/upload`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,assetPath:W.path,contentsBase64:W.contentsBase64,contentType:W.contentType})}),q=await O(ge,"Data App publish upload");if(!ge.ok)throw new Error(q.error||`Upload failed for ${W.path}.`)}l==null||l({phase:"complete",label:"Finalizing published version",detail:"Validating manifest and marking the version ready."});const z=await fetch(xe(s,`/${t.dataAppId}/publish/complete`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,manifest:b.manifest,entryFile:b.entryFile,styleFiles:b.styleFiles,validationStatus:E})}),L=await O(z,"Data App publish complete");if(!z.ok||!((B=L.version)!=null&&B.id))throw new Error(L.error||"Data App publish could not be completed.");return{dataAppId:t.dataAppId,versionId:L.version.id,version:L.version.version,publishedAt:L.version.updatedAt||new Date().toISOString()}}catch(b){throw await fetch(xe(s,`/${t.dataAppId}/publish/fail`),{method:"POST",credentials:ke(a),signal:d,headers:{"Content-Type":"application/json",...Se(a)},body:JSON.stringify({versionId:N,validationStatus:{ok:!1,error:b instanceof Error?b.message:String(b)}})}).catch(()=>{}),b}}function Rr(t){const s=Array.from(new Set(t)),a=["src/App.tsx","src/data-app/index.tsx","src/data-app/styles.css","src/data-app/format.ts","src/data-app/types.ts","src/index.css","src/main.tsx"],d=[];for(const l of a)s.includes(l)&&d.push(l);for(const l of s){if(d.length>=Tn)break;d.includes(l)||d.push(l)}return d}function Br(t,s,a=""){const d=Array.from(new Set(t)),l=Jn(a,d),u=[s,"src/data-app/index.tsx","src/data-app/styles.css","src/data-app/format.ts","src/data-app/types.ts",...l,"src/App.tsx","src/index.css","src/lib/utils.ts"].filter(g=>!!g),h=[];for(const g of u){if(h.length>=Rt)break;d.includes(g)&&!h.includes(g)&&h.push(g)}for(const g of d){if(h.length>=Rt)break;h.includes(g)||/^src\/components\/ui\//.test(g)||/^src\/data-app\//.test(g)&&h.push(g)}return h.length>0?h:d.slice(0,Rt)}function Jn(t,s){const a=t.toLowerCase(),d=s.filter(u=>u.startsWith("src/components/ui/"));if(/\b(shadcn|component|components|ui)\b/.test(a))return d;const l=[["select","src/components/ui/select.tsx"],["dropdown","src/components/ui/select.tsx"],["filter","src/components/ui/select.tsx"],["progress","src/components/ui/progress.tsx"],["calendar","src/components/ui/calendar.tsx"],["date picker","src/components/ui/calendar.tsx"],["datepicker","src/components/ui/calendar.tsx"],["card","src/components/ui/card.tsx"],["table","src/components/ui/table.tsx"],["chart","src/components/ui/chart.tsx"],["badge","src/components/ui/badge.tsx"],["button","src/components/ui/button.tsx"]].filter(([u])=>a.includes(u)).map(([,u])=>u);return Array.from(new Set(l)).filter(u=>s.includes(u))}function _n(){return Mn.map(t=>({...t}))}function Bt(t){var a,d,l,u,h;return[t.error,(a=t.writePolicyValidation)==null?void 0:a.diagnostics.join(`
`),(d=t.importValidation)==null?void 0:d.diagnostics.join(`
`),(l=t.dataApiValidation)==null?void 0:l.diagnostics.join(`
`),(u=t.command)==null?void 0:u.stdout,(h=t.command)==null?void 0:h.stderr,...(t.attempts||[]).flatMap(g=>[g.command.stdout,g.command.stderr])].filter(Boolean).join(`

`).trim()||"Validation failed without diagnostics."}function Vn(t){return/\b(type\s*script|typescript|tsc|typecheck|compile|compiler)\b/i.test(t)}function Pt(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(t<1e4?1:0)}s`}function Un(t){const s={children:[]};for(const d of t){const l=d.path.split("/").filter(Boolean);let u=s,h="";l.forEach((g,N)=>{h=h?`${h}/${g}`:g;const f=N===l.length-1;let R=u.children.find(j=>j.name===g&&j.type===(f?"file":"directory"));R||(R={name:g,path:h,type:f?"file":"directory",size:f?d.size:void 0,children:[]},u.children.push(R)),u=R})}function a(d){d.children.sort((l,u)=>l.type!==u.type?l.type==="directory"?-1:1:l.name.localeCompare(u.name)),d.children.forEach(a)}return a(s),s.children}function Gn(t){return{idle:"Working through your request",context:"Reading app context",thinking:"Thinking through the request","inspecting-data":"Inspecting Semaphor data","reading-files":"Reading requested files",generating:"Generating source changes",planning:"Planning the changes"}[t]}function Kn(t){return{idle:"Preparing the next step.",context:"Reading the app and figuring out what to change.",thinking:"Deciding whether this needs an answer, file inspection, or edits.","inspecting-data":"Reading project data and dataset fields.","reading-files":"Loading source files the model asked to inspect.",generating:"Writing a bounded source revision.",planning:"Mapping your request to file edits."}[t]}function Qn(t){var d,l,u;const s=typeof t.message=="string"?t.message.trim():"";if(s)return s;const a=(u=(l=(d=t.revision)==null?void 0:d.plan)==null?void 0:l.files)==null?void 0:u.length;return a?`Yes - I'll make that change across ${a} file${a===1?"":"s"}, then run validation so you can review it.`:"Yes - I'll inspect the app context, make the change, and run validation so you can review it."}function Tr(t){return t.type==="screenshot"?`Screenshot attachment: ${t.name}`:[`DOM selection attachment: ${t.name}`,t.text.slice(0,1600)].join(`
`)}function qn(t){const s=t.slice(0,3).map(d=>d.split("/").pop()||d),a=t.length>s.length?` +${t.length-s.length} more`:"";return`${s.join(", ")}${a}`}function Xn(t){var d,l,u,h,g;if(t.type==="user"){const N=(t.attachments||[]).map(Tr).join(`

`);return{role:"user",content:[t.content,N].filter(Boolean).join(`

`).slice(0,2200)}}if(t.type==="assistant")return{role:"assistant",content:t.content.slice(0,1800)};const s=(l=(d=t.result)==null?void 0:d.changedFiles)!=null&&l.length?t.result.changedFiles.join(", "):"none",a=(g=(h=(u=t.result)==null?void 0:u.filePlan)==null?void 0:h.files)==null?void 0:g.map(N=>`${N.action}:${N.path}`).join(", ");return{role:"system",content:[`Build run ${t.status} for: ${t.prompt}`,`Changed files: ${s}`,a?`File plan: ${a}`:"",t.error?`Error: ${t.error}`:""].filter(Boolean).join(`
`).slice(0,2e3)}}function Oe(t){var h;const s=Array.isArray(t==null?void 0:t.sources)?t.sources:[],a=Array.isArray(t==null?void 0:t.inputs)?t.inputs:[],d=Array.isArray(t==null?void 0:t.views)?t.views:[],l=Array.isArray(t==null?void 0:t.interactions)?t.interactions:[],u=Array.isArray((h=t==null?void 0:t.layout)==null?void 0:h.sections)?t.layout.sections:[];return!!(t&&(s.length>0||a.length>0||d.length>0||l.length>0||u.length>0))}function Yn(t){var d;const s=(d=t==null?void 0:t.semaphor)==null?void 0:d.intentManifest;if(!s||typeof s!="object")return null;const a=s;return a.schemaVersion==="data-app-intent/v1"&&a.app&&Array.isArray(a.sources)&&Array.isArray(a.inputs)&&Array.isArray(a.views)?a:null}function Zn(t){const s=t.dataAppVersions||[];return s.find(a=>a.version===0&&a.status==="draft")||t.currentDataAppVersion||s.find(a=>a.status==="ready")||null}function es(t,s){var l,u,h;const a=(l=t.bridgeWorkspaceHint)==null?void 0:l.trim();if(a)return a;const d=(h=(u=t.sourceSnapshot)==null?void 0:u.metadata)==null?void 0:h.projectRoot;return typeof d=="string"&&d.trim()?d.trim():s}function ts(t){return JSON.stringify({schemaVersion:t.schemaVersion,files:[...t.files].map(s=>({path:s.path,contents:s.contents,hash:s.hash??null})).sort((s,a)=>s.path.localeCompare(a.path))})}async function Dr(t){const s=await window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(s)).map(a=>a.toString(16).padStart(2,"0")).join("")}function $r(t){return t.replace(/\\/g,"/").split("/").filter(Boolean).pop()}async function rs({snapshot:t,workspaceContext:s,projectDir:a,adapter:d}){const l=s.projectRoot||a;return{schemaVersion:"data-app-source-revision/v1",snapshotHash:await Dr(ts(t)),workspace:{adapter:d,...$r(l)?{rootName:$r(l)}:{},pathHash:await Dr(l)},collectedAt:new Date().toISOString()}}function Ze(t,s){const a=new Map;for(const d of t)a.set(d.id,d);for(const d of s)a.set(d.id,d);return Array.from(a.values())}function ns(t,s){return!s||!Oe(s)?t:!t||!Oe(t)?s:{schemaVersion:"data-app-intent/v1",app:{title:s.app.title||t.app.title,description:s.app.description||t.app.description,goal:s.app.goal||t.app.goal},sources:Ze(t.sources,s.sources),inputs:Ze(t.inputs,s.inputs),views:Ze(t.views,s.views),interactions:t.interactions||s.interactions?Ze(t.interactions||[],s.interactions||[]):void 0,layout:s.layout||t.layout}}function Pr(t,s){var N,f,R,j,B,b,E,z,L;const a=t.slice(-12).map(Xn),d=t.slice().reverse().find(F=>{var W;return F.type==="run"&&F.status==="done"&&((W=F.result)==null?void 0:W.ok)===!0}),l=t.slice().reverse().find(F=>{var W;return F.type==="user"&&!!((W=F.attachments)!=null&&W.length)}),u=(N=t.slice().reverse().find(F=>F.type==="assistant"&&!!F.operation))==null?void 0:N.operation,h=(Oe(s)?s:void 0)||((f=t.slice().reverse().find(F=>F.type==="assistant"&&Oe(F.intentManifest)))==null?void 0:f.intentManifest),g=[(R=l==null?void 0:l.attachments)!=null&&R.length?["Most recent selected/attached target:",...l.attachments.map(Tr)].join(`
`):"",(B=(j=d==null?void 0:d.result)==null?void 0:j.changedFiles)!=null&&B.length?`Last successful edit changed: ${d.result.changedFiles.join(", ")}`:"",u?`Last app-builder operation: ${u.type}${(b=u.target)!=null&&b.label?` on ${u.target.label}`:""}`:""].filter(Boolean);return{messages:a,activeTarget:g.join(`

`)||void 0,lastSuccessfulRun:d?{prompt:d.prompt,changedFiles:((E=d.result)==null?void 0:E.changedFiles)||[],summary:(z=d.result)==null?void 0:z.summary,filePlan:(L=d.result)==null?void 0:L.filePlan}:void 0,lastOperation:u,intentManifest:h||void 0}}function ss({files:t,selectedPath:s,onSelect:a}){const d=p.useMemo(()=>Un(t),[t]);return d.length===0?e.jsx("div",{className:"rounded-[5px] border border-border bg-background p-2 text-[11px] text-muted-foreground",children:"No browser files loaded yet."}):e.jsx("div",{className:"space-y-0.5",children:d.map(l=>e.jsx(Er,{node:l,depth:0,selectedPath:s,onSelect:a},l.path||l.name))})}function Er({node:t,depth:s,selectedPath:a,onSelect:d}){const l=t.type==="directory",u=a===t.path;return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",disabled:l,onClick:()=>d(t.path),className:`flex w-full items-center gap-1.5 rounded-[4px] py-1.5 pr-2 text-left font-mono text-[11px] ${u?"bg-background text-foreground":l?"cursor-default text-foreground":"text-muted-foreground hover:bg-background hover:text-foreground"}`,style:{paddingLeft:`${8+s*14}px`},children:[l?e.jsxs(e.Fragment,{children:[e.jsx(y.ChevronRight,{className:"h-3 w-3 rotate-90 text-muted-foreground"}),e.jsx(Bn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-3 w-3"}),e.jsx(y.CodeXml,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.name}),!l&&e.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:t.size})]}),l&&t.children.map(h=>e.jsx(Er,{node:h,depth:s+1,selectedPath:a,onSelect:d},h.path))]})}function as({manifest:t}){if(!t)return null;const s=t.packages.filter(d=>d.status==="supported").length,a=t.packages.length-s;return e.jsxs("div",{className:"mt-2 rounded-[5px] border border-border bg-background px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:t.name}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[t.moduleSystem," · ",t.cssPipeline.status]})]}),e.jsx("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:t.execution})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5 text-[10.5px] text-muted-foreground",children:[e.jsxs("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5",children:[t.components.length," components"]}),e.jsxs("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5",children:[s," packages"]}),a>0?e.jsxs("span",{className:"rounded-[4px] bg-amber-50 px-1.5 py-0.5 text-amber-700",children:[a," partial"]}):null]})]})}function os({plan:t,changedFiles:s}){const a=new Set(s||[]),d=(t==null?void 0:t.files)||[],l=(s||[]).filter(u=>!d.some(h=>h.path===u));return d.length===0&&l.length===0?null:e.jsxs("div",{className:"mt-2 rounded-[5px] border border-white/70 bg-background/60 p-2",children:[t!=null&&t.intent?e.jsx("div",{className:"mb-1.5 text-[11px] font-medium text-foreground",children:t.intent}):null,e.jsxs("div",{className:"space-y-1",children:[d.map(u=>e.jsxs("div",{className:"flex items-start justify-between gap-2 rounded-[4px] bg-background/70 px-2 py-1",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-mono text-[11px] text-foreground",children:u.path}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[10.5px] text-muted-foreground",children:u.purpose})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx("span",{className:"rounded-[4px] bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-muted-foreground",children:u.action}),a.has(u.path)?e.jsx("span",{className:"rounded-[4px] bg-emerald-50 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-emerald-700",children:"changed"}):null]})]},u.path)),l.map(u=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-[4px] bg-background/70 px-2 py-1",children:[e.jsx("span",{className:"min-w-0 truncate font-mono text-[11px] text-foreground",children:u}),e.jsx("span",{className:"rounded-[4px] bg-emerald-50 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-[0.04em] text-emerald-700",children:"changed"})]},u))]})]})}function is({projectId:t,projectName:s,dataAppId:a,apiServiceUrl:d,adapters:l}){var j,B;const u=p.useContext(y.SemaphorContext),h=typeof window>"u"?void 0:window.location.origin,g=d||((j=u.tokenProps)==null?void 0:j.apiServiceUrl)||h,N=(B=u.authToken)==null?void 0:B.accessToken,[f,R]=p.useState(()=>ue("builder-session"));return e.jsx("main",{className:"flex h-full min-h-0 w-full min-w-0 flex-1 flex-col self-stretch bg-muted/40 text-foreground",children:e.jsx(ls,{adapters:l,apiServiceUrl:g,accessToken:N,initialDataAppId:a||null,initialPrompt:"",path:"bridge",projectId:t,projectName:s,onRestart:()=>R(ue("builder-session"))},f)})}function ls({adapters:t,apiServiceUrl:s,accessToken:a,initialDataAppId:d,initialPrompt:l,path:u,projectId:h,projectName:g,onRestart:N}){var vr,jr;const[f,R]=p.useState(At),[j,B]=p.useState(Cr),[b,E]=p.useState(Ct),[z,L]=p.useState(!1),[F,W]=p.useState(At),[ge,q]=p.useState(0),[A]=p.useState(u),[Le,et]=p.useState(l||""),[tt,Ie]=p.useState([]),[Ne,Ae]=p.useState([]),[X,pe]=p.useState([]),[Mt,ze]=p.useState(null),[Y,We]=p.useState(!1),[Z,Tt]=p.useState(!1),[Ce,Or]=p.useState(!0),[Lr,ne]=p.useState("idle"),[Ir,se]=p.useState(null),[Et,Ot]=p.useState(null),[Lt,He]=p.useState(()=>Date.now()),[Re,It]=p.useState(null),[rt,zr]=p.useState("gpt-5.5-low"),Q=p.useRef(null),U=p.useRef(null),nt=p.useRef([]),st=p.useRef(null),at=p.useRef(null),zt=p.useRef(null),[he,be]=p.useState(!1),[Wt,ae]=p.useState(null),[Ht,ot]=p.useState(!1),[Jt,_t]=p.useState(!1),[Be,it]=p.useState("idle"),[Vt,Ut]=p.useState(null),[Wr,Gt]=p.useState(""),[Hr,Kt]=p.useState([]),[lt,Qt]=p.useState([]),[dt,qt]=p.useState(null),[Xt,Jr]=p.useState([]),[_r,Vr]=p.useState(null),[ct,Yt]=p.useState(null),[ut,Zt]=p.useState(null),[me,Je]=p.useState(d||null),[_e,pt]=p.useState("idle"),[er,ht]=p.useState("idle"),[tr,rr]=p.useState(null),[nr,sr]=p.useState(null),[mt,we]=p.useState(null),[oe,H]=p.useState(null),[ar,Ve]=p.useState(null),[Ue,ft]=p.useState(null),[xt,Ge]=p.useState(!1),[gt,or]=p.useState(""),[ir,bt]=p.useState(null),[lr,dr]=p.useState(!1),De=p.useRef(null),wt=p.useRef(null),ye=p.useRef(null),cr=(t==null?void 0:t.readStatus)||On,Ke=(t==null?void 0:t.runTurn)||Ln,yt=(t==null?void 0:t.saveDraft)||zn,Ur=(t==null?void 0:t.loadApp)||Wn,vt=(t==null?void 0:t.publish)||Hn,J=p.useMemo(()=>En(rt),[rt]),Gr=p.useMemo(()=>X.find(r=>r.type==="run"&&r.id===Mt),[Mt,X]),jt=p.useMemo(()=>[...X].reverse().find(r=>r.type==="run"),[X]),St=p.useMemo(()=>{const r=F.includes("?")?"&":"?";return`${F}${r}dataAppBuilderRefresh=${ge}`},[F,ge]);p.useEffect(()=>{const r=window.setInterval(()=>He(Date.now()),500);return()=>window.clearInterval(r)},[]),p.useEffect(()=>{nt.current=X},[X]),p.useEffect(()=>{if(!xt)return;const r=()=>{Ge(!1)};return window.addEventListener("blur",r),()=>{window.removeEventListener("blur",r)}},[xt]),p.useEffect(()=>{L(!1);const r=window.localStorage.getItem(ce(kr,h))||At,n=window.localStorage.getItem(ce(Nr,h))||Cr,i=window.localStorage.getItem(ce(Ar,h))||Ct,o=window.localStorage.getItem(ce(Sr,h));if(R(r),W(r),B(n),E(i),L(!0),o)try{pe(JSON.parse(o))}catch{pe([])}},[h]),p.useEffect(()=>{window.localStorage.setItem(ce(kr,h),f)},[f,h]),p.useEffect(()=>{window.localStorage.setItem(ce(Nr,h),j)},[j,h]),p.useEffect(()=>{window.localStorage.setItem(ce(Ar,h),b)},[b,h]),p.useEffect(()=>{var r;window.localStorage.setItem(ce(Sr,h),JSON.stringify(X.map(xs))),(r=st.current)==null||r.scrollTo({top:st.current.scrollHeight,behavior:"smooth"})},[X,h]),p.useEffect(()=>{ye.current=ct},[ct]);const kt=p.useCallback(async r=>{if(A!=="bridge"||!s)return;const n=j.replace(/\/$/,""),i=await fetch(`${n}/runtime-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({accessToken:a||null,apiBaseUrl:s,dataApiBaseUrl:s,dataAppId:me,projectId:h})}),o=await O(i,"Local bridge /runtime-context");if(!i.ok||!o.ok)throw new Error(o.error||"Bridge could not sync runtime context.")},[a,s,j,me,h,A]);p.useEffect(()=>{if(A!=="bridge"||!s)return;const r=new AbortController;return kt(r.signal).then(()=>{q(n=>n+1)}).catch(n=>{r.signal.aborted||(ot(!1),ae(n instanceof Error?n.message:"Bridge could not sync runtime context."))}),()=>r.abort()},[s,A,kt]),p.useEffect(()=>{Je(d||null)},[d]),p.useEffect(()=>{if(!d||!z||wt.current===`${d}:${A}:${b}`)return;const r=new AbortController;return wt.current=`${d}:${A}:${b}`,we(null),H({state:"running",label:"Opening Data App",detail:"Loading the saved Data App draft from Semaphor."}),(async()=>{var n,i;try{const o=await Ur({dataAppId:d},{apiServiceUrl:s,accessToken:a,signal:r.signal});if(r.signal.aborted)return;Je(o.id);const c=Zn(o);if(!c){H({state:"done",label:"Data App opened",detail:"No saved source snapshot exists yet."});return}const m=Yn(c.manifest);m&&ft(m),c.status==="draft"?rr(c.updatedAt||null):c.status==="ready"&&sr(c.updatedAt||null);const S=es(c,b);let w=!1;if(A==="bridge"&&((i=(n=c.sourceSnapshot)==null?void 0:n.files)!=null&&i.length)&&(H({state:"running",label:"Restore saved source",detail:"Comparing the saved source snapshot with the bridge workspace."}),w=await gn({snapshot:c.sourceSnapshot,targetProjectDir:S,signal:r.signal}),w&&q(C=>C+1)),A==="bridge"&&S!==b&&E(S),r.signal.aborted)return;H({state:"done",label:"Data App opened",detail:w?"Saved source was restored into the bridge workspace.":"Saved draft metadata was loaded."})}catch(o){if(r.signal.aborted)return;const c=o instanceof Error?o.message:String(o);wt.current=null,we(c),H({state:"failed",label:"Open Data App failed",detail:c}),M(`Open Data App failed: ${c}`,"blocked")}})(),()=>r.abort()},[z,d,b,A]),p.useEffect(()=>{function r(n){var c;if(n.source!==((c=at.current)==null?void 0:c.contentWindow))return;const i=n.data;if((i==null?void 0:i.source)!=="semaphor-dev-bridge-inspector")return;if(i.type==="ready"&&he){Xe("inspect-enable");return}if(i.type==="enabled"){ae("Click an element in the preview. Press Esc to cancel.");return}if(i.type==="disabled"){be(!1);return}if(i.type!=="selection"||!i.payload)return;const o=an(i.payload);Ie(m=>[...m,o]),be(!1),ae(`Selected ${o.name}. Add a message and send it.`)}return window.addEventListener("message",r),()=>window.removeEventListener("message",r)},[he]),p.useEffect(()=>{be(!1),ot(!1),ae(null)},[j,b,A]),p.useEffect(()=>{if(Y||Z||Ne.length===0)return;const[r,...n]=Ne;Ae(n),hr(r)},[Y,Z,Ne]),p.useEffect(()=>{let r=!1;const n=new AbortController;async function i(){try{const o=await cr({apiServiceUrl:s,accessToken:a,signal:n.signal});r||It(o)}catch(o){r||It({ok:!1,error:o instanceof Error?o.message:String(o)})}}return i(),()=>{r=!0}},[a,s,cr]);const Qe=p.useCallback(async(r=U.current)=>{if(!r)return;const n=await r.compileBrowserSandboxPreviewHtml();Gt(n.html),Kt(n.diagnostics),Qt(n.warnings||[]),qt(n.cssMode||null),q(i=>i+1)},[]),$e=p.useCallback((r=U.current,n=ye.current)=>{var m;if(!r)return;const i=r.listBrowserSandboxFiles(),o=r.readBrowserSandboxWorkspaceContext(),c=n&&i.some(S=>S.path===n)?n:((m=i[0])==null?void 0:m.path)||null;Jr(i),Vr(o.runtimeManifest||null),Yt(c),ye.current=c,Zt(c&&r.readBrowserSandboxFiles([c])[0]||null)},[]);p.useEffect(()=>{if(A!=="browser")return;let r=!1;async function n(){it("loading"),Ut(null),window.__SEMAPHOR_BROWSER_SANDBOX_VENDOR__={React:An,ReactDOMClient:Cn};try{const i=await Ye.loadSemaphorBrowserRuntime();if(r)return;U.current=i,it("ready"),await Qe(i),$e(i)}catch(i){if(r)return;it("failed"),Ut(i instanceof Error?i.message:String(i))}}return n(),()=>{r=!0}},[A,$e,Qe]);function Kr(r){const n=U.current;Yt(r),ye.current=r,Zt(n&&n.readBrowserSandboxFiles([r])[0]||null)}async function ur(){const r=U.current;!r||Y||(r.resetBrowserSandbox(),await Qe(r),$e(r),M("Browser Sandbox reset to the approved starter template. Existing generated browser files were replaced in local browser storage.","guidance"))}async function Qr(){if(Y||Z)return;if(ft(null),Ve(null),or(""),bt(null),A==="browser"){await ur();return}const r=new AbortController,n=j.replace(/\/$/,"");try{H({state:"running",label:"Resetting app",detail:"Restoring the local workspace to the blank Data App template."});const i=await fetch(`${n}/reset-app`,{method:"POST",signal:r.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),o=await O(i,"Local bridge /reset-app");if(!i.ok||!o.ok)throw new Error(o.error||"Bridge could not reset the app.");W(f),q(c=>c+1),H({state:"done",label:"App reset",detail:"Blank template restored and typecheck passed."}),M("Reset the local app to the blank Data App template. You can start a new build from here.","guidance")}catch(i){const o=i instanceof Error?i.message:String(i);H({state:"failed",label:"Reset failed",detail:o}),M(`Reset failed: ${o}`,"blocked")}}function qr(r){const n=r.durationMs??0;return r.state!=="running"||!r.startedAt?n:n+Math.max(0,Lt-r.startedAt)}function Xr(r,n,i){const o=r.durationMs??0;return r.state!=="running"&&n.state==="running"?{...n,startedAt:i,durationMs:o}:r.state==="running"&&n.state!=="running"?{...n,startedAt:void 0,durationMs:o+Math.max(0,i-(r.startedAt??i))}:{...n,startedAt:r.startedAt,durationMs:o}}function Yr(r,n,i){const o=Date.now();He(o),pe(c=>c.map(m=>{if(m.type!=="run"||m.id!==r)return m;const S=n(m.steps),w=new Map(m.steps.map(C=>[C.id,C]));return{...m,...i,steps:S.map(C=>{const v=w.get(C.id);return v?Xr(v,C,o):C})}}))}function qe(r,n){pe(i=>i.map(o=>o.type==="run"&&o.id===r?{...o,...n}:o))}function M(r,n="default",i){const o=Oe(i==null?void 0:i.intentManifest)?i==null?void 0:i.intentManifest:void 0;pe(c=>[...c,{id:ue("assistant"),type:"assistant",content:r,createdAt:Date.now(),tone:n,artifacts:i==null?void 0:i.artifacts,operation:i==null?void 0:i.operation,intentManifest:o}])}function Zr(r){var i;r.intentManifest&&ft(o=>ns(o,r.intentManifest));const n=(i=r.artifacts)==null?void 0:i.find(o=>o.type==="dataset_inspector");n&&Ve(n)}function pr(r){ne({received:"context",authenticating:"context",routing:"thinking",inspecting_data:"inspecting-data",reading_files:"reading-files",planning_revision:"planning",generating_code:"generating",done:"thinking"}[r.phase]),se(r.detail||r.label)}function hr(r){const n=r.prompt.trim();if(!n)return;const i=Date.now();pe(o=>[...o,{id:ue("user"),type:"user",content:n,createdAt:i,attachments:r.attachments}]),Ot(i),ne("context"),se("Preparing app context and available files."),vn({...r,prompt:n})}async function en(r){if(!r.type.startsWith("image/")){M("Only image attachments are supported right now.","blocked");return}if(r.size>6*1024*1024){M("That screenshot is larger than 6MB. Please attach a smaller image.","blocked");return}const n=await new Promise((i,o)=>{const c=new FileReader;c.onload=()=>{typeof c.result=="string"?i(c.result):o(new Error("Could not read image attachment."))},c.onerror=()=>o(c.error||new Error("Could not read image attachment.")),c.readAsDataURL(r)});Ie(i=>[...i,{id:ue("attachment"),type:"screenshot",name:r.name||"Screenshot",imageUrl:n,mediaType:r.type,createdAt:Date.now()}])}function tn(r){Ie(n=>n.filter(i=>i.id!==r))}function Xe(r){var i,o;let n="*";try{n=new URL(St).origin}catch{n="*"}(o=(i=at.current)==null?void 0:i.contentWindow)==null||o.postMessage({source:"semaphor-data-app-builder",type:r},n)}async function rn(){const r=j.replace(/\/$/,""),n=await fetch(`${r}/inspect/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),i=await O(n,"Local bridge /inspect/install");if(!n.ok||!i.ok)throw new Error(i.error||"Bridge could not install inspector.");return i}async function nn(){if(A!=="bridge"){M("Element inspection is only available in Local Bridge mode right now.","blocked");return}try{_t(!0),ae(Ht?null:"Preparing element inspector…");let r=!1;if(!Ht){const n=await rn();ot(!!n.installed),r=!!n.changed}be(!0),ae(r?"Loading inspector in the preview…":"Click an element in the preview. Press Esc to cancel."),r?(W(f),q(n=>n+1)):window.setTimeout(()=>Xe("inspect-enable"),50)}catch(r){be(!1),ae(null),M(r instanceof Error?r.message:String(r),"blocked")}finally{_t(!1)}}function sn(){be(!1),ae(null),Xe("inspect-disable")}function an(r){const n=(v,k="")=>typeof v=="string"&&v.trim()?v.trim():k,i=v=>Array.isArray(v)?v.map(k=>typeof k=="string"?k:k&&typeof k=="object"?JSON.stringify(k):"").filter(Boolean):[],o=n(r.elementLabel)||n(r.name),c=n(r.component),m=o&&c&&o!==c?`${o} in ${c}`:o||c||n(r.tagName,"Selected element"),S=i(r.reactOwners),w=i(r.sourceHints),C=[`Clicked element: ${o||m}`,`Nearest component: ${c||"unavailable"}`,`Tag: ${n(r.tagName,"unknown")}`,`Role: ${n(r.role,"none")}`,`Selector: ${n(r.selector,"none")}`,S.length?`React owner stack: ${S.join(" > ")}`:"React owner stack: unavailable",w.length?`Source hints: ${w.join(" | ")}`:"Source hints: unavailable",`Bounds: ${JSON.stringify(r.bounds||{})}`,`Ancestors: ${i(r.ancestorSummary).join(" > ")||"none"}`,`Classes: ${n(r.classes,"none")}`,"","Visible text:",n(r.text,"(no visible text)"),"","HTML excerpt:",n(r.htmlExcerpt,"(no HTML excerpt)")].join(`
`);return{id:ue("attachment"),type:"dom-selection",name:m,text:C,createdAt:Date.now()}}function on(r,n){Ae(i=>i.map(o=>o.id===r?{...o,prompt:n}:o))}function ln(r){Ae(n=>n.filter(i=>i.id!==r))}function dn(r,n){Ae(i=>i.map(o=>o.id===r?{...o,attachments:o.attachments.filter(c=>c.id!==n)}:o))}async function mr(r){for(const n of Array.from(r))await en(n)}function fr(r,n){var c;const i=n==="browser"?"Browser Sandbox":"Local Bridge",o=(c=r.changedFiles)!=null&&c.length?r.changedFiles.join(", "):"no files";return r.ok?`${i} applied the revision and validation passed. Changed files: ${o}. The preview has been refreshed; inspect the file tree and run card for the exact file plan.`:`${i} could not finish the revision cleanly. Changed files: ${o}. The run card includes the validation output so you can ask a follow-up repair question or switch runtimes.`}function G(r,n){Yr(r,i=>i.map(o=>{if(n==="failed")return{...o,state:o.state==="running"?"blocked":o.state};const c={reading:[],generating:["context"],writing:["context","generate"],typechecking:["context","generate","edit"],repairing:["context","generate","edit","typecheck"],complete:["context","generate","edit","typecheck","repair","preview"]},S={reading:"context",generating:"generate",writing:"edit",typechecking:"typecheck",repairing:"repair"}[n];return{...o,state:c[n].includes(o.id)?"done":S===o.id?"running":o.state==="done"?"done":"idle"}}))}async function cn(r,n,i){var S,w,C,v;(S=Q.current)==null||S.abort();const o=new AbortController,c=Date.now();Q.current=o,We(!0),ze(n),He(c),G(n,"reading");const m=window.setTimeout(()=>{o.abort()},18e4);try{let k=U.current;k||(k=await Ye.loadSemaphorBrowserRuntime(),U.current=k);const I=k.readBrowserSandboxWorkspaceContext(),D=(C=(w=I.files)==null?void 0:w.editable)!=null&&C.length?Br(I.files.editable,ye.current,r):["src/App.tsx"],ie=k.readBrowserSandboxFiles(D),ve=ie.reduce((te,ee)=>te+ee.contents.length,0);let je=ie,Pe=[],le=i,K=null;const de=[];for(let te=0;te<Te;te+=1){const ee=Pe.length>0||te>0,Fe=ee?`repair-${te+1}`:"initial";G(n,ee?"repairing":"generating");const _=le||(await Ke({projectId:h,message:r,currentFiles:je,workspaceContext:I,diagnostics:Pe,repair:ee,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(le=void 0,!_)throw new Error("Data App Builder did not return a revision.");G(n,"writing");const fe=k.applyBrowserSandboxRevision({..._,attemptLabel:Fe});de.push(...fe.attempts||[]),G(n,"typechecking");let $={...fe,attempts:[...de],filePlan:_.plan,telemetry:{contextFileCount:ie.length,contextChars:ve,generatedFileCount:_.files.length,generatedChars:_.files.reduce((P,V)=>P+V.contents.length,0),repairAttempts:de.filter(P=>P.label.startsWith("repair")).length}};if(fe.ok){const P=await k.compileBrowserSandboxPreviewHtml();if(Gt(P.html),Kt(P.diagnostics),Qt(P.warnings||[]),qt(P.cssMode||null),q(V=>V+1),$e(k),P.diagnostics.length>0){const V={command:"browser sandbox preview compile",durationMs:0,exitCode:1,ok:!1,stdout:"",stderr:P.diagnostics.join(`
`)};$={...$,ok:!1,validation:"typecheck",command:V,attempts:[...de,{label:Fe,ok:!1,command:V}],error:"Generated files failed Browser Sandbox preview compile."}}}if(K=$,$.ok||te===Te-1)break;const T=(v=$.changedFiles)!=null&&v.length?$.changedFiles:_.files.map(P=>P.path);je=k.readBrowserSandboxFiles(Array.from(new Set([...D,...T]))),Pe=[Bt($)]}if(!K)throw new Error("The browser runtime loop ended without a validation result.");G(n,K.ok?"complete":"failed"),qe(n,{status:K.ok?"done":"failed",result:K,error:K.error,finishedAt:Date.now()}),M(fr(K,"browser"),K.ok?"default":"blocked")}catch(k){const I=k instanceof DOMException&&k.name==="AbortError",D=I?"Timed out waiting for the browser runtime loop.":k instanceof Error?k.message:String(k);qe(n,{status:I?"cancelled":"failed",error:D,result:{ok:!1,error:D,summary:"The app-builder/browser runtime loop stopped before validation completed."},finishedAt:Date.now()}),M(`Browser Sandbox stopped before it could validate the app: ${D}`,"blocked"),G(n,"failed")}finally{We(!1),ze(null),Q.current=null,window.clearTimeout(m)}}async function un(r,n,i){var S,w,C,v;(S=Q.current)==null||S.abort();const o=new AbortController,c=Date.now();Q.current=o,We(!0),ze(n),He(c),G(n,"reading");const m=window.setTimeout(()=>{o.abort()},18e4);try{const k=j.replace(/\/$/,""),I=async $=>{const T=await fetch(`${k}/read-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:$,projectDir:b})}),P=await O(T,"Local bridge /read-files");if(!T.ok||!P.ok||!P.files)throw new Error(P.error||"Bridge could not read target files.");return P.files},D=async()=>{const $=await fetch(`${k}/workspace-context`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),T=await O($,"Local bridge /workspace-context");if(!$.ok||!T.ok||!T.workspaceContext)throw new Error(T.error||"Bridge could not read workspace context.");return T.workspaceContext};let ie=i;const ve=async({currentFiles:$,workspaceContext:T,diagnostics:P=[],repair:V=!1})=>{const re=ie||(await Ke({projectId:h,message:r,currentFiles:$,workspaceContext:T,diagnostics:P,repair:V,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal})).revision;if(ie=void 0,!re)throw new Error("Data App Builder did not return a revision.");return re},je=async $=>{const T=await fetch(`${k}/apply-files`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:$,projectDir:b})}),P=await O(T,"Local bridge /apply-files");if(!T.ok&&!P.command&&!P.writePolicyValidation&&!P.importValidation&&!P.dataApiValidation)throw new Error(P.error||"Bridge could not apply generated files.");return P},Pe=async()=>{const $=await fetch(`${k}/validate-typecheck`,{method:"POST",signal:o.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),T=await O($,"Local bridge /validate-typecheck");if(!$.ok&&!T.command)throw new Error(T.error||"Bridge could not typecheck the target app.");return T},le=await D();le.projectRoot&&E(le.projectRoot);let K=(C=(w=le.files)==null?void 0:w.editable)!=null&&C.length?Rr(le.files.editable):["src/App.tsx"];const de=await I(K),te=de.reduce(($,T)=>$+T.contents.length,0);let ee=[];if(Vn(r)){const $=await Pe();$.ok||(ee=[Bt($)])}let Fe=de,_=null;const fe=[];for(let $=0;$<Te;$+=1){const T=ee.length>0||$>0,P=T?`repair-${$+1}`:"initial";G(n,T?"repairing":"generating");const V=await ve({currentFiles:Fe,workspaceContext:le,diagnostics:ee,repair:T});G(n,"writing");const re=await je({...V,attemptLabel:P});if(W(f),q(Me=>Me+1),fe.push(...re.attempts||[]),_={...re,attempts:[...fe],filePlan:V.plan,telemetry:{contextFileCount:de.length,contextChars:te,generatedFileCount:V.files.length,generatedChars:V.files.reduce((Me,Sn)=>Me+Sn.contents.length,0),repairAttempts:fe.filter(Me=>Me.label.startsWith("repair")).length}},G(n,"typechecking"),re.ok||$===Te-1)break;Fe=(((v=re.changedFiles)==null?void 0:v.length)||0)>0?await I(K=Array.from(new Set([...K,...re.changedFiles||[]]))):V.files,ee=[Bt(re)]}if(!_)throw new Error("The app-builder loop ended without a validation result.");G(n,_.ok?"complete":"failed"),qe(n,{status:_.ok?"done":"failed",result:_,error:_.error,finishedAt:Date.now()}),M(fr(_,"bridge"),_.ok?"default":"blocked")}catch(k){const I=k instanceof DOMException&&k.name==="AbortError",D=I?"Timed out waiting for the app-builder/bridge loop. The target app may still have updated through HMR.":k instanceof Error?k.message:String(k);qe(n,{status:I?"cancelled":"failed",error:D,result:{ok:!1,error:D,summary:"The app-builder/bridge loop stopped before validation completed."},finishedAt:Date.now()}),M(`Local Bridge stopped before it could validate the app: ${D}`,"blocked"),G(n,"failed")}finally{We(!1),ze(null),Q.current=null,window.clearTimeout(m)}}async function pn(r){var c,m;let n=U.current;n||(n=await Ye.loadSemaphorBrowserRuntime(),U.current=n);const i=n.readBrowserSandboxWorkspaceContext(),o=(m=(c=i.files)==null?void 0:c.editable)!=null&&m.length?Br(i.files.editable,ye.current,r):["src/App.tsx"];return{currentFiles:n.readBrowserSandboxFiles(o),workspaceContext:i}}async function hn(r){const n=U.current;return n?n.readBrowserSandboxFiles(r):[]}async function Nt(r,n){const i=j.replace(/\/$/,""),o=await fetch(`${i}/read-files`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:r,projectDir:b})}),c=await O(o,"Local bridge /read-files");if(!o.ok||!c.ok||!c.files)throw new Error(c.error||"Bridge could not read requested files.");return c.files}function mn(r,n){const i=new Map;for(const o of r)i.set(o.path,o);for(const o of n)i.set(o.path,o);return Array.from(i.values())}async function xr(r){var S,w;await kt(r);const n=j.replace(/\/$/,""),i=await fetch(`${n}/workspace-context`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),o=await O(i,"Local bridge /workspace-context");if(!i.ok||!o.ok||!o.workspaceContext)throw new Error(o.error||"Bridge could not read workspace context.");const c=o.workspaceContext;c.projectRoot&&E(c.projectRoot);const m=(w=(S=c.files)==null?void 0:S.editable)!=null&&w.length?Rr(c.files.editable):["src/App.tsx"];return{currentFiles:await Nt(m,r),workspaceContext:c}}function gr(r,n){return{schemaVersion:"data-app/v1",app:{id:me||void 0,name:`${g} Data App`,createdWith:"semaphor-app-builder"},runtime:{framework:r.framework,bundler:r.framework==="vite-react"?"vite":void 0},semaphor:{projectId:h,runtime:A,intentManifest:Ue||void 0},build:{sourceFileCount:n.files.length,validation:r.validation}}}async function br(r){var S,w,C,v,k,I;const{workspaceContext:n}=await xr(r),i=j.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})});if(o.ok){const D=await O(o,"Local bridge /source-snapshot");if(!D.ok||!((S=D.files)!=null&&S.length))throw new Error(D.error||"Bridge did not return source snapshot files.");return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:D.files,metadata:{...D.metadata,capturedAt:typeof((w=D.metadata)==null?void 0:w.capturedAt)=="string"?D.metadata.capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||b,runtime:A}}}}const c=(v=(C=n.files)==null?void 0:C.snapshot)!=null&&v.length?n.files.snapshot:[...((k=n.files)==null?void 0:k.source)||[],...((I=n.files)==null?void 0:I.root)||[]],m=await Nt([...new Set(c.length?c:["src/App.tsx"])],r);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:m,metadata:{capturedAt:new Date().toISOString(),projectRoot:n.projectRoot||b,runtime:A}}}}async function fn(r,n){var m,S;const i=j.replace(/\/$/,""),o=await fetch(`${i}/source-snapshot`,{method:"POST",signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:r})});if(!o.ok)return null;const c=await O(o,"Local bridge /source-snapshot");return!c.ok||!((m=c.files)!=null&&m.length)?null:{schemaVersion:"data-app-source-snapshot/v1",files:c.files,metadata:{...c.metadata,capturedAt:typeof((S=c.metadata)==null?void 0:S.capturedAt)=="string"?c.metadata.capturedAt:new Date().toISOString(),projectRoot:r,runtime:A}}}async function xn(r,n,i){const o=j.replace(/\/$/,""),c=await fetch(`${o}/apply-files`,{method:"POST",signal:i,headers:{"Content-Type":"application/json"},body:JSON.stringify({revision:r,projectDir:n})}),m=await O(c,"Local bridge /apply-files");if(!c.ok||!m.ok)throw new Error(m.error||"Bridge could not restore saved files.");return m}async function gn({snapshot:r,targetProjectDir:n,signal:i}){const o=await fn(n,i);if(!o)throw new Error(`Bridge could not compare the current workspace before restore: ${n}`);const c=new Map(o.files.map(C=>[C.path,C.contents])),m=r.files.filter(C=>c.get(C.path)!==C.contents),S=Math.max(0,o.files.length-r.files.length);return o&&m.length===0||!window.confirm(["Restore this saved Data App source snapshot into the bridge workspace?","",`Target workspace: ${n}`,"",`${m.length||r.files.length} saved file${(m.length||r.files.length)===1?"":"s"} will be written. Extra local files are left unchanged.`,S?`${S} extra local file${S===1?"":"s"} may remain in the workspace.`:""].filter(Boolean).join(`
`))?!1:(await xn({provider:"semaphor",summary:"Restore saved Data App source snapshot",files:r.files.map(C=>({path:C.path,contents:C.contents})),changes:r.files.map(C=>({kind:"edit",label:C.path}))},n,i),!0)}async function bn(){var c,m,S,w;let r=U.current;r||(r=await Ye.loadSemaphorBrowserRuntime(),U.current=r);const n=r.readBrowserSandboxWorkspaceContext(),i=(m=(c=n.files)==null?void 0:c.snapshot)!=null&&m.length?n.files.snapshot:[...((S=n.files)==null?void 0:S.source)||[],...((w=n.files)==null?void 0:w.root)||[]],o=r.readBrowserSandboxFiles([...new Set(i.length?i:["src/App.tsx"])]);return{workspaceContext:n,snapshot:{schemaVersion:"data-app-source-snapshot/v1",files:o,metadata:{capturedAt:new Date().toISOString(),projectRoot:"browser-sandbox",runtime:A}}}}async function wr(){const r=new AbortController;dr(!0),bt(null);try{const{workspaceContext:n,snapshot:i}=A==="browser"?await bn():await br(r.signal),o=gr(n,i);or(JSON.stringify(o,null,2))}catch(n){bt(n instanceof Error?n.message:String(n))}finally{dr(!1)}}async function yr(){if(De.current)return De.current;if(!yt)return M("Save draft is not configured in this host yet.","blocked"),null;const r=new AbortController;pt("saving"),we(null),H({state:"running",label:"Saving draft",detail:"Reading the bridge source snapshot."});const n=(async()=>{var i;try{const{snapshot:o,workspaceContext:c}=await br(r.signal),m=gr(c,o),S=await rs({snapshot:o,workspaceContext:c,projectDir:b,adapter:"bridge"}),w=await yt({projectId:h,dataAppId:me,title:me?void 0:((i=m.app)==null?void 0:i.name)||`${g} Data App`,description:me?void 0:null,manifest:m,sourceSnapshot:o,sourceRevision:S,validationStatus:(jt==null?void 0:jt.result)||null,bridgeWorkspaceHint:c.projectRoot||b},{apiServiceUrl:s,accessToken:a,signal:r.signal});return Je(w.dataAppId),rr(w.savedAt||new Date().toISOString()),pt("saved"),H({state:"done",label:"Draft saved",detail:"Semaphor has the latest source snapshot."}),M("Draft saved to Semaphor.","default"),{dataAppId:w.dataAppId,draftId:w.draftId,manifest:m,snapshot:o,sourceRevision:S,workspaceContext:c}}catch(o){const c=o instanceof Error?o.message:String(o);return we(c),pt("failed"),H({state:"failed",label:"Save draft failed",detail:c}),M(`Save draft failed: ${c}`,"blocked"),null}finally{De.current=null}})();return De.current=n,n}async function wn(r){var c;const n=j.replace(/\/$/,""),i=await fetch(`${n}/publish-build`,{method:"POST",signal:r,headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDir:b})}),o=await O(i,"Local bridge /publish-build");if(!i.ok||!o.ok||!o.manifest||!o.entryFile||!((c=o.assets)!=null&&c.length))throw new Error(o.error||"Bridge could not build publish artifacts.");return o}async function yn(){if(!vt){M("Publish is not configured in this host yet.","blocked");return}if(_e==="saving"&&!De.current){M("Save draft is already in progress.","blocked");return}const r=await yr(),n=(r==null?void 0:r.dataAppId)||me;if(!r||!n||!r.draftId){M("Save the Data App before publishing.","blocked");return}const i=new AbortController;ht("publishing"),we(null),H({state:"running",label:"Preparing publish",detail:"Checking draft state before the local build."});try{H({state:"running",label:"Starting publish",detail:"Creating a publish session from the saved draft."});const o=await vt({projectId:h,dataAppId:n,draftId:r.draftId,title:`${g} Data App`,description:null,sourceSnapshot:r.snapshot,sourceRevision:r.sourceRevision,bridgeWorkspaceHint:r.workspaceContext.projectRoot||b,buildArtifacts:async({signal:c})=>{const m=await wn(c),S=m.assets;return{manifest:{...m.manifest,semaphor:{...m.manifest.semaphor||{},projectId:h,runtime:A,intentManifest:Ue||void 0}},validationStatus:m,bridgeWorkspaceHint:r.workspaceContext.projectRoot||b,assets:S,entryFile:m.entryFile,styleFiles:m.styleFiles||[]}}},{apiServiceUrl:s,accessToken:a,signal:i.signal,onProgress:c=>{H({state:"running",label:c.label,detail:c.detail})}});Je(o.dataAppId),sr(o.publishedAt||new Date().toISOString()),ht("published"),H({state:"done",label:"Published",detail:`Version ${o.version??o.versionId} is ready.`}),M(`Published Data App version ${o.version??o.versionId}.`,"default")}catch(o){const c=o instanceof Error?o.message:String(o);we(c),ht("failed"),H({state:"failed",label:"Publish failed",detail:c}),M(`Publish failed: ${c}`,"blocked")}}async function vn(r){var m,S;const{attachments:n,prompt:i}=r,o=new AbortController;Q.current=o,Tt(!0);const c=window.setTimeout(()=>{o.abort()},18e4);try{ne("context"),se("Reading the app manifest and starter context.");let w=A==="browser"?await pn(i):await xr(o.signal);const C=[];let v=null;for(;ne("thinking"),se(w.currentFiles.length>0?"Reviewing the app context and deciding the next step.":"Deciding whether this needs an answer, file inspection, or edits."),v=await Ke({projectId:h,message:i,currentFiles:w.currentFiles,workspaceContext:w.workspaceContext,conversationContext:Pr(nt.current,Ue),attachments:n,repair:!1,allowFileReads:!0,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal,onProgress:pr}),!(!v||v.mode!=="read_files");){const D=(v.requestedFiles||[]).filter(ve=>typeof ve=="string"&&!w.currentFiles.some(je=>je.path===ve));if(D.length===0){ne("thinking"),se("No additional source files are needed; preparing the response."),v=await Ke({projectId:h,message:i,currentFiles:w.currentFiles,workspaceContext:w.workspaceContext,conversationContext:Pr(nt.current,Ue),attachments:n,repair:!1,allowFileReads:!1,generationModel:J.model,generationReasoningEffort:J.reasoningEffort,repairModel:J.model,repairReasoningEffort:J.reasoningEffort},{accessToken:a,apiServiceUrl:s,signal:o.signal,onProgress:pr});break}ne("reading-files"),se(`Reading ${D.length} requested file${D.length===1?"":"s"}: ${qn(D)}.`),C.push({tool:"read_files",status:"done",detail:D.join(", ")});const ie=A==="browser"?await hn(D):await Nt(D,o.signal);w={...w,currentFiles:mn(w.currentFiles,ie)}}if(!v)throw new Error("Data App Builder did not return a turn.");if(C.length>0&&(v={...v,toolEvents:[...C,...v.toolEvents||[]]}),Zr(v),v.mode==="read_files"){M("I could not gather enough additional source context for that change. Please point me at the component or file you want to change, or try a narrower instruction.","guidance");return}if(v.mode!=="edit"){M(v.message,v.mode==="clarify"?"guidance":"default",{artifacts:v.artifacts,operation:v.operation,intentManifest:v.intentManifest});return}if(!v.revision)throw new Error("Data App Builder chose an edit but returned no revision.");M(Qn(v),"guidance",{operation:v.operation,intentManifest:v.intentManifest}),ne("planning"),se((S=(m=v.revision.plan)==null?void 0:m.files)!=null&&S.length?`Preparing edits for ${v.revision.plan.files.length} file${v.revision.plan.files.length===1?"":"s"}.`:"Preparing the file edit and validation run.");const k=ue("run"),I=Date.now();pe(D=>[...D,{id:k,type:"run",prompt:i,status:"running",steps:_n(),createdAt:I,startedAt:I}]),Q.current=null,A==="browser"?cn(i,k,v.revision):un(i,k,v.revision)}catch(w){const C=w instanceof DOMException&&w.name==="AbortError";M(C?"The app-builder turn timed out before a response was produced.":w instanceof Error?w.message:String(w),"blocked")}finally{Tt(!1),ne("idle"),se(null),Ot(null),Q.current===o&&(Q.current=null),window.clearTimeout(c)}}function jn(r){r.preventDefault();const n=Le.trim();if(!n)return;const i=Date.now(),o=tt,c={id:ue("turn"),prompt:n,attachments:o,createdAt:i};if(et(""),Ie([]),Y||Z){Ae(m=>[...m,c]);return}hr(c)}return e.jsxs(y.ResizablePanelGroup,{autoSaveId:`semaphor-data-app-builder-${h}`,className:"h-full min-h-0 flex-1",direction:"horizontal",children:[Ce?e.jsxs(e.Fragment,{children:[e.jsx(y.ResizablePanel,{className:"min-w-[320px] max-w-[760px]",defaultSize:28,maxSize:55,minSize:18,order:1,children:e.jsxs("aside",{className:"flex h-full min-h-0 flex-col border-r border-border",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Chat"}),e.jsx("div",{className:"ml-auto flex min-w-0 items-center gap-2",children:N?e.jsxs(y.AlertDialog,{children:[e.jsx(y.AlertDialogTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 px-1.5 text-muted-foreground",title:"Discard this conversation",children:[e.jsx(y.SquarePen,{className:"h-3.5 w-3.5"}),"New session"]})}),e.jsxs(y.AlertDialogContent,{children:[e.jsxs(y.AlertDialogHeader,{children:[e.jsx(y.AlertDialogTitle,{children:"Discard this conversation?"}),e.jsx(y.AlertDialogDescription,{children:"This clears the chat and run history in the builder and starts a new session. Generated files in your project are not affected."})]}),e.jsxs(y.AlertDialogFooter,{children:[e.jsx(y.AlertDialogCancel,{children:"Cancel"}),e.jsx(y.AlertDialogAction,{onClick:N,children:"Discard"})]})]})]}):null})]}),e.jsx("div",{ref:st,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4",children:e.jsxs("div",{className:"space-y-4",children:[X.length===0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[12.5px] font-medium text-foreground",children:"Start with a question or a build instruction"}),e.jsx("p",{className:"mt-1 text-[11.5px] leading-relaxed text-muted-foreground",children:"Ask about the current files, or describe the app you want."}),e.jsx("div",{className:"mt-3 grid gap-1.5",children:Fn.slice(0,3).map(r=>e.jsxs("button",{type:"button",onClick:()=>et(r.prompt),className:"rounded-[5px] border border-border px-2.5 py-2 text-left transition-colors hover:border-foreground/40",children:[e.jsx("div",{className:"truncate text-[11.5px] font-medium text-foreground",children:r.title}),e.jsx("div",{className:"mt-0.5 line-clamp-2 text-[10.5px] leading-relaxed text-muted-foreground",children:r.description})]},r.id))})]}),X.map(r=>r.type==="user"?e.jsx(fs,{message:r},r.id):r.type==="assistant"?e.jsx(gs,{message:r,onOpenDatasetInspector:Ve},r.id):e.jsx(vs,{getStepDuration:qr,run:r},r.id)),Z&&!Gr&&e.jsx(ys,{phase:Lr,detail:Ir,elapsedMs:Et?Math.max(0,Lt-Et):0})]})}),e.jsxs("form",{onSubmit:jn,className:"border-t border-border p-3",children:[Ne.length>0?e.jsx(ms,{turns:Ne,onDelete:ln,onRemoveAttachment:dn,onUpdatePrompt:on}):null,e.jsxs("div",{className:"rounded-[6px] border border-border focus-within:border-ring",children:[e.jsx("textarea",{value:Le,onChange:r=>et(r.target.value),onPaste:r=>{const n=Array.from(r.clipboardData.files).filter(i=>i.type.startsWith("image/"));n.length!==0&&(r.preventDefault(),mr(n))},onKeyDown:r=>{var n;r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),(n=r.currentTarget.form)==null||n.requestSubmit())},placeholder:"Ask a question, or write a build instruction like “Add a select filter for region”",className:"block min-h-[64px] w-full resize-none bg-transparent px-2.5 py-2 text-[13px] leading-relaxed text-foreground placeholder:text-muted-foreground focus:outline-none"}),tt.length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5 border-t border-border px-2 py-2",children:tt.map(r=>e.jsx(Ft,{attachment:r,onRemove:tn},r.id))}):null,e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border px-2 py-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("input",{ref:zt,type:"file",accept:"image/*",className:"hidden",multiple:!0,onChange:r=>{r.target.files&&mr(r.target.files),r.target.value=""}}),e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Add context","aria-label":"Add context",children:e.jsx(y.Plus,{className:"h-3.5 w-3.5"})})}),e.jsx(x.PopoverContent,{align:"start",side:"top",className:"w-44 p-1",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-foreground hover:bg-muted",onClick:()=>{var r;return(r=zt.current)==null?void 0:r.click()},children:[e.jsx(Dn,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Screenshot"]})})]}),e.jsxs(x.Select,{value:rt,onValueChange:zr,children:[e.jsx(x.SelectTrigger,{"aria-label":"Generation model",title:"Model used to generate changes",className:"h-7 w-auto gap-1.5 border-0 bg-transparent px-1.5 text-[11px] text-muted-foreground shadow-none hover:text-foreground focus:ring-0",children:e.jsx(x.SelectValue,{placeholder:"Model"})}),e.jsx(x.SelectContent,{align:"start",children:$t.map(r=>e.jsx(x.SelectItem,{value:r.id,className:"text-[12px]",children:r.label},r.id))})]})]}),e.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:Y||Z?e.jsxs(e.Fragment,{children:[e.jsx(x.Button,{type:"submit",size:"xs",variant:"outline",className:"gap-1.5",disabled:!Le.trim(),children:"Queue"}),e.jsxs(x.Button,{type:"button",variant:"outline",size:"xs",className:"gap-1.5",title:"Stop the current run",onClick:()=>{var r;return(r=Q.current)==null?void 0:r.abort()},children:[e.jsx(x.X,{className:"h-3 w-3"}),"Stop"]})]}):e.jsxs(x.Button,{type:"submit",size:"xs",className:"gap-1.5",disabled:!Le.trim(),children:[e.jsx(y.Send,{className:"h-3 w-3"}),"Send"]})})]})]})]})]})}),e.jsx(y.ResizableHandle,{className:"w-px bg-border/60 transition-colors hover:bg-border"})]}):null,e.jsx(y.ResizablePanel,{className:"min-w-0",defaultSize:Ce?72:100,minSize:35,order:2,children:e.jsxs("main",{className:"flex h-full min-w-0 flex-col bg-muted/40",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-3 border-b border-border px-3",children:[e.jsx(x.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-1 gap-1.5 px-1.5 text-muted-foreground",title:Ce?"Hide chat":"Show chat","aria-label":Ce?"Hide chat":"Show chat",onClick:()=>Or(r=>!r),children:Ce?e.jsx(Pn,{className:"h-3.5 w-3.5"}):e.jsx(y.PanelLeft,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[e.jsx("span",{className:"shrink-0 text-[12px] font-medium text-foreground",children:"Live preview"}),e.jsx("span",{className:"min-w-0 truncate font-mono text-[11px] text-muted-foreground",children:A==="browser"?"browser sandbox":F})]}),A==="browser"&&dt&&e.jsxs("span",{className:`text-[10.5px] ${dt==="tailwind"?"text-emerald-700 dark:text-emerald-400":"text-amber-700 dark:text-amber-400"}`,children:["CSS: ",dt]}),Wt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-blue-700 dark:text-blue-400",children:Wt}):null,mt?e.jsx("span",{className:"min-w-0 truncate text-[11px] text-destructive",title:mt,children:mt}):nr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-emerald-700 dark:text-emerald-400",children:["Published ",new Date(nr).toLocaleTimeString()]}):tr?e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["Saved ",new Date(tr).toLocaleTimeString()]}):null,e.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[e.jsxs(x.Popover,{open:xt,onOpenChange:r=>{Ge(r),r&&wr()},children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",title:"Inspect the current Data App manifest",children:[lr?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(y.FileCode,{className:"h-3.5 w-3.5"}),"Manifest"]})}),e.jsxs(x.PopoverContent,{align:"end",sideOffset:6,className:"w-[520px] p-0",onInteractOutside:()=>Ge(!1),onEscapeKeyDown:()=>Ge(!1),children:[e.jsxs("div",{className:"flex h-10 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.FileCode,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:"App manifest"}),e.jsx("div",{className:"truncate text-[10.5px] text-muted-foreground",children:"Current draft shape generated from the active runtime context"})]}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",disabled:!gt,title:"Copy manifest JSON","aria-label":"Copy manifest JSON",onClick:()=>{var r;(r=navigator.clipboard)==null||r.writeText(gt)},children:e.jsx(y.Copy,{className:"h-3.5 w-3.5"})}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",title:"Refresh manifest","aria-label":"Refresh manifest",onClick:()=>void wr(),children:e.jsx(y.RefreshCw,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"max-h-[520px] overflow-auto bg-muted/30 p-3",children:lr?e.jsxs("div",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-3 py-2 text-[12px] text-muted-foreground",children:[e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Reading current runtime manifest..."]}):ir?e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-3 py-2 text-[12px] text-destructive",children:ir}):e.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-[5px] border border-border bg-background p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:gt||"Open or refresh to inspect the manifest."})})]})]}),e.jsxs(y.AlertDialog,{children:[e.jsx(y.AlertDialogTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z,title:"Reset the app to a blank development template",children:[e.jsx(x.RotateCcw,{className:"h-3.5 w-3.5"}),"Reset app"]})}),e.jsxs(y.AlertDialogContent,{children:[e.jsxs(y.AlertDialogHeader,{children:[e.jsx(y.AlertDialogTitle,{children:"Reset this app?"}),e.jsx(y.AlertDialogDescription,{children:"This restores the active Data App workspace to the blank starter template and clears the builder's current app memory. Saved or published versions in Semaphor are not changed."})]}),e.jsxs(y.AlertDialogFooter,{children:[e.jsx(y.AlertDialogCancel,{children:"Cancel"}),e.jsx(y.AlertDialogAction,{onClick:()=>void Qr(),children:"Reset app"})]})]})]}),e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z||_e==="saving"||A!=="bridge"||!yt,title:"Save the current local source snapshot as a Semaphor draft",onClick:()=>void yr(),children:[_e==="saving"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn.Save,{className:"h-3.5 w-3.5"}),"Save draft"]}),e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",disabled:Y||Z||_e==="saving"||er==="publishing"||A!=="bridge"||!vt,title:"Build, upload, and publish the current Data App",onClick:()=>void yn(),children:[er==="publishing"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Rn,{className:"h-3.5 w-3.5"}),"Publish"]}),A==="bridge"?e.jsxs(x.Button,{type:"button",variant:he?"default":"ghost",size:"xs",disabled:Jt,className:he?"gap-1.5":"gap-1.5 text-muted-foreground",title:"Select an element in the preview and attach its DOM/React context",onClick:()=>he?sn():void nn(),children:[Jt?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx($n,{className:"h-3.5 w-3.5"}),he?"Cancel inspect":"Inspect"]}):null,e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsxs(x.Button,{type:"button",variant:"ghost",size:"xs",className:"gap-1.5 text-muted-foreground",children:[e.jsx(y.Settings2,{className:"h-3.5 w-3.5"}),"Runtime",A==="browser"&&lt.length>0?e.jsx("span",{className:"text-[10px] text-amber-600",children:"CSS fallback"}):null]})}),e.jsx(x.PopoverContent,{align:"end",sideOffset:6,className:"w-[380px] p-3",children:A==="bridge"?e.jsxs("div",{className:"space-y-2.5",children:[e.jsx(Dt,{label:"App Directory",value:b,placeholder:Ct,onChange:E}),e.jsx(Dt,{label:"App Local URL",value:f,onChange:R}),e.jsx(Dt,{label:"Bridge URL",value:j,onChange:B})]}):e.jsxs("div",{className:"text-[11px] leading-relaxed text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"min-w-0",children:"Browser files are stored locally in this browser."}),e.jsx(x.Button,{type:"button",variant:"outline",size:"xs",className:"h-6 shrink-0 text-[10.5px]",disabled:Y||Z||Be!=="ready",onClick:()=>void ur(),children:"Reset"})]}),lt[0]?e.jsx("div",{className:"mt-2 rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-muted-foreground",children:lt[0]}):null,e.jsx(as,{manifest:_r})]})})]}),e.jsx(x.Button,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground",title:"Reload the live preview","aria-label":"Reload the live preview",onClick:()=>{A==="browser"?(Qe(),$e()):(W(f),q(r=>r+1))},children:e.jsx(y.RefreshCw,{className:"h-3.5 w-3.5"})})]})]}),oe?e.jsx("div",{className:"shrink-0 border-b border-border bg-background px-3 py-2",children:e.jsxs("div",{className:`flex items-start gap-2 rounded-[6px] border px-2.5 py-2 text-[11.5px] leading-relaxed ${oe.state==="failed"?"border-destructive/30 bg-destructive/10 text-destructive":oe.state==="done"?"border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300":"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-900/60 dark:bg-blue-950/30 dark:text-blue-300"}`,children:[oe.state==="running"?e.jsx(x.LoaderCircle,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin"}):oe.state==="done"?e.jsx(x.Check,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):e.jsx(x.X,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:oe.label}),oe.detail?e.jsx("div",{className:"mt-0.5 truncate opacity-80",children:oe.detail}):null]})]})}):null,(A==="browser"&&(Be==="loading"||Be==="failed")||Re&&!((vr=Re.appBuilder)!=null&&vr.hasOpenAiKey))&&e.jsxs("div",{className:"shrink-0 border-b border-border px-3 py-2",children:[A==="browser"&&Be==="loading"&&e.jsx("p",{className:"text-[11px] leading-relaxed text-muted-foreground",children:"Loading the in-browser runtime…"}),A==="browser"&&Be==="failed"&&e.jsxs("div",{className:"rounded-[5px] border border-border bg-muted/40 px-2 py-1.5 text-[11px] leading-relaxed text-muted-foreground",children:["Browser runtime is unavailable. Link or install semaphor-browser-runtime, or use the local bridge path.",Vt?e.jsx("pre",{className:"mt-1.5 whitespace-pre-wrap font-mono text-[10.5px] text-muted-foreground",children:Vt}):null]}),Re&&!((jr=Re.appBuilder)!=null&&jr.hasOpenAiKey)&&e.jsx("div",{className:"rounded-[5px] border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-[11px] text-destructive",children:Re.error||"OPENAI_API_KEY is not configured."})]}),A==="browser"&&Hr.length>0&&e.jsx("div",{className:"shrink-0 border-b border-border px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-400",children:"Preview compiled with diagnostics. The next prompt can use them for repair."}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[A==="browser"&&e.jsxs("aside",{className:"flex w-[300px] shrink-0 flex-col border-r border-border",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.CodeXml,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-[11.5px] font-medium text-foreground",children:"Files"}),e.jsx("span",{className:"ml-auto font-mono text-[10px] text-muted-foreground",children:Xt.length})]}),e.jsx("div",{className:"max-h-72 shrink-0 overflow-y-auto border-b border-border p-2",children:e.jsx(ss,{files:Xt,selectedPath:ct,onSelect:Kr})}),e.jsx("pre",{className:"min-h-0 flex-1 overflow-auto p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:(ut==null?void 0:ut.contents)||"Select a file to inspect its source."})]}),e.jsx("iframe",{ref:at,className:"min-h-0 flex-1 bg-background",onLoad:()=>{he&&window.setTimeout(()=>Xe("inspect-enable"),100)},src:A==="browser"?void 0:St,srcDoc:A==="browser"?Wr:void 0,title:"Data app preview"},A==="browser"?`browser-${ge}`:St),ar?e.jsx(ws,{artifact:ar,onClose:()=>Ve(null)}):null]})]})})]})}function Dt({label:t,value:s,placeholder:a,onChange:d}){return e.jsxs("label",{className:"grid min-w-0 gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t}),e.jsx("input",{value:s,placeholder:a,spellCheck:!1,autoComplete:"off",onChange:l=>d(l.target.value),onFocus:l=>l.target.select(),className:"h-8 w-full min-w-0 rounded-[5px] border border-border bg-background px-2 font-mono text-[12px] text-foreground outline-none focus:border-ring"})]})}function ds({code:t,lang:s}){const[a,d]=p.useState(!1);return e.jsxs("div",{className:"my-2 overflow-hidden rounded-[6px] border border-border",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border bg-muted/40 px-2.5 py-1",children:[e.jsx("span",{className:"font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:s||"code"}),e.jsx("button",{type:"button",onClick:()=>{var l;(l=navigator.clipboard)==null||l.writeText(t),d(!0),window.setTimeout(()=>d(!1),1500)},className:"inline-flex items-center gap-1 rounded-[4px] px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground",children:a?e.jsxs(e.Fragment,{children:[e.jsx(x.Check,{className:"h-3 w-3"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(y.Copy,{className:"h-3 w-3"}),"Copy"]})})]}),e.jsx("div",{className:"overflow-x-auto bg-background",children:e.jsx(y.CodeHighlighter,{code:t,language:s||"tsx"})})]})}const cs=/(\b[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.(?:tsx?|jsx?|mjs|cjs|css|scss|json|mdx?|html?|ya?ml|toml|sql|sh|py|rb|go|rs)\b)/g;function us(t,s){return t.split(cs).map((a,d)=>d%2===1?e.jsxs("span",{className:"mx-px inline-flex items-baseline gap-1 rounded-[4px] border border-border bg-muted/60 px-1 font-mono text-[0.82em] text-foreground",children:[e.jsx(y.FileCode,{className:"h-3 w-3 shrink-0 translate-y-[1px] text-muted-foreground"}),a]},`${s}-f${d}`):e.jsx("span",{children:a},`${s}-t${d}`))}function ps(t,s){return t.split(`
`).map((a,d)=>e.jsxs("span",{children:[d>0?e.jsx("br",{}):null,a.split(/(`[^`]+`|\*\*[^*]+\*\*)/g).map((l,u)=>l.length>1&&l.startsWith("`")&&l.endsWith("`")?e.jsx("code",{className:"mx-px rounded-[4px] bg-foreground/10 px-1 font-mono text-[0.85em] text-foreground",children:l.slice(1,-1)},u):l.length>4&&l.startsWith("**")&&l.endsWith("**")?e.jsx("strong",{className:"font-semibold text-foreground",children:l.slice(2,-2)},u):e.jsx("span",{children:us(l,`${s}-${d}-${u}`)},u))]},`${s}-${d}`))}function hs(t){return t.split("```").map((s,a)=>{if(a%2===1){let d="",l=s;const u=s.indexOf(`
`);if(u!==-1){const h=s.slice(0,u).trim();h&&/^[A-Za-z0-9_.+-]{1,16}$/.test(h)&&(d=h,l=s.slice(u+1))}return l=l.replace(/^\n/,"").replace(/\s+$/,""),e.jsx(ds,{code:l,lang:d},a)}return e.jsx("span",{children:ps(s,a)},a)})}function ms({turns:t,onDelete:s,onRemoveAttachment:a,onUpdatePrompt:d}){var g;const[l,u]=p.useState(!1),h=t.length;return e.jsxs("div",{className:"mb-2 overflow-hidden rounded-[6px] border border-border bg-muted/40",children:[e.jsxs("button",{type:"button",onClick:()=>u(N=>!N),"aria-expanded":l,className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left",children:[e.jsx(y.ChevronRight,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${l?"rotate-90":""}`}),e.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-foreground",children:[h," queued"]}),l?null:e.jsxs("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["· ",((g=t[0])==null?void 0:g.prompt.trim())||"Queued instruction"]}),e.jsx("span",{className:"ml-auto shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:l?"Hide":"Show"})]}),l?e.jsx("div",{className:"max-h-[200px] space-y-1.5 overflow-y-auto border-t border-border p-2",children:t.map((N,f)=>e.jsxs("div",{className:"rounded-[5px] border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Next ",f+1]}),e.jsx("button",{type:"button",className:"rounded-[4px] px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>s(N.id),children:"Remove"})]}),e.jsx("textarea",{value:N.prompt,onChange:R=>d(N.id,R.target.value),className:"block min-h-[44px] w-full resize-none rounded-[4px] border border-border bg-transparent px-2 py-1.5 text-[12px] leading-relaxed text-foreground focus:border-ring focus:outline-none",placeholder:"Queued instruction"}),N.attachments.length>0?e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:N.attachments.map(R=>e.jsx(Ft,{attachment:R,onRemove:j=>a(N.id,j)},R.id))}):null]},N.id))}):null]})}function fs({message:t}){var s;return e.jsxs("div",{className:"ml-auto max-w-[88%] rounded-[6px] rounded-br-[2px] bg-foreground/10 px-3 py-2 text-[13px] leading-relaxed text-foreground",children:[e.jsx("div",{children:t.content}),(s=t.attachments)!=null&&s.length?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.attachments.map(a=>e.jsx(Ft,{attachment:a},a.id))}):null]})}function Ft({attachment:t,onRemove:s}){const a=e.jsxs(e.Fragment,{children:[t.type==="screenshot"?e.jsxs(e.Fragment,{children:[e.jsx("img",{alt:"",className:"h-5 w-7 rounded-[3px] border border-border object-cover",src:t.imageUrl}),e.jsx("span",{className:"max-w-[140px] truncate",children:t.name})]}):e.jsxs(e.Fragment,{children:[e.jsx(y.CodeXml,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate",children:t.name})]}),s?e.jsx("button",{type:"button",className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>s(t.id),"aria-label":`Remove ${t.name}`,children:e.jsx(x.X,{className:"h-3 w-3"})}):null]});return t.type==="dom-selection"?e.jsxs(x.Popover,{children:[e.jsx(x.PopoverTrigger,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex max-w-full items-center gap-1.5 rounded-[5px] border border-border bg-background px-1.5 py-1 text-[11px] text-muted-foreground hover:border-ring hover:text-foreground",title:"View captured DOM context",children:a})}),e.jsxs(x.PopoverContent,{align:"start",sideOffset:6,className:"w-[420px] p-0",children:[e.jsxs("div",{className:"border-b border-border px-3 py-2",children:[e.jsx("div",{className:"text-[12px] font-medium text-foreground",children:"Captured DOM context"}),e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:t.name})]}),e.jsx("pre",{className:"max-h-[360px] overflow-auto whitespace-pre-wrap p-3 font-mono text-[11px] leading-relaxed text-muted-foreground",children:t.text})]})]}):e.jsx("span",{className:"inline-flex max-w-full items-center gap-1.5 rounded-[5px] border border-border bg-background px-1.5 py-1 text-[11px] text-muted-foreground",children:a})}function xs(t){var s;if(t.type==="assistant"){const{artifacts:a,...d}=t;return d}return t.type==="user"&&((s=t.attachments)!=null&&s.length)?{...t,attachments:t.attachments.filter(a=>a.type!=="screenshot")}:t}function gs({message:t,onOpenDatasetInspector:s}){var d;const a=t.tone==="blocked"?"border-destructive/30 bg-destructive/10 text-destructive":t.tone==="guidance"?"border-blue-100 bg-blue-50/60 text-blue-950":"border-border bg-background text-foreground";return e.jsxs("div",{className:`max-w-[92%] rounded-[6px] rounded-bl-[2px] border px-3 py-2 text-[13px] leading-relaxed ${a}`,children:[e.jsx("div",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Assistant"}),hs(t.content),(d=t.artifacts)==null?void 0:d.map(l=>l.type==="dataset_inspector"?e.jsx(bs,{artifact:l,onOpen:()=>s(l)},l.id):null)]})}function bs({artifact:t,onOpen:s}){return e.jsxs("button",{type:"button",onClick:s,className:"mt-2 flex w-full items-center gap-2 rounded-[5px] border border-border bg-background px-2.5 py-2 text-left transition-colors hover:border-foreground/40",children:[e.jsx(y.Database,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-[12px] font-medium text-foreground",children:t.title}),e.jsxs("span",{className:"block truncate text-[10.5px] text-muted-foreground",children:[t.counts.total," fields · ",t.counts.measures," measures ·"," ",t.counts.dimensions," dimensions"]})]}),e.jsx("span",{className:"shrink-0 text-[10.5px] font-medium text-muted-foreground",children:"Open"})]})}function ws({artifact:t,onClose:s}){const[a,d]=p.useState(""),[l,u]=p.useState("all"),h=a.trim().toLowerCase(),g=t.fields.filter(f=>{var E,z;const R=(E=f.role)==null?void 0:E.toLowerCase(),j=(z=f.dataType)==null?void 0:z.toLowerCase(),B=l==="all"||l==="measures"&&(R==="measure"||R==="metric")||l==="dimensions"&&R==="dimension"||l==="dates"&&(R==="date"||j==="date"||j==="timestamp")||l==="identifiers"&&R==="identifier"||l==="calculated"&&f.source==="calculated",b=!h||[f.name,f.label,f.role,f.dataType].filter(L=>typeof L=="string").some(L=>L.toLowerCase().includes(h));return B&&b}),N=[{id:"all",label:"All",count:t.counts.total},{id:"measures",label:"Measures",count:t.counts.measures},{id:"dimensions",label:"Dimensions",count:t.counts.dimensions},{id:"dates",label:"Dates",count:t.counts.dates},{id:"identifiers",label:"IDs",count:t.counts.identifiers},{id:"calculated",label:"Calc",count:t.counts.calculated}];return e.jsxs("aside",{className:"flex w-[360px] shrink-0 flex-col border-l border-border bg-background",children:[e.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b border-border px-3",children:[e.jsx(y.Database,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:"Field inspector"})}),e.jsx(x.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground","aria-label":"Close field inspector",onClick:s,children:e.jsx(x.X,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"shrink-0 border-b border-border p-3",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:t.title}),e.jsxs("div",{className:"mt-0.5 truncate font-mono text-[10.5px] text-muted-foreground",children:[t.domain.label," · ",t.dataset.name]}),t.dataset.primaryDateField?e.jsxs("div",{className:"mt-2 rounded-[5px] bg-muted px-2 py-1 text-[11px] text-muted-foreground",children:["Primary date: ",t.dataset.primaryDateField]}):null,e.jsxs("label",{className:"mt-3 flex h-8 items-center gap-2 rounded-[5px] border border-border bg-background px-2",children:[e.jsx(y.Search,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{value:a,onChange:f=>d(f.target.value),placeholder:"Search fields",className:"min-w-0 flex-1 bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"})]}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:N.map(f=>e.jsxs("button",{type:"button",onClick:()=>u(f.id),className:`rounded-[5px] px-2 py-1 text-[10.5px] ${l===f.id?"bg-foreground text-background":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[f.label," ",f.count]},f.id))})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:g.length>0?e.jsx("div",{className:"space-y-1",children:g.map(f=>e.jsxs("div",{className:"rounded-[5px] border border-border px-2 py-1.5",children:[e.jsx("div",{className:"truncate text-[12px] font-medium text-foreground",children:f.label||f.name}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground",children:[e.jsx("span",{className:"truncate font-mono",children:f.name}),f.role?e.jsxs("span",{children:["· ",f.role]}):null,f.dataType?e.jsxs("span",{children:["· ",f.dataType]}):null,f.source==="calculated"?e.jsx("span",{children:"· calculated"}):null]})]},`${f.source}:${f.name}`))}):e.jsx("div",{className:"rounded-[5px] border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted-foreground",children:"No fields match this search."})})]})}function ys({phase:t,detail:s,elapsedMs:a}){const d=Gn(t),l=s||Kn(t);return e.jsxs("div",{className:"max-w-[92%] rounded-[6px] rounded-bl-[2px] border border-border bg-background px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}),e.jsx("span",{className:"text-[12.5px] font-medium text-foreground",children:d}),e.jsx("span",{className:"ml-auto shrink-0 font-mono text-[11px] tabular-nums text-muted-foreground",children:Pt(a)})]}),e.jsx("div",{className:"mt-1 flex items-center justify-between gap-3",children:e.jsx("span",{className:"text-[11px] leading-relaxed text-muted-foreground",children:l})})]})}function vs({run:t,getStepDuration:s}){var f,R,j;const a=t.steps.filter(B=>B.state==="done").length,d=t.steps.length,l=(R=(f=t.result)==null?void 0:f.generationMeta)==null?void 0:R.durationMs,u=B=>B.id==="generate"&&typeof l=="number"?l:s(B),h=t.steps.reduce((B,b)=>B+u(b),0),g=t.status==="running",N=g?"running":t.result?t.result.ok?"passed":"failed":t.status;return e.jsxs("details",{open:g,className:"group rounded-[6px] border border-border/60 bg-muted/20",children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-2 px-2.5 py-1.5 text-[12px] marker:hidden",children:[e.jsx(y.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform group-open:rotate-90"}),e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${g?"animate-pulse bg-amber-500":t.status==="done"?"bg-emerald-500":"bg-destructive"}`}),e.jsx("span",{className:"shrink-0 font-medium text-foreground",children:"Build"}),e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:["· ",t.prompt]}),e.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11px] text-muted-foreground",children:[N," · ",a,"/",d," ·"," ",Pt(h)]})]}),e.jsxs("div",{className:"space-y-2.5 border-t border-border/60 px-2.5 py-2",children:[g?e.jsx("div",{className:"h-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-foreground",style:{width:`${Math.round(a/Math.max(1,d)*100)}%`}})}):null,e.jsx("div",{className:"space-y-0.5",children:t.steps.map(B=>{var b,E;return e.jsx(js,{duration:u(B),repairAttempts:(E=(b=t.result)==null?void 0:b.telemetry)==null?void 0:E.repairAttempts,step:B},B.id)})}),t.result&&e.jsxs("div",{className:"space-y-1.5 border-t border-border pt-2.5 text-[12px] leading-relaxed text-muted-foreground",children:[e.jsxs("div",{className:"font-medium text-foreground",children:["Runtime result:"," ",e.jsx("span",{className:t.result.ok?"text-emerald-600":"text-destructive",children:t.result.ok?"passed":"failed"})]}),t.result.telemetry&&e.jsxs("div",{className:"grid gap-1 font-mono text-[11px] sm:grid-cols-2",children:[e.jsxs("span",{children:["context: ",t.result.telemetry.contextFileCount??0," ","files · ",t.result.telemetry.contextChars??0," chars"]}),e.jsxs("span",{children:["generated:"," ",t.result.telemetry.generatedFileCount??0," files ·"," ",t.result.telemetry.generatedChars??0," chars"]})]}),(j=t.result.changedFiles)!=null&&j.length?e.jsxs("div",{children:["Changed ",t.result.changedFiles.join(", ")]}):null,e.jsx(os,{plan:t.result.filePlan,changedFiles:t.result.changedFiles}),t.result.generationMeta&&e.jsxs("div",{children:["Model: ",t.result.generationMeta.model]}),t.result.error&&e.jsx("pre",{className:"mt-1 max-h-44 overflow-auto whitespace-pre-wrap rounded-[4px] border border-border bg-muted/40 p-2 font-mono text-[11px] text-foreground",children:t.result.error})]})]})]})}function js({duration:t,repairAttempts:s,step:a}){return e.jsxs("div",{className:"grid grid-cols-[16px_minmax(0,1fr)_auto] items-center gap-2 rounded-[4px] px-1.5 py-1 text-[11.5px]",children:[e.jsx(Ss,{state:a.state}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:`truncate font-mono ${a.state==="idle"?"text-muted-foreground":"text-foreground"}`,children:a.label}),a.state==="running"&&e.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:a.detail})]}),e.jsx("div",{className:"flex items-center gap-2 font-mono text-[11px] text-muted-foreground",children:a.id==="repair"&&a.state==="running"?e.jsxs("span",{children:["attempt ",(s||0)+1," / ",Te]}):e.jsx("span",{children:Pt(t)})})]})}function Ss({state:t}){return t==="done"?e.jsx(x.Check,{className:"h-3.5 w-3.5 text-emerald-600"}):t==="running"?e.jsx(x.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin text-blue-600"}):t==="blocked"?e.jsx(x.X,{className:"h-3.5 w-3.5 text-destructive"}):e.jsx(y.Circle,{className:"h-2.5 w-2.5 fill-zinc-300 stroke-none"})}exports.DataAppBuilder=is;
