1import{j as s,r as m,L as Je}from"./vendor-EG-m3W-5.js";import{w as ce,T as de,a as ue,l as me,o as he,q as fe,c as ge,b as X,u as He,d as Ve,k as Qe}from"./firestoreSdk-Bpg0pgBT.js";import{dR as Le,B as L,aa as $e,bm as Ye,bx as Ze,C as Xe,u as et,dS as tt,I as st,l as rt,aI as at,aD as nt}from"./index-duHAMWks.js";import{i as ot,u as lt}from"./monitoringRangeCutoff-4F6PEMeF.js";import{W as Me}from"./wrench-DhLsSVdr.js";import{C as it}from"./copy-DfE3oOzU.js";const ct=120*1e3;function C(e){if(!e)return 0;if(typeof e=="number")return e;if(typeof e=="string"){const t=Date.parse(e);return Number.isFinite(t)?t:0}if(e instanceof Date)return e.getTime();if(typeof e=="object"&&typeof e.toMillis=="function"){const t=e.toMillis();return Number.isFinite(t)?t:0}return typeof e=="object"&&typeof e.seconds=="number"?e.seconds*1e3:typeof e=="object"&&typeof e._seconds=="number"?e._seconds*1e3:0}function ye(e){if(typeof e=="string")return e.replace(/\s+/g," ").trim();if(e==null)return"";try{return JSON.stringify(e).replace(/\s+/g," ").trim()}catch{return String(e).replace(/\s+/g," ").trim()}}function V(e){return ye(e).toLowerCase()}function H(e){if(e&&typeof e=="object"&&!Array.isArray(e))return e;if(typeof e!="string")return null;try{const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function j(e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function dt(e){if(typeof e!="string")return null;const t=ye(e);return!t||!/^(error|failed|failure|exception)\b/i.test(t)&&!/\b(timed out|timeout|not authorized|required|invalid)\b/i.test(t)?null:t.slice(0,1200)}function ut(e){if(!Array.isArray(e))return null;for(const t of e){if(typeof t=="string"&&t.trim())return t.trim();if(t&&typeof t=="object"){const a=j([t.error,t.message]);if(a)return a}}return null}function mt(e){const t=H(e);if(!t)return dt(e);if(Le(t))return null;const a=j([t.error,t.errorMessage,t.error_message,t.status_msg,t.statusMessage]);if(a)return a;const r=ut(t.errors);if(r)return r;if(t.success===!1||t.ok===!1)return j([t.message,t.reason,t.detail,t.status])||"Tool reported an unsuccessful status";const l=V(t.status);return l==="error"||l==="failed"||l==="failure"||l==="fail"?j([t.message,t.reason,t.detail])||"Tool returned an error status":null}function se(e,t={}){return!e||Le(e)?!0:ot({...t,error:e})}function ht(e,t){if(e==="fixed")return"resolved";const a=t?.outcome;return a==="fixed"||a==="invalid"?"resolved":a==="reviewed"||e==="reviewed"?"analyzed":e==="seen"?"acknowledged":"open"}function ft(e){const t=e.selfHealingResolution??null,a=ht(e.status,t);if(a==="resolved")return null;const r=e.type==="user-feedback"?"user-feedback":e.type==="agent-error"?"agent-error":"tool-error";if(r!=="user-feedback"&&se(e.error,e))return null;const l=e.chatId||null,c=r==="user-feedback"?e.message||e.error:e.error||e.message,u=r==="user-feedback"?"user":"auto";return{id:`feedback:${e.id}`,feedbackId:e.id,source:"feedback",type:r,state:a,resolution:t,userId:e.userId,chatId:l,chatTitle:e.chatTitle??null,message:e.message??null,error:e.error??null,toolName:e.toolName??null,createdAt:e.createdAt,dedupeKey:`${u}:${l||e.userId||e.id}:${e.toolName||r}:${V(c)}`}}function re(e,t,a,r){const l=e.chatId||e.id,c=r.toolName||null;return{id:`${t}:${e.id}:${r.idPart}`,source:t,type:t==="stale-processing"?"agent-error":"tool-error",state:"open",userId:e.userId,chatId:l,chatTitle:e.title||null,message:r.message??null,error:a,toolName:c,createdAt:r.createdAt??e.updatedAt??e.createdAt,dedupeKey:`auto:${l}:${c||t}:${V(a)}`}}function Te(e){return Array.isArray(e.messages)?e.messages:[]}function Re(e){const t=new Map;for(const a of e)if(Array.isArray(a.tool_calls))for(const r of a.tool_calls)r.id&&r.function?.name&&t.set(r.id,r.function.name);return t}function gt(e){const t=Te(e),a=Re(t),r=[];return t.forEach((l,c)=>{if(l.role!=="tool")return;const u=mt(l.content);u&&(se(u,H(l.content)??{})||r.push(re(e,"chat-tool",u,{idPart:`${l.tool_call_id||c}:${V(u).slice(0,80)}`,toolName:l.tool_call_id?a.get(l.tool_call_id):null,createdAt:l.createdAt})))}),r}function xt(e){return(Array.isArray(e.ffmpegCards)?e.ffmpegCards:[]).filter(a=>a.status==="error").map((a,r)=>
1{const l=a.errorMessage||`${a.title||a.toolName||"FFmpeg tool"} failed`;return re(e,"ffmpeg-card",l,{idPart:`${a.afterMessageIndex??r}:${a.toolName||"ffmpeg"}`,toolName:a.toolName||"ffmpeg"})}).filter(a=>!se(a.error))}function N(e,t,a){const r=`${a.id}:${a.toolName}:${a.source}`;t.has(r)||(t.add(r),e.push(a))}function pt(e){const t=[],a=new Set;for(const r of e.songCards||[])r.taskId&&N(t,a,{id:r.taskId,toolName:"generate_song",title:r.title,source:"card"});for(const r of e.stemCards||[])r.taskId&&N(t,a,{id:r.taskId,toolName:"separate_stems",title:r.title,source:"card"});for(const r of e.captureCards||[])r.captureId&&N(t,a,{id:r.captureId,toolName:"capture_audio",title:r.title,source:"card"});for(const r of e.lyricsCards||[])r.lyricsId&&N(t,a,{id:r.lyricsId,toolName:"lyrics",title:r.title,source:"card"});for(const r of e.coverConfigCards||[])r.taskId&&N(t,a,{id:r.taskId,toolName:"execute_cover",title:r.title,source:"card"});for(const r of e.runCards||[])r.runId&&N(t,a,{id:r.runId,toolName:r.pipeline||"run_tool",title:r.title,source:"card"});return t}function bt(e){const t=Te(e),a=Re(t),r=[],l=new Set;for(const c of t){if(c.role!=="tool")continue;const u=H(c.content);if(!u)continue;const w=(c.tool_call_id?a.get(c.tool_call_id):void 0)||"tool-result",k=j([u.title,u.name]);if(typeof u.task_id=="string"&&u.task_id.trim()&&N(r,l,{id:u.task_id.trim(),toolName:w,title:k||void 0,source:"tool-result"}),Array.isArray(u.tasks))for(const I of u.tasks){const A=H(I),i=j([A?.task_id,A?.taskId]);i&&N(r,l,{id:i,toolName:w,title:j([A?.title,A?.name])||k||void 0,source:"tool-result"})}const T=j([u.capture_id,u.captureId]);T&&N(r,l,{id:T,toolName:"capture_audio",title:k||void 0,source:"tool-result"});const D=j([u.lyrics_id,u.lyricsId]);D&&N(r,l,{id:D,toolName:w==="tool-result"?"lyrics":w,title:k||void 0,source:"tool-result"});const R=j([u.run_id,u.runId]);R&&N(r,l,{id:R,toolName:j([u.pipeline])||w,title:k||void 0,source:"tool-result"})}return r}function Fe(e){const t=[],a=new Set;for(const r of[...pt(e),...bt(e)])N(t,a,r);return t}function wt(e,t){const a=new Set,r=[];for(const l of Fe(e)){if(a.has(l.id))continue;a.add(l.id);const c=t.get(l.id),u=V(c?.status);if(!c||u!=="error"&&u!=="failed"&&u!=="failure")continue;const h=c.error||c.message||`${c.title||l.title||l.toolName} failed`;se(h,c)||r.push(re(e,"linked-run",h,{idPart:`${l.id}:${l.toolName}`,toolName:l.toolName,createdAt:c.updatedAt||c.completedAt||c.createdAt||e.updatedAt,message:c.message||null}))}return r}function yt(e){if(!e.processing)return[];const t=C(e.processingHeartbeat)||C(e.activeToolCall?.startedAt)||C(e.updatedAt);if(!t||Date.now()-t<ct)return[];const a=Math.max(2,Math.round((Date.now()-t)/6e4));return[re(e,"stale-processing",`Agent chat has been processing without a fresh heartbeat for ${a} minutes`,{idPart:`stale:${t}`,toolName:e.activeToolCall?.tool||null,createdAt:e.processingHeartbeat||e.updatedAt||e.createdAt})]}function Nt(e,t=new Map){return[...gt(e),...xt(e),...wt(e,t),...yt(e)]}const De={"user-report":{label:"User reported a bad result",shortLabel:"User reports",hint:"A real person said the output was wrong. Read their words first.",recoverable:!1},stuck:{label:"Chat stuck while processing",shortLabel:"Stuck chats",hint:"The stream died without releasing the lock â the user cannot send another message until it expires.",recoverable:!1},"agent-slip":{label:"Agent passed a bad argument",shortLabel:"Agent slips",hint:"The tool rejected the agent's input and told it how to recover. Watch the rate, not the single event.",recoverable:!0},"missing-reference":{label:"Referenced item not found",shortLabel:"Not found",hint:"The agent polled an id that does not exist â usually a hallucinated or stale reference.",recoverable:!0},"rejected-input":{label:"Provider rejected the input",shortLabel:"Bad input",hint:"A length/format limit was exceeded. Clamp it before submitting instead of failing the run.",recoverable:!1},"source-blocked":{label:"Source could not be downloaded",shortLabel:"Source blocked",hint:"The upstream site blocked, gated, or removed the media. Usually not a Vocuno bug.",recoverable:!1},"provider-failed":{label:"Provider or pipeline failed",shortLabel:"Failures",hint:"An external provider or a Vocuno pipeline errored out. Check the linked run.",recoverable:!1},timeout:{label:"Timed out",shortLabel:"Timeouts",hint:"The operation exceeded its budget. Check provider latency and the polling window.",recoverable:!1},permission:{label:"Blocked by permissions or plan",shortLabel:"Blocked",hint:"Authorization, plan gate, or ownership check refused the call.",recoverable:!1},unknown:{label:"Unclassified error",shortLabel:"Other",hint:"No known pattern matched. Open the chat to read the transcript.",recoverable:!1}},kt=[{kind:"source-blocked",test:/\b(?:bot[- ]check|sign in to confirm|blocked this download|private video|video unavailable|not a downloadable media page|login required|rate[- ]?limit(?:ed|s)?|yt-dlp|unsupported url|unable to download webpage|http error 40\d)\b/i},{kind:"permission",test:/\b(?:not authorized|unauthorized|forbidden|permission denied|requires? an?
1(?:paid|starter|pro|studio)|plan required|not your)\b/i},{kind:"timeout",test:/\b(?:timed out|timeout|deadline exceeded|took too long)\b/i},{kind:"missing-reference",test:/\b(?:run|song|stem|capture|lyrics?|track|task|voice|model|chat|persona|workspace|document|record|file)\s+(?:was\s+)?not found\b|\bno such\b|\bdoes not exist\b/i},{kind:"rejected-input",test:/\b(?:characters or less|cannot exceed|exceeds the|too long|too short|is required|invalid|malformed|must be)\b/i},{kind:"provider-failed",test:/\b(?:failed|failure|error|could not|unable to|rejected|crashed)\b/i}],vt=new Set(["needs_audio_url","needs_voice_model","needs_reference_id","needs_source_url","needs_capture","not_found"]),jt=Object.fromEntries(Object.entries(De).map(([e,t])=>[e,t.shortLabel]));function Oe(e){const t=Ct(e);return{kind:t,...De[t]}}function Ct(e){if(e.type==="user-feedback")return"user-report";if(e.source==="stale-processing")return"stuck";const t=ye(e.error||e.message);if(!t)return"unknown";const a=H(e.error),r=typeof a?.status=="string"?a.status:"";if(vt.has(r))return"agent-slip";for(const l of kt)if(l.test.test(t))return l.kind;return"unknown"}function ze(e){if(e.toolName)return e.toolName;switch(e.source){case"feedback":return"agent chat";case"chat-tool":return"tool call";case"ffmpeg-card":return"ffmpeg";case"linked-run":return"linked run";case"stale-processing":return"chat stream"}}function At(e,t,a=new Map){const r=new Map;for(const l of e){const c=ft(l);c&&r.set(c.dedupeKey,c)}for(const l of t)for(const c of Nt(l,a))r.has(c.dedupeKey)||r.set(c.dedupeKey,c);return Array.from(r.values()).sort((l,c)=>C(c.createdAt)-C(l.createdAt))}function St(e,t){const a=new Set(e.map(h=>h.chatId).filter(Boolean)),r=Math.max(t.length,a.size),l=Math.max(0,r-a.size),c=e.filter(h=>h.source!=="feedback").length,u=e.filter(h=>h.source==="stale-processing").length;return{totalChats:r,cleanChats:l,affectedChats:a.size,userReports:e.filter(h=>h.type==="user-feedback").length,automaticErrors:e.filter(h=>h.type!=="user-feedback").length,activeSignals:e.length,feedbackReports:e.length-c,transcriptErrors:c,staleProcessing:u,processing:t.filter(h=>h.processing).length,pct:r===0?null:Math.round(l/r*100),openIssues:e.filter(h=>h.state==="open").length,analyzedIssues:e.filter(h=>h.state==="analyzed").length,recoveredIssues:e.filter(h=>Oe(h).recoverable).length}}function ee({label:e,value:t,detail:a,accent:r}){return s.jsxs("div",{className:"rounded-2xl border border-white/[0.07] bg-white/[0.025] p-4",children:[s.jsx("div",{className:"text-2xs font-semibold uppercase tracking-widest text-white/35",children:e}),s.jsx("div",{className:`mt-2 text-2xl font-semibold tabular-nums ${r??"text-white"}`,children:t}),a!=null&&s.jsx("div",{className:"mt-1 text-xs text-white/35",children:a})]})}function we({active:e,onClick:t,children:a}){return s.jsx(L,{variant:"ghost",size:"sm",onClick:t,"aria-pressed":e,className:`min-h-10 rounded-full border px-3 text-xs font-medium ${e?"border-primary/35 bg-primary/15 text-primary-100 hover:bg-primary/25 hover:text-primary-100":"border-white/[0.08] bg-white/[0.035] text-white/45 hover:bg-white/[0.07] hover:text-white/75"}`,children:a})}function xe({title:e,count:t,children:a}){const[r,l]=m.useState(!1);return s.jsxs("div",{className:"overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]",children:[s.jsxs(L,{variant:"ghost",onClick:()=>l(c=>!c),"aria-expanded":r,className:"h-auto w-full justify-start gap-2 whitespace-normal rounded-none px-4 py-3 text-left font-normal hover:bg-white/[0.03]",children:[s.jsx($e,{className:`h-4 w-4 shrink-0 text-white/35 transition-transform ${r?"rotate-180":""}`}),s.jsx("span",{className:"text-sm font-medium text-white/75",children:e}),t!=null&&s.jsx("span",{className:"ml-auto text-xs text-white/35",children:t})]}),r&&s.jsx("div",{className:"border-t border-white/[0.06] px-4 py-4",children:a})]})}const te=25,Ce={"user-report":{dot:"bg-fuchsia-400",chip:"border-fuchsia-400/30 bg-fuchsia-400/10 text-fuchsia-200"},stuck:{dot:"bg-amber-400",chip:"border-amber-400/30 bg-amber-400/10 text-amber-200"}
1,"agent-slip":{dot:"bg-sky-400",chip:"border-sky-400/30 bg-sky-400/10 text-sky-200"},"missing-reference":{dot:"bg-sky-400",chip:"border-sky-400/30 bg-sky-400/10 text-sky-200"},"rejected-input":{dot:"bg-orange-400",chip:"border-orange-400/30 bg-orange-400/10 text-orange-200"},"source-blocked":{dot:"bg-violet-400",chip:"border-violet-400/30 bg-violet-400/10 text-violet-200"},"provider-failed":{dot:"bg-red-400",chip:"border-red-400/30 bg-red-400/10 text-red-200"},timeout:{dot:"bg-red-400",chip:"border-red-400/30 bg-red-400/10 text-red-200"},permission:{dot:"bg-orange-400",chip:"border-orange-400/30 bg-orange-400/10 text-orange-200"},unknown:{dot:"bg-white/40",chip:"border-white/12 bg-white/[0.05] text-white/65"}},Ae={open:{label:"open",className:"border-white/12 bg-white/[0.05] text-white/60"},acknowledged:{label:"seen",className:"border-sky-400/25 bg-sky-400/10 text-sky-200"},analyzed:{label:"analyzed",className:"border-emerald-400/25 bg-emerald-400/10 text-emerald-200"},resolved:{label:"resolved",className:"border-emerald-400/25 bg-emerald-400/10 text-emerald-200"}}
1,It=["user-report","stuck","provider-failed","source-blocked","rejected-input","missing-reference","agent-slip","permission","timeout","unknown"];function _t(e){if(!e)return"recent";const t=Math.floor((Date.now()-e)/1e3);if(t<60)return`${t}s ago`;const a=Math.floor(t/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Et(e){if(!e)return"";const t=e.trim();if(!t.startsWith("{"))return t;try{const a=JSON.parse(t),r=[a.message,a.error,a.hint].find(l=>typeof l=="string"&&l.trim());return typeof r=="string"?r.trim():t}catch{return t}}function Lt(e){const t=new Map;for(const{failure:a}of e)t.set(a.kind,(t.get(a.kind)||0)+1);return It.filter(a=>(t.get(a)||0)>0).map(a=>({kind:a,count:t.get(a)||0}))}function $t({entries:e,canTriage:t=!1,triageError:a,onTriage:r,onCopyJson:l,copiedId:c}){const[u,h]=m.useState("all"),[w,k]=m.useState(te),[T,D]=m.useState(null),R=Lt(e),I=u==="all"?e:e.filter(i=>i.failure.kind===u),A=i=>{h(i),k(te)};return s.jsxs("section",{children:[s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[s.jsxs(we,{active:u==="all",onClick:()=>A("all"),children:["All ",s.jsx("span",{className:"ml-1 text-white/35",children:e.length})]}),R.map(({kind:i,count:$})=>s.jsxs(we,{active:u===i,onClick:()=>A(i),children:[s.jsx("span",{className:`mr-1.5 inline-block h-1.5 w-1.5 rounded-full align-middle ${Ce[i].dot}`}),jt[i]," ",s.jsx("span",{className:"ml-1 text-white/35",children:$})]},i))]}),a&&s.jsxs("div",{className:"mb-3 rounded-lg border border-red-400/25 bg-red-400/[0.07] px-3 py-2 text-xs text-red-200",children:["Could not update: ",a]}),I.length===0?s.jsx("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] py-16 text-center text-sm text-white/30",children:e.length===0?"No agent issues in this window. The agent is running clean.":"Nothing in this category."}):s.jsxs("div",{className:"space-y-2",children:[I.slice(0,w).map(({issue:i,failure:$,report:p})=>{const O=C(i.createdAt),U=Ce[$.kind],z=T===i.id,Q=Et(i.error);return s.jsxs("div",{className:"overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.025]",children:[s.jsxs(L,{variant:"ghost",onClick:()=>D(z?null:i.id),"aria-expanded":z,className:"h-auto w-full items-start justify-start gap-3 whitespace-normal rounded-none px-4 py-3 text-left font-normal hover:bg-white/[0.03]",children:[s.jsx("span",{className:`mt-1.5 h-2 w-2 shrink-0 rounded-full ${U.dot}`}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[s.jsx("span",{className:"text-sm font-medium text-white/90",children:$.label}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-mono text-2xs ${U.chip}`,children:ze(i)}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-2xs font-medium ${Ae[i.state].className}`,children:Ae[i.state].label})]}),i.message&&s.jsxs("p",{className:"mt-1.5 line-clamp-2 text-xs italic text-white/60",children:["â",i.message,"â"]}),Q&&s.jsx("p",{className:"mt-1 line-clamp-2 break-words font-mono text-2xs text-white/40",children:Q}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-2xs text-white/30",children:[s.jsx("span",{className:"truncate",children:i.userId||"unknown user"}),s.jsx("span",{children:O?_t(O):"recent"}),i.chatTitle&&s.jsx("span",{className:"max-w-64 truncate",children:i.chatTitle})]})]}),s.jsx($e,{className:`mt-1 h-4 w-4 shrink-0 text-white/25 transition-transform ${z?"rotate-180":""}`})]}),z&&s.jsxs("div",{className:"space-y-3 border-t border-white/[0.06] px-4 py-4",children:[s.jsx("p",{className:"text-xs text-white/50",children:$.hint}),i.resolution&&(i.resolution.rootCauseEnglish||i.resolution.summaryEnglish)&&s.jsxs("div",{className:"rounded-xl border border-emerald-400/20 bg-emerald-400/[0.06] p-3",children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-2xs font-semibold uppercase tracking-widest text-emerald-300/80",children:[s.jsx(Me,{className:"h-3 w-3"}),"Self-healing verdict",i.resolution.outcome&&s.jsxs("span",{className:"normal-case",children:["· ",i.resolution.outcome]})]}),i.resolution.summaryEnglish&&s.jsx("p",{className:"text-xs text-white/70",children:i.resolution.summaryEnglish}),i.resolution.rootCauseEnglish&&s.jsxs("p",{className:"mt-1.5 text-xs text-white/55",children:[s.jsx("span",{className:"text-emerald-300/70",children:"Root cause: "}),i.resolution.rootCauseEnglish]}),i.resolution.verificationEnglish&&s.jsxs("p",{className:"mt-1.5 text-xs text-white/55",children:[s.jsx("span",{className:"text-emerald-300/70",children:"Verified by: "}),i.resolution.verificationEnglish]})]}),i.error&&s.jsxs("div",{className:"rounded-xl border border-white/[0.06] bg-black/25 p-3",children:[s.jsx("div",{className:"mb-1.5 text-2xs font-semibold uppercase tracking-widest text-white/35",children:"Raw result"}),s.jsx("pre",{className:"max-h-56 overflow-auto whitespace-pre-wrap break-words font-mono text-2xs text-white/60",children:i.error})]}),p?.lastMessages&&p.lastMessages.length>0&&s.jsxs("div",{className:"rounded-xl border border-white/[0.06] bg-black/25 p-3",children:[s.jsxs("div",{className:"mb-2 text-2xs font-semibold uppercase tracking-widest text-white/35",children:["Last ",p.lastMessages.length," messages"]}),s.jsx("div",{className:"max-h-56 space-y-2 overflow-y-auto pr-1",children:p.lastMessages.map((q,ae)=>s.jsxs("div",{children:[s.jsx("div",{className:"text-2xs font-semibold uppercase tracking-wider text-white/30",children:q.role||"message"}),s.jsx("div",{className:"whitespace-pre-wrap break-words text-xs text-white/60",children:String(q.content||"").slice(0,1200)})]},ae))})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.chatId&&s.jsxs("a",{href:`/agent?chat=${encodeURIComponent(i.chatId)}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex min-h-10 items-center gap-1.5 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 text-xs text-white/60 transition-colors hover:bg-white/[0.08] hover:text-white/85",children:[s.jsx(Ye,{className:"h-3.5 w-3.5"}),"Open chat"]}),p&&l&&s.jsxs(L,{variant:"ghost",onClick:()=>l(i.id,p.raw),className:"min-h-10 gap-1.5 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 text-xs font-normal text-white/60 hover:bg-white/[0.08] hover:text-white/85",children:[s.jsx(it,{className:"h-3.5 w-3.5"}),c===i.id?"Copied":"Copy JSON"]}),t&&i.feedbackId&&i.state==="open"&&s.jsxs(L,{variant:"ghost",onClick:()=>r?.(i.feedbackId,"seen"),className:"min-h-10 gap-1.5 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 text-xs font-normal text-white/60 hover:bg-white/[0.08] hover:text-white/85",children:[s.jsx(Ze,{className:"h-3.5 w-3.5"}),"Mark seen"]}),t&&i.feedbackId&&s.jsxs(L,{variant:"ghost",onClick:()=>r?.(i.feedbackId,"fixed"),className:"min-h-10 gap-1.5 rounded-lg border border-emerald-400/25 bg-emerald-400/10 px-3 text-xs font-normal text-emerald-200 hover:bg-emerald-400/20 hover:text-emerald-100",children:[s.jsx(Xe,{className:"h-3.5 w-3.5"}),"Mark fixed"]})]})]})]},i.id)}),I.length>w&&s.jsxs(L,{variant:"ghost",onClick:()=>k(i=>i+te),className:"min-h-12 w-full rounded-2xl border border-white/[0.07] bg-white/[0.02] text-xs font-medium text-white/50 hover:bg-white/[0.05] hover:text-white/80",children:["Show ",Math.min(te,I.length-w)," more",s.jsxs("span",{className:"ml-1 text-white/25",children:["of ",I.length]})]})]})]})}const J=5e3,Se=5e3,Mt=[{value:"1h",label:"1h"},{value:"3h",label:"3h"},{value:"6h",label:"6h"},{value:"12h",label:"12h"},{value:"24h",label:"24h"},{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"3m",label:"3m"},{value:"1y",label:"1y"},{value:"all",label:"All"}],pe=[{key:"runs",collectionName:"runs",label:"Runs"},{key:"songs",collectionName:"songs",label:"Songs"},{key:"stems",collectionName:"stems",label:"Stems"},{key:"lyrics",collectionName:"lyrics",label:"Lyrics"}
1,{key:"captures",collectionName:"captures",label:"Captures"},{key:"dereverbs",collectionName:"dereverbs",label:"Dereverbs"}],be=["createdAt","updatedAt","completedAt"],Ie=[{key:"songCards",label:"Song"},{key:"stemCards",label:"Stem"},{key:"captureCards",label:"Capture"},{key:"lyricsCards",label:"Lyrics"},{key:"conversionCards",label:"Conversion"},{key:"youtubeCards",label:"YouTube"},{key:"coverConfigCards",label:"Cover config"},{key:"ffmpegCards",label:"FFmpeg"},{key:"runCards",label:"Run"},{key:"navigationCards",label:"Navigation"},{key:"creditsCards",label:"Credits"}];function _e(){return{docs:{runs:[],songs:[],stems:[],lyrics:[],captures:[],dereverbs:[]},errors:{},cappedQueries:[],loading:!0}}function Tt(e){if(!e)return"recent";const t=Math.floor((Date.now()-e)/1e3);if(t<60)return`${t}s ago`;const a=Math.floor(t/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ee(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return t==="error"||t==="failed"||t==="failure"}function Pt(){const{isAdmin:e}=et(),[t,a]=m.useState([]),[r,l]=m.useState([]),[c,u]=m.useState(_e),[h,w]=m.useState(null),[k,T]=m.useState(null),[D,R]=m.useState(!0),[I,A]=m.useState(!0),[i,$]=m.useState(""),[p,O]=m.useState(""),[U,z]=m.useState("7d"),[Q,q]=m.useState(null),[ae,Ne]=m.useState(null),[,Be]=m.useState(0),ne=m.useRef(new Set),{displayCutoff:oe,queryCutoff:v}
1=lt(U),le=v?String(v.getTime()):"all",[Pe,Ke]=m.useState(le);Pe!==le&&(Ke(le),u(_e())),m.useEffect(()=>{document.title="Agent Monitoring - Vocuno"},[]),m.useEffect(()=>{const n=window.setInterval(()=>Be(o=>o+1),5e3);return()=>window.clearInterval(n)},[]),m.useEffect(()=>{const n=[];return v&&n.push(ce("createdAt",">=",de.fromDate(v))),n.push(ue("createdAt","desc"),me(J)),he(fe(ge(X,"agentFeedback"),...n),o=>{w(null),R(!1),a(o.docs.map(d=>({id:d.id,...d.data(),_raw:d.data()})))},o=>{console.error("[agent-monitoring] agentFeedback snapshot error:",o),w(o.message||String(o)),R(!1),a([])})},[v]),m.useEffect(()=>{const n=[];return v&&n.push(ce("updatedAt",">=",de.fromDate(v))),n.push(ue("updatedAt","desc"),me(J)),he(fe(ge(X,"chats"),...n),o=>{T(null),A(!1),l(o.docs.map(d=>({id:d.id,...d.data(),_raw:d.data()})))},o=>{console.error("[agent-monitoring] chats snapshot error:",o),T(o.message||String(o)),A(!1),l([])})},[v]),m.useEffect(()=>{ne.current=new Set;const n=pe.length*be.length,o=new Map,d=new Set,F=x=>{const f=new Map;for(const g of be){const S=o.get(`${x}:${g}`);if(S)for(const[G,M]of S)f.set(G,M)}u(g=>({...g,docs:{...g.docs,[x]:Array.from(f.values())},cappedQueries:Array.from(d).sort()}))},W=x=>{ne.current.add(x),ne.current.size>=n&&u(f=>f.loading?{...f,loading:!1}:f)},E=pe.flatMap(x=>be.map(f=>{const g=`${x.key}:${f}`,S=`${x.collectionName}.${f}`,G=[];return v&&G.push(ce(f,">=",de.fromDate(v))),G.push(ue(f,"desc"),me(Se)),he(fe(ge(X,x.collectionName),...G),M=>{W(g),u(y=>{if(!y.errors[g])return y;const je={...y.errors};return delete je[g],{...y,errors:je}}),M.docs.length>=Se?d.add(S):d.delete(S),o.set(g,new Map(M.docs.map(y=>[y.id,{id:y.id,_source:x.key,...y.data(),_raw:y.data()}]))),F(x.key)},M=>{console.error(`[agent-monitoring] ${S} snapshot error:`,M),W(g),o.set(g,new Map),d.delete(S),F(x.key),u(y=>({...y,errors:{...y.errors,[g]:M.message||String(M)}}))})}));return()=>E.forEach(x=>x())},[v]);const B=oe?.getTime()||0,Y=m.useMemo(()=>{let n=t;if(p.trim()){const o=p.trim().toLowerCase();n=n.filter(d=>d.userId===o)}return B&&(n=n.filter(o=>C(o.createdAt)>=B)),n},[t,p,B]),_=m.useMemo(()=>{let n=r;if(p.trim()){const o=p.trim().toLowerCase();n=n.filter(d=>d.userId===o)}return B&&(n=n.filter(o=>(C(o.updatedAt)||C(o.createdAt))>=B)),n},[r,p,B]),ke=m.useMemo(()=>{const n=new Map;for(const o of Object.values(c.docs))for(const d of o)Ee(d.status)&&n.set(d.id,d);return n},[c.docs]),P=m.useMemo(()=>At(Y,_,ke),[Y,_,ke]),b=m.useMemo(()=>St(P,_),[P,_]),Ue=m.useMemo(()=>{const n=new Map(Y.map(o=>[o.id,o]));return P.map(o=>{const d=o.feedbackId?n.get(o.feedbackId):void 0;return{issue:o,failure:Oe(o),report:d?{lastMessages:d.lastMessages,raw:d._raw??d}:void 0}})},[P,Y]),K=m.useMemo(()=>{const n=new Map,o=new Set;let d=0,F=0,W=0;for(const E of _){const x=Array.isArray(E.messages)?E.messages:[];d+=x.length,W+=x.filter(f=>f.role==="tool").length,F+=x.reduce((f,g)=>f+(Array.isArray(g.tool_calls)?g.tool_calls.length:0),0);for(const f of Ie){const g=E[f.key],S=Array.isArray(g)?g.length:0;S>0&&n.set(f.label,(n.get(f.label)||0)+S)}for(const f of Fe(E))o.add(`${f.id}:${f.toolName}:${f.source}`)}return{messageCount:d,toolCallCount:F,toolResultCount:W,linkedRefCount:o.size,cardCounts:Ie.map(E=>({label:E.label,count:n.get(E.label)||0}))}},[_]),Z=m.useMemo(()=>{const n=new Map;for(const o of P){const d=ze(o);n.set(d,(n.get(d)||0)+1)}return Array.from(n.entries()).sort((o,d)=>d[1]-o[1]||o[0].localeCompare(d[0])).slice(0,6)},[P]),ie=[t.length>=J?"agentFeedback":null,r.length>=J?"chats":null,...c.cappedQueries].filter(Boolean),ve=[h?`agentFeedback: ${h}`:null,k?`chats: ${k}`:null,...Object.entries(c.errors).map(([n,o])=>`${n}: ${o}`)].filter(Boolean),qe=D||I||c.loading,We=async(n,o)=>{try{await navigator.clipboard?.writeText(JSON.stringify(o,null,2)),q(n),window.setTimeout(()=>q(null),1500)}catch(d){console.error("[agent-monitoring] failed to copy json:",d)}},Ge=async(n,o)=>{Ne(null);try{await He(Ve(X,"agentFeedback",n),{status:o,updatedAt:Qe()})}catch(d){console.error("[agent-monitoring] triage update failed:",d),Ne(d instanceof Error?d.message:String(d))}};return s.jsx("div",{className:"min-h-screen bg-neutral-950 text-white antialiased",children:s.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-6 sm:px-6",children:[s.jsxs("header",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx(tt,{className:"h-5 w-5 text-primary-300/80"}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-white",children:"Agent Monitoring"}),s.jsx("p",{className:"text-xs text-white/25",children:"What the AI agent got wrong, and where"})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(Je,{to:"/admin/monitoring",className:"inline-flex min-h-10 items-center gap-2 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 text-xs text-white/55 transition-colors hover:bg-white/[0.08] hover:text-white/80",children:[s.jsx(st,{className:"h-3.5 w-3.5"}),"Pipelines"]}),s.jsxs("span",{className:"inline-flex min-h-10 items-center gap-2 rounded-lg border border-emerald-400/20 bg-emerald-400/[0.08] px-3 text-xs text-emerald-300/80",children:[s.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"}),s.jsx("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-400"})]}
1),qe?"Syncing":"Live"]})]})]}),s.jsxs("section",{className:"mb-6 rounded-2xl border border-white/[0.07] bg-white/[0.025] p-4",children:[s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:Mt.map(n=>s.jsx(we,{active:U===n.value,onClick:()=>z(n.value),children:n.label},n.value))}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center",children:[s.jsxs("div",{className:"relative min-w-0 sm:w-64",children:[s.jsx(rt,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/25"}),s.jsx(at,{value:i,onChange:n=>$(n.target.value),onKeyDown:n=>{n.key==="Enter"&&O(i.trim().toLowerCase())},placeholder:"Filter by user email",className:"h-10 w-full rounded-lg border-white/[0.08] bg-white/[0.04] pl-9 text-sm text-white placeholder:text-white/25 focus-visible:border-primary/35"})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(L,{variant:"ghost",onClick:()=>O(i.trim().toLowerCase()),className:"min-h-10 rounded-lg border border-primary/30 bg-primary/15 px-4 text-xs font-medium text-primary-100 hover:bg-primary/25 hover:text-primary-100",children:"Apply"}),(p||i)&&s.jsx(L,{variant:"ghost",onClick:()=>{$(""),O("")},className:"min-h-10 rounded-lg border border-white/[0.08] px-4 text-xs font-medium text-white/50 hover:bg-white/[0.06] hover:text-white/80",children:"Reset"})]})]})]}),s.jsxs("div",{className:"mt-3 text-2xs text-white/25",children:[oe?`Since ${oe.toLocaleString()}`:`Latest ${J.toLocaleString()} docs`,p&&` · ${p}`]})]}),ve.length>0&&s.jsxs("section",{className:"mb-6 rounded-2xl border border-red-400/25 bg-red-400/[0.07] p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-red-200",children:[s.jsx(nt,{className:"h-4 w-4"}),"Some data could not be read"]}),ve.map(n=>s.jsx("div",{className:"mt-1.5 break-words text-xs text-red-200/70",children:n},n))]}),s.jsxs("section",{className:"mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4",children:[s.jsx(ee,{label:"Clean chats",value:b.pct==null?"â":`${b.pct}%`,detail:`${b.cleanChats} of ${b.totalChats} chats`,accent:"text-emerald-300"}),s.jsx(ee,{label:"Needs action",value:b.openIssues,detail:b.analyzedIssues>0?`${b.analyzedIssues} already analyzed`:"nothing waiting",accent:b.openIssues>0?"text-red-300":"text-white/50"}),s.jsx(ee,{label:"User complaints",value:b.userReports,detail:"people who said it was wrong",accent:b.userReports>0?"text-fuchsia-300":"text-white/50"}),s.jsx(ee,{label:"Stuck now",value:b.staleProcessing,detail:`${b.processing} processing`,accent:b.staleProcessing>0?"text-amber-300":"text-white/50"})]}),s.jsx("div",{className:"mb-6",children:s.jsx($t,{entries:Ue,canTriage:e,triageError:ae,onTriage:Ge,onCopyJson:We,copiedId:Q})}),s.jsxs("section",{className:"space-y-2",children:[s.jsx(xe,{title:"Where issues concentrate",count:`${Z.length} tools`,children:Z.length===0?s.jsx("p",{className:"text-xs text-white/35",children:"No issues to break down."}):s.jsx("div",{className:"space-y-1.5",children:Z.map(([n,o])=>s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"w-40 shrink-0 truncate font-mono text-xs text-white/60",children:n}),s.jsx("div",{className:"h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-white/[0.06]",children:s.jsx("div",{className:"h-full rounded-full bg-primary/60",style:{width:`${Math.round(o/Z[0][1]*100)}%`}})}),s.jsx("span",{className:"w-8 shrink-0 text-right text-xs tabular-nums text-white/45",children:o})]},n))})}),s.jsx(xe,{title:"Recent chats",count:`${_.length} in window`,children:_.length===0?s.jsx("p",{className:"text-xs text-white/35",children:"No agent chats in this window."}):s.jsx("div",{className:"space-y-1.5",children:_.slice(0,30).map(n=>{const o=C(n.updatedAt)||C(n.createdAt),d=Array.isArray(n.messages)?n.messages:[];return s.jsxs("a",{href:`/agent?chat=${encodeURIComponent(n.chatId||n.id)}`,target:"_blank",rel:"noopener noreferrer",className:"flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1 rounded-lg px-2 py-2 transition-colors hover:bg-white/[0.04]",children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${n.processing?"bg-sky-4
100":"bg-white/20"}`}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-white/75",children:n.title||"Untitled chat"}),s.jsxs("span",{className:"shrink-0 text-2xs text-white/30",children:[d.length," msg"]}),s.jsx("span",{className:"shrink-0 truncate text-2xs text-white/30",children:n.userId||"unknown"}),s.jsx("span",{className:"shrink-0 text-2xs text-white/25",children:o?Tt(o):"recent"})]},n.id)})})}),s.jsxs(xe,{title:"Scan coverage",count:ie.length>0?"fetch cap hit":`${K.messageCount.toLocaleString()} messages`,children:[s.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[{label:"Messages",value:K.messageCount},{label:"Tool calls",value:K.toolCallCount},{label:"Tool results",value:K.toolResultCount},{label:"Linked refs",value:K.linkedRefCount}].map(n=>s.jsxs("div",{className:"rounded-lg bg-white/[0.03] p-3",children:[s.jsx("div",{className:"text-2xs uppercase tracking-widest text-white/30",children:n.label}),s.jsx("div",{className:"mt-1 text-sm font-semibold tabular-nums text-white/80",children:n.value.toLocaleString()})]},n.label))}),s.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:K.cardCounts.filter(n=>n.count>0).map(n=>s.jsxs("span",{className:"rounded-full border border-white/[0.08] bg-white/[0.04] px-2 py-0.5 text-2xs text-white/50",children:[n.label," ",s.jsx("span",{className:"font-mono text-white/70",children:n.count})]},n.label))}),s.jsx("div",{className:"mt-4 grid grid-cols-2 gap-1.5 sm:grid-cols-3",children:pe.map(n=>{const o=c.docs[n.key],d=o.filter(F=>Ee(F.status)).length;return s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg bg-white/[0.03] px-2.5 py-1.5",children:[s.jsx("span",{className:"truncate text-2xs text-white/50",children:n.label}),s.jsxs("span",{className:"shrink-0 text-2xs tabular-nums text-white/30",children:[o.length.toLocaleString()," · ",s.jsx("span",{className:d>0?"text-red-300/70":"",children:d})]})]},n.key)})}),ie.length>0&&s.jsxs("p",{className:"mt-3 flex items-start gap-1.5 text-2xs text-amber-300/70",children:[s.jsx(Me,{className:"mt-0.5 h-3 w-3 shrink-0"}),ie.join(", ")," hit the fetch cap â narrow the range or user filter for exact counts."]})]})]})]})})}export{Pt as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.