1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[46131],{5212:(e,t,s)=>{s.d(t,{u:()=>O});var r=s(68987),a=s(2315),n=s(73591),i=s(7586),l=s(73248),o=s(46711),d=s(67486),c=s(15109),u=s(87201),m=s(15947),h=s(73579),x=s(93210),p=s(43198),f=s(14821),g=s(49405),b=s(63434);function y({open:e,copy:t,onOpenChange:s,onConfirm:n}){let[i,o]=(0,a.useState)(1),[d,c]=(0,a.useState)(!1);return t?(0,r.jsx)(b.Lt,{open:e,onOpenChange:e=>{d||(e||o(1),s(e))},children:(0,r.jsxs)(b.EO,{className:"max-w-md","data-quota-confirm-step":i,children:[(0,r.jsxs)(b.wd,{children:[(0,r.jsxs)("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:["Step ",i," of 2"]}),(0,r.jsx)(b.r7,{children:1===i?t.title:t.confirmTitle}),(0,r.jsx)(b.$v,{children:1===i?t.description:t.confirmDescription})]}),(0,r.jsxs)(b.ck,{children:[(0,r.jsx)(b.Zr,{disabled:d,className:"h-10 w-auto px-4",children:"Cancel"}),1===i?(0,r.jsx)(g.$,{type:"button",size:"sm",width:"auto",onClick:()=>o(2),children:"Continue"}):(0,r.jsxs)(g.$,{type:"button",size:"sm",width:"auto",variant:t.destructive?"destructive":"default",disabled:d,onClick:async()=>{c(!0);try{await n()}finally{c(!1),o(1),s(!1)}},children:[d?(0,r.jsx)(l.A,{className:"mr-2 h-4 w-4 animate-spin"}):null,t.confirmLabel]})]})]})}):null}var j=s(10575);let w=[{key:"claude",label:"Claude",canReset:!1},{key:"codex",label:"Codex",canReset:!0}];function v(e){return"codex"===e.providerKey?e.usageLimits?.resetCredits?.availableCount??0:0}function N(e){return e.authenticated&&!!e.accountFingerprint&&e.usageSupport.reports}function k(e){return N(e)&&e.usageSupport.resets&&v(e)>0}function S(e){return e.authenticated&&!e.usageSupport.reports}function $(e){let t=e.usageLimits?.windows??[];return t.length?Math.min(...t.map(e=>e.remainingFraction)):null}function C(e){let t=(e.usageLimits?.windows??[]).map(e=>e.resetsAt?Date.parse(e.resetsAt):NaN).filter(Number.isFinite);return t.length?Math.min(...t):null}function A(e,t){let s=Math.max(0,Math.floor((e-t)/6e4));if(0===s)return"now";let r=Math.floor(s/1440),a=Math.floor(s%1440/60);return r?`in ${r}d ${a}h`:a?`in ${a}h ${s%60}m`:`in ${s}m`}async function _(e){let t=await e.json().catch(()=>({}));if(!e.ok||!1===t.ok)throw Error(t.error||"The request failed.");return t}let I={status:async(e,t,s)=>_(await fetch(`/api/computers/${encodeURIComponent(e.computerId)}/usage-limits?commandId=${encodeURIComponent(t)}`,{cache:"no-store",signal:s})),list:async e=>(await _(await fetch("/api/computers",{cache:"no-store",signal:e}))).computers.flatMap(e=>"revoked"===e.computer.state?[]:e.providers.flatMap(t=>{var s;return"claude"!==(s=t.providerKey)&&"codex"!==s?[]:[{id:`${e.computer.id}:${t.providerKey}:${t.slot}`,providerKey:t.providerKey,computerId:e.computer.id,computerName:e.computer.name,slot:t.slot,accountLabel:t.accountLabel,identityLabel:t.accountIdentityLabel||t.accountLabel,authenticated:t.authenticated,live:t.live,activeSlot:t.activeSlot,accountFingerprint:t.accountFingerprint,usageLimits:t.usageLimits,usageSupport:t.usageSupport??{reports:!1,resets:!1}}]})),refresh:e=>(0,j.cL)(e.computerId,{provider:e.providerKey,slot:e.slot}),async reset(e,t){if("codex"!==e.providerKey||!e.accountFingerprint)throw Error("Only a signed-in Codex account can be reset.");return _(await fetch(`/api/computers/${encodeURIComponent(e.computerId)}/usage-limits`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({action:"reset",provider:"codex",slot:e.slot,accountFingerprint:e.accountFingerprint,confirmation:"reset-quota",requestId:t})}))}},L="growthub.quota-management.preferences.v1",U={filter:"all",sort:"name"},T=new Set,F={raw:null,value:U};function M(){let e=null;try{e=window.localStorage.getItem(L)}catch{}if(e===F.raw)return F.value;let t=U;try{let s=JSON.parse(e||"{}");t={filter:["all","claude","codex"].includes(s.filter)?s.filter:"all",sort:["name","remaining","reset"].includes(s.sort)?s.sort:"name"}}catch{}return F={raw:e,value:t},t}function R(e){return T.add(e),()=>{T.delete(e)}}function q(e){return Math.round(100*e)}function P(e){return e.replace(/^(\d+)([mhd])\b/,(e,t,s)=>`${t}-${"m"===s?"minute":"h"===s?"hour":"day"}`)}function D(e){return e<=.1?"bg-destructive":e<=.6?"bg-amber-500":"bg-emerald-500"}function K({window:e,now:t}){let s=q(e.remainingFraction),a=e.resetsAt?Date.parse(e.resetsAt):null,n=null!==a&&a-t<=36e5;return(0,r.jsxs)("div",{className:"min-w-0",title:`${P(e.windowLabel)} \xb7 ${s}% left`,children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2 text-sm",children:[(0,r.jsx)("span",{className:"truncate text-muted-foreground",children:P(e.windowLabel)}),(0,r.jsxs)("span",{className:"font-medium tabular-nums",children:[s,"%"]})]}),(0,r.jsx)("div",{role:"meter","aria-label":`${e.windowLabel} remaining`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":s,className:"mt-1.5 h-1 w-full overflow-hidden rounded-full bg-muted",children:(0,r.jsx)("div",{className:(0,x.cn)("h-full rounded-full transition-[width] duration-500",D(e.remainingFraction)),style:{width:`${s}%`}})}),(0,r.jsx)("p",{className:"mt-1.5 truncate text-xs text-muted-foreground",children:null===a?"No reset pending":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:(0,x.cn)(n&&"font-medium text-amber-600 dar
1k:text-amber-400"),children:A(a,t)})," \xb7 ",new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).format(a)]})})]})}function z({row:e,now:t,pending:s,onRefresh:a,onReset:n}){let i=e.usageLimits,c=v(e),u=i?.resetCredits?.nextExpiresAt?Date.parse(i.resetCredits.nextExpiresAt):null;return(0,r.jsxs)("div",{className:"grid gap-4 py-4 lg:grid-cols-[minmax(0,15rem)_minmax(0,1fr)_auto] lg:items-center","data-quota-row":e.id,children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"truncate font-mono text-sm font-medium",children:e.identityLabel}),(0,r.jsxs)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:[e.computerName," \xb7 ","default"===e.slot?"Default slot":e.slot,e.activeSlot?" \xb7 Active":""]}),(0,r.jsx)("p",{className:"mt-0.5 text-xs text-muted-foreground",children:s?(0,r.jsxs)("span",{className:"inline-flex items-center gap-1 text-foreground",children:[(0,r.jsx)(l.A,{className:"h-3 w-3 animate-spin"}),"reset"===s.kind?"Reset requested":"Refresh requested"," \xb7 waiting for the host"]}):i?(0,p.nt)(i.sampledAt,t):e.authenticated?S(e)?"Host update needed":"No report yet":"Not signed in"})]}),(0,r.jsxs)("div",{className:(0,x.cn)("grid min-w-0 gap-x-6 gap-y-4 sm:grid-cols-2 xl:grid-cols-[repeat(auto-fit,minmax(7.5rem,1fr))]",s&&"opacity-60"),children:[i?i.windows.map(e=>(0,r.jsx)(K,{window:e,now:t},e.windowLabel)):(0,r.jsx)("p",{className:"text-sm text-muted-foreground sm:col-span-2",children:e.authenticated?S(e)?"This slot runs an older host release that does not report usage. Update the Computer's hosts, then refresh.":"The provider has not reported limits for this account yet. Refresh to ask the host for a report.":"Sign in to this account on the Computer to see its usage."}),"codex"===e.providerKey&&i?.resetCredits?(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"Manual resets"}),(0,r.jsxs)("p",{className:"mt-0.5 text-sm",children:[(0,r.jsx)("span",{className:"font-medium tabular-nums",children:c})," ",(0,r.jsx)("span",{className:"text-muted-foreground",children:"available"})]}),(0,r.jsx)("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:c>0&&u?`Next expires ${A(u,t)}`:"None to redeem"})]}):null]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-1 lg:justify-end",children:["codex"===e.providerKey&&(0,r.jsxs)(g.$,{type:"button",variant:"ghost",size:"sm",width:"auto",className:"h-8 px-2.5 text-muted-foreground disabled:opacity-40",disabled:!k(e)||!!s,onClick:n,title:k(e)?"Redeem one provider reset credit":S(e)?"Update the Computer's hosts first":"No reset credit reported for this account",children:[(0,r.jsx)(o.A,{className:"mr-1.5 h-3.5 w-3.5"}),"Reset quota"]}),(0,r.jsxs)(g.$,{type:"button",variant:"ghost",size:"sm",width:"auto",className:"h-8 px-2.5 text-muted-foreground disabled:opacity-40",disabled:!N(e)||!!s,onClick:a,children:[(0,r.jsx)(d.A,{className:(0,x.cn)("mr-1.5 h-3.5 w-3.5",s?.kind==="refresh"&&"animate-spin")}),"Refresh quota"]})]})]})}function E({label:e,rows:t,now:s}){let a,n,i,l=t[0]?.providerKey;if(!l)return null;let o=(n=(a=t.filter(e=>e.providerKey===l)).map($).filter(e=>null!==e),i=a.map(C).filter(e=>null!==e),{providerKey:l,accounts:a.length,reporting:n.length,lowestRemaining:n.length?Math.min(...n):null,nextReset:i.length?Math.min(...i):null,resetCredits:a.reduce((e,t)=>e+v(t),0)});return(0,r.jsxs)("div",{className:"min-w-0 rounded-xl border bg-card px-4 py-3",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("p",{className:"text-sm font-medium",children:e}),(0,r.jsxs)("p",{className:"text-xs text-muted-foreground",children:[o.reporting,"/",o.accounts," reporting"]})]}),null===o.lowestRemaining?(0,r.jsx)("p",{className:"mt-3 text-sm text-muted-foreground",children:"No reports yet"}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"mt-2 flex items-baseline justify-between gap-2 text-sm",children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"Lowest remaining"}),(0,r.jsxs)("span",{className:"font-medium tabular-nums",children:[q(o.lowestRemaining),"%"]})]}),(0,r.jsx)("div",{className:"mt-1.5 h-1 w-full overflow-hidden rounded-full bg-muted",children:(0,r.jsx)("div",{className:(0,x.cn)("h-full rounded-full",D(o.lowestRemaining)),style:{width:`${q(o.lowestRemaining)}%`}})})]}),(0,r.jsxs)("p",{className:"mt-2 truncate text-xs text-muted-foreground",children:[o.nextReset?`Next reset ${A(o.nextReset,s)}`:"No reset pending","codex"===l?` \xb7 ${o.resetCredits} manual reset${1===o.resetCredits?"":"s"}`:""]})]})}function O({userId:e,source:t=I,sourceLabel:s}){let l=(0,n.jE)(),o=(0,a.useMemo)(()=>["quota-management",e,s??"computers"],[e,s]),[p,b]=(0,a.useState)(()=>Date.now()),j=(0,a.useSyncExternalStore)(R,M,()=>U),[N,k]=(0,a.useState)(w.map(e=>e.key)),[A,_]=(0,a.useState)({}),[q,P]=(0,a.useState)(null);(0,a.useEffect)(()=>{let e=setInterval(()=>b(Date.now()),3e4);return()=>clearInterval(e)},[]);let D=(0,i.I)({queryKey:o,queryFn:({signal:e})=>t.list(e),refetchInterval:Object.values(A).some(e=>p-e.requestedAt<=12e4)?3e3:6e4}),K=(0,a.useMemo)(()=>D.data??[],[D.data]),O=K.filter(S).length,B=(0,i.I)({queryKey:[...o,"actions",Object.values(A).map(e=>e.commandId)],enabled:Object.keys(A).length>0,queryFn:async({signal:e})=>Object.fromEntries(await Promise.all(Object.entries(A).map(async([s,r])=>[s,await t.status(r.row,r.commandId,e)]))),refetchInterval:e=>!!Object.values(e.state.data??{}).some(e=>"accepted"===e.status||"running"===e.status)&&3e3}),J=(0,a.useMemo)(()=>Object.entries(A).map(([e,t])=>{let s=B.data?.[e],r=s&&["completed","failed","cancelled"].includes(s.status),a=s?.status==="completed"&&s.commandId===t.commandId&&s.action===t.kind&&s.accountFingerprint===t.row.accountFingerprint&&!!s.usageLimits&&("reset"!==t.kind||"reset"===s.resetOutcome||"alreadyRedeemed"===s.resetOutcome);return{id:e,action:t,result:s,reported:a,settled:!!r||p-t.requestedAt>12e4}}
1),[A,B.data,p]),Q=(0,a.useMemo)(()=>Object.fromEntries(J.filter(e=>!e.settled).map(e=>[e.id,e.action])),[J]),W=(0,a.useRef)(new Set);(0,a.useEffect)(()=>{for(let{action:e,result:t,reported:s,settled:r}of J)!r||W.current.has(e.commandId)||(W.current.add(e.commandId),s?(h.o.success("reset"===e.kind?`Quota reset for ${e.row.identityLabel}`:`Quota refreshed for ${e.row.identityLabel}`),l.invalidateQueries({queryKey:o})):t?.status==="failed"||t?.status==="cancelled"?h.o.error(t.error||"The provider did not complete this quota action."):h.o.message("Quota action is not verified",{description:"The row shows the last provider report. Check the current report before trying again."}))},[J,l,o]);let Z=e=>(function(e){try{window.localStorage.setItem(L,JSON.stringify(e))}catch{}for(let t of(F={raw:JSON.stringify(e),value:e},T))t()})({...j,...e}),H=w.filter(e=>"all"===j.filter||j.filter===e.key),G=e=>{var t,s;let r;return t=K.filter(t=>t.providerKey===e),s=j.sort,r=(e,t)=>e.identityLabel.localeCompare(t.identityLabel)||e.id.localeCompare(t.id),[...t].sort((e,t)=>"remaining"===s?($(e)??1/0)-($(t)??1/0)||r(e,t):"reset"===s&&(C(e)??1/0)-(C(t)??1/0)||r(e,t))},Y=async()=>{if(!q)return;let{kind:e,row:s}=q;try{let r="reset"===e?await t.reset(s,q.requestId):await t.refresh(s);_(t=>({...t,[s.id]:{kind:e,requestedAt:Date.now(),commandId:r.commandId,row:s}})),h.o.message("reset"===e?"Reset requested":"Refresh requested",{description:r.woke?"Waking the account slot to report back.":"Waiting for the host to report back."}),l.invalidateQueries({queryKey:o})}catch(e){h.o.error(e instanceof Error?e.message:"The request failed.")}};return(0,r.jsxs)("section",{className:"space-y-6","aria-label":"Quota management",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[(0,r.jsxs)("div",{children:[(0,r.jsxs)("h2",{className:"flex items-center gap-2 text-xl font-medium tracking-[-0.02em]",children:[(0,r.jsx)(c.A,{className:"h-5 w-5"}),"Quota management",s?(0,r.jsx)("span",{className:"rounded-full border px-2 py-0.5 text-xs font-normal text-muted-foreground",children:s}):null]}),(0,r.jsx)("p",{className:"mt-1 text-sm text-muted-foreground",children:"Provider-reported limits for each saved account. Point-in-time reports; nothing is estimated."})]}),(0,r.jsx)(g.$,{type:"button",size:"icon",width:"auto",variant:"ghost","aria-label":"Reload quota",onClick:()=>void D.refetch(),disabled:D.isFetching,children:(0,r.jsx)(d.A,{className:(0,x.cn)("h-4 w-4",D.isFetching&&"animate-spin")})})]}),K.length>0&&(0,r.jsx)("div",{className:"grid gap-3 sm:grid-cols-2",children:H.map(e=>(0,r.jsx)(E,{label:e.label,rows:G(e.key),now:p},e.key))}),O>0&&(0,r.jsxs)("div",{role:"status",className:"flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-500/40 bg-amber-500/5 px-4 py-3 text-sm",children:[(0,r.jsxs)("p",{children:[(0,r.jsxs)("span",{className:"font-medium",children:[O," signed-in account",1===O?"":"s"]})," run a host release that does not report usage yet. Update the Computer's hosts to start reporting; Refresh and Reset stay off until then."]}),(0,r.jsx)("a",{className:"shrink-0 underline",href:"/dashboard/workflow/chat?view=workflows&workflowSection=computers",children:"Update hosts"})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,r.jsx)("div",{role:"group","aria-label":"Providers",className:"inline-flex items-center rounded-lg border bg-muted/40 p-0.5",children:[["all","All"],...w.map(e=>[e.key,e.label])].map(([e,t])=>(0,r.jsx)("button",{type:"button","aria-pressed":j.filter===e,onClick:()=>Z({filter:e}),className:(0,x.cn)("h-7 rounded-md px-3 text-sm transition-colors",j.filter===e?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:t},e))}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:["Sort",(0,r.jsxs)("select",{value:j.sort,onChange:e=>Z({sort:e.target.value}),className:"h-8 rounded-md border bg-background px-2 text-sm text-foreground",children:[(0,r.jsx)("option",{value:"name",children:"Account"}),(0,r.jsx)("option",{value:"remaining",children:"Lowest remaining"}),(0,r.jsx)("option",{value:"reset",children:"Soonest reset"})]})]}),(0,r.jsxs)(g.$,{type:"button",variant:"ghost",size:"sm",width:"auto",className:"h-8 px-2.5 text-muted-foreground",onClick:()=>k(N.length?[]:H.map(e=>e.key)),children:[N.length?(0,r.jsx)(u.A,{className:"mr-1.5 h-3.5 w-3.5"}):(0,r.jsx)(m.A,{className:"mr-1.5 h-3.5 w-3.5"}),N.length?"Collapse all":"Expand all"]})]})]}),D.isPending?(0,r.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:"Loading provider quotasâ¦"}):D.error?(0,r.jsx)("p",{role:"alert",className:"py-6 text-sm text-destructive",children:D.error.message}):0===K.length?(0,r.jsx)("p",{className:"py-6 text-sm text-muted-foreground",children:"No Codex or Claude account is signed in on your Computer yet. Add one under AI providers."}):(0,r.jsx)(f.Accordion,{type:"multiple",value:N,onValueChange:k,className:"space-y-3",children:H.map(e=>{let t=G(e.key);return(0,r.jsxs)(f.AccordionItem,{value:e.key,className:"rounded-[18px] border bg-background px-5",children:[(0,r.jsx)(f.AccordionTrigger,{className:"py-4 hover:no-underline",children:(0,r.jsxs)("span",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("span",{className:"text-base font-medium",children:e.label}),(0,r.jsx)("span",{className:"text-sm font-normal text-muted-foreground",children:t.length}),!e.canReset&&(0,r.jsx)("span",{className:"text-xs font-normal text-muted-foreground",children:"\xb7 check only"})]})}),(0,r.jsx)(f.AccordionContent,{children:0===t.length?(0,r.jsxs)("p",{className:"py-2 text-sm text-muted-foreground",children:["No ",e.label," account on your Computer."]}):(0,r.jsx)("div",{className:"divide-y border-t",children:t.map(e=>(0,r.jsx)(z,{row:e,now:p,pending:Q[e.id],onRefresh:()=>P({kind:"refresh",row:e,requestId:crypto.randomUUID()}),onReset:()=>P({kind:"reset",row:e,requestId:crypto.randomUUID()})},e.id))})})]},e.key)})}),(0,r.jsx)(y,{open:!!q,copy:function(e){if(!e)return null;let{row:t}=e;if("refresh"===e.kind)return{title:"Refresh quota?",description:`Ask the host for ${t.identityLabel} to send a fresh limit report from ${"codex"===t.providerKey?"Codex":"Claude Code"}. A stopped slot is woken for the check.`,confirmTitle:"Confirm quota refresh",confirmDescription:`Send one refresh command to ${t.computerName} \xb7 ${t.slot}. This reads usage only; it does not change the active account or spend any credit.`,confirmLabel:"Yes, refresh quota"};let s=v(t);return{title:"Reset Codex quota?",description:`This redeems one ChatGPT reset credit for ${t.identityLabel}, which restores its Codex limit windows. ${s} credit${1===s?"":"s"} available.`,confirmTitle:"Spend a reset credit?",confirmDescription:`The provider will spend 1 of ${s} reset credits on ${t.identityLabel}. A redeemed credit cannot be returned.`,confirmLabel:"Spend credit and reset",destructive:!0}}(q),onOpenChange:e=>{e||P(null)},onConfirm:Y})]})}},43198:(e,t,s)=>{s.d(t,{EY:()=>o,Ev:()=>i,FC:()=>d,Iq:()=>l,cp:()=>u,nt:()=>c});let r="provider";function a(e,t=60){if("string"!=typeof e)return null;let s=e.trim();return s&&s.length<=t?s:null}function n(e){if("string"!=typeof e)return null;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function i(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:null;if(!t||t.source!==r)return null;let s=n(t.sampledAt);if(!s||!Array.isArray(t.windows))return null;let i=t.windows.slice(0,8).flatMap(e=>{let t=function(e){var t;let s=e&&"object"==typeof e&&!Array.isArray(e)?e:null;if(!s)return null;let r=a(s.windowLabel),i="number"==typeof(t=s.remainingFraction)&&Number.isFinite(t)&&t>=0&&t<=1?t:null;return r&&null!==i?{windowLabel:r,remainingFraction:i,resetsAt:n(s.resetsAt)}:null}(e);return t?[t]:[]});if(!i.length)return null;let l=a(t.providerInstanceId,300),o=function(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:null;if(!t)return null;let s=t.availableCount;return"number"!=typeof s||!Number.isInteger(s)||s<0||s>1e3?null:{availableCount:s,nextExpiresAt:n(t.nextExpiresAt)}}(t.resetCredits);return{source:r,sampledAt:s,windows:i,...o?{resetCredits:o}:{},...l?{providerInstanceId:l}:{}}}function l(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:null;return t?i(t.usage_limits):null}function o(e){return!!(e&&.1>=Math.min(...e.windows.map(e=>e.remainingFraction)))}
1function d(e,t=Date.now()){if(!e)return null;let s=Date.parse(e);if(!Number.isFinite(s))return null;let r=Math.max(0,Math.floor((s-t)/6e4));if(0===r)return"resets now";let a=Math.floor(r/1440),n=Math.floor(r%1440/60),i=r%60,l=a?[`${a}d`,`${n}h`]:n?[`${n}h`,`${i}m`]:[`${i}m`];return`resets in ${l.join(" ")}`}function c(e,t=Date.now()){let s=Date.parse(e);if(!Number.isFinite(s))return"reported at an unknown time";let r=Math.max(0,Math.floor((t-s)/6e4));if(r<1)return"reported just now";if(r<60)return`reported ${r}m ago`;let a=Math.floor(r/60);return a<48?`reported ${a}h ago`:`reported ${Math.floor(a/24)}d ago`}function u(e,t=Date.now()){var s;let r=d(e.resetsAt,t);return[e.windowLabel,(s=e.remainingFraction,`${Math.round(100*s)}% left`),...r?[r]:[]].join(" \xb7 ")}},45092:(e,t,s)=>{s.d(t,{C:()=>d,z:()=>o});var r=s(68987),a=s(2315),n=s(23450),i=s(17150),l=s(76502);let o=a.forwardRef(({className:e,...t},s)=>(0,r.jsx)(n.bL,{className:(0,l.cn)("grid gap-2",e),...t,ref:s}));o.displayName=n.bL.displayName;let d=a.forwardRef(({className:e,...t},s)=>(0,r.jsx)(n.q7,{ref:s,className:(0,l.cn)("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:(0,r.jsx)(n.C1,{className:"flex items-center justify-center",children:(0,r.jsx)(i.A,{className:"h-2.5 w-2.5 fill-current text-current"})})}));d.displayName=n.q7.displayName},51374:(e,t,s)=>{s.d(t,{S:()=>o});var r=s(68987),a=s(2315),n=s(76384),i=s(60426),l=s(76502);let o=a.forwardRef(({className:e,...t},s)=>(0,r.jsx)(n.bL,{ref:s,className:(0,l.cn)("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:(0,r.jsx)(n.C1,{className:(0,l.cn)("flex items-center justify-center text-current"),children:(0,r.jsx)(i.A,{className:"h-4 w-4"})})}));o.displayName=n.bL.displayName},62978:(e,t,s)=>{s.d(t,{p:()=>eo});var r=s(68987),a=s(37866),n=s.n(a),i=s(49405),l=s(2315),o=s(73591),d=s(7586),c=s(87104),u=s(75472),m=s(60426),h=s(67486),x=s(10734),p=s(42934),f=s(47366),g=s(93210);let b=[{key:"codex",label:"Codex",color:"var(--usage-codex, #1f1f1f)"},{key:"claude",label:"Claude Code",color:"#d97757"}],y=[{days:1,label:"Past 24h"},{days:7,label:"7 days"},{days:30,label:"30 days"},{days:90,label:"90 days"}],j="unattributed";function w(e){let t=Math.abs(e);return e.toFixed(t>=100?0:t>=10?1:2).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0+$/,"$1")}function v(e){let t=Math.abs(e);return t>=1e12?`${w(e/1e12)}T`:t>=1e9?`${w(e/1e9)}B`:t>=1e6?`${w(e/1e6)}M`:t>=1e3?`${w(e/1e3)}K`:new Intl.NumberFormat("en-US").format(Math.round(e))}let N=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2});function k(e){return N.format(e)}function S(e){let t=100*e;return`${t>0&&t<.1?"<0.1":t.toFixed(1)}%`}function $(e){return new Intl.NumberFormat("en-US").format(e)}var C=s(95530),A=s(1925),_=s(80223);function I({userId:e,onUpdated:t}){let[s,a]=(0,l.useState)(!1),[n,o]=(0,l.useState)(null),[d,c]=(0,l.useState)(null),[u,m]=(0,l.useState)(!1),h=async()=>{a(!0),m(!0),c(null);try{let e=await fetch("/api/usage/report",{method:"POST"}),t=await e.json();if(!e.ok||!t.ok)throw Error(t.error||"Usage report could not be loaded.");o(t.item)}catch(e){c(e instanceof Error?e.message:"Usage report could not be loaded.")}finally{m(!1)}};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(i.$,{variant:"ghost",size:"icon",className:"size-8 text-muted-foreground hover:text-foreground","aria-label":"Share usage analytics",title:"Share usage analytics",onClick:()=>void h(),children:(0,r.jsx)(C.A,{className:"size-4","aria-hidden":"true"})}),(0,r.jsx)(A.lG,{open:s,onOpenChange:a,children:(0,r.jsxs)(A.Cf,{className:"max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-xl",children:[(0,r.jsx)(A.c7,{children:(0,r.jsx)(A.L3,{children:"Share usage analytics"})}),u?(0,r.jsx)("p",{role:"status",children:"Loading sharing settingsâ¦"}):d?(0,r.jsx)("p",{role:"alert",children:d}):n?(0,r.jsx)(_.J,{item:n,userId:e,onUpdate:t},n.id):null]})})]})}var L=s(57060),U=s(49861),T=s(17234),F=s(55753),M=s(78942),R=s(59149),q=s(10261);let P={codex:"Codex",claude:"Claude Code"},D={codex:"hsl(var(--foreground))",claude:"#d97757"};function K({provider:e,className:t}){return(0,r.jsx)("img",{src:"codex"===e?"/openai-logo.svg":"/claude-logo.svg",alt:"","aria-hidden":!0,
1className:(0,g.cn)("shrink-0 object-contain","codex"===e&&"dark:invert",t)})}function z(e,t,s){if("hour"===t){let t=Number(e.slice(11,13)),r=`${t%12||12}${t<12?"am":"pm"}`;return"axis"===s?r.toUpperCase():`${new Date(`${e.slice(0,10)}T12:00:00Z`).toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:"UTC"})}, ${r}`}let r=new Date(`${e}T12:00:00Z`),a=r.toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:"UTC"});return"axis"===s?a.toUpperCase():r.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",timeZone:"UTC"})}function E({series:e,providers:t,metric:s,resolution:a}){let n=(e,t)=>{let r=e.providers[t];return r?"cost"===s?r.costUsd:r.totalTokens:0},i=e.map(e=>({bucket:e.bucket,codex:n(e,"codex"),claude:n(e,"claude")})),l=[...t].sort((e,t)=>i.reduce((e,s)=>e+s[t],0)-i.reduce((t,s)=>t+s[e],0)),o=function(e,t=3){if(e<=0)return[0,1];let s=e/t,r=10**Math.floor(Math.log10(s)),a=[1,2,2.5,5,10].map(e=>e*r).find(e=>e>=s)??10*r;return Array.from({length:Math.max(1,Math.ceil(e/a))+1},(e,t)=>t*a)}(Math.max(0,...i.flatMap(e=>t.map(t=>e[t])))),d=o[o.length-1],c=e=>"cost"===s?k(e):v(e),u=i.length>2?[i[0].bucket,i[Math.floor((i.length-1)/2)].bucket,i[i.length-1].bucket]:i.map(e=>e.bucket);return(0,r.jsx)("div",{className:"h-[240px] w-full","data-testid":"usage-chart",children:(0,r.jsx)(L.u,{width:"100%",height:"100%",children:(0,r.jsxs)(U.Q,{data:i,margin:{top:8,right:4,bottom:0,left:0},children:[(0,r.jsx)(T.d,{vertical:!1,stroke:"hsl(var(--border))",strokeOpacity:.7}),(0,r.jsx)(F.W,{dataKey:"bucket",ticks:u,tickFormatter:e=>z(e,a,"axis"),tickLine:!1,axisLine:{stroke:"hsl(var(--border))"},interval:"preserveStartEnd",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),(0,r.jsx)(M.h,{domain:[0,d],ticks:o,tickFormatter:e=>0===e?"0":c(e),tickLine:!1,axisLine:!1,width:"cost"===s?64:48,tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),(0,r.jsx)(R.m,{cursor:{stroke:"hsl(var(--foreground))",strokeOpacity:.25},content:({active:e,payload:s,label:n})=>e&&s?.length?(0,r.jsxs)("div",{className:"rounded-md border bg-background px-3 py-2 text-xs shadow-sm",children:[(0,r.jsx)("p",{className:"mb-1 font-medium text-foreground",children:z(String(n),a,"tooltip")}),b.filter(({key:e})=>t.includes(e)).map(({key:e,label:t})=>{let a=s.find(t=>t.dataKey===e)?.value;return(0,r.jsxs)("p",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"size-2 rounded-full",style:{backgroundColor:D[e]}}),(0,r.jsx)("span",{children:t}),(0,r.jsx)("span",{className:"ms-auto tabular-nums text-foreground",children:c("number"==typeof a?a:0)})]},e)})]}):null}),l.map(e=>(0,r.jsx)(q.G,{type:"monotone",dataKey:e,stroke:D[e],strokeWidth:2,fill:D[e],fillOpacity:.12,isAnimationActive:!1,dot:!1,activeDot:{r:3}},e))]})})})}var O=s(7935),B=s(15109),J=s(14194),Q=s(2322);let W={"5h":18e6,"1d":864e5,"7d":6048e5};function Z(e){let t=e.split(/\s+/)[0],s=t.match(/^(\d+)h$/i);if(s)return Number(s[1]);let r=t.match(/^(\d+)d$/i);return r?24*Number(r[1])+ +!!e.includes(" "):1e4}function H(e,t){let s=Math.max(0,Math.floor((e-t)/6e4));if(0===s)return"now";let r=Math.floor(s/1440),a=Math.floor(s%1440/60);return r?`${r}d ${a}h`:a?`${a}h ${s%60}m`:`${s}m`}let G={ahead:{label:"Ahead of pace: spending faster than the window elapses",icon:O.A},on:{label:"On pace with the window",icon:B.A},under:{label:"Under pace: headroom left for the rest of the window",icon:J.A}};function Y({window:e,color:t,now:s,showNames:a}){let n=e.pace?G[e.pace].icon:null;return(0,r.jsxs)("div",{className:"grid items-center gap-x-6 gap-y-3 rounded-lg border border-border/60 p-4 md:grid-cols-[11rem_minmax(0,1fr)]",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.label}),(0,r.jsxs)("span",{className:"flex items-baseline gap-2",children:[(0,r.jsxs)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:[e.remainingPercent,"%"]}),(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:"left"}),n&&e.pace?(0,r.jsxs)(f.m_,{children:[(0,r.jsx)(f.k$,{asChild:!0,children:(0,r.jsx)("span",{role:"img","aria-label":G[e.pace].label,className:"inline-flex text-muted-foreground",children:(0,r.jsx)(n,{className:"size-3.5"})})}),(0,r.jsx)(f.ZI,{side:"top",children:G[e.pace].label})]}):null]}),e.nextRefill&&e.nextRefill.restoresPercent>0?(0,r.jsxs)("span",{className:"flex items-center gap-1 text-xs font-medium tabular-nums text-foreground",children:[(0,r.jsx)(Q.A,{"aria-hidden":!0,
1className:"size-3"}),"+",e.nextRefill.restoresPercent,"% in ",H(e.nextRefill.at,s)]}):null]}),(0,r.jsx)("div",{className:"grid gap-x-1",style:{gridTemplateColumns:`repeat(${e.segments.length}, minmax(0, 1fr))`},children:e.segments.map(e=>{let n=a?`${e.account.label}${"You"!==e.account.memberLabel?` \xb7 ${e.account.memberLabel}`:""}`:P[e.account.provider],i=e.resetsAt?H(e.resetsAt,s):null;return(0,r.jsxs)(f.m_,{children:[(0,r.jsx)(f.k$,{asChild:!0,children:(0,r.jsxs)("div",{role:"img",tabIndex:0,"aria-label":`${n}: ${e.remainingPercent}% left${i?`, resets in ${i}`:""}`,className:"relative h-8 min-w-0 cursor-default overflow-hidden rounded-md bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,r.jsx)("div",{"aria-hidden":!0,className:"absolute inset-y-0 left-0 rounded-md opacity-35",style:{width:`${e.remainingPercent}%`,backgroundColor:t}}),e.remainingPercent<100&&e.resetsAt?(0,r.jsx)("div",{"aria-hidden":!0,className:"absolute inset-y-0 right-0 opacity-20",style:{width:`${100-e.remainingPercent}%`,backgroundImage:`repeating-linear-gradient(135deg, ${t} 0 1px, transparent 1px 5px)`}}):null,(0,r.jsxs)("div",{className:"relative flex h-full min-w-0 items-center gap-1.5 px-2 text-xs",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-medium text-foreground",children:n}),(0,r.jsxs)("span",{className:"shrink-0 font-semibold tabular-nums text-foreground",children:[e.remainingPercent,"%"]}),i?(0,r.jsxs)("span",{className:"ms-auto flex shrink-0 items-center gap-1 rounded-sm bg-background/85 px-1.5 py-0.5 text-[11px] tabular-nums text-foreground",children:[(0,r.jsx)(Q.A,{"aria-hidden":!0,className:"size-3"}),i]}):null]})]})}),(0,r.jsx)(f.ZI,{side:"top",children:(0,r.jsxs)("div",{className:"flex flex-col gap-0.5 text-xs",children:[(0,r.jsx)("span",{className:"font-medium",children:n}),(0,r.jsxs)("span",{children:[e.remainingPercent,"% left"]}),e.resetsAt?(0,r.jsxs)("span",{className:"text-muted-foreground",children:["Resets ",new Date(e.resetsAt).toLocaleString()," \xb7 in ",i]}):(0,r.jsx)("span",{className:"text-muted-foreground",children:"The provider did not report a reset time."}),e.account.usageLimits?.sampledAt?(0,r.jsxs)("span",{className:"text-muted-foreground",children:["Reported ",new Date(e.account.usageLimits.sampledAt).toLocaleString()]}):null]})})]},e.account.key)})})]})}function V({accounts:e,now:t,isPending:s,error:a,showMembers:n,emptyHint:i}){if(s)return(0,r.jsx)("p",{role:"status",className:"py-6 text-sm text-muted-foreground",children:"Loading provider limitsâ¦"});if(a)return(0,r.jsx)("p",{role:"alert",className:"py-6 text-sm text-destructive",children:a});let l=["codex","claude"].flatMap(s=>{let r=e.filter(e=>e.provider===s);if(!r.length)return[];let a=r.filter(e=>e.usageLimits?.windows.length);return[{provider:s,windows:[...new Set(a.flatMap(e=>e.usageLimits.windows.map(e=>e.windowLabel)))].sort((e,t)=>Z(e)-Z(t)||e.localeCompare(t)).map(e=>{let s=a.flatMap(t=>{let s=t.usageLimits.windows.find(t=>t.windowLabel===e);if(!s)return[];let r=s.resetsAt?Date.parse(s.resetsAt):NaN;return[{account:t,remainingPercent:Math.round(100*s.remainingFraction),resetsAt:Number.isFinite(r)?r:null}]}),r=Math.round(s.reduce((e,t)=>e+t.remainingPercent,0)/s.length),n=s.filter(e=>null!==e.resetsAt&&e.resetsAt>t&&e.remainingPercent<100).sort((e,t)=>(e.resetsAt??0)-(t.resetsAt??0))[0],i=n?{at:n.resetsAt,restoresPercent:Math.round((100-n.remainingPercent)/s.length)}:null,l=null,o=W[e.split(/\s+/)[0]];if(o&&1===s.length&&n){let e=1-Math.min(1,Math.max(0,(n.resetsAt-t)/o)),s=1-r/100;l=s>e+.05?"ahead":s<e-.05?"under":"on"}return{id:e,label:function(e){let[t,...s]=e.trim().split(/\s+/),r=s.length?` \xb7 ${s.join(" ")}`:"";if(/^7d$/i.test(t)||/^weekly$/i.test(t)||/^seven_day$/i.test(t))return`Weekly${r}`;if(/^1d$/i.test(t))return`Daily${r}`;let a=t.match(/^(\d+)h$/i);if(a)return`${a[1]}-hour${r}`;let n=t.match(/^(\d+)d$/i);return n?`${n[1]}-day${r}`:e}(e),remainingPercent:r,segments:s,nextRefill:i,pace:l}}),notReporting:r.filter(e=>!e.usageLimits?.windows.length)}]});return l.length?(0,r.jsx)(f.Bc,{delayDuration:100,children:(0,r.jsx)("div",{className:"flex flex-col gap-8","data-testid":"usage-limits",children:l.map(e=>(0,r.jsxs)("section",{className:"flex flex-col gap-3","aria-label":`${P[e.provider]} limits`,children:[(0,r.jsxs)("h2",{className:"flex items-center gap-2 text-sm font-medium text-foreground",children:[(0,r.jsx)(K,{provider:e.provider,className:"size-4"}),P[e.provider]]}),e.windows.map(s=>(0,r.jsx)(Y,{window:s,color:D[e.provider],now:t,showNames:s.segments.length>1||n},s.id)),e.notReporting.length?(0,r.jsxs)("p",{className:"text-xs text-muted-foreground",children:[e.windows.length?"Also not reporting yet":`${e.notReporting.length} ${1===e.notReporting.length?"account has":"accounts have"} not reported limits yet`,": ",function(e,t){let s=new Map;for(let r of e){let e=t&&"You"!==r.memberLabel?`${r.label} \xb7 ${r.memberLabel}`:r.label;s.set(e,(s.get(e)??0)+1)}return[...s.entries()].map(([e,t])=>t>1?`${e} \xd7${t}`:e).join(", ")}(e.notReporting,n),". Limits appear after each account's host sends a provider report."]}):null]},e.provider))})}):(0,r.jsx)("div",{className:"py-6 text-sm text-muted-foreground",children:i})}let X=[{value:"cost",label:"Cost"},{value:"tokens",label:"Tokens"},{value:"limits",label:"Limits"}],ee="growthub:usage-page:v1";async function et(e){let t=await e.json().catch(()=>({}));if(!e.ok||t?.ok===!1)throw Error(t?.error||"The request failed.");return t}function es({label:e,value:t,options:s,onChange:a,disabled:n}){return(0,r.jsx)("div",{role:"radiogroup","aria-label":e,"aria-disabled":n||void 0,className:(0,g.cn)("inline-flex items-center rounded-lg bg-muted/70 p-0.5",n&&"opacity-60"),children:s.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":e.value===t,disabled:n,onClick:()=>a(e.value),className:(0,g.cn)("h-7 rounded-md px-3 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed",e.value===t?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e.label},String(e.value)))})}function er({label:e,heading:t,children:s,testId:a}){return(0,r.jsxs)(p.rI,{children:[(0,r.jsxs)(p.ty,{"data-testid":a,className:"inline-flex max-w-[16rem] items-center gap-1 rounded-md px-1.5 py-1 text-sm font-medium text-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,r.jsx)("span",{className:"truncate",children:e}
1),(0,r.jsx)(u.A,{"aria-hidden":!0,className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,r.jsxs)(p.SQ,{align:"start",className:"max-h-[min(28rem,70vh)] w-72 overflow-y-auto",children:[(0,r.jsx)(p.lp,{className:"text-xs font-normal text-muted-foreground",children:t}),s]})]})}function ea({selected:e,onSelect:t,children:s,disabled:a,hint:n}){return(0,r.jsxs)(p._2,{disabled:a,onSelect:t,className:"flex items-start gap-2",children:[(0,r.jsx)(m.A,{"aria-hidden":!0,className:(0,g.cn)("mt-0.5 size-3.5 shrink-0",e?"opacity-100":"opacity-0")}),(0,r.jsxs)("span",{className:"flex min-w-0 flex-col",children:[(0,r.jsx)("span",{className:"truncate",children:s}),n?(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:n}):null]})]})}let en={self:void 0,sharing:"Sharing provider usage","not-sharing":"Not shared"};function ei({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 flex-col gap-1",children:[(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:e}),(0,r.jsx)("span",{className:"text-lg font-medium tabular-nums text-foreground",children:t})]})}function el({kind:e,rows:t,providers:s,hourly:a,pricingAvailable:n}){let i=e=>!n||e.costUnknown?(0,r.jsx)("span",{className:"text-muted-foreground",children:"Unpriced"}):k(e.costUsd);return"time"===e?(0,r.jsxs)("table",{className:"w-full table-fixed text-sm",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[(0,r.jsx)("th",{className:"w-2/5 py-2 font-normal",children:a?"Hour":"Day"}),s.map(e=>(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:P[e]},e)),(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:"Total"}),(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:"Tokens"})]})}),(0,r.jsx)("tbody",{children:0===t.length?(0,r.jsx)("tr",{children:(0,r.jsx)("td",{colSpan:s.length+3,className:"py-6 text-center text-muted-foreground",children:"No activity in this window."})}):t.map(e=>(0,r.jsxs)("tr",{className:"border-b border-border/50 transition-colors hover:bg-muted/50",children:[(0,r.jsx)("td",{className:"py-2 text-foreground",children:function(e,t){if(t){let t=Number(e.slice(11,13));return`${new Date(`${e.slice(0,10)}T12:00:00Z`).toLocaleDateString("en-US",{month:"short",day:"numeric",timeZone:"UTC"})} \xb7 ${t%12||12}${t<12?"am":"pm"}`}return new Date(`${e}T12:00:00Z`).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",timeZone:"UTC"})}(e.key,a)}),s.map(t=>(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-muted-foreground",children:e.byProvider?.[t]?n&&!e.byProvider[t].costUnknown?k(e.byProvider[t].costUsd):(0,r.jsx)("span",{className:"text-muted-foreground",children:"Unpriced"}):"â"},t)),(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-foreground",children:i(e)}),(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-muted-foreground",children:v(e.totalTokens)})]},e.key))})]}):(0,r.jsxs)("table",{className:"w-full table-fixed text-sm",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[(0,r.jsx)("th",{className:"w-2/5 py-2 font-normal",children:{model:"Model",member:"Member",identity:"Account",brandKit:"Brand Kit"}[e]}),(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:"Cost"}),(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:"Share"}),(0,r.jsx)("th",{className:"py-2 text-right font-normal",children:"Tokens"})]})}),(0,r.jsx)("tbody",{children:0===t.length?(0,r.jsx)("tr",{children:(0,r.jsx)("td",{colSpan:4,className:"py-6 text-center text-muted-foreground",children:"No activity in this window."})}):t.map(t=>(0,r.jsxs)("tr",{className:"border-b border-border/50 transition-colors hover:bg-muted/50",children:[(0,r.jsx)("td",{className:"py-2 text-foreground",children:(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[t.provider?(0,r.jsx)(K,{provider:t.provider,className:"size-3.5"}):null,(0,r.jsx)("span",{className:"truncate",children:t.label}),"model"!==e?(0,r.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[$(t.sessions)," ",1===t.sessions?"session":"sessions"]}):null]})}),(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-foreground",children:i(t)}),(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-muted-foreground",children:!n||t.costUnknown?"â":S(t.costShare)}),(0,r.jsx)("td",{className:"py-2 text-right tabular-nums text-muted-foreground",children:v(t.totalTokens)})]},t.key))})]})}function eo({userId:e,quotaManagement:t,initialMetric:s,limitsSource:a}){let u,m=(0,o.jE)(),[w,N]=(0,l.useState)(!1),[C,A]=(0,l.useState)("cost"),[_,L]=(0,l.useState)(30),[U,T]=(0,l.useState)(e),[F,M]=(0,l.useState)("all"),[R,q]=(0,l.useState)("model"),[z,O]=(0,l.useState)(()=>Date.now()),[B,J]=(0,l.useState)(!1),[Q,W]=(0,l.useState)("within"),Z=(0,l.useMemo)(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}},[]);(0,l.useEffect)(()=>{let e=function(){try{let e=JSON.parse(window.localStorage.getItem(ee)||"{}");return{metric:X.some(t=>t.value===e.metric)?e.metric:"cost",days:y.some(t=>t.days===e.days)?e.days:30}}catch{return{metric:"cost",days:30}}}();A(s??e.metric),L(e.days);let t=new URLSearchParams(window.location.search).get("usageMember");t&&/^[0-9a-f-]{36}$/i.test(t)&&T(t),N(!0)},[s]),(0,l.useEffect)(()=>{w&&function(e){try{window.localStorage.setItem(ee,JSON.stringify(e))}catch{}}({metric:C,days:_})},[w,C,_]),(0,l.useEffect)(()=>{let e=window.setInterval(()=>
1O(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let H=(0,d.I)({queryKey:["usage-analytics",e,_,U,F,Z],enabled:w,staleTime:3e4,refetchInterval:!!B&&15e3,placeholderData:c.rX,queryFn:async({signal:t})=>et(await fetch(`/api/usage/analytics?${new URLSearchParams({days:String(_),...U===e?{}:{member:U},brandKit:F,tz:Z})}`,{cache:"no-store",signal:t}))}),G=(0,d.I)({queryKey:["usage-limits",e,U,a?.label??"live"],enabled:w&&"limits"===C,staleTime:15e3,queryFn:async({signal:t})=>a?{ok:!0,member:U,isAdmin:!1,accounts:await a.list(t)}:et(await fetch(`/api/usage/limits?${new URLSearchParams(U===e?{}:{member:U})}`,{cache:"no-store",signal:t}))}),Y=H.data,eo="within"===Q?Y:Y?.comparison?.[Q],ed=Y&&eo?{...Y,...eo}:void 0,ec=Y?.scope,eu=ec?.members??[],em=!!ec?.isAdmin,eh=eu.filter(e=>"sharing"===e.sharing).length,ex="all"===U?"All members":U===e?"You":eu.find(e=>e.id===U)?.label??"Team member",ep="all"===F?"All Brand Kits":F===j?"No Brand Kit":ec?.brandKits.find(e=>e.id===F)?.label??"Brand Kit",ef="limits"===C,eg=ed?.pricing.status!=="unavailable",eb=(ed?.providers??[]).map(e=>e.provider),ey=eb.length?eb:b.map(e=>e.key),ej=ed?.resolution==="hour",ew=[{value:"model",label:"Model"},{value:"time",label:ej?"Hour":"Day"},..."all"===U?[{value:"member",label:"Member"}]:[],{value:"identity",label:"Account"},{value:"brandKit",label:"Brand Kit"}],ev=ew.some(e=>e.value===R)?R:"model",eN=B||(ef?G.isFetching:H.isFetching),ek=async()=>{if(B)return!0;J(!0);let t=new URLSearchParams({member:U});try{if(!a){let e=await et(await fetch(`/api/usage/refresh?${t}`,{method:"POST"})),s=e.unavailable.map(e=>`${e.label}: ${e.reason}`);if(e.commands.length){t.set("commands",e.commands.map(e=>e.id).join(","));let r=!1;for(let e=0;e<30;e++){let e=await et(await fetch(`/api/usage/refresh?${t}`,{cache:"no-store"}));if(e.commands.every(e=>!["accepted","running"].includes(e.status))){let t=e.commands.filter(e=>"completed"!==e.status||!e.usageLimits).length;e.commands.some(e=>"completed"===e.status&&!e.historyAvailable)&&s.push("Native history is not available from every host yet. Update the connected Growthub host and refresh to include activity outside Growthub."),t&&s.push(`${t} provider ${1===t?"report did":"reports did"} not refresh. The last saved reports remain visible.`),r=!0;break}await new Promise(e=>setTimeout(e,2e3))}r||s.push("Provider refresh is still pending. The latest saved usage is shown; refresh again to check its result.")}else s.length||s.push("No connected provider accounts are available to refresh. The latest saved usage is shown.");s.length&&console.warn("[UsageSync]",s)}}catch(e){console.error("[UsageSync]",e)}finally{O(Date.now()),await Promise.all([m.invalidateQueries({queryKey:["usage-analytics",e]}),m.invalidateQueries({queryKey:["usage-limits",e]})]),J(!1)}return!0};(0,d.I)({queryKey:["usage-provider-sync",e,U],enabled:w&&!a,staleTime:6e4,refetchInterval:Y?.comparison?.coverage.pendingScan?6e4:3e5,refetchOnWindowFocus:!1,retry:!1,queryFn:ek});let eS=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[(0,r.jsxs)("nav",{"aria-label":"Usage scope",className:"flex min-w-0 items-center gap-1 text-sm",children:[(0,r.jsx)("span",{className:"px-1 text-muted-foreground",children:"Usage"}),(0,r.jsx)("span",{className:"text-muted-foreground",children:"/"}),em||eu.length>1?(0,r.jsxs)(er,{testId:"usage-member-scope",label:ex,heading:`Shared analytics \xb7 ${eh} ${1===eh?"member":"members"}`,children:[(0,r.jsx)(ea,{selected:"all"===U,onSelect:()=>T("all"),hint:"Your analytics and reports shared with you",children:"All members"}),(0,r.jsx)(p.mB,{}),eu.map(e=>(0,r.jsx)(ea,{selected:U===e.id,disabled:"not-sharing"===e.sharing,onSelect:()=>T(e.id),hint:en[e.sharing],children:e.label},e.id)),(0,r.jsx)(p.mB,{}),(0,r.jsxs)(p._2,{disabled:eN,onSelect:()=>void ek(),children:[(0,r.jsx)(h.A,{className:"mr-2 size-3.5"}),"Refresh selected usage"]})]}):(0,r.jsx)("span",{className:"px-1.5 font-medium text-foreground","data-testid":"usage-member-scope",children:"You"}),ef?null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-muted-foreground",children:"/"}),(0,r.jsxs)(er,{testId:"usage-brand-kit-scope",label:ep,heading:"Filter by Brand Kit (client)",children:[(0,r.jsx)(ea,{selected:"all"===F,onSelect:()=>{W("within"),M("all")},children:"All Brand Kits"}),(0,r.jsx)(ea,{selected:F===j,onSelect:()=>{W("within"),M(j)},hint:"Chats and runs without a Brand Kit",children:"No Brand Kit"}),(ec?.brandKits.length??0)>0?(0,r.jsx)(p.mB,{}):null,ec?.brandKits.map(e=>(0,r.jsx)(ea,{selected:F===e.id,onSelect:()=>{W("within"),M(e.id)},children:e.label},e.id))]})]})]}),(0,r.jsxs)("div",{className:"ms-auto flex flex-wrap items-center justify-end gap-2",children:[(0,r.jsx)(es,{label:"Usage metric",value:C,options:X,onChange:A}),(0,r.jsx)(es,{label:"Usage period",value:_,options:y.map(e=>({value:e.days,label:e.label})),onChange:L,disabled:ef}),(0,r.jsx)("button",{type:"button",onClick:ek,"aria-label":ef?"Refresh limits":"Refresh usage","aria-busy":eN,disabled:eN,className:"inline-flex size-8 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-60",children:(0,r.jsx)(h.A,{className:(0,g.cn)("size-4",eN&&"animate-spin")})}),(0,r.jsx)(I,{userId:e,onUpdated:()=>
1{m.invalidateQueries({queryKey:["usage-analytics"]}),m.invalidateQueries({queryKey:["usage-limits"]})}})]})]});if(ef)u=(0,r.jsxs)("div",{className:"flex flex-col gap-10",children:[a?(0,r.jsx)("span",{className:"w-fit rounded-full border px-2 py-0.5 text-xs text-muted-foreground",children:a.label}):null,(0,r.jsx)(V,{accounts:G.data?.accounts??[],now:z,isPending:G.isPending,error:G.error instanceof Error?G.error.message:null,showMembers:"all"===U,emptyHint:U===e||"all"===U?(0,r.jsxs)(r.Fragment,{children:["No Codex or Claude account has reported limits yet. Add or sign in to an account under ",(0,r.jsx)(n(),{className:"underline",href:"/dashboard/settings?tab=connections&connections=providers",children:"AI providers"}),"."]}):"This member has no provider account reporting limits yet."}),U===e&&t?(0,r.jsx)("div",{className:"border-t pt-8",children:t}):null]});else if(Y&&!eo)u=(0,r.jsxs)("div",{"aria-label":"Loading usage","aria-busy":"true",className:"grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]",children:[(0,r.jsx)("div",{className:"h-40 animate-pulse rounded-lg bg-muted/60"}),(0,r.jsx)("div",{className:"h-60 animate-pulse rounded-lg bg-muted/60"})]});else if(H.isPending||!ed)u=H.error?(0,r.jsx)("p",{role:"alert",className:"py-6 text-sm text-destructive",children:H.error instanceof Error?H.error.message:"Usage could not be loaded."}):(0,r.jsxs)("div",{role:"status","aria-label":"Loading usage",className:"grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]",children:[(0,r.jsx)("div",{className:"h-40 animate-pulse rounded-lg bg-muted/60"}),(0,r.jsx)("div",{className:"h-60 animate-pulse rounded-lg bg-muted/60"})]});else{let e=ed.totals;u=(0,r.jsxs)("div",{className:"flex flex-col gap-8",children:[H.error?(0,r.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:H.error instanceof Error?H.error.message:"Usage could not be refreshed."}):null,ed.truncated?(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"This window has more provider events than one read covers; totals include the first 50,000. Choose a shorter window for exact totals."}):null,(0,r.jsxs)("section",{className:"grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]",children:[(0,r.jsxs)("div",{className:"flex min-w-0 flex-col gap-5",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,r.jsx)("span",{className:"text-4xl font-semibold tabular-nums text-foreground","data-testid":"usage-headline",children:"cost"===C?eg&&e.unpricedRecords<e.records?k(e.costUsd):e.records?"Unpriced":k(0):v(e.totalTokens)}),(0,r.jsxs)("span",{className:"flex flex-wrap items-center gap-1 text-xs text-muted-foreground",children:[$(e.sessions)," ",1===e.sessions?"session":"sessions","cost"===C?eg?(0,r.jsxs)(r.Fragment,{children:[" \xb7 API estimate",e.unpricedShare>0?(0,r.jsxs)(r.Fragment,{children:[" excludes ",S(e.unpricedShare)," unpriced records"]}):null,(0,r.jsxs)(f.m_,{children:[(0,r.jsx)(f.k$,{asChild:!0,children:(0,r.jsx)("button",{type:"button","aria-label":"About this estimate",className:"inline-flex text-muted-foreground hover:text-foreground",children:(0,r.jsx)(x.A,{className:"size-3"})})}),(0,r.jsx)(f.ZI,{side:"top",className:"max-w-xs text-xs",children:"Estimated cost for the selected activity at model API rates. Tokens come from recorded provider usage; this estimate is not a subscription invoice."})]})]}):" \xb7 Pricing catalog unavailable; tokens are exact":null]}),0===e.records?(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"No recorded activity in this view and time window."}):null]}),ed.providers.map(e=>{let t="cost"===C?e.costShare:e.tokenShare,s=eg&&e.unpricedRecords<e.records;return(0,r.jsxs)("div",{className:"flex flex-col gap-1","data-testid":`usage-provider-${e.provider}`,children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-4",children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-2 text-sm text-foreground",children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"size-2 shrink-0 rounded-full",style:{backgroundColor:D[e.provider]}}),(0,r.jsx)(K,{provider:e.provider,className:"size-4"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[(0,r.jsx)("span",{className:"truncate",children:P[e.provider]}),(0,r.jsxs)("span",{className:"shrink-0 whitespace-nowrap text-[11px] tabular-nums text-muted-foreground",children:[$(e.sessions)," ",1===e.sessions?"session":"sessions"]})]})]}),(0,r.jsx)("span",{className:"shrink-0 text-sm font-medium tabular-nums text-foreground",children:"cost"===C?s?k(e.costUsd):"Unpriced":v(e.totalTokens)})]}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground",children:"cost"===C?`${s?`${S(t)} of cost`:"Unpriced"} \xb7 ${v(e.totalTokens)} tokens`:`${S(t)} of tokens \xb7 ${s?k(e.costUsd):"unpriced"}`})]},e.provider)})]}),(0,r.jsxs)("div",{className:"flex min-w-0 flex-col gap-3",children:[(0,r.jsxs)("h2",{className:"text-sm font-medium text-foreground",children:[ej?"Hourly":"Daily"," ","tokens"!==C&&eg?"cost":"processed tokens"]}),(0,r.jsx)(E,{series:ed.series,providers:ey,metric:"tokens"!==C&&eg?"cost":"tokens",resolution:ed.resolution})]})]}),(0,r.jsxs)("section",{className:"flex flex-col gap-2",children:[(0,r.jsx)("h2",{className:"text-sm font-medium text-foreground",children:"Totals"}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5","data-testid":"usage-totals",children:[(0,r.jsx)(ei,{label:"Processed tokens",value:v(e.totalTokens)}),(0,r.jsx)(ei,{label:"Cached input",value:v(e.cachedInputTokens)}),(0,r.jsx)(ei,{label:"Uncached input",value:v(e.uncachedInputTokens)}),(0,r.jsx)(ei,{label:"Output",value:v(e.outputTokens)}),(0,r.jsx)(ei,{label:"Cache savings",value:eg?k(e.cacheSavingsUsd):"Unpriced"})]})]}),(0,r.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[(0,r.jsx)("h2",{className:"text-sm font-medium text-foreground",children:"Breakdown"}),(0,r.jsx)(es,{label:"Usage breakdown",value:ev,options:ew,onChange:q})]}),(0,r.jsx)(el,{kind:ev,rows:ed.breakdown[ev],providers:eb,hourly:ej,pricingAvailable:eg})]})]})}return(0,r.jsx)(f.Bc,{delayDuration:150,children:(0,r.jsxs)("section",{className:"flex flex-col gap-8","aria-label":"Usage","data-testid":"usage-page",children:[eS,!ef&&(0,r.jsx)("div",{className:"space-y-3",children:(0,r.jsx)("div",{role:"group","aria-label":"Activity source",className:"flex flex-wrap gap-2",children:[["total","Total account usage"],["within","Within Growthub"],["outside","Outside Growthub"]].map(([e,t])=>(0,r.jsx)(i.$,{size:"sm",width:"auto",variant:Q===e?"within"===e?"gradient":"secondary":"ghost","aria-pressed":Q===e,onClick:()=>{W(e),"within"!==e&&M("all")},children:t},e))})}),u]})})}},80223:(e,t,s)=>{s.d(t,{J:()=>v});var r=s(68987),a=s(2315),n=s(7586),i=s(49405),l=s(72961),o=s(76843),d=s(42934),c=s(1925),u=s(34921),m=s(211
178),h=s(75035),x=s(64094),p=s(51374),f=s(45092),g=s(38193),b=s(93210),y=s(83360),j=s(70862);function w({workspaceId:e,userRole:t,userId:s,selectedUserIds:n=[],onSelectionChange:l,disabled:d=!1}){let[c,u]=(0,a.useState)(n.length>0?"specific":"all"),[h,w]=(0,a.useState)([]),[v,N]=(0,a.useState)(!1),[k,S]=(0,a.useState)(""),[$,C]=(0,a.useState)(new Set(n));(0,a.useEffect)(()=>{(async()=>{if(!e)return w([]);N(!0);try{let t=await fetch(`/api/knowledge/workspace-users?workspace_id=${e}`),s=await t.json();if(s.success&&s.users){let e=s.users.map(e=>({user_id:e.user_id,email:e.email,full_name:e.full_name,role:e.role,is_primary:e.is_primary||!1}));w(e)}else console.warn("[WorkspaceUserSelector] â API returned unsuccessful:",s),w([])}catch(e){console.error("[WorkspaceUserSelector] Error loading workspace users:",e),w([])}finally{N(!1)}})()},[e]),(0,a.useEffect)(()=>{n.length>0?(u("specific"),C(new Set(n))):(u("all"),C(new Set))},[e]);let A=(0,a.useMemo)(()=>{if(!k.trim())return h;let e=k.toLowerCase();return h.filter(t=>t.email.toLowerCase().includes(e)||t.full_name?.toLowerCase().includes(e)||t.role.toLowerCase().includes(e))},[h,k]),_=e=>{let t=new Set($);t.has(e)?t.delete(e):t.add(e),C(t),l({type:"specific",userIds:Array.from(t)})};return(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsxs)(f.z,{value:c||"all",onValueChange:e=>{!d&&!v&&(u(e),"all"===e?(C(new Set),l({type:"all"})):l({type:"specific",userIds:Array.from($)}))},className:"space-y-2",children:[(0,r.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,r.jsx)(f.C,{value:"all",id:"all",disabled:d||v,className:"flex-shrink-0"}),(0,r.jsxs)(g.J,{htmlFor:"all",className:(0,b.cn)("flex items-center gap-2 flex-1",d||v?"cursor-not-allowed opacity-50":"cursor-pointer"),children:[(0,r.jsx)(m.A,{className:"h-4 w-4 flex-shrink-0"}),(0,r.jsx)("span",{children:"All workspace members"}),(0,r.jsx)(x.E,{variant:"outline",className:"text-xs flex-shrink-0",children:h.length})]})]}),(0,r.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,r.jsx)(f.C,{value:"specific",id:"specific",disabled:d||v,className:"flex-shrink-0"}),(0,r.jsxs)(g.J,{htmlFor:"specific",className:(0,b.cn)("flex items-center gap-2 flex-1",d||v?"cursor-not-allowed opacity-50":"cursor-pointer"),children:[(0,r.jsx)(y.A,{className:"h-4 w-4 flex-shrink-0"}),(0,r.jsx)("span",{children:"Specific users"}),"specific"===c&&$.size>0&&(0,r.jsxs)(x.E,{variant:"secondary",className:"text-xs flex-shrink-0",children:[$.size," selected"]})]})]})]}),"specific"===c&&(0,r.jsxs)("div",{className:"space-y-3 border rounded-lg p-4 bg-gray-50",children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)(j.A,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"}),(0,r.jsx)(o.p,{placeholder:"Search users by name or email...",value:k,onChange:e=>S(e.target.value),className:"pl-9",disabled:d||v})]}),A.length>0&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,r.jsxs)(i.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{let e=new Set(A.map(e=>e.user_id));C(e),l({type:"specific",userIds:Array.from(e)})},disabled:d||v,className:"h-7 text-xs",children:["Select all (",A.length,")"]}),$.size>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"text-gray-400",children:"â¢"}),(0,r.jsxs)(i.$,{type:"button",variant:"ghost",size:"sm",onClick:()=>{C(new Set),l({type:"specific",userIds:[]})},disabled:d||v,className:"h-7 text-xs",children:["Clear (",$.size,")"]})]})]}),(0,r.jsx)("div",{className:"max-h-64 overflow-y-auto space-y-2",children:v?(0,r.jsx)("div",{className:"text-center py-4 text-sm text-gray-500",children:"Loading users..."}):0===A.length?(0,r.jsx)("div",{className:"text-center py-4 text-sm text-gray-500",children:k?"No users found matching your search":"No users in workspace"}):A.map(e=>{let t=$.has(e.user_id),a=e.user_id===s;return(0,r.jsxs)("div",{className:(0,b.cn)("flex items-center gap-3 p-3 rounded-lg border transition-colors",t?"bg-blue-50/50 border-blue-200":"bg-white border-gray-200 hover:border-gray-300",d&&"opacity-50"),children:[(0,r.jsx)(p.S,{checked:t,onCheckedChange:()=>!d&&!v&&_(e.user_id),disabled:d||v,className:"flex-shrink-0"}),(0,r.jsxs)("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>!d&&!v&&_(e.user_id),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,r.jsx)("span",{className:"font-medium text-sm text-gray-900",children:e.full_name||e.email.split("@")[0]}),a&&(0,r.jsx)(x.E,{variant:"outline",className:"text-xs font-normal",children:"You"}),(0,r.jsx)(x.E,{variant:"owner"===e.role?"default":"admin"===e.role?"secondary":"outline",className:"text-xs font-normal capitalize",children:e.role}),e.is_primary&&(0,r.jsx)(x.E,{variant:"default",className:"text-xs font-normal",children:"Primary"})]}),(0,r.jsx)("div",{className:"text-xs text-gray-500 truncate mt-0.5",children:e.email})]})]},e.user_id)})}),$.size>0&&(0,r.jsxs)("div",{className:"pt-2 border-t text-sm text-gray-600",children:[$.size," user",1!==$.size?"s":""," selected"]})]}),"all"===c&&(0,r.jsxs)("div",{className:"text-xs text-gray-500 bg-blue-50 border border-blue-200 rounded-md p-2",children:["Knowledge will be shared with all ",h.length," member",1!==h.length?"s":""," of this workspace."]})]})}function v({item:e,userId:t,onUpdate:s}){let x=(0,a.useMemo)(()=>e.metadata||{},[e.metadata]),p=(0,a.useMemo)(()=>{let e=x.workspace_user_ids;return Array.isArray(e)&&e.length>0?{type:"specific",userIds:e}:{type:"all"}},[x.workspace_user_ids]),[f,g]=(0,a.useState)(()=>x.visibility||"private"),[b,y]=(0,a.useState)(()=>x.workspace_id||null),[j,v]=(0,a.useState)(()=>p),[N,k]=(0,a.useState)(!1),[S,$]=(0,a.useState)(()=>{let e=x.share_config||{};return Array.isArray(e.collaborators)?e.collaborators:[]}),[C,A]=(0,a.useState)(""),[_,I]=(0,a.useState)(!0),[L,U]=(0,a.useState)(null),[T,F]=(0,a.useState)(null),[M,R]=(0,a.useState)(!1),{data:q=[],isLoading:P,refetch:D}=(0,n.I)({queryKey:["knowledge-shared-entities",M],enabled:M,queryFn:async()=>{let e=await fetch("/api/knowledge/share/manage"),t=await e.json();if(!e.ok||!t?.success)throw Error(t?.error||"Failed to load shared entities");return Array.isArray(t.entities)?t.entities:[]}}),{data:K=[],isLoading:z}=(0,n.I)({queryKey:["knowledge-user-workspaces",t],enabled:!!t,queryFn:async()=>{let e=await fetch("/api/knowledge/user-workspaces"),t=await e.json();return e.ok&&t?.success&&Array.isArray(t.workspaces)?t.workspaces:[]}}),E=async()=>{k(!0);try{let t={knowledge_item_id:e.id,visibility:f};
1"workspace"===f&&b&&(t.workspace_id=b,"specific"===j.type&&(t.workspace_user_ids=j.userIds||[]));let r=await fetch("/api/knowledge/share",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),a=await r.json();a.success?s():(console.error("[KnowledgeSharingControls] Save error:",a.error),alert(a.error||"Failed to update sharing settings"))}catch(e){console.error("[KnowledgeSharingControls] Save error:",e),alert("Failed to update sharing settings")}finally{k(!1)}},O=async()=>{try{let t=await fetch("/api/knowledge/share/manage"),s=await t.json();if(!t.ok||!s?.success||!Array.isArray(s.entities))return;let r=s.entities.find(t=>t.id===e.id);$(Array.isArray(r?.collaborators)?r.collaborators:[])}catch{}},B=async()=>{let t=C.trim().toLowerCase();if(t){F(`invite:${t}`),U(null);try{let r=await fetch("/api/knowledge/share/invite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({knowledge_item_id:e.id,email:t,can_edit:_,apply_to_table_items:"table"===e.source_type})}),a=await r.json();if(!r.ok||!a?.success)return void alert(a?.error||"Failed to invite collaborator");A(""),U(a.invitation_sent?{sent:!0,message:"Access saved. Invitation email sent."}:{sent:!1,message:`Access saved, but the invitation email was not sent. ${a.warning||"Email delivery could not be confirmed."}`}),await O(),await D(),s()}finally{F(null)}}},J=async(e,t,r,a)=>{F(`set:${e}:${r.email||r.user_id||"unknown"}`);try{let n=await fetch("/api/knowledge/share/manage",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({knowledge_item_id:e,action:"set_access",email:r.email||null,user_id:r.user_id||null,can_edit:a,apply_to_table_items:"table"===t})}),i=await n.json();if(!n.ok||!i?.success)return void alert(i?.error||"Failed to update collaborator access");await O(),await D(),s()}finally{F(null)}},Q=async(e,t,r)=>{let a=r.email||r.user_id||"this collaborator";if(window.confirm(`Remove access for ${a}?`)){F(`revoke:${e}:${a}`);try{let a=await fetch("/api/knowledge/share/manage",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({knowledge_item_id:e,action:"revoke",email:r.email||null,user_id:r.user_id||null,apply_to_table_items:"table"===t})}),n=await a.json();if(!a.ok||!n?.success)return void alert(n?.error||"Failed to revoke collaborator");await O(),await D(),s()}finally{F(null)}}},W=[{value:"private",label:"Private",icon:u.A,description:"Only you can access"},{value:"workspace",label:"Workspace",icon:m.A,description:"Shared with workspace members"},{value:"public",label:"Public",icon:h.A,description:"Accessible to all users"}];return(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs text-gray-500 uppercase mb-2 block",children:"Visibility"}),(0,r.jsxs)(l.l6,{value:f,onValueChange:e=>g(e),disabled:N||z,children:[(0,r.jsx)(l.bq,{children:(0,r.jsx)(l.yv,{})}),(0,r.jsx)(l.gC,{children:W.map(e=>{let t=e.icon;return(0,r.jsx)(l.eb,{value:e.value,children:(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(t,{className:"h-4 w-4"}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"font-medium",children:e.label}),(0,r.jsx)("div",{className:"text-xs text-gray-500",children:e.description})]})]})},e.value)})})]})]}),"workspace"===f&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs text-gray-500 uppercase mb-2 block",children:"Workspace"}),(0,r.jsxs)(l.l6,{value:b||void 0,onValueChange:e=>{y(e||null),v({type:"all"})},disabled:N||z,children:[(0,r.jsx)(l.bq,{children:(0,r.jsx)(l.yv,{placeholder:z?"Loading workspaces...":0===K.length?"No workspaces available":"Select workspace"})}),(0,r.jsx)(l.gC,{children:0===K.length?(0,r.jsx)("div",{className:"px-2 py-1.5 text-sm text-gray-500",children:"No workspaces available"}):K.map(e=>(0,r.jsx)(l.eb,{value:e.workspace_id,children:e.workspace_name||`Workspace ${e.workspace_id.substring(0,8)}`},e.workspace_id))})]})]}),b&&(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs text-gray-500 uppercase mb-2 block",children:"Share With"}),(0,r.jsx)(w,{workspaceId:b,userRole:K.find(e=>
1e.workspace_id===b)?.role||"member",userId:t,selectedUserIds:"specific"===j.type&&j.userIds||[],onSelectionChange:v,disabled:N||z})]})]}),(0,r.jsx)(i.$,{onClick:E,disabled:N||z||"workspace"===f&&!b||"workspace"===f&&"specific"===j.type&&(!j.userIds||0===j.userIds.length),size:"sm",width:"auto",children:N?"Saving...":"Save Sharing Settings"}),(0,r.jsxs)("div",{className:"space-y-2.5 rounded-md border border-gray-200 bg-white p-3",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-xs font-medium text-gray-500 uppercase",children:"Collaborators"}),(0,r.jsxs)("p",{className:"text-xs text-muted-foreground",children:[S.length," assigned"]})]}),(0,r.jsx)(i.$,{size:"sm",variant:"outline",width:"auto",className:"h-8 bg-white text-black border-gray-300 hover:bg-gray-50 hover:text-black",onClick:()=>R(!0),children:"Manage"})]}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(o.p,{value:C,onChange:e=>A(e.target.value),placeholder:"Invite by email",className:"h-8"}),(0,r.jsxs)("label",{className:"inline-flex shrink-0 items-center gap-2 text-xs text-gray-600",children:[(0,r.jsx)("input",{type:"checkbox",checked:_,onChange:e=>I(e.target.checked)}),"Can edit"]}),(0,r.jsx)(i.$,{size:"sm",variant:"outline",width:"auto",className:"h-8 shrink-0 bg-white text-black border-gray-300 hover:bg-gray-50 hover:text-black",disabled:!!T,onClick:()=>void B(),children:"Invite"})]}),L&&(0,r.jsx)("p",{role:L.sent?"status":"alert",className:"text-xs text-muted-foreground",children:L.message})]}),(0,r.jsx)(c.lG,{open:M,onOpenChange:R,children:(0,r.jsxs)(c.Cf,{className:"max-w-3xl p-4 sm:p-6",children:[(0,r.jsx)(c.c7,{children:(0,r.jsx)(c.L3,{children:"Manage Collaborators"})}),P?(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"Loading shared items..."}):0===q.length?(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"No shared items yet."}):(0,r.jsx)("div",{className:"max-h-[60vh] space-y-2.5 overflow-auto pr-1",children:q.map(e=>(0,r.jsxs)("div",{className:"rounded-md border border-gray-200 p-3",children:[(0,r.jsxs)("div",{className:"mb-2.5",children:[(0,r.jsx)("p",{className:"text-sm font-medium",children:e.name}),(0,r.jsxs)("p",{className:"text-xs text-muted-foreground",children:[e.source_type," \xb7 ",e.collaborator_count," collaborator(s)"]})]}),(0,r.jsx)("div",{className:"space-y-2",children:e.collaborators.map(t=>{let s=t.email||t.user_id||"Unknown user",a=!!(T&&T.includes(`${e.id}:`));return(0,r.jsxs)("div",{className:"flex items-center justify-between rounded border border-gray-200 px-2 py-1.5",children:[(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("p",{className:"truncate text-xs font-medium",children:s}),(0,r.jsx)("p",{className:"text-[11px] text-gray-500",children:t.can_edit?"Can edit":"Can view"})]}),(0,r.jsxs)(d.rI,{children:[(0,r.jsx)(d.ty,{asChild:!0,children:(0,r.jsx)(i.$,{size:"sm",variant:"outline",width:"auto",className:"h-7 px-2",disabled:a,suppressHydrationWarning:!0,children:(0,r.jsx)(m.A,{className:"h-3 w-3"})})}),(0,r.jsxs)(d.SQ,{align:"end",className:"w-40",children:[(0,r.jsx)(d._2,{onSelect:()=>void J(e.id,e.source_type,t,!0),children:"Can edit"}),(0,r.jsx)(d._2,{onSelect:()=>void J(e.id,e.source_type,t,!1),children:"Can view"}),(0,r.jsx)(d.mB,{}),(0,r.jsx)(d._2,{className:"text-red-600 focus:text-red-600",onSelect:()=>void Q(e.id,e.source_type,t),children:"Revoke access"})]})]})]},`${e.id}:${s}`)})})]},e.id))})]})})]})}}}]);
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.