@hienlh/ppm 0.9.72 → 0.9.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/web/assets/{chat-tab-BIXfzq-R.js → chat-tab-ByDDO6Pl.js} +2 -2
  3. package/dist/web/assets/{code-editor-DiFWfbbf.js → code-editor-D8VveTUt.js} +1 -1
  4. package/dist/web/assets/{database-viewer-BXHyTgAk.js → database-viewer-CcTlsR2D.js} +1 -1
  5. package/dist/web/assets/{diff-viewer-qdcj9_Bg.js → diff-viewer-CXU5BvCX.js} +1 -1
  6. package/dist/web/assets/{extension-webview-CYyNGX7Q.js → extension-webview-Dzkyl-2t.js} +1 -1
  7. package/dist/web/assets/{git-graph-BaRxrAyx.js → git-graph-Ce8pbmQX.js} +1 -1
  8. package/dist/web/assets/{index-DmuOwe2C.js → index-Y-Kfye7A.js} +3 -3
  9. package/dist/web/assets/keybindings-store-DoRbfX4Q.js +1 -0
  10. package/dist/web/assets/{markdown-renderer-BP1o2VVM.js → markdown-renderer-BinWj98E.js} +1 -1
  11. package/dist/web/assets/{port-forwarding-tab-DTCNdTnl.js → port-forwarding-tab-D15vANLc.js} +1 -1
  12. package/dist/web/assets/{postgres-viewer-Cj7U16lk.js → postgres-viewer-Nlg7DV9i.js} +1 -1
  13. package/dist/web/assets/{settings-tab-C_VMlB_J.js → settings-tab-BY9LX5Du.js} +1 -1
  14. package/dist/web/assets/{sql-query-editor-CqVt5FDX.js → sql-query-editor-njmHoOsX.js} +1 -1
  15. package/dist/web/assets/{sqlite-viewer-BuzTVRKG.js → sqlite-viewer-jSYguEYD.js} +1 -1
  16. package/dist/web/assets/{terminal-tab-BqFOxgtv.js → terminal-tab-DUz3dmkj.js} +1 -1
  17. package/dist/web/assets/{use-monaco-theme-COffNaVJ.js → use-monaco-theme-Dl6w9X-L.js} +1 -1
  18. package/dist/web/index.html +1 -1
  19. package/dist/web/sw.js +1 -1
  20. package/docs/project-changelog.md +22 -1
  21. package/docs/system-architecture.md +1 -1
  22. package/package.json +1 -1
  23. package/src/providers/claude-agent-sdk.ts +59 -22
  24. package/src/services/account-selector.service.ts +25 -7
  25. package/src/types/chat.ts +1 -0
  26. package/src/web/components/chat/message-list.tsx +5 -0
  27. package/src/web/hooks/use-chat.ts +7 -0
  28. package/dist/web/assets/keybindings-store-DUcpLoKq.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.9.73] - 2026-04-09
4
+
5
+ ### Added
6
+ - **Pre-flight token refresh loop**: Account selection now retries all available accounts when OAuth token refresh fails, instead of failing immediately.
7
+ - **`status_update` ChatEvent**: Frontend shows real-time status during account routing, token refresh, and account switching phases.
8
+ - **`onPreflightFail()` method**: Failed accounts enter 60s–5min exponential cooldown during pre-flight.
9
+ - **`excludeIds` param for `next()`**: Account selector can skip specific accounts (used by pre-flight loop).
10
+ - Unit tests for `next(excludeIds)`, `onPreflightFail()`, and `all_excluded` fail reason (+7 tests).
11
+
3
12
  ## [0.9.72] - 2026-04-09
4
13
 
5
14
  ### Added
@@ -1,9 +1,9 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/api-client-BfBM3I7n.js","assets/chunk-CFjPhJqf.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import"./react-dom-Bpkvzu3U.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{t as r}from"./arrow-up-BYhx9ckd.js";import{n as i,t as a}from"./x-D2_KzIET.js";import{t as o}from"./chevron-right-4zq1jPv6.js";import{n as s,t as c}from"./markdown-renderer-BP1o2VVM.js";import{t as l}from"./columns-2-BoZAN-iw.js";import{t as u}from"./square-oPKIkJiw.js";import{t as d}from"./tag-CXMT0QB6.js";import{t as f}from"./preload-helper-Bf_JiD2A.js";import{t as p}from"./jsx-runtime-kMwlnEGE.js";import"./dist-DIV6WgAG.js";import{n as m,r as h,t as g}from"./utils-BNytJOb1.js";import{i as _,r as v,t as y}from"./api-client-BfBM3I7n.js";import{a as b,c as x,f as ee,g as S,i as C,l as w,m as T,o as E,p as D,r as O,s as k,t as A,u as j}from"./api-settings-Bn-bIxD1.js";import{$ as M,A as N,At as P,B as te,C as F,Ct as I,D as L,Dt as ne,E as R,Ft as z,It as B,J as V,K as H,Lt as U,M as W,Mt as G,O as K,Ot as re,Pt as q,Q as J,T as Y,Tt as X,Y as ie,Z as ae,_t as oe,bt as se,c as ce,ct as le,d as ue,dt as de,et as fe,f as pe,ft as me,h as he,ht as ge,i as _e,it as ve,j as ye,jt as be,k as xe,l as Se,m as Ce,nt as we,ot as Te,p as Ee,pt as Z,q as De,r as Oe,rt as ke,s as Ae,st as je,t as Me,tt as Ne,u as Pe,ut as Fe,vt as Ie,wt as Le}from"./index-DmuOwe2C.js";import"./chunk-GEFDOKGD-D-pKjlVd.js";import"./src-BqX54PbV.js";import"./chunk-7R4GIKGN-Dv-4cAYn.js";import"./chunk-HHEYEP7N-C7vxA5i9.js";import"./dist-CSJdAyA9.js";import"./chunk-PU5JKC2W-ek7k4QVB.js";import"./chunk-MX3YWQON-BpS_PtKp.js";import"./chunk-YBOYWFTD-rQG3QH5s.js";import"./chunk-PQ6SQG4A-TF58UVMU.js";import"./chunk-KYZI473N-Bb0MCaIO.js";import"./chunk-O4XLMI2P-nDhi_cVu.js";import"./chunk-GLR3WWYH-DKikpoJM.js";import"./chunk-XPW4576I-BPQQBakK.js";var Re=n(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),ze=n(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),Be=n(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),Ve=n(`clipboard-list`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`M12 11h4`,key:`1jrz19`}],[`path`,{d:`M12 16h4`,key:`n85exb`}],[`path`,{d:`M8 11h.01`,key:`1dfujw`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),He=n(`hand`,[[`path`,{d:`M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2`,key:`1fvzgz`}],[`path`,{d:`M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2`,key:`1kc0my`}],[`path`,{d:`M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8`,key:`10h0bg`}],[`path`,{d:`M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15`,key:`1s1gnw`}]]),Ue=n(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),We=n(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Ge=n(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]),Ke=n(`list-todo`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`,key:`cif1o7`}]]),qe=n(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Je=n(`mic-off`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`,key:`1gzdoj`}],[`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`,key:`cqa7eg`}],[`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`,key:`16hl24`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`,key:`r2i35w`}]]),Ye=n(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),Xe=n(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Ze=n(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Qe=n(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),$e=n(`shield-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71`,key:`1jlk70`}],[`path`,{d:`M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264`,key:`18rp1v`}]]),et=n(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),tt=n(`users`,[[`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,key:`1yyitq`}],[`path`,{d:`M16 3.128a4 4 0 0 1 0 7.744`,key:`16gr8j`}],[`path`,{d:`M22 21v-2a4 4 0 0 0-3-3.87`,key:`kshegd`}],[`circle`,{cx:`9`,cy:`7`,r:`4`,key:`nufk8`}]]),nt=n(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),Q=e(t(),1);function rt({url:e,onMessage:t,autoConnect:n=!0}){let r=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let i=new Me(e);return r.current=i,t&&i.onMessage(t),n&&i.connect(),()=>{i.disconnect(),r.current=null}},[e,n]),{send:(0,Q.useCallback)(e=>{r.current?.send(e)},[]),connect:(0,Q.useCallback)(()=>{r.current?.connect()},[]),disconnect:(0,Q.useCallback)(()=>{r.current?.disconnect()},[])}}var it=null;function at(){return it||=new AudioContext,it}function ot(e,t,n,r,i=`sine`){let a=at(),o=a.createOscillator(),s=a.createGain();o.type=i,o.frequency.value=e,s.gain.setValueAtTime(r,n),s.gain.exponentialRampToValueAtTime(.001,n+t),o.connect(s),s.connect(a.destination),o.start(n),o.stop(n+t)}function st(){let e=at().currentTime;ot(523,.15,e,.15),ot(659,.2,e+.12,.15)}function ct(){let e=at().currentTime;ot(880,.12,e,.18,`square`),ot(698,.12,e+.15,.18,`square`),ot(880,.15,e+.3,.15,`square`)}function lt(){let e=at().currentTime;ot(440,.12,e,.12),ot(523,.12,e+.1,.12),ot(659,.18,e+.2,.12)}var ut={done:st,approval_request:ct,question:lt};function dt(e){try{ut[e]?.()}catch{}}var ft={hasTeams:!1,teamNames:[],messageCount:0,unreadCount:0};function pt(e){if(document.hidden)return!1;let{panels:t,focusedPanelId:n}=V.getState(),r=t[n];if(!r)return!1;let i=r.tabs.find(e=>e.id===r.activeTabId);return i?.type===`chat`&&i.metadata?.sessionId===e}function mt(e,t=`claude`,n=``){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(`idle`),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[ee,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(null),D=(0,Q.useRef)(``),O=(0,Q.useRef)([]),k=(0,Q.useRef)(null),A=(0,Q.useRef)(`idle`),j=(0,Q.useRef)(null),M=(0,Q.useRef)(()=>{}),N=(0,Q.useRef)(null),P=(0,Q.useRef)(e);P.current=e;let F=(0,Q.useRef)(n);F.current=n;let I=(0,Q.useRef)({teamNames:new Set,messages:[]}),L=(0,Q.useRef)(0),[ne,R]=(0,Q.useState)(ft),[z,B]=(0,Q.useState)([]),V=(0,Q.useCallback)(()=>{let e=I.current;R({hasTeams:e.teamNames.size>0,teamNames:Array.from(e.teamNames),messageCount:e.messages.length,unreadCount:L.current}),B([...e.messages])},[]),H=(0,Q.useCallback)(()=>{L.current=0,V()},[V]),U=s!==`idle`,W=(0,Q.useCallback)((e,t)=>{let n=O.current.findIndex(e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t);if(n===-1)return!1;let r=O.current[n];if(r.type!==`tool_use`)return!1;let i=[...r.children??[],e];return O.current[n]={...r,children:i},!0},[]),G=(0,Q.useCallback)(()=>{let e=D.current,t=[...O.current],n=k.current;i(r=>{let i=r[r.length-1];return i?.role===`assistant`&&!i.id.startsWith(`final-`)?[...r.slice(0,-1),{...i,content:e,events:t,...n}]:[...r,{id:`streaming-${Date.now()}`,role:`assistant`,content:e,events:t,timestamp:new Date().toISOString(),...n}]})},[]),K=(0,Q.useCallback)(e=>{let t=e,n=t?.type;if(n)switch(n){case`account_info`:k.current={accountId:t.accountId,accountLabel:t.accountLabel};break;case`account_retry`:t.accountId&&t.accountLabel&&(k.current={accountId:t.accountId,accountLabel:t.accountLabel}),O.current.push(t),G();break;case`text`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}D.current+=t.content,O.current.push(t),G();break}case`thinking`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`tool_use`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`tool_result`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`approval_request`:if(O.current.push(t),m({requestId:t.requestId,tool:t.tool,input:t.input}),P.current&&!pt(P.current)){let e=t.tool===`AskUserQuestion`?`question`:`approval_request`;te.getState().addNotification(P.current,e,F.current),dt(e)}break;case`error`:{O.current.push(t);let e=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,events:e}]:[...n,{id:`error-${Date.now()}`,role:`system`,content:t.message,events:[t],timestamp:new Date().toISOString()}]});break}case`team_detected`:{let e=t.teamName;e&&(I.current.teamNames.add(e),y.get(`/api/teams/${encodeURIComponent(e)}`).then(e=>{if(e?.messages){let t=I.current.messages,n=e.messages.filter(e=>!t.some(t=>t.timestamp===e.timestamp&&t.from===e.from));t.push(...n),t.sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())}V()}).catch(()=>{}),V());break}case`team_inbox`:{let e=t.messages;Array.isArray(e)&&(I.current.messages.push(...e),L.current+=e.length,V());break}case`team_updated`:V();break;case`done`:{if(A.current===`idle`)break;t.contextWindowPct!=null&&g(t.contextWindowPct),P.current&&!pt(P.current)&&(te.getState().addNotification(P.current,`done`,F.current),dt(`done`));let e=D.current,n=[...O.current];i(t=>{let r=t[t.length-1];return r?.role===`assistant`?[...t.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:n.length>0?n:r.events}]:t}),D.current=``,O.current=[],k.current=null;break}}},[W,G]),re=(0,Q.useCallback)(e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(t.type!==`ping`){if(t.type===`session_migrated`){let e=t.newSessionId;e&&E(e);return}if(t.type===`title_updated`){S(t.title??null);return}if(t.type===`compact_status`){let e=t.status;e===`compacting`?x(`compacting`):e===`done`&&(x(null),N.current?.());return}if(t.type===`phase_changed`){let e=t.phase;c(e),A.current=e,f(e===`connecting`?t.elapsed??0:0);return}if(t.type===`session_state`){w(!0);let e=t,n=e.phase;c(n),A.current=n,e.sessionTitle&&S(e.sessionTitle),e.pendingApproval&&m({requestId:e.pendingApproval.requestId,tool:e.pendingApproval.tool,input:e.pendingApproval.input}),n===`idle`&&(N.current?.(),u(!1));return}if(t.type===`turn_events`){let e=t.events;if(!e?.length){u(!1);return}i(e=>{let t=e.findLastIndex(e=>e.role===`user`);return t>=0?e.slice(0,t+1):e}),D.current=``,O.current=[],k.current=null;let n=0,r=()=>{let t=Math.min(n+100,e.length);for(let r=n;r<t;r++)K(e[r]);n=t,n<e.length?requestAnimationFrame(r):u(!1)};requestAnimationFrame(r);return}K(t)}},[K]),{send:q,connect:J}=rt({url:e&&n?`/ws/project/${encodeURIComponent(n)}/chat/${e}`:``,onMessage:re,autoConnect:!!e&&!!n});M.current=q,(0,Q.useEffect)(()=>{let r=!1;return c(`idle`),A.current=`idle`,m(null),x(null),D.current=``,O.current=[],w(!1),I.current={teamNames:new Set,messages:[]},L.current=0,R(ft),B([]),e&&n?(o(!0),fetch(`${_(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{r||A.current!==`idle`||(e.ok&&Array.isArray(e.data)&&e.data.length>0?i(e.data):i([]))}).catch(()=>{!r&&A.current===`idle`&&i([])}).finally(()=>{r||o(!1)})):i([]),()=>{r=!0}},[e,t,n]);let Y=(0,Q.useCallback)((e,t)=>{if(!e.trim())return;let n=A.current!==`idle`;if(n){let e=D.current,t=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:t.length>0?t:r.events}]:n})}i(t=>[...t,{id:`user-${Date.now()}`,role:`user`,content:e,timestamp:new Date().toISOString()}]),D.current=``,O.current=[],j.current=null,n?(c(`thinking`),A.current=`thinking`):(c(`initializing`),A.current=`initializing`),m(null),q(JSON.stringify({type:`message`,content:e,permissionMode:t?.permissionMode,priority:t?.priority,images:t?.images}))},[q]),X=(0,Q.useCallback)((e,t,n)=>{if(q(JSON.stringify({type:`approval_response`,requestId:e,approved:t,data:n})),t&&n){let t=O.current.find(t=>t.type===`approval_request`&&t.requestId===e&&t.tool===`AskUserQuestion`);if(t){let e=t.input;e&&typeof e==`object`&&(e.answers=n)}i(e=>[...e])}m(null)},[q]),ie=(0,Q.useCallback)(()=>{if(A.current===`idle`)return;q(JSON.stringify({type:`cancel`}));let e=D.current,t=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:t.length>0?t:r.events}]:n}),D.current=``,O.current=[],j.current=null,c(`idle`),A.current=`idle`,m(null)},[q]),ae=(0,Q.useCallback)(()=>{w(!1),u(!0),J()},[J]),oe=(0,Q.useCallback)(()=>{!e||!n||(o(!0),fetch(`${_(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{e.ok&&Array.isArray(e.data)&&e.data.length>0&&(i(e.data),D.current=``,O.current=[])}).catch(()=>{}).finally(()=>o(!1)))},[e,t,n]);return N.current=oe,{messages:r,messagesLoading:a,isStreaming:U,phase:s,isReconnecting:l,connectingElapsed:d,pendingApproval:p,contextWindowPct:h,compactStatus:b,sessionTitle:ee,migratedSessionId:T,teamActivity:ne,teamMessages:z,markTeamRead:H,sendMessage:Y,respondToApproval:X,cancelStreaming:ie,reconnect:ae,refetchMessages:oe,isConnected:C}}var ht=12e4;function gt(e,t=`claude`){let[n,r]=(0,Q.useState)({}),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)(null),l=(0,Q.useCallback)((n=!1)=>{if(!e)return;a(!0);let i=n?`&refresh=1`:``;fetch(`${_(e)}/chat/usage?providerId=${t}${i}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{e.ok&&e.data&&(r(t=>({...t,...e.data})),e.data.lastFetchedAt&&s(e.data.lastFetchedAt))}).catch(()=>{}).finally(()=>a(!1))},[e,t]);return(0,Q.useEffect)(()=>(l(),c.current=setInterval(()=>l(),ht),()=>{c.current&&clearInterval(c.current)}),[l]),{usageInfo:n,usageLoading:i,lastFetchedAt:o,refreshUsage:(0,Q.useCallback)(()=>l(!0),[l])}}var _t={damping:.7,stiffness:.05,mass:1.25},vt=70,yt=1e3/60,bt=350,xt=!1;globalThis.document?.addEventListener(`mousedown`,()=>{xt=!0}),globalThis.document?.addEventListener(`mouseup`,()=>{xt=!1}),globalThis.document?.addEventListener(`click`,()=>{xt=!1});var St=(e={})=>{let[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(e.initial!==!1),[a,o]=(0,Q.useState)(!1),s=(0,Q.useRef)(null);s.current=e;let c=(0,Q.useCallback)(()=>{if(!xt)return!1;let e=window.getSelection();if(!e||!e.rangeCount)return!1;let t=e.getRangeAt(0);return t.commonAncestorContainer.contains(g.current)||g.current?.contains(t.commonAncestorContainer)},[]),l=(0,Q.useCallback)(e=>{d.isAtBottom=e,i(e)},[]),u=(0,Q.useCallback)(e=>{d.escapedFromLock=e,n(e)},[]),d=(0,Q.useMemo)(()=>{let n;return{escapedFromLock:t,isAtBottom:r,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return g.current?.scrollTop??0},set scrollTop(e){g.current&&(g.current.scrollTop=e,d.ignoreScrollToTop=g.current.scrollTop)},get targetScrollTop(){return!g.current||!_.current?0:g.current.scrollHeight-1-g.current.clientHeight},get calculatedTargetScrollTop(){if(!g.current||!_.current)return 0;let{targetScrollTop:t}=this;if(!e.targetScrollTop)return t;if(n?.targetScrollTop===t)return n.calculatedScrollTop;let r=Math.max(Math.min(e.targetScrollTop(t,{scrollElement:g.current,contentElement:_.current}),t),0);return n={targetScrollTop:t,calculatedScrollTop:r},requestAnimationFrame(()=>{n=void 0}),r},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=vt}}},[]),f=(0,Q.useCallback)((e={})=>{typeof e==`string`&&(e={animation:e}),e.preserveScrollPosition||l(!0);let t=Date.now()+(Number(e.wait)||0),n=Tt(s.current,e.animation),{ignoreEscapes:r=!1}=e,i,a=d.calculatedTargetScrollTop;e.duration instanceof Promise?e.duration.finally(()=>{i=Date.now()}):i=t+(e.duration??0);let o=async()=>{let e=new Promise(requestAnimationFrame).then(()=>{if(!d.isAtBottom)return d.animation=void 0,!1;let{scrollTop:l}=d,u=performance.now(),p=(u-(d.lastTick??u))/yt;if(d.animation||={behavior:n,promise:e,ignoreEscapes:r},d.animation.behavior===n&&(d.lastTick=u),c()||t>Date.now())return o();if(l<Math.min(a,d.calculatedTargetScrollTop)){if(d.animation?.behavior===n){if(n===`instant`)return d.scrollTop=d.calculatedTargetScrollTop,o();d.velocity=(n.damping*d.velocity+n.stiffness*d.scrollDifference)/n.mass,d.accumulated+=d.velocity*p,d.scrollTop+=d.accumulated,d.scrollTop!==l&&(d.accumulated=0)}return o()}return i>Date.now()?(a=d.calculatedTargetScrollTop,o()):(d.animation=void 0,d.scrollTop<d.calculatedTargetScrollTop?f({animation:Tt(s.current,s.current.resize),ignoreEscapes:r,duration:Math.max(0,i-Date.now())||void 0}):d.isAtBottom)});return e.then(e=>(requestAnimationFrame(()=>{d.animation||(d.lastTick=void 0,d.velocity=0)}),e))};return e.wait!==!0&&(d.animation=void 0),d.animation?.behavior===n?d.animation.promise:o()},[l,c,d]),p=(0,Q.useCallback)(()=>{u(!0),l(!1)},[u,l]),m=(0,Q.useCallback)(({target:e})=>{if(e!==g.current)return;let{scrollTop:t,ignoreScrollToTop:n}=d,{lastScrollTop:r=t}=d;d.lastScrollTop=t,d.ignoreScrollToTop=void 0,n&&n>t&&(r=n),o(d.isNearBottom),setTimeout(()=>{if(d.resizeDifference||t===n)return;if(c()){u(!0),l(!1);return}let e=t>r,i=t<r;if(d.animation?.ignoreEscapes){d.scrollTop=r;return}i&&(u(!0),l(!1)),e&&u(!1),!d.escapedFromLock&&d.isNearBottom&&l(!0)},1)},[u,l,c,d]),h=(0,Q.useCallback)(({target:e,deltaY:t})=>{let n=e;for(;![`scroll`,`auto`].includes(getComputedStyle(n).overflow);){if(!n.parentElement)return;n=n.parentElement}n===g.current&&t<0&&g.current.scrollHeight>g.current.clientHeight&&!d.animation?.ignoreEscapes&&(u(!0),l(!1))},[u,l,d]),g=Ct(e=>{g.current?.removeEventListener(`scroll`,m),g.current?.removeEventListener(`wheel`,h),e?.addEventListener(`scroll`,m,{passive:!0}),e?.addEventListener(`wheel`,h,{passive:!0})},[]),_=Ct(e=>{if(d.resizeObserver?.disconnect(),!e)return;let t;d.resizeObserver=new ResizeObserver(([e])=>{let{height:n}=e.contentRect,r=n-(t??n);if(d.resizeDifference=r,d.scrollTop>d.targetScrollTop&&(d.scrollTop=d.targetScrollTop),o(d.isNearBottom),r>=0){let e=Tt(s.current,t?s.current.resize:s.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:e===`instant`?void 0:bt})}else d.isNearBottom&&(u(!1),l(!0));t=n,requestAnimationFrame(()=>{setTimeout(()=>{d.resizeDifference===r&&(d.resizeDifference=0)},1)})}),d.resizeObserver?.observe(e)},[]);return{contentRef:_,scrollRef:g,scrollToBottom:f,stopScroll:p,isAtBottom:r||a,isNearBottom:a,escapedFromLock:t,state:d}};function Ct(e,t){let n=(0,Q.useCallback)(t=>(n.current=t,e(t)),t);return n}var wt=new Map;function Tt(...e){let t={..._t},n=!1;for(let r of e){if(r===`instant`){n=!0;continue}typeof r==`object`&&(n=!1,t.damping=r.damping??t.damping,t.stiffness=r.stiffness??t.stiffness,t.mass=r.mass??t.mass)}let r=JSON.stringify(t);return wt.has(r)||wt.set(r,Object.freeze(t)),n?`instant`:wt.get(r)}var Et=(0,Q.createContext)(null),Dt=typeof window<`u`?Q.useLayoutEffect:Q.useEffect;function Ot({instance:e,children:t,resize:n,initial:r,mass:i,damping:a,stiffness:o,targetScrollTop:s,contextRef:c,...l}){let u=(0,Q.useRef)(null),d=St({mass:i,damping:a,stiffness:o,resize:n,initial:r,targetScrollTop:Q.useCallback((e,t)=>(y?.targetScrollTop??s)?.(e,t)??e,[s])}),{scrollRef:f,contentRef:p,scrollToBottom:m,stopScroll:h,isAtBottom:g,escapedFromLock:_,state:v}=e??d,y=(0,Q.useMemo)(()=>({scrollToBottom:m,stopScroll:h,scrollRef:f,isAtBottom:g,escapedFromLock:_,contentRef:p,state:v,get targetScrollTop(){return u.current},set targetScrollTop(e){u.current=e}}),[m,g,p,f,h,_,v]);return(0,Q.useImperativeHandle)(c,()=>y,[y]),Dt(()=>{f.current&&getComputedStyle(f.current).overflow===`visible`&&(f.current.style.overflow=`auto`)},[]),Q.createElement(Et.Provider,{value:y},Q.createElement(`div`,{...l},typeof t==`function`?t(y):t))}(function(e){function t({children:e,scrollClassName:t,...n}){let r=kt();return Q.createElement(`div`,{ref:r.scrollRef,style:{height:`100%`,width:`100%`,scrollbarGutter:`stable both-edges`},className:t},Q.createElement(`div`,{...n,ref:r.contentRef},typeof e==`function`?e(r):e))}e.Content=t})(Ot||={});function kt(){let e=(0,Q.useContext)(Et);if(!e)throw Error(`use-stick-to-bottom component context must be used within a StickToBottom component`);return e}var $=p();function At(e){let t=e.type===`approval_request`;return{toolName:e.type===`tool_use`?e.tool:t?e.tool??`Tool`:`Tool`,input:e.type===`tool_use`?e.input:t?e.input??{}:{}}}function jt({tool:e,result:t,completed:n,projectName:r}){let[a,s]=(0,Q.useState)(!1);if(e.type===`error`)return(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded bg-red-500/10 border border-red-500/20 px-2 py-1.5 text-xs text-red-400`,children:[(0,$.jsx)(be,{className:`size-3`}),(0,$.jsx)(`span`,{children:e.message})]});let{toolName:c,input:l}=At(e),u=t?.type===`tool_result`,d=u&&!!t.isError,f=c===`AskUserQuestion`&&!!l?.answers,p=(c===`Agent`||c===`Task`)&&e.type===`tool_use`,m=p?e.children:void 0,h=m&&m.length>0;return(0,$.jsxs)(`div`,{className:`rounded border text-xs ${p?`border-accent/30 bg-accent/5`:`border-border bg-background`}`,children:[(0,$.jsxs)(`button`,{onClick:()=>s(!a),className:`flex items-center gap-2 px-2 py-1.5 w-full text-left hover:bg-surface transition-colors min-w-0`,children:[a?(0,$.jsx)(i,{className:`size-3 shrink-0`}):(0,$.jsx)(o,{className:`size-3 shrink-0`}),d?(0,$.jsx)(ze,{className:`size-3 text-red-400 shrink-0`}):u||f||n?(0,$.jsx)(P,{className:`size-3 text-green-400 shrink-0`}):(0,$.jsx)(Z,{className:`size-3 text-yellow-400 shrink-0 animate-spin`}),(0,$.jsx)(`span`,{className:`truncate text-text-primary`,children:(0,$.jsx)(Mt,{name:c,input:l})}),h&&(0,$.jsxs)(`span`,{className:`ml-auto text-[10px] text-text-subtle shrink-0`,children:[m.length,` steps`]})]}),a&&(0,$.jsxs)(`div`,{className:`px-2 pb-2 space-y-1.5`,children:[(e.type===`tool_use`||e.type===`approval_request`)&&(0,$.jsx)(Nt,{name:c,input:l,projectName:r}),h&&(0,$.jsx)(Lt,{events:m,projectName:r}),u&&(0,$.jsx)(Ft,{toolName:c,output:t.output})]})]})}function Mt({name:e,input:t}){let n=e=>String(e??``);switch(e){case`Read`:case`Write`:case`Edit`:case`MultiEdit`:case`NotebookEdit`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:g(n(t.file_path))})]});case`Bash`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:zt(n(t.command),60)})]});case`Glob`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:n(t.pattern)})]});case`Grep`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:zt(n(t.pattern),40)})]});case`WebSearch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ne,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.query),50)})]});case`WebFetch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ge,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.url),50)})]});case`ToolSearch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ne,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.query),50)})]});case`Agent`:case`Task`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(B,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.description||t.prompt),60)})]});case`TodoWrite`:{let n=Array.isArray(t.todos)?t.todos:[],r=n.filter(e=>e.status===`completed`).length;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ke,{className:`size-3 inline`}),` `,e,` `,(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[r,`/`,n.length,` done`]})]})}case`AskUserQuestion`:{let n=Array.isArray(t.questions)?t.questions:[],r=!!t.answers;return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[n.length,` question`,n.length===1?``:`s`,r?` ✓`:``]})]})}default:return(0,$.jsx)($.Fragment,{children:e})}}function Nt({name:e,input:t,projectName:n}){let r=e=>String(e??``),{openTab:i}=H(),a=e=>{n&&i({type:`editor`,title:g(e),metadata:{filePath:e,projectName:n},projectId:n,closable:!0})},o=(e,t,r)=>{i({type:`git-diff`,title:`Diff ${g(e)}`,metadata:{filePath:e,projectName:n,original:t,modified:r},projectId:n??null,closable:!0})};switch(e){case`Bash`:return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[!!t.description&&(0,$.jsx)(`p`,{className:`text-text-subtle italic`,children:r(t.description)}),(0,$.jsx)(`pre`,{className:`font-mono text-text-secondary overflow-x-auto whitespace-pre-wrap break-all`,children:r(t.command)})]});case`Read`:case`Write`:case`Edit`:case`MultiEdit`:case`NotebookEdit`:{let n=r(t.file_path);return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`font-mono text-text-secondary break-all hover:text-primary hover:underline text-left flex items-center gap-1`,onClick:()=>a(n),title:`Open file in editor`,children:[(0,$.jsx)(Le,{className:`size-3 shrink-0`}),n]}),e===`Edit`&&(!!t.old_string||!!t.new_string)&&(0,$.jsxs)(`button`,{type:`button`,className:`text-text-subtle hover:text-primary hover:underline text-left flex items-center gap-1`,onClick:()=>o(n,r(t.old_string),r(t.new_string)),title:`View diff in new tab`,children:[(0,$.jsx)(l,{className:`size-3 shrink-0`}),`View Diff`]}),e===`Write`&&!!t.content&&(0,$.jsx)(`pre`,{className:`font-mono text-text-subtle overflow-x-auto max-h-32 whitespace-pre-wrap`,children:zt(r(t.content),300)})]})}case`Glob`:return(0,$.jsxs)(`p`,{className:`font-mono text-text-secondary`,children:[r(t.pattern),t.path?` in ${r(t.path)}`:``]});case`Grep`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`p`,{className:`font-mono text-text-secondary`,children:[`/`,r(t.pattern),`/`]}),!!t.path&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`in `,r(t.path)]})]});case`TodoWrite`:return(0,$.jsx)(Pt,{todos:t.todos??[]});case`Agent`:case`Task`:return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[!!t.description&&(0,$.jsx)(`p`,{className:`text-text-secondary font-medium`,children:r(t.description)}),!!t.subagent_type&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`Type: `,r(t.subagent_type)]}),!!t.prompt&&(0,$.jsx)(Rt,{content:r(t.prompt),maxHeight:`max-h-48`})]});case`ToolSearch`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsx)(`p`,{className:`font-mono text-text-secondary`,children:r(t.query)}),!!t.max_results&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`Max results: `,r(t.max_results)]})]});case`WebFetch`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`a`,{href:r(t.url),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-primary hover:underline break-all flex items-center gap-1`,children:[(0,$.jsx)(ge,{className:`size-3 shrink-0`}),r(t.url)]}),!!t.prompt&&(0,$.jsx)(`p`,{className:`text-text-subtle`,children:zt(r(t.prompt),100)})]});case`AskUserQuestion`:{let e=t.questions??[],n=t.answers??{};return(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`p`,{className:`text-text-primary font-medium`,children:[e.header?`${e.header}: `:``,e.question]}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map((t,r)=>(0,$.jsx)(`span`,{className:`inline-block rounded px-1.5 py-0.5 text-xs border ${(n[e.question]??``).split(`, `).includes(t.label)?`border-accent bg-accent/20 text-text-primary`:`border-border text-text-subtle`}`,children:t.label},r))}),n[e.question]&&(0,$.jsxs)(`p`,{className:`text-foreground text-xs`,children:[`Answer: `,n[e.question]]})]},t))})}default:return(0,$.jsx)(`pre`,{className:`overflow-x-auto text-text-secondary font-mono whitespace-pre-wrap break-all`,children:JSON.stringify(t,null,2)})}}function Pt({todos:e}){return(0,$.jsx)(`div`,{className:`space-y-0.5`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5 ${e.status===`completed`?`text-green-400`:e.status===`in_progress`?`text-yellow-400`:`text-text-subtle`}`,children:e.status===`completed`?`✓`:e.status===`in_progress`?`▶`:`○`}),(0,$.jsx)(`span`,{className:e.status===`completed`?`line-through text-text-subtle`:`text-text-secondary`,children:e.content})]},t))})}function Ft({toolName:e,output:t}){let[n,r]=(0,Q.useState)(!1),i=(0,Q.useMemo)(()=>{if(e!==`Agent`&&e!==`Task`)return null;try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`&&e.text).map(e=>e.text).join(`
2
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import"./react-dom-Bpkvzu3U.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{t as r}from"./arrow-up-BYhx9ckd.js";import{n as i,t as a}from"./x-D2_KzIET.js";import{t as o}from"./chevron-right-4zq1jPv6.js";import{n as s,t as c}from"./markdown-renderer-BinWj98E.js";import{t as l}from"./columns-2-BoZAN-iw.js";import{t as u}from"./square-oPKIkJiw.js";import{t as d}from"./tag-CXMT0QB6.js";import{t as f}from"./preload-helper-Bf_JiD2A.js";import{t as p}from"./jsx-runtime-kMwlnEGE.js";import"./dist-DIV6WgAG.js";import{n as m,r as h,t as g}from"./utils-BNytJOb1.js";import{i as _,r as v,t as y}from"./api-client-BfBM3I7n.js";import{a as b,c as x,f as ee,g as S,i as C,l as w,m as T,o as E,p as D,r as O,s as k,t as A,u as j}from"./api-settings-Bn-bIxD1.js";import{$ as M,A as N,At as P,B as te,C as F,Ct as I,D as L,Dt as ne,E as R,Ft as z,It as B,J as V,K as H,Lt as U,M as W,Mt as G,O as K,Ot as re,Pt as q,Q as J,T as Y,Tt as X,Y as ie,Z as ae,_t as oe,bt as se,c as ce,ct as le,d as ue,dt as de,et as fe,f as pe,ft as me,h as he,ht as ge,i as _e,it as ve,j as ye,jt as be,k as xe,l as Se,m as Ce,nt as we,ot as Te,p as Ee,pt as Z,q as De,r as Oe,rt as ke,s as Ae,st as je,t as Me,tt as Ne,u as Pe,ut as Fe,vt as Ie,wt as Le}from"./index-Y-Kfye7A.js";import"./chunk-GEFDOKGD-D-pKjlVd.js";import"./src-BqX54PbV.js";import"./chunk-7R4GIKGN-Dv-4cAYn.js";import"./chunk-HHEYEP7N-C7vxA5i9.js";import"./dist-CSJdAyA9.js";import"./chunk-PU5JKC2W-ek7k4QVB.js";import"./chunk-MX3YWQON-BpS_PtKp.js";import"./chunk-YBOYWFTD-rQG3QH5s.js";import"./chunk-PQ6SQG4A-TF58UVMU.js";import"./chunk-KYZI473N-Bb0MCaIO.js";import"./chunk-O4XLMI2P-nDhi_cVu.js";import"./chunk-GLR3WWYH-DKikpoJM.js";import"./chunk-XPW4576I-BPQQBakK.js";var Re=n(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),ze=n(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),Be=n(`clipboard-check`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`m9 14 2 2 4-4`,key:`df797q`}]]),Ve=n(`clipboard-list`,[[`rect`,{width:`8`,height:`4`,x:`8`,y:`2`,rx:`1`,ry:`1`,key:`tgr4d6`}],[`path`,{d:`M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2`,key:`116196`}],[`path`,{d:`M12 11h4`,key:`1jrz19`}],[`path`,{d:`M12 16h4`,key:`n85exb`}],[`path`,{d:`M8 11h.01`,key:`1dfujw`}],[`path`,{d:`M8 16h.01`,key:`18s6g9`}]]),He=n(`hand`,[[`path`,{d:`M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2`,key:`1fvzgz`}],[`path`,{d:`M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2`,key:`1kc0my`}],[`path`,{d:`M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8`,key:`10h0bg`}],[`path`,{d:`M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15`,key:`1s1gnw`}]]),Ue=n(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),We=n(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Ge=n(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]),Ke=n(`list-todo`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`,key:`cif1o7`}]]),qe=n(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),Je=n(`mic-off`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`,key:`1gzdoj`}],[`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`,key:`cqa7eg`}],[`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`,key:`16hl24`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`,key:`r2i35w`}]]),Ye=n(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),Xe=n(`paperclip`,[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]),Ze=n(`settings-2`,[[`path`,{d:`M14 17H5`,key:`gfn3mx`}],[`path`,{d:`M19 7h-9`,key:`6i9tg`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}],[`circle`,{cx:`7`,cy:`7`,r:`3`,key:`dfmy0x`}]]),Qe=n(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),$e=n(`shield-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71`,key:`1jlk70`}],[`path`,{d:`M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264`,key:`18rp1v`}]]),et=n(`sparkles`,[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]]),tt=n(`users`,[[`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,key:`1yyitq`}],[`path`,{d:`M16 3.128a4 4 0 0 1 0 7.744`,key:`16gr8j`}],[`path`,{d:`M22 21v-2a4 4 0 0 0-3-3.87`,key:`kshegd`}],[`circle`,{cx:`9`,cy:`7`,r:`4`,key:`nufk8`}]]),nt=n(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),Q=e(t(),1);function rt({url:e,onMessage:t,autoConnect:n=!0}){let r=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let i=new Me(e);return r.current=i,t&&i.onMessage(t),n&&i.connect(),()=>{i.disconnect(),r.current=null}},[e,n]),{send:(0,Q.useCallback)(e=>{r.current?.send(e)},[]),connect:(0,Q.useCallback)(()=>{r.current?.connect()},[]),disconnect:(0,Q.useCallback)(()=>{r.current?.disconnect()},[])}}var it=null;function at(){return it||=new AudioContext,it}function ot(e,t,n,r,i=`sine`){let a=at(),o=a.createOscillator(),s=a.createGain();o.type=i,o.frequency.value=e,s.gain.setValueAtTime(r,n),s.gain.exponentialRampToValueAtTime(.001,n+t),o.connect(s),s.connect(a.destination),o.start(n),o.stop(n+t)}function st(){let e=at().currentTime;ot(523,.15,e,.15),ot(659,.2,e+.12,.15)}function ct(){let e=at().currentTime;ot(880,.12,e,.18,`square`),ot(698,.12,e+.15,.18,`square`),ot(880,.15,e+.3,.15,`square`)}function lt(){let e=at().currentTime;ot(440,.12,e,.12),ot(523,.12,e+.1,.12),ot(659,.18,e+.2,.12)}var ut={done:st,approval_request:ct,question:lt};function dt(e){try{ut[e]?.()}catch{}}var ft={hasTeams:!1,teamNames:[],messageCount:0,unreadCount:0};function pt(e){if(document.hidden)return!1;let{panels:t,focusedPanelId:n}=V.getState(),r=t[n];if(!r)return!1;let i=r.tabs.find(e=>e.id===r.activeTabId);return i?.type===`chat`&&i.metadata?.sessionId===e}function mt(e,t=`claude`,n=``){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(`idle`),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[ee,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(null),D=(0,Q.useRef)(``),O=(0,Q.useRef)([]),k=(0,Q.useRef)(null),A=(0,Q.useRef)(`idle`),j=(0,Q.useRef)(null),M=(0,Q.useRef)(()=>{}),N=(0,Q.useRef)(null),P=(0,Q.useRef)(e);P.current=e;let F=(0,Q.useRef)(n);F.current=n;let I=(0,Q.useRef)({teamNames:new Set,messages:[]}),L=(0,Q.useRef)(0),[ne,R]=(0,Q.useState)(ft),[z,B]=(0,Q.useState)([]),V=(0,Q.useCallback)(()=>{let e=I.current;R({hasTeams:e.teamNames.size>0,teamNames:Array.from(e.teamNames),messageCount:e.messages.length,unreadCount:L.current}),B([...e.messages])},[]),H=(0,Q.useCallback)(()=>{L.current=0,V()},[V]),U=s!==`idle`,W=(0,Q.useCallback)((e,t)=>{let n=O.current.findIndex(e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t);if(n===-1)return!1;let r=O.current[n];if(r.type!==`tool_use`)return!1;let i=[...r.children??[],e];return O.current[n]={...r,children:i},!0},[]),G=(0,Q.useCallback)(()=>{let e=D.current,t=[...O.current],n=k.current;i(r=>{let i=r[r.length-1];return i?.role===`assistant`&&!i.id.startsWith(`final-`)?[...r.slice(0,-1),{...i,content:e,events:t,...n}]:[...r,{id:`streaming-${Date.now()}`,role:`assistant`,content:e,events:t,timestamp:new Date().toISOString(),...n}]})},[]),K=(0,Q.useCallback)(e=>{let t=e,n=t?.type;if(n)switch(n){case`account_info`:k.current={accountId:t.accountId,accountLabel:t.accountLabel};break;case`account_retry`:t.accountId&&t.accountLabel&&(k.current={accountId:t.accountId,accountLabel:t.accountLabel}),O.current.push(t),G();break;case`status_update`:O.current.push(t),G();break;case`text`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}D.current+=t.content,O.current.push(t),G();break}case`thinking`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`tool_use`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`tool_result`:{let e=t.parentToolUseId;if(e&&W(t,e)){G();break}O.current.push(t),G();break}case`approval_request`:if(O.current.push(t),m({requestId:t.requestId,tool:t.tool,input:t.input}),P.current&&!pt(P.current)){let e=t.tool===`AskUserQuestion`?`question`:`approval_request`;te.getState().addNotification(P.current,e,F.current),dt(e)}break;case`error`:{O.current.push(t);let e=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,events:e}]:[...n,{id:`error-${Date.now()}`,role:`system`,content:t.message,events:[t],timestamp:new Date().toISOString()}]});break}case`team_detected`:{let e=t.teamName;e&&(I.current.teamNames.add(e),y.get(`/api/teams/${encodeURIComponent(e)}`).then(e=>{if(e?.messages){let t=I.current.messages,n=e.messages.filter(e=>!t.some(t=>t.timestamp===e.timestamp&&t.from===e.from));t.push(...n),t.sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())}V()}).catch(()=>{}),V());break}case`team_inbox`:{let e=t.messages;Array.isArray(e)&&(I.current.messages.push(...e),L.current+=e.length,V());break}case`team_updated`:V();break;case`done`:{if(A.current===`idle`)break;t.contextWindowPct!=null&&g(t.contextWindowPct),P.current&&!pt(P.current)&&(te.getState().addNotification(P.current,`done`,F.current),dt(`done`));let e=D.current,n=[...O.current];i(t=>{let r=t[t.length-1];return r?.role===`assistant`?[...t.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:n.length>0?n:r.events}]:t}),D.current=``,O.current=[],k.current=null;break}}},[W,G]),re=(0,Q.useCallback)(e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(t.type!==`ping`){if(t.type===`session_migrated`){let e=t.newSessionId;e&&E(e);return}if(t.type===`title_updated`){S(t.title??null);return}if(t.type===`compact_status`){let e=t.status;e===`compacting`?x(`compacting`):e===`done`&&(x(null),N.current?.());return}if(t.type===`phase_changed`){let e=t.phase;c(e),A.current=e,f(e===`connecting`?t.elapsed??0:0);return}if(t.type===`session_state`){w(!0);let e=t,n=e.phase;c(n),A.current=n,e.sessionTitle&&S(e.sessionTitle),e.pendingApproval&&m({requestId:e.pendingApproval.requestId,tool:e.pendingApproval.tool,input:e.pendingApproval.input}),n===`idle`&&(N.current?.(),u(!1));return}if(t.type===`turn_events`){let e=t.events;if(!e?.length){u(!1);return}i(e=>{let t=e.findLastIndex(e=>e.role===`user`);return t>=0?e.slice(0,t+1):e}),D.current=``,O.current=[],k.current=null;let n=0,r=()=>{let t=Math.min(n+100,e.length);for(let r=n;r<t;r++)K(e[r]);n=t,n<e.length?requestAnimationFrame(r):u(!1)};requestAnimationFrame(r);return}K(t)}},[K]),{send:q,connect:J}=rt({url:e&&n?`/ws/project/${encodeURIComponent(n)}/chat/${e}`:``,onMessage:re,autoConnect:!!e&&!!n});M.current=q,(0,Q.useEffect)(()=>{let r=!1;return c(`idle`),A.current=`idle`,m(null),x(null),D.current=``,O.current=[],w(!1),I.current={teamNames:new Set,messages:[]},L.current=0,R(ft),B([]),e&&n?(o(!0),fetch(`${_(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{r||A.current!==`idle`||(e.ok&&Array.isArray(e.data)&&e.data.length>0?i(e.data):i([]))}).catch(()=>{!r&&A.current===`idle`&&i([])}).finally(()=>{r||o(!1)})):i([]),()=>{r=!0}},[e,t,n]);let Y=(0,Q.useCallback)((e,t)=>{if(!e.trim())return;let n=A.current!==`idle`;if(n){let e=D.current,t=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:t.length>0?t:r.events}]:n})}i(t=>[...t,{id:`user-${Date.now()}`,role:`user`,content:e,timestamp:new Date().toISOString()}]),D.current=``,O.current=[],j.current=null,n?(c(`thinking`),A.current=`thinking`):(c(`initializing`),A.current=`initializing`),m(null),q(JSON.stringify({type:`message`,content:e,permissionMode:t?.permissionMode,priority:t?.priority,images:t?.images}))},[q]),X=(0,Q.useCallback)((e,t,n)=>{if(q(JSON.stringify({type:`approval_response`,requestId:e,approved:t,data:n})),t&&n){let t=O.current.find(t=>t.type===`approval_request`&&t.requestId===e&&t.tool===`AskUserQuestion`);if(t){let e=t.input;e&&typeof e==`object`&&(e.answers=n)}i(e=>[...e])}m(null)},[q]),ie=(0,Q.useCallback)(()=>{if(A.current===`idle`)return;q(JSON.stringify({type:`cancel`}));let e=D.current,t=[...O.current];i(n=>{let r=n[n.length-1];return r?.role===`assistant`?[...n.slice(0,-1),{...r,id:`final-${Date.now()}`,content:e||r.content,events:t.length>0?t:r.events}]:n}),D.current=``,O.current=[],j.current=null,c(`idle`),A.current=`idle`,m(null)},[q]),ae=(0,Q.useCallback)(()=>{w(!1),u(!0),J()},[J]),oe=(0,Q.useCallback)(()=>{!e||!n||(o(!0),fetch(`${_(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{e.ok&&Array.isArray(e.data)&&e.data.length>0&&(i(e.data),D.current=``,O.current=[])}).catch(()=>{}).finally(()=>o(!1)))},[e,t,n]);return N.current=oe,{messages:r,messagesLoading:a,isStreaming:U,phase:s,isReconnecting:l,connectingElapsed:d,pendingApproval:p,contextWindowPct:h,compactStatus:b,sessionTitle:ee,migratedSessionId:T,teamActivity:ne,teamMessages:z,markTeamRead:H,sendMessage:Y,respondToApproval:X,cancelStreaming:ie,reconnect:ae,refetchMessages:oe,isConnected:C}}var ht=12e4;function gt(e,t=`claude`){let[n,r]=(0,Q.useState)({}),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)(null),l=(0,Q.useCallback)((n=!1)=>{if(!e)return;a(!0);let i=n?`&refresh=1`:``;fetch(`${_(e)}/chat/usage?providerId=${t}${i}`,{headers:{Authorization:`Bearer ${v()}`}}).then(e=>e.json()).then(e=>{e.ok&&e.data&&(r(t=>({...t,...e.data})),e.data.lastFetchedAt&&s(e.data.lastFetchedAt))}).catch(()=>{}).finally(()=>a(!1))},[e,t]);return(0,Q.useEffect)(()=>(l(),c.current=setInterval(()=>l(),ht),()=>{c.current&&clearInterval(c.current)}),[l]),{usageInfo:n,usageLoading:i,lastFetchedAt:o,refreshUsage:(0,Q.useCallback)(()=>l(!0),[l])}}var _t={damping:.7,stiffness:.05,mass:1.25},vt=70,yt=1e3/60,bt=350,xt=!1;globalThis.document?.addEventListener(`mousedown`,()=>{xt=!0}),globalThis.document?.addEventListener(`mouseup`,()=>{xt=!1}),globalThis.document?.addEventListener(`click`,()=>{xt=!1});var St=(e={})=>{let[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(e.initial!==!1),[a,o]=(0,Q.useState)(!1),s=(0,Q.useRef)(null);s.current=e;let c=(0,Q.useCallback)(()=>{if(!xt)return!1;let e=window.getSelection();if(!e||!e.rangeCount)return!1;let t=e.getRangeAt(0);return t.commonAncestorContainer.contains(g.current)||g.current?.contains(t.commonAncestorContainer)},[]),l=(0,Q.useCallback)(e=>{d.isAtBottom=e,i(e)},[]),u=(0,Q.useCallback)(e=>{d.escapedFromLock=e,n(e)},[]),d=(0,Q.useMemo)(()=>{let n;return{escapedFromLock:t,isAtBottom:r,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return g.current?.scrollTop??0},set scrollTop(e){g.current&&(g.current.scrollTop=e,d.ignoreScrollToTop=g.current.scrollTop)},get targetScrollTop(){return!g.current||!_.current?0:g.current.scrollHeight-1-g.current.clientHeight},get calculatedTargetScrollTop(){if(!g.current||!_.current)return 0;let{targetScrollTop:t}=this;if(!e.targetScrollTop)return t;if(n?.targetScrollTop===t)return n.calculatedScrollTop;let r=Math.max(Math.min(e.targetScrollTop(t,{scrollElement:g.current,contentElement:_.current}),t),0);return n={targetScrollTop:t,calculatedScrollTop:r},requestAnimationFrame(()=>{n=void 0}),r},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=vt}}},[]),f=(0,Q.useCallback)((e={})=>{typeof e==`string`&&(e={animation:e}),e.preserveScrollPosition||l(!0);let t=Date.now()+(Number(e.wait)||0),n=Tt(s.current,e.animation),{ignoreEscapes:r=!1}=e,i,a=d.calculatedTargetScrollTop;e.duration instanceof Promise?e.duration.finally(()=>{i=Date.now()}):i=t+(e.duration??0);let o=async()=>{let e=new Promise(requestAnimationFrame).then(()=>{if(!d.isAtBottom)return d.animation=void 0,!1;let{scrollTop:l}=d,u=performance.now(),p=(u-(d.lastTick??u))/yt;if(d.animation||={behavior:n,promise:e,ignoreEscapes:r},d.animation.behavior===n&&(d.lastTick=u),c()||t>Date.now())return o();if(l<Math.min(a,d.calculatedTargetScrollTop)){if(d.animation?.behavior===n){if(n===`instant`)return d.scrollTop=d.calculatedTargetScrollTop,o();d.velocity=(n.damping*d.velocity+n.stiffness*d.scrollDifference)/n.mass,d.accumulated+=d.velocity*p,d.scrollTop+=d.accumulated,d.scrollTop!==l&&(d.accumulated=0)}return o()}return i>Date.now()?(a=d.calculatedTargetScrollTop,o()):(d.animation=void 0,d.scrollTop<d.calculatedTargetScrollTop?f({animation:Tt(s.current,s.current.resize),ignoreEscapes:r,duration:Math.max(0,i-Date.now())||void 0}):d.isAtBottom)});return e.then(e=>(requestAnimationFrame(()=>{d.animation||(d.lastTick=void 0,d.velocity=0)}),e))};return e.wait!==!0&&(d.animation=void 0),d.animation?.behavior===n?d.animation.promise:o()},[l,c,d]),p=(0,Q.useCallback)(()=>{u(!0),l(!1)},[u,l]),m=(0,Q.useCallback)(({target:e})=>{if(e!==g.current)return;let{scrollTop:t,ignoreScrollToTop:n}=d,{lastScrollTop:r=t}=d;d.lastScrollTop=t,d.ignoreScrollToTop=void 0,n&&n>t&&(r=n),o(d.isNearBottom),setTimeout(()=>{if(d.resizeDifference||t===n)return;if(c()){u(!0),l(!1);return}let e=t>r,i=t<r;if(d.animation?.ignoreEscapes){d.scrollTop=r;return}i&&(u(!0),l(!1)),e&&u(!1),!d.escapedFromLock&&d.isNearBottom&&l(!0)},1)},[u,l,c,d]),h=(0,Q.useCallback)(({target:e,deltaY:t})=>{let n=e;for(;![`scroll`,`auto`].includes(getComputedStyle(n).overflow);){if(!n.parentElement)return;n=n.parentElement}n===g.current&&t<0&&g.current.scrollHeight>g.current.clientHeight&&!d.animation?.ignoreEscapes&&(u(!0),l(!1))},[u,l,d]),g=Ct(e=>{g.current?.removeEventListener(`scroll`,m),g.current?.removeEventListener(`wheel`,h),e?.addEventListener(`scroll`,m,{passive:!0}),e?.addEventListener(`wheel`,h,{passive:!0})},[]),_=Ct(e=>{if(d.resizeObserver?.disconnect(),!e)return;let t;d.resizeObserver=new ResizeObserver(([e])=>{let{height:n}=e.contentRect,r=n-(t??n);if(d.resizeDifference=r,d.scrollTop>d.targetScrollTop&&(d.scrollTop=d.targetScrollTop),o(d.isNearBottom),r>=0){let e=Tt(s.current,t?s.current.resize:s.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:e===`instant`?void 0:bt})}else d.isNearBottom&&(u(!1),l(!0));t=n,requestAnimationFrame(()=>{setTimeout(()=>{d.resizeDifference===r&&(d.resizeDifference=0)},1)})}),d.resizeObserver?.observe(e)},[]);return{contentRef:_,scrollRef:g,scrollToBottom:f,stopScroll:p,isAtBottom:r||a,isNearBottom:a,escapedFromLock:t,state:d}};function Ct(e,t){let n=(0,Q.useCallback)(t=>(n.current=t,e(t)),t);return n}var wt=new Map;function Tt(...e){let t={..._t},n=!1;for(let r of e){if(r===`instant`){n=!0;continue}typeof r==`object`&&(n=!1,t.damping=r.damping??t.damping,t.stiffness=r.stiffness??t.stiffness,t.mass=r.mass??t.mass)}let r=JSON.stringify(t);return wt.has(r)||wt.set(r,Object.freeze(t)),n?`instant`:wt.get(r)}var Et=(0,Q.createContext)(null),Dt=typeof window<`u`?Q.useLayoutEffect:Q.useEffect;function Ot({instance:e,children:t,resize:n,initial:r,mass:i,damping:a,stiffness:o,targetScrollTop:s,contextRef:c,...l}){let u=(0,Q.useRef)(null),d=St({mass:i,damping:a,stiffness:o,resize:n,initial:r,targetScrollTop:Q.useCallback((e,t)=>(y?.targetScrollTop??s)?.(e,t)??e,[s])}),{scrollRef:f,contentRef:p,scrollToBottom:m,stopScroll:h,isAtBottom:g,escapedFromLock:_,state:v}=e??d,y=(0,Q.useMemo)(()=>({scrollToBottom:m,stopScroll:h,scrollRef:f,isAtBottom:g,escapedFromLock:_,contentRef:p,state:v,get targetScrollTop(){return u.current},set targetScrollTop(e){u.current=e}}),[m,g,p,f,h,_,v]);return(0,Q.useImperativeHandle)(c,()=>y,[y]),Dt(()=>{f.current&&getComputedStyle(f.current).overflow===`visible`&&(f.current.style.overflow=`auto`)},[]),Q.createElement(Et.Provider,{value:y},Q.createElement(`div`,{...l},typeof t==`function`?t(y):t))}(function(e){function t({children:e,scrollClassName:t,...n}){let r=kt();return Q.createElement(`div`,{ref:r.scrollRef,style:{height:`100%`,width:`100%`,scrollbarGutter:`stable both-edges`},className:t},Q.createElement(`div`,{...n,ref:r.contentRef},typeof e==`function`?e(r):e))}e.Content=t})(Ot||={});function kt(){let e=(0,Q.useContext)(Et);if(!e)throw Error(`use-stick-to-bottom component context must be used within a StickToBottom component`);return e}var $=p();function At(e){let t=e.type===`approval_request`;return{toolName:e.type===`tool_use`?e.tool:t?e.tool??`Tool`:`Tool`,input:e.type===`tool_use`?e.input:t?e.input??{}:{}}}function jt({tool:e,result:t,completed:n,projectName:r}){let[a,s]=(0,Q.useState)(!1);if(e.type===`error`)return(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded bg-red-500/10 border border-red-500/20 px-2 py-1.5 text-xs text-red-400`,children:[(0,$.jsx)(be,{className:`size-3`}),(0,$.jsx)(`span`,{children:e.message})]});let{toolName:c,input:l}=At(e),u=t?.type===`tool_result`,d=u&&!!t.isError,f=c===`AskUserQuestion`&&!!l?.answers,p=(c===`Agent`||c===`Task`)&&e.type===`tool_use`,m=p?e.children:void 0,h=m&&m.length>0;return(0,$.jsxs)(`div`,{className:`rounded border text-xs ${p?`border-accent/30 bg-accent/5`:`border-border bg-background`}`,children:[(0,$.jsxs)(`button`,{onClick:()=>s(!a),className:`flex items-center gap-2 px-2 py-1.5 w-full text-left hover:bg-surface transition-colors min-w-0`,children:[a?(0,$.jsx)(i,{className:`size-3 shrink-0`}):(0,$.jsx)(o,{className:`size-3 shrink-0`}),d?(0,$.jsx)(ze,{className:`size-3 text-red-400 shrink-0`}):u||f||n?(0,$.jsx)(P,{className:`size-3 text-green-400 shrink-0`}):(0,$.jsx)(Z,{className:`size-3 text-yellow-400 shrink-0 animate-spin`}),(0,$.jsx)(`span`,{className:`truncate text-text-primary`,children:(0,$.jsx)(Mt,{name:c,input:l})}),h&&(0,$.jsxs)(`span`,{className:`ml-auto text-[10px] text-text-subtle shrink-0`,children:[m.length,` steps`]})]}),a&&(0,$.jsxs)(`div`,{className:`px-2 pb-2 space-y-1.5`,children:[(e.type===`tool_use`||e.type===`approval_request`)&&(0,$.jsx)(Nt,{name:c,input:l,projectName:r}),h&&(0,$.jsx)(Lt,{events:m,projectName:r}),u&&(0,$.jsx)(Ft,{toolName:c,output:t.output})]})]})}function Mt({name:e,input:t}){let n=e=>String(e??``);switch(e){case`Read`:case`Write`:case`Edit`:case`MultiEdit`:case`NotebookEdit`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:g(n(t.file_path))})]});case`Bash`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:zt(n(t.command),60)})]});case`Glob`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:n(t.pattern)})]});case`Grep`:return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsx)(`span`,{className:`font-mono text-text-subtle`,children:zt(n(t.pattern),40)})]});case`WebSearch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ne,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.query),50)})]});case`WebFetch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ge,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.url),50)})]});case`ToolSearch`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ne,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.query),50)})]});case`Agent`:case`Task`:return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(B,{className:`size-3 inline`}),` `,e,` `,(0,$.jsx)(`span`,{className:`text-text-subtle`,children:zt(n(t.description||t.prompt),60)})]});case`TodoWrite`:{let n=Array.isArray(t.todos)?t.todos:[],r=n.filter(e=>e.status===`completed`).length;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ke,{className:`size-3 inline`}),` `,e,` `,(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[r,`/`,n.length,` done`]})]})}case`AskUserQuestion`:{let n=Array.isArray(t.questions)?t.questions:[],r=!!t.answers;return(0,$.jsxs)($.Fragment,{children:[e,` `,(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[n.length,` question`,n.length===1?``:`s`,r?` ✓`:``]})]})}default:return(0,$.jsx)($.Fragment,{children:e})}}function Nt({name:e,input:t,projectName:n}){let r=e=>String(e??``),{openTab:i}=H(),a=e=>{n&&i({type:`editor`,title:g(e),metadata:{filePath:e,projectName:n},projectId:n,closable:!0})},o=(e,t,r)=>{i({type:`git-diff`,title:`Diff ${g(e)}`,metadata:{filePath:e,projectName:n,original:t,modified:r},projectId:n??null,closable:!0})};switch(e){case`Bash`:return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[!!t.description&&(0,$.jsx)(`p`,{className:`text-text-subtle italic`,children:r(t.description)}),(0,$.jsx)(`pre`,{className:`font-mono text-text-secondary overflow-x-auto whitespace-pre-wrap break-all`,children:r(t.command)})]});case`Read`:case`Write`:case`Edit`:case`MultiEdit`:case`NotebookEdit`:{let n=r(t.file_path);return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`font-mono text-text-secondary break-all hover:text-primary hover:underline text-left flex items-center gap-1`,onClick:()=>a(n),title:`Open file in editor`,children:[(0,$.jsx)(Le,{className:`size-3 shrink-0`}),n]}),e===`Edit`&&(!!t.old_string||!!t.new_string)&&(0,$.jsxs)(`button`,{type:`button`,className:`text-text-subtle hover:text-primary hover:underline text-left flex items-center gap-1`,onClick:()=>o(n,r(t.old_string),r(t.new_string)),title:`View diff in new tab`,children:[(0,$.jsx)(l,{className:`size-3 shrink-0`}),`View Diff`]}),e===`Write`&&!!t.content&&(0,$.jsx)(`pre`,{className:`font-mono text-text-subtle overflow-x-auto max-h-32 whitespace-pre-wrap`,children:zt(r(t.content),300)})]})}case`Glob`:return(0,$.jsxs)(`p`,{className:`font-mono text-text-secondary`,children:[r(t.pattern),t.path?` in ${r(t.path)}`:``]});case`Grep`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`p`,{className:`font-mono text-text-secondary`,children:[`/`,r(t.pattern),`/`]}),!!t.path&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`in `,r(t.path)]})]});case`TodoWrite`:return(0,$.jsx)(Pt,{todos:t.todos??[]});case`Agent`:case`Task`:return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[!!t.description&&(0,$.jsx)(`p`,{className:`text-text-secondary font-medium`,children:r(t.description)}),!!t.subagent_type&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`Type: `,r(t.subagent_type)]}),!!t.prompt&&(0,$.jsx)(Rt,{content:r(t.prompt),maxHeight:`max-h-48`})]});case`ToolSearch`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsx)(`p`,{className:`font-mono text-text-secondary`,children:r(t.query)}),!!t.max_results&&(0,$.jsxs)(`p`,{className:`text-text-subtle`,children:[`Max results: `,r(t.max_results)]})]});case`WebFetch`:return(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`a`,{href:r(t.url),target:`_blank`,rel:`noopener noreferrer`,className:`font-mono text-primary hover:underline break-all flex items-center gap-1`,children:[(0,$.jsx)(ge,{className:`size-3 shrink-0`}),r(t.url)]}),!!t.prompt&&(0,$.jsx)(`p`,{className:`text-text-subtle`,children:zt(r(t.prompt),100)})]});case`AskUserQuestion`:{let e=t.questions??[],n=t.answers??{};return(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`p`,{className:`text-text-primary font-medium`,children:[e.header?`${e.header}: `:``,e.question]}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map((t,r)=>(0,$.jsx)(`span`,{className:`inline-block rounded px-1.5 py-0.5 text-xs border ${(n[e.question]??``).split(`, `).includes(t.label)?`border-accent bg-accent/20 text-text-primary`:`border-border text-text-subtle`}`,children:t.label},r))}),n[e.question]&&(0,$.jsxs)(`p`,{className:`text-foreground text-xs`,children:[`Answer: `,n[e.question]]})]},t))})}default:return(0,$.jsx)(`pre`,{className:`overflow-x-auto text-text-secondary font-mono whitespace-pre-wrap break-all`,children:JSON.stringify(t,null,2)})}}function Pt({todos:e}){return(0,$.jsx)(`div`,{className:`space-y-0.5`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5 ${e.status===`completed`?`text-green-400`:e.status===`in_progress`?`text-yellow-400`:`text-text-subtle`}`,children:e.status===`completed`?`✓`:e.status===`in_progress`?`▶`:`○`}),(0,$.jsx)(`span`,{className:e.status===`completed`?`line-through text-text-subtle`:`text-text-secondary`,children:e.content})]},t))})}function Ft({toolName:e,output:t}){let[n,r]=(0,Q.useState)(!1),i=(0,Q.useMemo)(()=>{if(e!==`Agent`&&e!==`Task`)return null;try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`&&e.text).map(e=>e.text).join(`
3
3
 
4
4
  `);if(t)return t}if(typeof e==`string`)return e}catch{if(t&&!t.startsWith(`[{`))return t}return null},[e,t]);return i?(0,$.jsxs)(`div`,{className:`border-t border-border pt-1.5 space-y-1`,children:[(0,$.jsx)(Rt,{content:i,maxHeight:`max-h-60`}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(!n),className:`flex items-center gap-1 text-[10px] text-text-subtle hover:text-text-secondary transition-colors`,children:[(0,$.jsx)(s,{className:`size-3`}),n?`Hide`:`Show`,` raw`]}),n&&(0,$.jsx)(`pre`,{className:`overflow-x-auto text-text-subtle font-mono max-h-40 whitespace-pre-wrap break-all text-[10px]`,children:t})]}):(0,$.jsx)(It,{output:t})}function It({output:e}){let t=e.split(`
5
5
  `).length,n=t>3||e.length>200,[r,a]=(0,Q.useState)(n);return(0,$.jsxs)(`div`,{className:`border-t border-border pt-1.5`,children:[n&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>a(!r),className:`flex items-center gap-1 text-[10px] text-text-subtle hover:text-text-secondary transition-colors mb-1`,children:[r?(0,$.jsx)(o,{className:`size-3`}):(0,$.jsx)(i,{className:`size-3`}),`Output (`,t,` lines)`]}),(0,$.jsx)(`pre`,{className:`overflow-x-auto text-text-subtle font-mono whitespace-pre-wrap break-all ${r?`max-h-16 overflow-hidden`:`max-h-60`}`,children:e})]})}function Lt({events:e,projectName:t}){let n=[],r=``;for(let t of e)if(t.type===`text`)r+=t.content;else if(t.type===`tool_use`)r&&=(n.push({kind:`text`,content:r}),``),n.push({kind:`tool`,tool:t});else if(t.type===`tool_result`){let e=t.toolUseId,r=e?n.find(t=>t.kind===`tool`&&t.tool.type===`tool_use`&&t.tool.toolUseId===e&&!t.result):n.findLast(e=>e.kind===`tool`&&!e.result);r&&(r.result=t)}return r&&n.push({kind:`text`,content:r}),(0,$.jsx)(`div`,{className:`border-l-2 border-accent/20 pl-2 space-y-1 mt-1`,children:n.map((e,n)=>e.kind===`text`?(0,$.jsx)(`div`,{className:`text-text-secondary text-[11px]`,children:(0,$.jsx)(Rt,{content:e.content,maxHeight:`max-h-24`})},`st-${n}`):(0,$.jsx)(jt,{tool:e.tool,result:e.result,completed:!!e.result,projectName:t},`sc-${n}`))})}function Rt({content:e,maxHeight:t=`max-h-48`}){return(0,$.jsx)(c,{content:e,className:`text-text-secondary overflow-auto ${t}`})}function zt(e,t=50){return e?e.length>t?e.slice(0,t)+`…`:e:``}var Bt=5,Vt=20;function Ht(e){try{let t=new Date(e),n=new Date().getTime()-t.getTime(),r=Math.floor(n/6e4);if(r<1)return`just now`;if(r<60)return`${r}m ago`;let i=Math.floor(r/60);if(i<24)return`${i}h ago`;let a=Math.floor(i/24);return a<7?`${a}d ago`:t.toLocaleDateString(void 0,{month:`short`,day:`numeric`})}catch{return``}}function Ut({projectName:e,onSelectSession:t}){let[n,r]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),l=(0,Q.useCallback)(async()=>{if(e){o(!0);try{r((await y.get(`${_(e)}/chat/sessions?limit=${Vt}`)).sessions.slice(0,Vt))}catch{}finally{o(!1)}}},[e]);(0,Q.useEffect)(()=>{l()},[l]);let u=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),!e)return;let i=`${_(e)}/chat/sessions/${n.id}/pin`;try{n.pinned?await y.del(i):await y.put(i),r(e=>e.map(e=>e.id===n.id?{...e,pinned:!e.pinned}:e).sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()))}catch{}},[e]),d=n.filter(e=>e.pinned),f=n.filter(e=>!e.pinned),p=s?f:f.slice(0,Bt),m=f.length>Bt;function h(e){return(0,$.jsxs)(`button`,{onClick:()=>t(e),className:`group flex items-center gap-2.5 w-full px-3 py-2.5 text-left hover:bg-surface-elevated active:bg-surface-elevated transition-colors border-b border-border/50 last:border-0`,children:[(0,$.jsx)(de,{className:`size-3.5 shrink-0 text-text-subtle`}),(0,$.jsx)(`span`,{className:`flex-1 min-w-0 text-xs font-medium truncate text-text-primary`,children:e.title||`Untitled`}),e.updatedAt&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0`,children:Ht(e.updatedAt)}),(0,$.jsx)(`span`,{role:`button`,tabIndex:0,onClick:t=>u(t,e),className:`p-1 rounded transition-colors shrink-0 ${e.pinned?`text-primary hover:text-primary/70`:`text-text-subtle can-hover:opacity-0 can-hover:group-hover:opacity-100 hover:text-text-primary`}`,"aria-label":e.pinned?`Unpin session`:`Pin session`,children:e.pinned?(0,$.jsx)(je,{className:`size-3`}):(0,$.jsx)(Te,{className:`size-3`})})]},e.id)}return(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-6 text-text-secondary overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-3`,children:[(0,$.jsx)(B,{className:`size-10 text-text-subtle`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Send a message to start a new conversation`})]}),!a&&d.length>0&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 w-full max-w-sm px-4`,children:[(0,$.jsx)(`p`,{className:`text-xs text-text-subtle text-center`,children:`Pinned`}),(0,$.jsx)(`div`,{className:`w-full rounded-md border border-border bg-surface overflow-hidden`,children:d.map(h)})]}),!a&&p.length>0&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 w-full max-w-sm px-4`,children:[(0,$.jsx)(`p`,{className:`text-xs text-text-subtle text-center`,children:`Recent chats`}),(0,$.jsx)(`div`,{className:`w-full rounded-md border border-border bg-surface overflow-hidden`,children:p.map(h)}),m&&(0,$.jsxs)(`button`,{onClick:()=>c(!s),className:`flex items-center justify-center gap-1 text-[11px] text-text-subtle hover:text-text-primary transition-colors py-1`,children:[s?(0,$.jsx)(G,{className:`size-3`}):(0,$.jsx)(i,{className:`size-3`}),s?`Show less`:`Show more (${f.length-Bt})`]})]})]})}function Wt(e){let[t,n]=(0,Q.useState)({}),[r,i]=(0,Q.useState)({}),[a,o]=(0,Q.useState)(0),s=(0,Q.useCallback)((e,t)=>{n(n=>({...n,[e]:[t]})),i(t=>({...t,[e]:``}))},[]),c=(0,Q.useCallback)((e,t)=>{n(n=>{let r=n[e]||[];return{...n,[e]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}})},[]),l=(0,Q.useCallback)((e,t)=>{i(n=>({...n,[e]:t})),t&&n(t=>({...t,[e]:[]}))},[]),u=(0,Q.useCallback)(e=>(t[e]?.length??0)>0||(r[e]?.trim().length??0)>0,[t,r]);return{answers:t,customInputs:r,activeTab:a,setActiveTab:o,handleSingleSelect:s,handleMultiSelect:c,handleCustomInput:l,hasAnswer:u,allAnswered:(0,Q.useMemo)(()=>e.every((e,t)=>u(t)),[e,u]),getFinalAnswer:(0,Q.useCallback)(e=>r[e]?.trim()||(t[e]??[]).join(`, `),[t,r]),goToNextTab:(0,Q.useCallback)(()=>o(t=>Math.min(t+1,e.length-1)),[e.length]),goToPrevTab:(0,Q.useCallback)(()=>o(e=>Math.max(e-1,0)),[])}}function Gt(e){let[t,n]=(0,Q.useState)(0),r=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>n(0),[e.activeTab]),(0,Q.useEffect)(()=>{if(!e.enabled)return;let i=r=>{let i=document.activeElement===e.customInputRef.current;if(!i&&r.key>=`1`&&r.key<=`9`){r.preventDefault();let t=parseInt(r.key)-1;t<e.totalOptions-1&&(n(t),e.onSelectOption(t));return}if(!i&&(r.key===`o`||r.key===`O`||r.key===`0`)){r.preventDefault(),e.customInputRef.current?.focus(),n(e.totalOptions-1);return}if(r.key===`Tab`&&e.questions.length>1){r.preventDefault(),r.shiftKey?e.goToPrevTab():e.goToNextTab();return}if(!i){if(r.key===`ArrowLeft`){r.preventDefault(),e.goToPrevTab();return}if(r.key===`ArrowRight`){r.preventDefault(),e.goToNextTab();return}if(r.key===`ArrowUp`){r.preventDefault(),n(e=>Math.max(0,e-1));return}if(r.key===`ArrowDown`){r.preventDefault(),n(t=>Math.min(e.totalOptions-1,t+1));return}if(r.key===` `){r.preventDefault(),e.onSelectOption(t);return}}if(r.key===`Enter`){r.preventDefault(),e.allAnswered?e.onSubmit():e.hasAnswer(e.activeTab)&&e.goToNextTab();return}r.key===`Escape`&&i&&e.customInputRef.current?.blur()},a=r.current;return a&&(a.addEventListener(`keydown`,i),a.setAttribute(`tabindex`,`0`),a.contains(document.activeElement)||a.focus()),()=>{a?.removeEventListener(`keydown`,i)}},[e,t]),{focusedOption:t,setFocusedOption:n,containerRef:r}}function Kt({questions:e,onSubmit:t,onSkip:n}){let r=(0,Q.useRef)(null),i=Wt(e),a=e[i.activeTab],o=a?a.options.length+1:0,s=e.length>1,c=(0,Q.useCallback)(()=>{if(!i.allAnswered)return;let n={};e.forEach((e,t)=>{n[e.question]=i.getFinalAnswer(t)}),t(n)},[i.allAnswered,i.getFinalAnswer,e,t]),l=(0,Q.useCallback)(e=>{if(!(!a||e<0))if(e<a.options.length){let t=a.options[e]?.label;if(!t)return;a.multiSelect?i.handleMultiSelect(i.activeTab,t):i.handleSingleSelect(i.activeTab,t)}else e===a.options.length&&r.current?.focus()},[a,i]),u=Gt({questions:e,activeTab:i.activeTab,totalOptions:o,allAnswered:i.allAnswered,hasAnswer:i.hasAnswer,onSelectOption:l,goToNextTab:i.goToNextTab,goToPrevTab:i.goToPrevTab,onSubmit:c,customInputRef:r,enabled:!0}),d=(0,Q.useCallback)(e=>{l(e),u.setFocusedOption(e)},[l,u.setFocusedOption]);return(0,$.jsxs)(`div`,{ref:u.containerRef,className:`rounded-lg border-2 border-primary/30 bg-primary/5 p-3 space-y-3 outline-none animate-in slide-in-from-bottom-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-sm font-medium text-text-primary`,children:[(0,$.jsxs)(`span`,{children:[`AI has `,s?`${e.length} questions`:`a question`]}),(0,$.jsxs)(`span`,{className:`text-[10px] text-text-secondary font-normal`,children:[s?`←→ tabs · `:``,`↑↓ options · 1-`,Math.min(o-1,9),` select · Enter submit`]})]}),s&&(0,$.jsx)(`div`,{className:`flex gap-1 p-1 bg-background rounded-md overflow-x-auto border border-border`,children:e.map((e,t)=>(0,$.jsxs)(`button`,{className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs whitespace-nowrap transition-all ${i.activeTab===t?`bg-primary text-primary-foreground`:i.hasAnswer(t)?`text-primary bg-transparent`:`text-text-secondary hover:bg-surface-elevated`}`,onClick:()=>{i.setActiveTab(t),u.setFocusedOption(0)},tabIndex:-1,children:[(0,$.jsx)(`span`,{className:`flex items-center justify-center w-4 h-4 rounded-full text-[10px] font-semibold ${i.activeTab===t?`bg-white/20`:i.hasAnswer(t)?`bg-primary/20 text-primary`:`bg-surface-elevated text-text-secondary`}`,children:i.hasAnswer(t)?`✓`:t+1}),(0,$.jsx)(`span`,{className:`max-w-[100px] overflow-hidden text-ellipsis`,children:e.header||`Q${t+1}`})]},t))}),a&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[!s&&a.header&&(0,$.jsx)(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-text-secondary`,children:a.header}),(0,$.jsx)(`div`,{className:`text-sm text-text-primary`,children:a.question}),a.multiSelect&&(0,$.jsx)(`div`,{className:`text-[11px] text-text-secondary`,children:`Select multiple`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[a.options.map((e,t)=>{let n=(i.answers[i.activeTab]||[]).includes(e.label),r=u.focusedOption===t;return(0,$.jsxs)(`button`,{onClick:()=>d(t),className:`text-left flex items-start gap-2.5 rounded px-2.5 py-2 text-xs border transition-all ${n?`border-primary bg-primary/10 text-text-primary`:`border-border bg-background text-text-secondary hover:border-primary/40 hover:bg-primary/5`} ${r?`ring-2 ring-primary/40 ring-offset-1 ring-offset-background`:``}`,children:[(0,$.jsx)(`span`,{className:`flex items-center justify-center w-4.5 h-4.5 rounded text-[10px] font-semibold shrink-0 mt-px ${n?`bg-primary/20 text-primary`:`bg-surface-elevated text-text-secondary`}`,children:t+1}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5 flex-1`,children:[(0,$.jsx)(`span`,{className:`font-medium text-text-primary`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:`text-[11px] text-text-secondary`,children:e.description})]})]},t)}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2.5 rounded px-2.5 py-2 text-xs border border-dashed transition-all border-border bg-transparent ${u.focusedOption===o-1?`ring-2 ring-primary/40 ring-offset-1 ring-offset-background`:``}`,children:[(0,$.jsx)(`span`,{className:`flex items-center justify-center w-4.5 h-4.5 rounded bg-surface-elevated text-text-secondary text-[10px] font-semibold shrink-0 mt-px`,children:`O`}),(0,$.jsx)(`input`,{ref:r,type:`text`,className:`flex-1 px-2 py-1 text-xs bg-surface border border-border rounded text-text-primary outline-none placeholder:text-text-subtle focus:border-primary`,placeholder:`Other (press O to type)...`,value:i.customInputs[i.activeTab]||``,onChange:e=>i.handleCustomInput(i.activeTab,e.target.value),onFocus:()=>u.setFocusedOption(o-1)})]})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2 justify-end pt-1`,children:[s&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{className:`px-3 py-1.5 text-xs rounded border border-border bg-background text-text-primary hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors`,onClick:i.goToPrevTab,disabled:i.activeTab===0,tabIndex:-1,children:`← Prev`}),(0,$.jsx)(`button`,{className:`px-3 py-1.5 text-xs rounded border border-border bg-background text-text-primary hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors`,onClick:i.goToNextTab,disabled:i.activeTab===e.length-1,tabIndex:-1,children:`Next →`})]}),(0,$.jsx)(`button`,{onClick:n,className:`px-4 py-1.5 rounded border border-border bg-background text-text-secondary text-xs hover:bg-surface-elevated transition-colors`,tabIndex:-1,children:`Skip`}),(0,$.jsxs)(`button`,{onClick:c,disabled:!i.allAnswered,className:`px-4 py-1.5 rounded bg-primary text-primary-foreground text-xs font-medium hover:bg-primary/80 transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,tabIndex:-1,children:[`Submit `,i.allAnswered?`✓`:`(${e.filter((e,t)=>i.hasAnswer(t)).length}/${e.length})`]})]})]})}function qt({messages:e,messagesLoading:t,pendingApproval:n,onApprovalResponse:r,isStreaming:i,phase:a,onSelectSession:o,connectingElapsed:s,projectName:c,onFork:l}){if(t)return(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-text-secondary`,children:[(0,$.jsx)(B,{className:`size-10 text-text-subtle animate-pulse`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Loading messages...`})]});if(e.length===0&&!i)return(0,$.jsx)(Ut,{projectName:c||``,onSelectSession:o||(()=>{})});let u=(0,Q.useMemo)(()=>e.filter(e=>{let t=e.content&&e.content.trim().length>0,n=e.events&&e.events.length>0;return e.role===`user`?t:t||n}),[e]);return(0,$.jsx)(`div`,{className:`relative flex-1 overflow-hidden flex flex-col min-h-0`,children:(0,$.jsxs)(Ot,{className:`flex-1 overflow-y-auto overflow-x-hidden`,resize:`smooth`,initial:`instant`,children:[(0,$.jsxs)(Ot.Content,{className:`p-4 space-y-4`,children:[u.map((e,t)=>(0,$.jsx)(Yt,{message:e,isStreaming:i&&e.id.startsWith(`streaming-`),projectName:c,onFork:e.role===`user`&&l?()=>{let n=t>0?u[t-1]:void 0;l(e.content,n?.id)}:void 0},e.id)),n&&(n.tool===`AskUserQuestion`?(0,$.jsx)(xn,{approval:n,onRespond:r}):(0,$.jsx)(bn,{approval:n,onRespond:r})),i&&(0,$.jsx)(gn,{lastMessage:e[e.length-1],phase:a,elapsed:s})]}),(0,$.jsx)(Jt,{})]})})}function Jt(){let{isAtBottom:e,scrollToBottom:t}=kt();return e?null:(0,$.jsxs)(`button`,{onClick:()=>t(),className:`absolute bottom-4 left-1/2 -translate-x-1/2 z-10 flex items-center gap-1 px-3 py-1 rounded-full bg-surface-elevated border border-border text-xs text-text-secondary hover:text-foreground shadow-lg transition-all`,children:[(0,$.jsx)(i,{className:`size-3`}),`Scroll to bottom`]})}function Yt({message:e,isStreaming:t,projectName:n,onFork:r}){return e.role===`user`?(0,$.jsx)(rn,{content:e.content,projectName:n,onFork:r}):e.role===`system`?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg bg-red-500/10 border border-red-500/20 px-3 py-2 text-sm text-red-400`,children:[(0,$.jsx)(be,{className:`size-4 shrink-0`}),(0,$.jsx)(`p`,{children:e.content})]}):(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[e.events&&e.events.length>0?(0,$.jsx)(pn,{events:e.events,isStreaming:t,projectName:n}):e.content&&(0,$.jsx)(`div`,{className:`text-sm text-text-primary`,children:(0,$.jsx)(yn,{content:e.content,projectName:n})}),e.accountLabel&&(0,$.jsxs)(`p`,{className:`text-[10px] select-none`,style:{color:`var(--color-text-subtle)`},children:[`via `,e.accountLabel]})]})}var Xt=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`]),Zt={"system-reminder":`Context`,claudeMd:`CLAUDE.md`,gitStatus:`Git Status`,currentDate:`Date`,fast_mode_info:`Fast Mode`,"available-deferred-tools":`Tools`,"task-notification":`Task Result`,environment_details:`Environment`};function Qt(e){let t=[],n=/<(system-reminder|available-deferred-tools|antml:[\w-]+|fast_mode_info|claudeMd|gitStatus|currentDate|task-notification|environment_details)[^>]*>([\s\S]*?)<\/\1>/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];t.push({name:e,label:Zt[e]??e.replace(/^antml:/,``).replace(/-/g,` `),content:r[2].trim()})}return{cleanText:e.replace(n,``).trim(),tags:t}}function $t(e){let t=e.match(/^\[Attached file: (.+?)\]\n\n?/);if(t)return{files:[t[1]],text:e.slice(t[0].length)};let n=e.match(/^\[Attached files:\n([\s\S]+?)\]\n\n?/);return n?{files:n[1].split(`
6
- `).map(e=>e.trim()).filter(Boolean),text:e.slice(n[0].length)}:{files:[],text:e}}function en(e,t){let n=g(e);return`/api/project/${encodeURIComponent(t??`_`)}/chat/uploads/${encodeURIComponent(n)}`}function tn(e){let t=e.lastIndexOf(`.`);return t===-1?!1:Xt.has(e.slice(t).toLowerCase())}var nn=new Set([`task-notification`,`environment_details`]);function rn({content:e,projectName:t,onFork:n}){let{files:r,text:a,tags:o}=(0,Q.useMemo)(()=>{let t=$t(e),{cleanText:n,tags:r}=Qt(t.text);return{files:t.files,text:n,tags:r}},[e]),s=o.some(e=>nn.has(e.name)),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>d(e.scrollHeight>e.clientHeight+2);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[a]),(0,$.jsxs)(`div`,{className:m(`group/user relative rounded-lg px-3 py-2 text-sm border shadow-sm`,s?`bg-surface/40 border-border/40 text-text-secondary`:`bg-primary/10 border-primary/15 text-text-primary`),children:[o.length>0&&(0,$.jsx)(an,{tags:o}),r.length>0&&(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map((e,n)=>tn(e)?(0,$.jsx)(fn,{filePath:e,projectName:t},n):(0,$.jsxs)(`div`,{className:`flex items-center gap-1 rounded-md border border-border/60 bg-background/40 px-1.5 py-0.5 text-[11px] text-text-secondary`,children:[(0,$.jsx)(se,{className:`size-3 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:g(e)})]},n))}),a&&(0,$.jsx)(`div`,{ref:f,className:m(`whitespace-pre-wrap break-words transition-all duration-200`,!c&&`line-clamp-2`,c&&`max-h-[50vh] overflow-y-auto`),children:s?(0,$.jsx)(un,{text:a,projectName:t}):a}),(u||c)&&(0,$.jsx)(`button`,{onClick:()=>l(!c),className:m(`flex items-center gap-1 text-xs mt-1 transition-colors`,s?`text-text-subtle hover:text-text-secondary`:`text-primary/70 hover:text-primary`),children:c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(G,{className:`size-3`}),`Show less`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(i,{className:`size-3`}),`Show more`]})}),!s&&n&&(0,$.jsx)(`button`,{onClick:n,title:`Retry from this message (fork session)`,className:`absolute top-1.5 right-1.5 can-hover:opacity-0 can-hover:group-hover/user:opacity-100 transition-opacity size-5 flex items-center justify-center rounded text-text-subtle hover:text-text-primary`,children:(0,$.jsx)(we,{className:`size-3`})})]})}function an({tags:e}){return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,$.jsx)(on,{tag:e},t))})}function on({tag:e}){let[t,n]=(0,Q.useState)(!1);return e.name===`task-notification`?(0,$.jsx)(cn,{content:e.content}):(0,$.jsxs)(`div`,{className:`text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>n(!t),className:`flex items-center gap-1 rounded-full border border-border/60 bg-surface/50 px-2 py-0.5 text-text-subtle hover:text-text-secondary hover:bg-surface transition-colors`,children:[(0,$.jsx)(d,{className:`size-2.5`}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(o,{className:m(`size-2.5 transition-transform`,t&&`rotate-90`)})]}),t&&(0,$.jsx)(`div`,{className:`mt-1 rounded border border-border/40 bg-surface/30 px-2 py-1.5 text-[11px] text-text-subtle/80 whitespace-pre-wrap max-h-40 overflow-y-auto leading-relaxed`,children:e.content})]})}function sn(e,t){return e.match(RegExp(`<${t}>([\\s\\S]*?)</${t}>`))?.[1]?.trim()||void 0}function cn({content:e}){let[t,n]=(0,Q.useState)(!1),r=sn(e,`status`),i=sn(e,`summary`),a=sn(e,`output-file`),s=sn(e,`result`);return(0,$.jsxs)(`div`,{className:`text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>n(!t),className:`flex items-center gap-1.5 rounded-full border border-border/60 bg-surface/50 px-2 py-0.5 text-text-subtle hover:text-text-secondary hover:bg-surface transition-colors`,children:[r===`completed`?(0,$.jsx)(P,{className:`size-2.5 text-green-500`}):(0,$.jsx)(ze,{className:`size-2.5 text-yellow-500`}),(0,$.jsx)(`span`,{className:`truncate max-w-80`,children:i??`Task notification`}),(0,$.jsx)(o,{className:m(`size-2.5 transition-transform shrink-0`,t&&`rotate-90`)})]}),t&&(0,$.jsxs)(`div`,{className:`mt-1 rounded border border-border/40 bg-surface/30 px-2 py-1.5 space-y-1.5`,children:[i&&(0,$.jsx)(`p`,{className:`text-[11px] text-text-secondary`,children:i}),a&&(0,$.jsx)(ln,{path:a}),s&&(0,$.jsx)(`div`,{className:`text-[11px] text-text-subtle/80 max-h-60 overflow-y-auto leading-relaxed`,children:(0,$.jsx)(yn,{content:s})})]})]})}function ln({path:e,projectName:t}){return(0,$.jsxs)(`button`,{type:`button`,onClick:(0,Q.useCallback)(()=>{let n=H.getState().openTab,r=t??De.getState().activeProject?.name,i=g(e),a={filePath:e};r&&(a.projectName=r),y.get(`/api/fs/read?path=${encodeURIComponent(e)}`).then(()=>{n({type:`editor`,title:i,metadata:a,projectId:null,closable:!0})}).catch(()=>{n({type:`editor`,title:i,metadata:a,projectId:null,closable:!0})})},[e,t]),className:`inline-flex items-center gap-1 rounded border border-border/50 bg-surface/50 px-1.5 py-0.5 font-mono text-[10px] text-text-secondary hover:text-text-primary hover:bg-surface transition-colors cursor-pointer`,children:[(0,$.jsx)(se,{className:`size-2.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-60`,children:g(e)}),(0,$.jsx)(Le,{className:`size-2 shrink-0 opacity-50`})]})}function un({text:e,projectName:t}){return(0,$.jsx)($.Fragment,{children:(0,Q.useMemo)(()=>{let t=/(\/(?:[\w.\-]+\/)+[\w.\-]+)/g,n=[],r=0,i;for(;(i=t.exec(e))!==null;)i.index>r&&n.push({kind:`text`,value:e.slice(r,i.index)}),n.push({kind:`path`,value:i[1]}),r=i.index+i[0].length;return r<e.length&&n.push({kind:`text`,value:e.slice(r)}),n},[e]).map((e,n)=>e.kind===`path`?(0,$.jsx)(ln,{path:e.value,projectName:t},n):(0,$.jsx)(`span`,{children:e.value},n))})}function dn(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let t=!1,r,a=v();return fetch(e,{headers:a?{Authorization:`Bearer ${a}`}:{}}).then(e=>{if(!e.ok)throw Error(`Failed`);return e.blob()}).then(e=>{t||(r=URL.createObjectURL(e),n(r))}).catch(()=>{t||i(!0)}),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),{blobUrl:t,error:r}}function fn({filePath:e,projectName:t}){let{blobUrl:n,error:r}=dn(en(e,t)),i=Oe(e=>e.open),a=g(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n&&i(n,a),className:`flex items-center gap-1 rounded-md border border-border/60 bg-background/40 px-1.5 py-0.5 text-[11px] text-text-secondary hover:bg-surface transition-colors cursor-pointer`,children:[n?(0,$.jsx)(`img`,{src:n,alt:a,className:`size-4 rounded-sm object-cover shrink-0`}):r?(0,$.jsx)(We,{className:`size-3 shrink-0`}):(0,$.jsx)(`div`,{className:`size-4 rounded-sm bg-surface animate-pulse shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:a})]})}function pn({events:e,isStreaming:t,projectName:n}){let r=[],i=``,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n.type===`thinking`){i&&=(r.push({kind:`text`,content:i}),``),a+=n.content;continue}if(a&&=(r.push({kind:`thinking`,content:a}),``),n.type===`account_retry`){i&&=(r.push({kind:`text`,content:i}),``);let e=n.accountLabel??`another account`,t=n.reason??`Auth failed`;r.push({kind:`text`,content:`\n\n> ↻ ${t} — retrying with **${e}**...\n\n`});continue}n.type===`text`?i+=n.content:n.type===`tool_use`?(i&&=(r.push({kind:`text`,content:i}),``),r.push({kind:`tool`,tool:n})):n.type===`tool_result`||(i&&=(r.push({kind:`text`,content:i}),``),r.push({kind:`tool`,tool:n}))}a&&r.push({kind:`thinking`,content:a}),i&&r.push({kind:`text`,content:i});let o=e.filter(e=>e.type===`tool_result`);for(let e of o){let t=e.toolUseId;if(t){let n=r.find(e=>e.kind===`tool`&&e.tool.type===`tool_use`&&e.tool.toolUseId===t);if(n){n.result=e;continue}}let n=r.find(e=>e.kind===`tool`&&!e.result);n&&(n.result=e)}for(let e=0;e<r.length;e++){let n=r[e];if(n.kind===`tool`&&!n.result){let i=!1;if(n.tool.type===`tool_use`&&n.tool.tool===`Read`){let t=n.tool.input?.file_path;t&&(i=r.slice(e+1).some(e=>e.kind===`tool`&&e.result&&e.tool.type===`tool_use`&&e.tool.tool===`Edit`&&e.tool.input?.file_path===t))}n.completed=i||!t}}return(0,$.jsx)($.Fragment,{children:r.map((e,i)=>{if(e.kind===`thinking`)return(0,$.jsx)(mn,{content:e.content,isStreaming:t&&i===r.length-1},`think-${i}`);if(e.kind===`text`){let a=t&&i===r.length-1;return(0,$.jsx)(`div`,{className:`text-sm text-text-primary`,children:(0,$.jsx)(hn,{content:e.content,animate:a,projectName:n})},`text-${i}`)}return(0,$.jsx)(jt,{tool:e.tool,result:e.result,completed:e.completed,projectName:n},`tool-${i}`)})})}function mn({content:e,isStreaming:t}){let[n,r]=(0,Q.useState)(t);return(0,Q.useEffect)(()=>{!t&&e.length>0&&r(!1)},[t,e.length]),(0,$.jsxs)(`div`,{className:`rounded border border-border/50 bg-surface/30 text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>r(!n),className:`flex items-center gap-2 px-2 py-1.5 w-full text-left hover:bg-surface transition-colors text-text-subtle`,children:[t?(0,$.jsx)(Z,{className:`size-3 animate-spin`}):(0,$.jsx)(o,{className:`size-3 transition-transform ${n?`rotate-90`:``}`}),(0,$.jsxs)(`span`,{children:[`Thinking`,t?`...`:``]}),!t&&(0,$.jsx)(`span`,{className:`text-text-subtle/50 ml-auto`,children:e.length>100?`${Math.round(e.length/4)} tokens`:``})]}),n&&(0,$.jsx)(Ot,{className:`max-h-60 overflow-y-auto`,resize:`smooth`,initial:`instant`,children:(0,$.jsx)(Ot.Content,{className:`px-2 pb-2 text-text-subtle/80 whitespace-pre-wrap text-[11px] leading-relaxed`,children:e})})]})}function hn({content:e,animate:t,projectName:n}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(yn,{content:e,projectName:n}),t&&(0,$.jsx)(`span`,{className:`text-text-subtle text-sm animate-pulse`,children:`Thinking...`})]})}function gn({lastMessage:e,phase:t,elapsed:n}){let r=!e||e.role!==`assistant`,i=e?.events?.length?e.events[e.events.length-1].type===`tool_result`:!1;return!r&&!i?null:(0,$.jsxs)(`div`,{className:`flex flex-col gap-1 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-text-subtle`,children:[(0,$.jsx)(Z,{className:`size-3 animate-spin`}),(0,$.jsxs)(`span`,{children:[t===`initializing`?`Initializing`:t===`connecting`?`Connecting`:t===`thinking`?`Thinking`:`Processing`,r&&(n??0)>0&&(0,$.jsxs)(`span`,{className:`text-text-subtle/60`,children:[`... (`,n,`s)`]})]})]}),t===`connecting`&&(n??0)>=30&&(0,$.jsx)(`p`,{className:`text-xs text-yellow-500/80 ml-5`,children:`Taking longer than usual — may be rate-limited or API slow. Try sending a new message to retry.`})]})}var _n=/<teammate-message[^>]*>[\s\S]*?<\/teammate-message>/g;function vn(e){return e.replace(_n,``).replace(/\n{3,}/g,`
6
+ `).map(e=>e.trim()).filter(Boolean),text:e.slice(n[0].length)}:{files:[],text:e}}function en(e,t){let n=g(e);return`/api/project/${encodeURIComponent(t??`_`)}/chat/uploads/${encodeURIComponent(n)}`}function tn(e){let t=e.lastIndexOf(`.`);return t===-1?!1:Xt.has(e.slice(t).toLowerCase())}var nn=new Set([`task-notification`,`environment_details`]);function rn({content:e,projectName:t,onFork:n}){let{files:r,text:a,tags:o}=(0,Q.useMemo)(()=>{let t=$t(e),{cleanText:n,tags:r}=Qt(t.text);return{files:t.files,text:n,tags:r}},[e]),s=o.some(e=>nn.has(e.name)),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=f.current;if(!e)return;let t=()=>d(e.scrollHeight>e.clientHeight+2);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[a]),(0,$.jsxs)(`div`,{className:m(`group/user relative rounded-lg px-3 py-2 text-sm border shadow-sm`,s?`bg-surface/40 border-border/40 text-text-secondary`:`bg-primary/10 border-primary/15 text-text-primary`),children:[o.length>0&&(0,$.jsx)(an,{tags:o}),r.length>0&&(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map((e,n)=>tn(e)?(0,$.jsx)(fn,{filePath:e,projectName:t},n):(0,$.jsxs)(`div`,{className:`flex items-center gap-1 rounded-md border border-border/60 bg-background/40 px-1.5 py-0.5 text-[11px] text-text-secondary`,children:[(0,$.jsx)(se,{className:`size-3 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:g(e)})]},n))}),a&&(0,$.jsx)(`div`,{ref:f,className:m(`whitespace-pre-wrap break-words transition-all duration-200`,!c&&`line-clamp-2`,c&&`max-h-[50vh] overflow-y-auto`),children:s?(0,$.jsx)(un,{text:a,projectName:t}):a}),(u||c)&&(0,$.jsx)(`button`,{onClick:()=>l(!c),className:m(`flex items-center gap-1 text-xs mt-1 transition-colors`,s?`text-text-subtle hover:text-text-secondary`:`text-primary/70 hover:text-primary`),children:c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(G,{className:`size-3`}),`Show less`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(i,{className:`size-3`}),`Show more`]})}),!s&&n&&(0,$.jsx)(`button`,{onClick:n,title:`Retry from this message (fork session)`,className:`absolute top-1.5 right-1.5 can-hover:opacity-0 can-hover:group-hover/user:opacity-100 transition-opacity size-5 flex items-center justify-center rounded text-text-subtle hover:text-text-primary`,children:(0,$.jsx)(we,{className:`size-3`})})]})}function an({tags:e}){return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,$.jsx)(on,{tag:e},t))})}function on({tag:e}){let[t,n]=(0,Q.useState)(!1);return e.name===`task-notification`?(0,$.jsx)(cn,{content:e.content}):(0,$.jsxs)(`div`,{className:`text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>n(!t),className:`flex items-center gap-1 rounded-full border border-border/60 bg-surface/50 px-2 py-0.5 text-text-subtle hover:text-text-secondary hover:bg-surface transition-colors`,children:[(0,$.jsx)(d,{className:`size-2.5`}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(o,{className:m(`size-2.5 transition-transform`,t&&`rotate-90`)})]}),t&&(0,$.jsx)(`div`,{className:`mt-1 rounded border border-border/40 bg-surface/30 px-2 py-1.5 text-[11px] text-text-subtle/80 whitespace-pre-wrap max-h-40 overflow-y-auto leading-relaxed`,children:e.content})]})}function sn(e,t){return e.match(RegExp(`<${t}>([\\s\\S]*?)</${t}>`))?.[1]?.trim()||void 0}function cn({content:e}){let[t,n]=(0,Q.useState)(!1),r=sn(e,`status`),i=sn(e,`summary`),a=sn(e,`output-file`),s=sn(e,`result`);return(0,$.jsxs)(`div`,{className:`text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>n(!t),className:`flex items-center gap-1.5 rounded-full border border-border/60 bg-surface/50 px-2 py-0.5 text-text-subtle hover:text-text-secondary hover:bg-surface transition-colors`,children:[r===`completed`?(0,$.jsx)(P,{className:`size-2.5 text-green-500`}):(0,$.jsx)(ze,{className:`size-2.5 text-yellow-500`}),(0,$.jsx)(`span`,{className:`truncate max-w-80`,children:i??`Task notification`}),(0,$.jsx)(o,{className:m(`size-2.5 transition-transform shrink-0`,t&&`rotate-90`)})]}),t&&(0,$.jsxs)(`div`,{className:`mt-1 rounded border border-border/40 bg-surface/30 px-2 py-1.5 space-y-1.5`,children:[i&&(0,$.jsx)(`p`,{className:`text-[11px] text-text-secondary`,children:i}),a&&(0,$.jsx)(ln,{path:a}),s&&(0,$.jsx)(`div`,{className:`text-[11px] text-text-subtle/80 max-h-60 overflow-y-auto leading-relaxed`,children:(0,$.jsx)(yn,{content:s})})]})]})}function ln({path:e,projectName:t}){return(0,$.jsxs)(`button`,{type:`button`,onClick:(0,Q.useCallback)(()=>{let n=H.getState().openTab,r=t??De.getState().activeProject?.name,i=g(e),a={filePath:e};r&&(a.projectName=r),y.get(`/api/fs/read?path=${encodeURIComponent(e)}`).then(()=>{n({type:`editor`,title:i,metadata:a,projectId:null,closable:!0})}).catch(()=>{n({type:`editor`,title:i,metadata:a,projectId:null,closable:!0})})},[e,t]),className:`inline-flex items-center gap-1 rounded border border-border/50 bg-surface/50 px-1.5 py-0.5 font-mono text-[10px] text-text-secondary hover:text-text-primary hover:bg-surface transition-colors cursor-pointer`,children:[(0,$.jsx)(se,{className:`size-2.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-60`,children:g(e)}),(0,$.jsx)(Le,{className:`size-2 shrink-0 opacity-50`})]})}function un({text:e,projectName:t}){return(0,$.jsx)($.Fragment,{children:(0,Q.useMemo)(()=>{let t=/(\/(?:[\w.\-]+\/)+[\w.\-]+)/g,n=[],r=0,i;for(;(i=t.exec(e))!==null;)i.index>r&&n.push({kind:`text`,value:e.slice(r,i.index)}),n.push({kind:`path`,value:i[1]}),r=i.index+i[0].length;return r<e.length&&n.push({kind:`text`,value:e.slice(r)}),n},[e]).map((e,n)=>e.kind===`path`?(0,$.jsx)(ln,{path:e.value,projectName:t},n):(0,$.jsx)(`span`,{children:e.value},n))})}function dn(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let t=!1,r,a=v();return fetch(e,{headers:a?{Authorization:`Bearer ${a}`}:{}}).then(e=>{if(!e.ok)throw Error(`Failed`);return e.blob()}).then(e=>{t||(r=URL.createObjectURL(e),n(r))}).catch(()=>{t||i(!0)}),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),{blobUrl:t,error:r}}function fn({filePath:e,projectName:t}){let{blobUrl:n,error:r}=dn(en(e,t)),i=Oe(e=>e.open),a=g(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n&&i(n,a),className:`flex items-center gap-1 rounded-md border border-border/60 bg-background/40 px-1.5 py-0.5 text-[11px] text-text-secondary hover:bg-surface transition-colors cursor-pointer`,children:[n?(0,$.jsx)(`img`,{src:n,alt:a,className:`size-4 rounded-sm object-cover shrink-0`}):r?(0,$.jsx)(We,{className:`size-3 shrink-0`}):(0,$.jsx)(`div`,{className:`size-4 rounded-sm bg-surface animate-pulse shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:a})]})}function pn({events:e,isStreaming:t,projectName:n}){let r=[],i=``,a=``;for(let t=0;t<e.length;t++){let n=e[t];if(n.type===`thinking`){i&&=(r.push({kind:`text`,content:i}),``),a+=n.content;continue}if(a&&=(r.push({kind:`thinking`,content:a}),``),n.type===`status_update`){i&&=(r.push({kind:`text`,content:i}),``),r.push({kind:`text`,content:`\n\n> ⟳ ${n.message}\n\n`});continue}if(n.type===`account_retry`){i&&=(r.push({kind:`text`,content:i}),``);let e=n.accountLabel??`another account`,t=n.reason??`Auth failed`;r.push({kind:`text`,content:`\n\n> ↻ ${t} — retrying with **${e}**...\n\n`});continue}n.type===`text`?i+=n.content:n.type===`tool_use`?(i&&=(r.push({kind:`text`,content:i}),``),r.push({kind:`tool`,tool:n})):n.type===`tool_result`||(i&&=(r.push({kind:`text`,content:i}),``),r.push({kind:`tool`,tool:n}))}a&&r.push({kind:`thinking`,content:a}),i&&r.push({kind:`text`,content:i});let o=e.filter(e=>e.type===`tool_result`);for(let e of o){let t=e.toolUseId;if(t){let n=r.find(e=>e.kind===`tool`&&e.tool.type===`tool_use`&&e.tool.toolUseId===t);if(n){n.result=e;continue}}let n=r.find(e=>e.kind===`tool`&&!e.result);n&&(n.result=e)}for(let e=0;e<r.length;e++){let n=r[e];if(n.kind===`tool`&&!n.result){let i=!1;if(n.tool.type===`tool_use`&&n.tool.tool===`Read`){let t=n.tool.input?.file_path;t&&(i=r.slice(e+1).some(e=>e.kind===`tool`&&e.result&&e.tool.type===`tool_use`&&e.tool.tool===`Edit`&&e.tool.input?.file_path===t))}n.completed=i||!t}}return(0,$.jsx)($.Fragment,{children:r.map((e,i)=>{if(e.kind===`thinking`)return(0,$.jsx)(mn,{content:e.content,isStreaming:t&&i===r.length-1},`think-${i}`);if(e.kind===`text`){let a=t&&i===r.length-1;return(0,$.jsx)(`div`,{className:`text-sm text-text-primary`,children:(0,$.jsx)(hn,{content:e.content,animate:a,projectName:n})},`text-${i}`)}return(0,$.jsx)(jt,{tool:e.tool,result:e.result,completed:e.completed,projectName:n},`tool-${i}`)})})}function mn({content:e,isStreaming:t}){let[n,r]=(0,Q.useState)(t);return(0,Q.useEffect)(()=>{!t&&e.length>0&&r(!1)},[t,e.length]),(0,$.jsxs)(`div`,{className:`rounded border border-border/50 bg-surface/30 text-xs`,children:[(0,$.jsxs)(`button`,{onClick:()=>r(!n),className:`flex items-center gap-2 px-2 py-1.5 w-full text-left hover:bg-surface transition-colors text-text-subtle`,children:[t?(0,$.jsx)(Z,{className:`size-3 animate-spin`}):(0,$.jsx)(o,{className:`size-3 transition-transform ${n?`rotate-90`:``}`}),(0,$.jsxs)(`span`,{children:[`Thinking`,t?`...`:``]}),!t&&(0,$.jsx)(`span`,{className:`text-text-subtle/50 ml-auto`,children:e.length>100?`${Math.round(e.length/4)} tokens`:``})]}),n&&(0,$.jsx)(Ot,{className:`max-h-60 overflow-y-auto`,resize:`smooth`,initial:`instant`,children:(0,$.jsx)(Ot.Content,{className:`px-2 pb-2 text-text-subtle/80 whitespace-pre-wrap text-[11px] leading-relaxed`,children:e})})]})}function hn({content:e,animate:t,projectName:n}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(yn,{content:e,projectName:n}),t&&(0,$.jsx)(`span`,{className:`text-text-subtle text-sm animate-pulse`,children:`Thinking...`})]})}function gn({lastMessage:e,phase:t,elapsed:n}){let r=!e||e.role!==`assistant`,i=e?.events?.length?e.events[e.events.length-1].type===`tool_result`:!1;return!r&&!i?null:(0,$.jsxs)(`div`,{className:`flex flex-col gap-1 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-text-subtle`,children:[(0,$.jsx)(Z,{className:`size-3 animate-spin`}),(0,$.jsxs)(`span`,{children:[t===`initializing`?`Initializing`:t===`connecting`?`Connecting`:t===`thinking`?`Thinking`:`Processing`,r&&(n??0)>0&&(0,$.jsxs)(`span`,{className:`text-text-subtle/60`,children:[`... (`,n,`s)`]})]})]}),t===`connecting`&&(n??0)>=30&&(0,$.jsx)(`p`,{className:`text-xs text-yellow-500/80 ml-5`,children:`Taking longer than usual — may be rate-limited or API slow. Try sending a new message to retry.`})]})}var _n=/<teammate-message[^>]*>[\s\S]*?<\/teammate-message>/g;function vn(e){return e.replace(_n,``).replace(/\n{3,}/g,`
7
7
 
8
8
  `).trim()}function yn({content:e,projectName:t}){let n=vn(e);return n?(0,$.jsx)(c,{content:n,projectName:t,codeActions:!0}):null}function bn({approval:e,onRespond:t}){return(0,$.jsxs)(`div`,{className:`rounded-lg border-2 border-yellow-500/40 bg-yellow-500/10 p-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-yellow-400 text-sm font-medium`,children:[(0,$.jsx)(Qe,{className:`size-4`}),(0,$.jsx)(`span`,{children:`Tool Approval Required`})]}),(0,$.jsx)(`div`,{className:`text-xs text-text-primary`,children:(0,$.jsx)(`span`,{className:`font-medium`,children:e.tool})}),(0,$.jsx)(`pre`,{className:`text-xs font-mono text-text-secondary overflow-x-auto bg-background rounded p-2 border border-border`,children:JSON.stringify(e.input,null,2)}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`button`,{onClick:()=>t(e.requestId,!0),className:`px-4 py-1.5 rounded bg-green-600 text-white text-xs font-medium hover:bg-green-500 transition-colors`,children:`Allow`}),(0,$.jsx)(`button`,{onClick:()=>t(e.requestId,!1),className:`px-4 py-1.5 rounded bg-red-600 text-white text-xs font-medium hover:bg-red-500 transition-colors`,children:`Deny`})]})]})}function xn({approval:e,onRespond:t}){return(0,$.jsx)(Kt,{questions:e.input.questions??[],onSubmit:n=>t(e.requestId,!0,n),onSkip:()=>t(e.requestId,!1)})}function Sn(){let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function Cn(e){let[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(``),a=(0,Q.useRef)(null),o=(0,Q.useRef)(``),s=typeof window<`u`&&Sn()!==null;return{isListening:t,interimText:r,start:(0,Q.useCallback)(t=>{let r=Sn();if(!r)return;a.current?.abort();let s=new r;s.lang=e?.lang??`vi-VN`,s.continuous=!0,s.interimResults=!0,o.current=``,s.onresult=e=>{let n=``,r=``;for(let t=0;t<e.results.length;t++){let i=e.results[t];i.isFinal?r+=i[0].transcript:n+=i[0].transcript}r&&(o.current=r);let a=(o.current+` `+n).trim();i(n),t(a,n.length===0&&o.current.length>0)},s.onend=()=>{n(!1),i(``),o.current&&t(o.current.trim(),!0)},s.onerror=e=>{e.error!==`no-speech`&&e.error!==`aborted`&&console.warn(`[voice-input] error:`,e.error),n(!1),i(``)},a.current=s,s.start(),n(!0)},[e?.lang]),stop:(0,Q.useCallback)(()=>{a.current?.stop(),a.current=null,n(!1),i(``)},[]),supported:s}}var wn=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]),Tn=new Set([`application/pdf`]),En=[`text/`,`application/json`,`application/xml`,`application/javascript`,`application/typescript`,`application/x-yaml`,`application/toml`,`application/x-sh`],Dn=new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.py,.rb,.go,.rs,.java,.kt,.swift,.c,.cpp,.h,.hpp,.cs,.json,.yaml,.yml,.toml,.xml,.md,.mdx,.txt,.csv,.tsv,.html,.css,.scss,.less,.sass,.sh,.bash,.zsh,.fish,.sql,.graphql,.gql,.env,.ini,.cfg,.conf,.dockerfile,.makefile,.vue,.svelte,.astro,.ipynb`.split(`,`));function On(e){return wn.has(e.type)}function kn(e){if(wn.has(e.type)||Tn.has(e.type)||En.some(t=>e.type.startsWith(t)))return!0;let t=An(e.name);return!!(t&&Dn.has(t))}function An(e){let t=e.lastIndexOf(`.`);return t===-1?``:e.slice(t).toLowerCase()}function jn({attachments:e,onRemove:t}){return e.length===0?null:(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5 px-2 md:px-4 pt-2`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border border-border bg-surface px-2 py-1 text-xs text-text-secondary max-w-48`,children:[e.previewUrl?(0,$.jsx)(`img`,{src:e.previewUrl,alt:e.name,className:`size-5 rounded object-cover shrink-0`}):e.isImage?(0,$.jsx)(We,{className:`size-3.5 shrink-0 text-text-subtle`}):(0,$.jsx)(se,{className:`size-3.5 shrink-0 text-text-subtle`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.name}),e.status===`uploading`?(0,$.jsx)(Z,{className:`size-3 shrink-0 animate-spin text-text-subtle`}):e.status===`error`?(0,$.jsx)(`span`,{className:`text-red-500 shrink-0`,title:`Upload failed`,children:`!`}):null,(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:`shrink-0 rounded-sm p-0.5 hover:bg-border/50 transition-colors`,"aria-label":`Remove ${e.name}`,children:(0,$.jsx)(a,{className:`size-3`})})]},e.id))})}var Mn=[{id:`default`,label:`Ask before edits`,icon:He,description:`Claude will ask for approval before making each edit`},{id:`acceptEdits`,label:`Edit automatically`,icon:s,description:`Claude will edit files without asking first`},{id:`plan`,label:`Plan mode`,icon:Ve,description:`Claude will present a plan before editing`},{id:`bypassPermissions`,label:`Bypass permissions`,icon:$e,description:`Claude will not ask before running commands`}];function Nn(e){return Mn.find(t=>t.id===e)?.label??`Unknown`}function Pn(e){return Mn.find(t=>t.id===e)?.icon??He}function Fn({value:e,onChange:t,open:n,onOpenChange:r}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[n,r]),(0,Q.useEffect)(()=>{n&&(a.current=Mn.findIndex(t=>t.id===e),a.current<0&&(a.current=0))},[n,e]);let o=(0,Q.useCallback)(e=>{if(e.key===`Escape`){r(!1);return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;a.current=(a.current+t+Mn.length)%Mn.length,(i.current?.querySelector(`[data-idx="${a.current}"]`))?.focus()}if(e.key===`Enter`){e.preventDefault();let n=Mn[a.current];n&&(t(n.id),r(!1))}},[t,r]);return n?(0,$.jsxs)(`div`,{ref:i,role:`listbox`,"aria-label":`Permission modes`,onKeyDown:o,onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:`absolute bottom-full left-0 mb-1 z-50 w-72 md:w-80 rounded-lg border border-border bg-surface shadow-lg`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-2 border-b border-border`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-text-secondary`,children:`Modes`}),(0,$.jsx)(`kbd`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-text-subtle border border-border`,children:`Shift + Tab`})]}),(0,$.jsx)(`div`,{className:`py-1`,children:Mn.map((n,i)=>{let a=n.icon,o=n.id===e;return(0,$.jsxs)(`button`,{"data-idx":i,role:`option`,"aria-selected":o,tabIndex:0,onClick:()=>{t(n.id),r(!1)},className:`w-full flex items-start gap-3 px-3 py-2.5 text-left transition-colors hover:bg-surface-elevated focus:bg-surface-elevated focus:outline-none ${o?`bg-surface-elevated`:``}`,children:[(0,$.jsx)(a,{className:`size-4 mt-0.5 shrink-0 text-text-secondary`}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium text-text-primary`,children:n.label}),(0,$.jsx)(`div`,{className:`text-xs text-text-subtle leading-snug`,children:n.description})]}),o&&(0,$.jsx)(q,{className:`size-4 mt-0.5 shrink-0 text-primary`})]},n.id)})})]}):null}function In(e){let t=[];function n(e){for(let r of e)t.push(r),r.children&&n(r.children)}return n(e),t}function Ln({items:e,filter:t,onSelect:n,onClose:r,visible:i}){let[a,o]=(0,Q.useState)(0),s=(0,Q.useRef)(null),c=(()=>{if(!t)return e.slice(0,50);let n=t.toLowerCase();return e.filter(e=>e.path.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)).slice(0,50)})();(0,Q.useEffect)(()=>{o(0)},[t]),(0,Q.useEffect)(()=>{let e=s.current;e&&e.children[a]?.scrollIntoView({block:`nearest`})},[a]);let l=(0,Q.useCallback)(e=>{if(!i||c.length===0)return!1;switch(e.key){case`ArrowUp`:return e.preventDefault(),o(e=>e>0?e-1:c.length-1),!0;case`ArrowDown`:return e.preventDefault(),o(e=>e<c.length-1?e+1:0),!0;case`Enter`:case`Tab`:return e.preventDefault(),c[a]&&n(c[a]),!0;case`Escape`:return e.preventDefault(),r(),!0}return!1},[i,c,a,n,r]);return(0,Q.useEffect)(()=>{if(!i)return;let e=e=>{l(e)&&e.stopPropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[i,l]),!i||c.length===0?null:(0,$.jsx)(`div`,{className:`max-h-52 overflow-y-auto border-b border-border bg-surface`,children:(0,$.jsx)(`div`,{ref:s,className:`py-1`,children:c.map((e,t)=>(0,$.jsxs)(`button`,{className:`flex items-center gap-2 w-full px-3 py-1.5 text-left transition-colors ${t===a?`bg-primary/10 text-primary`:`hover:bg-surface-hover text-text-primary`}`,onMouseEnter:()=>o(t),onClick:()=>n(e),children:[(0,$.jsx)(`span`,{className:`shrink-0`,children:e.type===`directory`?(0,$.jsx)(oe,{className:`size-4 text-amber-500`}):(0,$.jsx)(Ie,{className:`size-4 text-blue-400`})}),(0,$.jsx)(`span`,{className:`text-sm truncate`,children:e.path})]},e.path))})})}var Rn=(0,Q.memo)(function({onSend:e,isStreaming:t,onCancel:n,disabled:i,projectName:a,onSlashStateChange:o,onSlashItemsLoaded:s,slashSelected:c,onFileStateChange:l,onFileItemsLoaded:d,fileSelected:f,externalFiles:p,initialValue:m,autoFocus:g,permissionMode:b,onModeChange:x,providerId:ee,onProviderChange:S}){let[C,w]=(0,Q.useState)(m??``),[T,E]=(0,Q.useState)([]),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(`next`),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),te=(0,Q.useRef)(null),F=(0,Q.useRef)([]),I=(0,Q.useRef)([]),L=Cn(),ne=(0,Q.useRef)(``),R=(0,Q.useCallback)(e=>{let t=ne.current;w(t?t+` `+e:e),requestAnimationFrame(()=>{let e=window.matchMedia(`(min-width: 768px)`).matches?N.current:P.current;e&&(e.style.height=`auto`,e.style.height=Math.min(e.scrollHeight,160)+`px`)})},[]),z=(0,Q.useCallback)(()=>{L.isListening?L.stop():(ne.current=C.trim(),L.start(R))},[L.isListening,L.start,L.stop,C,R]);(0,Q.useEffect)(()=>{let e=()=>{L.supported&&z()};return window.addEventListener(`toggle-voice-input`,e),()=>window.removeEventListener(`toggle-voice-input`,e)},[L.supported,z]),(0,Q.useEffect)(()=>{m&&(w(m),setTimeout(()=>{let e=N.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},50))},[m]),(0,Q.useEffect)(()=>{g&&setTimeout(()=>{(window.matchMedia(`(min-width: 768px)`).matches?N.current:P.current)?.focus()},100)},[]),(0,Q.useEffect)(()=>{if(!a){F.current=[],s?.([]);return}y.get(`${_(a)}/chat/slash-items`).then(e=>{F.current=e,s?.(e)}).catch(()=>{F.current=[],s?.([])})},[a]),(0,Q.useEffect)(()=>{if(!a){I.current=[],d?.([]);return}y.get(`${_(a)}/files/tree?depth=5`).then(e=>{let t=In(e);I.current=t,d?.(t)}).catch(()=>{I.current=[],d?.([])})},[a]),(0,Q.useEffect)(()=>{if(!c)return;let e=N.current,t=e?.selectionStart??C.length,n=C.slice(0,t),r=C.slice(t),i=n.replace(/(?:^|\s)\/\S*$/,e=>`${e.startsWith(`/`)?``:e[0]}/${c.name} `);w(i+r),o?.(!1,``),l?.(!1,``),e&&(e.focus(),setTimeout(()=>{e.selectionStart=e.selectionEnd=i.length},0))},[c]),(0,Q.useEffect)(()=>{if(!f)return;let e=N.current;if(!e)return;let t=e.selectionStart,n=C.slice(0,t),r=C.slice(t),i=n.match(/@(\S*)$/);if(i){let t=n.length-i[0].length;w(n.slice(0,t)+`@${f.path} `+r);let a=t+f.path.length+2;setTimeout(()=>{e.selectionStart=e.selectionEnd=a,e.focus()},0)}else{let t=C+`@${f.path} `;w(t),setTimeout(()=>{e.selectionStart=e.selectionEnd=t.length,e.focus()},0)}l?.(!1,``)},[f]),(0,Q.useEffect)(()=>{!p||p.length===0||V(p)},[p]);let B=(0,Q.useCallback)(async e=>{if(!a)return null;try{let t=new FormData;t.append(`files`,e);let n={},r=v();r&&(n.Authorization=`Bearer ${r}`);let i=await(await fetch(`${_(a)}/chat/upload`,{method:`POST`,headers:n,body:t})).json();return i.ok&&Array.isArray(i.data)&&i.data.length>0?i.data[0].path:null}catch{return null}},[a]),V=(0,Q.useCallback)(e=>{for(let t of e){if(!kn(t)){w(e=>e+(e.length>0&&!e.endsWith(` `)?` `:``)+t.name);continue}let e=h(),n=On(t),r=n?URL.createObjectURL(t):void 0,i={id:e,name:t.name,file:t,isImage:n,previewUrl:r,status:`uploading`};E(e=>[...e,i]),B(t).then(t=>{E(n=>n.map(n=>n.id===e?{...n,serverPath:t??void 0,status:t?`ready`:`error`}:n))})}(P.current??N.current)?.focus()},[B]),H=(0,Q.useCallback)(e=>{E(t=>{let n=t.find(t=>t.id===e);return n?.previewUrl&&URL.revokeObjectURL(n.previewUrl),t.filter(t=>t.id!==e)})},[]),U=(0,Q.useCallback)(()=>{let n=C.trim(),r=T.filter(e=>e.status===`ready`);if(!n&&r.length===0){A(!1);return}o?.(!1,``),l?.(!1,``),L.isListening&&L.stop(),e(n,r,t?j:void 0),w(``);for(let e of T)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);E([]),A(!1),M(`next`),N.current&&(N.current.style.height=`auto`),P.current&&(P.current.style.height=`auto`)},[C,T,e,o,l,t,j]),W=(0,Q.useCallback)(()=>{if(!i){if(T.some(e=>e.status===`uploading`)){(C.trim()||T.some(e=>e.status!==`error`))&&A(!0);return}U()}},[C,T,i,U]);(0,Q.useEffect)(()=>{k&&(T.some(e=>e.status===`uploading`)||U())},[k,T,U]);let G=(0,Q.useCallback)(e=>{if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),W();return}if(e.shiftKey&&e.key===`Tab`){e.preventDefault();let t=[`default`,`acceptEdits`,`plan`,`bypassPermissions`],n=t[(t.indexOf(b??`bypassPermissions`)+1)%t.length];x?.(n)}},[W,b,x]),K=(0,Q.useCallback)((e,t)=>{let n=e.slice(0,t),r=n.match(/(?:^|\s)\/(\S*)$/);if(r&&F.current.length>0){o?.(!0,r[1]??``),l?.(!1,``);return}let i=n.match(/@(\S*)$/);if(i&&I.current.length>0){l?.(!0,i[1]??``),o?.(!1,``);return}o?.(!1,``),l?.(!1,``)},[o,l]),re=(0,Q.useCallback)((e,t)=>{w(e),K(e,t)},[K]),q=(0,Q.useCallback)(e=>{let t=e?.target??N.current;t&&(t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,160)+`px`)},[]),J=(0,Q.useCallback)(e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e of t)if(e.kind===`file`){let t=e.getAsFile();t&&n.push(t)}n.length>0&&(e.preventDefault(),V(n))},[V]),Y=(0,Q.useCallback)(e=>{e.preventDefault();let t=Array.from(e.dataTransfer.files);t.length>0&&V(t)},[V]),X=(0,Q.useCallback)(e=>{e.preventDefault()},[]),ie=(0,Q.useCallback)(()=>{te.current?.click()},[]),ae=(0,Q.useCallback)(e=>{let t=Array.from(e.target.files??[]);t.length>0&&V(t),e.target.value=``},[V]),oe=C.trim().length>0||T.some(e=>e.status!==`error`),se=t&&!oe;return(0,$.jsxs)(`div`,{className:`p-2 md:p-3 bg-background`,children:[(0,$.jsxs)(`div`,{className:`border border-border rounded-xl md:rounded-2xl bg-surface shadow-sm cursor-text`,onClick:e=>{i||e.target instanceof HTMLTextAreaElement||(window.matchMedia(`(min-width: 768px)`).matches?N.current:P.current)?.focus()},children:[(0,$.jsx)(jn,{attachments:T,onRemove:H}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 pt-2 md:hidden relative`,children:[(0,$.jsx)(zn,{mode:b??`bypassPermissions`,onClick:()=>O(e=>!e)}),(0,$.jsx)(Fn,{value:b??`bypassPermissions`,onChange:e=>x?.(e),open:D,onOpenChange:O}),S&&a&&(0,$.jsx)(Se,{value:ee??`claude`,onChange:S,projectName:a}),t&&(0,$.jsx)(Vn,{value:j,onChange:M})]}),(0,$.jsxs)(`div`,{className:`flex items-end gap-1 md:hidden px-2 py-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ie()},disabled:i,className:`flex items-center justify-center size-7 shrink-0 rounded-full text-text-subtle hover:text-text-primary transition-colors disabled:opacity-50`,"aria-label":`Attach file`,children:(0,$.jsx)(Xe,{className:`size-4`})}),(0,$.jsx)(`textarea`,{ref:P,value:C,onChange:e=>{re(e.target.value,e.target.selectionStart),q(e)},onKeyDown:G,onPaste:J,onDrop:Y,onDragOver:X,placeholder:t?`Follow-up...`:`Ask anything...`,disabled:i,rows:1,className:`flex-1 resize-none bg-transparent py-1.5 text-sm text-foreground placeholder:text-text-subtle focus:outline-none disabled:opacity-50 max-h-20`}),L.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),z()},disabled:i,className:`flex items-center justify-center size-7 shrink-0 rounded-full transition-colors disabled:opacity-50 ${L.isListening?`bg-red-600 text-white animate-pulse`:`text-text-subtle hover:text-text-primary`}`,"aria-label":L.isListening?`Stop voice input`:`Start voice input`,children:L.isListening?(0,$.jsx)(Je,{className:`size-4`}):(0,$.jsx)(Fe,{className:`size-4`})}),se?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),n?.()},className:`flex items-center justify-center size-7 shrink-0 rounded-full bg-red-600 text-white hover:bg-red-500 transition-colors`,"aria-label":`Stop`,children:(0,$.jsx)(u,{className:`size-3`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),k?A(!1):W()},disabled:i||!oe,className:`flex items-center justify-center size-7 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-30 transition-colors`,"aria-label":k?`Cancel queued send`:`Send`,children:k?(0,$.jsx)(Z,{className:`size-3.5 animate-spin`}):(0,$.jsx)(r,{className:`size-3.5`})})]}),(0,$.jsxs)(`div`,{className:`hidden md:block`,children:[(0,$.jsx)(`textarea`,{ref:N,value:C,onChange:e=>{re(e.target.value,e.target.selectionStart),q(e)},onKeyDown:G,onPaste:J,onDrop:Y,onDragOver:X,placeholder:t?`Follow-up or Stop...`:`Ask anything...`,disabled:i,rows:1,className:`w-full resize-none bg-transparent px-4 pt-3 pb-1 text-sm text-foreground placeholder:text-text-subtle focus:outline-none disabled:opacity-50 max-h-40`}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-3 pb-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ie()},disabled:i,className:`flex items-center justify-center size-8 rounded-full text-text-subtle hover:text-text-primary hover:bg-surface-elevated transition-colors disabled:opacity-50`,"aria-label":`Attach file`,children:(0,$.jsx)(Xe,{className:`size-4`})}),(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(zn,{mode:b??`bypassPermissions`,onClick:()=>O(e=>!e)}),(0,$.jsx)(Fn,{value:b??`bypassPermissions`,onChange:e=>x?.(e),open:D,onOpenChange:O})]}),S&&a&&(0,$.jsx)(Se,{value:ee??`claude`,onChange:S,projectName:a}),t&&(0,$.jsx)(Vn,{value:j,onChange:M})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[L.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),z()},disabled:i,className:`flex items-center justify-center size-8 rounded-full transition-colors disabled:opacity-50 ${L.isListening?`bg-red-600 text-white animate-pulse`:`text-text-subtle hover:text-text-primary hover:bg-surface-elevated`}`,"aria-label":L.isListening?`Stop voice input`:`Start voice input`,children:L.isListening?(0,$.jsx)(Je,{className:`size-4`}):(0,$.jsx)(Fe,{className:`size-4`})}),se?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),n?.()},className:`flex items-center justify-center size-8 rounded-full bg-red-600 text-white hover:bg-red-500 transition-colors`,"aria-label":`Stop response`,children:(0,$.jsx)(u,{className:`size-3.5`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),k?A(!1):W()},disabled:i||!oe,className:`flex items-center justify-center size-8 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-30 disabled:cursor-not-allowed transition-colors`,"aria-label":k?`Cancel queued send`:`Send message`,children:k?(0,$.jsx)(Z,{className:`size-4 animate-spin`}):(0,$.jsx)(r,{className:`size-4`})})]})]})]})]}),(0,$.jsx)(`input`,{ref:te,type:`file`,multiple:!0,className:`hidden`,onChange:ae})]})});function zn({mode:e,onClick:t}){let n=Pn(e),r=Nn(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t()},className:`inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] text-text-subtle hover:text-text-primary hover:bg-surface-elevated transition-colors border border-transparent hover:border-border`,"aria-label":`Permission mode: ${r}`,children:[(0,$.jsx)(n,{className:`size-3`}),(0,$.jsx)(`span`,{className:`max-w-[100px] truncate`,children:r})]})}var Bn=[{value:`now`,label:`Interrupt`,Icon:nt},{value:`next`,label:`Queue`,Icon:Ge},{value:`later`,label:`Later`,Icon:re}];function Vn({value:e,onChange:t}){let n=(0,Q.useCallback)(()=>{let n=[`next`,`later`,`now`];t(n[(n.indexOf(e)+1)%n.length])},[e,t]),r=Bn.find(t=>t.value===e)??Bn[1],i=r.Icon;return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),n()},className:`inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] text-text-subtle hover:text-text-primary hover:bg-surface-elevated transition-colors border border-transparent hover:border-border`,"aria-label":`Message priority: ${r.label}`,title:`Priority: ${r.label} (click to cycle)`,children:[(0,$.jsx)(i,{className:`size-3`}),(0,$.jsx)(`span`,{children:r.label})]})}function Hn({items:e,filter:t,onSelect:n,onClose:r,visible:i}){let[a,o]=(0,Q.useState)(0),s=(0,Q.useRef)(null),c=e.filter(e=>{let n=t.toLowerCase();return e.name.toLowerCase().includes(n)||e.description.toLowerCase().includes(n)});(0,Q.useEffect)(()=>{o(0)},[t]),(0,Q.useEffect)(()=>{let e=s.current;e&&e.children[a]?.scrollIntoView({block:`nearest`})},[a]);let l=(0,Q.useCallback)(e=>{if(!i||c.length===0)return!1;switch(e.key){case`ArrowUp`:return e.preventDefault(),o(e=>e>0?e-1:c.length-1),!0;case`ArrowDown`:return e.preventDefault(),o(e=>e<c.length-1?e+1:0),!0;case`Enter`:case`Tab`:return e.preventDefault(),c[a]&&n(c[a]),!0;case`Escape`:return e.preventDefault(),r(),!0}return!1},[i,c,a,n,r]);return(0,Q.useEffect)(()=>{if(!i)return;let e=e=>{l(e)&&e.stopPropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[i,l]),!i||c.length===0?null:(0,$.jsx)(`div`,{className:`max-h-52 overflow-y-auto border-b border-border bg-surface`,children:(0,$.jsx)(`div`,{ref:s,className:`py-1`,children:c.map((e,t)=>(0,$.jsxs)(`button`,{className:`flex items-start gap-3 w-full px-3 py-2 text-left transition-colors ${t===a?`bg-primary/10 text-primary`:`hover:bg-surface-hover text-text-primary`}`,onMouseEnter:()=>o(t),onClick:()=>n(e),children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5`,children:e.type===`skill`?(0,$.jsx)(et,{className:`size-4 text-amber-500`}):(0,$.jsx)(M,{className:`size-4 text-blue-500`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,$.jsxs)(`span`,{className:`font-medium text-sm`,children:[`/`,e.name]}),e.argumentHint&&(0,$.jsx)(`span`,{className:`text-xs text-text-subtle`,children:e.argumentHint}),(0,$.jsx)(`span`,{className:`text-xs text-text-subtle capitalize ml-auto`,children:e.scope===`user`?`global`:e.type})]}),e.description&&(0,$.jsx)(`p`,{className:`text-xs text-text-subtle mt-0.5 line-clamp-2`,children:e.description})]})]},`${e.type}-${e.name}`))})})}var Un=`ppm-hienlh`;function Wn({open:e,onOpenChange:t,onSuccess:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(`idle`);function y(){f(null),m(``),v(`idle`),u(null)}function b(){t(!1),y(),i(``),o(``),u(null)}async function x(){g(!0),u(null);try{let{url:e,state:t}=await j();f(t),v(`waiting`),window.open(e,`_blank`)}catch(e){u(e.message)}g(!1)}async function ee(){if(!(!p.trim()||!d)){g(!0),u(null);try{let e=p.trim();e.includes(`#`)&&(e=e.split(`#`)[0]??e),await C(e,d),b(),n(`Account connected via OAuth!`)}catch(e){u(e.message)}g(!1)}}async function S(){if(r.trim()){c(!0),u(null);try{await A({apiKey:r.trim(),label:a.trim()||void 0}),b(),n(`Account added!`)}catch(e){u(e.message)}c(!1)}}let w=r.trim()?r.trim().startsWith(`sk-ant-oat`)?`OAuth token (Claude Max/Pro)`:r.trim().startsWith(`sk-ant-api`)?`API key`:`Unknown format`:``;return(0,$.jsx)(R,{open:e,onOpenChange:e=>{e||b()},children:(0,$.jsxs)(L,{className:`sm:max-w-md`,children:[(0,$.jsxs)(N,{children:[(0,$.jsx)(ye,{className:`text-sm`,children:`Add Claude Account`}),(0,$.jsx)(K,{className:`text-xs leading-relaxed`,children:`Connect via OAuth (recommended) or paste a token manually.`})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border p-3 space-y-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-medium`,children:`Recommended: Login with Claude`}),_===`idle`?(0,$.jsx)(W,{size:`sm`,className:`w-full h-8 text-xs`,onClick:x,disabled:h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{className:`size-3 animate-spin mr-1`}),` Opening...`]}):`Login with Claude`}):(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Authorize in the opened tab, then paste the code:`}),(0,$.jsx)(Y,{placeholder:`Paste code here...`,value:p,onChange:e=>m(e.target.value),className:`text-xs h-8 font-mono`,autoFocus:!0}),(0,$.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,$.jsx)(W,{size:`sm`,className:`flex-1 h-7 text-xs`,onClick:ee,disabled:!p.trim()||h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{className:`size-3 animate-spin mr-1`}),` Connecting...`]}):`Connect`}),(0,$.jsx)(W,{size:`sm`,variant:`ghost`,className:`h-7 text-xs`,onClick:y,children:`Cancel`})]})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`div`,{className:`flex-1 border-t`}),(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`or paste token`}),(0,$.jsx)(`div`,{className:`flex-1 border-t`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(F,{htmlFor:`add-token`,className:`text-xs`,children:`Token`}),(0,$.jsx)(Y,{id:`add-token`,type:`password`,placeholder:`sk-ant-...`,value:r,onChange:e=>i(e.target.value),className:`text-xs h-8 font-mono`}),w&&(0,$.jsxs)(`p`,{className:`text-[10px] text-muted-foreground`,children:[`Detected: `,w]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(F,{htmlFor:`add-label`,className:`text-xs`,children:`Label (optional)`}),(0,$.jsx)(Y,{id:`add-label`,placeholder:`e.g. Personal, Work`,value:a,onChange:e=>o(e.target.value),className:`text-xs h-8`})]})]}),l&&(0,$.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-red-500/10 text-red-600`,children:l}),(0,$.jsxs)(xe,{children:[(0,$.jsx)(W,{size:`sm`,variant:`outline`,className:`text-xs h-7`,onClick:b,children:`Cancel`}),(0,$.jsx)(W,{size:`sm`,className:`text-xs h-7`,onClick:S,disabled:!r.trim()||s,children:s?`Adding...`:`Add Token`})]})]})})}function Gn({open:e,onOpenChange:t,accounts:n,preselectId:r,onMessage:i}){let a=n.filter(e=>e.hasRefreshToken),[o,s]=(0,Q.useState)(new Set),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1);e&&!g&&(s(r?new Set([r]):new Set(a.map(e=>e.id))),_(!0)),!e&&g&&_(!1);function y(){t(!1),l(``),d(!1),p(!1)}async function b(e){if(o.size===0)return;h(!0);let t=c.trim()||Un;try{let n={"Content-Type":`application/json`},r=v();r&&(n.Authorization=`Bearer ${r}`);let a=await fetch(`/api/accounts/export`,{method:`POST`,headers:n,body:JSON.stringify({password:t,accountIds:[...o],includeRefreshToken:u,refreshBeforeExport:f})});if(!a.ok){let e=await a.json();throw Error(e.error??`Export failed: ${a.status}`)}let s=await a.text();if(e)try{await navigator.clipboard.writeText(s),i?.(`Backup copied to clipboard!`)}catch{qn(s),i?.(`Backup downloaded.`)}else qn(s),i?.(`Backup downloaded.`);y()}catch{}h(!1)}let x=o.size>0&&!m;return(0,$.jsx)(R,{open:e,onOpenChange:e=>{e||y()},children:(0,$.jsxs)(L,{className:`sm:max-w-md`,children:[(0,$.jsxs)(N,{children:[(0,$.jsxs)(ye,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(me,{className:`size-3.5`}),` Export Accounts`]}),(0,$.jsx)(K,{className:`text-xs`,children:`Select accounts and set a password to protect the backup.`})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-muted-foreground`,children:`Accounts to export`}),(0,$.jsx)(`button`,{className:`text-[10px] text-primary hover:underline cursor-pointer`,onClick:()=>s(o.size===a.length?new Set:new Set(a.map(e=>e.id))),children:o.size===a.length?`Deselect all`:`Select all`})]}),a.length===0?(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground p-2 border rounded`,children:`No exportable accounts.`}):(0,$.jsx)(`div`,{className:`max-h-36 overflow-y-auto space-y-1 border rounded p-2`,children:a.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`exp-${e.id}`,checked:o.has(e.id),onChange:t=>{let n=new Set(o);t.target.checked?n.add(e.id):n.delete(e.id),s(n)},className:`size-3.5 accent-primary cursor-pointer`}),(0,$.jsx)(`label`,{htmlFor:`exp-${e.id}`,className:`text-xs cursor-pointer truncate`,children:e.label??e.email??e.id.slice(0,8)})]},e.id))})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(F,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Y,{type:`password`,placeholder:`Leave empty for default`,value:c,onChange:e=>l(e.target.value),className:`text-xs h-8`,autoComplete:`new-password`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`exp-full`,checked:u,onChange:e=>d(e.target.checked),className:`size-3.5 accent-primary cursor-pointer`}),(0,$.jsx)(`label`,{htmlFor:`exp-full`,className:`text-[11px] cursor-pointer`,children:`Include refresh tokens (full transfer)`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,id:`exp-refresh`,checked:f,onChange:e=>p(e.target.checked),className:`size-3.5 accent-primary cursor-pointer`}),(0,$.jsx)(`label`,{htmlFor:`exp-refresh`,className:`text-[11px] cursor-pointer`,children:`Refresh tokens before export`})]}),u?(0,$.jsxs)(`div`,{className:`rounded-md border border-red-500/30 bg-red-500/5 p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-red-600`,children:`Full transfer — source accounts will expire`}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Refresh tokens included. Source machine expires in ~1h after target refreshes.`})]}):f?(0,$.jsx)(`div`,{className:`rounded-md border border-amber-500/30 bg-amber-500/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-amber-600`,children:`Refresh before export — invalidates previous shares`})}):(0,$.jsx)(`div`,{className:`rounded-md border border-green-500/30 bg-green-500/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-green-600`,children:`Share current token (safe)`})}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Encrypted with AES-256-GCM + scrypt.`})]}),(0,$.jsxs)(xe,{className:`gap-1.5 flex-col sm:flex-row`,children:[(0,$.jsx)(W,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:y,children:`Cancel`}),(0,$.jsxs)(W,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,disabled:!x,onClick:()=>b(!0),children:[(0,$.jsx)(ne,{className:`size-3 mr-1`}),` Copy`]}),(0,$.jsx)(W,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!x,onClick:()=>b(!1),children:m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{className:`size-3 animate-spin mr-1`}),` Exporting...`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{className:`size-3 mr-1`}),` Download`]})})]})]})})}function Kn({open:e,onOpenChange:t,onSuccess:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null);function d(){t(!1),i(``),o(``),u(null)}async function f(){if(r.trim()){c(!0),u(null);try{let e=await D({data:r.trim(),password:a.trim()||Un});d(),n(`Imported ${e.imported} account(s)`)}catch(e){u(e.message||`Import failed`)}c(!1)}}return(0,$.jsx)(R,{open:e,onOpenChange:e=>{e||d()},children:(0,$.jsxs)(L,{className:`sm:max-w-md`,children:[(0,$.jsxs)(N,{children:[(0,$.jsxs)(ye,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(me,{className:`size-3.5`}),` Import Accounts`]}),(0,$.jsx)(K,{className:`text-xs`,children:`Paste backup data and enter the export password. Imported accounts are temporary (~1h).`})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(F,{className:`text-xs`,children:`Backup data`}),(0,$.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),placeholder:`Paste backup JSON here...`,rows:4,className:`w-full text-xs p-2 rounded border border-border bg-background font-mono resize-none focus:outline-none focus:ring-1 focus:ring-primary`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(F,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Y,{type:`password`,placeholder:`Leave empty for default`,value:a,onChange:e=>o(e.target.value),className:`text-xs h-8`,autoComplete:`current-password`})]})]}),l&&(0,$.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-red-500/10 text-red-600`,children:l}),(0,$.jsxs)(xe,{children:[(0,$.jsx)(W,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:d,children:`Cancel`}),(0,$.jsx)(W,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!r.trim()||s,onClick:f,children:s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{className:`size-3 animate-spin mr-1`}),` Importing...`]}):`Import`})]})]})})}function qn(e){let t=new Blob([e],{type:`application/json`}),n=document.createElement(`a`);n.href=URL.createObjectURL(t),n.download=`ppm-accounts-backup.json`,n.click(),URL.revokeObjectURL(n.href)}var Jn=typeof window<`u`?window.matchMedia(`(min-width: 768px)`):null;function Yn(e){return Jn?.addEventListener(`change`,e),()=>Jn?.removeEventListener(`change`,e)}function Xn(){return Jn?.matches??!0}function Zn(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0);return(0,Q.useEffect)(()=>{r(!0),E().then(t).finally(()=>r(!1))},[]),n?(0,$.jsx)(`p`,{className:`text-xs text-text-subtle py-4 text-center`,children:`Loading...`}):e?(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Rotation Strategy`}),(0,$.jsxs)(ue,{value:e.strategy,onValueChange:async e=>{t(await S({strategy:e}))},children:[(0,$.jsx)(Ce,{className:`w-full h-9 text-xs`,children:(0,$.jsx)(he,{})}),(0,$.jsxs)(pe,{children:[(0,$.jsx)(Ee,{value:`round-robin`,children:`Round-robin`}),(0,$.jsx)(Ee,{value:`fill-first`,children:`Fill-first`}),(0,$.jsx)(Ee,{value:`lowest-usage`,children:`Lowest usage`})]})]}),(0,$.jsxs)(`p`,{className:`text-[10px] text-text-subtle`,children:[e.strategy===`round-robin`&&`Cycles through accounts evenly`,e.strategy===`fill-first`&&`Uses one account until its limit, then moves on`,e.strategy===`lowest-usage`&&`Picks the account with the lowest current usage`]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Max Retry`}),(0,$.jsx)(`input`,{type:`number`,min:0,value:e.maxRetry,className:`w-full h-9 text-xs border rounded-md px-3 bg-background`,onChange:async e=>{let n=parseInt(e.target.value,10);!isNaN(n)&&n>=0&&t(await S({maxRetry:n}))}}),(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`How many accounts to try on failure. 0 = try all available accounts.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs border-t border-border pt-3`,children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Active accounts`}),(0,$.jsx)(`span`,{className:`font-medium text-text-primary`,children:e.activeCount})]})]}):(0,$.jsx)(`p`,{className:`text-xs text-text-subtle py-4 text-center`,children:`Failed to load settings`})}function Qn({open:e,onOpenChange:t}){let n=(0,Q.useSyncExternalStore)(Yn,Xn);return e?n?(0,$.jsx)(R,{open:e,onOpenChange:t,children:(0,$.jsxs)(L,{className:`sm:max-w-sm`,children:[(0,$.jsx)(N,{children:(0,$.jsxs)(ye,{className:`text-sm flex items-center gap-2`,children:[(0,$.jsx)(fe,{className:`size-4`}),` Rotation & Retry`]})}),(0,$.jsx)(Zn,{})]})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-50 transition-opacity duration-200 opacity-100`,onClick:()=>t(!1),style:{backgroundColor:`rgba(0,0,0,0.5)`}}),(0,$.jsxs)(`div`,{className:m(`fixed bottom-0 left-0 right-0 z-50 bg-background rounded-t-2xl border-t border-border shadow-2xl`,`transition-transform duration-300 ease-out max-h-[85vh] overflow-y-auto`,`translate-y-0`),children:[(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsx)(`div`,{className:`w-10 h-1 rounded-full bg-border`})}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,$.jsxs)(`span`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,$.jsx)(fe,{className:`size-4`}),` Rotation & Retry`]}),(0,$.jsx)(`button`,{onClick:()=>t(!1),className:`flex items-center justify-center size-7 rounded-md hover:bg-surface-elevated transition-colors`,children:(0,$.jsx)(a,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`px-4 py-4 pb-8`,children:(0,$.jsx)(Zn,{})})]})]}):null}var $n=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],er=Array.from({length:24},(e,t)=>t);function tr(e,t){let n=Array.from({length:7},()=>Array.from({length:24},()=>({sum:0,count:0,avg:0})));for(let r of e){let e=t===`5h`?r.five_hour_util:r.weekly_util;if(e==null)continue;let i=new Date(r.recorded_at+(r.recorded_at.endsWith(`Z`)?``:`Z`)),a=(i.getDay()+6)%7,o=i.getHours();n[a][o].sum+=e,n[a][o].count+=1}for(let e of n)for(let t of e)t.avg=t.count>0?t.sum/t.count:0;return n}function nr(e){return e.map(e=>{let t=e.reduce((e,t)=>e+t.sum,0),n=e.reduce((e,t)=>e+t.count,0);return n>0?t/n:0})}function rr(e){return er.map(t=>{let n=0,r=0;for(let i of e)n+=i[t].sum,r+=i[t].count;return r>0?n/r:0})}function ir(e){return e===0?`bg-surface-elevated`:e<.3?`bg-green-500/30`:e<.5?`bg-green-500/60`:e<.7?`bg-amber-500/50`:e<.9?`bg-amber-500/80`:`bg-red-500/80`}function ar(e){return e<.3?`bg-green-500`:e<.7?`bg-amber-500`:`bg-red-500`}function or({accountId:e}){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(`5h`);(0,Q.useEffect)(()=>{i(!0),ee(e).then(n).catch(()=>n([])).finally(()=>i(!1))},[e]);let s=(0,Q.useMemo)(()=>t?tr(t,a):null,[t,a]),c=(0,Q.useMemo)(()=>s?nr(s):[],[s]),l=(0,Q.useMemo)(()=>s?rr(s):[],[s]),u=Math.max(...c,.01);if(Math.max(...l,.01),r)return(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(Z,{className:`size-3 animate-spin text-text-subtle`})});if(!t||t.length===0)return(0,$.jsx)(`div`,{className:`text-[10px] text-text-subtle py-2 text-center`,children:`No usage history yet`});let d=t.length,f=new Set(t.map(e=>new Date(e.recorded_at+(e.recorded_at.endsWith(`Z`)?``:`Z`)).toDateString())).size;return(0,$.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-text-subtle`,children:`Usage Pattern (7d)`}),(0,$.jsxs)(`div`,{className:`flex gap-0.5 text-[9px]`,children:[(0,$.jsx)(`button`,{onClick:()=>o(`5h`),className:`px-1.5 py-0.5 rounded cursor-pointer transition-colors ${a===`5h`?`bg-primary/15 text-primary`:`text-text-subtle hover:text-text-secondary`}`,title:`5-hour rolling window limit — resets every 5 hours`,children:`5h`}),(0,$.jsx)(`button`,{onClick:()=>o(`weekly`),className:`px-1.5 py-0.5 rounded cursor-pointer transition-colors ${a===`weekly`?`bg-primary/15 text-primary`:`text-text-subtle hover:text-text-secondary`}`,title:`Weekly limit — resets every 7 days`,children:`Wk`})]})]}),(0,$.jsxs)(`p`,{className:`text-[9px] text-text-subtle leading-tight`,children:[`Avg `,a===`5h`?`5-hour`:`weekly`,` limit usage over `,f,`d (`,d,` samples). Higher % = closer to rate limit. Hover cells for details.`]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Avg usage by day of week`}),(0,$.jsx)(`div`,{className:`flex flex-col gap-[2px] mt-0.5`,children:$n.map((e,t)=>{let n=c[t]??0;return(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`span`,{className:`text-[8px] text-text-subtle w-5 shrink-0 text-right tabular-nums`,children:e}),(0,$.jsx)(`div`,{className:`flex-1 h-2.5 bg-surface-elevated rounded-sm overflow-hidden`,children:(0,$.jsx)(`div`,{className:`h-full rounded-sm transition-all ${ar(n)}`,style:{width:`${Math.round(n/u*100)}%`}})}),(0,$.jsxs)(`span`,{className:`text-[8px] text-text-subtle w-6 shrink-0 text-right tabular-nums`,children:[Math.round(n*100),`%`]})]},e)})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Avg usage by hour (0h-23h)`}),(0,$.jsx)(`div`,{className:`flex gap-[1px] mt-0.5`,children:er.map(e=>{let t=l[e]??0;return(0,$.jsxs)(`div`,{className:`flex-1 flex flex-col items-center gap-[1px]`,children:[(0,$.jsx)(`div`,{className:`w-full aspect-square rounded-[2px] ${ir(t)}`,title:`${e}:00 — avg ${Math.round(t*100)}% usage`}),e%6==0&&(0,$.jsx)(`span`,{className:`text-[7px] text-text-subtle tabular-nums`,children:e})]},e)})})]}),s&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Day x Hour heatmap`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-[1px] mt-0.5`,children:[$n.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-[1px]`,children:[(0,$.jsx)(`span`,{className:`text-[7px] text-text-subtle w-4 shrink-0 text-right`,children:e.charAt(0)}),er.map(n=>{let r=s[t][n];return(0,$.jsx)(`div`,{className:`flex-1 aspect-square rounded-[1px] ${ir(r.avg)}`,title:`${e} ${n}:00 — ${r.count>0?`avg ${Math.round(r.avg*100)}% (${r.count} samples)`:`no data`}`},n)})]},e)),(0,$.jsxs)(`div`,{className:`flex items-center gap-[1px]`,children:[(0,$.jsx)(`span`,{className:`w-4 shrink-0`}),er.map(e=>(0,$.jsx)(`div`,{className:`flex-1 text-center`,children:e%6==0&&(0,$.jsx)(`span`,{className:`text-[7px] text-text-subtle tabular-nums`,children:e})},e))]})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[8px] text-text-subtle`,children:[(0,$.jsx)(`span`,{children:`Low`}),(0,$.jsxs)(`div`,{className:`flex gap-[2px]`,children:[(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-green-500/30`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-green-500/60`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-amber-500/50`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-amber-500/80`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-red-500/80`})]}),(0,$.jsx)(`span`,{children:`High`}),(0,$.jsx)(`span`,{className:`ml-1`,children:`|`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-surface-elevated border border-border/30`}),(0,$.jsx)(`span`,{children:`No data`})]})]})}function sr(e){return e>=90?`text-red-500`:e>=70?`text-amber-500`:`text-green-500`}function cr(e){return e>=90?`bg-red-500`:e>=70?`bg-amber-500`:`bg-green-500`}function lr(e){if(!e)return null;let t=null;if(e.resetsInMinutes!=null)t=e.resetsInMinutes;else if(e.resetsInHours!=null)t=Math.round(e.resetsInHours*60);else if(e.resetsAt){let n=new Date(e.resetsAt).getTime()-Date.now();t=n>0?Math.ceil(n/6e4):0}if(t==null)return null;if(t<=0)return`now`;let n=Math.floor(t/1440),r=Math.floor(t%1440/60),i=t%60;return n>0?i>0?`${n}d ${r}h ${i}m`:r>0?`${n}d ${r}h`:`${n}d`:r>0?i>0?`${r}h ${i}m`:`${r}h`:`${i}m`}function ur({label:e,bucket:t}){if(!t)return null;let n=Math.round(t.utilization*100),r=lr(t);return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium text-text-primary`,children:e}),r&&(0,$.jsxs)(`span`,{className:`text-[10px] text-text-subtle`,title:`Resets in`,children:[`↻ `,r]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`div`,{className:`flex-1 h-2 rounded-full bg-border overflow-hidden`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full transition-all ${cr(n)}`,style:{width:`${Math.min(n,100)}%`}})}),(0,$.jsxs)(`span`,{className:`text-xs font-medium tabular-nums w-10 text-right ${sr(n)}`,children:[n,`%`]})]})]})}function dr(e){let t=e-Date.now();if(t<=0)return`expired`;let n=Math.ceil(t/6e4),r=Math.floor(n/60),i=Math.floor(r/24);return i>0?`${i}d ${r%24}h`:r>0?`${r}h ${n%60}m`:`${n}m`}function fr(e){if(!e)return{label:`unknown`,tip:`No account info available`,color:`text-text-subtle`};if(!e.expiresAt)return{label:`key`,tip:`API key (no expiry)`,color:`text-text-subtle`};let t=e.expiresAt*1e3<Date.now();return t&&e.hasRefreshToken?{label:`expired`,tip:`Token expired but has refresh token — will auto-renew`,color:`text-amber-500`}:t?{label:`expired`,tip:`Token expired, no refresh token`,color:`text-red-500`}:e.hasRefreshToken?{label:`long-lived`,tip:`OAuth token with refresh — long-lived`,color:`text-green-500`}:{label:`temp`,tip:`Temporary token without refresh — will expire`,color:`text-amber-500`}}function pr(e){if(!e)return null;let t=Math.round((Date.now()-e)/1e3);if(t<5)return`just now`;if(t<60)return`${t}s ago`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60),i=n%60;return r<24?i>0?`${r}h ${i}m ago`:`${r}h ago`:`${Math.floor(r/24)}d ago`}function mr({entry:e,isActive:t,accountInfo:n,onToggle:r,onDelete:i,onExport:a,onViewProfile:o,flash:s,fullscreen:c}){let{usage:l}=e,u=l.session||l.weekly||l.weeklyOpus||l.weeklySonnet,d=n?.status??e.accountStatus,f=!!(n&&!n.hasRefreshToken&&n.expiresAt&&n.expiresAt<Math.floor(Date.now()/1e3));return(0,$.jsxs)(`div`,{className:`rounded-md border p-2 transition-colors duration-500 ${c?`flex flex-col gap-1.5 overflow-hidden`:`space-y-1.5 min-w-[200px] shrink-0 snap-start`} ${f?`opacity-50`:``} ${s?`bg-primary/10 border-primary/40`:``} ${t?`border-primary/30 bg-primary/5`:`border-border/50`}`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium truncate flex-1 min-w-0`,children:e.accountLabel??e.accountId.slice(0,8)}),f&&(0,$.jsx)(`span`,{className:`text-[9px] text-red-500 shrink-0 font-medium`,children:`Expired`}),!e.isOAuth&&!f&&(0,$.jsx)(`span`,{className:`text-[9px] text-text-subtle shrink-0`,children:`API key`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[!f&&o&&n?.profileData&&(0,$.jsx)(`button`,{className:`p-1 rounded cursor-pointer text-text-subtle hover:text-foreground hover:bg-surface-elevated transition-colors`,onClick:()=>o(n.profileData,e.accountId),title:`View profile`,children:(0,$.jsx)(I,{className:`size-3`})}),!f&&a&&e.isOAuth&&(0,$.jsx)(`button`,{className:`p-1 rounded cursor-pointer text-text-subtle hover:text-blue-500 hover:bg-surface-elevated transition-colors`,onClick:()=>a(e.accountId),title:`Export this account`,children:(0,$.jsx)(X,{className:`size-3`})}),!f&&r&&(0,$.jsx)(Pe,{checked:d!==`disabled`,onCheckedChange:()=>r(e.accountId,d),disabled:d===`cooldown`,className:`scale-[0.6] cursor-pointer`}),i&&(0,$.jsx)(`button`,{className:`p-1 rounded cursor-pointer text-text-subtle hover:text-red-500 hover:bg-surface-elevated transition-colors`,onClick:()=>i(e.accountId,e.accountLabel??e.accountId.slice(0,8)),title:`Remove account`,children:(0,$.jsx)(J,{className:`size-3`})})]})]}),u?(0,$.jsxs)(`div`,{className:c?`flex-1 flex flex-col justify-evenly min-h-0`:`space-y-1.5`,children:[(0,$.jsx)(ur,{label:`5-Hour Session`,bucket:l.session}),(0,$.jsx)(ur,{label:`Weekly`,bucket:l.weekly}),(0,$.jsx)(ur,{label:`Weekly (Opus)`,bucket:l.weeklyOpus}),(0,$.jsx)(ur,{label:`Weekly (Sonnet)`,bucket:l.weeklySonnet})]}):(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:e.isOAuth?`No usage data yet`:`Usage tracking not available for API keys`}),(()=>{let e=fr(n);return(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[9px] text-text-subtle flex-wrap`,children:[l.lastFetchedAt&&(0,$.jsxs)(`span`,{title:`Last usage data update`,children:[`↻ `,pr(new Date(l.lastFetchedAt).getTime())]}),n?.expiresAt&&n.expiresAt*1e3>Date.now()&&(0,$.jsxs)(`span`,{title:`Token expires in`,children:[`⏱ `,dr(n.expiresAt*1e3)]}),(0,$.jsxs)(`span`,{className:e.color,title:e.tip,children:[`© `,e.label]})]})})()]})}function hr({usage:e,visible:t,onClose:n,onReload:r,loading:i,lastFetchedAt:o}){let[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(!0),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)(null),[ee,S]=(0,Q.useState)(!1),[C,E]=(0,Q.useState)(!1),[D,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(null),[te,F]=(0,Q.useState)(null),[I,L]=(0,Q.useState)(!1),[ne,R]=(0,Q.useState)(null),z=(0,Q.useRef)(void 0),B=(0,Q.useRef)([]);function V(e){z.current&&clearTimeout(z.current),R(e),z.current=setTimeout(()=>R(null),4e3)}function H(e){U(),e&&V(e)}async function U(){let e=s.length>0;e?g(!0):m(!0);let[t,n,r]=await Promise.allSettled([w(),k(),x()]);if(t.status===`fulfilled`){let n=t.value;if(e&&B.current.length>0){let e=new Set,t=new Map(B.current.map(e=>[e.accountId,e]));for(let r of n){let n=t.get(r.accountId);if(!n){e.add(r.accountId);continue}let i=n.usage,a=r.usage;(i.session?.utilization!==a.session?.utilization||i.weekly?.utilization!==a.weekly?.utilization||i.weeklyOpus?.utilization!==a.weeklyOpus?.utilization||i.weeklySonnet?.utilization!==a.weeklySonnet?.utilization)&&e.add(r.accountId)}e.size>0&&(v(e),setTimeout(()=>v(new Set),1500))}B.current=n,c(n)}n.status===`fulfilled`&&u(n.value),r.status===`fulfilled`&&f(r.value?.id??null),m(!1),g(!1)}if((0,Q.useEffect)(()=>{t&&U()},[t]),(0,Q.useEffect)(()=>{!t||!o||U()},[o]),!t)return null;let W=new Map(l.map(e=>[e.id,e])),G=e.queryCostUsd!=null||e.totalCostUsd!=null,K=s.length>0,re=s.length||1,q=Math.ceil(Math.sqrt(re)),J=Math.ceil(re/q);async function Y(e,t){await T(e,{status:t===`disabled`?`active`:`disabled`}),U(),r?.()}async function ie(){if(N){try{await O(N.id),V(`Account "${N.display}" removed.`),U(),r?.()}catch(e){V(`Failed to remove: ${e.message}`)}P(null)}}function oe(){F(null),E(!0)}return(0,$.jsxs)(`div`,{className:`relative border-b border-border bg-surface px-3 py-2.5 ${I?`fixed inset-0 z-50 flex flex-col gap-2.5 overflow-hidden`:`space-y-2.5 max-h-[350px] overflow-y-auto`}`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-xs font-semibold text-text-primary`,children:`Usage & Accounts`}),o&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:pr(new Date(o).getTime())})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{onClick:()=>M(!0),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:`Rotation & retry settings`,children:(0,$.jsx)(fe,{className:`size-3`})}),K&&(0,$.jsx)(`button`,{onClick:()=>L(e=>!e),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:I?`Exit fullscreen`:`Fullscreen view`,children:I?(0,$.jsx)(Ye,{className:`size-3`}):(0,$.jsx)(qe,{className:`size-3`})}),r&&(0,$.jsx)(`button`,{onClick:()=>{r(),U()},disabled:i||h,className:`text-xs text-text-subtle hover:text-text-primary px-1 disabled:opacity-50 cursor-pointer`,title:`Refresh`,children:(0,$.jsx)(ke,{className:`size-3 ${i||h?`animate-spin`:``}`})}),(0,$.jsx)(`button`,{onClick:()=>{L(!1),n()},className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,children:(0,$.jsx)(a,{className:`size-3`})})]})]}),ne&&(0,$.jsx)(`div`,{className:`text-[11px] p-1.5 rounded bg-green-500/10 text-green-600 text-center animate-in fade-in duration-200`,children:ne}),K||p?(0,$.jsx)(`div`,{className:I?`flex-1 min-h-0 grid gap-2 overflow-hidden`:`flex gap-1.5 overflow-x-auto pb-1 -mx-3 px-3 snap-x snap-mandatory scrollbar-thin`,style:I?{gridTemplateColumns:`repeat(${q}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${J}, minmax(0, 1fr))`}:void 0,children:p?(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Loading...`}):s.map(t=>(0,$.jsx)(mr,{entry:t,isActive:t.accountId===(d??e.activeAccountId),accountInfo:W.get(t.accountId),onToggle:Y,onDelete:(e,t)=>P({id:e,display:t}),onExport:e=>{F(e),E(!0)},onViewProfile:(e,t)=>b({profile:e,accountId:t}),flash:_.has(t.accountId),fullscreen:I},t.accountId))}):(0,$.jsx)($.Fragment,{children:e.session||e.weekly||e.weeklyOpus||e.weeklySonnet?(0,$.jsxs)(`div`,{className:`space-y-2.5`,children:[(0,$.jsx)(ur,{label:`5-Hour Session`,bucket:e.session}),(0,$.jsx)(ur,{label:`Weekly`,bucket:e.weekly}),(0,$.jsx)(ur,{label:`Weekly (Opus)`,bucket:e.weeklyOpus}),(0,$.jsx)(ur,{label:`Weekly (Sonnet)`,bucket:e.weeklySonnet})]}):(0,$.jsx)(`p`,{className:`text-xs text-text-subtle`,children:`No usage data available`})}),G&&(0,$.jsxs)(`div`,{className:`border-t border-border pt-2 space-y-1`,children:[e.queryCostUsd!=null&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs`,children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Last query`}),(0,$.jsxs)(`span`,{className:`text-text-primary font-medium tabular-nums`,children:[`$`,e.queryCostUsd.toFixed(4)]})]}),e.totalCostUsd!=null&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs`,children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Session total`}),(0,$.jsxs)(`span`,{className:`text-text-primary font-medium tabular-nums`,children:[`$`,e.totalCostUsd.toFixed(4)]})]})]}),y&&(0,$.jsxs)(`div`,{className:`border-t border-border pt-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-text-subtle`,children:`Profile`}),(0,$.jsx)(`button`,{className:`text-text-subtle hover:text-foreground cursor-pointer`,onClick:()=>b(null),children:(0,$.jsx)(a,{className:`size-3`})})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[70px_1fr] gap-x-2 gap-y-0.5 text-[10px]`,children:[y.profile.account?.display_name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Name`}),(0,$.jsx)(`span`,{children:y.profile.account.display_name})]}),y.profile.account?.email&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Email`}),(0,$.jsx)(`span`,{children:y.profile.account.email})]}),y.profile.organization?.name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Org`}),(0,$.jsx)(`span`,{children:y.profile.organization.name})]}),y.profile.organization?.organization_type&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Type`}),(0,$.jsx)(`span`,{children:y.profile.organization.organization_type})]}),y.profile.organization?.rate_limit_tier&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Tier`}),(0,$.jsx)(`span`,{children:y.profile.organization.rate_limit_tier})]}),y.profile.organization?.subscription_status&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Status`}),(0,$.jsx)(`span`,{children:y.profile.organization.subscription_status})]})]}),(0,$.jsx)(or,{accountId:y.accountId})]}),(0,$.jsxs)(`div`,{className:`border-t border-border pt-2 flex gap-1.5 shrink-0`,children:[(0,$.jsxs)(`button`,{onClick:()=>S(!0),className:`flex-1 flex items-center justify-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] text-text-secondary hover:bg-surface-hover transition-colors cursor-pointer`,children:[(0,$.jsx)(ve,{className:`size-3`}),` Add`]}),(0,$.jsxs)(`button`,{onClick:oe,className:`flex-1 flex items-center justify-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] text-text-secondary hover:bg-surface-hover transition-colors cursor-pointer`,children:[(0,$.jsx)(X,{className:`size-3`}),` Export`]}),(0,$.jsxs)(`button`,{onClick:()=>A(!0),className:`flex-1 flex items-center justify-center gap-1 rounded-md border border-border px-2 py-1 text-[11px] text-text-secondary hover:bg-surface-hover transition-colors cursor-pointer`,children:[(0,$.jsx)(ae,{className:`size-3`}),` Import`]})]}),N&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-10 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-md`,children:(0,$.jsxs)(`div`,{className:`bg-surface border border-border rounded-lg shadow-lg p-4 mx-4 max-w-[280px] w-full space-y-3`,children:[(0,$.jsxs)(`p`,{className:`text-xs text-text-primary text-center`,children:[`Remove `,(0,$.jsx)(`strong`,{className:`text-foreground`,children:N.display}),`?`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`button`,{onClick:()=>P(null),className:`flex-1 px-3 py-1.5 rounded-md text-xs border border-border text-text-secondary hover:bg-surface-hover cursor-pointer transition-colors`,children:`Cancel`}),(0,$.jsx)(`button`,{onClick:ie,className:`flex-1 px-3 py-1.5 rounded-md text-xs bg-red-500 text-white hover:bg-red-600 cursor-pointer transition-colors`,children:`Remove`})]})]})}),(0,$.jsx)(Wn,{open:ee,onOpenChange:S,onSuccess:H}),(0,$.jsx)(Gn,{open:C,onOpenChange:e=>{E(e),e||F(null)},accounts:l,preselectId:te,onMessage:V}),(0,$.jsx)(Kn,{open:D,onOpenChange:A,onSuccess:H}),(0,$.jsx)(Qn,{open:j,onOpenChange:M})]})}var gr={active:`bg-green-500`,idle:`bg-yellow-500`,shutdown:`bg-zinc-400`},_r={task_assignment:{label:`task`,className:`bg-blue-500/20 text-blue-400`},idle_notification:{label:`idle`,className:`bg-yellow-500/20 text-yellow-400`},completion:{label:`done`,className:`bg-green-500/20 text-green-400`},shutdown_request:{label:`shutdown`,className:`bg-red-500/20 text-red-400`},shutdown_approved:{label:`shutdown ✓`,className:`bg-zinc-500/20 text-zinc-400`}};function vr({teamNames:e,messages:t}){let[n,r]=(0,Q.useState)(e[0]??``),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{e.length>0&&!e.includes(n)&&r(e[0])},[e,n]);let l=(0,Q.useCallback)(async e=>{s(!0);try{a((await y.get(`/api/teams/${encodeURIComponent(e)}`))?.members??[])}catch{a([])}s(!1)},[]);(0,Q.useEffect)(()=>{n&&l(n)},[n,l]),(0,Q.useEffect)(()=>{c.current?.scrollIntoView({behavior:`smooth`})},[t.length]);let u=t.slice(-200);return(0,$.jsxs)(`div`,{className:`space-y-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 mb-2`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1 overflow-x-auto min-w-0 flex-1`,children:e.map(e=>(0,$.jsx)(`button`,{onClick:()=>r(e),className:m(`px-2 py-0.5 text-[11px] rounded-md whitespace-nowrap transition-colors`,n===e?`bg-primary/10 text-primary font-medium`:`text-text-subtle hover:text-text-primary`),children:e},e))}),(0,$.jsx)(`button`,{onClick:()=>n&&l(n),className:`text-text-subtle hover:text-foreground p-1 shrink-0`,"aria-label":`Refresh`,children:(0,$.jsx)(ke,{className:m(`size-3`,o&&`animate-spin`)})})]}),i.length>0&&(0,$.jsxs)(`div`,{className:`pb-2 mb-2 border-b border-border/30`,children:[(0,$.jsx)(`div`,{className:`text-[10px] text-text-subtle uppercase tracking-wider mb-1`,children:`Members`}),(0,$.jsx)(`div`,{className:`space-y-1`,children:i.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`span`,{className:m(`size-1.5 rounded-full shrink-0`,gr[e.status]??`bg-zinc-400`)}),(0,$.jsx)(`span`,{className:`font-medium truncate`,children:e.name}),e.model&&e.model!==`unknown`&&(0,$.jsxs)(`span`,{className:`text-text-subtle text-[10px]`,children:[`(`,e.model,`)`]}),(0,$.jsx)(`span`,{className:`ml-auto text-text-subtle text-[10px]`,children:e.status})]},e.name))})]}),(0,$.jsx)(`div`,{className:`max-h-40 overflow-y-auto`,children:u.length===0?(0,$.jsx)(`p`,{className:`text-xs text-text-subtle text-center py-2`,children:`No messages yet`}):(0,$.jsxs)(`div`,{className:`space-y-2`,children:[u.map((e,t)=>{let n=e.parsedType?_r[e.parsedType]:null,r=yr(e.timestamp);return(0,$.jsxs)(`div`,{className:`text-xs`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-text-subtle`,children:[(0,$.jsx)(`span`,{className:`font-medium`,style:br(e.color),children:e.from}),(0,$.jsx)(`span`,{children:`→`}),(0,$.jsx)(`span`,{children:e.to}),(0,$.jsx)(`span`,{className:`ml-auto text-[10px]`,children:r})]}),(0,$.jsxs)(`div`,{className:`mt-0.5 text-foreground/90 break-words`,children:[n&&(0,$.jsx)(`span`,{className:m(`inline-block px-1 py-0 rounded text-[9px] mr-1`,n.className),children:n.label}),e.summary??xr(e.text)]})]},`${e.timestamp}-${t}`)}),(0,$.jsx)(`div`,{ref:c})]})})]})}function yr(e){try{return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}catch{return``}}function br(e){if(e&&(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^[a-zA-Z]{3,20}$/.test(e)))return{color:e}}function xr(e,t=120){if(!e)return``;try{let n=JSON.parse(e);return n.summary??n.text??e.slice(0,t)}catch{}return e.length>t?e.slice(0,t)+`...`:e}function Sr(e){try{return new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}catch{return``}}function Cr(e){return e>=90?`text-red-500`:e>=70?`text-amber-500`:`text-green-500`}function wr({sessionId:e,projectName:t}){let[n,r]=(0,Q.useState)(!1);return(0,$.jsx)(`button`,{onClick:()=>{try{let n=y.get(`${_(t)}/chat/sessions/${e}/debug?project=${encodeURIComponent(t)}`).then(e=>{let t=[`PPM Session: ${e.ppmSessionId}`,`SDK Session: ${e.sdkSessionId}`,e.jsonlPath?`JSONL: ${e.jsonlPath}`:`JSONL: not found`,e.projectPath?`Project: ${e.projectPath}`:null].filter(Boolean).join(`
9
9
  `);return new Blob([t],{type:`text/plain`})});navigator.clipboard.write([new ClipboardItem({"text/plain":n})]).then(()=>{r(!0),setTimeout(()=>r(!1),1500)})}catch{}},className:`p-1 rounded transition-colors ${n?`text-green-500 bg-green-500/10`:`text-text-subtle hover:text-text-secondary hover:bg-surface-elevated`}`,title:n?`Copied!`:`Copy session debug info`,children:n?(0,$.jsx)(Be,{className:`size-3`}):(0,$.jsx)(z,{className:`size-3`})})}function Tr({projectName:e,usageInfo:t,compactStatus:n,usageLoading:r,refreshUsage:i,lastFetchedAt:o,sessionId:s,providerId:c,onSelectSession:l,onBugReport:u,isConnected:d,onReconnect:f,teamActivity:p,teamMessages:m,onTeamOpen:h}){let[g,v]=(0,Q.useState)(null),[b,x]=(0,Q.useState)([]),[ee,S]=(0,Q.useState)(!1),C=te(e=>s?e.notifications.has(s):!1),w=te(e=>e.clearForSession),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(``),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),F=(0,Q.useRef)(null),I=H(e=>e.openTab),L=e=>{v(t=>t===e?null:e)},ne=(0,Q.useCallback)(async()=>{if(e){S(!0);try{let t=await y.get(`${_(e)}/chat/sessions?limit=50&offset=0`);x(t.sessions),M(t.hasMore)}catch{}finally{S(!1)}}},[e]),R=(0,Q.useCallback)(async()=>{if(!(!e||N||!j)){P(!0);try{let t=b.filter(e=>!e.pinned).length,n=await y.get(`${_(e)}/chat/sessions?limit=50&offset=${t}`);x(e=>{let t=new Set(e.map(e=>e.id)),r=n.sessions.filter(e=>!t.has(e.id));return[...e,...r]}),M(n.hasMore)}catch{}finally{P(!1)}}},[e,N,j,b]);(0,Q.useEffect)(()=>{g===`history`&&b.length===0&&ne()},[g]);function z(t){l?(l(t),v(null)):I({type:`chat`,title:t.title||`Chat`,projectId:e??null,metadata:{projectName:e,sessionId:t.id,providerId:t.providerId},closable:!0})}let V=(0,Q.useCallback)((e,t)=>{t.stopPropagation(),O(e.id),A(e.title||``),setTimeout(()=>F.current?.select(),0)},[]),W=(0,Q.useCallback)(async()=>{if(!D||!k.trim()||!e){O(null);return}try{await y.patch(`${_(e)}/chat/sessions/${D}`,{title:k.trim()}),x(e=>e.map(e=>e.id===D?{...e,title:k.trim()}:e))}catch{}O(null)},[D,k,e]),G=(0,Q.useCallback)(()=>O(null),[]),K=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),!e)return;let r=`${_(e)}/chat/sessions/${n.id}/pin`;try{n.pinned?await y.del(r):await y.put(r),x(e=>e.map(e=>e.id===n.id?{...e,pinned:!e.pinned}:e).sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()))}catch{}},[e]),re=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),e&&window.confirm(`Delete this session? This cannot be undone.`))try{await y.del(`${_(e)}/chat/sessions/${n.id}?providerId=${n.providerId}`),x(e=>e.filter(e=>e.id!==n.id))}catch{}},[e]),Y=T.trim()?b.filter(e=>(e.title||``).toLowerCase().includes(T.toLowerCase())):b,X=!c||c===`claude`,ie=t.fiveHour==null?null:Math.round(t.fiveHour*100),ae=t.sevenDay==null?null:Math.round(t.sevenDay*100),oe=ie!=null||ae!=null?Cr(Math.max(ie??0,ae??0)):`text-text-subtle`;return(0,$.jsxs)(`div`,{className:`border-b border-border/50`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1`,children:[(0,$.jsxs)(`button`,{onClick:()=>L(`history`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${g===`history`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,children:[(0,$.jsx)(Ue,{className:`size-3`}),(0,$.jsx)(`span`,{children:`History`})]}),s&&c&&c!==`mock`?(0,$.jsxs)(`button`,{onClick:()=>L(`config`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${g===`config`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`AI Settings`,children:[(0,$.jsx)(ce,{providerId:c}),(0,$.jsx)(`span`,{className:`capitalize`,children:c})]}):(0,$.jsx)(`button`,{onClick:()=>L(`config`),className:`p-1 rounded transition-colors ${g===`config`?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary hover:bg-surface-elevated`}`,title:`AI Settings`,children:(0,$.jsx)(Ze,{className:`size-3`})}),X?(0,$.jsxs)(`button`,{onClick:()=>L(`usage`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium tabular-nums transition-colors hover:bg-surface-elevated ${g===`usage`?`bg-primary/10`:``} ${oe}`,title:`Usage limits`,children:[(0,$.jsx)(Re,{className:`size-3`}),t.activeAccountLabel&&(0,$.jsxs)(`span`,{className:`text-text-secondary font-normal truncate max-w-[60px]`,children:[`[`,t.activeAccountLabel,`]`]}),(0,$.jsxs)(`span`,{children:[`5h:`,ie==null?`--%`:`${ie}%`]}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Wk:`,ae==null?`--%`:`${ae}%`]}),n===`compacting`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`·`}),(0,$.jsx)(`span`,{className:`text-blue-400 animate-pulse`,children:`compacting...`})]})]}):n===`compacting`?(0,$.jsx)(`span`,{className:`text-[11px] px-1.5 py-0.5 text-blue-400 animate-pulse`,children:`compacting...`}):null,p?.hasTeams&&(0,$.jsxs)(`button`,{onClick:()=>{L(`team`),h?.()},className:`relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${g===`team`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`Team activity`,children:[(0,$.jsx)(tt,{className:`size-3`}),(0,$.jsx)(`span`,{children:`Team`}),(p.unreadCount??0)>0&&(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 size-2 bg-primary rounded-full animate-pulse`})]}),(0,$.jsx)(`div`,{className:`flex-1`}),C&&s&&(0,$.jsx)(`button`,{onClick:()=>w(s),className:`p-1 rounded text-amber-500 hover:text-amber-400 hover:bg-surface-elevated transition-colors`,title:`Mark as read`,children:(0,$.jsx)(U,{className:`size-3`})}),s&&(0,$.jsx)(wr,{sessionId:s,projectName:e}),f&&(0,$.jsx)(`button`,{onClick:f,className:`size-4 flex items-center justify-center`,title:d?`Connected`:`Disconnected — click to reconnect`,children:(0,$.jsx)(`span`,{className:`size-2 rounded-full ${d?`bg-green-500`:`bg-red-500 animate-pulse`}`})})]}),g===`history`&&(0,$.jsxs)(`div`,{className:`border-t border-border/30 bg-surface`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2 py-1 border-b border-border/30`,children:[(0,$.jsx)(Ne,{className:`size-3 text-text-subtle shrink-0`}),(0,$.jsx)(`input`,{type:`text`,value:T,onChange:e=>E(e.target.value),placeholder:`Search sessions...`,className:`flex-1 bg-transparent text-[11px] text-text-primary outline-none placeholder:text-text-subtle`}),(0,$.jsx)(`button`,{onClick:ne,disabled:ee,className:`p-0.5 rounded text-text-subtle hover:text-text-secondary transition-colors disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(ke,{className:`size-3 ${ee?`animate-spin`:``}`})})]}),(0,$.jsx)(`div`,{className:`max-h-[200px] overflow-y-auto`,children:ee&&b.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(Z,{className:`size-3.5 animate-spin text-text-subtle`})}):Y.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3 text-[11px] text-text-subtle`,children:T?`No matching sessions`:`No sessions yet`}):(0,$.jsxs)($.Fragment,{children:[Y.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 w-full px-3 py-1.5 text-left hover:bg-surface-elevated transition-colors group`,children:[(0,$.jsx)(ce,{providerId:e.providerId}),D===e.id?(0,$.jsxs)(`form`,{className:`flex items-center gap-1 flex-1 min-w-0`,onSubmit:e=>{e.preventDefault(),W()},children:[(0,$.jsx)(`input`,{ref:F,value:k,onChange:e=>A(e.target.value),onBlur:W,onKeyDown:e=>{e.key===`Escape`&&G()},className:`flex-1 min-w-0 bg-surface-elevated text-[11px] text-text-primary px-1 py-0.5 rounded border border-border outline-none focus:border-primary`,autoFocus:!0}),(0,$.jsx)(`button`,{type:`submit`,className:`p-0.5 text-green-500 hover:text-green-400`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(q,{className:`size-3`})}),(0,$.jsx)(`button`,{type:`button`,className:`p-0.5 text-text-subtle hover:text-text-secondary`,onClick:e=>{e.stopPropagation(),G()},children:(0,$.jsx)(a,{className:`size-3`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{onClick:()=>z(e),className:`text-[11px] truncate flex-1 text-left flex items-center gap-1`,children:[e.title?.startsWith(`[PPM]`)&&(0,$.jsx)(B,{className:`size-3 text-muted-foreground shrink-0`}),e.title?.startsWith(`[PPM]`)?e.title.slice(7):e.title||`Untitled`]}),(0,$.jsx)(`button`,{onClick:t=>K(t,e),className:`p-0.5 rounded transition-all ${e.pinned?`text-primary hover:text-primary/70`:`text-text-subtle hover:text-text-secondary can-hover:opacity-0 can-hover:group-hover:opacity-100`}`,title:e.pinned?`Unpin session`:`Pin session`,children:e.pinned?(0,$.jsx)(je,{className:`size-3`}):(0,$.jsx)(Te,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:t=>V(e,t),className:`p-0.5 rounded text-text-subtle hover:text-text-secondary can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity`,title:`Rename session`,children:(0,$.jsx)(le,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:t=>re(t,e),className:`p-0.5 rounded text-text-subtle hover:text-red-400 hover:bg-red-500/20 can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity`,title:`Delete session`,children:(0,$.jsx)(J,{className:`size-3`})})]}),D!==e.id&&e.updatedAt&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0 w-10 text-right`,children:Sr(e.updatedAt)})]},e.id)),j&&!T&&(0,$.jsxs)(`button`,{onClick:R,disabled:N,className:`flex items-center justify-center gap-1 w-full py-1.5 text-[11px] text-text-subtle hover:text-text-secondary hover:bg-surface-elevated transition-colors`,children:[N?(0,$.jsx)(Z,{className:`size-3 animate-spin`}):null,N?`Loading...`:`Load more`]})]})})]}),g===`config`&&(0,$.jsx)(`div`,{className:`border-t border-border/30 bg-surface px-3 py-2 max-h-[280px] overflow-y-auto`,children:(0,$.jsx)(Ae,{compact:!0})}),g===`team`&&p?.hasTeams&&(0,$.jsx)(`div`,{className:`border-t border-border/30 bg-surface px-3 py-2 max-h-[280px] overflow-y-auto`,children:(0,$.jsx)(vr,{teamNames:p.teamNames,messages:m??[]})}),g===`usage`&&X&&(0,$.jsx)(hr,{usage:t,visible:!0,onClose:()=>v(null),onReload:i,loading:r,lastFetchedAt:o})]})}function Er({metadata:e,tabId:t}){let[n,r]=(0,Q.useState)(e?.sessionId??null),[i,a]=(0,Q.useState)(e?.providerId??`claude`),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)([]),[v,x]=(0,Q.useState)(!1),[ee,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)(e?.permissionMode??void 0),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(null),j=(0,Q.useRef)(0),M=e?.projectName??``,N=H(e=>e.updateTab),P=ie(e=>e.version),{usageInfo:F,usageLoading:I,lastFetchedAt:L,refreshUsage:ne}=gt(M,i);(0,Q.useEffect)(()=>{T||b().then(e=>{let t=e.providers[e.default_provider??`claude`];E(t?.permission_mode??`bypassPermissions`)}).catch(()=>{})},[]),(0,Q.useEffect)(()=>{!t||!n||N(t,{metadata:{...e,sessionId:n,providerId:i,permissionMode:T}})},[n,i,T]);let{messages:R,messagesLoading:z,isStreaming:B,phase:U,isReconnecting:W,connectingElapsed:G,pendingApproval:K,contextWindowPct:re,compactStatus:q,sessionTitle:J,migratedSessionId:Y,sendMessage:X,respondToApproval:oe,cancelStreaming:se,reconnect:ce,refetchMessages:le,isConnected:ue,teamActivity:de,teamMessages:fe,markTeamRead:pe}=mt(n,i,M);(0,Q.useEffect)(()=>{Y&&Y!==n&&r(Y)},[Y]),(0,Q.useEffect)(()=>{if(!n||!t)return;let e=()=>{if(document.hidden)return;let{panels:e,focusedPanelId:r}=V.getState();e[r]?.activeTabId===t&&te.getState().clearForSession(n)};e(),document.addEventListener(`visibilitychange`,e);let r=V.subscribe(e);return()=>{document.removeEventListener(`visibilitychange`,e),r()}},[n,t]),(0,Q.useEffect)(()=>{t&&J&&N(t,{title:J})},[J]);let[me,he]=(0,Q.useState)(e?.pendingMessage);(0,Q.useEffect)(()=>{me&&ue&&n&&t&&N(t,{metadata:{...e,pendingMessage:void 0}})},[ue,n]),(0,Q.useCallback)(()=>{H.getState().openTab({type:`chat`,title:`AI Chat`,metadata:{projectName:M,providerId:i},projectId:M||null,closable:!0})},[M,i]);let ge=(0,Q.useCallback)(e=>{r(e.id),a(e.providerId),t&&N(t,{title:e.title||`Chat`})},[t,N]),ve=(0,Q.useCallback)(async(e,t)=>{if(!(!n||!M))try{let{api:r,projectUrl:a}=await f(async()=>{let{api:e,projectUrl:t}=await import(`./api-client-BfBM3I7n.js`).then(e=>e.n);return{api:e,projectUrl:t}},__vite__mapDeps([0,1])),o=await r.post(`${a(M)}/chat/sessions/${n}/fork?providerId=${i}`,{messageId:t});H.getState().openTab({type:`chat`,title:`Fork: ${e.slice(0,30)}`,metadata:{projectName:M,sessionId:o.id,providerId:i,pendingMessage:e},projectId:M||null,closable:!0})}catch(e){console.error(`Fork failed:`,e)}},[n,M,i]),ye=(0,Q.useCallback)((e,t)=>{if(t.length===0)return e;let n=t.filter(e=>e.serverPath).map(e=>e.serverPath).join(`
@@ -1,5 +1,5 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/csv-preview-D2pJJj3K.js","assets/chunk-CFjPhJqf.js","assets/lib-DurwGtQO.js","assets/react-nm2Ru1Pt.js","assets/createLucideIcon-PuMiQgHl.js","assets/arrow-up-BYhx9ckd.js","assets/react-dom-Bpkvzu3U.js","assets/jsx-runtime-kMwlnEGE.js","assets/csv-parser-CNNw2RVA.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import"./react-dom-Bpkvzu3U.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{t as r}from"./chevron-right-4zq1jPv6.js";import{n as i,t as a}from"./markdown-renderer-BP1o2VVM.js";import{t as o}from"./table-DFevCOMd.js";import{t as s}from"./text-wrap-BWNOVswA.js";import{t as c}from"./preload-helper-Bf_JiD2A.js";import{t as l}from"./jsx-runtime-kMwlnEGE.js";import"./dist-DIV6WgAG.js";import{t as u}from"./utils-BNytJOb1.js";import{i as d,r as f,t as p}from"./api-client-BfBM3I7n.js";import{Ct as m,Et as ee,K as h,R as g,S as _,St as v,Tt as y,Y as te,_ as b,_t as x,a as ne,at as re,b as S,bt as C,g as w,pt as T,v as E,vt as ie,w as ae,wt as D,x as O,xt as k,y as A,yt as j}from"./index-DmuOwe2C.js";import"./chunk-GEFDOKGD-D-pKjlVd.js";import"./src-BqX54PbV.js";import"./chunk-7R4GIKGN-Dv-4cAYn.js";import"./chunk-HHEYEP7N-C7vxA5i9.js";import"./dist-CSJdAyA9.js";import"./chunk-PU5JKC2W-ek7k4QVB.js";import"./chunk-MX3YWQON-BpS_PtKp.js";import"./chunk-YBOYWFTD-rQG3QH5s.js";import"./chunk-PQ6SQG4A-TF58UVMU.js";import"./chunk-KYZI473N-Bb0MCaIO.js";import"./chunk-O4XLMI2P-nDhi_cVu.js";import"./chunk-GLR3WWYH-DKikpoJM.js";import"./chunk-XPW4576I-BPQQBakK.js";import{n as oe,t as se}from"./use-monaco-theme-COffNaVJ.js";import{n as ce,t as le}from"./sql-completion-provider-DM9Qov6L.js";var M=n(`file-exclamation-point`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),N=e(t(),1),P=l(),ue={ts:k,tsx:k,js:k,jsx:k,py:k,rs:k,go:k,html:k,css:k,scss:k,json:v,md:C,txt:C,yaml:j,yml:j};function de(e,t){return t?x:ue[e.split(`.`).pop()?.toLowerCase()??``]??ie}function F(e,t){let n=[],r=e;for(let e=0;e<t.length;e++){let i=t[e],a=t.slice(0,e+1).join(`/`),o=r.find(e=>e.name===i);if(n.push({name:i,fullPath:a,node:o??null,siblings:r}),o?.children)r=o.children;else{for(let r=e+1;r<t.length;r++)n.push({name:t[r],fullPath:t.slice(0,r+1).join(`/`),node:null,siblings:[]});break}}return n}function I(e){return[...e].sort((e,t)=>e.type===t.type?e.name.localeCompare(t.name):e.type===`directory`?-1:1)}function fe({filePath:e,projectName:t,tabId:n,className:i}){let a=g(e=>e.tree),{updateTab:o,openTab:s}=h(),c=(0,N.useRef)(null),l=(0,N.useMemo)(()=>F(a,e.split(`/`).filter(Boolean)),[a,e]);(0,N.useEffect)(()=>{c.current&&(c.current.scrollLeft=c.current.scrollWidth)},[l]);function d(e,r){let i=u(e);r.metaKey||r.ctrlKey?s({type:`editor`,title:i,metadata:{filePath:e,projectName:t},projectId:t,closable:!0}):o(n,{title:i,metadata:{filePath:e,projectName:t}})}return(0,P.jsx)(`div`,{ref:c,className:i,children:l.map((e,n)=>(0,P.jsxs)(`div`,{className:`flex items-center shrink-0`,children:[n>0&&(0,P.jsx)(r,{className:`size-3 text-muted-foreground shrink-0 mx-0.5`}),e.siblings.length>0?(0,P.jsx)(pe,{segment:e,isLast:n===l.length-1,projectName:t,onFileClick:d}):(0,P.jsx)(`span`,{className:`text-xs text-muted-foreground px-1 py-0.5`,children:e.name})]},e.fullPath))})}function pe({segment:e,isLast:t,projectName:n,onFileClick:r}){let i=(0,N.useMemo)(()=>I(e.siblings),[e.siblings]);return(0,P.jsxs)(w,{children:[(0,P.jsx)(_,{asChild:!0,children:(0,P.jsx)(`button`,{type:`button`,className:`text-xs px-1 py-0.5 rounded hover:bg-muted transition-colors truncate max-w-[120px] ${t?`text-foreground font-medium`:`text-muted-foreground`}`,children:e.name})}),(0,P.jsx)(b,{align:`start`,className:`max-h-[300px] p-1`,children:i.map(t=>(0,P.jsx)(L,{node:t,projectName:n,activePath:e.fullPath,onFileClick:r},t.path))})]})}function L({node:e,projectName:t,activePath:n,onFileClick:r}){let i=de(e.name,e.type===`directory`),a=e.path===n;return e.type===`directory`&&e.children&&e.children.length>0?(0,P.jsxs)(A,{children:[(0,P.jsxs)(O,{className:`text-xs gap-1.5 ${a?`bg-muted`:``}`,children:[(0,P.jsx)(i,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,P.jsx)(`span`,{className:`truncate`,children:e.name})]}),(0,P.jsx)(S,{className:`max-h-[300px] overflow-y-auto p-1`,children:I(e.children).map(e=>(0,P.jsx)(L,{node:e,projectName:t,activePath:n,onFileClick:r},e.path))})]}):(0,P.jsxs)(E,{className:`text-xs gap-1.5 cursor-pointer ${a?`bg-muted`:``}`,onSelect:e=>{},onClick:t=>{e.type!==`directory`&&r(e.path,t)},children:[(0,P.jsx)(i,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,P.jsx)(`span`,{className:`truncate`,children:e.name})]})}function R({active:e,onClick:t,icon:n,label:r}){return(0,P.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-1 px-2 py-1 rounded text-xs transition-colors ${e?`bg-muted text-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[(0,P.jsx)(n,{className:`size-3`}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:r})]})}function me({ext:e,mdMode:t,onMdModeChange:n,csvMode:r,onCsvModeChange:a,wordWrap:c,onToggleWordWrap:l,filePath:u,projectName:d,className:f}){return(0,P.jsxs)(`div`,{className:f,children:[(e===`md`||e===`mdx`)&&n&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(R,{active:t===`edit`,onClick:()=>n(`edit`),icon:i,label:`Edit`}),(0,P.jsx)(R,{active:t===`preview`,onClick:()=>n(`preview`),icon:m,label:`Preview`})]}),e===`csv`&&a&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(R,{active:r===`table`,onClick:()=>a(`table`),icon:o,label:`Table`}),(0,P.jsx)(R,{active:r===`raw`,onClick:()=>a(`raw`),icon:i,label:`Raw`})]}),(0,P.jsx)(R,{active:c,onClick:l,icon:s,label:`Wrap`}),u&&d&&(0,P.jsx)(R,{active:!1,onClick:()=>ae(d,u),icon:y,label:`Download`})]})}var he=(0,N.lazy)(()=>c(()=>import(`./csv-preview-D2pJJj3K.js`).then(e=>({default:e.CsvPreview})),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))),ge=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`]),_e=new Set([`db`,`sqlite`,`sqlite3`]);function z(e){return e.split(`.`).pop()?.toLowerCase()??``}function ve(e){return{js:`javascript`,jsx:`javascript`,ts:`typescript`,tsx:`typescript`,py:`python`,html:`html`,css:`css`,scss:`scss`,json:`json`,md:`markdown`,mdx:`markdown`,yaml:`yaml`,yml:`yaml`,sh:`shell`,bash:`shell`,sql:`sql`}[z(e)]??`plaintext`}function B({metadata:e,tabId:t}){let n=e?.filePath,r=e?.projectName,i=e?.inlineContent,a=e?.inlineLanguage,[o,s]=(0,N.useState)(i??null),[c,l]=(0,N.useState)(`utf-8`),[f,m]=(0,N.useState)(!0),[g,_]=(0,N.useState)(null),[v,y]=(0,N.useState)(!1),b=(0,N.useRef)(null),x=(0,N.useRef)(``),S=(0,N.useRef)(null),{tabs:C,updateTab:w}=h(),{wordWrap:E,toggleWordWrap:ie}=te(),ae=se(),D=C.find(e=>e.id===t),O=n?z(n):``,k=ge.has(O),A=O===`pdf`,j=_e.has(O),ue=O===`md`||O===`mdx`,de=O===`csv`,F=O===`sql`,[I,pe]=(0,N.useState)(`preview`),[L,R]=(0,N.useState)(`table`),{connections:B,cachedTables:Se,refreshTables:Ce}=ne(),[V,we]=(0,N.useState)(()=>{if(!F||!n)return null;let e=localStorage.getItem(`ppm:sql-conn:${n}`);return e?Number(e):null}),H=(0,N.useRef)(null),U=(0,N.useRef)(null),W=(0,N.useMemo)(()=>B.find(e=>e.id===V)??null,[B,V]),Te=i!=null&&(a===`json`||a===`xml`),[G,K]=(0,N.useState)(!1),Ee=(0,N.useCallback)(()=>{if(i)if(G)s(i),K(!1);else{let e=i.trimStart();if(a===`json`)try{s(JSON.stringify(JSON.parse(e),null,2)),K(!0)}catch{}else if(a===`xml`){let t=0;s(e.replace(/(>)(<)(\/*)/g,`$1
2
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import"./react-dom-Bpkvzu3U.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{t as r}from"./chevron-right-4zq1jPv6.js";import{n as i,t as a}from"./markdown-renderer-BinWj98E.js";import{t as o}from"./table-DFevCOMd.js";import{t as s}from"./text-wrap-BWNOVswA.js";import{t as c}from"./preload-helper-Bf_JiD2A.js";import{t as l}from"./jsx-runtime-kMwlnEGE.js";import"./dist-DIV6WgAG.js";import{t as u}from"./utils-BNytJOb1.js";import{i as d,r as f,t as p}from"./api-client-BfBM3I7n.js";import{Ct as m,Et as ee,K as h,R as g,S as _,St as v,Tt as y,Y as te,_ as b,_t as x,a as ne,at as re,b as S,bt as C,g as w,pt as T,v as E,vt as ie,w as ae,wt as D,x as O,xt as k,y as A,yt as j}from"./index-Y-Kfye7A.js";import"./chunk-GEFDOKGD-D-pKjlVd.js";import"./src-BqX54PbV.js";import"./chunk-7R4GIKGN-Dv-4cAYn.js";import"./chunk-HHEYEP7N-C7vxA5i9.js";import"./dist-CSJdAyA9.js";import"./chunk-PU5JKC2W-ek7k4QVB.js";import"./chunk-MX3YWQON-BpS_PtKp.js";import"./chunk-YBOYWFTD-rQG3QH5s.js";import"./chunk-PQ6SQG4A-TF58UVMU.js";import"./chunk-KYZI473N-Bb0MCaIO.js";import"./chunk-O4XLMI2P-nDhi_cVu.js";import"./chunk-GLR3WWYH-DKikpoJM.js";import"./chunk-XPW4576I-BPQQBakK.js";import{n as oe,t as se}from"./use-monaco-theme-Dl6w9X-L.js";import{n as ce,t as le}from"./sql-completion-provider-DM9Qov6L.js";var M=n(`file-exclamation-point`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),N=e(t(),1),P=l(),ue={ts:k,tsx:k,js:k,jsx:k,py:k,rs:k,go:k,html:k,css:k,scss:k,json:v,md:C,txt:C,yaml:j,yml:j};function de(e,t){return t?x:ue[e.split(`.`).pop()?.toLowerCase()??``]??ie}function F(e,t){let n=[],r=e;for(let e=0;e<t.length;e++){let i=t[e],a=t.slice(0,e+1).join(`/`),o=r.find(e=>e.name===i);if(n.push({name:i,fullPath:a,node:o??null,siblings:r}),o?.children)r=o.children;else{for(let r=e+1;r<t.length;r++)n.push({name:t[r],fullPath:t.slice(0,r+1).join(`/`),node:null,siblings:[]});break}}return n}function I(e){return[...e].sort((e,t)=>e.type===t.type?e.name.localeCompare(t.name):e.type===`directory`?-1:1)}function fe({filePath:e,projectName:t,tabId:n,className:i}){let a=g(e=>e.tree),{updateTab:o,openTab:s}=h(),c=(0,N.useRef)(null),l=(0,N.useMemo)(()=>F(a,e.split(`/`).filter(Boolean)),[a,e]);(0,N.useEffect)(()=>{c.current&&(c.current.scrollLeft=c.current.scrollWidth)},[l]);function d(e,r){let i=u(e);r.metaKey||r.ctrlKey?s({type:`editor`,title:i,metadata:{filePath:e,projectName:t},projectId:t,closable:!0}):o(n,{title:i,metadata:{filePath:e,projectName:t}})}return(0,P.jsx)(`div`,{ref:c,className:i,children:l.map((e,n)=>(0,P.jsxs)(`div`,{className:`flex items-center shrink-0`,children:[n>0&&(0,P.jsx)(r,{className:`size-3 text-muted-foreground shrink-0 mx-0.5`}),e.siblings.length>0?(0,P.jsx)(pe,{segment:e,isLast:n===l.length-1,projectName:t,onFileClick:d}):(0,P.jsx)(`span`,{className:`text-xs text-muted-foreground px-1 py-0.5`,children:e.name})]},e.fullPath))})}function pe({segment:e,isLast:t,projectName:n,onFileClick:r}){let i=(0,N.useMemo)(()=>I(e.siblings),[e.siblings]);return(0,P.jsxs)(w,{children:[(0,P.jsx)(_,{asChild:!0,children:(0,P.jsx)(`button`,{type:`button`,className:`text-xs px-1 py-0.5 rounded hover:bg-muted transition-colors truncate max-w-[120px] ${t?`text-foreground font-medium`:`text-muted-foreground`}`,children:e.name})}),(0,P.jsx)(b,{align:`start`,className:`max-h-[300px] p-1`,children:i.map(t=>(0,P.jsx)(L,{node:t,projectName:n,activePath:e.fullPath,onFileClick:r},t.path))})]})}function L({node:e,projectName:t,activePath:n,onFileClick:r}){let i=de(e.name,e.type===`directory`),a=e.path===n;return e.type===`directory`&&e.children&&e.children.length>0?(0,P.jsxs)(A,{children:[(0,P.jsxs)(O,{className:`text-xs gap-1.5 ${a?`bg-muted`:``}`,children:[(0,P.jsx)(i,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,P.jsx)(`span`,{className:`truncate`,children:e.name})]}),(0,P.jsx)(S,{className:`max-h-[300px] overflow-y-auto p-1`,children:I(e.children).map(e=>(0,P.jsx)(L,{node:e,projectName:t,activePath:n,onFileClick:r},e.path))})]}):(0,P.jsxs)(E,{className:`text-xs gap-1.5 cursor-pointer ${a?`bg-muted`:``}`,onSelect:e=>{},onClick:t=>{e.type!==`directory`&&r(e.path,t)},children:[(0,P.jsx)(i,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,P.jsx)(`span`,{className:`truncate`,children:e.name})]})}function R({active:e,onClick:t,icon:n,label:r}){return(0,P.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-1 px-2 py-1 rounded text-xs transition-colors ${e?`bg-muted text-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[(0,P.jsx)(n,{className:`size-3`}),(0,P.jsx)(`span`,{className:`hidden sm:inline`,children:r})]})}function me({ext:e,mdMode:t,onMdModeChange:n,csvMode:r,onCsvModeChange:a,wordWrap:c,onToggleWordWrap:l,filePath:u,projectName:d,className:f}){return(0,P.jsxs)(`div`,{className:f,children:[(e===`md`||e===`mdx`)&&n&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(R,{active:t===`edit`,onClick:()=>n(`edit`),icon:i,label:`Edit`}),(0,P.jsx)(R,{active:t===`preview`,onClick:()=>n(`preview`),icon:m,label:`Preview`})]}),e===`csv`&&a&&(0,P.jsxs)(P.Fragment,{children:[(0,P.jsx)(R,{active:r===`table`,onClick:()=>a(`table`),icon:o,label:`Table`}),(0,P.jsx)(R,{active:r===`raw`,onClick:()=>a(`raw`),icon:i,label:`Raw`})]}),(0,P.jsx)(R,{active:c,onClick:l,icon:s,label:`Wrap`}),u&&d&&(0,P.jsx)(R,{active:!1,onClick:()=>ae(d,u),icon:y,label:`Download`})]})}var he=(0,N.lazy)(()=>c(()=>import(`./csv-preview-D2pJJj3K.js`).then(e=>({default:e.CsvPreview})),__vite__mapDeps([0,1,2,3,4,5,6,7,8]))),ge=new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`]),_e=new Set([`db`,`sqlite`,`sqlite3`]);function z(e){return e.split(`.`).pop()?.toLowerCase()??``}function ve(e){return{js:`javascript`,jsx:`javascript`,ts:`typescript`,tsx:`typescript`,py:`python`,html:`html`,css:`css`,scss:`scss`,json:`json`,md:`markdown`,mdx:`markdown`,yaml:`yaml`,yml:`yaml`,sh:`shell`,bash:`shell`,sql:`sql`}[z(e)]??`plaintext`}function B({metadata:e,tabId:t}){let n=e?.filePath,r=e?.projectName,i=e?.inlineContent,a=e?.inlineLanguage,[o,s]=(0,N.useState)(i??null),[c,l]=(0,N.useState)(`utf-8`),[f,m]=(0,N.useState)(!0),[g,_]=(0,N.useState)(null),[v,y]=(0,N.useState)(!1),b=(0,N.useRef)(null),x=(0,N.useRef)(``),S=(0,N.useRef)(null),{tabs:C,updateTab:w}=h(),{wordWrap:E,toggleWordWrap:ie}=te(),ae=se(),D=C.find(e=>e.id===t),O=n?z(n):``,k=ge.has(O),A=O===`pdf`,j=_e.has(O),ue=O===`md`||O===`mdx`,de=O===`csv`,F=O===`sql`,[I,pe]=(0,N.useState)(`preview`),[L,R]=(0,N.useState)(`table`),{connections:B,cachedTables:Se,refreshTables:Ce}=ne(),[V,we]=(0,N.useState)(()=>{if(!F||!n)return null;let e=localStorage.getItem(`ppm:sql-conn:${n}`);return e?Number(e):null}),H=(0,N.useRef)(null),U=(0,N.useRef)(null),W=(0,N.useMemo)(()=>B.find(e=>e.id===V)??null,[B,V]),Te=i!=null&&(a===`json`||a===`xml`),[G,K]=(0,N.useState)(!1),Ee=(0,N.useCallback)(()=>{if(i)if(G)s(i),K(!1);else{let e=i.trimStart();if(a===`json`)try{s(JSON.stringify(JSON.parse(e),null,2)),K(!0)}catch{}else if(a===`xml`){let t=0;s(e.replace(/(>)(<)(\/*)/g,`$1
3
3
  $2$3`).split(`
4
4
  `).map(e=>{let n=e.trim();n.startsWith(`</`)&&(t=Math.max(0,t-1));let r=` `.repeat(t)+n;return n.startsWith(`<`)&&!n.startsWith(`</`)&&!n.endsWith(`/>`)&&!n.includes(`</`)&&t++,r}).join(`
5
5
  `)),K(!0)}}},[i,a,G]),De=(0,N.useCallback)(e=>{we(e),n&&localStorage.setItem(`ppm:sql-conn:${n}`,String(e)),Ce(e).catch(()=>{})},[n,Ce]),q=(0,N.useMemo)(()=>{if(!F||!V)return;let e=(Se.get(V)??[]).map(e=>({name:e.tableName,schema:e.schemaName}));if(e.length!==0)return{tables:e,getColumns:async(e,t)=>p.get(`/api/db/connections/${V}/schema?table=${encodeURIComponent(e)}${t?`&schema=${encodeURIComponent(t)}`:``}`)}},[F,V,Se]);(0,N.useEffect)(()=>{if(!(!H.current||!q))return U.current?.dispose(),le(),U.current=H.current.languages.registerCompletionItemProvider(`sql`,ce(H.current,q)),()=>{U.current?.dispose()}},[q]);let Oe=h(e=>e.openTab),J=(0,N.useCallback)(e=>{W&&Oe({type:`database`,title:`${W.name} · Query`,projectId:null,closable:!0,metadata:{connectionId:W.id,connectionName:W.name,dbType:W.type,initialSql:e}})},[W,Oe]),ke=(0,N.useCallback)(()=>{if(!S.current||!W)return;let e=S.current,t=e.getSelection();J(t&&!t.isEmpty()?e.getModel()?.getValueInRange(t)??e.getValue():e.getValue())},[W,J]),Y=(0,N.useRef)([]),X=(0,N.useRef)(J);X.current=J,(0,N.useEffect)(()=>{j&&t&&w(t,{type:`sqlite`})},[j,t,w]);let Z=n?/^(\/|[A-Za-z]:[/\\])/.test(n):!1;(0,N.useEffect)(()=>{if(i!=null){m(!1);return}if(!n||!Z&&!r)return;if(k||A){m(!1);return}m(!0),_(null);let e=Z?`/api/fs/read?path=${encodeURIComponent(n)}`:`${d(r)}/files/read?path=${encodeURIComponent(n)}`;return p.get(e).then(e=>{s(e.content),e.encoding&&l(e.encoding),x.current=e.content,m(!1)}).catch(e=>{_(e instanceof Error?e.message:`Failed to load file`),m(!1)}),()=>{b.current&&clearTimeout(b.current)}},[n,r,k,A,Z]),(0,N.useEffect)(()=>{if(!D)return;let e=n?u(n):`Untitled`,t=v?`${e} \u25CF`:e;D.title!==t&&w(D.id,{title:t})},[v]);let Ae=(0,N.useCallback)(async e=>{if(n&&!(!Z&&!r))try{Z?await p.put(`/api/fs/write`,{path:n,content:e}):await p.put(`${d(r)}/files/write`,{path:n,content:e}),y(!1)}catch{}},[n,r,Z]);function je(e){let t=e??``;s(t),x.current=t,y(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>Ae(x.current),1e3)}let Q=e?.lineNumber,Me=(0,N.useCallback)((e,t)=>{if(S.current=e,H.current=t,Q&&Q>0&&setTimeout(()=>{e.revealLineInCenter(Q),e.setPosition({lineNumber:Q,column:1}),e.focus()},100),e.addCommand(t.KeyMod.Alt|t.KeyCode.KeyZ,()=>te.getState().toggleWordWrap()),t.languages.typescript.typescriptDefaults.setDiagnosticsOptions({noSemanticValidation:!0,noSyntaxValidation:!0,noSuggestionDiagnostics:!0}),t.languages.typescript.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!0,noSyntaxValidation:!0,noSuggestionDiagnostics:!0}),q&&(U.current?.dispose(),U.current=t.languages.registerCompletionItemProvider(`sql`,ce(t,q))),F){Y.current.forEach(e=>e.dispose()),Y.current=[];let n=e.addCommand(0,(e,t)=>{t&&X.current(t)});if(n){let e=t.languages.registerCodeLensProvider(`sql`,{provideCodeLenses:e=>{let t=[],r=e.getValue().split(`
@@ -1,2 +1,2 @@
1
- import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{n as r,t as i}from"./x-D2_KzIET.js";import{t as a}from"./chevron-right-4zq1jPv6.js";import{t as o}from"./jsx-runtime-kMwlnEGE.js";import{t as s}from"./api-client-BfBM3I7n.js";import{Ct as c,Et as l,K as u,Mt as d,Nt as f,Q as p,Tt as m,it as h,mt as g,ot as _,pt as v,rt as y,st as b,tt as x}from"./index-DmuOwe2C.js";import"./use-monaco-theme-COffNaVJ.js";import{t as S}from"./sql-query-editor-CqVt5FDX.js";import{n as C}from"./csv-parser-CNNw2RVA.js";var w=n(`columns-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]]),T=n(`funnel`,[[`path`,{d:`M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z`,key:`sc7q7i`}]]),E=e(t(),1);function D(e,t,n,r){return`ppm-db-${e}-${n}.${t}-p${r}`}function O(e,t,n,r){try{let i=sessionStorage.getItem(D(e,t,n,r));return i?JSON.parse(i):null}catch{return null}}function ee(e,t,n,r,i,a){try{sessionStorage.setItem(D(e,t,n,r),JSON.stringify({data:i,cols:a}))}catch{}}function k(e){let t=`/api/db/connections/${e}`,[n,r]=(0,E.useState)(null),[i,a]=(0,E.useState)(`public`),[o,c]=(0,E.useState)(null),[l,u]=(0,E.useState)([]),[d,f]=(0,E.useState)(!1),[p,m]=(0,E.useState)(null),[h,g]=(0,E.useState)(1),[_,v]=(0,E.useState)(null),[y,b]=(0,E.useState)(null),[x,S]=(0,E.useState)(!1),[C,w]=(0,E.useState)(null),[T,D]=(0,E.useState)(`ASC`),k=(0,E.useCallback)(async(r,a,o,l,d)=>{let p=r??n,g=a??i;if(!p)return;f(!0);let _=l===void 0?C:l,v=d??T;try{let n=_?`&orderBy=${encodeURIComponent(_)}&orderDir=${v}`:``,[r,i]=await Promise.all([s.get(`${t}/data?table=${encodeURIComponent(p)}&schema=${g}&page=${o??h}&limit=100${n}`),s.get(`${t}/schema?table=${encodeURIComponent(p)}&schema=${g}`)]);c(r),u(i),ee(e,p,g,o??h,r,i)}catch(e){m(e.message)}finally{f(!1)}},[t,e,n,i,h,C,T]),A=(0,E.useCallback)((t,n=`public`)=>{r(t),a(n),g(1),v(null);let i=O(e,t,n,1);i?(c(i.data),u(i.cols),f(!1),k(t,n,1)):k(t,n,1)},[e,k]),j=(0,E.useCallback)(e=>{g(e),k(void 0,void 0,e)},[k]),te=(0,E.useCallback)(async e=>{S(!0),b(null);try{let r=await s.post(`${t}/query`,{sql:e});v(r),r.changeType===`modify`&&k(n??void 0,i)}catch(e){b(e.message)}finally{S(!1)}},[t,n,i,k]),M=(0,E.useCallback)(async(e,r,a,o)=>{if(!n)return;let c=n,l=i;try{await s.put(`${t}/cell`,{table:c,schema:l,pkColumn:e,pkValue:r,column:a,value:o}),k(c,l)}catch(e){m(e.message)}},[t,n,i,k]),N=(0,E.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.del(`${t}/row`,{table:a,schema:o,pkColumn:e,pkValue:r}),k(a,o)}catch(e){m(e.message)}},[t,n,i,k]);return{selectedTable:n,selectedSchema:i,selectTable:A,tableData:o,schema:l,loading:d,error:p,page:h,setPage:j,orderBy:C,orderDir:T,toggleSort:(0,E.useCallback)(e=>{let t,n=`ASC`;C===e?T===`ASC`?(t=e,n=`DESC`):(t=null,n=`ASC`):(t=e,n=`ASC`),w(t),D(n),g(1),k(void 0,void 0,1,t,n)},[C,T,k]),queryResult:_,queryError:y,queryLoading:x,executeQuery:te,updateCell:M,deleteRow:N,bulkDelete:(0,E.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.post(`${t}/rows/delete`,{table:a,schema:o,pkColumn:e,pkValues:r}),k(a,o)}catch(e){m(e.message)}},[t,n,i,k]),insertRow:(0,E.useCallback)(async e=>{if(!n)return;let r=n,a=i;try{await s.post(`${t}/row`,{table:r,schema:a,values:e}),k(r,a)}catch(e){throw m(e.message),e}},[t,n,i,k]),refreshData:k,queryAsTable:(0,E.useCallback)(async e=>{f(!0);try{let n=await s.post(`${t}/query`,{sql:e});n.changeType===`select`&&c({columns:n.columns,rows:n.rows,total:n.rows.length,page:1,limit:n.rows.length})}catch(e){m(e.message)}finally{f(!1)}},[t])}}var A=o();function j(e,t,n){let r=new Blob([t],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=e,a.click(),URL.revokeObjectURL(i)}function te({columns:e,rows:t,filename:n=`export`,exportAllUrl:r}){let[i,a]=(0,E.useState)(!1),[o,s]=(0,E.useState)(!1),c=(0,E.useRef)(null);(0,E.useEffect)(()=>{if(!i)return;let e=e=>{c.current&&!c.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let l=()=>{let r=C(e,t.map(t=>e.map(e=>String(t[e]??``))));j(`${n}.csv`,r,`text/csv`),a(!1)},u=()=>{let e=JSON.stringify(t,null,2);j(`${n}.json`,e,`application/json`),a(!1)},d=async e=>{if(r){s(!0);try{let t=await(await fetch(`${r}&format=${e}&limit=10000`)).text(),i=e===`csv`?`text/csv`:`application/json`;j(`${n}-all.${e}`,t,i)}catch{}s(!1),a(!1)}};return e.length===0||t.length===0?null:(0,A.jsxs)(`div`,{className:`relative`,ref:c,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`p-1 rounded text-muted-foreground hover:text-foreground transition-colors`,title:`Export`,children:(0,A.jsx)(m,{className:`size-3.5`})}),i&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 z-50 bg-popover border border-border rounded-md shadow-md py-1 min-w-[160px] text-xs`,children:[(0,A.jsx)(`button`,{onClick:l,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (CSV)`}),(0,A.jsx)(`button`,{onClick:u,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (JSON)`}),r&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`border-t border-border my-1`}),(0,A.jsx)(`button`,{onClick:()=>d(`csv`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (CSV)`}),(0,A.jsx)(`button`,{onClick:()=>d(`json`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (JSON)`})]})]})]})}function M({tableData:e,schema:t,loading:n,page:o,onPageChange:s,onCellUpdate:c,onRowDelete:l,orderBy:m,orderDir:g,onToggleSort:y,onBulkDelete:S,onInsertRow:C,connectionId:D,selectedTable:O,selectedSchema:ee,connectionName:k,columnFilters:j={},onColumnFilter:M}){let[N,P]=(0,E.useState)(null),[F,I]=(0,E.useState)(``),[L,R]=(0,E.useState)(null),[z,ae]=(0,E.useState)(``),[B,V]=(0,E.useState)(new Set),[oe,se]=(0,E.useState)(!1),[ce,le]=(0,E.useState)({}),[ue,de]=(0,E.useState)(null),[fe,pe]=(0,E.useState)(!1),{openTab:H}=u(),me=(0,E.useCallback)(e=>{H({type:`editor`,title:e.col,projectId:null,closable:!0,metadata:{inlineContent:e.value,inlineLanguage:ne(e.value)}})},[H]),[U,he]=(0,E.useState)(new Set),[ge,_e]=(0,E.useState)(new Set),[ve,ye]=(0,E.useState)(null),[be,W]=(0,E.useState)(!1),xe=(0,E.useRef)(null),G=(0,E.useMemo)(()=>t.find(e=>e.pk)?.name||(t.find(e=>e.name.toLowerCase()===`id`)?.name??null),[t]),Se=(0,E.useCallback)(e=>{let t=JSON.stringify(e,null,2),n=G?String(e[G]??``):``;H({type:`editor`,title:n?`Row ${n}`:`Row`,projectId:null,closable:!0,metadata:{inlineContent:t,inlineLanguage:`json`}})},[H,G]),Ce=(0,E.useRef)(N);Ce.current=N;let K=(0,E.useRef)(F);K.current=F;let we=(0,E.useRef)(B);we.current=B;let Te=(0,E.useRef)(L);Te.current=L;let Ee=(0,E.useCallback)((e,t,n)=>{P({rowIdx:e,col:t}),I(n==null?``:typeof n==`object`?JSON.stringify(n):String(n))},[]),De=(0,E.useCallback)(()=>{let t=Ce.current;if(!t||!e||!G)return;let n=e.rows[t.rowIdx];if(!n)return;let r=n[t.col];String(r??``)!==K.current&&c(G,n[G],t.col,K.current===``?null:K.current),P(null)},[e,G,c]),Oe=(0,E.useCallback)(()=>P(null),[]),ke=(0,E.useCallback)(t=>{if(!e||!G||!l)return;let n=e.rows[t];n&&(l(G,n[G]),R(null))},[e,G,l]),Ae=(0,E.useCallback)(e=>{he(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),je=(0,E.useCallback)(e=>{_e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Me=(0,E.useCallback)((e,t)=>{let n={...j};t?n[e]=t:delete n[e],M?.(n)},[j,M]),Ne=(0,E.useCallback)(e=>{V(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Pe=(0,E.useCallback)(()=>{e&&V(t=>t.size===e.rows.length?new Set:new Set(e.rows.map((e,t)=>t)))},[e]),Fe=(0,E.useCallback)(()=>{!e||!G||!S||(S(G,Array.from(B).map(t=>e.rows[t]?.[G]).filter(e=>e!=null)),V(new Set),pe(!1))},[e,G,S,B]),Ie=(0,E.useCallback)(async()=>{if(C){de(null);try{let e={};for(let[t,n]of Object.entries(ce))n!==``&&(e[t]=n);await C(e),se(!1),le({})}catch(e){de(e.message)}}},[C,ce]),q=(0,E.useMemo)(()=>{if(!e||!z)return e?.rows??[];let t=z.toLowerCase();return e.rows.filter(n=>e.columns.some(e=>String(n[e]??``).toLowerCase().includes(t)))},[e,z]),Le=(0,E.useRef)(null);(0,E.useEffect)(()=>{let t=Le.current;if(!t)return;let n=t=>{if(t.key===`Escape`){W(!1);return}let n=t.target?.tagName;if(!(n===`INPUT`||n===`TEXTAREA`)){if(t.key===`/`){t.preventDefault(),W(!0);return}if(!(!(t.metaKey||t.ctrlKey)||!e)&&(t.key===`a`&&(t.preventDefault(),V(new Set(e.rows.map((e,t)=>t)))),t.key===`c`&&B.size>0)){t.preventDefault();let n=e.columns,r=n.join(` `),i=Array.from(B).sort((e,t)=>e-t).map(t=>n.map(n=>{let r=e.rows[t]?.[n];return r==null?``:typeof r==`object`?JSON.stringify(r):String(r)}).join(` `));navigator.clipboard.writeText([r,...i].join(`
1
+ import{o as e}from"./chunk-CFjPhJqf.js";import{t}from"./react-nm2Ru1Pt.js";import{t as n}from"./createLucideIcon-PuMiQgHl.js";import{n as r,t as i}from"./x-D2_KzIET.js";import{t as a}from"./chevron-right-4zq1jPv6.js";import{t as o}from"./jsx-runtime-kMwlnEGE.js";import{t as s}from"./api-client-BfBM3I7n.js";import{Ct as c,Et as l,K as u,Mt as d,Nt as f,Q as p,Tt as m,it as h,mt as g,ot as _,pt as v,rt as y,st as b,tt as x}from"./index-Y-Kfye7A.js";import"./use-monaco-theme-Dl6w9X-L.js";import{t as S}from"./sql-query-editor-njmHoOsX.js";import{n as C}from"./csv-parser-CNNw2RVA.js";var w=n(`columns-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]]),T=n(`funnel`,[[`path`,{d:`M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z`,key:`sc7q7i`}]]),E=e(t(),1);function D(e,t,n,r){return`ppm-db-${e}-${n}.${t}-p${r}`}function O(e,t,n,r){try{let i=sessionStorage.getItem(D(e,t,n,r));return i?JSON.parse(i):null}catch{return null}}function ee(e,t,n,r,i,a){try{sessionStorage.setItem(D(e,t,n,r),JSON.stringify({data:i,cols:a}))}catch{}}function k(e){let t=`/api/db/connections/${e}`,[n,r]=(0,E.useState)(null),[i,a]=(0,E.useState)(`public`),[o,c]=(0,E.useState)(null),[l,u]=(0,E.useState)([]),[d,f]=(0,E.useState)(!1),[p,m]=(0,E.useState)(null),[h,g]=(0,E.useState)(1),[_,v]=(0,E.useState)(null),[y,b]=(0,E.useState)(null),[x,S]=(0,E.useState)(!1),[C,w]=(0,E.useState)(null),[T,D]=(0,E.useState)(`ASC`),k=(0,E.useCallback)(async(r,a,o,l,d)=>{let p=r??n,g=a??i;if(!p)return;f(!0);let _=l===void 0?C:l,v=d??T;try{let n=_?`&orderBy=${encodeURIComponent(_)}&orderDir=${v}`:``,[r,i]=await Promise.all([s.get(`${t}/data?table=${encodeURIComponent(p)}&schema=${g}&page=${o??h}&limit=100${n}`),s.get(`${t}/schema?table=${encodeURIComponent(p)}&schema=${g}`)]);c(r),u(i),ee(e,p,g,o??h,r,i)}catch(e){m(e.message)}finally{f(!1)}},[t,e,n,i,h,C,T]),A=(0,E.useCallback)((t,n=`public`)=>{r(t),a(n),g(1),v(null);let i=O(e,t,n,1);i?(c(i.data),u(i.cols),f(!1),k(t,n,1)):k(t,n,1)},[e,k]),j=(0,E.useCallback)(e=>{g(e),k(void 0,void 0,e)},[k]),te=(0,E.useCallback)(async e=>{S(!0),b(null);try{let r=await s.post(`${t}/query`,{sql:e});v(r),r.changeType===`modify`&&k(n??void 0,i)}catch(e){b(e.message)}finally{S(!1)}},[t,n,i,k]),M=(0,E.useCallback)(async(e,r,a,o)=>{if(!n)return;let c=n,l=i;try{await s.put(`${t}/cell`,{table:c,schema:l,pkColumn:e,pkValue:r,column:a,value:o}),k(c,l)}catch(e){m(e.message)}},[t,n,i,k]),N=(0,E.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.del(`${t}/row`,{table:a,schema:o,pkColumn:e,pkValue:r}),k(a,o)}catch(e){m(e.message)}},[t,n,i,k]);return{selectedTable:n,selectedSchema:i,selectTable:A,tableData:o,schema:l,loading:d,error:p,page:h,setPage:j,orderBy:C,orderDir:T,toggleSort:(0,E.useCallback)(e=>{let t,n=`ASC`;C===e?T===`ASC`?(t=e,n=`DESC`):(t=null,n=`ASC`):(t=e,n=`ASC`),w(t),D(n),g(1),k(void 0,void 0,1,t,n)},[C,T,k]),queryResult:_,queryError:y,queryLoading:x,executeQuery:te,updateCell:M,deleteRow:N,bulkDelete:(0,E.useCallback)(async(e,r)=>{if(!n)return;let a=n,o=i;try{await s.post(`${t}/rows/delete`,{table:a,schema:o,pkColumn:e,pkValues:r}),k(a,o)}catch(e){m(e.message)}},[t,n,i,k]),insertRow:(0,E.useCallback)(async e=>{if(!n)return;let r=n,a=i;try{await s.post(`${t}/row`,{table:r,schema:a,values:e}),k(r,a)}catch(e){throw m(e.message),e}},[t,n,i,k]),refreshData:k,queryAsTable:(0,E.useCallback)(async e=>{f(!0);try{let n=await s.post(`${t}/query`,{sql:e});n.changeType===`select`&&c({columns:n.columns,rows:n.rows,total:n.rows.length,page:1,limit:n.rows.length})}catch(e){m(e.message)}finally{f(!1)}},[t])}}var A=o();function j(e,t,n){let r=new Blob([t],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=e,a.click(),URL.revokeObjectURL(i)}function te({columns:e,rows:t,filename:n=`export`,exportAllUrl:r}){let[i,a]=(0,E.useState)(!1),[o,s]=(0,E.useState)(!1),c=(0,E.useRef)(null);(0,E.useEffect)(()=>{if(!i)return;let e=e=>{c.current&&!c.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let l=()=>{let r=C(e,t.map(t=>e.map(e=>String(t[e]??``))));j(`${n}.csv`,r,`text/csv`),a(!1)},u=()=>{let e=JSON.stringify(t,null,2);j(`${n}.json`,e,`application/json`),a(!1)},d=async e=>{if(r){s(!0);try{let t=await(await fetch(`${r}&format=${e}&limit=10000`)).text(),i=e===`csv`?`text/csv`:`application/json`;j(`${n}-all.${e}`,t,i)}catch{}s(!1),a(!1)}};return e.length===0||t.length===0?null:(0,A.jsxs)(`div`,{className:`relative`,ref:c,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`p-1 rounded text-muted-foreground hover:text-foreground transition-colors`,title:`Export`,children:(0,A.jsx)(m,{className:`size-3.5`})}),i&&(0,A.jsxs)(`div`,{className:`absolute right-0 top-full mt-1 z-50 bg-popover border border-border rounded-md shadow-md py-1 min-w-[160px] text-xs`,children:[(0,A.jsx)(`button`,{onClick:l,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (CSV)`}),(0,A.jsx)(`button`,{onClick:u,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors`,children:`Export Page (JSON)`}),r&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`border-t border-border my-1`}),(0,A.jsx)(`button`,{onClick:()=>d(`csv`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (CSV)`}),(0,A.jsx)(`button`,{onClick:()=>d(`json`),disabled:o,className:`w-full text-left px-3 py-1.5 hover:bg-muted transition-colors disabled:opacity-50`,children:o?`Exporting…`:`Export All (JSON)`})]})]})]})}function M({tableData:e,schema:t,loading:n,page:o,onPageChange:s,onCellUpdate:c,onRowDelete:l,orderBy:m,orderDir:g,onToggleSort:y,onBulkDelete:S,onInsertRow:C,connectionId:D,selectedTable:O,selectedSchema:ee,connectionName:k,columnFilters:j={},onColumnFilter:M}){let[N,P]=(0,E.useState)(null),[F,I]=(0,E.useState)(``),[L,R]=(0,E.useState)(null),[z,ae]=(0,E.useState)(``),[B,V]=(0,E.useState)(new Set),[oe,se]=(0,E.useState)(!1),[ce,le]=(0,E.useState)({}),[ue,de]=(0,E.useState)(null),[fe,pe]=(0,E.useState)(!1),{openTab:H}=u(),me=(0,E.useCallback)(e=>{H({type:`editor`,title:e.col,projectId:null,closable:!0,metadata:{inlineContent:e.value,inlineLanguage:ne(e.value)}})},[H]),[U,he]=(0,E.useState)(new Set),[ge,_e]=(0,E.useState)(new Set),[ve,ye]=(0,E.useState)(null),[be,W]=(0,E.useState)(!1),xe=(0,E.useRef)(null),G=(0,E.useMemo)(()=>t.find(e=>e.pk)?.name||(t.find(e=>e.name.toLowerCase()===`id`)?.name??null),[t]),Se=(0,E.useCallback)(e=>{let t=JSON.stringify(e,null,2),n=G?String(e[G]??``):``;H({type:`editor`,title:n?`Row ${n}`:`Row`,projectId:null,closable:!0,metadata:{inlineContent:t,inlineLanguage:`json`}})},[H,G]),Ce=(0,E.useRef)(N);Ce.current=N;let K=(0,E.useRef)(F);K.current=F;let we=(0,E.useRef)(B);we.current=B;let Te=(0,E.useRef)(L);Te.current=L;let Ee=(0,E.useCallback)((e,t,n)=>{P({rowIdx:e,col:t}),I(n==null?``:typeof n==`object`?JSON.stringify(n):String(n))},[]),De=(0,E.useCallback)(()=>{let t=Ce.current;if(!t||!e||!G)return;let n=e.rows[t.rowIdx];if(!n)return;let r=n[t.col];String(r??``)!==K.current&&c(G,n[G],t.col,K.current===``?null:K.current),P(null)},[e,G,c]),Oe=(0,E.useCallback)(()=>P(null),[]),ke=(0,E.useCallback)(t=>{if(!e||!G||!l)return;let n=e.rows[t];n&&(l(G,n[G]),R(null))},[e,G,l]),Ae=(0,E.useCallback)(e=>{he(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),je=(0,E.useCallback)(e=>{_e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Me=(0,E.useCallback)((e,t)=>{let n={...j};t?n[e]=t:delete n[e],M?.(n)},[j,M]),Ne=(0,E.useCallback)(e=>{V(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Pe=(0,E.useCallback)(()=>{e&&V(t=>t.size===e.rows.length?new Set:new Set(e.rows.map((e,t)=>t)))},[e]),Fe=(0,E.useCallback)(()=>{!e||!G||!S||(S(G,Array.from(B).map(t=>e.rows[t]?.[G]).filter(e=>e!=null)),V(new Set),pe(!1))},[e,G,S,B]),Ie=(0,E.useCallback)(async()=>{if(C){de(null);try{let e={};for(let[t,n]of Object.entries(ce))n!==``&&(e[t]=n);await C(e),se(!1),le({})}catch(e){de(e.message)}}},[C,ce]),q=(0,E.useMemo)(()=>{if(!e||!z)return e?.rows??[];let t=z.toLowerCase();return e.rows.filter(n=>e.columns.some(e=>String(n[e]??``).toLowerCase().includes(t)))},[e,z]),Le=(0,E.useRef)(null);(0,E.useEffect)(()=>{let t=Le.current;if(!t)return;let n=t=>{if(t.key===`Escape`){W(!1);return}let n=t.target?.tagName;if(!(n===`INPUT`||n===`TEXTAREA`)){if(t.key===`/`){t.preventDefault(),W(!0);return}if(!(!(t.metaKey||t.ctrlKey)||!e)&&(t.key===`a`&&(t.preventDefault(),V(new Set(e.rows.map((e,t)=>t)))),t.key===`c`&&B.size>0)){t.preventDefault();let n=e.columns,r=n.join(` `),i=Array.from(B).sort((e,t)=>e-t).map(t=>n.map(n=>{let r=e.rows[t]?.[n];return r==null?``:typeof r==`object`?JSON.stringify(r):String(r)}).join(` `));navigator.clipboard.writeText([r,...i].join(`
2
2
  `))}}};return t.addEventListener(`keydown`,n),()=>t.removeEventListener(`keydown`,n)},[e,B]);let J=(0,E.useMemo)(()=>{if(!e)return[];let t=e.columns.filter(e=>U.has(e)),n=e.columns.filter(e=>!U.has(e));return[...t,...n]},[e?.columns,U]),Re=(0,E.useRef)(null),[Y,ze]=(0,E.useState)(0),[X,Be]=(0,E.useState)(new Map);(0,E.useEffect)(()=>{let e=Re.current;if(!e)return;let t=()=>{ze(e.offsetHeight);let t=new Map;e.querySelectorAll(`th[data-col]`).forEach(e=>{t.set(e.dataset.col,e.offsetWidth)});let n=e.querySelector(`th[data-col='_cb']`);n&&t.set(`_cb`,n.offsetWidth),Be(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e?.columns,U]);let Z=(0,E.useMemo)(()=>{let e=new Map,t=X.get(`_cb`)??(G?40:0);for(let n of J){if(!U.has(n))break;e.set(n,t),t+=X.get(n)??100}return e},[J,U,G,X]),Q=(0,E.useMemo)(()=>Array.from(ge).sort((e,t)=>e-t).map(e=>({idx:e,row:q[e]})).filter(e=>e.row),[ge,q]),Ve=(0,E.useRef)(new Map),[$,He]=(0,E.useState)(new Map),Ue=(0,E.useCallback)((e,t)=>{t?Ve.current.set(e,t):Ve.current.delete(e)},[]);(0,E.useEffect)(()=>{if(Q.length===0){$.size>0&&He(new Map);return}let e=requestAnimationFrame(()=>{let e=new Map;for(let{idx:t}of Q){let n=Ve.current.get(t);n&&e.set(t,n.offsetHeight)}He(e)});return()=>cancelAnimationFrame(e)},[Q,e]);let We=(0,E.useMemo)(()=>{let e=new Map,t=Y;for(let{idx:n}of Q)e.set(n,t),t+=$.get(n)??28;return e},[Y,Q,$]),Ge=(0,E.useCallback)(e=>{let t=xe.current,n=t?.querySelector(`th[data-col="${e}"]`);if(!t||!n)return;let r=0,i=t.querySelector(`th[data-col="_cb"]`);i&&(r+=i.offsetWidth);for(let[t,n]of Z)t!==e&&(r=Math.max(r,n+(X.get(t)??0)));let a=n.offsetLeft-r;t.scrollTo({left:a,behavior:`smooth`}),W(!1)},[Z,X]);if(!e)return(0,A.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:n?(0,A.jsx)(v,{className:`size-4 animate-spin`}):`Select a table`});let Ke=Math.ceil(e.total/e.limit)||1,qe=B.size>0,Je=B.size===e.rows.length&&e.rows.length>0;return(0,A.jsxs)(`div`,{ref:Le,tabIndex:0,className:`flex flex-col h-full overflow-hidden outline-none`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1 border-b border-border bg-background shrink-0`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-1 flex-1`,children:[(0,A.jsx)(x,{className:`size-3 text-muted-foreground`}),(0,A.jsx)(`input`,{type:`text`,value:z,onChange:e=>ae(e.target.value),placeholder:`Search current page…`,className:`flex-1 text-xs bg-transparent outline-none text-foreground placeholder:text-muted-foreground`}),z&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>ae(``),className:`text-muted-foreground hover:text-foreground`,children:(0,A.jsx)(i,{className:`size-3`})})]}),(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>W(!be),className:`p-0.5 rounded transition-colors ${be?`text-primary`:`text-muted-foreground hover:text-foreground`}`,title:`Jump to column ( / )`,children:(0,A.jsx)(w,{className:`size-3.5`})}),be&&(0,A.jsx)(re,{columns:e.columns,onSelect:Ge,onClose:()=>W(!1)})]}),qe&&(0,A.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs`,children:[(0,A.jsxs)(`span`,{className:`text-muted-foreground`,children:[B.size,` selected`]}),S&&G&&(fe?(0,A.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:Fe,className:`text-destructive text-[10px] font-medium hover:underline`,children:[`Delete `,B.size,`?`]}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>pe(!1),className:`text-muted-foreground text-[10px] hover:underline`,children:`Cancel`})]}):(0,A.jsx)(`button`,{type:`button`,onClick:()=>pe(!0),className:`p-0.5 text-muted-foreground hover:text-destructive`,children:(0,A.jsx)(p,{className:`size-3`})})),(0,A.jsx)(te,{columns:e.columns,rows:Array.from(B).map(t=>e.rows[t]).filter(Boolean),filename:`${k??`db`}-selected`})]}),C&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{se(!0),le({}),de(null)},className:`p-0.5 rounded text-muted-foreground hover:text-primary transition-colors`,title:`Insert row`,children:(0,A.jsx)(h,{className:`size-3.5`})})]}),oe&&(0,A.jsxs)(`div`,{className:`px-2 py-1.5 border-b border-border bg-muted/30 text-xs space-y-1`,children:[(0,A.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.filter(e=>!e.pk).map(e=>(0,A.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,A.jsx)(`label`,{className:`text-muted-foreground text-[10px] w-16 truncate`,title:e.name,children:e.name}),(0,A.jsx)(`input`,{value:ce[e.name]??``,onChange:t=>le(n=>({...n,[e.name]:t.target.value})),placeholder:e.defaultValue??(e.nullable?`NULL`:``),className:`h-5 w-24 text-[11px] px-1 rounded border border-border bg-background outline-none focus:border-primary`})]},e.name))}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:Ie,className:`text-[10px] px-2 py-0.5 rounded bg-primary text-primary-foreground hover:bg-primary/90`,children:`Save`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>se(!1),className:`text-[10px] text-muted-foreground hover:underline`,children:`Cancel`}),ue&&(0,A.jsx)(`span`,{className:`text-[10px] text-destructive`,children:ue})]})]}),(0,A.jsxs)(`div`,{ref:xe,className:`flex-1 overflow-auto relative`,children:[n&&(0,A.jsx)(`div`,{className:`absolute inset-0 z-30 flex items-center justify-center bg-background/60`,children:(0,A.jsx)(v,{className:`size-5 animate-spin text-primary`})}),(0,A.jsxs)(`table`,{className:`w-full text-xs`,style:{borderCollapse:`separate`,borderSpacing:0},children:[(0,A.jsx)(`thead`,{ref:Re,className:`sticky top-0 z-20 bg-muted`,children:(0,A.jsxs)(`tr`,{children:[G&&(0,A.jsx)(`th`,{"data-col":`_cb`,className:`px-2 py-1.5 text-left font-medium text-muted-foreground border-b border-border w-10 bg-muted`,style:{position:`sticky`,left:0,zIndex:30},children:(0,A.jsx)(`input`,{type:`checkbox`,checked:Je,onChange:Pe,className:`size-3 accent-primary`})}),J.map(e=>{let n=t.find(t=>t.name===e)?.pk,a=m===e,o=U.has(e),s=!!j[e],c=ve===e,l=Z.get(e);return(0,A.jsxs)(`th`,{"data-col":e,className:`group/th px-2 py-1.5 text-left font-medium text-muted-foreground border-b border-border whitespace-nowrap bg-muted ${o?`border-r border-r-primary/20`:``}`,style:l==null?void 0:{position:`sticky`,left:l,zIndex:25},children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,A.jsxs)(`button`,{type:`button`,onClick:()=>y(e),className:`flex items-center gap-0.5 ${n?`font-bold`:``} hover:text-foreground transition-colors`,children:[e,a&&g===`ASC`&&(0,A.jsx)(d,{className:`size-3`}),a&&g===`DESC`&&(0,A.jsx)(r,{className:`size-3`})]}),M&&(0,A.jsx)(`button`,{type:`button`,title:`Filter column`,onClick:()=>ye(c?null:e),className:`p-0.5 rounded transition-colors ${s||c?`text-primary`:`text-muted-foreground/40 md:opacity-0 md:group-hover/th:opacity-100 hover:text-foreground`}`,children:(0,A.jsx)(T,{className:`size-2.5`})}),(0,A.jsx)(`button`,{type:`button`,title:o?`Unpin column`:`Pin column`,onClick:()=>Ae(e),className:`p-0.5 rounded transition-colors ${o?`text-primary`:`text-muted-foreground/40 md:opacity-0 md:group-hover/th:opacity-100 hover:text-foreground`}`,children:o?(0,A.jsx)(b,{className:`size-2.5`}):(0,A.jsx)(_,{className:`size-2.5`})})]}),c&&(0,A.jsxs)(`div`,{className:`mt-1 flex items-center gap-1`,children:[(0,A.jsx)(`input`,{autoFocus:!0,type:`text`,value:j[e]??``,placeholder:`ILIKE filter…`,onChange:t=>Me(e,t.target.value),onKeyDown:e=>{e.key===`Escape`&&ye(null)},className:`w-full h-5 text-[10px] px-1 rounded border border-border bg-background outline-none focus:border-primary`}),s&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>Me(e,``),className:`text-muted-foreground hover:text-foreground`,children:(0,A.jsx)(i,{className:`size-2.5`})})]})]},e)}),l&&G&&(0,A.jsx)(`th`,{className:`px-2 py-1.5 border-b border-border w-14 bg-muted`})]})}),(0,A.jsxs)(`tbody`,{children:[Q.map(({idx:e,row:t})=>(0,A.jsx)(ie,{row:t,rowIdx:e,columns:J,selected:B.has(e),onToggleSelect:Ne,pkCol:G,editingCell:N,editValue:F,onStartEdit:Ee,onCommitEdit:De,onCancelEdit:Oe,onSetEditValue:I,showDelete:!!l,confirmingDelete:L===e,onDelete:ke,onConfirmDelete:R,onViewCell:me,onViewRow:Se,pinned:!0,onTogglePin:je,pinnedCols:U,pinnedColOffsets:Z,stickyTop:We.get(e)??Y,trRef:t=>Ue(e,t)},`pin-${e}`)),q.map((e,t)=>ge.has(t)?null:(0,A.jsx)(ie,{row:e,rowIdx:t,columns:J,selected:B.has(t),onToggleSelect:Ne,pkCol:G,editingCell:N,editValue:F,onStartEdit:Ee,onCommitEdit:De,onCancelEdit:Oe,onSetEditValue:I,showDelete:!!l,confirmingDelete:L===t,onDelete:ke,onConfirmDelete:R,onViewCell:me,onViewRow:Se,pinned:!1,onTogglePin:je,pinnedCols:U,pinnedColOffsets:Z},t)),q.length===0&&(0,A.jsx)(`tr`,{children:(0,A.jsx)(`td`,{colSpan:J.length+2,className:`px-2 py-8 text-center text-muted-foreground`,children:`No data`})})]})]})]}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between px-3 py-1.5 border-t border-border bg-background shrink-0 text-xs text-muted-foreground`,children:[(0,A.jsxs)(`span`,{children:[e.total.toLocaleString(),` rows`]}),(0,A.jsxs)(`div`,{className:`hidden md:flex items-center gap-2 text-[10px] text-muted-foreground/50`,children:[(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`kbd`,{className:`px-1 py-0.5 rounded bg-muted text-[9px]`,children:`/`}),` columns`]}),(0,A.jsxs)(`span`,{children:[(0,A.jsxs)(`kbd`,{className:`px-1 py-0.5 rounded bg-muted text-[9px]`,children:[`⌘`,`A`]}),` select all`]}),(0,A.jsxs)(`span`,{children:[(0,A.jsxs)(`kbd`,{className:`px-1 py-0.5 rounded bg-muted text-[9px]`,children:[`⌘`,`C`]}),` copy`]})]}),(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(`button`,{type:`button`,disabled:o<=1,onClick:()=>s(o-1),className:`p-0.5 rounded hover:bg-muted disabled:opacity-30`,children:(0,A.jsx)(f,{className:`size-3.5`})}),(0,A.jsxs)(`span`,{children:[o,` / `,Ke]}),(0,A.jsx)(`button`,{type:`button`,disabled:o>=Ke,onClick:()=>s(o+1),className:`p-0.5 rounded hover:bg-muted disabled:opacity-30`,children:(0,A.jsx)(a,{className:`size-3.5`})})]})]})]})}function N(e){return e==null?`NULL`:typeof e==`object`?JSON.stringify(e):String(e)}var P=200;function F(e){if(e==null)return!1;if(typeof e==`object`)return!0;let t=String(e);if(t.length>=P)return!0;let n=t.trimStart();return!!((n[0]===`{`||n[0]===`[`)&&(n.endsWith(`}`)||n.endsWith(`]`))||n.startsWith(`<?xml`)||n.startsWith(`<`)&&n.endsWith(`>`))}function ne(e){let t=e.trimStart();if(t[0]===`{`||t[0]===`[`)try{return JSON.parse(t),`json`}catch{}return t.startsWith(`<?xml`)||t.startsWith(`<`)&&/<\/\w+>/.test(t)?`xml`:t.startsWith(`---`)||/^\w+:\s/m.test(t)?`yaml`:`plaintext`}function re({columns:e,onSelect:t,onClose:n}){let[r,i]=(0,E.useState)(``),[a,o]=(0,E.useState)(0),s=(0,E.useMemo)(()=>{if(!r)return e;let t=r.toLowerCase();return e.filter(e=>e.toLowerCase().includes(t))},[e,r]),c=(0,E.useRef)(null);return(0,E.useEffect)(()=>{c.current?.scrollIntoView({block:`nearest`})},[a]),(0,A.jsxs)(`div`,{className:`absolute top-full right-0 mt-1 z-50 w-52 max-h-56 bg-popover border border-border rounded-md shadow-lg overflow-hidden flex flex-col`,children:[(0,A.jsx)(`input`,{autoFocus:!0,type:`text`,value:r,onChange:e=>{i(e.target.value),o(0)},onKeyDown:e=>{e.key===`Escape`?n():e.key===`ArrowDown`?(e.preventDefault(),o(e=>Math.min(e+1,s.length-1))):e.key===`ArrowUp`?(e.preventDefault(),o(e=>Math.max(e-1,0))):e.key===`Enter`&&s[a]&&t(s[a])},placeholder:`Search columns…`,className:`px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border text-foreground placeholder:text-muted-foreground`}),(0,A.jsx)(`div`,{className:`overflow-auto flex-1`,children:s.map((e,n)=>(0,A.jsx)(`button`,{type:`button`,onClick:()=>t(e),ref:n===a?c:void 0,className:`w-full text-left px-2 py-1 text-xs truncate ${n===a?`bg-primary/10 text-primary`:`text-foreground hover:bg-muted`}`,children:e},e))})]})}var ie=(0,E.memo)(function({row:e,rowIdx:t,columns:n,selected:r,onToggleSelect:i,pkCol:a,editingCell:o,editValue:s,onStartEdit:l,onCommitEdit:u,onCancelEdit:d,onSetEditValue:f,showDelete:m,confirmingDelete:h,onDelete:g,onConfirmDelete:v,onViewCell:y,onViewRow:x,pinned:S,onTogglePin:C,pinnedCols:w,pinnedColOffsets:T,stickyTop:E,trRef:D}){let O=S?`bg-muted`:r?`bg-primary/5`:`bg-background`;return(0,A.jsxs)(`tr`,{ref:D,className:`group ${S?``:`hover:bg-muted/30`}`,style:S?{position:`sticky`,top:E,zIndex:15}:void 0,children:[a&&(0,A.jsx)(`td`,{className:`px-2 py-1 border-b border-border/50 ${O}`,style:{position:`sticky`,left:0,zIndex:12},children:(0,A.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:r,onChange:()=>i(t),className:`size-3 accent-primary`}),(0,A.jsx)(`button`,{type:`button`,title:`View row as JSON`,onClick:()=>x(e),className:`p-0.5 rounded transition-colors text-muted-foreground/30 md:opacity-0 md:group-hover:opacity-100 hover:text-foreground`,children:(0,A.jsx)(c,{className:`size-2.5`})}),(0,A.jsx)(`button`,{type:`button`,title:S?`Unpin row`:`Pin row`,onClick:()=>C(t),className:`p-0.5 rounded transition-colors ${S?`text-primary`:`text-muted-foreground/30 md:opacity-0 md:group-hover:opacity-100 hover:text-foreground`}`,children:S?(0,A.jsx)(b,{className:`size-2.5`}):(0,A.jsx)(_,{className:`size-2.5`})})]})}),n.map(n=>{let r=o?.rowIdx===t&&o?.col===n,i=e[n],p=!r&&F(i),m=w.has(n),h=T.get(n);return(0,A.jsx)(`td`,{className:`px-2 py-1 max-w-[300px] border-b border-border/50 ${m?`border-r border-r-primary/20`:``} ${m||S?O:``}`,style:h==null?void 0:{position:`sticky`,left:h,zIndex:10},children:r?(0,A.jsx)(`input`,{autoFocus:!0,className:`w-full bg-transparent border border-primary/50 rounded px-1 py-0 text-xs outline-none`,value:s,onChange:e=>f(e.target.value),onBlur:u,onKeyDown:e=>{e.key===`Enter`&&u(),e.key===`Escape`&&d()}}):(0,A.jsxs)(`span`,{className:`flex items-center gap-0.5`,children:[(0,A.jsx)(`span`,{className:`cursor-pointer truncate flex-1 ${i==null?`text-muted-foreground/40 italic`:``}`,onDoubleClick:()=>a&&l(t,n,i),title:N(i),children:N(i)}),p&&(0,A.jsx)(`button`,{type:`button`,title:`View full content`,onClick:()=>y({col:n,value:N(i)}),className:`shrink-0 p-0.5 rounded text-muted-foreground/50 hover:text-foreground transition-colors`,children:(0,A.jsx)(c,{className:`size-3`})})]})},n)}),m&&a&&(0,A.jsx)(`td`,{className:`px-2 py-1 border-b border-border/50 ${S?O:``}`,children:h?(0,A.jsxs)(`span`,{className:`flex items-center gap-1 whitespace-nowrap`,children:[(0,A.jsx)(`button`,{type:`button`,onClick:()=>g(t),className:`text-destructive text-[10px] font-medium hover:underline`,children:`Confirm`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>v(null),className:`text-muted-foreground text-[10px] hover:underline`,children:`Cancel`})]}):(0,A.jsx)(`button`,{type:`button`,onClick:()=>v(t),className:`p-0.5 rounded md:opacity-0 md:group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive transition-opacity`,title:`Delete row`,children:(0,A.jsx)(p,{className:`size-3`})})})]})});function I(e){let t={},n=/"(\w+)"\s+ILIKE\s+'%([^']*?)%'/gi,r;for(;(r=n.exec(e))!==null;)t[r[1]]=r[2].replace(/''/g,`'`);return t}function L({metadata:e}){let t=e?.connectionId,n=e?.connectionName,r=e?.tableName,i=e?.schemaName??`public`,a=e?.initialSql,o=k(t),[c,u]=(0,E.useState)([]),[d,f]=(0,E.useState)(180),p=(0,E.useRef)(null),[m,h]=(0,E.useState)({}),_=(0,E.useMemo)(()=>{if(a&&!o.selectedTable)return a;if(o.selectedTable){let e=`SELECT * FROM "${o.selectedTable}"`,t=Object.entries(m).filter(([,e])=>e.trim()).map(([e,t])=>`"${e}" ILIKE '%${t.replace(/'/g,`''`)}%'`);t.length>0&&(e+=` WHERE ${t.join(` AND `)}`),o.orderBy&&(e+=` ORDER BY "${o.orderBy}" ${o.orderDir}`);let n=(o.page-1)*100;return e+=` LIMIT 100`,n>0&&(e+=` OFFSET ${n}`),e}return`SELECT * FROM `},[a,o.selectedTable,o.orderBy,o.orderDir,o.page,m]),v=(0,E.useCallback)(e=>{h(e)},[]),b=(0,E.useRef)(void 0);(0,E.useEffect)(()=>{if(!(!o.selectedTable||Object.keys(m).length===0))return clearTimeout(b.current),b.current=setTimeout(()=>{o.queryAsTable(_)},500),()=>clearTimeout(b.current)},[m]);let x=(0,E.useCallback)(e=>{e.preventDefault();let t=e.clientY,n=d,r=e=>{let r=e.clientY-t;f(Math.max(80,Math.min(n+r,(p.current?.clientHeight??600)-100)))},i=()=>{document.removeEventListener(`mousemove`,r),document.removeEventListener(`mouseup`,i)};document.addEventListener(`mousemove`,r),document.addEventListener(`mouseup`,i)},[d]);(0,E.useEffect)(()=>{s.get(`/api/db/connections/${t}/tables?cached=1`).then(e=>u(e.map(e=>({name:e.name,schema:e.schema})))).catch(()=>{})},[t]);let C=(0,E.useMemo)(()=>{if(c.length!==0)return{tables:c,getColumns:async(e,n)=>await s.get(`/api/db/connections/${t}/schema?table=${encodeURIComponent(e)}${n?`&schema=${encodeURIComponent(n)}`:``}`)}},[t,c]),w=(0,E.useRef)(!1);(0,E.useEffect)(()=>{w.current||(w.current=!0,a?o.executeQuery(a):r&&o.selectTable(r,i))},[r,i,a]);let[T,D]=(0,E.useState)(!!a),O=(0,E.useCallback)(e=>{let t=e.trim();if(o.selectedTable&&RegExp(`^SELECT\\s+\\*\\s+FROM\\s+"?${o.selectedTable.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}"?\\b`,`i`).test(t)){h(I(t)),o.queryAsTable(t);return}D(!0),o.executeQuery(e)},[o.executeQuery,o.queryAsTable,o.selectedTable]),ee=(0,E.useCallback)(e=>{D(!1),o.toggleSort(e)},[o.toggleSort]),j=(0,E.useCallback)(e=>{D(!1),o.setPage(e)},[o.setPage]),N=o.queryResult,P=T&&!!(N||o.queryError),F=o.selectedTable&&!P;return(0,A.jsx)(`div`,{ref:p,className:`flex h-full w-full overflow-hidden`,children:(0,A.jsxs)(`div`,{className:`flex-1 flex flex-col overflow-hidden`,children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-1.5 border-b border-border bg-background shrink-0`,children:[(0,A.jsx)(l,{className:`size-3.5 text-muted-foreground`}),(0,A.jsx)(`span`,{className:`text-xs text-muted-foreground truncate`,children:n??`Database`}),o.selectedTable&&(0,A.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`/ `,o.selectedTable]}),(0,A.jsxs)(`div`,{className:`ml-auto flex items-center gap-1`,children:[o.tableData&&(0,A.jsx)(te,{columns:o.tableData.columns,rows:o.tableData.rows,filename:n?`${n}-${o.selectedTable??`data`}`:o.selectedTable??`data`,exportAllUrl:o.selectedTable?`/api/db/connections/${t}/export?table=${encodeURIComponent(o.selectedTable)}&schema=${o.selectedSchema}`:void 0}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o.refreshData(),title:`Reload data`,className:`p-1 rounded text-muted-foreground hover:text-foreground transition-colors`,children:(0,A.jsx)(y,{className:`size-3 ${o.loading?`animate-spin`:``}`})})]})]}),(0,A.jsx)(`div`,{className:`shrink-0 border-b border-border`,style:{height:d},children:(0,A.jsx)(S,{onExecute:O,loading:o.queryLoading,defaultValue:_,schemaInfo:C})}),(0,A.jsx)(`div`,{onMouseDown:x,className:`shrink-0 h-1.5 cursor-row-resize bg-border/50 hover:bg-primary/30 flex items-center justify-center transition-colors`,children:(0,A.jsx)(g,{className:`size-3 text-muted-foreground/50`})}),(0,A.jsxs)(`div`,{className:`flex-1 overflow-hidden`,children:[F&&(0,A.jsx)(M,{tableData:o.tableData,schema:o.schema,loading:o.loading,page:o.page,onPageChange:j,onCellUpdate:o.updateCell,onRowDelete:o.deleteRow,orderBy:o.orderBy,orderDir:o.orderDir,onToggleSort:ee,onBulkDelete:o.bulkDelete,onInsertRow:o.insertRow,connectionId:t,selectedTable:o.selectedTable,selectedSchema:o.selectedSchema,connectionName:n,columnFilters:m,onColumnFilter:v}),P&&(0,A.jsx)(z,{result:N,error:o.queryError,loading:o.queryLoading,schema:o.schema,connectionName:n})]})]})})}var R=()=>{};function z({result:e,error:t,loading:n,schema:r,connectionName:i}){let a=(0,E.useMemo)(()=>e?.changeType===`select`&&e.rows.length>0?{columns:e.columns,rows:e.rows,total:e.rows.length,limit:e.rows.length}:null,[e]),o=(0,E.useMemo)(()=>r?.length?r:(e?.columns??[]).map(e=>({name:e,type:`text`,nullable:!0,pk:!1,defaultValue:null})),[r,e?.columns]);return(0,A.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden text-xs`,children:[t&&(0,A.jsx)(`div`,{className:`px-3 py-2 text-destructive bg-destructive/5 shrink-0`,children:t}),e?.changeType===`modify`&&(0,A.jsxs)(`div`,{className:`px-3 py-2 text-green-500 shrink-0`,children:[e.rowsAffected,` row(s) affected`,e.executionTimeMs!=null&&(0,A.jsxs)(`span`,{className:`text-muted-foreground ml-2`,children:[e.executionTimeMs,`ms`]})]}),a&&(0,A.jsxs)(`div`,{className:`flex-1 overflow-hidden`,children:[(0,A.jsx)(M,{tableData:a,schema:o,loading:!!n,page:1,onPageChange:R,onCellUpdate:R,orderBy:null,orderDir:`ASC`,onToggleSort:R,connectionName:i}),e?.executionTimeMs!=null&&(0,A.jsxs)(`div`,{className:`px-3 py-0.5 border-t border-border text-[10px] text-muted-foreground shrink-0`,children:[e.rows.length,` rows · `,e.executionTimeMs,`ms`]})]}),e?.changeType===`select`&&e.rows.length===0&&(0,A.jsxs)(`div`,{className:`px-3 py-2 text-muted-foreground shrink-0`,children:[`No results`,e.executionTimeMs!=null&&(0,A.jsxs)(`span`,{className:`ml-2 text-muted-foreground/60`,children:[e.executionTimeMs,`ms`]})]}),!e&&!t&&(0,A.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:n?(0,A.jsx)(v,{className:`size-4 animate-spin`}):`Run a query to see results`})]})}export{L as DatabaseViewer};