import{j as e,r as l,u as ke,b as Ye,c as Ae}from"./query-Bw69rE6b.js";import{a as It,u as Et,L as ot,e as qt}from"./react-CQKYBN-P.js";import{d as ct,c as ae,j as Re,m as dt,T as bt,B as W,p as je,R as He,a as we,b as xe,S as it,q as Ft,X as Ot,r as Le,f as Pt,t as zt,v as Dt,w as Bt,x as Ke,y as Kt,z as Qt,E as Vt,G as xt,n as st,P as Gt}from"./index-CoUu6FiM.js";import{P as Ve}from"./PageHeader-qtVByY5c.js";import{C as ne,a as Se,b as ie}from"./Card-nuKO-lKR.js";import{J as Ut}from"./JobProgress-CArMtskB.js";import{S as ut}from"./StatusPill-DBEWzsQ3.js";import{A as Ht,C as Jt,L as Wt}from"./InsightBadges-Cf20HBne.js";import{E as at,u as gt,s as jt,A as yt,b as vt}from"./AdvancedLLMOverrides-BR8rzUMx.js";import{B as Ge}from"./Badge-DwoQNRW3.js";import{A as Je}from"./AlertDialog-IkMNJ6QG.js";import{I as Yt}from"./InlineEditText-BpIisHVz.js";import{R as ft}from"./RouteState-Cu5M7yS-.js";import{C as kt}from"./circle-pause-BD9iFI5E.js";import{C as Xt}from"./circle-play-BX3na9-o.js";import"./pencil-ByuKsEO5.js";import"./EmptyState-CgO0CCgi.js";import"./rotate-ccw-CDH4c_fo.js";/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Zt=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],es=ct("pin-off",Zt);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ts=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],ss=ct("skip-forward",ts);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ns=[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]],Nt=ct("timer",ns);function ge({children:t,className:s}){return e.jsx("kbd",{className:ae("inline-flex h-5 min-w-[1.25rem] items-center justify-center rounded border border-border bg-surface-subtle px-1 font-mono text-[10.5px] font-medium text-ink-muted shadow-xs",s),children:t})}function _t({open:t,onClose:s,targets:i,onSubmitted:n,contextSummary:r}){const{push:u}=Re(),[x,o]=l.useState(""),[m,p]=l.useState(!1),[h,b]=l.useState(at),[E,q]=l.useState(!1),j=ke({queryKey:["context","rerun-defaults"],queryFn:()=>we.context(),enabled:t,staleTime:6e4}),A=j.data?.llm_profile_defaults??null,F=j.data?.active_llm_profile??null,f=ke({queryKey:["profiles","llm"],queryFn:()=>xe("/api/profiles/llm"),enabled:t,staleTime:6e4}).data?.profiles??[],z=f.find(y=>y.name===h.profile),L=z?.provider??j.data?.llm_provider??null,M=z?.model??j.data?.llm_model??null,{supportsThinking:G,supportsLogprobs:re}=gt(L,M),U=!!(z&&z.has_credentials===!1);l.useEffect(()=>{t&&b(jt(A))},[t,A]);const P=i.length>1,X=l.useMemo(()=>P?e.jsxs("p",{className:"text-[11px] text-ink-dim",children:["Defaults shown reflect your active LLM profile",F?e.jsxs(e.Fragment,{children:[" ","(",e.jsx("span",{className:"font-mono",children:F}),")"]}):null,". Overrides apply uniformly to all ",i.length," selected items."]}):null,[P,F,i.length]),k=async()=>{if(!i.length){u({tone:"error",title:"No targets selected to re-run."});return}q(!0);try{const y=vt(h,A),w=typeof y?.temperature=="number"?Math.max(0,Math.min(1,y.temperature)):null,B=await we.rerunItems({result_ids:i.map(C=>C.resultId),user_instructions:x.trim()||null,temperature_override:w,llm_overrides:y});n(B.job_id),o(""),b(at),p(!1),s()}catch(y){u({tone:"error",title:"Re-run failed to start",description:y instanceof Error?y.message:String(y)})}finally{q(!1)}},$=i.length,R=$===1?"Re-Run this item":`Re-Run ${$} items`;return e.jsx(dt,{open:t,onClose:E?()=>{}:s,title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{size:14,className:"text-accent"})," ",R]}),description:r||"Original DB, docs, codebase context is preserved. Anything you type below is appended as additional guidance — the agents still see all the inputs from the original run.",size:"lg",preventBackdropClose:E,footer:e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"ghost",onClick:s,disabled:E,children:"Cancel"}),e.jsx(W,{variant:"primary",onClick:k,disabled:E||$===0||U,children:E?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(je,{size:14,className:"animate-spin"})," Starting…"]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(He,{size:14})," Re-Run"]})})]}),children:e.jsxs("div",{className:"space-y-4",children:[P&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] uppercase tracking-wider text-ink-dim",children:"Targets"}),e.jsx("ul",{className:"max-h-32 overflow-y-auto rounded-md border border-border bg-surface-subtle/40 px-3 py-2 text-xs",children:i.map(y=>e.jsx("li",{className:"font-mono text-ink-muted",children:y.label},y.resultId))})]}),!P&&i[0]&&e.jsxs("div",{className:"rounded-md border border-border bg-surface-subtle/40 px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Target"}),e.jsx("div",{className:"mt-0.5 font-mono text-ink",children:i[0].label})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rerun-instructions",className:"mb-1 block text-[10px] uppercase tracking-wider text-ink-dim",children:"Additional instructions (optional)"}),e.jsx(bt,{id:"rerun-instructions",placeholder:'e.g. "Note that this column also includes soft-deleted rows."',value:x,onChange:y=>o(y.target.value),rows:4,disabled:E}),e.jsx("p",{className:"mt-1 text-[11px] text-ink-dim",children:"Agents always re-read the original DB / docs / codebase inputs. This text is appended to bias the new alternatives."})]}),e.jsx(yt,{open:m,onToggle:()=>p(y=>!y),form:h,onChange:b,defaults:A,profileName:F,livePrice:null,livePriceLoading:!1,title:"Advanced LLM settings",prelude:X,profiles:f,supportsThinking:G,supportsLogprobs:re,effectiveModel:M}),U&&e.jsxs("p",{className:"rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-[11px] text-warn",children:["The selected LLM profile is missing credentials. Open Settings → LLM → ",h.profile," to add an API key before re-running."]})]})})}function is({open:t,onClose:s,originalRunId:i,resultId:n,alternativeIndex:r,seedText:u,seedLetter:x,initialMode:o="semantic",onSubmitted:m}){const{push:p}=Re(),[h,b]=l.useState(o),[E,q]=l.useState(""),[j,A]=l.useState(!1),[F,V]=l.useState(at),[f,z]=l.useState(!1),L=ke({queryKey:["context","variations-defaults"],queryFn:()=>we.context(),enabled:t,staleTime:6e4}),M=L.data?.llm_profile_defaults??null,G=L.data?.active_llm_profile??null,U=ke({queryKey:["profiles","llm"],queryFn:()=>xe("/api/profiles/llm"),enabled:t,staleTime:6e4}).data?.profiles??[],P=U.find(C=>C.name===F.profile),X=P?.provider??L.data?.llm_provider??null,k=P?.model??L.data?.llm_model??null,{supportsThinking:$,supportsLogprobs:R}=gt(X,k),y=!!(P&&P.has_credentials===!1);l.useEffect(()=>{t&&(V(jt(M)),b(o),q(""),A(!1))},[t,M,o]);const w=l.useMemo(()=>"Original DB, docs, codebase context is preserved. The selected alternative is used as a seed to bias the new descriptions.",[]),B=async()=>{if(!u.trim()){p({tone:"error",title:"Seed text is empty."});return}z(!0);try{const C=vt(F,M),D=await we.generateVariations({original_run_id:i,result_id:n,alternative_index:r,seed_text:u,mode:h,user_instructions:E.trim()||null,llm_overrides:C});m(D.job_id,D.new_run_id??null),s()}catch(C){p({tone:"error",title:"Variations failed to start",description:C instanceof Error?C.message:String(C)})}finally{z(!1)}};return e.jsx(dt,{open:t,onClose:f?()=>{}:s,title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(it,{size:14,className:"text-accent"}),"Generate variations from this alternative"]}),description:w,size:"lg",preventBackdropClose:f,footer:e.jsxs(e.Fragment,{children:[e.jsx(W,{variant:"ghost",onClick:s,disabled:f,children:"Cancel"}),e.jsx(W,{variant:"primary",onClick:B,disabled:f||y,children:f?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(je,{size:14,className:"animate-spin"})," Starting…"]}):e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(it,{size:14})," Generate Variations"]})})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] uppercase tracking-wider text-ink-dim",children:"Seed Alternative"}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border bg-surface-subtle/40 px-3 py-2 text-xs",children:[e.jsx("span",{className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-accent/15 font-mono text-[11px] font-semibold text-accent",children:x}),e.jsx("span",{className:"text-ink",children:u})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-[10px] uppercase tracking-wider text-ink-dim",children:"Variation type"}),e.jsx("div",{className:"flex flex-wrap items-stretch gap-2",children:["semantic","lexical"].map(C=>{const D=h===C,H=C==="semantic"?"Paraphrases of the seed — same meaning, different wording.":"Share vocabulary with the seed; allow meaning to drift through added nuances.";return e.jsxs("button",{type:"button",onClick:()=>b(C),disabled:f,className:"min-w-[180px] flex-1 rounded-md border px-3 py-2 text-left text-xs "+(D?"border-accent bg-accent/10 text-ink":"border-surface-border bg-surface text-ink-muted hover:bg-surface-subtle"),children:[e.jsx("div",{className:"font-medium capitalize",children:C}),e.jsx("div",{className:"mt-0.5 text-[11px] text-ink-dim",children:H})]},C)})})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"variations-instructions",className:"mb-1 block text-[10px] uppercase tracking-wider text-ink-dim",children:"Additional instructions (optional)"}),e.jsx(bt,{id:"variations-instructions",placeholder:'e.g. "Emphasize the temporal dimension."',value:E,onChange:C=>q(C.target.value),rows:3,disabled:f})]}),e.jsx(yt,{open:j,onToggle:()=>A(C=>!C),form:F,onChange:V,defaults:M,profileName:G,livePrice:null,livePriceLoading:!1,title:"Advanced LLM settings",profiles:U,hideAlternativesModeRow:!0,supportsThinking:$,supportsLogprobs:R,effectiveModel:k}),y&&e.jsxs("p",{className:"rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-[11px] text-warn",children:["The selected LLM profile is missing credentials. Open Settings → LLM → ",F.profile," to add an API key before generating variations."]})]})})}function as(t,s){const[i,n]=l.useState(t);return l.useEffect(()=>{const r=window.setTimeout(()=>n(t),s);return()=>window.clearTimeout(r)},[t,s]),i}const rs=[{value:"natural",label:"Natural order"},{value:"conf-asc",label:"Confidence (low → high)"},{value:"conf-desc",label:"Confidence (high → low)"},{value:"logprob-asc",label:"Logprob (low → high)"},{value:"logprob-desc",label:"Logprob (high → low)"},{value:"name-asc",label:"Asset name (A → Z)"},{value:"status",label:"Status (unreviewed first)"}],ls=[{value:"none",label:"None"},{value:"schema",label:"Schema"},{value:"table",label:"Table"}],os=[{value:"all",label:"All"},{value:"unreviewed",label:"Unreviewed"},{value:"accepted",label:"Accepted"},{value:"skipped",label:"Skipped"}],cs=[{value:"low_conf",label:"Low confidence (<0.7)"},{value:"has_citations",label:"Has citations"},{value:"table_only",label:"Table-level only"}];function ds({query:t,onQueryChange:s,sort:i,onSortChange:n,group:r,onGroupChange:u,statusFilter:x,onStatusChange:o,presetActive:m,onPresetChange:p,totalCount:h,visibleCount:b,statusCounts:E,searchInputRef:q}){const[j,A]=l.useState(t),F=as(j,150);l.useEffect(()=>{F!==t&&s(F)},[F]),l.useEffect(()=>{A(t)},[t]);const V=f=>{p(m===f?null:f)};return e.jsxs("div",{className:"space-y-2 rounded-lg border border-surface-border bg-surface-subtle/40 px-3 py-2.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[18rem] flex-1",children:[e.jsx(Ft,{size:13,className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-ink-dim"}),e.jsx("input",{ref:q,type:"text",value:j,onChange:f=>A(f.target.value),placeholder:"Search schema · table · column · description","aria-label":"Filter suggestions",className:"w-full rounded-md border border-surface-border bg-surface py-1.5 pl-8 pr-7 text-xs text-ink placeholder:text-ink-dim focus:border-accent/40 focus:outline-none focus:ring-1 focus:ring-accent/30"}),j&&e.jsx("button",{type:"button",onClick:()=>A(""),"aria-label":"Clear search",className:"absolute right-2 top-1/2 -translate-y-1/2 text-ink-dim hover:text-ink",children:e.jsx(Ot,{size:12})})]}),e.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-ink-muted",children:[e.jsx("span",{className:"text-ink-dim",children:"Sort"}),e.jsx("select",{value:i,onChange:f=>n(f.target.value),className:"rounded-md border border-surface-border bg-surface px-1.5 py-1 text-xs text-ink focus:border-accent/40 focus:outline-none",children:rs.map(f=>e.jsx("option",{value:f.value,children:f.label},f.value))})]}),e.jsxs("div",{className:"inline-flex items-center gap-1 text-xs text-ink-muted",children:[e.jsx("span",{className:"text-ink-dim",children:"Group"}),e.jsx("div",{role:"group","aria-label":"Group by",className:"inline-flex overflow-hidden rounded-md border border-surface-border",children:ls.map(f=>e.jsx("button",{type:"button",onClick:()=>u(f.value),className:ae("px-2 py-1 text-xs transition-colors",r===f.value?"bg-accent-soft text-accent-ink":"bg-surface text-ink-muted hover:bg-surface-subtle"),children:f.label},f.value))})]}),e.jsx("span",{className:"ml-auto rounded-md bg-surface-subtle px-2 py-1 font-mono text-[11px] tabular-nums text-ink-muted",children:b===h?`${h} suggestions`:`Showing ${b} of ${h}`})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[os.map(f=>{const z=x===f.value,L=E?.[f.value];return e.jsxs("button",{type:"button",onClick:()=>o(f.value),className:ae("rounded-full border px-2.5 py-0.5 text-[11px] transition-colors",z?"border-accent/40 bg-accent-soft text-accent-ink":"border-surface-border bg-surface text-ink-muted hover:border-accent/30 hover:bg-surface-subtle"),children:[f.label,typeof L=="number"&&e.jsxs("span",{className:"ml-1 font-mono tabular-nums text-ink-dim",children:["(",L,")"]})]},f.value)}),e.jsx("span",{className:"mx-1 hidden h-4 w-px bg-surface-border sm:inline-block"}),cs.map(f=>{const z=m===f.value;return e.jsx("button",{type:"button",onClick:()=>V(f.value),className:ae("rounded-full border px-2.5 py-0.5 text-[11px] transition-colors",z?"border-warning/40 bg-warning-soft/40 text-ink":"border-surface-border bg-surface text-ink-muted hover:border-warning/40 hover:bg-warning-soft/20"),title:z?"Click to clear this preset":"Click to apply this preset",children:f.label},f.value)})]})]})}const Qe=50;function us({lineage:t}){const s=(t.seed_alternative_text??"").trim(),i=s.length>60?`${s.slice(0,60)}…`:s,n=(()=>{const r=t.seed_alternative_id??"",u=r.lastIndexOf(":");if(u===-1)return null;const x=Number(r.slice(u+1));return Number.isFinite(x)?String.fromCharCode(65+x):null})();return e.jsxs(ot,{to:`/runs/${t.parent_run_id}`,title:"Navigate to the parent run that produced the seed alternative",className:ae("inline-flex items-center gap-1.5 rounded-full border border-border bg-surface-subtle/40 px-2.5 py-0.5 font-mono text-[10.5px] text-ink-muted hover:border-accent/40 hover:bg-accent-soft/30 hover:text-ink"),children:[e.jsx("span",{className:"text-ink-dim",children:t.kind==="variations"?"From run":"Re-run of run"}),e.jsxs("span",{className:"text-accent",children:["#",t.parent_run_id]}),t.kind==="variations"&&n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"· seed:"}),e.jsx("span",{className:"rounded bg-accent/15 px-1 text-[10px] font-semibold text-accent",children:n})]}),t.kind==="variations"&&i&&e.jsxs("span",{className:"max-w-[28rem] truncate text-ink-dim",children:['"',i,'"']})]})}function ms(t){if(Array.isArray(t.line_range)&&t.line_range.length===2){const[s,i]=t.line_range;if(Number.isFinite(s)&&s>0)return Number.isFinite(i)&&i>0&&i!==s?`${t.source}:${s}-${i}`:`${t.source}:${s}`}return typeof t.chunk_idx=="number"&&t.chunk_idx>0?`${t.source}:${t.chunk_idx}`:t.source}function nn(){const s=It().runId??"",i=s.startsWith("new-"),n=i?s.slice(4):"",r=i?null:Number(s);return!i&&(r===null||!Number.isFinite(r))?null:i?e.jsx(ps,{jobId:n}):e.jsx(vs,{runId:r})}function ps({jobId:t}){const s=Et(),i=Ye(),[n,r]=l.useState([]),[u,x]=l.useState(null),[o,m]=l.useState({}),[p,h]=l.useState(null),[b,E]=l.useState({input:0,output:0}),[q,j]=l.useState(null),[A,F]=l.useState(null),[V]=l.useState(()=>Date.now()),[f,z]=l.useState(()=>Date.now()),{events:L,closed:M,error:G}=Le({path:`/api/runs/${t}/events`,enabled:!0}),re=ke({queryKey:["job",t],queryFn:()=>xe(`/api/runs/${t}`),refetchInterval:M?!1:2e3,refetchOnWindowFocus:!1,retry:1});l.useEffect(()=>{const _=re.data?.run_id;typeof _=="number"&&u==null&&x(_)},[re.data,u]),l.useEffect(()=>{u!=null&&s(`/runs/${u}`,{replace:!0})},[u,s]),l.useEffect(()=>{if(M)return;const _=setInterval(()=>z(Date.now()),1e3);return()=>clearInterval(_)},[M]);const U=l.useRef(0);l.useEffect(()=>{L.length<U.current&&(U.current=0);const _=U.current;U.current=L.length;for(let te=_;te<L.length;te++){const v=L[te],Y=String(v.type||"");if(Y==="run.created"&&typeof v.run_id=="number")x(v.run_id);else if(Y==="run.scope.resolved"&&v.scope)m(v.scope);else if(Y==="activity.added")r(O=>[...O,{idx:Number(v.idx??O.length),label:String(v.label??"—"),status:"running"}]);else if(Y==="activity.complete"){const Q=Array.isArray(v.results)?v.results:[];r(ce=>ce.map(ee=>ee.idx===Number(v.idx)?{...ee,status:"done",detail:String(v.detail??""),results:Q}:ee))}else if(Y==="activity.fail")r(O=>O.map(Q=>Q.idx===Number(v.idx)?{...Q,status:"failed",detail:String(v.detail??"")}:Q));else if(Y==="tokens.snapshot")h({total_tokens:Number(v.total_tokens??0),total_cost_usd:Number(v.total_cost_usd??0)}),E({input:Number(v.input_tokens??0),output:Number(v.output_tokens??0)});else if(Y==="step.added"||Y==="step.begin"||Y==="step.update"){const O=String(v.label??"").trim();O&&(j(O),F(Date.now()))}else if(Y==="step.thinking"){const O=String(v.label??"Thinking").trim();j(O?`${O}…`:"Thinking…"),F(Date.now())}else if(Y==="step.complete"||Y==="step.fail")j(null),F(null);else if(Y==="tokens.delta"){const O=Number(v.total_in??0),Q=Number(v.total_out??0),ce=Number(v.total_cost_usd??0);(O||Q)&&h({total_tokens:O+Q,total_cost_usd:ce})}}},[L]),l.useEffect(()=>{M&&u!=null&&(i.invalidateQueries({queryKey:["recent-runs"]}),s(`/runs/${u}`,{replace:!0}))},[M,u,s,i]);const P=Re(),[X,k]=l.useState(!1),$=Ae({mutationFn:()=>we.cancelRun(t),onSuccess:()=>{k(!1),P.push({title:"Cancellation requested",description:"The worker bails between rows; already-written changes stay.",tone:"warning"})},onError:_=>{k(!1),P.push({title:"Cancel failed",description:_.message,tone:"error"})}}),R=L[L.length-1],y=R?String(R.type||""):"",w=l.useMemo(()=>{for(let _=n.length-1;_>=0;_--)if(n[_].status==="running")return n[_];return n[n.length-1]},[n]),B=n.filter(_=>_.status!=="running").length,C=Math.max(0,Math.floor((f-V)/1e3)),D=q&&A?Math.max(0,Math.floor((f-A)/1e3)):null,H=D!=null&&D>0?` (${De(D)})`:"";return e.jsxs(e.Fragment,{children:[e.jsx(Ve,{title:u?`Run #${u}`:M?y==="job.done"?"Run · ended":y==="job.cancelled"?"Run · cancelled":y==="job.failed"?"Run · failed":"Run · ended":n.length>0?"Run · running…":"Run · starting…",breadcrumbs:[{label:"Runs",to:"/runs"},{label:u?`#${u}`:"live"}],actions:!M&&e.jsx(W,{variant:"danger",size:"md",leadingIcon:e.jsx(kt,{size:14}),onClick:()=>k(!0),disabled:$.isPending,children:"Cancel"})}),!M&&e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-3 rounded-lg border border-accent/30 bg-accent-soft/40 px-4 py-2.5 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-accent-ink",children:[e.jsx(je,{size:14,className:"animate-spin"}),"running"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono tabular-nums text-ink",children:[e.jsx(Nt,{size:13,className:"text-ink-muted"}),De(C)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-ink",children:[e.jsx(Pt,{size:13,className:"text-ink-muted"}),e.jsx("span",{className:"text-ink-muted",children:"Now:"}),e.jsx("span",{className:"font-mono",children:w?q?`${w.label} — ${q}${H}`:w.label:q?`${q}${H}`:"Waiting for the worker…"})]}),p&&p.total_tokens>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono tabular-nums text-ink",title:p.total_cost_usd>0?"Running USD cost based on the prices recorded with each LLM call. Refresh prices via /refresh-prices.":"No price recorded for this model — run /refresh-prices or set a custom override via /cost.",children:[e.jsx("span",{className:"text-ink-muted",children:"↓"}),p.total_tokens.toLocaleString()," tok",p.total_cost_usd>0&&e.jsxs("span",{className:"text-positive",children:["· $",p.total_cost_usd.toFixed(4)]})]}),e.jsxs("span",{className:"ml-auto text-xs text-ink-dim",children:[B,"/",n.length||"—"," processed"]})]}),e.jsx(Je,{open:X,onClose:()=>k(!1),onConfirm:()=>$.mutate(),loading:$.isPending,title:"Cancel this run?",description:"The worker exits between rows. Already-written descriptions stay; in-flight assets stop. This cannot be undone.",confirmLabel:"Cancel run"}),p&&p.total_tokens>0&&e.jsxs(ne,{className:"mb-4",children:[e.jsx(Se,{title:"Tokens & cost",description:"Running totals while the worker streams. Frozen at run end into the persisted Metrics card."}),e.jsx(ie,{children:e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm md:grid-cols-4",children:[e.jsx(me,{label:"Input",children:e.jsxs("span",{className:"font-mono tabular-nums text-xs",children:["↑ ",b.input.toLocaleString()]})}),e.jsx(me,{label:"Output",children:e.jsxs("span",{className:"font-mono tabular-nums text-xs",children:["↓ ",b.output.toLocaleString()]})}),e.jsx(me,{label:"Total",children:e.jsx("span",{className:"font-mono tabular-nums text-xs font-semibold",children:p.total_tokens.toLocaleString()})}),e.jsx(me,{label:"Cost",children:e.jsx("span",{className:"font-mono tabular-nums text-xs",children:p.total_cost_usd>0?e.jsxs("span",{className:"text-positive",children:["$",p.total_cost_usd.toFixed(4)]}):e.jsx("span",{className:"text-ink-dim",title:"No price recorded for this model — set a custom override via /cost or run /refresh-prices.",children:"—"})})})]})})]}),e.jsxs(ne,{children:[e.jsx(Se,{title:"Progress",description:M?y==="job.done"?"Run completed.":y==="job.cancelled"?"Run cancelled.":"Run failed.":"Live activity from the worker."}),e.jsxs(ie,{className:"p-0",children:[Object.keys(o).length>0&&e.jsxs("div",{className:"border-b border-surface-border px-5 py-3 text-xs text-ink-muted",children:[e.jsx("span",{className:"text-ink-dim",children:"Scope:"})," ",e.jsx("span",{className:"font-mono",children:Object.entries(o).map(([_,te])=>te.length===0?`${_}.*`:te.map(v=>`${_}.${v}`).join(", ")).join(" · ")})]}),n.length===0?e.jsxs("div",{className:"px-5 py-6 text-sm text-ink-dim",children:[e.jsx(je,{size:14,className:"mr-2 inline animate-spin"}),q?`${q}${H}`:"Waiting for the worker to begin…"]}):e.jsx("ul",{className:"divide-y divide-surface-border",children:n.map(_=>e.jsxs("li",{className:"px-5 py-2.5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($t,{status:_.status}),e.jsx("span",{className:"font-mono",children:_.label}),_.detail&&e.jsx("span",{className:"ml-auto text-xs text-ink-muted",children:_.detail})]}),_.results&&_.results.length>0&&e.jsx("div",{className:"mt-3 space-y-2 border-l border-surface-border pl-4",children:_.results.map((te,v)=>e.jsx(xs,{detail:te},te.result_id??`${_.idx}-${v}`))})]},_.idx))}),G&&e.jsx("div",{className:"border-t border-surface-border px-5 py-2 text-xs text-critical",children:G})]})]})]})}function xs({detail:t}){const s=rt(t.alternatives),i=t.confidence==="high"?"positive":t.confidence==="low"?"warning":"neutral";return e.jsxs("div",{className:"rounded-md border border-surface-border bg-surface p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-xs",children:t.column??e.jsx("em",{className:"text-ink-dim",children:"(table)"})}),e.jsx(ut,{tone:i,children:t.confidence}),t.logprob_score!=null&&e.jsxs("span",{className:"font-mono text-[10px] text-ink-dim",children:["logprob ",t.logprob_score.toFixed(3)]}),e.jsx(Ht,{mode:t.alternatives_mode}),t.source&&e.jsx("span",{className:"ml-auto text-[10px] uppercase tracking-wider text-ink-dim",children:t.source})]}),e.jsx(St,{reasoning:t.reasoning??""}),e.jsx(wt,{citations:t.citations}),e.jsx("div",{className:"mt-2 space-y-1",children:s.length===0?e.jsx("div",{className:"text-xs text-ink-dim",children:t.chosen_description||"—"}):s.map((n,r)=>{const u=n.text===t.chosen_description||r===0&&!t.chosen_description,x=n.band&&We[n.band]?We[n.band].stripe:"bg-transparent";return e.jsxs("div",{className:ae("flex overflow-hidden rounded border text-xs",u?"border-accent/40 bg-accent-soft/30 text-ink":"border-surface-border text-ink-muted"),children:[e.jsx("div",{className:ae("hidden sm:block w-1 shrink-0",x),"aria-hidden":!0}),e.jsx("div",{className:"flex-1 px-2 py-1",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"mr-1.5 inline-block w-3 text-[10px] text-ink-dim",children:String.fromCharCode(65+r)}),n.text]}),e.jsx(lt,{alt:n})]})})]},r)})})]})}function wt({citations:t}){return!t||t.length===0?null:e.jsxs("div",{className:"mt-2 space-y-1 rounded-md border border-border bg-surface-subtle/20 px-2.5 py-1.5 text-xs text-ink-muted",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Sources"}),t.map((s,i)=>{const n=ms(s);return e.jsxs("div",{children:[e.jsxs("div",{className:"font-mono",children:[e.jsx("span",{className:"text-ink",children:n}),e.jsxs("span",{className:"ml-2 text-ink-dim",children:["score ",s.score.toFixed(2)]})]}),s.snippet&&e.jsxs("div",{className:"ml-3 mt-0.5 italic text-ink-dim line-clamp-2",children:["“",s.snippet,"…”"]})]},`${s.source}-${s.chunk_idx}-${i}`)})]})}function St({reasoning:t}){const[s,i]=l.useState(!1),n=(t||"").trim();return n?e.jsxs("button",{type:"button",onClick:()=>i(r=>!r),className:"mt-2 block w-full rounded-md border border-border bg-surface-subtle/20 px-2.5 py-1.5 text-left text-xs italic text-ink-muted transition hover:border-accent/30 hover:text-ink",title:s?"Click to collapse":n,children:[e.jsx("span",{className:"not-italic mr-2 text-[10px] uppercase tracking-wider text-ink-dim",children:"Why"}),e.jsx("span",{className:ae(s?"":"line-clamp-2"),children:n})]}):null}function De(t){if(!Number.isFinite(t)||t<0)return"0s";if(t<60)return`${t}s`;const s=Math.floor(t/60),i=t%60;if(s<60)return`${s}m ${i.toString().padStart(2,"0")}s`;const n=Math.floor(s/60),r=s%60;return`${n}h ${r.toString().padStart(2,"0")}m`}function Ct(t){if(!Array.isArray(t))return[];const s=[];for(const i of t)if(typeof i=="string")s.push(i);else if(i&&typeof i=="object"){const n=i;typeof n.text=="string"?s.push(n.text):typeof n.description=="string"&&s.push(n.description)}return s}function rt(t){let s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=[]}if(!Array.isArray(s))return[];const i=[];for(const n of s)if(typeof n=="string")i.push({text:n,signal:null,score:null,band:null});else if(n&&typeof n=="object"&&"text"in n){const r=n,u=String(r.text??""),x="signal"in r||"score"in r;i.push({text:u,signal:x&&typeof r.signal=="string"?r.signal:null,score:x&&typeof r.score=="number"?r.score:null,band:r.band==="HIGH"||r.band==="MED"||r.band==="LOW"?r.band:null})}else n&&typeof n=="object"&&"description"in n&&i.push({text:String(n.description),signal:null,score:null,band:null});return i}const We={HIGH:{stripe:"bg-positive",pill:"border border-positive/40 bg-positive-soft text-positive",label:"HIGH"},MED:{stripe:"bg-warning",pill:"border border-warning/40 bg-warning-soft text-warning",label:"MED"},LOW:{stripe:"bg-critical",pill:"border border-critical/40 bg-critical-soft text-critical",label:"LOW"}},fs={logprob:"LP",self_consistency:"SC",self_decl:"SD",judge:"JU"};function lt({alt:t}){if(!t.band||!We[t.band])return null;const s=We[t.band],i=typeof t.score=="number"?t.score.toFixed(2):null,n=t.signal?fs[t.signal]??null:null;return e.jsxs("details",{className:"inline-block relative align-middle",children:[e.jsxs("summary",{className:`cursor-pointer list-none select-none inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-medium ${s.pill}`,children:[e.jsx("span",{className:`sm:hidden inline-block h-2 w-2 rounded-full ${s.stripe}`,"aria-hidden":!0}),n&&e.jsxs("span",{className:"opacity-70",children:[n,":"]}),s.label,i&&e.jsx("span",{className:"opacity-70",children:i})]}),e.jsx("div",{className:"absolute right-0 z-10 mt-1 w-56 rounded-md border border-surface-border bg-surface p-2 text-[11px] text-ink shadow-lg",children:e.jsx("table",{className:"w-full",children:e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"py-0.5 pr-2 text-ink-dim",children:"Signal"}),e.jsx("td",{className:"py-0.5 text-right font-mono",children:t.signal??"—"})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"py-0.5 pr-2 text-ink-dim",children:"Score"}),e.jsx("td",{className:"py-0.5 text-right font-mono",children:i??"—"})]}),e.jsxs("tr",{className:"border-t border-surface-border font-medium",children:[e.jsx("td",{className:"py-0.5 pr-2",children:"Band"}),e.jsx("td",{className:"py-0.5 text-right font-mono",children:s.label})]})]})})})]})}function hs({run:t}){const s=t.tokens_json??{};let i=0,n=0;const r=s.records??[];if(r.length>0)for(const m of r)i+=Number(m.prompt_tokens??0),n+=Number(m.completion_tokens??0);else if(Array.isArray(s.summary))for(const m of s.summary)Array.isArray(m)&&m.length>=4&&(i+=Number(m[1]??0),n+=Number(m[2]??0));const u=i+n,x=u>0?u:typeof s.total_tokens=="number"?Number(s.total_tokens):0,o=typeof s.total_cost_usd=="number"?s.total_cost_usd:null;return x===0&&o==null?null:e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-surface-border bg-surface-subtle/60 px-2 py-0.5 font-mono tabular-nums text-[11px] text-ink",title:"Tokens consumed by this run (input ↑ + output ↓) and the USD cost frozen at run time. Open the Summary tab for the per-step breakdown.",children:[u>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"↑"}),nt(i),e.jsx("span",{className:"text-ink-dim",children:"↓"}),nt(n)]}),u===0&&x>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"tokens"}),nt(x)]}),o!=null&&o>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-ink-dim",children:"·"}),e.jsxs("span",{className:"text-positive",children:["$",o.toFixed(4)]})]})]})}function bs({run:t}){const s=t.scope_json??t.scope??{},i=t.database&&t.database.trim()||t.catalog&&t.catalog.trim()||"",n=Object.entries(s).filter(([o])=>o&&o!=="db_profile");if(n.length===0&&!i&&!t.db_profile)return null;const r=(()=>{if(n.length===0)return"All schemas";let o=0,m=!0;for(const[,p]of n)Array.isArray(p)&&p.length>0&&(o+=p.length,m=!1);if(n.length===1){const[p,h]=n[0];return Array.isArray(h)&&h.length>0?`${p} · ${h.length} ${h.length===1?"table":"tables"}`:`${p} (all tables)`}return m?`${n.length} schemas`:`${n.length} schemas · ${o} ${o===1?"table":"tables"}`})(),u=i?` @ ${i}`:"",x=t.db_profile?`${t.db_profile}`:"";return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-surface-border bg-surface-subtle/60 px-2 py-0.5 font-mono text-[11px] text-ink-muted",title:"Scope this run targeted. Open the Scope tab for the raw JSON.",children:[e.jsx("span",{className:"text-ink-dim",children:"scope"}),e.jsxs("span",{className:"text-ink",children:[x?`${x}${u} · `:"",r]})]})}function gs({run:t}){const s=t.metrics_json??{},i=Array.isArray(s.doc_profiles_used)?s.doc_profiles_used.filter(u=>u&&u.length>0):[],n=typeof s.rag_unavailable_reason=="string"?s.rag_unavailable_reason:null,r=typeof s.rag_hits_total=="number"?s.rag_hits_total:null;return i.length===0&&!n&&r==null?null:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-surface-border bg-surface-subtle/60 px-2 py-0.5 font-mono text-[11px] text-ink-muted",title:"Doc profiles fed into the RAG agent for this run.",children:[e.jsx("span",{className:"text-ink-dim",children:"docs"}),e.jsxs("span",{className:"text-ink",children:[i.length===0?"no docs used":i.join(", "),r!=null&&r>0?` · ${r.toLocaleString()} hits`:""]})]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-critical/30 bg-critical/5 px-2 py-0.5 font-mono text-[11px] text-critical",title:"The RAG store could not be opened. The run proceeded without document context.",children:["⚠ Docs unavailable: ",n]})]})}function js({run:t}){const s=t.metrics_json??{},i=Array.isArray(s.code_profiles_used)?s.code_profiles_used.filter(u=>u&&u.length>0):[],n=typeof s.code_unavailable_reason=="string"?s.code_unavailable_reason:null,r=typeof s.code_hits_total=="number"?s.code_hits_total:null;return i.length===0&&!n&&r==null?null:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-surface-border bg-surface-subtle/60 px-2 py-0.5 font-mono text-[11px] text-ink-muted",title:"Code profiles fed into the Code agent for this run.",children:[e.jsx("span",{className:"text-ink-dim",children:"code"}),e.jsxs("span",{className:"text-ink",children:[i.length===0?"no code used":i.join(", "),r!=null&&r>0?` · ${r.toLocaleString()} chunks`:""]})]}),n&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-critical/30 bg-critical/5 px-2 py-0.5 font-mono text-[11px] text-critical",title:"The Code RAG store could not be opened. The run proceeded without code context.",children:["⚠ Code unavailable: ",n]})]})}function nt(t){return!Number.isFinite(t)||t<=0?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function ys({jobId:t,startedAtEpochSec:s,initialStepLabel:i}){const[n,r]=l.useState([]),[u,x]=l.useState(null),[o,m]=l.useState(i??null),[p,h]=l.useState(null),[b,E]=l.useState([]),q=l.useRef(0),j=s!=null&&Number.isFinite(s)?Math.floor(s*1e3):Date.now(),[A,F]=l.useState(()=>Date.now()),{events:V,closed:f,error:z}=Le({path:`/api/runs/${t}/events`,enabled:!0});l.useEffect(()=>{if(f)return;const k=setInterval(()=>F(Date.now()),1e3);return()=>clearInterval(k)},[f]);const L=l.useRef(0);l.useEffect(()=>{V.length<L.current&&(L.current=0);const k=L.current;L.current=V.length;for(let $=k;$<V.length;$++){const R=V[$],y=String(R.type||"");if(y==="activity.added")r(w=>{const B=Number(R.idx??w.length);return w.some(C=>C.idx===B)?w:[...w,{idx:B,label:String(R.label??"—"),status:"running"}]});else if(y==="activity.complete"){const B=Array.isArray(R.results)?R.results:[];r(C=>C.map(D=>D.idx===Number(R.idx)?{...D,status:"done",detail:String(R.detail??""),results:B}:D)),m(null),h(null)}else if(y==="activity.fail")r(w=>w.map(B=>B.idx===Number(R.idx)?{...B,status:"failed",detail:String(R.detail??"")}:B)),m(null),h(null);else if(y==="step.added"||y==="step.begin"||y==="step.update"){const w=String(R.label??"").trim();w&&(m(w),h(Date.now()))}else if(y==="step.thinking"){const w=String(R.label??"Thinking").trim();m(w?`${w}…`:"Thinking…"),h(Date.now())}else if(y==="step.complete"||y==="step.fail"){const w=String(R.label??"").trim();if(w){const B=Math.max(0,Math.floor((Date.now()-j)/1e3));q.current+=1;const C=q.current;E(D=>{const H=[...D,{id:C,label:`${y==="step.fail"?"✗ ":"✓ "}${w}`,offsetSec:B}];return H.length>5?H.slice(H.length-5):H})}m(null),h(null)}else if(y==="tokens.snapshot")x({total_tokens:Number(R.total_tokens??0),total_cost_usd:Number(R.total_cost_usd??0)});else if(y==="tokens.delta"){const w=Number(R.total_in??0),B=Number(R.total_out??0),C=Number(R.total_cost_usd??0);(w||B)&&x({total_tokens:w+B,total_cost_usd:C})}}},[V]);const M=n.filter(k=>k.status!=="running").length,G=n.length,re=n.find(k=>k.status==="running"),U=Math.max(0,Math.floor((A-j)/1e3)),P=o&&p?Math.max(0,Math.floor((A-p)/1e3)):null,X=P!=null&&P>0?` (${De(P)})`:"";return e.jsxs(ne,{className:"mb-4 border-accent/40",children:[e.jsx(Se,{title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(je,{size:14,className:ae("text-accent",!f&&"animate-spin")}),"Live progress",G>0&&e.jsxs("span",{className:"rounded bg-surface-subtle px-1.5 py-0.5 font-mono text-[10px] text-ink-muted",title:G===1?"Tables in this run.":`Tables completed (${M} of ${G}).`,children:[M,"/",G," ",G===1?"table":"tables"]}),!f&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-surface-subtle px-1.5 py-0.5 font-mono tabular-nums text-[10px] text-ink-muted",title:"Time elapsed since the run page loaded",children:[e.jsx(Nt,{size:10}),De(U)]})]}),description:f?"Worker exited. The status badge above will refresh automatically.":re?o?`Now: ${re.label} — ${o}${X}`:`Now: ${re.label}`:o?`Now: ${o}${X}`:"Waiting for the worker to begin…"}),e.jsxs(ie,{className:"p-0",children:[u&&u.total_tokens>0&&e.jsx("div",{className:"border-b border-surface-border px-5 py-2 text-xs",children:e.jsxs("span",{className:"font-mono tabular-nums text-ink",children:[e.jsx("span",{className:"text-ink-muted",children:"Running totals: "}),"↓"," ",u.total_tokens.toLocaleString()," tokens",u.total_cost_usd>0&&e.jsxs("span",{className:"ml-2 text-positive",children:["$",u.total_cost_usd.toFixed(4)]})]})}),b.length>0&&e.jsxs("div",{className:"border-b border-surface-border px-5 py-2",children:[e.jsx("p",{className:"mb-1 text-[10px] font-semibold uppercase tracking-wider text-ink-dim",children:"Recent steps"}),e.jsx("ul",{className:"space-y-0.5 text-xs",children:b.map(k=>e.jsxs("li",{className:"flex items-center gap-2 font-mono tabular-nums text-ink-muted",children:[e.jsxs("span",{className:"text-[10px] text-ink-dim",children:["+",De(k.offsetSec)]}),e.jsx("span",{className:"truncate text-ink",children:k.label})]},k.id))})]}),n.length===0?e.jsxs("div",{className:"px-5 py-4 text-sm text-ink-dim",children:[e.jsx(je,{size:14,className:"mr-2 inline animate-spin"}),o?`Now: ${o}${X}`:"Waiting for the worker to begin…"]}):e.jsx("ul",{className:"divide-y divide-surface-border",children:n.map(k=>e.jsx("li",{className:"px-5 py-2 text-sm",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($t,{status:k.status}),e.jsx("span",{className:"font-mono",children:k.label}),k.detail&&e.jsx("span",{className:"ml-auto text-xs text-ink-muted",children:k.detail})]})},k.idx))}),z&&e.jsx("div",{className:"border-t border-surface-border px-5 py-2 text-xs text-critical",children:z})]})]})}function $t({status:t}){const s=t==="done"?"bg-positive":t==="failed"?"bg-critical":"bg-accent animate-pulse";return e.jsx("span",{className:ae("inline-block h-2 w-2 rounded-full",s)})}function vs({runId:t}){const[s,i]=l.useState("results"),[n,r]=l.useState(!1),u=Re(),x=Ye(),o=ke({queryKey:["run",t],queryFn:()=>xe(`/api/history/runs/${t}`),refetchInterval:b=>b.state.data?.live_job_id?3e3:!1,meta:{silentError:!0}}),m=o.data?.live_job_id??null,p=ke({queryKey:["run-results",t],queryFn:()=>xe(`/api/history/runs/${t}/results?include_history=true&include_descendants=true`),enabled:s==="results",refetchInterval:m?4e3:!1});l.useEffect(()=>{m||(x.invalidateQueries({queryKey:["run",t]}),x.invalidateQueries({queryKey:["run-results",t]}))},[m,t,x]);const h=Ae({mutationFn:()=>{if(!m)throw new Error("This run already finished.");return we.cancelRun(m)},onSuccess:()=>{r(!1),u.push({title:"Cancellation requested",description:"The worker bails between rows; already-written changes stay.",tone:"warning"}),x.invalidateQueries({queryKey:["run",t]})},onError:b=>{r(!1),u.push({title:"Cancel failed",description:b.message,tone:"error"})}});return o.isLoading&&!o.data?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{title:`Run #${t}`,breadcrumbs:[{label:"Runs",to:"/runs"},{label:`#${t}`}]}),e.jsx(ft,{status:"loading",hideLoadingTitle:!0,loadingBlocks:3})]}):o.error&&!o.data?e.jsxs(e.Fragment,{children:[e.jsx(Ve,{title:`Run #${t}`,breadcrumbs:[{label:"Runs",to:"/runs"},{label:`#${t}`}]}),e.jsx(ft,{status:"error",error:o.error,onRetry:()=>o.refetch()})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ve,{title:o.data?.command??`Run #${t}`,breadcrumbs:[{label:"Runs",to:"/runs"},{label:`#${t}`}],description:o.data?e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-x-2 gap-y-1 text-xs",children:[e.jsx(Ge,{tone:o.data.status==="success"?"positive":o.data.status==="failed"?"critical":o.data.status==="cancelled"?"warning":"neutral",dot:!0,children:o.data.status}),e.jsx("span",{className:"font-mono text-ink-muted tabular-nums",children:o.data.duration_sec!=null?`${o.data.duration_sec.toFixed(1)}s`:"—"}),e.jsx("span",{className:"font-mono text-ink-muted",children:o.data.llm_model??"—"}),e.jsx(hs,{run:o.data}),o.data.lineage&&e.jsx(us,{lineage:o.data.lineage}),e.jsx(bs,{run:o.data}),e.jsx(gs,{run:o.data}),e.jsx(js,{run:o.data})]}):void 0,actions:e.jsxs("div",{className:"flex items-center gap-3",children:[m&&e.jsx(W,{variant:"danger",size:"md",leadingIcon:e.jsx(kt,{size:14}),onClick:()=>r(!0),disabled:h.isPending,children:"Cancel"}),e.jsx(ot,{to:"/runs",className:"text-xs text-ink-dim hover:text-ink",children:"← All runs"})]})}),e.jsx(Je,{open:n,onClose:()=>r(!1),onConfirm:()=>h.mutate(),loading:h.isPending,title:"Cancel this run?",description:"The worker exits between rows. Already-written descriptions stay; in-flight assets stop. This cannot be undone.",confirmLabel:"Cancel run"}),m&&e.jsx(ys,{jobId:m,startedAtEpochSec:o.data?.started_at??null,initialStepLabel:o.data?.current_step_label??null}),e.jsxs(zt,{value:s,onValueChange:b=>i(b),children:[e.jsx(Dt,{children:["summary","results","scope","settings"].map(b=>e.jsx(Bt,{value:b,badge:b==="results"&&p.data?.count!=null?e.jsx("span",{className:"ml-1 rounded bg-surface-subtle px-1 text-[10px] text-ink-dim",children:p.data.count}):void 0,children:b[0].toUpperCase()+b.slice(1)},b))}),e.jsx(Ke,{value:"summary",children:e.jsx(ks,{run:o.data})}),e.jsxs(Ke,{value:"results",children:[p.data?.has_descendants&&e.jsxs("p",{className:"mb-3 text-[11px] text-ink-dim",children:["Showing ",p.data.count," original ·"," ",p.data.descendants?.length??0," ",(p.data.descendants?.length??0)===1?"variation / re-run":"variations / re-runs",". Each version below is independently collapsible — fall back to v1 at any time by collapsing the newer ones."]}),e.jsx(Cs,{runId:t,loading:p.isLoading,rows:p.data?.results??[],error:p.error,descendants:p.data?.descendants??[],runStatus:o.data?.status??null,runErrorText:o.data?.error_text??null,scope:{db_profile:o.data?.db_profile??null,database:o.data?.database??null,catalog:o.data?.catalog??null}})]}),e.jsx(Ke,{value:"scope",children:e.jsx(ne,{children:e.jsx(ie,{children:e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap rounded-md bg-ink p-3 font-mono text-xs text-bg",children:JSON.stringify(o.data?.scope_json??o.data?.scope??{},null,2)})})})}),e.jsx(Ke,{value:"settings",children:e.jsxs(ne,{children:[e.jsx(Se,{title:"Settings snapshot"}),e.jsx(ie,{children:e.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap rounded-md bg-ink p-3 font-mono text-xs text-bg",children:JSON.stringify(o.data?.settings_json??o.data?.settings??{},null,2)})})]})})]})]})}function ks({run:t}){if(!t)return e.jsx(ne,{children:e.jsx(ie,{children:"Loading…"})});const s=t.metrics??{};return e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ne,{children:[e.jsx(Se,{title:"Status"}),e.jsxs(ie,{className:"space-y-2 text-sm",children:[e.jsx(me,{label:"Status",children:e.jsx(ut,{tone:t.status==="success"?"positive":t.status==="failed"?"critical":"neutral",children:t.status})}),e.jsx(me,{label:"Duration",children:e.jsx("span",{className:"font-mono text-xs",children:t.duration_sec!=null?`${t.duration_sec.toFixed(2)}s`:"—"})}),e.jsx(me,{label:"LLM model",children:e.jsx("span",{className:"font-mono text-xs",children:t.llm_model??"—"})})]})]}),e.jsxs(ne,{children:[e.jsx(Se,{title:"Metrics"}),e.jsxs(ie,{className:"space-y-2 text-sm",children:[e.jsx(Ns,{run:t}),e.jsx(_s,{run:t}),Object.entries(s).length===0?e.jsx("div",{className:"text-ink-dim",children:"No metrics recorded."}):Object.entries(s).slice(0,10).map(([i,n])=>e.jsx(me,{label:i,children:e.jsx("span",{className:"font-mono text-xs",children:typeof n=="object"?JSON.stringify(n):String(n)})},i))]})]})]})}function Ns({run:t}){const s=t.tokens_json??{};let i=0,n=0;const r=s.records??[];if(r.length>0)for(const o of r)i+=Number(o.prompt_tokens??0),n+=Number(o.completion_tokens??0);else if(Array.isArray(s.summary))for(const o of s.summary)Array.isArray(o)&&o.length>=4&&(i+=Number(o[1]??0),n+=Number(o[2]??0));const u=i+n,x=u>0?u:typeof s.total_tokens=="number"?Number(s.total_tokens):0;return x===0?null:u===0?e.jsx(me,{label:"Tokens",children:e.jsxs("span",{className:"font-mono tabular-nums text-xs",children:[x.toLocaleString()," total",e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wider text-ink-dim",children:"(legacy run · no input/output split)"})]})}):e.jsx(me,{label:"Tokens",children:e.jsxs("span",{className:"inline-flex items-center gap-2 font-mono tabular-nums text-xs",children:[e.jsxs("span",{title:"Input (prompt) tokens billed at the input rate.",children:["↑ ",i.toLocaleString()]}),e.jsxs("span",{title:"Output (completion) tokens billed at the output rate — usually the dominant cost contributor.",children:["↓ ",n.toLocaleString()]}),e.jsx("span",{className:"text-ink-dim",children:"·"}),e.jsxs("span",{title:"Sum of input + output.",children:[x.toLocaleString()," total"]})]})})}function _s({run:t}){const s=t.tokens_json??{},i=typeof s.total_cost_usd=="number"?s.total_cost_usd:null,n=typeof s.total_tokens=="number"?s.total_tokens:null,r=t.llm_provider??"",u=t.llm_model??"",[x,o]=l.useState(null),[m,p]=l.useState(""),[h,b]=l.useState(!1),E=async()=>{if(!(!r||!u||n==null)){b(!0);try{const A=await we.lookupPrice(r,u),F=s.records??[];let V=0,f=0;for(const L of F)V+=Number(L.prompt_tokens??0),f+=Number(L.completion_tokens??0);const z=V/1e6*A.input_per_mtok+f/1e6*A.output_per_mtok;o(z),p(A.source)}finally{b(!1)}}};if(i==null&&x==null)return e.jsx(me,{label:"Cost",children:e.jsxs("span",{className:"text-xs text-ink-dim",children:[n!=null?"no cost data — pre-cost run, recompute below":"—",n!=null&&e.jsx("button",{type:"button",onClick:E,disabled:h,className:"ml-2 rounded border border-surface-border px-2 py-0.5 text-[10px] uppercase tracking-wider text-ink-muted hover:border-accent hover:text-accent disabled:opacity-50",children:h?"Recomputing…":"Recompute"})]})});const q=x??i,j=x!=null?`live · ${m||"?"}`:"frozen at run time";return e.jsx(me,{label:"Cost",children:e.jsxs("span",{className:"inline-flex items-center gap-2 font-mono text-xs",children:[e.jsxs("span",{children:["$",q.toFixed(4)]}),e.jsxs("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:["(",j,")"]}),r&&u&&e.jsx("button",{type:"button",onClick:E,disabled:h,className:"rounded border border-surface-border px-2 py-0.5 text-[10px] uppercase tracking-wider text-ink-muted hover:border-accent hover:text-accent disabled:opacity-50",children:h?"…":x!=null?"Refresh":"Recompute"})]})})}function me({label:t,children:s}){return e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-xs text-ink-dim",children:t}),e.jsx("span",{className:"truncate",children:s})]})}function ws({errorText:t}){const[s,i]=l.useState(!0),[n,r]=l.useState(!1),u=()=>{navigator.clipboard.writeText(t).then(()=>{r(!0),setTimeout(()=>r(!1),1500)})};return e.jsxs(ne,{children:[e.jsx(Se,{title:"Run failed"}),e.jsxs(ie,{children:[e.jsx("p",{className:"text-sm text-ink-muted",children:"The worker stopped before producing any per-column suggestions. The error below was captured on the run row (``analysis_runs.error_text``)."}),e.jsxs("div",{className:"mt-3 rounded-md border border-critical/30 bg-critical-soft/20 px-3 py-2 text-xs",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("button",{type:"button",onClick:()=>i(x=>!x),className:"inline-flex items-center gap-1 text-[11px] font-medium text-critical hover:underline",children:s?"Hide error details":"View error details"}),e.jsx("button",{type:"button",onClick:u,className:"rounded border border-critical/40 px-2 py-0.5 text-[10px] uppercase tracking-wider text-critical hover:bg-critical-soft/40",children:n?"Copied":"Copy traceback"})]}),s&&e.jsx("pre",{className:"mt-2 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md bg-ink p-2 font-mono text-[11px] text-bg",children:t})]})]})]})}function Ss({jobId:t,onTerminal:s}){const i=Le({path:`/api/runs/${encodeURIComponent(t)}/events`,enabled:!0});return l.useEffect(()=>{i.events.find(r=>r.type==="job.done"||r.type==="job.failed"||r.type==="job.cancelled")&&s()},[i.events]),null}function Cs({runId:t,loading:s,rows:i,error:n,descendants:r,runStatus:u,runErrorText:x,scope:o}){const m=Ye(),p=Re(),[h,b]=l.useState(null),[E,q]=l.useState(!1),[j,A]=l.useState(new Set),[F,V]=l.useState(!1),[f,z]=l.useState(null),L=l.useCallback(a=>{A(c=>{const d=new Set(c);return d.has(a)?d.delete(a):d.add(a),d})},[]),[M,G]=l.useState(o.database??""),[re,U]=l.useState(!1),[P]=l.useState(o.catalog??""),X=ke({queryKey:["live","databases",o.db_profile],queryFn:()=>xe(`/api/live/databases?profile=${encodeURIComponent(o.db_profile??"")}`),enabled:!!o.db_profile&&!o.database,retry:!1}),k=ke({queryKey:["pending"],queryFn:()=>xe("/api/pending"),retry:!1}),$=l.useMemo(()=>{const a=new Map;for(const c of k.data?.pending??[])c.result_id!=null&&a.set(c.result_id,c);return a},[k.data]),R=l.useMemo(()=>{const a=new Map;for(const c of k.data?.pending??[]){if(c.result_id==null)continue;const d=`${c.schema}.${c.table}.${c.column??"__table__"}`;a.set(d,c.result_id)}return a},[k.data]),{descendantsByV1Id:y,versionInfoByRowId:w}=l.useMemo(()=>{const a=new Map;for(const N of i){const K=`${N.schema_name}.${N.table_name}.${N.column_name??"__table__"}`;N.id!=null&&a.set(K,N.id)}const c=new Map;for(const N of r)for(const K of N.rows??[]){const oe=`${K.schema_name}.${K.table_name}.${K.column_name??"__table__"}`;if(!a.has(oe))continue;const J=c.get(oe)??[];J.push({row:K,entry:N}),c.set(oe,J)}const d=new Map,T=new Map;for(const[N,K]of c.entries()){const oe=a.get(N);if(oe==null)continue;K.sort((Z,tt)=>(Z.entry.run_id??0)-(tt.entry.run_id??0));const J=[];K.forEach((Z,tt)=>{J.push(Z.row),Z.row.id!=null&&T.set(Z.row.id,{versionLabel:`v${tt+2}`,kind:Z.entry.kind,runId:Z.entry.run_id,mode:Z.entry.mode,model:Z.entry.model,seedAlternativeId:Z.entry.seed_alternative_id,seedAlternativeText:Z.entry.seed_alternative_text??null,confidenceSignal:Z.entry.confidence_signal??null})}),d.set(oe,J)}for(const[,N]of a.entries())d.has(N)&&T.set(N,{versionLabel:"v1",kind:"original",runId:0,mode:null,model:null,seedAlternativeId:null,seedAlternativeText:null,confidenceSignal:null});return{descendantsByV1Id:d,versionInfoByRowId:T}},[i,r]),B=l.useMemo(()=>{const a=new Map,c=new Map;for(const d of i){const T=`${d.schema_name}.${d.table_name}.${d.column_name??"__table__"}`;d.id!=null&&c.set(T,d.id)}for(const d of r){if(!(d.status==="running"||d.status==="queued"))continue;const N=(()=>{const K=d.seed_alternative_id??"",oe=K.lastIndexOf(":");if(oe===-1)return null;const J=Number(K.slice(oe+1));return Number.isFinite(J)?J:null})();for(const K of d.rows??[]){const oe=`${K.schema_name}.${K.table_name}.${K.column_name??"__table__"}`,J=c.get(oe);if(J==null)continue;const Z=a.get(J)??[];Z.push({kind:d.kind,seedAltIdx:N,jobId:d.live_job_id??null,runId:d.run_id}),a.set(J,Z)}}return a},[i,r]),C=l.useCallback(()=>{m.invalidateQueries({queryKey:["run-results"]}),m.invalidateQueries({queryKey:["pending"]}),m.invalidateQueries({queryKey:["recent-runs"]})},[m]),D=Ae({mutationFn:()=>{const a=(o.database||M||"").trim(),c=(o.catalog||P||"").trim();return xe("/api/pending/apply",{method:"POST",body:JSON.stringify({db_profile:o.db_profile??void 0,database:a||void 0,catalog:c||void 0})})},onSuccess:a=>{b(a.job_id),p.push({title:"Apply started",description:"Watching the live worker stream below.",tone:"info",duration:1800})},onError:a=>p.push({title:"Apply failed",description:a.message,tone:"error"})}),H=Ae({mutationFn:a=>xe(`/api/pending/${a.idx}`,{method:"PATCH",body:JSON.stringify({final_description:a.description})}),onSuccess:()=>{m.invalidateQueries({queryKey:["pending"]}),p.push({title:"Description updated",tone:"info",duration:1800})},onError:a=>p.push({title:"Update failed",description:a.message,tone:"error"})}),_=Ae({mutationFn:a=>xe(`/api/pending/${a}`,{method:"DELETE"}),onSuccess:()=>{m.invalidateQueries({queryKey:["pending"]}),p.push({title:"Skipped",description:"Removed from the pending queue. You can restore it any time.",tone:"info",duration:2e3})},onError:a=>p.push({title:"Skip failed",description:a.message,tone:"error"})}),te=Ae({mutationFn:a=>we.restorePending(a),onSuccess:()=>{m.invalidateQueries({queryKey:["pending"]}),p.push({title:"Restored",description:"Back in the pending queue. Apply will write it on next run.",tone:"success",duration:2e3})},onError:a=>p.push({title:"Restore failed",description:a.message,tone:"error"})}),[v,Y]=qt(),O=l.useMemo(()=>({q:v.get("q")??"",sort:v.get("sort")??"natural",group:v.get("group")??"table",status:v.get("status")??"all",preset:v.get("preset")??null,page:Math.max(1,parseInt(v.get("page")??"1",10)||1),reviewMode:v.get("mode")==="review"}),[]),[Q,ce]=l.useState(O.q),[ee,Me]=l.useState(O.sort),[fe,Be]=l.useState(O.group),[de,Ie]=l.useState(O.status),[ue,Ee]=l.useState(O.preset),[ye,he]=l.useState(O.page),[be,Xe]=l.useState(O.reviewMode),[ve,g]=l.useState(new Set),[S,I]=l.useState(null),[qe,Ce]=l.useState(!1),Te=l.useRef(0),Fe=l.useRef(null),[pe,$e]=l.useState(null);l.useEffect(()=>{const a=new URLSearchParams(v),c=(d,T)=>{T?a.set(d,T):a.delete(d)};c("q",Q.trim()),c("sort",ee==="natural"?"":String(ee)),c("group",fe==="table"?"":String(fe)),c("status",de==="all"?"":String(de)),c("preset",ue??""),c("page",ye===1?"":String(ye)),c("mode",be?"review":""),a.toString()!==v.toString()&&Y(a,{replace:!0})},[Q,ee,fe,de,ue,ye,be]),l.useEffect(()=>{he(1)},[Q,ee,fe,de,ue]);const Rt=l.useCallback(a=>{g(c=>{const d=new Set(c);return d.has(a)?d.delete(a):d.add(a),d})},[]),se=l.useMemo(()=>{let a=i.slice();if(Q.trim()&&(a=a.filter(c=>ht(c,Q))),de!=="all"&&(a=a.filter(c=>Es(c,de,$))),ue==="low_conf"?a=a.filter(c=>ze(c)<.7):ue==="has_citations"?a=a.filter(c=>(c.citations_json??[]).length>0):ue==="table_only"&&(a=a.filter(c=>c.column_name==null)),ee==="status"){const c={pending:0,accepted:1,skipped:2,applied:3};a.sort((d,T)=>c[Ue(d,$)]-c[Ue(T,$)])}else ee!=="natural"&&a.sort(qs[ee]);return a},[i,Q,ee,de,ue,$]),Tt=l.useMemo(()=>{const a=Q.trim()?i.filter(N=>ht(N,Q)):i;let c=0,d=0,T=0;for(const N of a){const K=Ue(N,$);K==="pending"?c++:K==="accepted"?d++:K==="skipped"&&T++}return{all:a.length,unreviewed:c,accepted:d,skipped:T}},[i,Q,$]),Ze=l.useMemo(()=>{const a=[];for(const c of se)if(a.push(c),c.id!=null)for(const d of y.get(c.id)??[])a.push(d);return a},[se,y]),Oe=Math.max(1,Math.ceil(Ze.length/Qe)),Ne=Math.min(ye,Oe),Pe=l.useMemo(()=>{const a=(Ne-1)*Qe;return Ze.slice(a,a+Qe)},[Ze,Ne]),At=l.useMemo(()=>fe==="table"?Os(Pe):Fs(Pe,fe),[Pe,fe]),le=l.useMemo(()=>Pe.map(a=>a.id).filter(a=>a!=null),[Pe]);if(l.useEffect(()=>{const a=c=>{const d=c.target;if(d){const N=d.tagName;if((N==="INPUT"||N==="TEXTAREA"||N==="SELECT"||d.isContentEditable)&&c.key!=="Escape")return}if(c.metaKey||c.ctrlKey||c.altKey)return;const T=c.key;if(T==="j"){if(c.preventDefault(),!le.length)return;const N=S==null?-1:le.indexOf(S);N>=le.length-1?Ne<Oe&&(he(Ne+1),I(null)):I(le[N+1])}else if(T==="k"){if(c.preventDefault(),!le.length)return;const N=S==null?0:le.indexOf(S);N<=0?Ne>1&&(he(Ne-1),I(null)):I(le[N-1])}else if(T==="Enter"){if(S==null||!$.get(S))return;c.preventDefault(),p.push({title:"Row accepted",description:"Stays in the queue; Apply will write it.",tone:"success",duration:1500})}else if(T==="x"){if(S==null)return;const N=$.get(S);if(!N)return;c.preventDefault(),_.mutate(N.idx)}else if(T==="/")c.preventDefault(),Fe.current?.focus();else if(T==="g"){const N=Date.now();N-Te.current<500?(c.preventDefault(),le.length&&I(le[0]),Te.current=0):Te.current=N}else T==="G"?(c.preventDefault(),le.length&&I(le[le.length-1])):T==="?"?(c.preventDefault(),Ce(!0)):T==="Escape"&&(Ce(!1),I(null))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[le,S,Ne,Oe,$,_,p]),s)return e.jsx(ne,{children:e.jsx(ie,{children:"Loading results…"})});if(n)return e.jsx(ne,{children:e.jsx(ie,{className:"text-sm text-critical",children:n.message})});if(i.length===0){const a=u==="failed",c=(x??"").trim();return a?e.jsx(ws,{errorText:c||"Worker reported no error message."}):e.jsx(ne,{children:e.jsx(ie,{className:"text-sm text-ink-dim",children:"This run produced no per-column suggestions. (The missing-only filter dropped every asset, or the scope was empty.) For executor failures, check the run's status — failed runs surface the underlying error here."})})}const et=new Set;for(const a of i)a.id!=null&&et.add(a.id);for(const a of y.values())for(const c of a)c.id!=null&&et.add(c.id);let _e=0;for(const a of $.keys())et.has(a)&&(_e+=1);const mt=i.filter(a=>!!a.applied_at&&!(a.id!=null&&$.has(a.id))).length,Lt=_e===0&&!h,Mt=h?"Apply running…":_e===0?mt>0?"Queue empty — all applied":"Nothing to apply":`Apply pending queue (${_e})`,pt=!!(o.database&&o.database.trim()||M.trim()||o.catalog&&o.catalog.trim()||P.trim());return e.jsxs("div",{className:"space-y-3",children:[Array.from(B.entries()).flatMap(([a,c])=>c.filter(d=>!!d.jobId).map(d=>e.jsx(Ss,{jobId:d.jobId,onTerminal:C},`${a}-${d.runId}`))),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-xs text-ink-muted",children:["Run #",t," produced ",e.jsx("span",{className:"font-mono",children:i.length})," ","suggestion",i.length===1?"":"s"," —"," ",e.jsxs("span",{className:"text-positive",children:[mt," applied"]}),","," ",e.jsxs("span",{className:"text-ink",children:[_e," queued"]}),". Edit text inline, pick an alternative, or skip a row."]}),e.jsx(W,{variant:"primary",size:"md",leadingIcon:e.jsx(Xt,{size:14}),loading:D.isPending,disabled:!!h||Lt||D.isPending||!pt,onClick:()=>U(!0),title:pt?void 0:"Pick a target database below — this run didn't capture one.",children:Mt})]}),e.jsx(Je,{open:re,onClose:()=>U(!1),onConfirm:()=>{U(!1),D.mutate()},loading:D.isPending,title:`Apply ${_e} pending ${_e===1?"row":"rows"}?`,description:(()=>{const a=(o.database||M||o.catalog||"").trim(),c=o.db_profile||"";return`This writes COMMENT statements to ${c&&a?`${c} @ ${a}`:c||a||"the active database profile"}. The change is permanent — restoring the previous comment requires another apply with the old text. Cancel here to keep reviewing the queue.`})(),confirmLabel:`Apply ${_e}`}),!o.database&&!o.catalog&&o.db_profile&&e.jsx(ne,{children:e.jsxs(ie,{className:"space-y-2 px-4 py-3 text-xs",children:[e.jsxs("p",{className:"text-ink-muted",children:["This run didn't capture the target database. Pick the database the schemas live in so apply targets it directly — otherwise the COMMENTs would land in the active profile's default and produce",e.jsx("span",{className:"font-mono",children:' schema "…" does not exist'})," ","errors."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-ink-dim",children:"Profile:"}),e.jsx("span",{className:"font-mono",children:o.db_profile}),e.jsx("span",{className:"text-ink-dim",children:"·"}),e.jsx("span",{className:"text-ink-dim",children:"Database:"}),e.jsx("input",{type:"text",value:M,onChange:a=>G(a.target.value),placeholder:"e.g. car_retails_db",list:`db-suggestions-${t}`,className:"rounded-md border border-surface-border bg-surface px-2 py-1 font-mono text-xs"}),e.jsx("datalist",{id:`db-suggestions-${t}`,children:(X.data?.databases??[]).map(a=>e.jsx("option",{value:a},a))}),(X.data?.databases??[]).length>0&&e.jsxs("span",{className:"text-[10px] text-ink-dim",children:["(",X.data.databases.length," reachable)"]})]})]})}),h&&e.jsx(Ut,{jobId:h,kind:"apply",onCancel:async()=>{try{await xe(`/api/apply/${h}/cancel`,{method:"POST"})}catch{}},onTerminal:()=>{const a=()=>{m.invalidateQueries({queryKey:["pending"]}),m.invalidateQueries({queryKey:["run",t]}),m.invalidateQueries({queryKey:["run-results",t]}),m.invalidateQueries({queryKey:["recent-runs"]}),m.invalidateQueries({queryKey:["stats"]}),m.invalidateQueries({queryKey:["apply-events"]})};a(),window.setTimeout(a,1200),window.setTimeout(a,3e3),p.push({title:"Apply finished",description:"Pending queue and applied badges refreshed.",tone:"success",duration:2400}),b(null)}}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(W,{variant:"ghost",size:"sm",leadingIcon:e.jsx(He,{size:12}),onClick:()=>{q(a=>{const c=!a;return c||A(new Set),c})},children:E?"Cancel selection":"Select multiple to re-run"}),E&&j.size>0&&e.jsxs(e.Fragment,{children:[e.jsxs(W,{variant:"primary",size:"sm",onClick:()=>V(!0),disabled:!!f,children:["Re-Run selected (",j.size,")"]}),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>A(new Set),children:"Clear"})]}),f&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-ink-muted",children:[e.jsx(je,{size:12,className:"animate-spin"})," Bulk re-run running…"]})]}),e.jsx(Ts,{open:F,onOpenChange:V,rows:i,selectedIds:j,bulkRerunJobId:f,setBulkRerunJobId:z,onBulkDone:()=>{A(new Set),q(!1),m.invalidateQueries({queryKey:["run-results"]}),m.invalidateQueries({queryKey:["pending"]}),m.invalidateQueries({queryKey:["recent-runs"]})}}),e.jsx(ds,{query:Q,onQueryChange:ce,sort:ee,onSortChange:Me,group:fe,onGroupChange:Be,statusFilter:de,onStatusChange:Ie,presetActive:ue,onPresetChange:Ee,totalCount:i.length,visibleCount:se.length,statusCounts:Tt,searchInputRef:Fe}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(W,{variant:be?"primary":"ghost",size:"sm",onClick:()=>{Xe(a=>(a&&g(new Set),!a))},children:be?"Review mode: on":"Review mode: off"}),e.jsx("button",{type:"button",className:"text-xs text-ink-dim underline decoration-dotted underline-offset-2 hover:text-ink",onClick:()=>Ce(!0),children:"Keyboard shortcuts (?)"}),be&&e.jsxs("span",{className:"text-xs text-ink-muted",children:[ve.size," selected · use checkboxes to multi-pick"]})]}),be&&e.jsx(Rs,{selectedCount:ve.size,onAcceptSelected:()=>{p.push({title:`${ve.size} row(s) accepted`,description:"Stays in the queue. Apply will write them.",tone:"success",duration:1800}),g(new Set)},onSkipSelected:()=>{const a=Array.from(ve);for(const c of a){const d=$.get(c);d&&_.mutate(d.idx)}g(new Set)},onClearSelection:()=>g(new Set),onAcceptAllVisible:()=>$e("accept"),onSkipAllVisible:()=>$e("skip"),visibleCount:se.length}),e.jsx(Je,{open:pe!=null,onClose:()=>$e(null),onConfirm:()=>{if(pe==="skip"){for(const a of se){if(a.id==null)continue;const c=$.get(a.id);c&&_.mutate(c.idx)}p.push({title:`${se.length} row(s) skipped`,tone:"info",duration:1800})}else pe==="accept"&&p.push({title:`${se.length} row(s) accepted`,description:"Stays in the queue. Apply will write them.",tone:"success",duration:1800});$e(null)},title:pe==="skip"?`Skip ${se.length} visible row(s)?`:`Accept ${se.length} visible row(s)?`,description:pe==="skip"?`This removes ${se.length} row(s) from the pending queue. You can restore any of them from the run-detail row menu.`:`This keeps ${se.length} row(s) in the pending queue for the next Apply.`,confirmLabel:pe==="skip"?`Skip ${se.length}`:`Accept ${se.length}`}),e.jsx(dt,{open:qe,onClose:()=>Ce(!1),title:"Keyboard shortcuts",children:e.jsxs("ul",{className:"space-y-2 text-sm",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"j"})," / ",e.jsx(ge,{children:"k"})," ",e.jsx("span",{className:"text-ink-muted",children:"— move row focus down / up"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"Enter"})," ",e.jsx("span",{className:"text-ink-muted",children:"— accept the focused row"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"x"})," ",e.jsx("span",{className:"text-ink-muted",children:"— skip the focused row"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"/"})," ",e.jsx("span",{className:"text-ink-muted",children:"— focus the search input"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"g"})," ",e.jsx(ge,{children:"g"})," ",e.jsx("span",{className:"text-ink-muted",children:"— jump to the first row on page"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"G"})," ",e.jsx("span",{className:"text-ink-muted",children:"— jump to the last row on page"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"?"})," ",e.jsx("span",{className:"text-ink-muted",children:"— open this cheatsheet"})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(ge,{children:"Esc"})," ",e.jsx("span",{className:"text-ink-muted",children:"— close + clear row focus"})]})]})}),se.length===0&&e.jsx(ne,{children:e.jsx(ie,{className:"text-sm text-ink-dim",children:"No suggestions match the current filter combo. Clear the search or status chip to see more rows."})}),At.map(({key:a,rows:c})=>e.jsxs(ne,{children:[a?e.jsx(Se,{title:e.jsx("span",{className:"font-mono text-base",children:a}),description:`${c.length} suggestion${c.length===1?"":"s"}`}):null,e.jsx(ie,{className:"p-0",children:e.jsx("ul",{className:"divide-y divide-border",children:c.map(d=>{const T=d.id!=null?$.get(d.id):void 0,N=`${d.schema_name}.${d.table_name}.${d.column_name??"__table__"}`,K=R.get(N),oe=K!=null&&K!==d.id?{versionLabel:w.get(K)?.versionLabel??"v1"}:null;return e.jsx(Ls,{row:d,dbProfile:o.db_profile,pendingEntry:T,lockedByOtherVersion:oe,pickAlternative:J=>{T&&H.mutate({idx:T.idx,description:J})},skipRow:()=>{T&&_.mutate(T.idx)},restoreRow:J=>{const Z=Ct(d.alternatives_json);te.mutate({result_id:d.id??null,schema:d.schema_name,table:d.table_name,column:d.column_name,final_description:J,confidence:d.confidence||"medium",source:d.source||"user_restore",asset_kind:d.asset_kind||"table",alternatives:Z,logprob_score:d.logprob_score})},isMutating:H.isPending||_.isPending||te.isPending,multiSelectMode:E,isSelected:j.has(d.id),onToggleSelected:L,reviewMode:be,isReviewSelected:d.id!=null&&ve.has(d.id),onToggleReviewSelected:Rt,isKeynavFocused:d.id!=null&&S===d.id,versionInfo:d.id!=null?w.get(d.id)??null:null,hydratedRunningKinds:d.id!=null?(B.get(d.id)??[]).map(J=>({kind:J.kind,seedAltIdx:J.seedAltIdx})):[]},d.id)})})})]},a||"ungrouped")),Oe>1&&e.jsx($s,{currentPage:Ne,pageCount:Oe,onChange:a=>he(a),totalRows:se.length,pageSize:Qe})]})}function $s({currentPage:t,pageCount:s,onChange:i,totalRows:n,pageSize:r}){const u=l.useMemo(()=>{if(s<=7)return Array.from({length:s},(b,E)=>E+1);const m=[1];t>3&&m.push("ellipsis");const p=Math.max(2,t-1),h=Math.min(s-1,t+1);for(let b=p;b<=h;b++)m.push(b);return t<s-2&&m.push("ellipsis"),m.push(s),m},[t,s]),x=(t-1)*r+1,o=Math.min(n,t*r);return e.jsxs("nav",{className:"flex flex-wrap items-center justify-between gap-2","aria-label":"Results pagination",children:[e.jsxs("span",{className:"text-xs text-ink-muted",children:["Showing ",x,"–",o," of ",n]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>i(Math.max(1,t-1)),disabled:t<=1,children:"< Prev"}),u.map((m,p)=>m==="ellipsis"?e.jsx("span",{className:"px-1 text-ink-dim",children:"…"},`ellipsis-${p}`):e.jsx(W,{variant:m===t?"primary":"ghost",size:"sm",onClick:()=>i(m),children:m},m)),e.jsx(W,{variant:"ghost",size:"sm",onClick:()=>i(Math.min(s,t+1)),disabled:t>=s,children:"Next >"})]})]})}function Rs({selectedCount:t,onAcceptSelected:s,onSkipSelected:i,onClearSelection:n,onAcceptAllVisible:r,onSkipAllVisible:u,visibleCount:x}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md border border-surface-border bg-surface px-3 py-2",children:[e.jsxs(W,{variant:"primary",size:"sm",onClick:s,disabled:t===0,children:["Accept selected (",t,")"]}),e.jsxs(W,{variant:"ghost",size:"sm",onClick:i,disabled:t===0,children:["Skip selected (",t,")"]}),e.jsx(W,{variant:"ghost",size:"sm",onClick:n,disabled:t===0,children:"Clear selection"}),e.jsx("span",{className:"mx-1 h-4 w-px bg-surface-border","aria-hidden":!0}),e.jsxs(W,{variant:"ghost",size:"sm",onClick:r,disabled:x===0,children:["Accept all visible (",x,")"]}),e.jsxs(W,{variant:"ghost",size:"sm",onClick:u,disabled:x===0,children:["Skip all visible (",x,")"]})]})}function Ts({open:t,onOpenChange:s,rows:i,selectedIds:n,bulkRerunJobId:r,setBulkRerunJobId:u,onBulkDone:x}){const{push:o}=Re(),m=l.useMemo(()=>i.filter(h=>n.has(h.id)).map(h=>({resultId:h.id,label:[h.schema_name,h.table_name,h.column_name].filter(Boolean).join(".")||`result #${h.id}`})),[i,n]),p=Le({path:r?`/api/runs/${encodeURIComponent(r)}/events`:"",enabled:!!r});return l.useEffect(()=>{if(!r)return;const h=p.events.find(b=>b.type==="job.done"||b.type==="job.failed"||b.type==="job.cancelled");if(h){if(h.type==="job.done"){const b=h.summary;o({tone:"success",title:"Bulk re-run complete",description:b?`${b.successful}/${b.total} target(s) succeeded under run #${b.new_run_id??"?"}.`:"Re-run finished."})}else if(h.type==="job.failed"){const b=h.error;o({tone:"error",title:"Bulk re-run failed",description:b||"The worker reported an error."})}else o({tone:"warning",title:"Bulk re-run cancelled"});u(null),x()}},[p.events,r]),e.jsx(_t,{open:t,onClose:()=>s(!1),targets:m,onSubmitted:h=>{u(h),s(!1)},contextSummary:m.length===0?"Select rows in the lists below before opening this dialog.":void 0})}function As({row:t,dbProfile:s,pendingEntry:i,pickAlternative:n,skipRow:r,restoreRow:u,isMutating:x,multiSelectMode:o=!1,isSelected:m=!1,onToggleSelected:p,reviewMode:h=!1,isReviewSelected:b=!1,onToggleReviewSelected:E,isKeynavFocused:q=!1,versionInfo:j=null,hydratedRunningKinds:A=[],lockedByOtherVersion:F=null}){const V=(()=>{if(j!=null)return null;const g=t.history;if(!Array.isArray(g)||g.length===0)return null;const S=g[g.length-1];return!S||S.id===t.id?null:S})(),f=V??t,z=i?Ms(i.alternatives):Ct(f.alternatives_json),L=rt(i?i.alternatives:f.alternatives_json),M=new Map(L.map(g=>[g.text,g])),G=i?.final_description??f.chosen_description??"",re=M.get(G)??null,U=G&&!z.includes(G)?[G,...z]:z,P=!!t.applied_at,X=!!i,k=P&&!X,$=X,R=!P&&!X,y=$,w=V?.rerun_seq??t.rerun_seq??0,B=k?"positive":$?P?"warning":"neutral":"warning",C=k?"applied":$?P?"applied · revising":"accepted":R?"skipped":t.evaluation||"unreviewed",D=Ye(),{push:H}=Re(),[_,te]=l.useState(!1),[v,Y]=l.useState(null),[O,Q]=l.useState(null),[ce,ee]=l.useState(null),Me=Le({path:ce?`/api/runs/${encodeURIComponent(ce)}/events`:"",enabled:!!ce});l.useEffect(()=>{if(!ce)return;const g=Me.events.find(S=>S.type==="job.done"||S.type==="job.failed"||S.type==="job.cancelled");if(g){if(g.type==="job.done"){const I=g.summary?.new_run_id;H({tone:"success",title:"Variations complete",description:I?`New seeded variations saved under run #${I}.`:"Variations saved."})}else if(g.type==="job.failed"){const S=g.error;H({tone:"error",title:"Variations failed",description:S||"The worker reported an error."})}else H({tone:"warning",title:"Variations cancelled"});D.invalidateQueries({queryKey:["run-results"]}),D.invalidateQueries({queryKey:["recent-runs"]}),ee(null)}},[Me.events,ce]);const fe=A.filter(g=>g.kind==="variations"),Be=!!ce&&!Me.closed||fe.length>0,de=Le({path:v?`/api/runs/${encodeURIComponent(v)}/events`:"",enabled:!!v});l.useEffect(()=>{if(!v)return;const g=de.events.find(S=>S.type==="job.done"||S.type==="job.failed"||S.type==="job.cancelled");if(g){if(g.type==="job.done"){const I=g.summary?.new_run_id;H({tone:"success",title:"Re-run complete",description:I?`New alternatives saved under run #${I}.`:"New alternatives saved."})}else if(g.type==="job.failed"){const S=g.error;H({tone:"error",title:"Re-run failed",description:S||"The worker reported an error."})}else H({tone:"warning",title:"Re-run cancelled"});D.invalidateQueries({queryKey:["run-results"]}),D.invalidateQueries({queryKey:["pending"]}),D.invalidateQueries({queryKey:["recent-runs"]}),Y(null)}},[de.events,v]);const Ie=!!v&&!de.closed||A.some(g=>g.kind==="rerun"),ue=(()=>{const g=[];return t.schema_name&&g.push(t.schema_name),t.table_name&&g.push(t.table_name),t.column_name&&g.push(t.column_name),g.join(".")||"(unnamed)"})(),Ee=t.column_name==null,ye=l.useMemo(()=>({run_id:t.run_id,db:null,schema:t.schema_name,table:t.table_name,column:t.column_name??null}),[t.run_id,t.schema_name,t.table_name,t.column_name]),[he,be]=l.useState(()=>Kt(s,ye)),Xe=l.useCallback(()=>{he?(Qt(s,ye),be(!1)):(Vt(s,ye),be(!0)),typeof window<"u"&&window.dispatchEvent(new CustomEvent("amx:pinned-cells-changed"))},[s,he,ye]),ve=l.useRef(null);return l.useEffect(()=>{q&&ve.current&&ve.current.scrollIntoView({block:"nearest"})},[q]),e.jsxs("li",{ref:ve,className:ae("px-5 py-3",Ee&&"border-l-2 border-l-accent/70 bg-accent-soft/10",q&&"outline outline-2 outline-accent"),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[o&&e.jsx(xt,{checked:m,onChange:()=>p?.(t.id),"aria-label":`Select ${ue} for bulk re-run`,className:"mr-1"}),h&&e.jsx(xt,{checked:b,onChange:()=>{t.id!=null&&E?.(t.id)},"aria-label":`Select ${ue} for bulk review action`,className:"mr-1"}),Ee&&e.jsx("span",{className:"rounded-sm bg-accent-soft/60 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-accent-ink",children:"Table"}),e.jsx("span",{className:ae("font-mono",Ee?"text-sm font-semibold text-ink":"text-ink"),children:t.column_name??t.table_name}),e.jsx(Jt,{value:t.confidence,score:t.logprob_score}),e.jsx(ut,{tone:B,children:C}),e.jsx(Wt,{score:t.logprob_score}),re&&e.jsx(lt,{alt:re}),j!=null&&e.jsx("span",{title:j.kind==="original"?"Original alternatives for this asset":j.kind==="variations"?`Variations · run #${j.runId}`:`Re-Run · run #${j.runId}`,children:e.jsx(Ge,{tone:"info",children:j.versionLabel})}),t.production_warning&&e.jsx("span",{title:`${t.production_warning}. Two possible causes: (1) the LLM genuinely returned fewer blocks than requested, or (2) the output parser dropped a malformed block silently. Check the backend studio.log for the raw response if the count keeps missing the requested N.`,children:e.jsxs(Ge,{tone:"warning",children:["⚠ ",t.production_warning]})}),j==null&&w>0&&e.jsx("span",{title:f.user_instructions?`Re-run version ${w}. User added: "${f.user_instructions}"`:`Re-run version ${w}.`,children:e.jsxs(Ge,{tone:"info",children:["v",w+1]})}),e.jsxs("span",{className:"ml-auto inline-flex items-center gap-2",children:[t.source&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:t.source}),e.jsx(st,{icon:he?e.jsx(es,{size:12}):e.jsx(Gt,{size:12}),label:he?"Unpin from compare drawer":"Pin this cell for cross-run comparison",size:"sm",variant:"ghost",onClick:Xe,className:ae(he&&"text-accent")}),e.jsx(st,{icon:Ie?e.jsx(je,{size:12,className:"animate-spin"}):e.jsx(He,{size:12}),label:Ie?"Re-running…":"Re-Run this item with optional new instructions",size:"sm",variant:"ghost",onClick:()=>te(!0),disabled:x||Ie}),y&&e.jsx(st,{icon:e.jsx(ss,{size:12}),label:"Skip — remove from pending queue",size:"sm",variant:"ghost",onClick:r,disabled:x})]})]}),j!=null&&j.kind!=="original"&&e.jsxs("div",{className:"mt-1.5 inline-flex flex-wrap items-center gap-x-2 gap-y-0.5 rounded-md border border-border bg-surface-subtle/30 px-2.5 py-1 text-[10.5px] text-ink-dim",children:[e.jsx("span",{className:"text-ink-muted",children:j.kind==="variations"?(()=>{const g=j.seedAlternativeId??"",S=g.lastIndexOf(":"),I=Number(g.slice(S+1));return`variations of ${Number.isFinite(I)?String.fromCharCode(65+I):"?"}`})():"re-run"}),e.jsxs(ot,{to:`/runs/${j.runId}`,className:"font-mono text-accent hover:underline",title:"Open this version on its own detail page",children:["run #",j.runId]}),j.mode&&e.jsxs("span",{children:["· ",j.mode]}),j.confidenceSignal&&e.jsxs("span",{className:"font-mono",title:"Confidence signal active when this version ran. Badge types between v1 and vN can legitimately differ; the badge type on each row matches the signal active when that row was produced.",children:["· ",j.confidenceSignal]}),j.model&&e.jsxs("span",{className:"font-mono",children:["· ",j.model]}),j.seedAlternativeText&&e.jsxs("span",{className:"block w-full italic",children:["Seed:"," ",e.jsxs("span",{className:"font-mono not-italic text-ink-muted",children:['"',j.seedAlternativeText,'"']})]})]}),e.jsx(_t,{open:_,onClose:()=>te(!1),targets:[{resultId:t.id,label:ue}],onSubmitted:g=>Y(g)}),O&&e.jsx(is,{open:!0,onClose:()=>Q(null),originalRunId:t.run_id,resultId:t.id,alternativeIndex:O.altIndex,seedText:O.altText,seedLetter:O.altLetter,initialMode:f.alternatives_mode==="lexical"?"lexical":"semantic",onSubmitted:g=>{ee(g),Q(null)}}),y&&e.jsxs("div",{className:"mt-2 rounded-md border border-border bg-surface-subtle/30 px-2.5 py-1.5 text-xs",children:[e.jsx("div",{className:"mb-0.5 text-[10px] uppercase tracking-wider text-ink-dim",children:"Chosen — edit text directly"}),e.jsx(Yt,{value:G,onSave:g=>n(g),multiline:!0,italicEmpty:!0,emptyLabel:"(empty — click to write a custom description)"})]}),e.jsx(St,{reasoning:f.reasoning??""}),e.jsx(wt,{citations:f.citations_json}),e.jsxs("div",{className:"mt-2 space-y-1",children:[U.length===0?e.jsx("p",{className:"text-xs text-ink-dim",children:G||"—"}):U.map((g,S)=>{const I=g===G,qe=y&&!I,Ce=(R||k)&&!I,Te=y&&I&&!P,Fe=(qe||Ce||Te)&&!F;return e.jsxs("button",{type:"button",onClick:()=>{Te?r():qe?n(g):Ce&&u(g)},disabled:!Fe||x,title:F?`Locked: this asset already has a selection on ${F.versionLabel}. Deselect it there first to pick from this version.`:k?I?"Currently applied to the live database.":"Click to queue this alternative as a revision -- the next Apply overwrites the live comment.":P?I?"Pending revision uses this alternative -- Apply to overwrite the live comment.":"Make this the queued revision (does not write to the database until Apply).":R?"Click to restore this row to the pending queue with this alternative chosen.":I?"Click again to deselect — sends the row back to the unreviewed queue.":"Make this the chosen alternative",className:ae("flex w-full items-start gap-2 rounded-md border px-2.5 py-1.5 text-left text-xs transition-colors duration-fast",I?"border-accent/40 bg-accent-soft/40 text-ink":R?"border-warning/30 text-ink-muted hover:border-warning/60 hover:bg-warning-soft/30 hover:text-ink":"border-border text-ink-muted hover:border-accent/40 hover:bg-surface-subtle/50 hover:text-ink",(!Fe||x)&&!I&&"cursor-default opacity-70 hover:border-border hover:bg-transparent hover:text-ink-muted"),children:[e.jsx("span",{className:ae("mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-[10px] font-semibold",I?"bg-accent text-white":"bg-surface-subtle text-ink-dim"),children:I?"✓":String.fromCharCode(65+S)}),e.jsx("span",{className:"flex-1 leading-relaxed",children:g}),(()=>{const pe=M.get(g);return pe?e.jsx(lt,{alt:pe}):null})(),U.length>=2&&(Be?e.jsx("span",{title:"Generating variations…",className:"ml-1 inline-flex h-5 w-5 shrink-0 items-center justify-center text-accent",children:e.jsx(je,{size:11,className:"animate-spin"})}):e.jsx("button",{type:"button",onClick:pe=>{pe.stopPropagation();const $e=I?"✓":String.fromCharCode(65+S);Q({altIndex:S,altText:g,altLetter:$e==="✓"?"★":$e})},title:"Generate variations from this alternative",className:"ml-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-ink-dim hover:bg-surface-subtle hover:text-accent","aria-label":"Generate variations from this alternative",children:e.jsx(it,{size:11})}))]},`${t.id}-${S}`)}),R&&U.length>0&&e.jsx("p",{className:"px-1 text-[10.5px] text-ink-dim",children:"Skipped — click any alternative above to restore this row."}),k&&U.length>0&&e.jsx("p",{className:"px-1 text-[10.5px] text-ink-dim",children:"Applied — pick a different alternative above to queue a revision, then Apply to overwrite the live comment."}),Be&&e.jsxs("p",{className:"px-1 text-[10.5px] text-accent inline-flex items-center gap-1",children:[e.jsx(je,{size:10,className:"animate-spin","aria-hidden":!0}),"Generating variations… results will appear here and in /history when done."]})]})]})}const Ls=l.memo(As);function Ms(t){const s=[];for(const n of t??[])if(typeof n=="string")s.push(n);else if(n&&typeof n=="object"){const r=n;typeof r.text=="string"?s.push(r.text):typeof r.description=="string"&&s.push(r.description)}const i=new Set;return s.filter(n=>i.has(n)?!1:(i.add(n),!0))}const Is={low:.3,medium:.6,high:.9};function ze(t){const s=(t.confidence||"medium").toLowerCase();return Is[s]??.6}function Ue(t,s){return t.applied_at?"applied":t.id!=null&&s.has(t.id)?"accepted":"pending"}function Es(t,s,i){if(s==="all")return!0;const n=Ue(t,i);return s==="unreviewed"?n==="pending":s==="accepted"?n==="accepted":s==="skipped"?n==="skipped":!0}function ht(t,s){const i=s.trim().toLowerCase();return i?[t.schema_name,t.table_name,t.column_name??"",t.chosen_description??""].join(" ").toLowerCase().includes(i):!0}const qs={natural:()=>0,"conf-asc":(t,s)=>ze(t)-ze(s),"conf-desc":(t,s)=>ze(s)-ze(t),"logprob-asc":(t,s)=>{const i=t.logprob_score??Number.POSITIVE_INFINITY,n=s.logprob_score??Number.POSITIVE_INFINITY;return i-n},"logprob-desc":(t,s)=>{const i=t.logprob_score??Number.NEGATIVE_INFINITY;return(s.logprob_score??Number.NEGATIVE_INFINITY)-i},"name-asc":(t,s)=>t.schema_name!==s.schema_name?t.schema_name.localeCompare(s.schema_name):t.table_name!==s.table_name?t.table_name.localeCompare(s.table_name):t.column_name==null&&s.column_name!=null?-1:t.column_name!=null&&s.column_name==null?1:(t.column_name??"").localeCompare(s.column_name??""),status:()=>0};function Fs(t,s){if(s==="none")return[{key:"",rows:t}];const i=new Map;for(const n of t){const r=s==="schema"?n.schema_name:`${n.schema_name}.${n.table_name}`,u=i.get(r)??[];u.push(n),i.set(r,u)}return Array.from(i.entries()).map(([n,r])=>({key:n,rows:r}))}function Os(t){const s=new Map;for(const i of t){const n=`${i.schema_name}.${i.table_name}`,r=s.get(n)??[];r.push(i),s.set(n,r)}for(const i of s.values())i.sort((n,r)=>{const u=n.column_name==null?0:1,x=r.column_name==null?0:1;return u!==x?u-x:(n.column_name??"").localeCompare(r.column_name??"")});return Array.from(s.entries()).map(([i,n])=>({key:i,rows:n}))}export{nn as default};
