@hienlh/ppm 0.17.38 → 0.17.40

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 (66) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/assets/skills/ppm/SKILL.md +1 -1
  3. package/assets/skills/ppm/references/http-api.md +5 -1
  4. package/dist/web/assets/{ai-resource-editor-ChT9FzxT.js → ai-resource-editor-bGSN2dFv.js} +1 -1
  5. package/dist/web/assets/{api-client-BgM59GxL.js → api-client-COQtP-dB.js} +1 -1
  6. package/dist/web/assets/api-client-RtNXvS0P.js +1 -0
  7. package/dist/web/assets/api-settings-De--HNHp.js +1 -0
  8. package/dist/web/assets/{api-settings-D108koFG.js → api-settings-Do0Z0IRN.js} +1 -1
  9. package/dist/web/assets/{api-themes-cPGCYGB_.js → api-themes-DXi8sz-9.js} +1 -1
  10. package/dist/web/assets/{audio-preview-CSK6nxNy.js → audio-preview-DnSpaaBX.js} +1 -1
  11. package/dist/web/assets/{chat-tab-DGM7js5J.js → chat-tab-Cvuo7XWm.js} +4 -4
  12. package/dist/web/assets/{code-editor-BvLxm1bf.js → code-editor-BvwCPxaD.js} +2 -2
  13. package/dist/web/assets/{conflict-editor-Bc063EfD.js → conflict-editor-LDIdkUJm.js} +1 -1
  14. package/dist/web/assets/{csv-preview-ft27dubA.js → csv-preview-47tAvhIq.js} +1 -1
  15. package/dist/web/assets/{database-viewer-Bdj1ferk.js → database-viewer-RkxcBpY3.js} +1 -1
  16. package/dist/web/assets/{diff-viewer-C46_ZovZ.js → diff-viewer-YTRJpdV6.js} +1 -1
  17. package/dist/web/assets/{docx-preview-CLDLTD8N.js → docx-preview-B4B4W5LU.js} +1 -1
  18. package/dist/web/assets/{extension-webview-BSvKnN1E.js → extension-webview-CB8-nHNA.js} +1 -1
  19. package/dist/web/assets/{git-log-panel-GP8XaTlA.js → git-log-panel-OXE-EtxM.js} +1 -1
  20. package/dist/web/assets/{glide-data-grid-On_pS9Y7.js → glide-data-grid-CCVPfJtk.js} +1 -1
  21. package/dist/web/assets/{group-chat-tab-DmYt9GfT.js → group-chat-tab-D5rkf_zG.js} +1 -1
  22. package/dist/web/assets/{image-preview-BWNTrufr.js → image-preview-CenSD210.js} +1 -1
  23. package/dist/web/assets/index-BEB87kj8.css +2 -0
  24. package/dist/web/assets/index-bQy6gwMT.js +50 -0
  25. package/dist/web/assets/keybindings-store-Bk2X4njD.js +1 -0
  26. package/dist/web/assets/markdown-renderer-CAFmdvwK.js +1 -0
  27. package/dist/web/assets/{markdown-renderer-suZuQvya.js → markdown-renderer-CyzYLWuu.js} +1 -1
  28. package/dist/web/assets/notification-store-C9MS_FlD.js +1 -0
  29. package/dist/web/assets/{pdf-preview-DcP6Tj7N.js → pdf-preview-CsOL51Lb.js} +1 -1
  30. package/dist/web/assets/{postgres-viewer-BOlXoo4R.js → postgres-viewer-Dtt-XLSP.js} +1 -1
  31. package/dist/web/assets/{project-store-8_AdCduJ.js → project-store-D0ALup9Z.js} +1 -1
  32. package/dist/web/assets/{settings-store-BhZ7VYJD.js → settings-store-BbFtHCGd.js} +2 -2
  33. package/dist/web/assets/settings-tab-BR9fp2pd.js +1 -0
  34. package/dist/web/assets/{sql-query-editor-h4zuID_d.js → sql-query-editor-BwquzTWY.js} +1 -1
  35. package/dist/web/assets/{sqlite-viewer-D5X8iWUw.js → sqlite-viewer-YO4IEGzt.js} +1 -1
  36. package/dist/web/assets/{system-monitor-tab-DL-viZmD.js → system-monitor-tab-C-WT_FG3.js} +1 -1
  37. package/dist/web/assets/terminal-tab-BqW8reuZ.js +3 -0
  38. package/dist/web/assets/{tool-cards-zK7OP3DS.js → tool-cards-DtF80k3f.js} +2 -2
  39. package/dist/web/assets/{use-blob-url-BYDGMRMU.js → use-blob-url-B3YovXF6.js} +1 -1
  40. package/dist/web/assets/{use-monaco-theme-Bk-dETGV.js → use-monaco-theme-CF_57XHm.js} +1 -1
  41. package/dist/web/assets/{video-preview-C6bKCBvz.js → video-preview-OoDYJ8U4.js} +1 -1
  42. package/dist/web/index.html +6 -6
  43. package/dist/web/sw.js +1 -1
  44. package/package.json +2 -2
  45. package/src/server/index.ts +4 -0
  46. package/src/server/routes/oauth-loopback.ts +75 -0
  47. package/src/web/components/layout/dock-panel.tsx +8 -1
  48. package/src/web/components/layout/mobile-nav.tsx +16 -2
  49. package/src/web/components/terminal/terminal-finish-login.tsx +75 -0
  50. package/src/web/components/terminal/terminal-links-sheet.tsx +53 -30
  51. package/src/web/components/ui/mobile-bottom-sheet.tsx +29 -26
  52. package/src/web/hooks/use-chat.ts +9 -8
  53. package/src/web/hooks/use-terminal.ts +18 -7
  54. package/src/web/hooks/use-usage.ts +11 -10
  55. package/src/web/hooks/use-visual-viewport.ts +83 -0
  56. package/src/web/lib/api-client.ts +17 -6
  57. package/src/web/lib/oauth-loopback-url.ts +55 -0
  58. package/dist/web/assets/api-client-BwMdPtp6.js +0 -1
  59. package/dist/web/assets/api-settings-D2fY0GUc.js +0 -1
  60. package/dist/web/assets/index-Crnizc26.js +0 -50
  61. package/dist/web/assets/index-opWDpE6A.css +0 -2
  62. package/dist/web/assets/keybindings-store-B4EWnplE.js +0 -1
  63. package/dist/web/assets/markdown-renderer-Bhv5w9Op.js +0 -1
  64. package/dist/web/assets/notification-store-B3zEJT3q.js +0 -1
  65. package/dist/web/assets/settings-tab-BqJJqL1l.js +0 -1
  66. package/dist/web/assets/terminal-tab-BVW9MfC3.js +0 -3
@@ -1,11 +1,11 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/edit-diff-preview-D1TEK7Jz.js","assets/rolldown-runtime-FhOqtrmT.js","assets/vendor-markdown-CKTlmXbz.js","assets/libesm-DdtEjhIi.js","assets/markdown-renderer-Bhv5w9Op.js","assets/vendor-mermaid-CYOBtZtD.js","assets/vendor-ui-DMRGWRuc.js","assets/markdown-renderer-suZuQvya.js","assets/index-Crnizc26.js","assets/dialog-HHdNInEH.js","assets/utils-E0yyGxXt.js","assets/createLucideIcon-ConhwJnb.js","assets/x-BsFLg-T8.js","assets/eye-off-Rq1n2-oe.js","assets/bot-E9mcVZnr.js","assets/context-menu-DIiZdfbE.js","assets/chevron-right-DeUue2aK.js","assets/use-is-mobile-BcuCjH19.js","assets/sparkles-B3DmG8PJ.js","assets/database-COYAMZaw.js","assets/plus-DcuJuDC3.js","assets/api-client-BgM59GxL.js","assets/react-8hrD3-kv.js","assets/api-settings-D108koFG.js","assets/project-store-8_AdCduJ.js","assets/panel-store-CpKvXNnm.js","assets/settings-store-BhZ7VYJD.js","assets/tab-store-BQmDVh9c.js","assets/apply-theme-BSJDABU3.js","assets/resolve-theme-B9Mgd5GG.js","assets/index-opWDpE6A.css","assets/image-gallery-CObzTisL.js","assets/api-client-BwMdPtp6.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-FhOqtrmT.js";import{b as t,y as n}from"./vendor-markdown-CKTlmXbz.js";import"./vendor-ui-DMRGWRuc.js";import{t as r}from"./createLucideIcon-ConhwJnb.js";import{t as i}from"./bot-E9mcVZnr.js";import{d as a,f as o,l as s}from"./context-menu-DIiZdfbE.js";import{n as c,r as l}from"./use-is-mobile-BcuCjH19.js";import{t as u}from"./chevron-right-DeUue2aK.js";import{a as d,i as f,n as p,r as m,t as h}from"./tool-cards-zK7OP3DS.js";import{a as g,c as _,i as v,n as y,o as b,r as x,t as S,u as C}from"./dialog-HHdNInEH.js";import{t as w}from"./code-TekEnDFM.js";import{n as ee,t as T}from"./sparkles-B3DmG8PJ.js";import{n as te,r as ne,t as re}from"./plus-DcuJuDC3.js";import{t as E}from"./shield-off-D5tU7gQT.js";import{t as D}from"./x-BsFLg-T8.js";import{i as O,n as k,r as ie,s as A}from"./api-client-BgM59GxL.js";import{q as j}from"./vendor-mermaid-CYOBtZtD.js";import{t as ae}from"./settings-store-BhZ7VYJD.js";import{n as M,r as oe,t as N}from"./utils-E0yyGxXt.js";import{t as P}from"./panel-store-CpKvXNnm.js";import{i as F}from"./project-store-8_AdCduJ.js";import{t as I}from"./tab-store-BQmDVh9c.js";import{_ as L,a as se,c as R,h as z,i as B,l as ce,m as le,o as V,p as H,r as U,s as W,t as G,u as K}from"./api-settings-D108koFG.js";import{$t as q,B as J,Bt as ue,Cn as de,Ct as Y,Et as fe,F as pe,Ft as me,Gt as he,H as X,Ht as ge,I as _e,It as ve,J as ye,Jt as be,Kt as xe,L as Se,Lt as Ce,Mt as we,N as Te,Ot as Ee,P as De,Pt as Oe,Qt as ke,R as Ae,Rt as Z,Sn as je,Tt as Me,U as Ne,Ut as Pe,V as Fe,Yt as Ie,Zt as Le,_n as Re,_t as ze,an as Be,bn as Ve,cn as He,dn as Ue,f as We,fn as Ge,gn as Ke,gt as qe,hn as Je,ht as Ye,jt as Xe,kt as Ze,nn as Qe,on as $e,ot as et,r as tt,rt as nt,t as rt,tn as it,vn as at,w as ot,wn as st,wt as ct,xn as lt,yn as ut,yt as dt,z as ft,zt as pt}from"./index-Crnizc26.js";import"./use-blob-url-BYDGMRMU.js";import{n as mt,r as ht,t as gt}from"./image-gallery-CObzTisL.js";import{t as _t}from"./libesm-DdtEjhIi.js";var vt=r(`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`}]]),yt=r(`chevrons-down`,[[`path`,{d:`m7 6 5 5 5-5`,key:`1lc07p`}],[`path`,{d:`m7 13 5 5 5-5`,key:`1d48rs`}]]),bt=r(`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`}]]),xt=r(`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`}]]),St=r(`image-off`,[[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`,key:`a6p6uj`}],[`path`,{d:`M10.41 10.41a2 2 0 1 1-2.83-2.83`,key:`1bzlo9`}],[`line`,{x1:`13.5`,x2:`6`,y1:`13.5`,y2:`21`,key:`1q0aeu`}],[`line`,{x1:`18`,x2:`21`,y1:`12`,y2:`15`,key:`5mozeu`}],[`path`,{d:`M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59`,key:`mmje98`}],[`path`,{d:`M21 15V5a2 2 0 0 0-2-2H9`,key:`43el77`}]]),Ct=r(`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`}]]),wt=r(`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`}]]),Tt=r(`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`}]]),Et=r(`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`}]]),Dt=r(`slash`,[[`path`,{d:`M22 2 2 22`,key:`y4kqgn`}]]),Q=e(t(),1);function Ot(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function kt(e,t){let n=`pc-${Ot(t)}-`;return e.map(e=>e.id?{...e,id:`${n}${e.id}`}:e)}function At(e,t){if(t.size===0)return e;let n=[];for(let r of e){let e=r.id?t.get(r.id):void 0;e&&e.length>0&&n.push(...e),n.push(r)}return n}var jt=null;function Mt(){return jt||=new AudioContext,jt}function Nt(e,t,n,r,i=`sine`){let a=Mt(),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 Pt(){let e=Mt().currentTime;Nt(523,.15,e,.15),Nt(659,.2,e+.12,.15)}function Ft(){let e=Mt().currentTime;Nt(880,.12,e,.18,`square`),Nt(698,.12,e+.15,.18,`square`),Nt(880,.15,e+.3,.15,`square`)}function It(){let e=Mt().currentTime;Nt(440,.12,e,.12),Nt(523,.12,e+.1,.12),Nt(659,.18,e+.2,.12)}var Lt={done:Pt,approval_request:Ft,question:It};function Rt(e){try{Lt[e]?.()}catch{}}var zt={hasTeams:!1,teamNames:[],messageCount:0,unreadCount:0};function Bt(e){if(document.hidden)return!1;let{panels:t}=P.getState();for(let n of Object.values(t)){let t=n.tabs.find(e=>e.id===n.activeTabId);if(t?.type===`chat`&&t.metadata?.sessionId===e)return!0}return!1}function Vt(e,t=`claude`,n=``){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(new Map),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)({}),[d,f]=(0,Q.useState)(`idle`),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(null),[w,ee]=(0,Q.useState)([]),T=(0,Q.useRef)([]),[te,ne]=(0,Q.useState)(null),[re,E]=(0,Q.useState)(null),[D,j]=(0,Q.useState)(!1),[ae,M]=(0,Q.useState)(null),[oe,N]=(0,Q.useState)(null),F=(0,Q.useRef)(null),I=(0,Q.useRef)(null),[L,se]=(0,Q.useState)(null),R=(0,Q.useRef)(null),[z,B]=(0,Q.useState)(!0),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(null),V=(0,Q.useRef)(``),H=(0,Q.useRef)([]),U=(0,Q.useRef)(new Map),W=(0,Q.useRef)(null),G=(0,Q.useRef)(`idle`),K=(0,Q.useRef)(null),q=(0,Q.useRef)(()=>{}),J=(0,Q.useRef)(null),ue=(0,Q.useRef)(!1),de=(0,Q.useRef)(new Set),Y=(0,Q.useRef)(0),fe=(0,Q.useRef)(null),pe=(0,Q.useRef)(e);pe.current=e;let me=(0,Q.useRef)([]);me.current=r;let he=(0,Q.useRef)(n);he.current=n;let X=(0,Q.useRef)(null),ge=(0,Q.useRef)(0),_e=(0,Q.useRef)({teamNames:new Set,messages:[]}),ve=(0,Q.useRef)(0),[ye,be]=(0,Q.useState)(zt),[xe,Se]=(0,Q.useState)([]),Ce=(0,Q.useCallback)(()=>{let e=_e.current;be({hasTeams:e.teamNames.size>0,teamNames:Array.from(e.teamNames),messageCount:e.messages.length,unreadCount:ve.current}),Se([...e.messages])},[]),we=(0,Q.useCallback)(()=>{ve.current=0,Ce()},[Ce]),Te=d!==`idle`;(0,Q.useEffect)(()=>{if(e)return et.getState().setStreaming(e,d!==`idle`),()=>{et.getState().setStreaming(e,!1)}},[e,d]);let Ee=(0,Q.useCallback)((e,t)=>{let n=H.current.findIndex(e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t);if(n===-1)return!1;let r=H.current[n];if(r.type!==`tool_use`)return!1;let i=[...r.children??[],e];return H.current[n]={...r,children:i},!0},[]),De=(0,Q.useCallback)(()=>{ge.current=0;let e=V.current,t=[...H.current],n=W.current;(0,Q.startTransition)(()=>{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}]})})},[]),Oe=(0,Q.useCallback)(()=>{ge.current||=window.setTimeout(De,100)},[De]),ke=(0,Q.useCallback)(e=>{let t=e,n=t?.type;if(!n)return;let r=e=>{let n=H.current,r=n.findIndex(e);r===-1?n.push(t):n[r]=t};switch(n){case`account_info`:W.current={accountId:t.accountId,accountLabel:t.accountLabel},ne(null);break;case`account_retry`:t.accountId&&t.accountLabel&&(W.current={accountId:t.accountId,accountLabel:t.accountLabel}),H.current=[t],Oe();break;case`status_update`:{let e=t.accountLabel?` (${t.accountLabel})`:``;ne(`${t.message}${e}`);break}case`text`:{let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}V.current+=t.content,H.current.push(t),Oe();break}case`thinking`:{let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}H.current.push(t),Oe();break}case`tool_use`:{if(t.tool===`AskUserQuestion`){t.toolUseId&&de.current.add(t.toolUseId);break}let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}let n=t.toolUseId;r(e=>!!n&&e.type===`tool_use`&&e.toolUseId===n),Oe();break}case`tool_result`:{let e=t.toolUseId;if(e&&U.current.delete(e),e&&de.current.has(e))break;let n=t.parentToolUseId;if(n&&Ee(t,n)){Oe();break}r(t=>!!e&&t.type===`tool_result`&&t.toolUseId===e),Oe();break}case`approval_resolved`:{let e=t.requestId;if(t.approved&&t.answers){let n=H.current.find(t=>t.type===`approval_request`&&t.requestId===e&&t.tool===`AskUserQuestion`),r=n&&n.input;r&&typeof r==`object`&&(r.answers=t.answers,i(e=>[...e]))}y(t=>t&&t.requestId===e?null:t),X.current!=null&&(A.dismiss(X.current),X.current=null);break}case`approval_request`:if(r(e=>e.type===`approval_request`&&e.requestId===t.requestId),ue.current)break;if(y({requestId:t.requestId,tool:t.tool,input:t.input}),pe.current&&!Bt(pe.current)){Rt(t.tool===`AskUserQuestion`?`question`:`approval_request`);let e=pe.current,n=t.tool===`AskUserQuestion`;X.current=A[n?`info`:`warning`](n?`AI has a question`:`${t.tool} needs permission`,{description:he.current||`Session ${e.slice(0,8)}`,duration:1/0,action:{label:`Go to session`,onClick:()=>{let{panels:t}=P.getState();for(let[n,r]of Object.entries(t)){let t=r.tabs.find(t=>t.metadata?.sessionId===e);if(t){P.getState().setActiveTab(t.id,n);break}}}}})}break;case`error`:i(e=>{let n=e[e.length-1];if(n?.role===`assistant`){let r=H.current,i=r[r.length-1],a=i?.type===`error`&&i.message===t.message?r:[...r,t];return H.current=a,[...e.slice(0,-1),{...n,events:a}]}return n?.role===`system`&&n.content===t.message?e:[...e,{id:`error-${Date.now()}`,role:`system`,content:t.message,events:[t],timestamp:new Date().toISOString()}]});break;case`team_detected`:{let e=t.teamName;e&&(_e.current.teamNames.add(e),k.get(`/api/teams/${encodeURIComponent(e)}`).then(e=>{if(e?.messages){let t=_e.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()),t.length>500&&t.splice(0,t.length-500)}Ce()}).catch(()=>{}),Ce());break}case`team_inbox`:{let e=t.messages;if(Array.isArray(e)){let t=_e.current.messages;t.push(...e),t.length>500&&t.splice(0,t.length-500),ve.current+=e.length,Ce()}break}case`team_updated`:Ce();break;case`bash_output`:{let e=t.toolUseId;if(e){let n=U.current.get(e);n?(n.content+=t.content,n.content.length>5e5&&(n.content=n.content.slice(-5e5)),n.lineCount=t.lineCount):U.current.set(e,{content:t.content,lineCount:t.lineCount}),Oe()}break}case`background_registry`:{let e=t.shells??[];T.current=e,ee(e);break}case`done`:{if(G.current===`idle`)break;t.contextWindowPct!=null&&x(t.contextWindowPct),pe.current&&!Bt(pe.current)&&Rt(`done`),ge.current&&=(clearTimeout(ge.current),0);let e=V.current,n=[...H.current],r=W.current,a=t.lastMessageUuid;i(t=>{let i=t[t.length-1];return i?.role===`assistant`?[...t.slice(0,-1),{...i,id:`final-${Date.now()}`,content:e||i.content,events:n.length>0?n:i.events,...a&&{sdkUuid:a}}]:e||n.length>0?[...t,{id:`final-${Date.now()}`,role:`assistant`,content:e,events:n,timestamp:new Date().toISOString(),...a&&{sdkUuid:a},...r}]:t}),V.current=``,H.current=[],W.current=null,fe.current=null,U.current.clear(),ne(null);break}}},[Ee,Oe]),Ae=(0,Q.useCallback)(e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(t.type!==`ping`){if(t.type===`title_updated`){E(t.title??null);return}if(t.type===`compact_status`){let e=t.status;e===`compacting`?C(`compacting`):e===`done`&&C(null);return}if(t.type===`phase_changed`){let e=t.phase;f(e),G.current=e,_(e===`connecting`?t.elapsed??0:0),e===`idle`&&C(null);return}if(t.type===`session_state`){j(!0),M(t.sessionId??pe.current);let e=t,n=e.phase;f(n),G.current=n,e.sessionTitle&&E(e.sessionTitle),e.model&&(I.current&&e.model!==I.current||(e.model===I.current&&(I.current=null),N(e.model),F.current=e.model)),typeof e.effort==`string`&&(se(e.effort),R.current=e.effort),typeof e.thinking==`boolean`&&B(e.thinking),e.pendingApproval&&y({requestId:e.pendingApproval.requestId,tool:e.pendingApproval.tool,input:e.pendingApproval.input}),C(e.compactStatus===`compacting`?`compacting`:null),n===`idle`&&(J.current?.(),h(!1));return}if(t.type===`turn_events`){let e=t.events,n=t.userMessage;if(!e?.length&&!n){h(!1);return}Y.current&&=(cancelAnimationFrame(Y.current),0),fe.current=n,i(e=>{let t=[...e],r=t.length;for(;r>0&&t[r-1].role===`assistant`;)r--;if(n!=null&&r>0&&t[r-1].role===`user`&&t[r-1].content===n)t=t.slice(0,r-1);else{let e=t[t.length-1];e?.role===`assistant`&&e.id.startsWith(`streaming-`)&&(t=t.slice(0,-1))}if(n){let e=t[t.length-1];(e?.role!==`user`||e.content!==n)&&(t=[...t,{id:`user-replay-${Date.now()}`,role:`user`,content:n,timestamp:new Date().toISOString()}])}return t}),V.current=``,H.current=[],W.current=null,ue.current=!0;let r=0,a=()=>{let t=Math.min(r+100,e.length);for(let n=r;n<t;n++)ke(e[n]);r=t,r<e.length?Y.current=requestAnimationFrame(a):(Y.current=0,ue.current=!1,h(!1))};Y.current=requestAnimationFrame(a);return}ke(t)}},[ke]),{send:Z,connect:je}=p({url:e&&n?`/ws/project/${encodeURIComponent(n)}/chat/${e}`:``,onMessage:Ae,autoConnect:!!e&&!!n});q.current=Z,(0,Q.useEffect)(()=>{let r=!1;le.current&&le.current!==e&&(I.current=null,ce.current=null),le.current=e??null,f(`idle`),G.current=`idle`,y(null),X.current!=null&&(A.dismiss(X.current),X.current=null),C(null),o(new Map),u({}),V.current=``,H.current=[],fe.current=null,U.current.clear(),ge.current&&=(clearTimeout(ge.current),0),j(!1),M(null),_e.current={teamNames:new Set,messages:[]},ve.current=0,be(zt),Se([]);let a=new Set(me.current.map(e=>e.id));return e&&n?(c(!0),fetch(`${O(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${ie()}`}}).then(e=>e.json()).then(e=>{if(r)return;let t=e.ok?Array.isArray(e.data)?{messages:e.data,versionMap:{}}:e.data:null,n=Array.isArray(t?.messages)?t.messages:[];t?.versionMap&&u(t.versionMap);let o=fe.current;if(o!=null){for(let e=n.length-1;e>=0;e--)if(n[e].role===`user`&&n[e].content===o){n=n.slice(0,e);break}}i(e=>{let t=e.filter(e=>!a.has(e.id));return[...n,...t]})}).catch(()=>{r||i(e=>e.filter(e=>!a.has(e.id)))}).finally(()=>{r||c(!1)})):i([]),()=>{r=!0}},[e,t,n]);let Me=(0,Q.useCallback)((e,t)=>{if(!e.trim())return;let n=G.current!==`idle`;if(n){ge.current&&=(clearTimeout(ge.current),0);let e=V.current,t=[...H.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()}]),V.current=``,H.current=[],K.current=null,n?(f(`thinking`),G.current=`thinking`):(f(`initializing`),G.current=`initializing`),y(null),X.current!=null&&(A.dismiss(X.current),X.current=null),Z(JSON.stringify({type:`message`,content:e,permissionMode:t?.permissionMode,priority:t?.priority,images:t?.images,...F.current&&{model:F.current},...R.current&&{effort:R.current},...ce.current!==null&&{thinking:ce.current}}))},[Z]),Ne=(0,Q.useCallback)(e=>{N(e),F.current=e,I.current=e,Z(JSON.stringify({type:`set_model`,model:e}))},[Z]),Pe=(0,Q.useCallback)(e=>{se(e),R.current=e,Z(JSON.stringify({type:`set_effort`,effort:e}))},[Z]),Fe=(0,Q.useCallback)(e=>{B(e),ce.current=e,Z(JSON.stringify({type:`set_thinking`,enabled:e}))},[Z]),Ie=(0,Q.useCallback)((e,t,n)=>{if(Z(JSON.stringify({type:`approval_response`,requestId:e,approved:t,data:n})),t&&n){let t=H.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])}y(null),X.current!=null&&(A.dismiss(X.current),X.current=null)},[Z]),Le=(0,Q.useCallback)(()=>{if(G.current===`idle`)return;Z(JSON.stringify({type:`cancel`}));let e=V.current,t=[...H.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}),V.current=``,H.current=[],U.current.clear(),K.current=null,f(`idle`),G.current=`idle`,y(null),X.current!=null&&(A.dismiss(X.current),X.current=null)},[Z]),Re=(0,Q.useCallback)(e=>{e&&Z(JSON.stringify({type:`kill_background_shell`,shellId:e}))},[Z]),ze=(0,Q.useCallback)(e=>{if(!e)return;let t=e.replace(/\.output$/,``);return T.current.find(n=>n.shellId===t||n.outputPath.endsWith(e)||n.outputPath.endsWith(`${t}.output`))},[]);(0,Q.useEffect)(()=>{e&&rt.getState().setSessionShells(e,w)},[e,w]),(0,Q.useEffect)(()=>{if(e)return rt.getState().retainSession(e),()=>{rt.getState().releaseSession(e)}},[e]);let Be=(0,Q.useCallback)(()=>{j(!1),h(!0),je()},[je]),Ve=(0,Q.useCallback)(()=>{!e||!n||fetch(`${O(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${ie()}`}}).then(e=>e.json()).then(e=>{if(G.current!==`idle`)return;let t=e.ok?Array.isArray(e.data)?{messages:e.data,versionMap:void 0}:e.data:null;t?.versionMap&&u(t.versionMap),Array.isArray(t?.messages)&&t.messages.length>0&&(i(t.messages),V.current=``,H.current=[])}).catch(()=>{})},[e,t,n]);J.current=Ve;let He=(0,Q.useCallback)(async(e,t)=>{if(!n)throw Error(`No project context available`);let r=e.replace(/^pc-[^-]+-/,``),i=`${O(n)}/chat/pre-compact-messages?jsonlPath=${encodeURIComponent(t)}&before=${encodeURIComponent(r)}`,a=kt(await k.get(i),t);return o(t=>{let n=new Map(t);return n.set(e,a),n}),a.length},[n]),Ue=(0,Q.useCallback)(e=>a.has(e),[a]),We=(0,Q.useCallback)(e=>{i(t=>t.filter(t=>t.id!==e))},[]),Ge=(0,Q.useCallback)(()=>{i(e=>e.filter(e=>e.role!==`system`))},[]);return{messages:r,renderedMessages:(0,Q.useMemo)(()=>At(r,a),[r,a]),expandCompact:He,isCompactExpanded:Ue,dismissMessage:We,clearErrors:Ge,messagesLoading:s,versionMap:l,isStreaming:Te,phase:d,isReconnecting:m,connectingElapsed:g,pendingApproval:v,contextWindowPct:b,compactStatus:S,statusMessage:te,sessionTitle:re,model:oe,setModel:Ne,effort:L,setEffort:Pe,thinking:z,setThinking:Fe,teamActivity:ye,teamMessages:xe,markTeamRead:we,bashPartialOutput:U,backgroundShells:w,killBackgroundShell:Re,findBackgroundShellByOutput:ze,sendMessage:Me,respondToApproval:Ie,cancelStreaming:Le,reconnect:Be,refetchMessages:Ve,isConnected:D&&ae===e}}var Ht=12e4;function Ut(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(`${O(e)}/chat/usage?providerId=${t}${i}`,{headers:{Authorization:`Bearer ${ie()}`}}).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 Wt={damping:.7,stiffness:.05,mass:1.25},Gt=70,Kt=1e3/60,qt=350,Jt=!1;globalThis.document?.addEventListener(`mousedown`,()=>{Jt=!0}),globalThis.document?.addEventListener(`mouseup`,()=>{Jt=!1}),globalThis.document?.addEventListener(`click`,()=>{Jt=!1});var Yt=(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(!Jt)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){if(g.current){let{scrollBehavior:t}=getComputedStyle(g.current);t!==`auto`&&(g.current.style.scrollBehavior=`auto`),g.current.scrollTop=e,d.ignoreScrollToTop=g.current.scrollTop,t!==`auto`&&(g.current.style.scrollBehavior=t)}},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<=Gt}}},[]),f=(0,Q.useCallback)((e={})=>{typeof e==`string`&&(e={animation:e}),e.preserveScrollPosition||l(!0);let t=Date.now()+(Number(e.wait)||0),n=Qt(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))/Kt;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:Qt(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=Xt(e=>{g.current?.removeEventListener(`scroll`,m),g.current?.removeEventListener(`wheel`,h),e?.addEventListener(`scroll`,m,{passive:!0}),e?.addEventListener(`wheel`,h,{passive:!0})},[]),_=Xt(e=>{if(d.resizeObserver?.disconnect(),d.resizeObserver=void 0,!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=Qt(s.current,t?s.current.resize:s.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:e===`instant`?void 0:qt})}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 Xt(e,t){let n=(0,Q.useCallback)(t=>(n.current=t,e(t)),t);return n}var Zt=new Map;function Qt(...e){let t={...Wt},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 Zt.has(r)||Zt.set(r,Object.freeze(t)),n?`instant`:Zt.get(r)}var $t=60,en=8,tn=1400;function nn(e){if(e.scrollHeight<=e.clientHeight)return!1;let t=getComputedStyle(e).overflowY;return t===`auto`||t===`scroll`}function rn(e,t){let n=[],r=e.parentElement;for(;r&&r!==t;)nn(r)&&n.push(r),r=r.parentElement;return n}function an(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}function on(e,t){let n=e.querySelector(`[data-edit-ref="${CSS.escape(t)}"]`);if(n)return{el:n,level:`edit`};let r=t.replace(/-\d+$/,``),i=e.querySelector(`[data-tool-ref="${CSS.escape(r)}"]`);return i?{el:i,level:`card`}:null}function sn(e,t,n,r){let i=e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-n;e.scrollTo({top:i,behavior:r?`smooth`:`auto`})}function cn(e,t){let n=on(e,t);if(!n)return()=>{};let{el:r,level:i}=n;for(let t of rn(r,e))sn(t,r,en,!1);sn(e,r,$t,!an()),r.dataset.flash=i;let a=setTimeout(()=>{delete r.dataset.flash},tn);return()=>{clearTimeout(a),delete r.dataset.flash}}var ln=new Set([`Write`,`Edit`,`MultiEdit`,`NotebookEdit`]),un={create:3,write:2,notebook:2,edit:1};function dn(e){return typeof e==`string`?e:``}function fn(e,t){let n=0,r=0;for(let i of _t(e,t))i.added?n+=i.count??0:i.removed&&(r+=i.count??0);return{added:n,removed:r}}function pn(e){return e&&/created successfully/i.test(e)?`create`:`write`}function mn(e,t,n){switch(e){case`Write`:{let e=dn(t.file_path);return e?{filePath:e,op:pn(n),fragments:[{oldStr:``,newStr:dn(t.content)}]}:null}case`Edit`:{let e=dn(t.file_path);return e?{filePath:e,op:`edit`,fragments:[{oldStr:dn(t.old_string),newStr:dn(t.new_string)}]}:null}case`MultiEdit`:{let e=dn(t.file_path);if(!e||!Array.isArray(t.edits))return null;let n=t.edits.filter(e=>!!e&&typeof e==`object`).map(e=>({oldStr:dn(e.old_string),newStr:dn(e.new_string)}));return n.length===0?null:{filePath:e,op:`edit`,fragments:n}}case`NotebookEdit`:{let e=dn(t.notebook_path)||dn(t.file_path);return e?{filePath:e,op:`notebook`,fragments:[{oldStr:``,newStr:dn(t.new_source)}]}:null}default:return null}}function hn(e,t){if(e){for(let n of e)if(n.type===`tool_result`&&n.toolUseId&&t.set(n.toolUseId,n.output??``),n.type===`tool_use`){let e=n.result;n.toolUseId&&e?.output!=null&&!t.has(n.toolUseId)&&t.set(n.toolUseId,e.output),hn(n.children,t)}}}function gn(e,t,n,r){if(e)for(let i of e){if(i.type!==`tool_use`||(i.children?.length&&gn(i.children,!0,n,r),!ln.has(i.tool)))continue;let e=i.input&&typeof i.input==`object`?i.input:null;if(!e)continue;let a=mn(i.tool,e,i.toolUseId?r.get(i.toolUseId):void 0);if(!a)continue;let o=n.get(a.filePath);o||(o={filePath:a.filePath,op:a.op,editCount:0,linesAdded:0,linesRemoved:0,edits:[],viaSubagent:!1},n.set(a.filePath,o)),un[a.op]>un[o.op]&&(o.op=a.op),t&&(o.viaSubagent=!0),a.fragments.forEach((e,n)=>{let{added:r,removed:a}=fn(e.oldStr,e.newStr);o.linesAdded+=r,o.linesRemoved+=a,o.editCount+=1,o.edits.push({...e,toolUseId:i.toolUseId,editIndex:n,editRef:i.toolUseId?`${i.toolUseId}-${n}`:void 0,viaSubagent:t})})}}function _n(e){let t=new Map;for(let n of e)hn(n.events,t);let n=new Map;for(let r of e)gn(r.events,!1,n,t);return[...n.values()]}function vn(e,t){let n=[];for(let r=t;r>=0&&e[r]?.role===`assistant`;r--)n.unshift(e[r]);return n}var $=n();function yn(e){try{return new Date(e).toLocaleString()}catch{return``}}function bn({icon:e,label:t,title:n,onClick:r}){return(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:n,"aria-label":t,className:`inline-flex items-center justify-center gap-1 rounded-md px-1.5 py-1 text-text-subtle hover:text-text-primary hover:bg-surface transition-colors`,children:[e,(0,$.jsx)(`span`,{children:t})]})}function xn({content:e}){let[t,n]=(0,Q.useState)(!1);return(0,$.jsx)(bn,{icon:t?(0,$.jsx)(a,{className:`size-3.5`}):(0,$.jsx)(Ge,{className:`size-3.5`}),label:t?`Copied`:`Copy`,title:`Copy message to clipboard`,onClick:()=>{nt(e),n(!0),setTimeout(()=>n(!1),1500)}})}function Sn({timestamp:e,content:t,accountLabel:n,className:r,children:i}){return(0,$.jsxs)(`div`,{className:M(`flex items-center gap-0.5 flex-wrap text-xs text-text-subtle select-none`,r),children:[(0,$.jsx)(`time`,{title:yn(e),className:`pr-1 tabular-nums`,children:Me(e)}),n&&(0,$.jsxs)(`span`,{className:`px-1 truncate max-w-40`,children:[`via `,n]}),(0,$.jsx)(xn,{content:t}),i]})}function Cn(e){let t=0,n=0;for(let r of e)t+=r.linesAdded,n+=r.linesRemoved;return{added:t,removed:n}}function wn({count:e,totals:t,open:n,onToggle:r,ref:i}){let a=`${e} file${e===1?``:`s`}`;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":!0,className:`mx-1.5 h-3.5 w-px bg-border-soft`}),(0,$.jsxs)(`button`,{ref:i,type:`button`,onClick:r,"aria-expanded":n,"aria-label":`${a} changed this turn, ${t.added} added, ${t.removed} removed`,className:M(`inline-flex items-center gap-[7px] rounded-full font-mono text-[11.5px]`,`px-3 min-h-11 md:min-h-0 md:px-[9px] md:py-[5px]`,`text-text-secondary transition-colors hover:bg-surface hover:text-text-primary`),children:[(0,$.jsx)(`span`,{"aria-hidden":!0,className:`size-[5px] shrink-0 rounded-full bg-primary`}),(0,$.jsx)(`span`,{children:a}),(0,$.jsxs)(`span`,{className:`flex items-center gap-[5px] tabular-nums`,children:[(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,t.added]}),(0,$.jsxs)(`span`,{className:`text-error`,children:[`−`,t.removed]})]})]})]})}function Tn(e){if(!e)return!1;let t=e.closest(`[data-tab-pool-id]`)?.dataset.tabPoolId;if(!t)return e.offsetParent!==null;let{panels:n,focusedPanelId:r}=P.getState();return n[r]?.activeTabId===t}var En={create:{glyph:`A`,cls:`text-success`,label:`created`},write:{glyph:`W`,cls:`text-warning`,label:`overwritten`},notebook:{glyph:`N`,cls:`text-accent-2`,label:`notebook edited`},edit:{glyph:`·`,cls:`text-text-subtle`,label:`edited`}};function Dn(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?{base:e,dir:``}:{base:e.slice(t+1),dir:e.slice(0,t)}}function On({added:e,removed:t,editCount:n,className:r}){return(0,$.jsxs)(`span`,{className:M(`flex items-center gap-[5px] tabular-nums`,r),children:[(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,e]}),(0,$.jsxs)(`span`,{className:`text-error`,children:[`−`,t]}),n!=null&&n>1&&(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[`×`,n]})]})}function kn({change:e,dense:t,selected:n,onClick:r}){let i=En[e.op],{base:a,dir:o}=Dn(e.filePath),s=e.viaSubagent?`${i.label} · changed by a sub-agent`:i.label;return(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:e.filePath,className:M(`grid w-full grid-cols-[16px_1fr_auto_10px] items-center gap-[10px] text-left font-mono`,`border-b border-border-soft hover:bg-surface transition-colors`,t?`min-h-[38px] px-2.5 py-[5px] text-xs`:`min-h-[52px] px-3 py-[7px] text-[12.5px]`,n&&`bg-surface shadow-[inset_2px_0_0_var(--accent)]`),children:[(0,$.jsx)(`span`,{"aria-label":s,title:s,className:M(`inline-flex size-4 items-center justify-center rounded bg-white/5 text-[9px] font-semibold`,i.cls,e.viaSubagent&&`bg-accent-2/20 ring-1 ring-inset ring-accent-2/35`),children:i.glyph}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block truncate text-text-primary`,children:a}),o&&(0,$.jsx)(`span`,{className:`block overflow-hidden text-ellipsis whitespace-nowrap text-[10px] text-text-subtle [direction:rtl] text-left`,children:o})]}),(0,$.jsx)(On,{added:e.linesAdded,removed:e.linesRemoved,editCount:e.editCount,className:`text-[11px]`}),(0,$.jsx)(u,{className:`size-[11px] text-text-subtle`})]})}var An=(0,Q.lazy)(()=>j(()=>import(`./edit-diff-preview-D1TEK7Jz.js`),__vite__mapDeps([0,1,2,3])));function jn({change:e,onJump:t}){return(0,$.jsx)(`div`,{children:e.edits.map((n,r)=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`button`,{type:`button`,disabled:!n.editRef,onClick:()=>n.editRef&&t(n.editRef),className:`group flex min-h-11 w-full items-center gap-2 px-3 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface disabled:hover:bg-transparent`,children:[(0,$.jsxs)(`span`,{children:[`edit `,r+1,` of `,e.editCount]}),(0,$.jsx)(`span`,{className:`h-px flex-1 bg-border-soft`}),n.editRef&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 group-hover:text-primary`,children:[(0,$.jsx)(st,{className:`size-3`}),`jump`]})]}),(0,$.jsx)(`div`,{className:`mx-3 mb-1`,children:(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`h-4`}),children:(0,$.jsx)(An,{oldStr:n.oldStr,newStr:n.newStr,filePath:e.filePath})})})]},n.editRef??r))})}function Mn(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?{base:e,dir:``}:{base:e.slice(t+1),dir:e.slice(0,t)}}var Nn=null;function Pn(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function Fn({changes:e,onJump:t,onClose:n}){let[r,i]=(0,Q.useState)(0),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),s=(0,Q.useId)();(0,Q.useEffect)(()=>(Nn=s,o.current?.querySelector(`button`)?.focus(),()=>{Nn===s&&(Nn=null)}),[s]),(0,Q.useEffect)(()=>{let o=o=>{if(Nn===s&&Tn(a.current)&&!Pn(document.activeElement)){if(o.key===`Escape`)o.preventDefault(),n();else if(o.key===`j`)o.preventDefault(),i(t=>Math.min(t+1,e.length-1));else if(o.key===`k`)o.preventDefault(),i(e=>Math.max(e-1,0));else if(o.key===`Enter`){let n=e[r]?.edits[0]?.editRef;n&&(o.preventDefault(),t(n))}}};return window.addEventListener(`keydown`,o),()=>window.removeEventListener(`keydown`,o)},[s,e,r,t,n]);let c=e[Math.min(r,e.length-1)];if(!c)return null;let{base:l,dir:u}=Mn(c.filePath);return(0,$.jsx)(`div`,{ref:a,className:`mt-0.5 overflow-hidden rounded-[10px] border border-border-soft bg-bg`,children:(0,$.jsxs)(`div`,{className:`grid h-[356px] grid-cols-[294px_1fr] grid-rows-[minmax(0,1fr)] bg-surface-elevated`,children:[(0,$.jsxs)(`div`,{ref:o,className:`min-h-0 overflow-y-auto border-r border-border-soft`,children:[e.map((e,t)=>(0,$.jsx)(kn,{change:e,dense:!0,selected:t===r,onClick:()=>i(t)},e.filePath)),(0,$.jsx)(`p`,{className:`px-2.5 pt-2 pb-2.5 font-mono text-[10px] text-text-subtle`,children:`j / k to move · enter to jump`})]}),(0,$.jsxs)(`div`,{className:`min-h-0 overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center gap-2 border-b border-border-soft bg-surface-elevated py-[5px] pl-2.5 pr-2`,children:[(0,$.jsx)(`span`,{className:`shrink-0 font-mono text-xs font-medium text-text-primary`,children:l}),u&&(0,$.jsx)(`span`,{title:c.filePath,className:`min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-[10.5px] text-text-subtle [direction:rtl] text-left`,children:u}),(0,$.jsx)(On,{added:c.linesAdded,removed:c.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void nt(c.filePath),className:`shrink-0 rounded-md px-1.5 py-1 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:`copy path`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close change tray`,className:`inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:(0,$.jsx)(D,{className:`size-3.5`})})]}),(0,$.jsx)(jn,{change:c,onJump:t})]})]})})}function In(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?e:e.slice(t+1)}function Ln({label:e,onClick:t,children:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-label":e,className:`inline-flex size-11 shrink-0 items-center justify-center rounded-lg text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:n})}function Rn({changes:e,totals:t,open:n,onClose:r,onJump:i}){let[a,o]=(0,Q.useState)(null),s=a==null?null:e[a],c=(0,Q.useRef)(null),l=()=>{o(null),r()},u=e=>{l(),i(e)};return(0,Q.useEffect)(()=>{if(!n)return;let e=c.current,t=()=>Array.from(e?.querySelectorAll(`button:not([disabled])`)??[]);t()[0]?.focus();let r=e=>{if(e.key===`Escape`){e.preventDefault(),l();return}if(e.key!==`Tab`)return;let n=t();if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus())};return window.addEventListener(`keydown`,r),()=>window.removeEventListener(`keydown`,r)},[n,a]),(0,$.jsx)(ye,{open:n,onClose:l,className:`flex max-h-[85%] flex-col rounded-t-[14px] motion-reduce:animate-none`,children:(0,$.jsx)(`div`,{ref:c,className:`flex min-h-0 flex-1 flex-col`,children:s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 border-b border-border-soft px-1 pb-1`,children:[(0,$.jsx)(Ln,{label:`Back to file list`,onClick:()=>o(null),children:(0,$.jsx)(Ve,{className:`size-4`})}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs font-medium text-text-primary`,children:In(s.filePath)}),(0,$.jsx)(On,{added:s.linesAdded,removed:s.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Ln,{label:`Close`,onClick:l,children:(0,$.jsx)(D,{className:`size-4`})})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 border-b border-border-soft py-1.5 pl-3 pr-2`,children:[(0,$.jsx)(`span`,{title:s.filePath,className:`min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-[10.5px] text-text-subtle [direction:rtl] text-left`,children:s.filePath}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void nt(s.filePath),className:`inline-flex min-h-11 shrink-0 items-center rounded-md px-2.5 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:`copy`}),s.edits[0]?.editRef&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(s.edits[0].editRef),className:`inline-flex min-h-11 shrink-0 items-center gap-1 rounded-md px-2.5 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-primary`,children:[(0,$.jsx)(st,{className:`size-3`}),`card`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,$.jsx)(jn,{change:s,onJump:u})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border-soft px-3 pb-2`,children:[(0,$.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs font-medium text-text-primary`,children:[`Changed this turn · `,e.length,` file`,e.length===1?``:`s`]}),(0,$.jsx)(On,{added:t.added,removed:t.removed,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Ln,{label:`Close`,onClick:l,children:(0,$.jsx)(D,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.map((e,t)=>(0,$.jsx)(kn,{change:e,onClick:()=>o(t)},e.filePath))})]})})})}function zn({timestamp:e,content:t,accountLabel:n,changes:r,onJumpToEdit:i}){let[a,o]=(0,Q.useState)(!1),s=c(),l=(0,Q.useRef)(null),u=()=>{o(!1),l.current?.focus()},d=(0,$.jsx)(Sn,{timestamp:e,content:t,accountLabel:n,className:`-mt-1.5`,children:r&&r.length>0&&(0,$.jsx)(wn,{ref:l,count:r.length,totals:Cn(r),open:a,onToggle:()=>a?u():o(!0)})});return!r||r.length===0?d:(0,$.jsxs)($.Fragment,{children:[d,s?(0,$.jsx)(Rn,{changes:r,totals:Cn(r),open:a,onClose:u,onJump:i??(()=>{})}):a&&(0,$.jsx)(Fn,{changes:r,onJump:e=>{o(!1),i?.(e)},onClose:u})]})}function Bn(e,t,n,r){let[i,a]=(0,Q.useState)([]),o=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!n||!e||!t){a([]);return}let r=!1;return o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{k.get(`/api/project/${encodeURIComponent(e)}/chat/sessions/${encodeURIComponent(t)}/tasks`).then(e=>{r||a(e)}).catch(()=>{})},300),()=>{r=!0,o.current&&clearTimeout(o.current)}},[e,t,n,r]),i}var Vn=new Set([`TaskCreate`,`TaskUpdate`,`TaskStop`]);function Hn(e){let t=0;for(let n of e)if(n.events)for(let e of n.events)e.type===`tool_use`&&Vn.has(e.tool)&&t++;return t}var Un={completed:{icon:`✓`,cls:`text-success`},in_progress:{icon:`▶`,cls:`text-warning`},stopped:{icon:`■`,cls:`text-text-subtle`},pending:{icon:`○`,cls:`text-text-subtle`}};function Wn({projectName:e,sessionId:t,messages:n}){let r=(0,Q.useMemo)(()=>Hn(n),[n]),i=Bn(e,t,r>0,r),[a,o]=(0,Q.useState)(!0);if(i.length===0||i.every(e=>e.status===`completed`||e.status===`stopped`))return null;let s=i.filter(e=>e.status===`completed`).length,c=i.length,d=c?Math.round(s/c*100):0;return(0,$.jsxs)(`div`,{className:`shrink-0 border-b border-border bg-surface/60 backdrop-blur-sm`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o(e=>!e),className:`flex items-center gap-2 w-full px-3 min-h-11 text-left text-xs hover:bg-surface transition-colors`,children:[a?(0,$.jsx)(u,{className:`size-3.5 shrink-0`}):(0,$.jsx)(l,{className:`size-3.5 shrink-0`}),(0,$.jsx)(m,{className:`size-3.5 shrink-0 text-text-secondary`}),(0,$.jsx)(`span`,{className:`text-text-primary font-medium`,children:`Tasks`}),(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[s,`/`,c,` done`]}),(0,$.jsx)(`span`,{className:`ml-auto h-1 w-16 rounded-full bg-border overflow-hidden shrink-0`,children:(0,$.jsx)(`span`,{className:`block h-full bg-success/70`,style:{width:`${d}%`}})})]}),!a&&(0,$.jsx)(`ul`,{className:`px-3 pb-2 space-y-0.5 max-h-48 overflow-y-auto`,children:i.map(e=>(0,$.jsx)(Gn,{task:e},e.id))})]})}function Gn({task:e}){let t=Un[e.status]??Un.pending,n=e.status===`in_progress`;return(0,$.jsxs)(`li`,{className:`flex items-start gap-1.5 text-xs rounded px-1 ${n?`bg-warning/10`:``}`,children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5 ${t.cls}`,children:t.icon}),(0,$.jsx)(`span`,{className:e.status===`completed`?`line-through text-text-subtle`:n?`text-text-primary font-medium`:`text-text-secondary`,children:e.subject||(0,$.jsxs)(`span`,{className:`text-text-subtle italic`,children:[`#`,e.id,` (no title)`]})})]})}var Kn=/read the full transcript at:\s*(\S+\.jsonl)/i;function qn(e){return e.match(Kn)?.[1]?.trim()??null}var Jn=class extends Q.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback?this.props.fallback:this.props.fallbackContent?(0,$.jsx)(`div`,{className:`text-sm whitespace-pre-wrap break-words text-text-primary opacity-80`,children:this.props.fallbackContent}):null:this.props.children}};function Yn({projectName:e,onSelectSession:t}){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)(i,{className:`size-10 text-text-subtle`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Send a message to start a new conversation`})]}),(0,$.jsx)(qe,{projectName:e,onSelectSession:t,className:`w-full px-4`})]})}var Xn=3200,Zn=1e3,Qn={hasAbove:!1,atBottom:!0,idx:0,total:0};function $n({scrollElement:e,userIndices:t,scrollToBottom:n}){let r=c(),[i,a]=(0,Q.useState)(Qn),[o,s]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(0),f=(0,Q.useRef)(Xn),p=(0,Q.useRef)(null),m=(0,Q.useRef)(null),h=(0,Q.useRef)(!1),g=(0,Q.useRef)(!1),_=(e,t,n)=>t.getBoundingClientRect().top-n+e.scrollTop,v=(0,Q.useCallback)(e=>Array.from(e.querySelectorAll(`[data-msg-index]`)).filter(e=>t.includes(Number(e.dataset.msgIndex))),[t]);(0,Q.useEffect)(()=>{let t=e;if(!t)return;let n=0,r=()=>{let e=t.scrollTop,n=t.getBoundingClientRect().top,r=v(t).map(e=>_(t,e,n)),i=0;for(let t=0;t<r.length;t++)r[t]<=e+12&&(i=t+1);let o={hasAbove:r.some(t=>t<e-4),atBottom:t.scrollHeight-e-t.clientHeight<8,idx:i,total:r.length};a(e=>e.hasAbove===o.hasAbove&&e.atBottom===o.atBottom&&e.idx===o.idx&&e.total===o.total?e:o)},i=()=>{n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r(),t.addEventListener(`scroll`,i,{passive:!0});let o=new ResizeObserver(i);return o.observe(t),()=>{n&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,i),o.disconnect()}},[e,v]),(0,Q.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>s(!1),f.current);return()=>clearTimeout(e)},[o,i.idx,u]),(0,Q.useEffect)(()=>{if(!o||!g.current)return;g.current=!1;let e=p.current;(e?.querySelector(`button:not(:disabled)`)??e)?.focus()},[o]),(0,Q.useEffect)(()=>{o||!h.current||(h.current=!1,m.current?.focus())},[o]);let y=(0,Q.useCallback)(()=>{f.current=Xn,d(e=>e+1)},[]),b=(0,Q.useCallback)(()=>{let t=e;if(!t)return;let n=t.scrollTop,r=t.getBoundingClientRect().top,i;for(let e of v(t)){let a=_(t,e,r);if(a<n-4)i=a;else break}i!=null&&t.scrollTo({top:i,behavior:`auto`}),y()},[e,v,y]),x=(0,Q.useCallback)(()=>{let t=e;if(!t)return;let r=t.scrollTop,i=t.getBoundingClientRect().top,a=v(t).map(e=>_(t,e,i)).find(e=>e>r+4);a==null?n({animation:`instant`}):t.scrollTo({top:a,behavior:`auto`}),y()},[e,v,n,y]),S=(0,Q.useCallback)(()=>{n({animation:`instant`}),y()},[n,y]);(0,Q.useEffect)(()=>{let t=e;if(!t)return;let n=e=>()=>{Tn(t)&&(e(),f.current=Zn,s(!0))},r=n(b),i=n(x);return window.addEventListener(`chat-nav-prev`,r),window.addEventListener(`chat-nav-next`,i),()=>{window.removeEventListener(`chat-nav-prev`,r),window.removeEventListener(`chat-nav-next`,i)}},[e,b,x]);let C=M(`w-[34px] flex items-center justify-center rounded-[9px] text-text-secondary`,`motion-safe:transition-colors hover:bg-surface-elevated hover:text-foreground`,`disabled:opacity-30 disabled:cursor-default disabled:hover:bg-transparent disabled:hover:text-text-secondary`,r?`h-9`:`h-[30px]`);return(0,$.jsx)(`div`,{className:`absolute bottom-3 right-2.5 z-10 flex flex-col items-end gap-1.5`,children:o?(0,$.jsxs)(`div`,{ref:p,tabIndex:-1,className:`flex flex-col p-[3px] rounded-xl border border-border bg-surface-elevated/95 backdrop-blur-[8px] shadow-lg outline-none`,onFocus:()=>{h.current=!0},onKeyDown:e=>{e.key===`Escape`&&s(!1)},children:[(0,$.jsx)(`button`,{type:`button`,onClick:b,disabled:!i.hasAbove,"aria-label":`Jump to previous message`,className:C,children:(0,$.jsx)(ut,{className:`size-[15px]`})}),(0,$.jsx)(`span`,{className:`font-mono text-[10px] font-medium text-text-subtle text-center py-px`,"aria-label":`Message ${i.idx||1} of ${i.total}`,children:i.total?`${i.idx||1}/${i.total}`:`0/0`}),(0,$.jsx)(`button`,{type:`button`,onClick:x,disabled:i.atBottom,"aria-label":`Jump to next message`,className:C,children:(0,$.jsx)(l,{className:`size-[15px]`})}),(0,$.jsx)(`button`,{type:`button`,onClick:S,disabled:i.atBottom,"aria-label":`Jump to latest`,className:C,children:(0,$.jsx)(yt,{className:`size-[13px]`})})]}):(0,$.jsx)(`button`,{ref:m,type:`button`,onClick:()=>{f.current=Xn,g.current=!0,s(!0)},"aria-label":`Navigate messages`,"aria-expanded":!1,title:`Navigate messages`,className:M(`group flex items-center justify-center`,r?`size-11`:`size-[30px]`),children:(0,$.jsx)(`span`,{className:M(`flex items-center justify-center rounded-full border border-border bg-surface-elevated/55 backdrop-blur-[6px] text-text-subtle`,`motion-safe:transition-colors group-hover:bg-surface-elevated group-hover:text-foreground`,r?`size-9`:`size-[30px]`),children:(0,$.jsx)(at,{className:`size-[15px]`})})})})}function er({group:e,onNavigate:t,disabled:n}){if(!e||e.ids.length<2)return null;let{ids:r,currentIndex:i}=e,a=e=>{let i=r[e];i&&!n&&t(i)};return(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-1 text-xs text-text-subtle select-none`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(i-1),disabled:n||i<=0,"aria-label":`Previous version`,className:`flex items-center justify-center rounded p-0.5 hover:text-text-primary disabled:opacity-30 disabled:cursor-default`,children:(0,$.jsx)(Ve,{className:`size-3.5`})}),(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[i+1,`/`,r.length]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(i+1),disabled:n||i>=r.length-1,"aria-label":`Next version`,className:`flex items-center justify-center rounded p-0.5 hover:text-text-primary disabled:opacity-30 disabled:cursor-default`,children:(0,$.jsx)(u,{className:`size-3.5`})})]})}function tr(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 nr(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 rr({questions:e,onSubmit:t,onSkip:n}){let r=(0,Q.useRef)(null),i=tr(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=nr({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 select-text`,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)(`div`,{role:`button`,onClick:()=>d(t),className:`text-left flex items-start gap-2.5 rounded px-2.5 py-2 text-xs border transition-all cursor-pointer select-text ${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})`]})]})]})}var ir={"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`,"local-command-caveat":`System`};function ar(e){let t=[],n=/<(system-reminder|available-deferred-tools|antml:[\w-]+|fast_mode_info|claudeMd|gitStatus|currentDate|task-notification|environment_details|local-command-caveat)[^>]*>([\s\S]*?)<\/\1>/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];t.push({name:e,label:ir[e]??e.replace(/^antml:/,``).replace(/-/g,` `),content:r[2].trim()})}return{cleanText:e.replace(n,``).trim(),tags:t}}function or(e){let t=e.match(/<command-name>([\s\S]*?)<\/command-name>/);if(!t)return{command:null,cleanText:e};let n=t[1].trim(),r=e.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim()||void 0,i=e.replace(/<command-name>[\s\S]*?<\/command-name>/g,``).replace(/<command-message>[\s\S]*?<\/command-message>/g,``).replace(/<command-args>[\s\S]*?<\/command-args>/g,``).trim();return{command:{name:n,args:r},cleanText:i}}function sr(e){let t=e.match(/^Use the (\S+) agent to\s?/);return t?{agent:t[1],cleanText:e.slice(t[0].length)}:{agent:null,cleanText:e}}function cr(e){let t=/<ide_opened_file>([\s\S]*?)<\/ide_opened_file>/g.exec(e);return t?{idePath:t[1].match(/opened the file (.+?) in the IDE/)?.[1]?.trim()??null,cleanText:e.replace(/<ide_opened_file>[\s\S]*?<\/ide_opened_file>/g,``).trim()}:{idePath:null,cleanText:e}}function lr(e){let t=e.match(/^\[Attached file: (.+?)\]\n*/);if(t)return{files:[t[1]],text:e.slice(t[0].length)};let n=e.match(/^\[Attached files:\n([\s\S]+?)\]\n*/);return n?{files:n[1].split(`
3
- `).map(e=>e.trim()).filter(Boolean),text:e.slice(n[0].length)}:{files:[],text:e}}function ur(e){let t=[],n=e,r=/^```(?:bash|sh|shell|zsh)\n([\s\S]*?)\n```\s*(?:\n\n?)?/,i;for(;(i=n.match(r))!==null;)t.push(i[1]),n=n.slice(i[0].length);return{blocks:t,remainingText:n.trim()}}function dr(e){let{idePath:t,cleanText:n}=cr(e),{blocks:r,remainingText:i}=ur(n),a=lr(i),{cleanText:o,tags:s}=ar(a.text.replace(/<local-command-(?:stdout|stderr)>([\s\S]*?)<\/local-command-(?:stdout|stderr)>/g,`$1`)),{command:c,cleanText:l}=or(o),{agent:u,cleanText:d}=sr(l),f=c?.args?d?`${c.args}\n\n${d}`:c.args:d;return{files:a.files,text:f,body:d,tags:s,command:c,terminalBlocks:r,idePath:t,agent:u}}function fr(e){let{agent:t,body:n,command:r}=dr(e);if(!r)return{agent:t,text:n};let i=`/${r.name.replace(/^\/+/,``)}${r.args?` ${r.args}`:``}`;return{agent:t,text:n?`${i}\n\n${n}`:i}}var pr=j(()=>import(`./markdown-renderer-Bhv5w9Op.js`),__vite__mapDeps([4,5,1,6,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31])),mr=(0,Q.lazy)(()=>pr.then(e=>({default:e.MarkdownRenderer})));function hr({messages:e,messagesLoading:t,keepStaleWhileLoading:n,pendingApproval:r,onApprovalResponse:a,isStreaming:o,phase:s,onSelectSession:c,connectingElapsed:l,statusMessage:u,compactStatus:f,projectName:p,onFork:m,onEdit:h,editingMsgId:g,sessionId:_,providerId:v,onNavigateVersion:y,versionMap:b,bashPartialOutput:x,onExpandCompact:S,isCompactExpanded:C,onDismissMessage:w,onClearErrors:ee}){let{scrollRef:T,contentRef:te,scrollToBottom:ne,stopScroll:re,isAtBottom:E}=Yt({initial:`instant`,resize:`instant`}),D=(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]),O=!!r||o,[k,ie]=(0,Q.useState)(null),A=(0,Q.useCallback)(e=>{T(e),ie(e)},[T]),j=(0,Q.useRef)(new Map),ae=(0,Q.useMemo)(()=>{let e=j.current,t=new Map;for(let n=0;n<D.length;n++){let r=D[n];if(r.role!==`assistant`||D[n+1]?.role===`assistant`)continue;let i=`${r.id}:${r.events?.length??0}`,a=e.get(i);a||(a=_n(vn(D,n)),e.set(i,a)),a.length>0&&t.set(n,a)}return t},[D]),M=(0,Q.useRef)(null),oe=(0,Q.useCallback)(e=>{k&&(M.current?.(),M.current=cn(k,e))},[k]);(0,Q.useEffect)(()=>()=>M.current?.(),[]);let N=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let e=k;e&&N.current!=null&&(e.scrollTop=e.scrollHeight-N.current,N.current=null)},[D.length,k]),(0,Q.useLayoutEffect)(()=>{k&&ne({animation:`instant`})},[_,k]);let P=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>{k&&k.clientHeight>0&&(P.current=E)},[E,k]),(0,Q.useEffect)(()=>{let e=k;if(!e)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=t===0&&n>0;t=n,r&&!P.current&&re()});return n.observe(e),()=>n.disconnect()},[k,re]);let F=(0,Q.useCallback)((e,t)=>{m?.(e,t)},[m]),I=(0,Q.useCallback)((e,t,n)=>{h?.(e,t,n)},[h]),L=(0,Q.useCallback)(e=>{w?.(e)},[w]),se=(0,Q.useMemo)(()=>D.reduce((e,t)=>t.role===`system`?e+1:e,0),[D]),R=(0,Q.useMemo)(()=>D.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),[D]),z=(0,Q.useCallback)(()=>{if(!S||!C)return null;for(let e of D){if(C(e.id))continue;let t=qn(e.content||``);if(t)return{id:e.id,jsonlPath:t};if(e.events){for(let t of e.events)if(t.type===`text`){let n=qn(t.content||``);if(n)return{id:e.id,jsonlPath:n}}}}return null},[D,S,C])(),B=!!z,[ce,le]=(0,Q.useState)(!1),V=(0,Q.useCallback)(async()=>{if(!z||!S||ce)return;let e=k;N.current=e?e.scrollHeight-e.scrollTop:null,le(!0);try{await S(z.id,z.jsonlPath)}finally{le(!1)}},[z,S,ce,k]);return(0,Q.useEffect)(()=>{let e=k;if(!e||!B)return;let t=()=>{e.scrollTop<200&&!ce&&V()};return e.addEventListener(`scroll`,t,{passive:!0}),()=>e.removeEventListener(`scroll`,t)},[k,B,ce,V]),t&&(!n||e.length===0)?(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-text-secondary`,children:[(0,$.jsx)(i,{className:`size-10 text-text-subtle animate-pulse`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Loading messages...`})]}):e.length===0&&!o?(0,$.jsx)(Yn,{projectName:p||``,onSelectSession:c||(()=>{})}):(0,$.jsxs)(`div`,{className:`relative flex-1 overflow-hidden flex flex-col min-h-0`,children:[(0,$.jsx)(Wn,{projectName:p,sessionId:_,messages:e}),se>1&&ee&&(0,$.jsx)(`div`,{className:`absolute top-2 left-0 right-0 z-20 flex justify-center pointer-events-none`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:ee,className:`pointer-events-auto flex items-center gap-1.5 rounded-full bg-error/15 border border-error/25 px-3 py-1 text-xs text-error hover:bg-error/25 shadow-md backdrop-blur-sm`,children:[(0,$.jsx)(d,{className:`size-3.5`}),`Clear all errors (`,se,`)`]})}),ce&&(0,$.jsxs)(`div`,{className:`absolute top-2 left-0 right-0 z-10 flex items-center justify-center gap-1.5 text-xs text-text-secondary pointer-events-none`,children:[(0,$.jsx)(q,{className:`size-3 animate-spin`}),`Loading previous conversation...`]}),(0,$.jsx)(`div`,{ref:A,[mt]:``,className:`flex-1 overflow-y-auto overflow-x-hidden [overflow-anchor:none]`,style:{WebkitOverflowScrolling:`touch`,overscrollBehavior:`contain`},children:(0,$.jsxs)(`div`,{ref:te,className:`w-full`,children:[D.map((e,t)=>{let n=t>0?D[t-1]:void 0,r=e.role===`user`?D.slice(0,t+1).reduce((e,t)=>e+(t.role===`user`?1:0),0):0,i=r?b?.[r]:void 0,a=e.role===`user`&&g!=null&&e.id===g,s=D[t+1],c=e.role===`assistant`&&s?.role!==`assistant`,l;if(c){let e=[];for(let n=t;n>=0&&D[n].role===`assistant`;n--){let t=gr(D[n]);t&&e.unshift(t)}l=e.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/edit-diff-preview-D1TEK7Jz.js","assets/rolldown-runtime-FhOqtrmT.js","assets/vendor-markdown-CKTlmXbz.js","assets/libesm-DdtEjhIi.js","assets/markdown-renderer-CAFmdvwK.js","assets/vendor-mermaid-CYOBtZtD.js","assets/vendor-ui-DMRGWRuc.js","assets/markdown-renderer-CyzYLWuu.js","assets/index-bQy6gwMT.js","assets/dialog-HHdNInEH.js","assets/utils-E0yyGxXt.js","assets/createLucideIcon-ConhwJnb.js","assets/x-BsFLg-T8.js","assets/eye-off-Rq1n2-oe.js","assets/bot-E9mcVZnr.js","assets/context-menu-DIiZdfbE.js","assets/chevron-right-DeUue2aK.js","assets/use-is-mobile-BcuCjH19.js","assets/sparkles-B3DmG8PJ.js","assets/database-COYAMZaw.js","assets/plus-DcuJuDC3.js","assets/api-client-COQtP-dB.js","assets/react-8hrD3-kv.js","assets/api-settings-Do0Z0IRN.js","assets/project-store-D0ALup9Z.js","assets/panel-store-CpKvXNnm.js","assets/settings-store-BbFtHCGd.js","assets/tab-store-BQmDVh9c.js","assets/apply-theme-BSJDABU3.js","assets/resolve-theme-B9Mgd5GG.js","assets/index-BEB87kj8.css","assets/image-gallery-CObzTisL.js","assets/api-client-RtNXvS0P.js"])))=>i.map(i=>d[i]);
2
+ import{o as e}from"./rolldown-runtime-FhOqtrmT.js";import{b as t,y as n}from"./vendor-markdown-CKTlmXbz.js";import"./vendor-ui-DMRGWRuc.js";import{t as r}from"./createLucideIcon-ConhwJnb.js";import{t as i}from"./bot-E9mcVZnr.js";import{d as a,f as o,l as s}from"./context-menu-DIiZdfbE.js";import{n as c,r as l}from"./use-is-mobile-BcuCjH19.js";import{t as u}from"./chevron-right-DeUue2aK.js";import{a as d,i as f,n as p,r as m,t as h}from"./tool-cards-DtF80k3f.js";import{a as g,c as _,i as v,n as y,o as b,r as x,t as S,u as C}from"./dialog-HHdNInEH.js";import{t as w}from"./code-TekEnDFM.js";import{n as ee,t as T}from"./sparkles-B3DmG8PJ.js";import{n as te,r as ne,t as re}from"./plus-DcuJuDC3.js";import{t as E}from"./shield-off-D5tU7gQT.js";import{t as D}from"./x-BsFLg-T8.js";import{i as O,n as k,r as ie,s as A}from"./api-client-COQtP-dB.js";import{q as j}from"./vendor-mermaid-CYOBtZtD.js";import{t as ae}from"./settings-store-BbFtHCGd.js";import{n as M,r as oe,t as N}from"./utils-E0yyGxXt.js";import{t as P}from"./panel-store-CpKvXNnm.js";import{i as F}from"./project-store-D0ALup9Z.js";import{t as I}from"./tab-store-BQmDVh9c.js";import{_ as L,a as se,c as R,h as z,i as B,l as ce,m as le,o as V,p as H,r as U,s as W,t as G,u as K}from"./api-settings-Do0Z0IRN.js";import{$t as q,B as J,Bt as ue,Cn as de,Ct as Y,Et as fe,F as pe,Ft as me,Gt as he,H as X,Ht as ge,I as _e,It as ve,J as ye,Jt as be,Kt as xe,L as Se,Lt as Ce,Mt as we,N as Te,Ot as Ee,P as De,Pt as Oe,Qt as ke,R as Ae,Rt as Z,Sn as je,Tt as Me,U as Ne,Ut as Pe,V as Fe,Yt as Ie,Zt as Le,_n as Re,_t as ze,an as Be,bn as Ve,cn as He,dn as Ue,f as We,fn as Ge,gn as Ke,gt as qe,hn as Je,ht as Ye,jt as Xe,kt as Ze,nn as Qe,on as $e,ot as et,r as tt,rt as nt,t as rt,tn as it,vn as at,w as ot,wn as st,wt as ct,xn as lt,yn as ut,yt as dt,z as ft,zt as pt}from"./index-bQy6gwMT.js";import"./use-blob-url-B3YovXF6.js";import{n as mt,r as ht,t as gt}from"./image-gallery-CObzTisL.js";import{t as _t}from"./libesm-DdtEjhIi.js";var vt=r(`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`}]]),yt=r(`chevrons-down`,[[`path`,{d:`m7 6 5 5 5-5`,key:`1lc07p`}],[`path`,{d:`m7 13 5 5 5-5`,key:`1d48rs`}]]),bt=r(`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`}]]),xt=r(`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`}]]),St=r(`image-off`,[[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`,key:`a6p6uj`}],[`path`,{d:`M10.41 10.41a2 2 0 1 1-2.83-2.83`,key:`1bzlo9`}],[`line`,{x1:`13.5`,x2:`6`,y1:`13.5`,y2:`21`,key:`1q0aeu`}],[`line`,{x1:`18`,x2:`21`,y1:`12`,y2:`15`,key:`5mozeu`}],[`path`,{d:`M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59`,key:`mmje98`}],[`path`,{d:`M21 15V5a2 2 0 0 0-2-2H9`,key:`43el77`}]]),Ct=r(`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`}]]),wt=r(`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`}]]),Tt=r(`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`}]]),Et=r(`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`}]]),Dt=r(`slash`,[[`path`,{d:`M22 2 2 22`,key:`y4kqgn`}]]),Q=e(t(),1);function Ot(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function kt(e,t){let n=`pc-${Ot(t)}-`;return e.map(e=>e.id?{...e,id:`${n}${e.id}`}:e)}function At(e,t){if(t.size===0)return e;let n=[];for(let r of e){let e=r.id?t.get(r.id):void 0;e&&e.length>0&&n.push(...e),n.push(r)}return n}var jt=null;function Mt(){return jt||=new AudioContext,jt}function Nt(e,t,n,r,i=`sine`){let a=Mt(),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 Pt(){let e=Mt().currentTime;Nt(523,.15,e,.15),Nt(659,.2,e+.12,.15)}function Ft(){let e=Mt().currentTime;Nt(880,.12,e,.18,`square`),Nt(698,.12,e+.15,.18,`square`),Nt(880,.15,e+.3,.15,`square`)}function It(){let e=Mt().currentTime;Nt(440,.12,e,.12),Nt(523,.12,e+.1,.12),Nt(659,.18,e+.2,.12)}var Lt={done:Pt,approval_request:Ft,question:It};function Rt(e){try{Lt[e]?.()}catch{}}var zt={hasTeams:!1,teamNames:[],messageCount:0,unreadCount:0};function Bt(e){if(document.hidden)return!1;let{panels:t}=P.getState();for(let n of Object.values(t)){let t=n.tabs.find(e=>e.id===n.activeTabId);if(t?.type===`chat`&&t.metadata?.sessionId===e)return!0}return!1}function Vt(e,t=`claude`,n=``){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(new Map),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)({}),[d,f]=(0,Q.useState)(`idle`),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(null),[w,ee]=(0,Q.useState)([]),T=(0,Q.useRef)([]),[te,ne]=(0,Q.useState)(null),[re,E]=(0,Q.useState)(null),[D,j]=(0,Q.useState)(!1),[ae,M]=(0,Q.useState)(null),[oe,N]=(0,Q.useState)(null),F=(0,Q.useRef)(null),I=(0,Q.useRef)(null),[L,se]=(0,Q.useState)(null),R=(0,Q.useRef)(null),[z,B]=(0,Q.useState)(!0),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(null),V=(0,Q.useRef)(``),H=(0,Q.useRef)([]),U=(0,Q.useRef)(new Map),W=(0,Q.useRef)(null),G=(0,Q.useRef)(`idle`),K=(0,Q.useRef)(null),q=(0,Q.useRef)(()=>{}),J=(0,Q.useRef)(null),ue=(0,Q.useRef)(!1),de=(0,Q.useRef)(new Set),Y=(0,Q.useRef)(0),fe=(0,Q.useRef)(null),pe=(0,Q.useRef)(e);pe.current=e;let me=(0,Q.useRef)([]);me.current=r;let he=(0,Q.useRef)(n);he.current=n;let X=(0,Q.useRef)(null),ge=(0,Q.useRef)(0),_e=(0,Q.useRef)({teamNames:new Set,messages:[]}),ve=(0,Q.useRef)(0),[ye,be]=(0,Q.useState)(zt),[xe,Se]=(0,Q.useState)([]),Ce=(0,Q.useCallback)(()=>{let e=_e.current;be({hasTeams:e.teamNames.size>0,teamNames:Array.from(e.teamNames),messageCount:e.messages.length,unreadCount:ve.current}),Se([...e.messages])},[]),we=(0,Q.useCallback)(()=>{ve.current=0,Ce()},[Ce]),Te=d!==`idle`;(0,Q.useEffect)(()=>{if(e)return et.getState().setStreaming(e,d!==`idle`),()=>{et.getState().setStreaming(e,!1)}},[e,d]);let Ee=(0,Q.useCallback)((e,t)=>{let n=H.current.findIndex(e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t);if(n===-1)return!1;let r=H.current[n];if(r.type!==`tool_use`)return!1;let i=[...r.children??[],e];return H.current[n]={...r,children:i},!0},[]),De=(0,Q.useCallback)(()=>{ge.current=0;let e=V.current,t=[...H.current],n=W.current;(0,Q.startTransition)(()=>{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}]})})},[]),Oe=(0,Q.useCallback)(()=>{ge.current||=window.setTimeout(De,100)},[De]),ke=(0,Q.useCallback)(e=>{let t=e,n=t?.type;if(!n)return;let r=e=>{let n=H.current,r=n.findIndex(e);r===-1?n.push(t):n[r]=t};switch(n){case`account_info`:W.current={accountId:t.accountId,accountLabel:t.accountLabel},ne(null);break;case`account_retry`:t.accountId&&t.accountLabel&&(W.current={accountId:t.accountId,accountLabel:t.accountLabel}),H.current=[t],Oe();break;case`status_update`:{let e=t.accountLabel?` (${t.accountLabel})`:``;ne(`${t.message}${e}`);break}case`text`:{let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}V.current+=t.content,H.current.push(t),Oe();break}case`thinking`:{let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}H.current.push(t),Oe();break}case`tool_use`:{if(t.tool===`AskUserQuestion`){t.toolUseId&&de.current.add(t.toolUseId);break}let e=t.parentToolUseId;if(e&&Ee(t,e)){Oe();break}let n=t.toolUseId;r(e=>!!n&&e.type===`tool_use`&&e.toolUseId===n),Oe();break}case`tool_result`:{let e=t.toolUseId;if(e&&U.current.delete(e),e&&de.current.has(e))break;let n=t.parentToolUseId;if(n&&Ee(t,n)){Oe();break}r(t=>!!e&&t.type===`tool_result`&&t.toolUseId===e),Oe();break}case`approval_resolved`:{let e=t.requestId;if(t.approved&&t.answers){let n=H.current.find(t=>t.type===`approval_request`&&t.requestId===e&&t.tool===`AskUserQuestion`),r=n&&n.input;r&&typeof r==`object`&&(r.answers=t.answers,i(e=>[...e]))}y(t=>t&&t.requestId===e?null:t),X.current!=null&&(A.dismiss(X.current),X.current=null);break}case`approval_request`:if(r(e=>e.type===`approval_request`&&e.requestId===t.requestId),ue.current)break;if(y({requestId:t.requestId,tool:t.tool,input:t.input}),pe.current&&!Bt(pe.current)){Rt(t.tool===`AskUserQuestion`?`question`:`approval_request`);let e=pe.current,n=t.tool===`AskUserQuestion`;X.current=A[n?`info`:`warning`](n?`AI has a question`:`${t.tool} needs permission`,{description:he.current||`Session ${e.slice(0,8)}`,duration:1/0,action:{label:`Go to session`,onClick:()=>{let{panels:t}=P.getState();for(let[n,r]of Object.entries(t)){let t=r.tabs.find(t=>t.metadata?.sessionId===e);if(t){P.getState().setActiveTab(t.id,n);break}}}}})}break;case`error`:i(e=>{let n=e[e.length-1];if(n?.role===`assistant`){let r=H.current,i=r[r.length-1],a=i?.type===`error`&&i.message===t.message?r:[...r,t];return H.current=a,[...e.slice(0,-1),{...n,events:a}]}return n?.role===`system`&&n.content===t.message?e:[...e,{id:`error-${Date.now()}`,role:`system`,content:t.message,events:[t],timestamp:new Date().toISOString()}]});break;case`team_detected`:{let e=t.teamName;e&&(_e.current.teamNames.add(e),k.get(`/api/teams/${encodeURIComponent(e)}`).then(e=>{if(e?.messages){let t=_e.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()),t.length>500&&t.splice(0,t.length-500)}Ce()}).catch(()=>{}),Ce());break}case`team_inbox`:{let e=t.messages;if(Array.isArray(e)){let t=_e.current.messages;t.push(...e),t.length>500&&t.splice(0,t.length-500),ve.current+=e.length,Ce()}break}case`team_updated`:Ce();break;case`bash_output`:{let e=t.toolUseId;if(e){let n=U.current.get(e);n?(n.content+=t.content,n.content.length>5e5&&(n.content=n.content.slice(-5e5)),n.lineCount=t.lineCount):U.current.set(e,{content:t.content,lineCount:t.lineCount}),Oe()}break}case`background_registry`:{let e=t.shells??[];T.current=e,ee(e);break}case`done`:{if(G.current===`idle`)break;t.contextWindowPct!=null&&x(t.contextWindowPct),pe.current&&!Bt(pe.current)&&Rt(`done`),ge.current&&=(clearTimeout(ge.current),0);let e=V.current,n=[...H.current],r=W.current,a=t.lastMessageUuid;i(t=>{let i=t[t.length-1];return i?.role===`assistant`?[...t.slice(0,-1),{...i,id:`final-${Date.now()}`,content:e||i.content,events:n.length>0?n:i.events,...a&&{sdkUuid:a}}]:e||n.length>0?[...t,{id:`final-${Date.now()}`,role:`assistant`,content:e,events:n,timestamp:new Date().toISOString(),...a&&{sdkUuid:a},...r}]:t}),V.current=``,H.current=[],W.current=null,fe.current=null,U.current.clear(),ne(null);break}}},[Ee,Oe]),Ae=(0,Q.useCallback)(e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(t.type!==`ping`){if(t.type===`title_updated`){E(t.title??null);return}if(t.type===`compact_status`){let e=t.status;e===`compacting`?C(`compacting`):e===`done`&&C(null);return}if(t.type===`phase_changed`){let e=t.phase;f(e),G.current=e,_(e===`connecting`?t.elapsed??0:0),e===`idle`&&C(null);return}if(t.type===`session_state`){j(!0),M(t.sessionId??pe.current);let e=t,n=e.phase;f(n),G.current=n,e.sessionTitle&&E(e.sessionTitle),e.model&&(I.current&&e.model!==I.current||(e.model===I.current&&(I.current=null),N(e.model),F.current=e.model)),typeof e.effort==`string`&&(se(e.effort),R.current=e.effort),typeof e.thinking==`boolean`&&B(e.thinking),e.pendingApproval&&y({requestId:e.pendingApproval.requestId,tool:e.pendingApproval.tool,input:e.pendingApproval.input}),C(e.compactStatus===`compacting`?`compacting`:null),n===`idle`&&(J.current?.(),h(!1));return}if(t.type===`turn_events`){let e=t.events,n=t.userMessage;if(!e?.length&&!n){h(!1);return}Y.current&&=(cancelAnimationFrame(Y.current),0),fe.current=n,i(e=>{let t=[...e],r=t.length;for(;r>0&&t[r-1].role===`assistant`;)r--;if(n!=null&&r>0&&t[r-1].role===`user`&&t[r-1].content===n)t=t.slice(0,r-1);else{let e=t[t.length-1];e?.role===`assistant`&&e.id.startsWith(`streaming-`)&&(t=t.slice(0,-1))}if(n){let e=t[t.length-1];(e?.role!==`user`||e.content!==n)&&(t=[...t,{id:`user-replay-${Date.now()}`,role:`user`,content:n,timestamp:new Date().toISOString()}])}return t}),V.current=``,H.current=[],W.current=null,ue.current=!0;let r=0,a=()=>{let t=Math.min(r+100,e.length);for(let n=r;n<t;n++)ke(e[n]);r=t,r<e.length?Y.current=requestAnimationFrame(a):(Y.current=0,ue.current=!1,h(!1))};Y.current=requestAnimationFrame(a);return}ke(t)}},[ke]),{send:Z,connect:je}=p({url:e&&n?`/ws/project/${encodeURIComponent(n)}/chat/${e}`:``,onMessage:Ae,autoConnect:!!e&&!!n});q.current=Z,(0,Q.useEffect)(()=>{let r=!1;le.current&&le.current!==e&&(I.current=null,ce.current=null),le.current=e??null,f(`idle`),G.current=`idle`,y(null),X.current!=null&&(A.dismiss(X.current),X.current=null),C(null),o(new Map),u({}),V.current=``,H.current=[],fe.current=null,U.current.clear(),ge.current&&=(clearTimeout(ge.current),0),j(!1),M(null),_e.current={teamNames:new Set,messages:[]},ve.current=0,be(zt),Se([]);let a=new Set(me.current.map(e=>e.id));return e&&n?(c(!0),k.get(`${O(n)}/chat/sessions/${e}/messages?providerId=${t}`).then(e=>{if(r)return;let t=Array.isArray(e)?{messages:e,versionMap:{}}:e,n=Array.isArray(t?.messages)?t.messages:[];t?.versionMap&&u(t.versionMap);let o=fe.current;if(o!=null){for(let e=n.length-1;e>=0;e--)if(n[e].role===`user`&&n[e].content===o){n=n.slice(0,e);break}}i(e=>{let t=e.filter(e=>!a.has(e.id));return[...n,...t]})}).catch(()=>{r||i(e=>e.filter(e=>!a.has(e.id)))}).finally(()=>{r||c(!1)})):i([]),()=>{r=!0}},[e,t,n]);let Me=(0,Q.useCallback)((e,t)=>{if(!e.trim())return;let n=G.current!==`idle`;if(n){ge.current&&=(clearTimeout(ge.current),0);let e=V.current,t=[...H.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()}]),V.current=``,H.current=[],K.current=null,n?(f(`thinking`),G.current=`thinking`):(f(`initializing`),G.current=`initializing`),y(null),X.current!=null&&(A.dismiss(X.current),X.current=null),Z(JSON.stringify({type:`message`,content:e,permissionMode:t?.permissionMode,priority:t?.priority,images:t?.images,...F.current&&{model:F.current},...R.current&&{effort:R.current},...ce.current!==null&&{thinking:ce.current}}))},[Z]),Ne=(0,Q.useCallback)(e=>{N(e),F.current=e,I.current=e,Z(JSON.stringify({type:`set_model`,model:e}))},[Z]),Pe=(0,Q.useCallback)(e=>{se(e),R.current=e,Z(JSON.stringify({type:`set_effort`,effort:e}))},[Z]),Fe=(0,Q.useCallback)(e=>{B(e),ce.current=e,Z(JSON.stringify({type:`set_thinking`,enabled:e}))},[Z]),Ie=(0,Q.useCallback)((e,t,n)=>{if(Z(JSON.stringify({type:`approval_response`,requestId:e,approved:t,data:n})),t&&n){let t=H.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])}y(null),X.current!=null&&(A.dismiss(X.current),X.current=null)},[Z]),Le=(0,Q.useCallback)(()=>{if(G.current===`idle`)return;Z(JSON.stringify({type:`cancel`}));let e=V.current,t=[...H.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}),V.current=``,H.current=[],U.current.clear(),K.current=null,f(`idle`),G.current=`idle`,y(null),X.current!=null&&(A.dismiss(X.current),X.current=null)},[Z]),Re=(0,Q.useCallback)(e=>{e&&Z(JSON.stringify({type:`kill_background_shell`,shellId:e}))},[Z]),ze=(0,Q.useCallback)(e=>{if(!e)return;let t=e.replace(/\.output$/,``);return T.current.find(n=>n.shellId===t||n.outputPath.endsWith(e)||n.outputPath.endsWith(`${t}.output`))},[]);(0,Q.useEffect)(()=>{e&&rt.getState().setSessionShells(e,w)},[e,w]),(0,Q.useEffect)(()=>{if(e)return rt.getState().retainSession(e),()=>{rt.getState().releaseSession(e)}},[e]);let Be=(0,Q.useCallback)(()=>{j(!1),h(!0),je()},[je]),Ve=(0,Q.useCallback)(()=>{!e||!n||fetch(`${O(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${ie()}`}}).then(e=>e.json()).then(e=>{if(G.current!==`idle`)return;let t=e.ok?Array.isArray(e.data)?{messages:e.data,versionMap:void 0}:e.data:null;t?.versionMap&&u(t.versionMap),Array.isArray(t?.messages)&&t.messages.length>0&&(i(t.messages),V.current=``,H.current=[])}).catch(()=>{})},[e,t,n]);J.current=Ve;let He=(0,Q.useCallback)(async(e,t)=>{if(!n)throw Error(`No project context available`);let r=e.replace(/^pc-[^-]+-/,``),i=`${O(n)}/chat/pre-compact-messages?jsonlPath=${encodeURIComponent(t)}&before=${encodeURIComponent(r)}`,a=kt(await k.get(i),t);return o(t=>{let n=new Map(t);return n.set(e,a),n}),a.length},[n]),Ue=(0,Q.useCallback)(e=>a.has(e),[a]),We=(0,Q.useCallback)(e=>{i(t=>t.filter(t=>t.id!==e))},[]),Ge=(0,Q.useCallback)(()=>{i(e=>e.filter(e=>e.role!==`system`))},[]);return{messages:r,renderedMessages:(0,Q.useMemo)(()=>At(r,a),[r,a]),expandCompact:He,isCompactExpanded:Ue,dismissMessage:We,clearErrors:Ge,messagesLoading:s,versionMap:l,isStreaming:Te,phase:d,isReconnecting:m,connectingElapsed:g,pendingApproval:v,contextWindowPct:b,compactStatus:S,statusMessage:te,sessionTitle:re,model:oe,setModel:Ne,effort:L,setEffort:Pe,thinking:z,setThinking:Fe,teamActivity:ye,teamMessages:xe,markTeamRead:we,bashPartialOutput:U,backgroundShells:w,killBackgroundShell:Re,findBackgroundShellByOutput:ze,sendMessage:Me,respondToApproval:Ie,cancelStreaming:Le,reconnect:Be,refetchMessages:Ve,isConnected:D&&ae===e}}var Ht=12e4;function Ut(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`:``;k.get(`${O(e)}/chat/usage?providerId=${t}${i}`).then(e=>{e&&(r(t=>({...t,...e})),e.lastFetchedAt&&s(e.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 Wt={damping:.7,stiffness:.05,mass:1.25},Gt=70,Kt=1e3/60,qt=350,Jt=!1;globalThis.document?.addEventListener(`mousedown`,()=>{Jt=!0}),globalThis.document?.addEventListener(`mouseup`,()=>{Jt=!1}),globalThis.document?.addEventListener(`click`,()=>{Jt=!1});var Yt=(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(!Jt)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){if(g.current){let{scrollBehavior:t}=getComputedStyle(g.current);t!==`auto`&&(g.current.style.scrollBehavior=`auto`),g.current.scrollTop=e,d.ignoreScrollToTop=g.current.scrollTop,t!==`auto`&&(g.current.style.scrollBehavior=t)}},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<=Gt}}},[]),f=(0,Q.useCallback)((e={})=>{typeof e==`string`&&(e={animation:e}),e.preserveScrollPosition||l(!0);let t=Date.now()+(Number(e.wait)||0),n=Qt(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))/Kt;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:Qt(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=Xt(e=>{g.current?.removeEventListener(`scroll`,m),g.current?.removeEventListener(`wheel`,h),e?.addEventListener(`scroll`,m,{passive:!0}),e?.addEventListener(`wheel`,h,{passive:!0})},[]),_=Xt(e=>{if(d.resizeObserver?.disconnect(),d.resizeObserver=void 0,!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=Qt(s.current,t?s.current.resize:s.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:e===`instant`?void 0:qt})}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 Xt(e,t){let n=(0,Q.useCallback)(t=>(n.current=t,e(t)),t);return n}var Zt=new Map;function Qt(...e){let t={...Wt},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 Zt.has(r)||Zt.set(r,Object.freeze(t)),n?`instant`:Zt.get(r)}var $t=60,en=8,tn=1400;function nn(e){if(e.scrollHeight<=e.clientHeight)return!1;let t=getComputedStyle(e).overflowY;return t===`auto`||t===`scroll`}function rn(e,t){let n=[],r=e.parentElement;for(;r&&r!==t;)nn(r)&&n.push(r),r=r.parentElement;return n}function an(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}function on(e,t){let n=e.querySelector(`[data-edit-ref="${CSS.escape(t)}"]`);if(n)return{el:n,level:`edit`};let r=t.replace(/-\d+$/,``),i=e.querySelector(`[data-tool-ref="${CSS.escape(r)}"]`);return i?{el:i,level:`card`}:null}function sn(e,t,n,r){let i=e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-n;e.scrollTo({top:i,behavior:r?`smooth`:`auto`})}function cn(e,t){let n=on(e,t);if(!n)return()=>{};let{el:r,level:i}=n;for(let t of rn(r,e))sn(t,r,en,!1);sn(e,r,$t,!an()),r.dataset.flash=i;let a=setTimeout(()=>{delete r.dataset.flash},tn);return()=>{clearTimeout(a),delete r.dataset.flash}}var ln=new Set([`Write`,`Edit`,`MultiEdit`,`NotebookEdit`]),un={create:3,write:2,notebook:2,edit:1};function dn(e){return typeof e==`string`?e:``}function fn(e,t){let n=0,r=0;for(let i of _t(e,t))i.added?n+=i.count??0:i.removed&&(r+=i.count??0);return{added:n,removed:r}}function pn(e){return e&&/created successfully/i.test(e)?`create`:`write`}function mn(e,t,n){switch(e){case`Write`:{let e=dn(t.file_path);return e?{filePath:e,op:pn(n),fragments:[{oldStr:``,newStr:dn(t.content)}]}:null}case`Edit`:{let e=dn(t.file_path);return e?{filePath:e,op:`edit`,fragments:[{oldStr:dn(t.old_string),newStr:dn(t.new_string)}]}:null}case`MultiEdit`:{let e=dn(t.file_path);if(!e||!Array.isArray(t.edits))return null;let n=t.edits.filter(e=>!!e&&typeof e==`object`).map(e=>({oldStr:dn(e.old_string),newStr:dn(e.new_string)}));return n.length===0?null:{filePath:e,op:`edit`,fragments:n}}case`NotebookEdit`:{let e=dn(t.notebook_path)||dn(t.file_path);return e?{filePath:e,op:`notebook`,fragments:[{oldStr:``,newStr:dn(t.new_source)}]}:null}default:return null}}function hn(e,t){if(e){for(let n of e)if(n.type===`tool_result`&&n.toolUseId&&t.set(n.toolUseId,n.output??``),n.type===`tool_use`){let e=n.result;n.toolUseId&&e?.output!=null&&!t.has(n.toolUseId)&&t.set(n.toolUseId,e.output),hn(n.children,t)}}}function gn(e,t,n,r){if(e)for(let i of e){if(i.type!==`tool_use`||(i.children?.length&&gn(i.children,!0,n,r),!ln.has(i.tool)))continue;let e=i.input&&typeof i.input==`object`?i.input:null;if(!e)continue;let a=mn(i.tool,e,i.toolUseId?r.get(i.toolUseId):void 0);if(!a)continue;let o=n.get(a.filePath);o||(o={filePath:a.filePath,op:a.op,editCount:0,linesAdded:0,linesRemoved:0,edits:[],viaSubagent:!1},n.set(a.filePath,o)),un[a.op]>un[o.op]&&(o.op=a.op),t&&(o.viaSubagent=!0),a.fragments.forEach((e,n)=>{let{added:r,removed:a}=fn(e.oldStr,e.newStr);o.linesAdded+=r,o.linesRemoved+=a,o.editCount+=1,o.edits.push({...e,toolUseId:i.toolUseId,editIndex:n,editRef:i.toolUseId?`${i.toolUseId}-${n}`:void 0,viaSubagent:t})})}}function _n(e){let t=new Map;for(let n of e)hn(n.events,t);let n=new Map;for(let r of e)gn(r.events,!1,n,t);return[...n.values()]}function vn(e,t){let n=[];for(let r=t;r>=0&&e[r]?.role===`assistant`;r--)n.unshift(e[r]);return n}var $=n();function yn(e){try{return new Date(e).toLocaleString()}catch{return``}}function bn({icon:e,label:t,title:n,onClick:r}){return(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:n,"aria-label":t,className:`inline-flex items-center justify-center gap-1 rounded-md px-1.5 py-1 text-text-subtle hover:text-text-primary hover:bg-surface transition-colors`,children:[e,(0,$.jsx)(`span`,{children:t})]})}function xn({content:e}){let[t,n]=(0,Q.useState)(!1);return(0,$.jsx)(bn,{icon:t?(0,$.jsx)(a,{className:`size-3.5`}):(0,$.jsx)(Ge,{className:`size-3.5`}),label:t?`Copied`:`Copy`,title:`Copy message to clipboard`,onClick:()=>{nt(e),n(!0),setTimeout(()=>n(!1),1500)}})}function Sn({timestamp:e,content:t,accountLabel:n,className:r,children:i}){return(0,$.jsxs)(`div`,{className:M(`flex items-center gap-0.5 flex-wrap text-xs text-text-subtle select-none`,r),children:[(0,$.jsx)(`time`,{title:yn(e),className:`pr-1 tabular-nums`,children:Me(e)}),n&&(0,$.jsxs)(`span`,{className:`px-1 truncate max-w-40`,children:[`via `,n]}),(0,$.jsx)(xn,{content:t}),i]})}function Cn(e){let t=0,n=0;for(let r of e)t+=r.linesAdded,n+=r.linesRemoved;return{added:t,removed:n}}function wn({count:e,totals:t,open:n,onToggle:r,ref:i}){let a=`${e} file${e===1?``:`s`}`;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":!0,className:`mx-1.5 h-3.5 w-px bg-border-soft`}),(0,$.jsxs)(`button`,{ref:i,type:`button`,onClick:r,"aria-expanded":n,"aria-label":`${a} changed this turn, ${t.added} added, ${t.removed} removed`,className:M(`inline-flex items-center gap-[7px] rounded-full font-mono text-[11.5px]`,`px-3 min-h-11 md:min-h-0 md:px-[9px] md:py-[5px]`,`text-text-secondary transition-colors hover:bg-surface hover:text-text-primary`),children:[(0,$.jsx)(`span`,{"aria-hidden":!0,className:`size-[5px] shrink-0 rounded-full bg-primary`}),(0,$.jsx)(`span`,{children:a}),(0,$.jsxs)(`span`,{className:`flex items-center gap-[5px] tabular-nums`,children:[(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,t.added]}),(0,$.jsxs)(`span`,{className:`text-error`,children:[`−`,t.removed]})]})]})]})}function Tn(e){if(!e)return!1;let t=e.closest(`[data-tab-pool-id]`)?.dataset.tabPoolId;if(!t)return e.offsetParent!==null;let{panels:n,focusedPanelId:r}=P.getState();return n[r]?.activeTabId===t}var En={create:{glyph:`A`,cls:`text-success`,label:`created`},write:{glyph:`W`,cls:`text-warning`,label:`overwritten`},notebook:{glyph:`N`,cls:`text-accent-2`,label:`notebook edited`},edit:{glyph:`·`,cls:`text-text-subtle`,label:`edited`}};function Dn(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?{base:e,dir:``}:{base:e.slice(t+1),dir:e.slice(0,t)}}function On({added:e,removed:t,editCount:n,className:r}){return(0,$.jsxs)(`span`,{className:M(`flex items-center gap-[5px] tabular-nums`,r),children:[(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,e]}),(0,$.jsxs)(`span`,{className:`text-error`,children:[`−`,t]}),n!=null&&n>1&&(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[`×`,n]})]})}function kn({change:e,dense:t,selected:n,onClick:r}){let i=En[e.op],{base:a,dir:o}=Dn(e.filePath),s=e.viaSubagent?`${i.label} · changed by a sub-agent`:i.label;return(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:e.filePath,className:M(`grid w-full grid-cols-[16px_1fr_auto_10px] items-center gap-[10px] text-left font-mono`,`border-b border-border-soft hover:bg-surface transition-colors`,t?`min-h-[38px] px-2.5 py-[5px] text-xs`:`min-h-[52px] px-3 py-[7px] text-[12.5px]`,n&&`bg-surface shadow-[inset_2px_0_0_var(--accent)]`),children:[(0,$.jsx)(`span`,{"aria-label":s,title:s,className:M(`inline-flex size-4 items-center justify-center rounded bg-white/5 text-[9px] font-semibold`,i.cls,e.viaSubagent&&`bg-accent-2/20 ring-1 ring-inset ring-accent-2/35`),children:i.glyph}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block truncate text-text-primary`,children:a}),o&&(0,$.jsx)(`span`,{className:`block overflow-hidden text-ellipsis whitespace-nowrap text-[10px] text-text-subtle [direction:rtl] text-left`,children:o})]}),(0,$.jsx)(On,{added:e.linesAdded,removed:e.linesRemoved,editCount:e.editCount,className:`text-[11px]`}),(0,$.jsx)(u,{className:`size-[11px] text-text-subtle`})]})}var An=(0,Q.lazy)(()=>j(()=>import(`./edit-diff-preview-D1TEK7Jz.js`),__vite__mapDeps([0,1,2,3])));function jn({change:e,onJump:t}){return(0,$.jsx)(`div`,{children:e.edits.map((n,r)=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`button`,{type:`button`,disabled:!n.editRef,onClick:()=>n.editRef&&t(n.editRef),className:`group flex min-h-11 w-full items-center gap-2 px-3 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface disabled:hover:bg-transparent`,children:[(0,$.jsxs)(`span`,{children:[`edit `,r+1,` of `,e.editCount]}),(0,$.jsx)(`span`,{className:`h-px flex-1 bg-border-soft`}),n.editRef&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 group-hover:text-primary`,children:[(0,$.jsx)(st,{className:`size-3`}),`jump`]})]}),(0,$.jsx)(`div`,{className:`mx-3 mb-1`,children:(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`h-4`}),children:(0,$.jsx)(An,{oldStr:n.oldStr,newStr:n.newStr,filePath:e.filePath})})})]},n.editRef??r))})}function Mn(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?{base:e,dir:``}:{base:e.slice(t+1),dir:e.slice(0,t)}}var Nn=null;function Pn(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function Fn({changes:e,onJump:t,onClose:n}){let[r,i]=(0,Q.useState)(0),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),s=(0,Q.useId)();(0,Q.useEffect)(()=>(Nn=s,o.current?.querySelector(`button`)?.focus(),()=>{Nn===s&&(Nn=null)}),[s]),(0,Q.useEffect)(()=>{let o=o=>{if(Nn===s&&Tn(a.current)&&!Pn(document.activeElement)){if(o.key===`Escape`)o.preventDefault(),n();else if(o.key===`j`)o.preventDefault(),i(t=>Math.min(t+1,e.length-1));else if(o.key===`k`)o.preventDefault(),i(e=>Math.max(e-1,0));else if(o.key===`Enter`){let n=e[r]?.edits[0]?.editRef;n&&(o.preventDefault(),t(n))}}};return window.addEventListener(`keydown`,o),()=>window.removeEventListener(`keydown`,o)},[s,e,r,t,n]);let c=e[Math.min(r,e.length-1)];if(!c)return null;let{base:l,dir:u}=Mn(c.filePath);return(0,$.jsx)(`div`,{ref:a,className:`mt-0.5 overflow-hidden rounded-[10px] border border-border-soft bg-bg`,children:(0,$.jsxs)(`div`,{className:`grid h-[356px] grid-cols-[294px_1fr] grid-rows-[minmax(0,1fr)] bg-surface-elevated`,children:[(0,$.jsxs)(`div`,{ref:o,className:`min-h-0 overflow-y-auto border-r border-border-soft`,children:[e.map((e,t)=>(0,$.jsx)(kn,{change:e,dense:!0,selected:t===r,onClick:()=>i(t)},e.filePath)),(0,$.jsx)(`p`,{className:`px-2.5 pt-2 pb-2.5 font-mono text-[10px] text-text-subtle`,children:`j / k to move · enter to jump`})]}),(0,$.jsxs)(`div`,{className:`min-h-0 overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center gap-2 border-b border-border-soft bg-surface-elevated py-[5px] pl-2.5 pr-2`,children:[(0,$.jsx)(`span`,{className:`shrink-0 font-mono text-xs font-medium text-text-primary`,children:l}),u&&(0,$.jsx)(`span`,{title:c.filePath,className:`min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-[10.5px] text-text-subtle [direction:rtl] text-left`,children:u}),(0,$.jsx)(On,{added:c.linesAdded,removed:c.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void nt(c.filePath),className:`shrink-0 rounded-md px-1.5 py-1 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:`copy path`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close change tray`,className:`inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:(0,$.jsx)(D,{className:`size-3.5`})})]}),(0,$.jsx)(jn,{change:c,onJump:t})]})]})})}function In(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?e:e.slice(t+1)}function Ln({label:e,onClick:t,children:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-label":e,className:`inline-flex size-11 shrink-0 items-center justify-center rounded-lg text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:n})}function Rn({changes:e,totals:t,open:n,onClose:r,onJump:i}){let[a,o]=(0,Q.useState)(null),s=a==null?null:e[a],c=(0,Q.useRef)(null),l=()=>{o(null),r()},u=e=>{l(),i(e)};return(0,Q.useEffect)(()=>{if(!n)return;let e=c.current,t=()=>Array.from(e?.querySelectorAll(`button:not([disabled])`)??[]);t()[0]?.focus();let r=e=>{if(e.key===`Escape`){e.preventDefault(),l();return}if(e.key!==`Tab`)return;let n=t();if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus())};return window.addEventListener(`keydown`,r),()=>window.removeEventListener(`keydown`,r)},[n,a]),(0,$.jsx)(ye,{open:n,onClose:l,className:`flex max-h-[85%] flex-col rounded-t-[14px] motion-reduce:animate-none`,children:(0,$.jsx)(`div`,{ref:c,className:`flex min-h-0 flex-1 flex-col`,children:s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 border-b border-border-soft px-1 pb-1`,children:[(0,$.jsx)(Ln,{label:`Back to file list`,onClick:()=>o(null),children:(0,$.jsx)(Ve,{className:`size-4`})}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs font-medium text-text-primary`,children:In(s.filePath)}),(0,$.jsx)(On,{added:s.linesAdded,removed:s.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Ln,{label:`Close`,onClick:l,children:(0,$.jsx)(D,{className:`size-4`})})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 border-b border-border-soft py-1.5 pl-3 pr-2`,children:[(0,$.jsx)(`span`,{title:s.filePath,className:`min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-[10.5px] text-text-subtle [direction:rtl] text-left`,children:s.filePath}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void nt(s.filePath),className:`inline-flex min-h-11 shrink-0 items-center rounded-md px-2.5 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-text-primary`,children:`copy`}),s.edits[0]?.editRef&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(s.edits[0].editRef),className:`inline-flex min-h-11 shrink-0 items-center gap-1 rounded-md px-2.5 font-mono text-[10px] text-text-subtle transition-colors hover:bg-surface hover:text-primary`,children:[(0,$.jsx)(st,{className:`size-3`}),`card`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,$.jsx)(jn,{change:s,onJump:u})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border-soft px-3 pb-2`,children:[(0,$.jsxs)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs font-medium text-text-primary`,children:[`Changed this turn · `,e.length,` file`,e.length===1?``:`s`]}),(0,$.jsx)(On,{added:t.added,removed:t.removed,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Ln,{label:`Close`,onClick:l,children:(0,$.jsx)(D,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.map((e,t)=>(0,$.jsx)(kn,{change:e,onClick:()=>o(t)},e.filePath))})]})})})}function zn({timestamp:e,content:t,accountLabel:n,changes:r,onJumpToEdit:i}){let[a,o]=(0,Q.useState)(!1),s=c(),l=(0,Q.useRef)(null),u=()=>{o(!1),l.current?.focus()},d=(0,$.jsx)(Sn,{timestamp:e,content:t,accountLabel:n,className:`-mt-1.5`,children:r&&r.length>0&&(0,$.jsx)(wn,{ref:l,count:r.length,totals:Cn(r),open:a,onToggle:()=>a?u():o(!0)})});return!r||r.length===0?d:(0,$.jsxs)($.Fragment,{children:[d,s?(0,$.jsx)(Rn,{changes:r,totals:Cn(r),open:a,onClose:u,onJump:i??(()=>{})}):a&&(0,$.jsx)(Fn,{changes:r,onJump:e=>{o(!1),i?.(e)},onClose:u})]})}function Bn(e,t,n,r){let[i,a]=(0,Q.useState)([]),o=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!n||!e||!t){a([]);return}let r=!1;return o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{k.get(`/api/project/${encodeURIComponent(e)}/chat/sessions/${encodeURIComponent(t)}/tasks`).then(e=>{r||a(e)}).catch(()=>{})},300),()=>{r=!0,o.current&&clearTimeout(o.current)}},[e,t,n,r]),i}var Vn=new Set([`TaskCreate`,`TaskUpdate`,`TaskStop`]);function Hn(e){let t=0;for(let n of e)if(n.events)for(let e of n.events)e.type===`tool_use`&&Vn.has(e.tool)&&t++;return t}var Un={completed:{icon:`✓`,cls:`text-success`},in_progress:{icon:`▶`,cls:`text-warning`},stopped:{icon:`■`,cls:`text-text-subtle`},pending:{icon:`○`,cls:`text-text-subtle`}};function Wn({projectName:e,sessionId:t,messages:n}){let r=(0,Q.useMemo)(()=>Hn(n),[n]),i=Bn(e,t,r>0,r),[a,o]=(0,Q.useState)(!0);if(i.length===0||i.every(e=>e.status===`completed`||e.status===`stopped`))return null;let s=i.filter(e=>e.status===`completed`).length,c=i.length,d=c?Math.round(s/c*100):0;return(0,$.jsxs)(`div`,{className:`shrink-0 border-b border-border bg-surface/60 backdrop-blur-sm`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o(e=>!e),className:`flex items-center gap-2 w-full px-3 min-h-11 text-left text-xs hover:bg-surface transition-colors`,children:[a?(0,$.jsx)(u,{className:`size-3.5 shrink-0`}):(0,$.jsx)(l,{className:`size-3.5 shrink-0`}),(0,$.jsx)(m,{className:`size-3.5 shrink-0 text-text-secondary`}),(0,$.jsx)(`span`,{className:`text-text-primary font-medium`,children:`Tasks`}),(0,$.jsxs)(`span`,{className:`text-text-subtle`,children:[s,`/`,c,` done`]}),(0,$.jsx)(`span`,{className:`ml-auto h-1 w-16 rounded-full bg-border overflow-hidden shrink-0`,children:(0,$.jsx)(`span`,{className:`block h-full bg-success/70`,style:{width:`${d}%`}})})]}),!a&&(0,$.jsx)(`ul`,{className:`px-3 pb-2 space-y-0.5 max-h-48 overflow-y-auto`,children:i.map(e=>(0,$.jsx)(Gn,{task:e},e.id))})]})}function Gn({task:e}){let t=Un[e.status]??Un.pending,n=e.status===`in_progress`;return(0,$.jsxs)(`li`,{className:`flex items-start gap-1.5 text-xs rounded px-1 ${n?`bg-warning/10`:``}`,children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5 ${t.cls}`,children:t.icon}),(0,$.jsx)(`span`,{className:e.status===`completed`?`line-through text-text-subtle`:n?`text-text-primary font-medium`:`text-text-secondary`,children:e.subject||(0,$.jsxs)(`span`,{className:`text-text-subtle italic`,children:[`#`,e.id,` (no title)`]})})]})}var Kn=/read the full transcript at:\s*(\S+\.jsonl)/i;function qn(e){return e.match(Kn)?.[1]?.trim()??null}var Jn=class extends Q.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback?this.props.fallback:this.props.fallbackContent?(0,$.jsx)(`div`,{className:`text-sm whitespace-pre-wrap break-words text-text-primary opacity-80`,children:this.props.fallbackContent}):null:this.props.children}};function Yn({projectName:e,onSelectSession:t}){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)(i,{className:`size-10 text-text-subtle`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Send a message to start a new conversation`})]}),(0,$.jsx)(qe,{projectName:e,onSelectSession:t,className:`w-full px-4`})]})}var Xn=3200,Zn=1e3,Qn={hasAbove:!1,atBottom:!0,idx:0,total:0};function $n({scrollElement:e,userIndices:t,scrollToBottom:n}){let r=c(),[i,a]=(0,Q.useState)(Qn),[o,s]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(0),f=(0,Q.useRef)(Xn),p=(0,Q.useRef)(null),m=(0,Q.useRef)(null),h=(0,Q.useRef)(!1),g=(0,Q.useRef)(!1),_=(e,t,n)=>t.getBoundingClientRect().top-n+e.scrollTop,v=(0,Q.useCallback)(e=>Array.from(e.querySelectorAll(`[data-msg-index]`)).filter(e=>t.includes(Number(e.dataset.msgIndex))),[t]);(0,Q.useEffect)(()=>{let t=e;if(!t)return;let n=0,r=()=>{let e=t.scrollTop,n=t.getBoundingClientRect().top,r=v(t).map(e=>_(t,e,n)),i=0;for(let t=0;t<r.length;t++)r[t]<=e+12&&(i=t+1);let o={hasAbove:r.some(t=>t<e-4),atBottom:t.scrollHeight-e-t.clientHeight<8,idx:i,total:r.length};a(e=>e.hasAbove===o.hasAbove&&e.atBottom===o.atBottom&&e.idx===o.idx&&e.total===o.total?e:o)},i=()=>{n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r(),t.addEventListener(`scroll`,i,{passive:!0});let o=new ResizeObserver(i);return o.observe(t),()=>{n&&cancelAnimationFrame(n),t.removeEventListener(`scroll`,i),o.disconnect()}},[e,v]),(0,Q.useEffect)(()=>{if(!o)return;let e=setTimeout(()=>s(!1),f.current);return()=>clearTimeout(e)},[o,i.idx,u]),(0,Q.useEffect)(()=>{if(!o||!g.current)return;g.current=!1;let e=p.current;(e?.querySelector(`button:not(:disabled)`)??e)?.focus()},[o]),(0,Q.useEffect)(()=>{o||!h.current||(h.current=!1,m.current?.focus())},[o]);let y=(0,Q.useCallback)(()=>{f.current=Xn,d(e=>e+1)},[]),b=(0,Q.useCallback)(()=>{let t=e;if(!t)return;let n=t.scrollTop,r=t.getBoundingClientRect().top,i;for(let e of v(t)){let a=_(t,e,r);if(a<n-4)i=a;else break}i!=null&&t.scrollTo({top:i,behavior:`auto`}),y()},[e,v,y]),x=(0,Q.useCallback)(()=>{let t=e;if(!t)return;let r=t.scrollTop,i=t.getBoundingClientRect().top,a=v(t).map(e=>_(t,e,i)).find(e=>e>r+4);a==null?n({animation:`instant`}):t.scrollTo({top:a,behavior:`auto`}),y()},[e,v,n,y]),S=(0,Q.useCallback)(()=>{n({animation:`instant`}),y()},[n,y]);(0,Q.useEffect)(()=>{let t=e;if(!t)return;let n=e=>()=>{Tn(t)&&(e(),f.current=Zn,s(!0))},r=n(b),i=n(x);return window.addEventListener(`chat-nav-prev`,r),window.addEventListener(`chat-nav-next`,i),()=>{window.removeEventListener(`chat-nav-prev`,r),window.removeEventListener(`chat-nav-next`,i)}},[e,b,x]);let C=M(`w-[34px] flex items-center justify-center rounded-[9px] text-text-secondary`,`motion-safe:transition-colors hover:bg-surface-elevated hover:text-foreground`,`disabled:opacity-30 disabled:cursor-default disabled:hover:bg-transparent disabled:hover:text-text-secondary`,r?`h-9`:`h-[30px]`);return(0,$.jsx)(`div`,{className:`absolute bottom-3 right-2.5 z-10 flex flex-col items-end gap-1.5`,children:o?(0,$.jsxs)(`div`,{ref:p,tabIndex:-1,className:`flex flex-col p-[3px] rounded-xl border border-border bg-surface-elevated/95 backdrop-blur-[8px] shadow-lg outline-none`,onFocus:()=>{h.current=!0},onKeyDown:e=>{e.key===`Escape`&&s(!1)},children:[(0,$.jsx)(`button`,{type:`button`,onClick:b,disabled:!i.hasAbove,"aria-label":`Jump to previous message`,className:C,children:(0,$.jsx)(ut,{className:`size-[15px]`})}),(0,$.jsx)(`span`,{className:`font-mono text-[10px] font-medium text-text-subtle text-center py-px`,"aria-label":`Message ${i.idx||1} of ${i.total}`,children:i.total?`${i.idx||1}/${i.total}`:`0/0`}),(0,$.jsx)(`button`,{type:`button`,onClick:x,disabled:i.atBottom,"aria-label":`Jump to next message`,className:C,children:(0,$.jsx)(l,{className:`size-[15px]`})}),(0,$.jsx)(`button`,{type:`button`,onClick:S,disabled:i.atBottom,"aria-label":`Jump to latest`,className:C,children:(0,$.jsx)(yt,{className:`size-[13px]`})})]}):(0,$.jsx)(`button`,{ref:m,type:`button`,onClick:()=>{f.current=Xn,g.current=!0,s(!0)},"aria-label":`Navigate messages`,"aria-expanded":!1,title:`Navigate messages`,className:M(`group flex items-center justify-center`,r?`size-11`:`size-[30px]`),children:(0,$.jsx)(`span`,{className:M(`flex items-center justify-center rounded-full border border-border bg-surface-elevated/55 backdrop-blur-[6px] text-text-subtle`,`motion-safe:transition-colors group-hover:bg-surface-elevated group-hover:text-foreground`,r?`size-9`:`size-[30px]`),children:(0,$.jsx)(at,{className:`size-[15px]`})})})})}function er({group:e,onNavigate:t,disabled:n}){if(!e||e.ids.length<2)return null;let{ids:r,currentIndex:i}=e,a=e=>{let i=r[e];i&&!n&&t(i)};return(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-1 text-xs text-text-subtle select-none`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(i-1),disabled:n||i<=0,"aria-label":`Previous version`,className:`flex items-center justify-center rounded p-0.5 hover:text-text-primary disabled:opacity-30 disabled:cursor-default`,children:(0,$.jsx)(Ve,{className:`size-3.5`})}),(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[i+1,`/`,r.length]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(i+1),disabled:n||i>=r.length-1,"aria-label":`Next version`,className:`flex items-center justify-center rounded p-0.5 hover:text-text-primary disabled:opacity-30 disabled:cursor-default`,children:(0,$.jsx)(u,{className:`size-3.5`})})]})}function tr(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 nr(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 rr({questions:e,onSubmit:t,onSkip:n}){let r=(0,Q.useRef)(null),i=tr(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=nr({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 select-text`,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)(`div`,{role:`button`,onClick:()=>d(t),className:`text-left flex items-start gap-2.5 rounded px-2.5 py-2 text-xs border transition-all cursor-pointer select-text ${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})`]})]})]})}var ir={"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`,"local-command-caveat":`System`};function ar(e){let t=[],n=/<(system-reminder|available-deferred-tools|antml:[\w-]+|fast_mode_info|claudeMd|gitStatus|currentDate|task-notification|environment_details|local-command-caveat)[^>]*>([\s\S]*?)<\/\1>/g,r;for(;(r=n.exec(e))!==null;){let e=r[1];t.push({name:e,label:ir[e]??e.replace(/^antml:/,``).replace(/-/g,` `),content:r[2].trim()})}return{cleanText:e.replace(n,``).trim(),tags:t}}function or(e){let t=e.match(/<command-name>([\s\S]*?)<\/command-name>/);if(!t)return{command:null,cleanText:e};let n=t[1].trim(),r=e.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim()||void 0,i=e.replace(/<command-name>[\s\S]*?<\/command-name>/g,``).replace(/<command-message>[\s\S]*?<\/command-message>/g,``).replace(/<command-args>[\s\S]*?<\/command-args>/g,``).trim();return{command:{name:n,args:r},cleanText:i}}function sr(e){let t=e.match(/^Use the (\S+) agent to\s?/);return t?{agent:t[1],cleanText:e.slice(t[0].length)}:{agent:null,cleanText:e}}function cr(e){let t=/<ide_opened_file>([\s\S]*?)<\/ide_opened_file>/g.exec(e);return t?{idePath:t[1].match(/opened the file (.+?) in the IDE/)?.[1]?.trim()??null,cleanText:e.replace(/<ide_opened_file>[\s\S]*?<\/ide_opened_file>/g,``).trim()}:{idePath:null,cleanText:e}}function lr(e){let t=e.match(/^\[Attached file: (.+?)\]\n*/);if(t)return{files:[t[1]],text:e.slice(t[0].length)};let n=e.match(/^\[Attached files:\n([\s\S]+?)\]\n*/);return n?{files:n[1].split(`
3
+ `).map(e=>e.trim()).filter(Boolean),text:e.slice(n[0].length)}:{files:[],text:e}}function ur(e){let t=[],n=e,r=/^```(?:bash|sh|shell|zsh)\n([\s\S]*?)\n```\s*(?:\n\n?)?/,i;for(;(i=n.match(r))!==null;)t.push(i[1]),n=n.slice(i[0].length);return{blocks:t,remainingText:n.trim()}}function dr(e){let{idePath:t,cleanText:n}=cr(e),{blocks:r,remainingText:i}=ur(n),a=lr(i),{cleanText:o,tags:s}=ar(a.text.replace(/<local-command-(?:stdout|stderr)>([\s\S]*?)<\/local-command-(?:stdout|stderr)>/g,`$1`)),{command:c,cleanText:l}=or(o),{agent:u,cleanText:d}=sr(l),f=c?.args?d?`${c.args}\n\n${d}`:c.args:d;return{files:a.files,text:f,body:d,tags:s,command:c,terminalBlocks:r,idePath:t,agent:u}}function fr(e){let{agent:t,body:n,command:r}=dr(e);if(!r)return{agent:t,text:n};let i=`/${r.name.replace(/^\/+/,``)}${r.args?` ${r.args}`:``}`;return{agent:t,text:n?`${i}\n\n${n}`:i}}var pr=j(()=>import(`./markdown-renderer-CAFmdvwK.js`),__vite__mapDeps([4,5,1,6,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31])),mr=(0,Q.lazy)(()=>pr.then(e=>({default:e.MarkdownRenderer})));function hr({messages:e,messagesLoading:t,keepStaleWhileLoading:n,pendingApproval:r,onApprovalResponse:a,isStreaming:o,phase:s,onSelectSession:c,connectingElapsed:l,statusMessage:u,compactStatus:f,projectName:p,onFork:m,onEdit:h,editingMsgId:g,sessionId:_,providerId:v,onNavigateVersion:y,versionMap:b,bashPartialOutput:x,onExpandCompact:S,isCompactExpanded:C,onDismissMessage:w,onClearErrors:ee}){let{scrollRef:T,contentRef:te,scrollToBottom:ne,stopScroll:re,isAtBottom:E}=Yt({initial:`instant`,resize:`instant`}),D=(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]),O=!!r||o,[k,ie]=(0,Q.useState)(null),A=(0,Q.useCallback)(e=>{T(e),ie(e)},[T]),j=(0,Q.useRef)(new Map),ae=(0,Q.useMemo)(()=>{let e=j.current,t=new Map;for(let n=0;n<D.length;n++){let r=D[n];if(r.role!==`assistant`||D[n+1]?.role===`assistant`)continue;let i=`${r.id}:${r.events?.length??0}`,a=e.get(i);a||(a=_n(vn(D,n)),e.set(i,a)),a.length>0&&t.set(n,a)}return t},[D]),M=(0,Q.useRef)(null),oe=(0,Q.useCallback)(e=>{k&&(M.current?.(),M.current=cn(k,e))},[k]);(0,Q.useEffect)(()=>()=>M.current?.(),[]);let N=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let e=k;e&&N.current!=null&&(e.scrollTop=e.scrollHeight-N.current,N.current=null)},[D.length,k]),(0,Q.useLayoutEffect)(()=>{k&&ne({animation:`instant`})},[_,k]);let P=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>{k&&k.clientHeight>0&&(P.current=E)},[E,k]),(0,Q.useEffect)(()=>{let e=k;if(!e)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=t===0&&n>0;t=n,r&&!P.current&&re()});return n.observe(e),()=>n.disconnect()},[k,re]);let F=(0,Q.useCallback)((e,t)=>{m?.(e,t)},[m]),I=(0,Q.useCallback)((e,t,n)=>{h?.(e,t,n)},[h]),L=(0,Q.useCallback)(e=>{w?.(e)},[w]),se=(0,Q.useMemo)(()=>D.reduce((e,t)=>t.role===`system`?e+1:e,0),[D]),R=(0,Q.useMemo)(()=>D.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),[D]),z=(0,Q.useCallback)(()=>{if(!S||!C)return null;for(let e of D){if(C(e.id))continue;let t=qn(e.content||``);if(t)return{id:e.id,jsonlPath:t};if(e.events){for(let t of e.events)if(t.type===`text`){let n=qn(t.content||``);if(n)return{id:e.id,jsonlPath:n}}}}return null},[D,S,C])(),B=!!z,[ce,le]=(0,Q.useState)(!1),V=(0,Q.useCallback)(async()=>{if(!z||!S||ce)return;let e=k;N.current=e?e.scrollHeight-e.scrollTop:null,le(!0);try{await S(z.id,z.jsonlPath)}finally{le(!1)}},[z,S,ce,k]);return(0,Q.useEffect)(()=>{let e=k;if(!e||!B)return;let t=()=>{e.scrollTop<200&&!ce&&V()};return e.addEventListener(`scroll`,t,{passive:!0}),()=>e.removeEventListener(`scroll`,t)},[k,B,ce,V]),t&&(!n||e.length===0)?(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-text-secondary`,children:[(0,$.jsx)(i,{className:`size-10 text-text-subtle animate-pulse`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Loading messages...`})]}):e.length===0&&!o?(0,$.jsx)(Yn,{projectName:p||``,onSelectSession:c||(()=>{})}):(0,$.jsxs)(`div`,{className:`relative flex-1 overflow-hidden flex flex-col min-h-0`,children:[(0,$.jsx)(Wn,{projectName:p,sessionId:_,messages:e}),se>1&&ee&&(0,$.jsx)(`div`,{className:`absolute top-2 left-0 right-0 z-20 flex justify-center pointer-events-none`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:ee,className:`pointer-events-auto flex items-center gap-1.5 rounded-full bg-error/15 border border-error/25 px-3 py-1 text-xs text-error hover:bg-error/25 shadow-md backdrop-blur-sm`,children:[(0,$.jsx)(d,{className:`size-3.5`}),`Clear all errors (`,se,`)`]})}),ce&&(0,$.jsxs)(`div`,{className:`absolute top-2 left-0 right-0 z-10 flex items-center justify-center gap-1.5 text-xs text-text-secondary pointer-events-none`,children:[(0,$.jsx)(q,{className:`size-3 animate-spin`}),`Loading previous conversation...`]}),(0,$.jsx)(`div`,{ref:A,[mt]:``,className:`flex-1 overflow-y-auto overflow-x-hidden [overflow-anchor:none]`,style:{WebkitOverflowScrolling:`touch`,overscrollBehavior:`contain`},children:(0,$.jsxs)(`div`,{ref:te,className:`w-full`,children:[D.map((e,t)=>{let n=t>0?D[t-1]:void 0,r=e.role===`user`?D.slice(0,t+1).reduce((e,t)=>e+(t.role===`user`?1:0),0):0,i=r?b?.[r]:void 0,a=e.role===`user`&&g!=null&&e.id===g,s=D[t+1],c=e.role===`assistant`&&s?.role!==`assistant`,l;if(c){let e=[];for(let n=t;n>=0&&D[n].role===`assistant`;n--){let t=gr(D[n]);t&&e.unshift(t)}l=e.join(`
4
4
 
5
5
  `)}return(0,$.jsx)(`div`,{"data-msg-index":t,className:`px-4 pt-4 select-none`,children:(0,$.jsx)(Jn,{fallbackContent:e.content,children:(0,$.jsx)(_r,{message:e,isStreaming:o&&e.id.startsWith(`streaming-`),isLastAssistantInTurn:c,turnCopyText:l,turnChanges:c?ae.get(t):void 0,onJumpToEdit:oe,projectName:p,onFork:e.role===`user`&&m?F:void 0,onEdit:e.role===`user`&&h?I:void 0,isEditing:a,onDismiss:e.role===`system`&&w?L:void 0,prevMsgId:n?.sdkUuid??n?.id,sessionId:_,providerId:v,versionGroup:i,onNavigateVersion:y,versionNavDisabled:o,bashPartialOutput:x})})},e.id)}),O&&(0,$.jsxs)(`div`,{className:`px-4 pt-4 pb-4 space-y-4 select-none`,children:[r&&(r.tool===`AskUserQuestion`?(0,$.jsx)(Hr,{approval:r,onRespond:a}):(0,$.jsx)(Vr,{approval:r,onRespond:a})),o&&(0,$.jsx)(Lr,{lastMessage:e[e.length-1],phase:s,elapsed:l,statusMessage:f===`compacting`?`Compacting messages...`:u})]})]})}),(0,$.jsx)($n,{scrollElement:k,userIndices:R,scrollToBottom:ne})]})}function gr(e){return e.events?.length?e.events.filter(e=>e.type===`text`).map(e=>e.content).join(``):e.content}var _r=(0,Q.memo)(function({message:e,isStreaming:t,isLastAssistantInTurn:n,turnCopyText:r,turnChanges:i,onJumpToEdit:a,projectName:o,onFork:s,onEdit:c,isEditing:l,onDismiss:u,prevMsgId:f,sessionId:p,providerId:m,versionGroup:h,onNavigateVersion:g,versionNavDisabled:_,bashPartialOutput:v}){if(e.role===`user`){let t=s?()=>s(e.content,f):void 0,n=c?()=>c(e.content,f,e.id):void 0;return(0,$.jsx)(Sr,{content:e.content,messageId:e.id,timestamp:e.timestamp,projectName:o,onFork:t,onEdit:n,isEditing:l,sessionId:p,providerId:m,versionGroup:h,onNavigateVersion:g,versionNavDisabled:_})}return e.role===`system`?(0,$.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-lg bg-error/10 border border-error/20 px-3 py-2 text-sm text-error`,children:[(0,$.jsx)(Re,{className:`size-4 shrink-0`}),(0,$.jsx)(`p`,{className:`flex-1`,children:e.content}),u&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(e.id),"aria-label":`Dismiss`,title:`Dismiss`,className:`shrink-0 rounded p-1 text-error/70 hover:text-error hover:bg-error/15 md:opacity-0 md:group-hover:opacity-100`,children:(0,$.jsx)(d,{className:`size-4`})})]}):(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[e.events&&e.events.length>0?(0,$.jsx)(Pr,{events:e.events,isStreaming:t,projectName:o,bashPartialOutput:v}):e.content&&(0,$.jsx)(`div`,{className:`text-sm text-text-primary select-text`,children:(0,$.jsx)(Br,{content:e.content,projectName:o})}),!t&&n&&(0,$.jsx)(zn,{timestamp:e.timestamp,content:r??gr(e),accountLabel:e.accountLabel,changes:i,onJumpToEdit:a})]})}),vr=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`]);function yr(e,t){let n=N(e);return`/api/project/${encodeURIComponent(t??`_`)}/chat/uploads/${encodeURIComponent(n)}`}function br(e){let t=e.lastIndexOf(`.`);return t===-1?!1:vr.has(e.slice(t).toLowerCase())}var xr=new Set([`task-notification`,`environment_details`,`local-command-caveat`]);function Sr({content:e,messageId:t,timestamp:n,projectName:r,onFork:a,onEdit:o,isEditing:c,sessionId:u,providerId:d,versionGroup:f,onNavigateVersion:p,versionNavDisabled:m}){let{files:h,text:g,tags:_,command:v,terminalBlocks:y,idePath:b,agent:x}=(0,Q.useMemo)(()=>dr(e),[e]),S=_.some(e=>xr.has(e.name)),[C,w]=(0,Q.useState)(!1),[ee,T]=(0,Q.useState)(!1),te=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=te.current;if(!e)return;let t=()=>T(e.scrollHeight>e.clientHeight+2);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[g]),(0,$.jsxs)(`div`,{className:M(`flex flex-col gap-1`,!S&&`items-end`),children:[(0,$.jsxs)(`div`,{"data-user-message":S?void 0:`true`,style:S?void 0:{borderRadius:`var(--rad) var(--rad) 4px var(--rad)`},className:M(`group/user relative px-3 py-2 text-sm border shadow-sm transition-all`,S?`rounded-lg bg-surface/40 border-border/40 text-text-secondary`:`max-w-[80%] bg-accent-wash border-accent-wash-border text-text`,c&&`ring-2 ring-primary/60 border-primary/40`),children:[_.length>0&&(0,$.jsx)(wr,{tags:_}),x&&(0,$.jsx)(`div`,{className:`flex items-center gap-1.5 mb-0.5`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-sky-500/15 border border-sky-500/25 px-2 py-0.5 text-xs font-medium text-sky-600 dark:text-sky-400`,children:[(0,$.jsx)(i,{className:`size-3 shrink-0`}),x]})}),v&&(0,$.jsx)(`div`,{className:`flex items-center gap-1.5 mb-0.5`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 border border-primary/20 px-2 py-0.5 text-xs font-medium text-primary`,children:[(0,$.jsx)(Dt,{className:`size-3 shrink-0`}),v.name]})}),b&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1 text-[11px] text-text-subtle`,children:[(0,$.jsx)(`span`,{className:`shrink-0`,children:`Opened in IDE:`}),(0,$.jsx)(Or,{path:b,projectName:r})]}),h.length>0&&(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:h.map((e,t)=>br(e)?(0,$.jsx)(Nr,{filePath:e,projectName:r},t):(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)(He,{className:`size-3 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:N(e)})]},t))}),y.length>0&&(0,$.jsx)(`div`,{className:`space-y-1.5`,children:y.map((e,t)=>(0,$.jsx)(Cr,{content:e},t))}),g&&(0,$.jsx)(`div`,{ref:te,className:M(`whitespace-pre-wrap break-words transition-all duration-200 select-text`,!C&&`line-clamp-2`,C&&`max-h-[50vh] overflow-y-auto`),children:S?(0,$.jsx)(Ar,{text:g,projectName:r}):(0,$.jsx)(kr,{text:g})}),(ee||C)&&(0,$.jsx)(`button`,{onClick:()=>w(!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)(ut,{className:`size-3`}),`Show less`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(l,{className:`size-3`}),`Show more`]})}),!S&&p&&(0,$.jsx)(er,{group:f,onNavigate:p,disabled:m})]}),!S&&(0,$.jsxs)(Sn,{timestamp:n,content:e,children:[o&&(0,$.jsx)(bn,{icon:(0,$.jsx)(s,{className:`size-3.5`}),label:`Edit`,title:`Edit this message (continue in the same tab)`,onClick:o}),a&&(0,$.jsx)(bn,{icon:(0,$.jsx)(ge,{className:`size-3.5`}),label:`Fork`,title:`Retry from this message (fork into a new tab)`,onClick:a})]})]})}function Cr({content:e}){let[t,n]=(0,Q.useState)(!1);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(!t),className:M(`flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors`,t?`border-primary/50 bg-surface-elevated text-text-primary`:`border-border/60 bg-background/40 text-text-secondary hover:bg-surface`),children:[(0,$.jsx)(Z,{className:`size-3.5 shrink-0`}),(0,$.jsx)(`span`,{children:`Terminal output`}),(0,$.jsx)(l,{className:M(`size-3 shrink-0 transition-transform`,t&&`rotate-180`)})]}),t&&(0,$.jsx)(`pre`,{className:`mt-1 max-h-40 overflow-auto rounded-md border border-border bg-background p-2 text-xs text-text-primary font-mono whitespace-pre-wrap break-words`,children:e})]})}function wr({tags:e}){return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,$.jsx)(Tr,{tag:e},t))})}function Tr({tag:e}){let[t,n]=(0,Q.useState)(!1);return e.name===`task-notification`?(0,$.jsx)(Dr,{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)(ve,{className:`size-2.5`}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(u,{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 Er(e,t){return e.match(RegExp(`<${t}>([\\s\\S]*?)</${t}>`))?.[1]?.trim()||void 0}function Dr({content:e}){let[t,n]=(0,Q.useState)(!1),r=Er(e,`status`),i=Er(e,`summary`),a=Er(e,`output-file`),o=Er(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)(Ke,{className:`size-2.5 text-success`}):(0,$.jsx)(d,{className:`size-2.5 text-warning`}),(0,$.jsx)(`span`,{className:`truncate max-w-80`,children:i??`Task notification`}),(0,$.jsx)(u,{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)(Or,{path:a}),o&&(0,$.jsx)(`div`,{className:`text-[11px] text-text-subtle/80 max-h-60 overflow-y-auto leading-relaxed`,children:(0,$.jsx)(Br,{content:o})})]})]})}function Or({path:e,projectName:t}){return(0,$.jsxs)(`button`,{type:`button`,onClick:(0,Q.useCallback)(()=>{let n=I.getState().openTab,r=t??F.getState().activeProject?.name,i=N(e),a={filePath:e};r&&(a.projectName=r),k.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)(He,{className:`size-2.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-60`,children:N(e)}),(0,$.jsx)(Ue,{className:`size-2 shrink-0 opacity-50`})]})}function kr({text:e}){let t=(0,Q.useMemo)(()=>{let t=/(https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/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:`url`,value:i[1]}),r=i.index+i[0].length;return r<e.length&&n.push({kind:`text`,value:e.slice(r)}),n},[e]);return t.every(e=>e.kind===`text`)?(0,$.jsx)($.Fragment,{children:e}):(0,$.jsx)($.Fragment,{children:t.map((e,t)=>e.kind===`url`?(0,$.jsx)(`a`,{href:e.value,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2 hover:text-primary/80 break-all`,onClick:e=>e.stopPropagation(),children:e.value},t):(0,$.jsx)(`span`,{children:e.value},t))})}function Ar({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)(Or,{path:e.value,projectName:t},n):(0,$.jsx)(`span`,{children:e.value},n))})}var jr=new Map;function Mr(e){let[t,n]=(0,Q.useState)(()=>jr.get(e)?.url??null),[r,i]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let t=jr.get(e);if(t){n(t.url);return}let r=!1,a=ie();return fetch(e,{headers:a?{Authorization:`Bearer ${a}`}:{}}).then(e=>{if(!e.ok)throw Error(`Failed`);return e.blob()}).then(t=>{if(r)return;let i=URL.createObjectURL(t);jr.set(e,{url:i}),n(i)}).catch(()=>{r||i(!0)}),()=>{r=!0}},[e]),{blobUrl:t,error:r}}function Nr({filePath:e,projectName:t}){let{blobUrl:n,error:r}=Mr(yr(e,t)),i=tt(e=>e.open),a=N(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>n&&i(n,a,ht(e.currentTarget)),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,[gt]:``,className:`size-4 rounded-sm object-cover shrink-0`}):r?(0,$.jsx)(it,{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 Pr({events:e,isStreaming:t,projectName:n,bashPartialOutput:r}){let i=[],a=``,o=``;for(let t=0;t<e.length;t++){let n=e[t];if(n.type===`thinking`){a&&=(i.push({kind:`text`,content:a}),``),o+=n.content;continue}if(o&&=(i.push({kind:`thinking`,content:o}),``),n.type===`account_retry`){a&&=(i.push({kind:`text`,content:a}),``);let e=n.accountLabel??`another account`,t=n.reason??`Auth failed`;i.push({kind:`text`,content:`\n\n> ↻ ${t} — retrying with **${e}**...\n\n`});continue}n.type===`text`?a+=n.content:n.type===`tool_use`?(a&&=(i.push({kind:`text`,content:a}),``),i.push({kind:`tool`,tool:n})):n.type===`tool_result`||(a&&=(i.push({kind:`text`,content:a}),``),i.push({kind:`tool`,tool:n}))}o&&i.push({kind:`thinking`,content:o}),a&&i.push({kind:`text`,content:a});let s=e.filter(e=>e.type===`tool_result`);for(let e of s){let t=e.toolUseId;if(t){let n=i.find(e=>e.kind===`tool`&&e.tool.type===`tool_use`&&e.tool.toolUseId===t);if(n){n.result=e;continue}}let n=i.find(e=>e.kind===`tool`&&!e.result);n&&(n.result=e)}for(let e of i)if(e.kind===`tool`&&!e.result&&e.tool.type===`tool_use`){let t=e.tool.result;t&&(e.result={type:`tool_result`,output:t.output,isError:t.isError})}for(let e=0;e<i.length;e++){let n=i[e];if(n.kind===`tool`&&!n.result){let r=!1;if(n.tool.type===`tool_use`&&n.tool.tool===`Read`){let t=n.tool.input?.file_path;t&&(r=i.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=r||!t}}return(0,$.jsx)($.Fragment,{children:i.map((e,a)=>{if(e.kind===`thinking`)return(0,$.jsx)(Fr,{content:e.content,isStreaming:t&&a===i.length-1},`think-${a}`);if(e.kind===`text`){let r=t&&a===i.length-1;return(0,$.jsx)(`div`,{className:`text-sm text-text-primary select-text`,children:(0,$.jsx)(Ir,{content:e.content,animate:r,projectName:n})},`text-${a}`)}return(0,$.jsx)(h,{tool:e.tool,result:e.result,completed:e.completed,projectName:n,bashPartialOutput:r},`tool-${a}`)})})}function Fr({content:e,isStreaming:t}){let[n,r]=(0,Q.useState)(t),i=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{!t&&e.length>0&&r(!1)},[t,e.length]),(0,Q.useEffect)(()=>{t&&n&&i.current&&(i.current.scrollTop=i.current.scrollHeight)},[e,t,n]),(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)(q,{className:`size-3 animate-spin`}):(0,$.jsx)(u,{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)(`div`,{ref:i,className:`max-h-60 overflow-y-auto`,children:(0,$.jsx)(`div`,{className:`px-2 pb-2 text-text-subtle/80 whitespace-pre-wrap text-[11px] leading-relaxed`,children:e})})]})}function Ir({content:e,animate:t,projectName:n}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Br,{content:e,projectName:n,isStreaming:t}),t&&(0,$.jsx)(`span`,{className:`text-text-subtle text-sm animate-pulse`,children:`Thinking...`})]})}function Lr({lastMessage:e,phase:t,elapsed:n,statusMessage:r}){let i=!e||e.role!==`assistant`,a=e?.events?.length?e.events[e.events.length-1].type===`tool_result`:!1;return!r&&!i&&!a?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)(q,{className:`size-3 animate-spin`}),(0,$.jsxs)(`span`,{children:[r||(t===`initializing`?`Initializing`:t===`connecting`?`Connecting`:t===`thinking`?`Thinking`:`Processing`),i&&(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-warning/80 ml-5`,children:`Taking longer than usual — may be rate-limited or API slow. Try sending a new message to retry.`})]})}var Rr=/<teammate-message[^>]*>[\s\S]*?<\/teammate-message>/g;function zr(e){return e.replace(Rr,``).replace(/\n{3,}/g,`
6
6
 
7
7
  `).trim()}function Br({content:e,projectName:t,isStreaming:n}){let r=zr(e);return r?(0,$.jsx)(Jn,{fallbackContent:r,children:(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`animate-pulse h-4 bg-muted rounded`}),children:(0,$.jsx)(mr,{content:r,projectName:t,codeActions:!0,isStreaming:n})})}):null}function Vr({approval:e,onRespond:t}){return(0,$.jsxs)(`div`,{className:`rounded-lg border-2 border-warning/40 bg-warning/10 p-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-warning text-sm font-medium`,children:[(0,$.jsx)(Et,{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-success text-white text-xs font-medium hover:bg-success/80 transition-colors`,children:`Allow`}),(0,$.jsx)(`button`,{onClick:()=>t(e.requestId,!1),className:`px-4 py-1.5 rounded bg-error text-white text-xs font-medium hover:bg-error/80 transition-colors`,children:`Deny`})]})]})}function Hr({approval:e,onRespond:t}){return(0,$.jsx)(rr,{questions:e.input.questions??[],onSubmit:n=>t(e.requestId,!0,n),onSkip:()=>t(e.requestId,!1)})}function Ur({shells:e,onKill:t}){let n=rt(e=>e.openPanel),r=e.filter(e=>e.status!==`stopped`);return r.length===0?null:(0,$.jsx)(`div`,{className:`shrink-0 border-b border-border bg-surface-elevated/60 px-2 py-1.5 space-y-1`,children:r.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[e.status===`stopping`?(0,$.jsx)(q,{className:`size-3.5 shrink-0 animate-spin text-warning`}):(0,$.jsxs)(`span`,{className:`relative flex size-2 shrink-0`,children:[(0,$.jsx)(`span`,{className:`absolute inline-flex size-full animate-ping rounded-full bg-emerald-400 opacity-60`}),(0,$.jsx)(`span`,{className:`relative inline-flex size-2 rounded-full bg-emerald-500`})]}),(0,$.jsx)(Z,{className:`size-3.5 shrink-0 text-text-secondary`}),(0,$.jsx)(`span`,{className:`flex-1 truncate font-mono text-text-primary`,title:e.command,children:e.command}),e.status===`stopping`&&(0,$.jsx)(`span`,{className:`text-[11px] text-warning shrink-0`,children:`stopping…`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e.shellId),className:`flex items-center justify-center size-8 rounded hover:bg-surface text-text-secondary hover:text-text-primary transition-colors`,"aria-label":`View output`,title:`View output`,children:(0,$.jsx)(te,{className:`size-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e.shellId),disabled:e.status===`stopping`,className:`flex items-center justify-center size-8 rounded hover:bg-surface text-text-secondary hover:text-error transition-colors disabled:opacity-40`,"aria-label":`Stop command`,title:`Stop command`,children:(0,$.jsx)(Ce,{className:`size-3.5`})})]},e.shellId))})}function Wr(){let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function Gr(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`&&Wr()!==null;return{isListening:t,interimText:r,start:(0,Q.useCallback)(t=>{let r=Wr();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 Kr=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function qr(e){return Kr.has(e.type)}function Jr({attachments:e,onRemove:t}){let[n,r]=(0,Q.useState)(null);if(e.length===0)return null;let i=n?e.find(e=>e.id===n):null;return(0,$.jsxs)(`div`,{className:`px-2 md:px-4 pt-2`,children:[(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map(e=>(0,$.jsxs)(`div`,{className:M(`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`,e.textContent&&`cursor-pointer hover:border-primary/50`,n===e.id&&`border-primary/50 bg-surface-elevated`),onClick:()=>{e.textContent&&r(n===e.id?null:e.id)},children:[e.previewUrl?(0,$.jsx)(`img`,{src:e.previewUrl,alt:e.name,className:`size-5 rounded object-cover shrink-0`}):e.textContent?(0,$.jsx)(Z,{className:`size-3.5 shrink-0 text-text-subtle`}):e.isImage?(0,$.jsx)(it,{className:`size-3.5 shrink-0 text-text-subtle`}):(0,$.jsx)(He,{className:`size-3.5 shrink-0 text-text-subtle`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.name}),e.textContent&&(0,$.jsx)(l,{className:M(`size-3 shrink-0 text-text-subtle transition-transform`,n===e.id&&`rotate-180`)}),e.status===`uploading`?(0,$.jsx)(q,{className:`size-3 shrink-0 animate-spin text-text-subtle`}):e.status===`error`?(0,$.jsx)(`span`,{className:`text-error shrink-0`,title:`Upload failed`,children:`!`}):null,(0,$.jsx)(`button`,{type:`button`,onClick:i=>{i.stopPropagation(),t(e.id),n===e.id&&r(null)},className:`shrink-0 rounded-sm p-0.5 hover:bg-border/50 transition-colors`,"aria-label":`Remove ${e.name}`,children:(0,$.jsx)(D,{className:`size-3`})})]},e.id))}),i?.textContent&&(0,$.jsx)(`pre`,{className:`mt-1.5 max-h-40 overflow-auto rounded-md border border-border bg-background p-2 text-xs text-text-primary font-mono whitespace-pre-wrap break-words`,children:Yr(i.textContent)})]})}function Yr(e){let t=e.trim(),n=t.match(/^```\w*\n([\s\S]*?)\n```$/);return n?n[1]:t}function Xr(e,t,n){if(e.length===0)return null;let r=t+n;return r<-1||r>=e.length?null:{index:r,text:r===-1?``:e[e.length-1-r]}}var Zr=[{id:`default`,label:`Ask before edits`,icon:xt,description:`Claude will ask for approval before making each edit`},{id:`acceptEdits`,label:`Edit automatically`,icon:w,description:`Claude will edit files without asking first`},{id:`plan`,label:`Plan mode`,icon:f,description:`Claude will present a plan before editing`},{id:`bypassPermissions`,label:`Bypass permissions`,icon:E,description:`Claude will not ask before running commands`}];function Qr(e){return Zr.find(t=>t.id===e)?.label??`Unknown`}function $r(e){return Zr.find(t=>t.id===e)?.icon??xt}function ei({value:e,onChange:t,open:n,onOpenChange:r}){let i=(0,Q.useRef)(null),o=(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&&(o.current=Zr.findIndex(t=>t.id===e),o.current<0&&(o.current=0))},[n,e]);let s=(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;o.current=(o.current+t+Zr.length)%Zr.length,(i.current?.querySelector(`[data-idx="${o.current}"]`))?.focus()}if(e.key===`Enter`){e.preventDefault();let n=Zr[o.current];n&&(t(n.id),r(!1))}},[t,r]);return n?(0,$.jsxs)(`div`,{ref:i,role:`listbox`,"aria-label":`Permission modes`,onKeyDown:s,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 popover-solid shadow-[var(--shadow-panel)]`,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:Zr.map((n,i)=>{let o=n.icon,s=n.id===e;return(0,$.jsxs)(`button`,{"data-idx":i,role:`option`,"aria-selected":s,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 ${s?`bg-surface-elevated`:``}`,children:[(0,$.jsx)(o,{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})]}),s&&(0,$.jsx)(a,{className:`size-4 mt-0.5 shrink-0 text-primary`})]},n.id)})})]}):null}var ti=[{label:`Low`,value:`low`},{label:`Medium`,value:`medium`},{label:`High`,value:`high`,default:!0},{label:`Extra`,value:`xhigh`},{label:`Max`,value:`max`}];function ni(e){return e?ti.find(t=>t.value===e)?.label??e:``}function ri(e,t){let n=ni(t);return n?`${e} · ${n}`:e}function ii(e){return e.replace(/^Claude\s+/i,``)}var ai=ti.find(e=>e.default).value;function oi({model:e,effort:t,thinking:n,onModelChange:r,onEffortChange:i,onThinkingChange:s,projectName:l,providerId:u,disabled:d}){let[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.useRef)(null),_=c();(0,Q.useEffect)(()=>{!l||!u||k.get(`${O(l)}/chat/providers/${u}/models`).then(p).catch(()=>{})},[l,u]),(0,Q.useEffect)(()=>{d&&h(!1)},[d]),(0,Q.useEffect)(()=>{if(!m||_)return;let e=e=>{g.current&&!g.current.contains(e.target)&&h(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[m,_]);let v=f.find(t=>t.value===e),y=v?ii(v.label):e?ii(e):`Model`,b=t??ai,x=f.length>1,S=ri(y,b),C=e=>{e(),_||h(!1)},w=(0,$.jsxs)(`div`,{className:`flex divide-x divide-border`,children:[x&&(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 py-1`,children:[(0,$.jsx)(si,{children:`Model`}),f.map(t=>(0,$.jsxs)(li,{active:t.value===e,onClick:()=>C(()=>r(t.value)),children:[(0,$.jsx)(`span`,{className:`flex-1 truncate`,children:ii(t.label)}),t.value===e&&(0,$.jsx)(a,{className:`size-4 shrink-0 text-primary`})]},t.value))]}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 py-1`,children:[(0,$.jsx)(si,{children:`Effort`}),ti.map(e=>(0,$.jsxs)(li,{active:e.value===b,onClick:()=>C(()=>i(e.value)),children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate`,children:[e.label,e.default&&(0,$.jsx)(`span`,{className:`ml-2 text-xs text-text-subtle`,children:`Default`})]}),e.value===b&&(0,$.jsx)(a,{className:`size-4 shrink-0 text-primary`})]},e.value)),(0,$.jsx)(ci,{}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>s(!n),className:`w-full flex items-center gap-3 px-3 min-h-[44px] text-left text-sm hover:bg-surface-elevated`,role:`switch`,"aria-checked":n,children:[(0,$.jsx)(o,{className:`size-4 shrink-0`}),(0,$.jsx)(`span`,{className:`flex-1`,children:`Thinking`}),(0,$.jsx)(`span`,{className:`inline-flex h-5 w-9 items-center rounded-full transition-colors ${n?`bg-primary`:`bg-border`}`,children:(0,$.jsx)(`span`,{className:`h-4 w-4 rounded-full bg-white transition-transform ${n?`translate-x-4`:`translate-x-0.5`}`})})]})]})]});return(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsxs)(`button`,{type:`button`,disabled:d,onClick:e=>{e.stopPropagation(),d||h(e=>!e)},className:`inline-flex items-center gap-1.5 px-[9px] py-1 rounded-full text-[11.5px] text-primary bg-accent-wash border border-accent-wash-border hover:brightness-110 transition-[filter] disabled:opacity-50 disabled:cursor-default`,"aria-label":`Model ${y}, effort ${b}${n?`, thinking on`:``}`,title:d?`Can't change while running`:S,children:[(0,$.jsx)(T,{className:`h-3.5 w-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`max-w-[140px] truncate`,children:S}),n&&(0,$.jsx)(o,{className:`h-3 w-3 shrink-0`})]}),m&&!d&&(_?(0,$.jsx)(ye,{open:m,onClose:()=>h(!1),children:(0,$.jsx)(`div`,{className:`px-1 pb-2`,children:w})}):(0,$.jsx)(`div`,{ref:g,role:`listbox`,"aria-label":`Model and thinking`,onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:`absolute bottom-full left-0 mb-1 z-50 w-80 rounded-lg border border-border popover-solid shadow-[var(--shadow-panel)] max-h-[70vh] overflow-y-auto`,children:w}))]})}function si({children:e}){return(0,$.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-medium text-text-secondary`,children:e})}function ci(){return(0,$.jsx)(`div`,{className:`my-1 border-t border-border`})}function li({active:e,onClick:t,children:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,className:`w-full flex items-center gap-3 px-3 min-h-[44px] text-left text-sm text-text-primary transition-colors hover:bg-surface-elevated ${e?`bg-surface-elevated`:``}`,children:n})}var ui=new Map;function di(e){let t=ui.get(e);if(t)return t;let n=k.get(`${O(e)}/chat/slash-items`).then(e=>({items:e.items??[],recentNames:e.recentNames??[]})).catch(t=>{throw ui.delete(e),t});return ui.set(e,n),n}function fi(e){e?ui.delete(e):ui.clear()}var pi=(0,Q.memo)(function({onSend:e,isStreaming:t,onCancel:n,disabled:r,projectName:a,onSlashStateChange:o,onSlashItemsLoaded:s,slashSelected:c,onFileStateChange:l,onFileItemsLoaded:u,fileSelected:d,externalFiles:f,externalPaths:p,onExternalPathsConsumed:m,initialValue:h,clearSignal:g,onContentChange:_,getUserHistory:v,autoFocus:y,permissionMode:b,onModeChange:x,providerId:S,onProviderChange:C,model:w,onModelChange:ee,effort:T,onEffortChange:te,thinking:ne,onThinkingChange:re}){let E=(0,Q.useRef)(h??``),[k,A]=(0,Q.useState)(()=>(h??``).trim().length>0),[j,ae]=(0,Q.useState)([]),[M,N]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[se,R]=(0,Q.useState)(`next`),z=(0,Q.useRef)(null),B=(0,Q.useRef)(null),ce=(0,Q.useRef)(null),le=(0,Q.useRef)([]),V=(0,Q.useRef)([]),H=(0,Q.useRef)(0),U=(0,Q.useRef)(!1),W=(0,Q.useRef)(!1),G=(0,Q.useRef)(typeof CSS>`u`||!CSS.supports(`field-sizing`,`content`)),K=(0,Q.useCallback)(e=>{E.current=e,z.current&&(z.current.value=e),B.current&&(B.current.value=e),A(e.trim().length>0)},[]),J=(0,Q.useCallback)(()=>window.matchMedia(`(min-width: 768px)`).matches?z.current:B.current,[]),ue=(0,Q.useRef)(-1),de=(0,Q.useCallback)(e=>{let t=Xr(v?.()??[],ue.current,e);if(!t)return!1;ue.current=t.index;let{agent:n,text:r}=fr(t.text);N(n),K(r);let i=J();return i?(i.focus(),requestAnimationFrame(()=>{i.selectionStart=i.selectionEnd=r.length}),G.current&&(i.style.height=`auto`,i.style.height=Math.min(i.scrollHeight,i===B.current?80:160)+`px`),!0):!0},[v,K,J]),Y=Gr(),fe=(0,Q.useRef)(``),me=(0,Q.useCallback)(e=>{let t=fe.current;K(t?t+` `+e:e),G.current&&requestAnimationFrame(()=>{let e=J();e&&(e.style.height=`auto`,e.style.height=Math.min(e.scrollHeight,160)+`px`)})},[K,J]),he=(0,Q.useCallback)(()=>{Y.isListening?Y.stop():(fe.current=E.current.trim(),Y.start(me))},[Y.isListening,Y.start,Y.stop,me]);(0,Q.useEffect)(()=>{let e=()=>{Y.supported&&Tn(J())&&he()};return window.addEventListener(`toggle-voice-input`,e),()=>window.removeEventListener(`toggle-voice-input`,e)},[Y.supported,he,J]),(0,Q.useEffect)(()=>{let e=e=>{let{text:t,label:n}=e.detail??{};if(!t)return;window.dispatchEvent(new Event(`ppm:send-to-chat:ack`));let r={id:oe(),name:n??`Terminal output`,file:new File([],`terminal-output.txt`),isImage:!1,textContent:t,status:`ready`};ae(e=>[...e,r]),J()?.focus()};return window.addEventListener(`ppm:send-to-chat`,e),()=>window.removeEventListener(`ppm:send-to-chat`,e)},[J]),(0,Q.useEffect)(()=>{h&&!E.current&&(K(h),setTimeout(()=>{let e=z.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},50))},[h]),(0,Q.useEffect)(()=>{g&&K(``)},[g]),(0,Q.useEffect)(()=>{y&&setTimeout(()=>{J()?.focus()},100)},[]);let X=(0,Q.useCallback)(()=>{if(!a){le.current=[],s?.([],[]);return}di(a).then(e=>{le.current=e.items,s?.(e.items,e.recentNames)}).catch(()=>{le.current=[],s?.([],[])})},[a,s]);(0,Q.useEffect)(()=>{X()},[X]),(0,Q.useEffect)(()=>{let e=()=>{fi(a),X()};return window.addEventListener(`ppm:slash-items-refresh`,e),()=>window.removeEventListener(`ppm:slash-items-refresh`,e)},[X,a]),(0,Q.useEffect)(()=>{let e=()=>{if(!a){V.current=[],u?.([]);return}let{fileIndex:e}=Ye.getState(),t=e.map(e=>({name:e.name,path:e.path,type:e.type}));V.current=t,u?.(t)};e();let t=Ye.getState().fileIndex,n=Ye.getState().indexStatus;return Ye.subscribe(r=>{(r.fileIndex!==t||r.indexStatus!==n)&&(t=r.fileIndex,n=r.indexStatus,e())})},[a]),(0,Q.useEffect)(()=>{if(!c)return;let e=J();if(!e)return;let t=e.value,n=e.selectionStart,r=t.slice(0,n),i=t.slice(n),a=e=>e.startsWith(`/`)?``:e[0];if(c.type===`agent`){let t=r.replace(/(?:^|\s)\/\S*$/,a);N(c.name),K(t+i),o?.(!1,``),U.current=!1,e.focus(),setTimeout(()=>{e.selectionStart=e.selectionEnd=t.length},0);return}let s=r.replace(/(?:^|\s)\/\S*$/,e=>`${a(e)}/${c.name} `);K(s+i),o?.(!1,``),U.current=!1,l?.(!1,``),W.current=!1,e.focus(),setTimeout(()=>{e.selectionStart=e.selectionEnd=s.length},0)},[c]),(0,Q.useEffect)(()=>{if(!d)return;let e=J();if(!e)return;let t=e.value,n=e.selectionStart,r=t.slice(0,n),i=t.slice(n),a=r.match(/@(\S*)$/);if(a){let t=r.length-a[0].length;K(r.slice(0,t)+`@${d.path} `+i);let n=t+d.path.length+2;setTimeout(()=>{e.selectionStart=e.selectionEnd=n,e.focus()},0)}else{let n=t+`@${d.path} `;K(n),setTimeout(()=>{e.selectionStart=e.selectionEnd=n.length,e.focus()},0)}l?.(!1,``),W.current=!1},[d]),(0,Q.useEffect)(()=>{!f||f.length===0||_e(f)},[f]),(0,Q.useEffect)(()=>{if(!p||p.length===0)return;let e=p.map(e=>`@${e}`).join(` `),t=E.current;K(t+(t.length>0&&!t.endsWith(` `)?` `:``)+e+` `),J()?.focus(),m?.()},[p]);let ge=(0,Q.useCallback)(async e=>{if(!a)return null;try{let t=new FormData;t.append(`files`,e);let n={},r=ie();r&&(n.Authorization=`Bearer ${r}`);let i=await(await fetch(`${O(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]),_e=(0,Q.useCallback)(async e=>{for(let t of e){let e=oe(),n=qr(t),r=n?URL.createObjectURL(t):void 0,i={id:e,name:t.name,file:t,isImage:n,previewUrl:r,status:`uploading`};ae(e=>[...e,i]),ge(t).then(t=>{ae(n=>n.map(n=>n.id===e?{...n,serverPath:t??void 0,status:t?`ready`:`error`}:n))})}(B.current??z.current)?.focus()},[ge]),ve=(0,Q.useCallback)(e=>{ae(t=>{let n=t.find(t=>t.id===e);return n?.previewUrl&&URL.revokeObjectURL(n.previewUrl),t.filter(t=>t.id!==e)})},[]),ye=(0,Q.useCallback)(()=>{let n=E.current.trim(),r=j.filter(e=>e.status===`ready`);if(!n&&r.length===0&&!M){L(!1);return}let i=M?`Use the ${M} agent to ${n}`.trimEnd():n;o?.(!1,``),U.current=!1,l?.(!1,``),W.current=!1,Y.isListening&&Y.stop(),e(i,r,t?se:void 0),K(``);for(let e of j)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);ae([]),N(null),L(!1),R(`next`),ue.current=-1,G.current&&(z.current&&(z.current.style.height=`auto`),B.current&&(B.current.style.height=`auto`))},[j,M,e,o,l,t,se,K]),be=(0,Q.useCallback)(()=>{if(!r){if(j.some(e=>e.status===`uploading`)){(E.current.trim()||j.some(e=>e.status!==`error`))&&L(!0);return}ye()}},[j,r,ye]);(0,Q.useEffect)(()=>{I&&(j.some(e=>e.status===`uploading`)||ye())},[I,j,ye]);let xe=(0,Q.useCallback)(e=>{if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),be();return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){if(!(ue.current>=0)&&(e.key===`ArrowDown`||E.current!==``||M))return;de(e.key===`ArrowUp`?1:-1)&&e.preventDefault();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)}},[be,b,x,de,M]),Se=(0,Q.useCallback)((e,t)=>{let n=e.slice(0,t),r=n.includes(`/`),i=n.includes(`@`);if(!r&&!i){U.current&&=(o?.(!1,``),!1),W.current&&=(l?.(!1,``),!1);return}if(r){let e=n.match(/(?:^|\s)\/(\S*)$/);if(e&&le.current.length>0){let t=e[1]??``;o?.(!0,t),U.current=!0,W.current&&=(l?.(!1,``),!1);return}}if(i){let e=n.match(/@(\S*)$/);if(e&&V.current.length>0){l?.(!0,e[1]??``),W.current=!0,U.current&&=(o?.(!1,``),!1);return}}U.current&&=(o?.(!1,``),!1),W.current&&=(l?.(!1,``),!1)},[o,l]),we=(0,Q.useCallback)(e=>{let t=e.target,n=t.value;E.current=n,ue.current=-1;let r=t===z.current?B.current:z.current;r&&(r.value=n),A(n.trim().length>0),Se(n,t.selectionStart),_?.(n,j.filter(e=>e.status===`ready`&&e.serverPath).map(e=>({name:e.name,path:e.serverPath}))),G.current&&(H.current&&cancelAnimationFrame(H.current),H.current=requestAnimationFrame(()=>{H.current=0,t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,t===B.current?80:160)+`px`}))},[Se,_,j]),Te=(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(),_e(n))},[_e]),Ee=(0,Q.useCallback)(e=>{e.preventDefault();let t=e.dataTransfer.getData(`application/x-ppm-path`);if(t){let e=E.current;K(e+(e.length>0&&!e.endsWith(` `)?` `:``)+`@${t} `),J()?.focus();return}let n=Array.from(e.dataTransfer.files);n.length>0&&_e(n)},[_e,K,J]),De=(0,Q.useCallback)(e=>{e.preventDefault()},[]),Oe=(0,Q.useCallback)(()=>{ce.current?.click()},[]),ke=(0,Q.useCallback)(e=>{let t=Array.from(e.target.files??[]);t.length>0&&_e(t),e.target.value=``},[_e]),Ae=k||j.some(e=>e.status!==`error`)||!!M,Z=t&&!Ae;return(0,$.jsxs)(`div`,{className:`p-2 md:p-3`,children:[(0,$.jsxs)(`div`,{className:`border border-border rounded-[var(--rad)] bg-panel shadow-[var(--shadow-float)] cursor-text`,onClick:e=>{r||e.target instanceof HTMLTextAreaElement||J()?.focus()},children:[M&&(0,$.jsx)(`div`,{className:`px-2 md:px-4 pt-2`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 rounded-md border border-sky-500/30 bg-sky-500/10 px-2 py-1 text-xs font-medium text-sky-600 dark:text-sky-400`,children:[(0,$.jsx)(i,{className:`size-3.5 shrink-0`}),M,(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(null),J()?.focus()},className:`shrink-0 rounded-sm p-0.5 hover:bg-sky-500/20 transition-colors`,"aria-label":`Remove ${M} agent`,children:(0,$.jsx)(D,{className:`size-3`})})]})}),(0,$.jsx)(Jr,{attachments:j,onRemove:ve}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 pt-2 md:hidden relative`,children:[(0,$.jsx)(mi,{mode:b??`bypassPermissions`,onClick:()=>F(e=>!e)}),(0,$.jsx)(ei,{value:b??`bypassPermissions`,onChange:e=>x?.(e),open:P,onOpenChange:F}),C&&a&&(0,$.jsx)(pe,{value:S??`claude`,onChange:C,projectName:a}),ee&&a&&(0,$.jsx)(oi,{model:w??null,effort:T??null,thinking:ne??!1,onModelChange:ee,onEffortChange:te??(()=>{}),onThinkingChange:re??(()=>{}),projectName:a,providerId:S??`claude`,disabled:t}),t&&(0,$.jsx)(gi,{value:se,onChange:R})]}),(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(),Oe()},disabled:r,className:`flex items-center justify-center size-8 shrink-0 rounded-[10px] text-text-3 hover:text-text-primary transition-colors disabled:opacity-50`,"aria-label":`Attach file`,children:(0,$.jsx)(Tt,{className:`size-4`})}),(0,$.jsx)(`textarea`,{ref:B,defaultValue:h??``,onChange:we,onKeyDown:xe,onPaste:Te,onDrop:Ee,onDragOver:De,placeholder:t?`Follow-up...`:`Ask anything...`,disabled:r,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 [field-sizing:content]`}),Y.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},disabled:r,className:`flex items-center justify-center size-8 shrink-0 rounded-[10px] transition-colors disabled:opacity-50 ${Y.isListening?`bg-error text-white animate-pulse`:`text-text-3 hover:text-text-primary`}`,"aria-label":Y.isListening?`Stop voice input`:`Start voice input`,children:Y.isListening?(0,$.jsx)(wt,{className:`size-4`}):(0,$.jsx)(Ie,{className:`size-4`})}),Z?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),n?.()},className:`flex items-center justify-center size-9 shrink-0 rounded-[11px] bg-error text-white hover:bg-error/80 shadow-[var(--shadow-float)] transition-colors`,"aria-label":`Stop`,children:(0,$.jsx)(Ce,{className:`size-3.5`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),I?L(!1):be()},disabled:r||!Ae,className:`flex items-center justify-center size-9 shrink-0 rounded-[11px] bg-primary text-primary-foreground hover:bg-primary/90 shadow-[var(--shadow-float)] disabled:opacity-30 disabled:shadow-none transition-colors`,"aria-label":I?`Cancel queued send`:`Send`,children:I?(0,$.jsx)(q,{className:`size-4 animate-spin`}):(0,$.jsx)(st,{className:`size-4`})})]}),(0,$.jsxs)(`div`,{className:`hidden md:block`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 px-2.5 pt-2.5`,children:[(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(mi,{mode:b??`bypassPermissions`,onClick:()=>F(e=>!e)}),(0,$.jsx)(ei,{value:b??`bypassPermissions`,onChange:e=>x?.(e),open:P,onOpenChange:F})]}),C&&a&&(0,$.jsx)(pe,{value:S??`claude`,onChange:C,projectName:a}),ee&&a&&(0,$.jsx)(oi,{model:w??null,effort:T??null,thinking:ne??!1,onModelChange:ee,onEffortChange:te??(()=>{}),onThinkingChange:re??(()=>{}),projectName:a,providerId:S??`claude`,disabled:t}),t&&(0,$.jsx)(gi,{value:se,onChange:R})]}),(0,$.jsxs)(`div`,{className:`flex items-end gap-2 px-2.5 py-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),Oe()},disabled:r,className:`flex items-center justify-center size-[34px] shrink-0 rounded-[10px] text-text-3 hover:text-text-primary hover:bg-surface-elevated transition-colors disabled:opacity-50`,"aria-label":`Attach file`,children:(0,$.jsx)(Tt,{className:`size-[17px]`})}),(0,$.jsx)(`textarea`,{ref:z,defaultValue:h??``,onChange:we,onKeyDown:xe,onPaste:Te,onDrop:Ee,onDragOver:De,placeholder:t?`Follow-up or Stop...`:`Ask anything...`,disabled:r,rows:1,className:`flex-1 resize-none bg-transparent py-2 text-sm text-foreground placeholder:text-text-subtle focus:outline-none disabled:opacity-50 max-h-[90px] leading-relaxed [field-sizing:content]`}),Y.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),he()},disabled:r,className:`flex items-center justify-center size-[34px] shrink-0 rounded-[10px] transition-colors disabled:opacity-50 ${Y.isListening?`bg-error text-white animate-pulse`:`text-text-3 hover:text-text-primary hover:bg-surface-elevated`}`,"aria-label":Y.isListening?`Stop voice input`:`Start voice input`,children:Y.isListening?(0,$.jsx)(wt,{className:`size-[17px]`}):(0,$.jsx)(Ie,{className:`size-[17px]`})}),Z?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),n?.()},className:`flex items-center justify-center size-9 shrink-0 rounded-[11px] bg-error text-white hover:bg-error/80 shadow-[var(--shadow-float)] transition-colors`,"aria-label":`Stop response`,children:(0,$.jsx)(Ce,{className:`size-4`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),I?L(!1):be()},disabled:r||!Ae,className:`flex items-center justify-center size-9 shrink-0 rounded-[11px] bg-primary text-primary-foreground hover:bg-primary/90 shadow-[var(--shadow-float)] disabled:opacity-30 disabled:cursor-not-allowed disabled:shadow-none transition-colors`,"aria-label":I?`Cancel queued send`:`Send message`,children:I?(0,$.jsx)(q,{className:`size-4 animate-spin`}):(0,$.jsx)(st,{className:`size-[17px]`})})]})]})]}),(0,$.jsx)(`input`,{ref:ce,type:`file`,multiple:!0,className:`hidden`,onChange:ke})]})});function mi({mode:e,onClick:t}){let n=$r(e),r=Qr(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t()},className:`inline-flex items-center gap-1.5 px-[9px] py-1 rounded-full text-[11.5px] text-text-2 bg-panel-2 border border-border-soft hover:text-text-primary hover:border-border transition-colors`,"aria-label":`Permission mode: ${r}`,children:[(0,$.jsx)(n,{className:`size-3`}),(0,$.jsx)(`span`,{className:`max-w-[100px] truncate`,children:r})]})}var hi=[{value:`now`,label:`Interrupt`,Icon:fe},{value:`next`,label:`Queue`,Icon:Ct},{value:`later`,label:`Later`,Icon:C}];function gi({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=hi.find(t=>t.value===e)??hi[1],i=r.Icon;return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),n()},className:`inline-flex items-center gap-1.5 px-[9px] py-1 rounded-full text-[11.5px] text-text-2 bg-panel-2 border border-border-soft hover:text-text-primary hover:border-border transition-colors`,"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 _i(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(r[a-1]+1,n[a]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function vi(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r.startsWith(n))return{rank:0,distance:0};if(r.includes(n))return{rank:1,distance:r.indexOf(n)};let i=Math.max(Math.floor(n.length*.4),2),a=_i(n,r.slice(0,n.length+i));return a<=i?{rank:2,distance:a}:null}var yi=1;function bi(e,t,n=20,r=[]){if(!t)return e;t=t.slice(0,50);let i=new Map(r.map((e,t)=>[e,t])),a=[];for(let n of e){let e=vi(t,n.name),o=[e,vi(t,n.description)].filter(e=>e!==null).sort((e,t)=>e.rank-t.rank||e.distance-t.distance)[0];if(o){let t=i.get(n.name),s=t!==void 0&&e?.rank===o.rank;a.push({item:n,rank:o.rank-(s?yi:0),distance:o.distance,recency:t??r.length})}}return a.sort((e,t)=>e.rank-t.rank||e.recency-t.recency||e.distance-t.distance||e.item.name.localeCompare(t.item.name)),a.slice(0,n).map(e=>e.item)}function xi({items:e,filter:t,onSelect:n,onClose:r,visible:a,recentNames:o=[],projectName:s}){let[c,l]=(0,Q.useState)(0),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=(0,Q.useMemo)(()=>new Set(o),[o]),m=(0,Q.useMemo)(()=>{if(t)return{items:bi(e,t,20,o),recentCount:0};if(o.length>0){let t=[],n=[];for(let r of e)p.has(r.name)?t.push(r):n.push(r);return t.sort((e,t)=>o.indexOf(e.name)-o.indexOf(t.name)),{items:[...t,...n],recentCount:t.length}}return{items:e,recentCount:0}},[e,t,o,p]),h=m.items,g=m.recentCount;(0,Q.useEffect)(()=>{l(0)},[t]),(0,Q.useEffect)(()=>{let e=f.current;e&&e.children[c]?.scrollIntoView({block:`nearest`})},[c]);let _=(0,Q.useCallback)(e=>{if(!a||h.length===0)return!1;switch(e.key){case`ArrowUp`:return e.preventDefault(),l(e=>e>0?e-1:h.length-1),!0;case`ArrowDown`:return e.preventDefault(),l(e=>e<h.length-1?e+1:0),!0;case`Enter`:case`Tab`:return e.preventDefault(),h[c]&&n(h[c]),!0;case`Escape`:return e.preventDefault(),r(),!0}return!1},[a,h,c,n,r]);(0,Q.useEffect)(()=>{if(!a)return;let e=e=>{_(e)&&e.stopPropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[a,_]);let v=(0,Q.useCallback)(()=>{!s||u||(d(!0),k.del(`${O(s)}/chat/slash-items/cache`).then(()=>{window.dispatchEvent(new CustomEvent(`ppm:slash-items-refresh`))}).finally(()=>d(!1)))},[s,u]);return!a||h.length===0?null:(0,$.jsx)(`div`,{className:`max-h-52 overflow-y-auto overflow-x-hidden border-b border-border bg-surface`,children:(0,$.jsx)(`div`,{ref:f,className:`py-1`,children:h.map((e,t)=>{let r=g>0&&t===0,a=g>0&&t===g;return(0,$.jsxs)(`div`,{children:[r&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-3 pt-1 pb-0.5`,children:[(0,$.jsxs)(`span`,{className:`text-[10px] font-medium text-text-subtle uppercase tracking-wider flex items-center gap-1`,children:[(0,$.jsx)(C,{className:`size-3`}),`Recent`]}),s&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),v()},className:`text-text-subtle hover:text-text-primary transition-colors p-0.5 rounded`,title:`Refresh skill list`,"aria-label":`Refresh skill list`,children:(0,$.jsx)(Pe,{className:`size-3 ${u?`animate-spin`:``}`})})]}),a&&(0,$.jsx)(`div`,{className:`px-3 pt-1.5 pb-0.5`,children:(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-text-subtle uppercase tracking-wider`,children:`All`})}),(0,$.jsxs)(`button`,{className:`flex items-start gap-3 w-full px-3 py-2 text-left transition-colors ${t===c?`bg-primary/10 text-primary`:`hover:bg-surface-hover text-text-primary`}`,onMouseEnter:()=>l(t),onClick:()=>n(e),children:[(0,$.jsx)(`span`,{className:`shrink-0 mt-0.5`,children:e.type===`builtin`?(0,$.jsx)(fe,{className:`size-4 text-emerald-500`}):e.type===`skill`?(0,$.jsx)(T,{className:`size-4 text-warning`}):e.type===`agent`?(0,$.jsx)(i,{className:`size-4 text-sky-500`}):(0,$.jsx)(Oe,{className:`size-4 text-primary`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline gap-2 min-w-0`,children:[(0,$.jsxs)(`span`,{className:`font-medium text-sm truncate`,children:[`/`,e.name]}),e.argumentHint&&(0,$.jsx)(`span`,{className:`text-xs text-text-subtle truncate`,children:e.argumentHint}),(0,$.jsx)(`span`,{className:`text-xs text-text-subtle capitalize ml-auto shrink-0 whitespace-nowrap`,children:e.scope===`bundled`?`PPM`:e.scope===`user`?`global`:e.type})]}),e.description&&(0,$.jsx)(`p`,{className:`text-xs text-text-subtle mt-0.5 line-clamp-2 break-words`,children:e.description})]})]})]},`${e.type}-${e.name}`)})})})}function Si({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)(Be,{className:`size-4 text-warning`}):(0,$.jsx)($e,{className:`size-4 text-primary`})}),(0,$.jsx)(`span`,{className:`text-sm truncate`,children:e.path})]},e.path))})})}var Ci=e=>`${(e/1048576).toFixed(2)} MB`;function wi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Ti(){let e=null;for(let t of document.querySelectorAll(`.overflow-y-auto`))t.clientHeight<100||!t.querySelector(`[data-msg-index]`)||(!e||t.scrollHeight>e.scrollHeight)&&(e=t);let t=[];e&&(t.push(`Rendered messages: ${e.querySelectorAll(`[data-msg-index]`).length}`),t.push(`Transcript DOM nodes: ${e.querySelectorAll(`*`).length}`),t.push(`Transcript height: ${Math.round(e.scrollHeight)}px`));let n=performance.memory;return n&&t.push(`JS heap (page): ${(n.usedJSHeapSize/1048576).toFixed(1)} MB`),t}function Ei({sessionId:e,projectName:t}){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let n=!0;return k.get(`${O(t)}/chat/sessions/${e}/images?project=${encodeURIComponent(t)}`).then(e=>{n&&r(e)}).catch(e=>{n&&a(e.message)}),()=>{n=!1}},[e,t]);let u=n=>{s(n),a(null),k.post(`${O(t)}/chat/sessions/${e}/images/strip?project=${encodeURIComponent(t)}`,{mode:n}).then(e=>{r(e.remaining),l({removed:e.removed,bytes:e.bytesFreed})}).catch(e=>a(e.message)).finally(()=>s(null))};return i&&!n?(0,$.jsx)(`p`,{className:`text-[11px] text-error`,children:i}):n?(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`h3`,{className:`text-xs font-semibold text-foreground`,children:`Transcript images`}),n.total===0?(0,$.jsxs)(`p`,{className:`text-[11px] text-text-subtle`,children:[`No images in tool results`,c?` — transcript is clean.`:`.`]}):(0,$.jsxs)(`p`,{className:`text-[11px] text-text-secondary`,children:[n.total,` image`,n.total===1?``:`s`,` in tool results · `,wi(n.bytes),` of base64, replayed on every turn.`]}),n.oversized>0&&(0,$.jsxs)(`div`,{className:`flex gap-2 rounded-md border border-warning/40 bg-warning/10 p-2 text-[11px] text-text-secondary`,children:[(0,$.jsx)(Xe,{className:`mt-px size-3.5 shrink-0 text-warning`}),(0,$.jsxs)(`span`,{children:[n.oversized,` image`,n.oversized===1?` is`:`s are`,` wider than `,n.limit,`px (largest `,n.largestSide,`px). The API rejects those once a request carries several images, so they already contribute nothing — removing them loses no context.`]})]}),c&&(0,$.jsxs)(`p`,{className:`text-[11px] text-success`,children:[`Removed `,c.removed,` image`,c.removed===1?``:`s`,`, freed `,wi(c.bytes),`.`]}),i&&(0,$.jsx)(`p`,{className:`text-[11px] text-error`,children:i}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 sm:flex-row`,children:[(0,$.jsxs)(_,{size:`sm`,variant:`outline`,className:`flex-1`,disabled:o!==null||n.oversized===0,onClick:()=>u(`oversized`),children:[o===`oversized`?(0,$.jsx)(q,{className:`size-3.5 animate-spin`}):(0,$.jsx)(St,{className:`size-3.5`}),`Remove oversized`,n.oversized>0?` (${n.oversized} · ${wi(n.oversizedBytes)})`:``]}),(0,$.jsxs)(_,{size:`sm`,variant:`destructive`,className:`flex-1`,disabled:o!==null||n.total===0,onClick:()=>u(`all`),children:[o===`all`?(0,$.jsx)(q,{className:`size-3.5 animate-spin`}):(0,$.jsx)(St,{className:`size-3.5`}),`Remove all`,n.total>0?` (${n.total} · ${wi(n.bytes)})`:``]})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-text-subtle`,children:`Images you attached to a message are never touched. A removed tool image is replaced by its placeholder text; the chat still shows the file, re-read from disk.`})]}):(0,$.jsx)(`p`,{className:`text-[11px] text-text-subtle`,children:`Scanning transcript for images...`})}function Di({sessionId:e,projectName:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),l=c(),u=()=>{r(!0),s(!1),a(null),k.get(`${O(t)}/chat/sessions/${e}/debug?project=${encodeURIComponent(t)}`).then(e=>{let t=e.jsonlSizeBytes==null?``:` (${Ci(e.jsonlSizeBytes)}${e.jsonlLines==null?``:`, ${e.jsonlLines} records`})`;a([`PPM Session: ${e.ppmSessionId}`,`SDK Session: ${e.sdkSessionId}`,e.jsonlPath?`JSONL: ${e.jsonlPath}${t}`:`JSONL: not found`,e.projectPath?`Project: ${e.projectPath}`:null,...Ti()].filter(Boolean).join(`
8
- `))}).catch(()=>a(`Failed to load debug info`))},d=(0,$.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,$.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[(0,$.jsx)(je,{className:`size-4 text-primary`}),`Session debug info`]}),(0,$.jsx)(`pre`,{className:`max-h-[35vh] overflow-y-auto whitespace-pre-wrap break-all rounded-md border border-border bg-surface p-2.5 font-mono text-[11px] leading-relaxed text-text-secondary select-text`,children:i??`Loading...`}),(0,$.jsx)(_,{size:`sm`,onClick:()=>{i&&nt(i).then(e=>{e&&(s(!0),setTimeout(()=>s(!1),1500))})},disabled:!i,className:`w-full`,children:o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(bt,{className:`size-3.5`}),` Copied!`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ge,{className:`size-3.5`}),` Copy`]})}),(0,$.jsx)(`div`,{className:`border-t border-border pt-3`,children:n&&(0,$.jsx)(Ei,{sessionId:e,projectName:t})})]});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{onClick:u,className:`p-1 rounded text-text-subtle hover:text-text-secondary hover:bg-surface-elevated transition-colors`,title:`Session debug info`,children:(0,$.jsx)(je,{className:`size-3`})}),l?(0,$.jsx)(ye,{open:n,onClose:()=>r(!1),className:`popover-solid`,children:(0,$.jsx)(`div`,{className:`max-h-[85vh] overflow-y-auto px-4 pb-4 pt-1`,children:d})}):(0,$.jsx)(S,{open:n,onOpenChange:r,children:(0,$.jsxs)(y,{className:`sm:max-w-lg`,children:[(0,$.jsx)(b,{className:`sr-only`,children:`Session debug info`}),d]})})]})}var Oi=`ppm-hienlh`;function ki({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,C]=(0,Q.useState)(!1),[w,ee]=(0,Q.useState)(`idle`);function T(){f(null),m(``),ee(`idle`),u(null)}function te(){t(!1),T(),i(``),o(``),u(null)}async function ne(){C(!0),u(null);try{let{url:e,state:t}=await K();f(t),ee(`waiting`),window.open(e,`_blank`)}catch(e){u(e.message)}C(!1)}async function re(){if(!(!p.trim()||!d)){C(!0),u(null);try{let e=p.trim();e.includes(`#`)&&(e=e.split(`#`)[0]??e),await B(e,d),te(),n(`Account connected via OAuth!`)}catch(e){u(e.message)}C(!1)}}async function E(){if(r.trim()){c(!0),u(null);try{await G({apiKey:r.trim(),label:a.trim()||void 0}),te(),n(`Account added!`)}catch(e){u(e.message)}c(!1)}}let D=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)(S,{open:e,onOpenChange:e=>{e||te()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsx)(b,{className:`text-sm`,children:`Add Claude Account`}),(0,$.jsx)(x,{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`}),w===`idle`?(0,$.jsx)(_,{size:`sm`,className:`w-full h-8 text-xs`,onClick:ne,disabled:h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{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)(Ne,{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)(_,{size:`sm`,className:`flex-1 h-7 text-xs`,onClick:re,disabled:!p.trim()||h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Connecting...`]}):`Connect`}),(0,$.jsx)(_,{size:`sm`,variant:`ghost`,className:`h-7 text-xs`,onClick:T,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)(X,{htmlFor:`add-token`,className:`text-xs`,children:`Token`}),(0,$.jsx)(Ne,{id:`add-token`,type:`password`,placeholder:`sk-ant-...`,value:r,onChange:e=>i(e.target.value),className:`text-xs h-8 font-mono`}),D&&(0,$.jsxs)(`p`,{className:`text-[10px] text-muted-foreground`,children:[`Detected: `,D]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(X,{htmlFor:`add-label`,className:`text-xs`,children:`Label (optional)`}),(0,$.jsx)(Ne,{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-error/10 text-error`,children:l}),(0,$.jsxs)(v,{children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7`,onClick:te,children:`Cancel`}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7`,onClick:E,disabled:!r.trim()||s,children:s?`Adding...`:`Add Token`})]})]})})}function Ai({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),[C,w]=(0,Q.useState)(!1);e&&!C&&(s(r?new Set([r]):new Set(a.map(e=>e.id))),w(!0)),!e&&C&&w(!1);function ee(){t(!1),l(``),d(!1),p(!1)}async function T(e){if(o.size===0)return;h(!0);let t=c.trim()||Oi;try{let n={"Content-Type":`application/json`},r=ie();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();e&&await nt(s)?i?.(`Backup copied to clipboard!`):(Mi(s),i?.(`Backup downloaded.`)),ee()}catch{}h(!1)}let te=o.size>0&&!m;return(0,$.jsx)(S,{open:e,onOpenChange:e=>{e||ee()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsxs)(b,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(ke,{className:`size-3.5`}),` Export Accounts`]}),(0,$.jsx)(x,{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)(X,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Ne,{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-error/30 bg-error/5 p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-error`,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-warning/30 bg-warning/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-warning`,children:`Refresh before export — invalidates previous shares`})}):(0,$.jsx)(`div`,{className:`rounded-md border border-success/30 bg-success/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-success`,children:`Share current token (safe)`})}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Encrypted with AES-256-GCM + scrypt.`})]}),(0,$.jsxs)(v,{className:`gap-1.5 flex-col sm:flex-row`,children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:ee,children:`Cancel`}),(0,$.jsxs)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,disabled:!te,onClick:()=>T(!0),children:[(0,$.jsx)(Ge,{className:`size-3 mr-1`}),` Copy`]}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!te,onClick:()=>T(!1),children:m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Exporting...`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ne,{className:`size-3 mr-1`}),` Download`]})})]})]})})}function ji({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 le({data:r.trim(),password:a.trim()||Oi});d(),n(`Imported ${e.imported} account(s)`)}catch(e){u(e.message||`Import failed`)}c(!1)}}return(0,$.jsx)(S,{open:e,onOpenChange:e=>{e||d()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsxs)(b,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(ke,{className:`size-3.5`}),` Import Accounts`]}),(0,$.jsx)(x,{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)(X,{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)(X,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Ne,{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-error/10 text-error`,children:l}),(0,$.jsxs)(v,{children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:d,children:`Cancel`}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!r.trim()||s,onClick:f,children:s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Importing...`]}):`Import`})]})]})})}function Mi(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 Ni=typeof window<`u`?window.matchMedia(`(min-width: 768px)`):null;function Pi(e){return Ni?.addEventListener(`change`,e),()=>Ni?.removeEventListener(`change`,e)}function Fi(){return Ni?.matches??!0}function Ii(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0);return(0,Q.useEffect)(()=>{r(!0),V().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)(_e,{value:e.strategy,onValueChange:async e=>{t(await L({strategy:e}))},children:[(0,$.jsx)(ft,{className:`w-full h-9 text-xs`,children:(0,$.jsx)(J,{})}),(0,$.jsxs)(Se,{children:[(0,$.jsx)(Ae,{value:`round-robin`,children:`Round-robin`}),(0,$.jsx)(Ae,{value:`fill-first`,children:`Fill-first`}),(0,$.jsx)(Ae,{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 L({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:`space-y-1.5 border-t border-border pt-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Cooldown parking`}),(0,$.jsx)(Fe,{checked:e.cooldownEnabled,onCheckedChange:async e=>{t(await L({cooldownEnabled:e}))}})]}),(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Park a failing account (rate limit / usage limit / auth error) until it recovers. Off: accounts stay selectable — rotation still skips accounts already ≥95% on the 5-hour limit.`})]}),(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 Li({open:e,onOpenChange:t}){let n=(0,Q.useSyncExternalStore)(Pi,Fi);return e?n?(0,$.jsx)(S,{open:e,onOpenChange:t,children:(0,$.jsxs)(y,{className:`sm:max-w-sm`,children:[(0,$.jsx)(g,{children:(0,$.jsxs)(b,{className:`text-sm flex items-center gap-2`,children:[(0,$.jsx)(pt,{className:`size-4`}),` Rotation & Retry`]})}),(0,$.jsx)(Ii,{})]})}):(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)(pt,{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)(D,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`px-4 py-4 pb-8`,children:(0,$.jsx)(Ii,{})})]})]}):null}var Ri=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],zi=Array.from({length:24},(e,t)=>t);function Bi(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 Vi(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 Hi(e){return zi.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 Ui(e){return e===0?`bg-surface-elevated`:e<.3?`bg-success/30`:e<.5?`bg-success/60`:e<.7?`bg-warning/50`:e<.9?`bg-warning/80`:`bg-error/80`}function Wi(e){return e<.3?`bg-success`:e<.7?`bg-warning`:`bg-error`}function Gi({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),H(e).then(n).catch(()=>n([])).finally(()=>i(!1))},[e]);let s=(0,Q.useMemo)(()=>t?Bi(t,a):null,[t,a]),c=(0,Q.useMemo)(()=>s?Vi(s):[],[s]),l=(0,Q.useMemo)(()=>s?Hi(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)(q,{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:Ri.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 ${Wi(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:zi.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] ${Ui(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:[Ri.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)}),zi.map(n=>{let r=s[t][n];return(0,$.jsx)(`div`,{className:`flex-1 aspect-square rounded-[1px] ${Ui(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`}),zi.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-success/30`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-success/60`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/50`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/80`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-error/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 Ki(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function qi(e){return e>=90?`bg-error`:e>=70?`bg-warning`:`bg-success`}function Ji(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 Yi({label:e,bucket:t}){if(!t)return null;let n=Math.round(t.utilization*100),r=Ji(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 ${qi(n)}`,style:{width:`${Math.min(n,100)}%`}})}),(0,$.jsxs)(`span`,{className:`text-xs font-medium tabular-nums w-10 text-right ${Ki(n)}`,children:[n,`%`]})]})]})}function Xi(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 Zi(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-warning`}:t?{label:`expired`,tip:`Token expired, no refresh token`,color:`text-error`}:e.hasRefreshToken?{label:`long-lived`,tip:`OAuth token with refresh — long-lived`,color:`text-success`}:{label:`temp`,tip:`Temporary token without refresh — will expire`,color:`text-warning`}}function Qi(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 $i({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-error 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)(te,{className:`size-3`})}),!f&&a&&e.isOAuth&&(0,$.jsx)(`button`,{className:`p-1 rounded cursor-pointer text-text-subtle hover:text-primary hover:bg-surface-elevated transition-colors`,onClick:()=>a(e.accountId),title:`Export this account`,children:(0,$.jsx)(ne,{className:`size-3`})}),!f&&r&&(0,$.jsx)(Fe,{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-error hover:bg-surface-elevated transition-colors`,onClick:()=>i(e.accountId,e.accountLabel??e.accountId.slice(0,8)),title:`Remove account`,children:(0,$.jsx)(we,{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)(Yi,{label:`5-Hour Session`,bucket:l.session}),(0,$.jsx)(Yi,{label:`Weekly`,bucket:l.weekly}),(0,$.jsx)(Yi,{label:`Weekly (Opus)`,bucket:l.weeklyOpus}),(0,$.jsx)(Yi,{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=Zi(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:[`↻ `,Qi(new Date(l.lastFetchedAt).getTime())]}),n?.expiresAt&&n.expiresAt*1e3>Date.now()&&(0,$.jsxs)(`span`,{title:`Token expires in`,children:[`⏱ `,Xi(n.expiresAt*1e3)]}),(0,$.jsxs)(`span`,{className:e.color,title:e.tip,children:[`© `,e.label]})]})})()]})}function ea({usage:e,visible:t,onClose:n,onReload:r,loading:i,lastFetchedAt:a}){let[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!0),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(new Set),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,ee]=(0,Q.useState)(!1),[T,te]=(0,Q.useState)(!1),[E,O]=(0,Q.useState)(null),[k,ie]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(!1),[ae,M]=(0,Q.useState)(null),oe=(0,Q.useRef)(void 0),N=(0,Q.useRef)([]);function P(e){oe.current&&clearTimeout(oe.current),M(e),oe.current=setTimeout(()=>M(null),4e3)}function F(e){I(),e&&P(e)}async function I(){let e=o.length>0;e?h(!0):p(!0);let[t,n,r]=await Promise.allSettled([ce(),W(),R()]);if(t.status===`fulfilled`){let n=t.value;if(e&&N.current.length>0){let e=new Set,t=new Map(N.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&&(_(e),setTimeout(()=>_(new Set),1500))}N.current=n,s(n)}n.status===`fulfilled`&&l(n.value),r.status===`fulfilled`&&d(r.value?.id??null),p(!1),h(!1)}if((0,Q.useEffect)(()=>{t&&I()},[t]),(0,Q.useEffect)(()=>{!t||!a||I()},[a]),!t)return null;let L=new Map(c.map(e=>[e.id,e])),se=e.queryCostUsd!=null||e.totalCostUsd!=null,B=o.length>0,le=o.length||1,V=Math.ceil(Math.sqrt(le)),H=Math.ceil(le/V);async function G(e,t){await z(e,{status:t===`disabled`?`active`:`disabled`}),I(),r?.()}async function K(){if(E){try{await U(E.id),P(`Account "${E.display}" removed.`),I(),r?.()}catch(e){P(`Failed to remove: ${e.message}`)}O(null)}}function q(){ie(null),C(!0)}return(0,$.jsxs)(`div`,{className:`relative border-b border-border bg-surface px-3 py-2.5 ${A?`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`}),a&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:Qi(new Date(a).getTime())})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{onClick:()=>te(!0),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:`Rotation & retry settings`,children:(0,$.jsx)(pt,{className:`size-3`})}),B&&(0,$.jsx)(`button`,{onClick:()=>j(e=>!e),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:A?`Exit fullscreen`:`Fullscreen view`,children:A?(0,$.jsx)(be,{className:`size-3`}):(0,$.jsx)(Le,{className:`size-3`})}),r&&(0,$.jsx)(`button`,{onClick:()=>{r(),I()},disabled:i||m,className:`text-xs text-text-subtle hover:text-text-primary px-1 disabled:opacity-50 cursor-pointer`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${i||m?`animate-spin`:``}`})}),(0,$.jsx)(`button`,{onClick:()=>{j(!1),n()},className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,children:(0,$.jsx)(D,{className:`size-3`})})]})]}),ae&&(0,$.jsx)(`div`,{className:`text-[11px] p-1.5 rounded bg-success/10 text-success text-center animate-in fade-in duration-200`,children:ae}),B||f?(0,$.jsx)(`div`,{className:A?`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:A?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${H}, minmax(0, 1fr))`}:void 0,children:f?(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Loading...`}):o.map(t=>(0,$.jsx)($i,{entry:t,isActive:t.accountId===(u??e.activeAccountId),accountInfo:L.get(t.accountId),onToggle:G,onDelete:(e,t)=>O({id:e,display:t}),onExport:e=>{ie(e),C(!0)},onViewProfile:(e,t)=>y({profile:e,accountId:t}),flash:g.has(t.accountId),fullscreen:A},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)(Yi,{label:`5-Hour Session`,bucket:e.session}),(0,$.jsx)(Yi,{label:`Weekly`,bucket:e.weekly}),(0,$.jsx)(Yi,{label:`Weekly (Opus)`,bucket:e.weeklyOpus}),(0,$.jsx)(Yi,{label:`Weekly (Sonnet)`,bucket:e.weeklySonnet})]}):(0,$.jsx)(`p`,{className:`text-xs text-text-subtle`,children:`No usage data available`})}),se&&(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)]})]})]}),v&&(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:()=>y(null),children:(0,$.jsx)(D,{className:`size-3`})})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[70px_1fr] gap-x-2 gap-y-0.5 text-[10px]`,children:[v.profile.account?.display_name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Name`}),(0,$.jsx)(`span`,{children:v.profile.account.display_name})]}),v.profile.account?.email&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Email`}),(0,$.jsx)(`span`,{children:v.profile.account.email})]}),v.profile.organization?.name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Org`}),(0,$.jsx)(`span`,{children:v.profile.organization.name})]}),v.profile.organization?.organization_type&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Type`}),(0,$.jsx)(`span`,{children:v.profile.organization.organization_type})]}),v.profile.organization?.rate_limit_tier&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Tier`}),(0,$.jsx)(`span`,{children:v.profile.organization.rate_limit_tier})]}),v.profile.organization?.subscription_status&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Status`}),(0,$.jsx)(`span`,{children:v.profile.organization.subscription_status})]})]}),(0,$.jsx)(Gi,{accountId:v.accountId})]}),(0,$.jsxs)(`div`,{className:`border-t border-border pt-2 flex gap-1.5 shrink-0`,children:[(0,$.jsxs)(`button`,{onClick:()=>x(!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)(re,{className:`size-3`}),` Add`]}),(0,$.jsxs)(`button`,{onClick:q,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)(ne,{className:`size-3`}),` Export`]}),(0,$.jsxs)(`button`,{onClick:()=>ee(!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)(Ze,{className:`size-3`}),` Import`]})]}),E&&(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:E.display}),`?`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`button`,{onClick:()=>O(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:K,className:`flex-1 px-3 py-1.5 rounded-md text-xs bg-error text-white hover:bg-error/80 cursor-pointer transition-colors`,children:`Remove`})]})]})}),(0,$.jsx)(ki,{open:b,onOpenChange:x,onSuccess:F}),(0,$.jsx)(Ai,{open:S,onOpenChange:e=>{C(e),e||ie(null)},accounts:c,preselectId:k,onMessage:P}),(0,$.jsx)(ji,{open:w,onOpenChange:ee,onSuccess:F}),(0,$.jsx)(Li,{open:T,onOpenChange:te})]})}function ta(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function na(e){return e>=90?`bg-error`:e>=70?`bg-warning`:`bg-success`}function ra({label:e,frac:t}){let n=t==null?null:Math.round(t*100);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}),(0,$.jsx)(`span`,{className:`text-xs font-medium tabular-nums ${n==null?`text-text-subtle`:ta(n)}`,children:n==null?`—`:`${n}%`})]}),(0,$.jsx)(`div`,{className:`h-2 rounded-full bg-border overflow-hidden`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full transition-all ${n==null?``:na(n)}`,style:{width:`${Math.min(n??0,100)}%`}})})]})}function ia({onClose:e,usage:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)({}),[o,s]=(0,Q.useState)(!1),c=(0,Q.useCallback)(async()=>{s(!0);try{r((await k.get(`/api/codex-accounts`)).accounts),a(await k.get(`/api/codex-accounts/usage`))}catch{}finally{s(!1)}},[]);return(0,Q.useEffect)(()=>{c()},[c]),(0,$.jsxs)(`div`,{className:`border-t border-border bg-surface px-3 py-2.5 space-y-2.5 max-h-[350px] overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`text-xs font-semibold text-text-primary`,children:`Codex Usage`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{onClick:c,disabled:o,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${o?`animate-spin`:``}`})}),(0,$.jsx)(`button`,{onClick:e,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:`Close`,children:(0,$.jsx)(D,{className:`size-3`})})]})]}),o&&n.length===0&&(0,$.jsxs)(`div`,{className:`text-xs text-text-subtle flex items-center gap-2`,children:[(0,$.jsx)(q,{className:`size-3 animate-spin`}),` Loading…`]}),!o&&n.length===0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-border/50 bg-surface/40 p-2.5 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm text-text-primary truncate flex-1 min-w-0`,children:t.activeAccountLabel||`Default login`}),(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-text-subtle border border-border rounded px-1`,children:`~/.codex`})]}),(0,$.jsx)(ra,{label:`5-Hour`,frac:t.fiveHour}),(0,$.jsx)(ra,{label:`Weekly`,frac:t.sevenDay})]}),(0,$.jsxs)(`p`,{className:`text-[11px] text-text-subtle`,children:[`Using your default `,(0,$.jsx)(`code`,{children:`~/.codex`}),` login. Add managed accounts in Settings → AI Provider → Codex.`]})]}),n.map(e=>{let t=i[e.id]??{};return(0,$.jsxs)(`div`,{className:`rounded-md border border-border/50 bg-surface/40 p-2.5 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm text-text-primary truncate flex-1 min-w-0`,children:e.label}),(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-text-subtle border border-border rounded px-1`,children:e.type}),e.planType&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:e.planType})]}),(0,$.jsx)(ra,{label:`5-Hour`,frac:t.fiveHour}),(0,$.jsx)(ra,{label:`Weekly`,frac:t.sevenDay})]},e.id)})]})}var aa={active:`bg-success`,idle:`bg-warning`,shutdown:`bg-text-3`},oa={task_assignment:{label:`task`,className:`bg-primary/20 text-primary`},idle_notification:{label:`idle`,className:`bg-warning/20 text-warning`},completion:{label:`done`,className:`bg-success/20 text-success`},shutdown_request:{label:`shutdown`,className:`bg-error/20 text-error`},shutdown_approved:{label:`shutdown ✓`,className:`bg-text-3/20 text-text-3`}};function sa({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 k.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)(Pe,{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`,aa[e.status]??`bg-text-3`)}),(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?oa[e.parsedType]:null,r=ca(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:la(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??ua(e.text)]})]},`${e.timestamp}-${t}`)}),(0,$.jsx)(`div`,{ref:c})]})})]})}function ca(e){try{return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}catch{return``}}function la(e){if(e&&(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^[a-zA-Z]{3,20}$/.test(e)))return{color:e}}function ua(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 da(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function fa({projectName:e,usageInfo:t,usageLoading:n,refreshUsage:r,lastFetchedAt:o,sessionId:c,providerId:l,onSelectSession:u,onBugReport:d,isConnected:f,onReload:p,teamActivity:m,teamMessages:h,onTeamOpen:g}){let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)([]),[x,S]=(0,Q.useState)(!1),C=Y(e=>e.notifications),w=Y(e=>c?e.notifications.has(c):!1),T=Y(e=>e.clearForSession),te=Y(e=>e.markUnread),[ne,re]=(0,Q.useState)(``),E=ct(ne,300),[ie,A]=(0,Q.useState)(null),[j,ae]=(0,Q.useState)(``),[oe,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[L,se]=(0,Q.useState)([]),[R,z]=(0,Q.useState)(null),[B,ce]=(0,Q.useState)({}),[le,V]=(0,Q.useState)(!1),H=(0,Q.useRef)(null),U=I(e=>e.openTab),W=e=>{v(t=>t===e?null:e)},G=(0,Q.useCallback)(async t=>{if(e){S(!0);try{let n=new URLSearchParams({limit:`50`,offset:`0`});t&&n.set(`q`,t);let r=await k.get(`${O(e)}/chat/sessions?${n}`);b(r.sessions),N(r.hasMore)}catch{}finally{S(!1)}}},[e]),K=(0,Q.useCallback)(async()=>{if(!(!e||P||!oe)){F(!0);try{let t=y.filter(e=>!e.pinned).length,n=new URLSearchParams({limit:`50`,offset:String(t)});E&&n.set(`q`,E);let r=await k.get(`${O(e)}/chat/sessions?${n}`);b(e=>{let t=new Set(e.map(e=>e.id)),n=r.sessions.filter(e=>!t.has(e.id));return[...e,...n]}),N(r.hasMore)}catch{}finally{F(!1)}}},[e,P,oe,y,E]);(0,Q.useEffect)(()=>{_===`history`&&y.length===0&&G()},[_]),(0,Q.useEffect)(()=>{_===`history`&&G(E||void 0)},[E]);let J=(0,Q.useCallback)(async()=>{if(e)try{let t=await k.get(`${O(e)}/tags`);se(t.tags),ce(t.counts)}catch{}},[e]);(0,Q.useEffect)(()=>{_===`history`&&e&&J()},[_,e,J]);function fe(t){u?(u(t),v(null)):U({type:`chat`,title:t.title||`Chat`,projectId:e??null,metadata:{projectName:e,sessionId:t.id,providerId:t.providerId},closable:!0})}let pe=(0,Q.useCallback)((e,t)=>{t.stopPropagation(),A(e.id),ae(e.title||``),setTimeout(()=>H.current?.select(),0)},[]),X=(0,Q.useCallback)(async()=>{if(!ie||!j.trim()||!e){A(null);return}try{await k.patch(`${O(e)}/chat/sessions/${ie}`,{title:j.trim()}),b(e=>e.map(e=>e.id===ie?{...e,title:j.trim()}:e))}catch{}A(null)},[ie,j,e]),ge=(0,Q.useCallback)(()=>A(null),[]),_e=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),!e)return;let r=`${O(e)}/chat/sessions/${n.id}/pin`;try{n.pinned?await k.del(r):await k.put(r),b(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]),ve=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),e&&window.confirm(`Delete this session? This cannot be undone.`))try{await k.del(`${O(e)}/chat/sessions/${n.id}?providerId=${n.providerId}`),b(e=>e.filter(e=>e.id!==n.id))}catch{}},[e]),ye=(0,Q.useCallback)((e,t)=>{b(n=>n.map(n=>n.id===e?{...n,tag:t}:n)),J()},[J]),be=(0,Q.useCallback)(async()=>{if(!e)return;let t=window.prompt(`Delete sessions older than how many days? (pinned sessions are kept)`,`30`);if(!t)return;let n=parseInt(t,10);if(!(!n||n<1)&&window.confirm(`Delete all unpinned sessions older than ${n} days? This cannot be undone.`)){S(!0);try{await k.del(`${O(e)}/chat/sessions?olderThanDays=${n}`),G(E||void 0)}catch{}}},[e,G,E]);(0,Q.useEffect)(()=>{if(_!==`history`)return;let t=t=>{if(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement)return;let n=parseInt(t.key);if(n>=1&&n<=L.length&&c){let t=L[n-1];t&&(k.patch(`${O(e)}/chat/sessions/${c}/tag`,{tagId:t.id}).catch(()=>{}),ye(c,{id:t.id,name:t.name,color:t.color}))}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[_,L,c,e,ye]);let Se=R===null?y:y.filter(e=>e.tag?.id===R),Ce=!l||l===`claude`,Oe=l===`codex`,ke=t.fiveHour==null?null:Math.round(t.fiveHour*100),Ae=t.sevenDay==null?null:Math.round(t.sevenDay*100),Z=ke!=null||Ae!=null?da(Math.max(ke??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:()=>W(`history`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`history`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,children:[(0,$.jsx)(Qe,{className:`size-3`}),(0,$.jsx)(`span`,{children:`History`})]}),c&&l&&l!==`mock`?(0,$.jsxs)(`button`,{onClick:()=>W(`config`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`config`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`AI Settings`,children:[(0,$.jsx)(De,{providerId:l}),(0,$.jsx)(`span`,{className:`capitalize`,children:l})]}):(0,$.jsx)(`button`,{onClick:()=>W(`config`),className:`p-1 rounded transition-colors ${_===`config`?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary hover:bg-surface-elevated`}`,title:`AI Settings`,children:(0,$.jsx)(ue,{className:`size-3`})}),Ce||Oe?(0,$.jsxs)(`button`,{onClick:()=>W(`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 ${_===`usage`?`bg-primary/10`:``} ${Z}`,title:`Usage limits`,children:[(0,$.jsx)(vt,{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:`,ke==null?`--%`:`${ke}%`]}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Wk:`,Ae==null?`--%`:`${Ae}%`]})]}):null,m?.hasTeams&&(0,$.jsxs)(`button`,{onClick:()=>{W(`team`),g?.()},className:`relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`team`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`Team activity`,children:[(0,$.jsx)(Ee,{className:`size-3`}),(0,$.jsx)(`span`,{children:`Team`}),(m.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`}),w&&c&&(0,$.jsx)(`button`,{onClick:()=>T(c),className:`p-1 rounded text-warning hover:text-warning/80 hover:bg-surface-elevated transition-colors`,title:`Mark as read`,children:(0,$.jsx)(de,{className:`size-3`})}),!w&&c&&(0,$.jsx)(`button`,{onClick:()=>te(c,e),className:`p-1 rounded text-primary hover:text-primary/80 hover:bg-surface-elevated transition-colors`,title:`Mark as unread`,children:(0,$.jsx)(Je,{className:`size-3 fill-current`})}),c&&(0,$.jsx)(Di,{sessionId:c,projectName:e}),p&&(0,$.jsxs)(`button`,{onClick:e=>{let t=e.currentTarget.querySelector(`svg`);t&&(t.classList.add(`animate-spin`),setTimeout(()=>t.classList.remove(`animate-spin`),600)),p()},className:`relative size-4 flex items-center justify-center`,title:f?`Reload messages`:`Disconnected — click to reload`,children:[(0,$.jsx)(Pe,{className:`size-3 ${f?`text-muted-foreground/60`:`text-error`}`,strokeWidth:2.5}),(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 size-1.5 rounded-full ${f?`bg-success`:`bg-error animate-pulse`}`})]})]}),_===`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)(ee,{className:`size-3 text-text-subtle shrink-0`}),(0,$.jsx)(`input`,{type:`text`,value:ne,onChange:e=>re(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:be,className:`p-0.5 rounded text-text-subtle hover:text-error transition-colors`,title:`Delete old sessions...`,children:(0,$.jsx)(lt,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:()=>G(E||void 0),disabled:x,className:`p-0.5 rounded text-text-subtle hover:text-text-secondary transition-colors disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${x?`animate-spin`:``}`})})]}),L.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1 overflow-x-auto border-b border-border/30 scrollbar-none`,children:[(0,$.jsxs)(`button`,{onClick:()=>z(null),className:`shrink-0 rounded-md border px-2 py-1 text-[10px] transition-colors ${R===null?`bg-primary/20 border-primary text-primary`:`border-border bg-surface text-text-secondary`}`,children:[`All (`,y.length,`)`]}),L.map(e=>(0,$.jsxs)(`button`,{onClick:()=>z(R===e.id?null:e.id),className:`shrink-0 flex items-center gap-1 rounded-md border px-2 py-1 text-[10px] transition-colors ${R===e.id?`border-current`:`border-border bg-surface`}`,style:R===e.id?{backgroundColor:e.color+`20`,color:e.color,borderColor:e.color}:void 0,children:[(0,$.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:e.color}}),e.name,` (`,B[e.id]??0,`)`]},e.id)),(0,$.jsx)(`button`,{onClick:()=>V(!le),className:`shrink-0 p-1 rounded transition-colors ${le?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary`}`,title:`Manage tags`,children:(0,$.jsx)(me,{className:`size-3`})})]}),le&&(0,$.jsx)(`div`,{className:`border-b border-border/30 px-2 py-2 max-h-[180px] overflow-y-auto bg-surface-elevated/50`,children:(0,$.jsx)(ot,{projectName:e,onTagsChanged:J})}),(0,$.jsx)(`div`,{className:`max-h-[200px] overflow-y-auto`,children:x&&y.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(q,{className:`size-3.5 animate-spin text-text-subtle`})}):Se.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3 text-[11px] text-text-subtle`,children:ne?`No matching sessions`:`No sessions yet`}):(0,$.jsxs)($.Fragment,{children:[Se.map(t=>{let n=C.get(t.id),r=!!n;return(0,$.jsx)(ze,{session:t,projectName:e,projectTags:L,onTogglePin:_e,onStartEditing:pe,onDeleteSession:ve,onTagChanged:ye,children:(0,$.jsxs)(`div`,{className:M(`flex items-center gap-2 w-full px-3 py-1.5 text-left hover:bg-surface-elevated transition-colors group`,r&&`font-medium text-foreground`,r&&dt(n.type),!r&&`text-text-secondary`),children:[(0,$.jsx)(De,{providerId:t.providerId}),t.tag&&(0,$.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:t.tag.color},title:t.tag.name}),ie===t.id?(0,$.jsxs)(`form`,{className:`flex items-center gap-1 flex-1 min-w-0`,onSubmit:e=>{e.preventDefault(),X()},children:[(0,$.jsx)(`input`,{ref:H,value:j,onChange:e=>ae(e.target.value),onBlur:X,onKeyDown:e=>{e.key===`Escape`&&ge()},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-success hover:text-success/80`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(a,{className:`size-3`})}),(0,$.jsx)(`button`,{type:`button`,className:`p-0.5 text-text-subtle hover:text-text-secondary`,onClick:e=>{e.stopPropagation(),ge()},children:(0,$.jsx)(D,{className:`size-3`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{onClick:()=>fe(t),className:`text-[11px] truncate flex-1 text-left flex items-center gap-1`,children:[t.title?.startsWith(`[PPM]`)&&(0,$.jsx)(i,{className:`size-3 text-muted-foreground shrink-0`}),t.title?.startsWith(`[PPM]`)?t.title.slice(7):t.title||`Untitled`]}),(0,$.jsx)(`button`,{onClick:e=>_e(e,t),className:`p-0.5 rounded transition-all ${t.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:t.pinned?`Unpin session`:`Pin session`,children:t.pinned?(0,$.jsx)(xe,{className:`size-3`}):(0,$.jsx)(he,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>pe(t,e),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)(s,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>ve(e,t),className:`p-0.5 rounded text-text-subtle hover:text-error hover:bg-error/20 can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity`,title:`Delete session`,children:(0,$.jsx)(we,{className:`size-3`})})]}),ie!==t.id&&t.updatedAt&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0 w-16 text-right`,children:Me(t.updatedAt)})]})},t.id)}),oe&&(0,$.jsxs)(`button`,{onClick:K,disabled:P,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:[P?(0,$.jsx)(q,{className:`size-3 animate-spin`}):null,P?`Loading...`:`Load more`]})]})})]}),_===`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)(Te,{compact:!0})}),_===`team`&&m?.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)(sa,{teamNames:m.teamNames,messages:h??[]})}),_===`usage`&&Ce&&(0,$.jsx)(ea,{usage:t,visible:!0,onClose:()=>v(null),onReload:r,loading:n,lastFetchedAt:o}),_===`usage`&&Oe&&(0,$.jsx)(ia,{usage:t,onClose:()=>v(null)})]})}var pa=3e3;function ma(e,t){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),o=(0,Q.useRef)(void 0),s=(0,Q.useRef)(t);s.current=t;let c=t??`__new__`;(0,Q.useEffect)(()=>{if(!e){a(!1);return}let t=!1;a(!0);let n=setTimeout(()=>{t||a(!1)},pa);return k.get(`${O(e)}/chat/drafts/${encodeURIComponent(c)}`).then(e=>{if(!t)if(e){let t=[];try{t=JSON.parse(e.attachments)}catch{}r({content:e.content,attachments:t})}else r(null)}).catch(()=>{t||r(null)}).finally(()=>{clearTimeout(n),t||a(!1)}),()=>{t=!0,clearTimeout(n)}},[e,c]);let l=(0,Q.useCallback)((t,n)=>{e&&(o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{let r=s.current??`__new__`;k.put(`${O(e)}/chat/drafts/${encodeURIComponent(r)}`,{content:t,attachments:JSON.stringify(n??[])}).catch(()=>{})},1e3))},[e]),u=(0,Q.useCallback)(()=>{if(!e)return;o.current&&clearTimeout(o.current);let t=s.current??`__new__`;k.del(`${O(e)}/chat/drafts/${encodeURIComponent(t)}`).catch(()=>{}),r(null)},[e]);return(0,Q.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]),{draft:n,draftLoading:i,saveDraft:l,clearDraft:u}}function ha({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)(``),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)([]),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null),[w,ee]=(0,Q.useState)(e?.permissionMode??void 0),T=(0,Q.useRef)(null),[te,ne]=(0,Q.useState)(!1),[re,E]=(0,Q.useState)(null),[ie,M]=(0,Q.useState)(null),[oe,N]=(0,Q.useState)(null),F=(0,Q.useRef)(0),L=e?.projectName??``,R=I(e=>e.updateTab),z=ae(e=>e.version),{usageInfo:B,usageLoading:ce,lastFetchedAt:le,refreshUsage:V}=Ut(L,i),{draft:H,draftLoading:U,saveDraft:W,clearDraft:G}=ma(L,n);(0,Q.useEffect)(()=>{w||se().then(e=>{let t=e.providers[e.default_provider??`claude`];ee(t?.permission_mode??`bypassPermissions`)}).catch(()=>{})},[]),(0,Q.useEffect)(()=>{!t||!n||R(t,{metadata:{...e,sessionId:n,providerId:i,permissionMode:w}})},[n,i,w]);let{messages:K,renderedMessages:J,expandCompact:ue,isCompactExpanded:de,dismissMessage:fe,clearErrors:pe,messagesLoading:me,versionMap:he,isStreaming:X,phase:ge,isReconnecting:_e,connectingElapsed:ve,pendingApproval:ye,contextWindowPct:be,compactStatus:xe,statusMessage:Se,sessionTitle:Ce,model:we,setModel:Te,effort:Ee,setEffort:De,thinking:Oe,setThinking:ke,sendMessage:Ae,respondToApproval:Z,cancelStreaming:je,reconnect:Me,refetchMessages:Ne,isConnected:Pe,teamActivity:Fe,teamMessages:Ie,markTeamRead:Le,bashPartialOutput:Re,backgroundShells:ze,killBackgroundShell:Be}=Vt(n,i,L);(0,Q.useEffect)(()=>{if(Pe&&T.current){let{content:e,permissionMode:t}=T.current;T.current=null,Ae(e,{permissionMode:t})}},[Pe,Ae]),(0,Q.useEffect)(()=>{if(!n||!t)return;let e=()=>{if(document.hidden)return;let{panels:e}=P.getState();Object.values(e).some(e=>e.activeTabId===t)&&(Y.getState().notifications.get(n)?.manual||Y.getState().clearForSession(n))};e(),document.addEventListener(`visibilitychange`,e);let r=P.subscribe(e),i=Y.subscribe(e);return()=>{document.removeEventListener(`visibilitychange`,e),r(),i()}},[n,t]),(0,Q.useEffect)(()=>{t&&Ce&&R(t,{title:Ce})},[Ce]);let[Ve,He]=(0,Q.useState)(e?.pendingMessage),[Ue,Ge]=(0,Q.useState)(null),[Ke,qe]=(0,Q.useState)(!1),[Je,Ye]=(0,Q.useState)(0),[Xe,Qe]=(0,Q.useState)(!1),$e=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{$e.current&&!me&&Qe(!1),$e.current=!!me},[me]);let[et,tt]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{U||tt(!0)},[U]),(0,Q.useEffect)(()=>{Ve&&Pe&&n&&t&&R(t,{metadata:{...e,pendingMessage:void 0}})},[Pe,n]),(0,Q.useEffect)(()=>{Ke&&X&&qe(!1)},[Ke,X]),(0,Q.useEffect)(()=>{if(!Ke)return;let e=setTimeout(()=>qe(!1),6e4);return()=>clearTimeout(e)},[Ke]);let nt=(0,Q.useCallback)((e,t)=>{I.getState().openTab({type:`chat`,title:e||`AI Chat`,metadata:{projectName:L,providerId:i,...t&&{clearedFrom:t}},projectId:L||null,closable:!0})},[L,i]),rt=(0,Q.useCallback)(e=>{qe(!1),r(e.id),a(e.providerId),t&&R(t,{title:e.title||`Chat`}),Y.getState().clearForSession(e.id)},[t,R]),it=(0,Q.useCallback)(async(e,t)=>{if(!(!n||!L))try{let{api:r,projectUrl:a}=await j(async()=>{let{api:e,projectUrl:t}=await import(`./api-client-BwMdPtp6.js`);return{api:e,projectUrl:t}},__vite__mapDeps([32,6,1,2,21])),o=await r.post(`${a(L)}/chat/sessions/${n}/fork?providerId=${i}`,{messageId:t});I.getState().openTab({type:`chat`,title:`Fork: ${e.slice(0,30)}`,metadata:{projectName:L,sessionId:o.id,providerId:i,pendingMessage:e},projectId:L||null,closable:!0})}catch(e){console.error(`Fork failed:`,e);let t=e?.message||`Unknown error`;A.error(`Cannot fork from this message`,{description:t.includes(`not found`)||t.includes(`Invalid upToMessageId`)?`The original message is no longer available in the session transcript. Try forking from a different message.`:t})}},[n,L,i]),at=(0,Q.useCallback)((e,t,n)=>{He(e),Ge({anchorMsgId:t,ownMsgId:n})},[]),ot=(0,Q.useCallback)(()=>{Ge(null),He(void 0),qe(!1),G(),Ye(e=>e+1)},[G]),st=(0,Q.useCallback)(async(a,o)=>{if(!(!a.trim()||!n||!L)){qe(!0);try{let s=await k.post(`${O(L)}/chat/sessions/${n}/fork?providerId=${i}&mode=edit`,{messageId:o});T.current={content:a,permissionMode:w},Qe(!0),t&&R(t,{metadata:{...e,sessionId:s.id}}),r(s.id)}catch(e){qe(!1);let t=e?.message||`Unknown error`;A.error(`Cannot edit from this message`,{description:t.includes(`not found`)||t.includes(`Invalid upToMessageId`)?`The original message is no longer available in the session transcript.`:t})}}},[n,L,i,w,t,R,e]),ct=(0,Q.useCallback)(i=>{!i||i===n||(qe(!1),Qe(!0),t&&R(t,{metadata:{...e,sessionId:i}}),r(i))},[n,t,R,e]),lt=(0,Q.useCallback)((e,t)=>{if(t.length===0)return e;let n=[];for(let e of t)e.textContent&&n.push(e.textContent);let r=t.filter(e=>e.serverPath);if(r.length>0){let e=r.map(e=>e.serverPath).join(`
8
+ `))}).catch(()=>a(`Failed to load debug info`))},d=(0,$.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,$.jsxs)(`h2`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[(0,$.jsx)(je,{className:`size-4 text-primary`}),`Session debug info`]}),(0,$.jsx)(`pre`,{className:`max-h-[35vh] overflow-y-auto whitespace-pre-wrap break-all rounded-md border border-border bg-surface p-2.5 font-mono text-[11px] leading-relaxed text-text-secondary select-text`,children:i??`Loading...`}),(0,$.jsx)(_,{size:`sm`,onClick:()=>{i&&nt(i).then(e=>{e&&(s(!0),setTimeout(()=>s(!1),1500))})},disabled:!i,className:`w-full`,children:o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(bt,{className:`size-3.5`}),` Copied!`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ge,{className:`size-3.5`}),` Copy`]})}),(0,$.jsx)(`div`,{className:`border-t border-border pt-3`,children:n&&(0,$.jsx)(Ei,{sessionId:e,projectName:t})})]});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{onClick:u,className:`p-1 rounded text-text-subtle hover:text-text-secondary hover:bg-surface-elevated transition-colors`,title:`Session debug info`,children:(0,$.jsx)(je,{className:`size-3`})}),l?(0,$.jsx)(ye,{open:n,onClose:()=>r(!1),className:`popover-solid`,children:(0,$.jsx)(`div`,{className:`max-h-[85vh] overflow-y-auto px-4 pb-4 pt-1`,children:d})}):(0,$.jsx)(S,{open:n,onOpenChange:r,children:(0,$.jsxs)(y,{className:`sm:max-w-lg`,children:[(0,$.jsx)(b,{className:`sr-only`,children:`Session debug info`}),d]})})]})}var Oi=`ppm-hienlh`;function ki({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,C]=(0,Q.useState)(!1),[w,ee]=(0,Q.useState)(`idle`);function T(){f(null),m(``),ee(`idle`),u(null)}function te(){t(!1),T(),i(``),o(``),u(null)}async function ne(){C(!0),u(null);try{let{url:e,state:t}=await K();f(t),ee(`waiting`),window.open(e,`_blank`)}catch(e){u(e.message)}C(!1)}async function re(){if(!(!p.trim()||!d)){C(!0),u(null);try{let e=p.trim();e.includes(`#`)&&(e=e.split(`#`)[0]??e),await B(e,d),te(),n(`Account connected via OAuth!`)}catch(e){u(e.message)}C(!1)}}async function E(){if(r.trim()){c(!0),u(null);try{await G({apiKey:r.trim(),label:a.trim()||void 0}),te(),n(`Account added!`)}catch(e){u(e.message)}c(!1)}}let D=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)(S,{open:e,onOpenChange:e=>{e||te()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsx)(b,{className:`text-sm`,children:`Add Claude Account`}),(0,$.jsx)(x,{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`}),w===`idle`?(0,$.jsx)(_,{size:`sm`,className:`w-full h-8 text-xs`,onClick:ne,disabled:h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{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)(Ne,{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)(_,{size:`sm`,className:`flex-1 h-7 text-xs`,onClick:re,disabled:!p.trim()||h,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Connecting...`]}):`Connect`}),(0,$.jsx)(_,{size:`sm`,variant:`ghost`,className:`h-7 text-xs`,onClick:T,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)(X,{htmlFor:`add-token`,className:`text-xs`,children:`Token`}),(0,$.jsx)(Ne,{id:`add-token`,type:`password`,placeholder:`sk-ant-...`,value:r,onChange:e=>i(e.target.value),className:`text-xs h-8 font-mono`}),D&&(0,$.jsxs)(`p`,{className:`text-[10px] text-muted-foreground`,children:[`Detected: `,D]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(X,{htmlFor:`add-label`,className:`text-xs`,children:`Label (optional)`}),(0,$.jsx)(Ne,{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-error/10 text-error`,children:l}),(0,$.jsxs)(v,{children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7`,onClick:te,children:`Cancel`}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7`,onClick:E,disabled:!r.trim()||s,children:s?`Adding...`:`Add Token`})]})]})})}function Ai({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),[C,w]=(0,Q.useState)(!1);e&&!C&&(s(r?new Set([r]):new Set(a.map(e=>e.id))),w(!0)),!e&&C&&w(!1);function ee(){t(!1),l(``),d(!1),p(!1)}async function T(e){if(o.size===0)return;h(!0);let t=c.trim()||Oi;try{let n={"Content-Type":`application/json`},r=ie();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();e&&await nt(s)?i?.(`Backup copied to clipboard!`):(Mi(s),i?.(`Backup downloaded.`)),ee()}catch{}h(!1)}let te=o.size>0&&!m;return(0,$.jsx)(S,{open:e,onOpenChange:e=>{e||ee()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsxs)(b,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(ke,{className:`size-3.5`}),` Export Accounts`]}),(0,$.jsx)(x,{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)(X,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Ne,{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-error/30 bg-error/5 p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-error`,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-warning/30 bg-warning/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-warning`,children:`Refresh before export — invalidates previous shares`})}):(0,$.jsx)(`div`,{className:`rounded-md border border-success/30 bg-success/5 p-2.5`,children:(0,$.jsx)(`p`,{className:`text-[10px] font-medium text-success`,children:`Share current token (safe)`})}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Encrypted with AES-256-GCM + scrypt.`})]}),(0,$.jsxs)(v,{className:`gap-1.5 flex-col sm:flex-row`,children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:ee,children:`Cancel`}),(0,$.jsxs)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,disabled:!te,onClick:()=>T(!0),children:[(0,$.jsx)(Ge,{className:`size-3 mr-1`}),` Copy`]}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!te,onClick:()=>T(!1),children:m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Exporting...`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ne,{className:`size-3 mr-1`}),` Download`]})})]})]})})}function ji({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 le({data:r.trim(),password:a.trim()||Oi});d(),n(`Imported ${e.imported} account(s)`)}catch(e){u(e.message||`Import failed`)}c(!1)}}return(0,$.jsx)(S,{open:e,onOpenChange:e=>{e||d()},children:(0,$.jsxs)(y,{className:`sm:max-w-md`,children:[(0,$.jsxs)(g,{children:[(0,$.jsxs)(b,{className:`text-sm flex items-center gap-1.5`,children:[(0,$.jsx)(ke,{className:`size-3.5`}),` Import Accounts`]}),(0,$.jsx)(x,{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)(X,{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)(X,{className:`text-xs`,children:[`Password `,(0,$.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,$.jsx)(Ne,{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-error/10 text-error`,children:l}),(0,$.jsxs)(v,{children:[(0,$.jsx)(_,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:d,children:`Cancel`}),(0,$.jsx)(_,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!r.trim()||s,onClick:f,children:s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{className:`size-3 animate-spin mr-1`}),` Importing...`]}):`Import`})]})]})})}function Mi(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 Ni=typeof window<`u`?window.matchMedia(`(min-width: 768px)`):null;function Pi(e){return Ni?.addEventListener(`change`,e),()=>Ni?.removeEventListener(`change`,e)}function Fi(){return Ni?.matches??!0}function Ii(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0);return(0,Q.useEffect)(()=>{r(!0),V().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)(_e,{value:e.strategy,onValueChange:async e=>{t(await L({strategy:e}))},children:[(0,$.jsx)(ft,{className:`w-full h-9 text-xs`,children:(0,$.jsx)(J,{})}),(0,$.jsxs)(Se,{children:[(0,$.jsx)(Ae,{value:`round-robin`,children:`Round-robin`}),(0,$.jsx)(Ae,{value:`fill-first`,children:`Fill-first`}),(0,$.jsx)(Ae,{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 L({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:`space-y-1.5 border-t border-border pt-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Cooldown parking`}),(0,$.jsx)(Fe,{checked:e.cooldownEnabled,onCheckedChange:async e=>{t(await L({cooldownEnabled:e}))}})]}),(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Park a failing account (rate limit / usage limit / auth error) until it recovers. Off: accounts stay selectable — rotation still skips accounts already ≥95% on the 5-hour limit.`})]}),(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 Li({open:e,onOpenChange:t}){let n=(0,Q.useSyncExternalStore)(Pi,Fi);return e?n?(0,$.jsx)(S,{open:e,onOpenChange:t,children:(0,$.jsxs)(y,{className:`sm:max-w-sm`,children:[(0,$.jsx)(g,{children:(0,$.jsxs)(b,{className:`text-sm flex items-center gap-2`,children:[(0,$.jsx)(pt,{className:`size-4`}),` Rotation & Retry`]})}),(0,$.jsx)(Ii,{})]})}):(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)(pt,{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)(D,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`px-4 py-4 pb-8`,children:(0,$.jsx)(Ii,{})})]})]}):null}var Ri=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],zi=Array.from({length:24},(e,t)=>t);function Bi(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 Vi(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 Hi(e){return zi.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 Ui(e){return e===0?`bg-surface-elevated`:e<.3?`bg-success/30`:e<.5?`bg-success/60`:e<.7?`bg-warning/50`:e<.9?`bg-warning/80`:`bg-error/80`}function Wi(e){return e<.3?`bg-success`:e<.7?`bg-warning`:`bg-error`}function Gi({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),H(e).then(n).catch(()=>n([])).finally(()=>i(!1))},[e]);let s=(0,Q.useMemo)(()=>t?Bi(t,a):null,[t,a]),c=(0,Q.useMemo)(()=>s?Vi(s):[],[s]),l=(0,Q.useMemo)(()=>s?Hi(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)(q,{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:Ri.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 ${Wi(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:zi.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] ${Ui(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:[Ri.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)}),zi.map(n=>{let r=s[t][n];return(0,$.jsx)(`div`,{className:`flex-1 aspect-square rounded-[1px] ${Ui(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`}),zi.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-success/30`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-success/60`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/50`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/80`}),(0,$.jsx)(`div`,{className:`size-2 rounded-[1px] bg-error/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 Ki(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function qi(e){return e>=90?`bg-error`:e>=70?`bg-warning`:`bg-success`}function Ji(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 Yi({label:e,bucket:t}){if(!t)return null;let n=Math.round(t.utilization*100),r=Ji(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 ${qi(n)}`,style:{width:`${Math.min(n,100)}%`}})}),(0,$.jsxs)(`span`,{className:`text-xs font-medium tabular-nums w-10 text-right ${Ki(n)}`,children:[n,`%`]})]})]})}function Xi(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 Zi(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-warning`}:t?{label:`expired`,tip:`Token expired, no refresh token`,color:`text-error`}:e.hasRefreshToken?{label:`long-lived`,tip:`OAuth token with refresh — long-lived`,color:`text-success`}:{label:`temp`,tip:`Temporary token without refresh — will expire`,color:`text-warning`}}function Qi(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 $i({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-error 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)(te,{className:`size-3`})}),!f&&a&&e.isOAuth&&(0,$.jsx)(`button`,{className:`p-1 rounded cursor-pointer text-text-subtle hover:text-primary hover:bg-surface-elevated transition-colors`,onClick:()=>a(e.accountId),title:`Export this account`,children:(0,$.jsx)(ne,{className:`size-3`})}),!f&&r&&(0,$.jsx)(Fe,{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-error hover:bg-surface-elevated transition-colors`,onClick:()=>i(e.accountId,e.accountLabel??e.accountId.slice(0,8)),title:`Remove account`,children:(0,$.jsx)(we,{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)(Yi,{label:`5-Hour Session`,bucket:l.session}),(0,$.jsx)(Yi,{label:`Weekly`,bucket:l.weekly}),(0,$.jsx)(Yi,{label:`Weekly (Opus)`,bucket:l.weeklyOpus}),(0,$.jsx)(Yi,{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=Zi(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:[`↻ `,Qi(new Date(l.lastFetchedAt).getTime())]}),n?.expiresAt&&n.expiresAt*1e3>Date.now()&&(0,$.jsxs)(`span`,{title:`Token expires in`,children:[`⏱ `,Xi(n.expiresAt*1e3)]}),(0,$.jsxs)(`span`,{className:e.color,title:e.tip,children:[`© `,e.label]})]})})()]})}function ea({usage:e,visible:t,onClose:n,onReload:r,loading:i,lastFetchedAt:a}){let[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!0),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(new Set),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,ee]=(0,Q.useState)(!1),[T,te]=(0,Q.useState)(!1),[E,O]=(0,Q.useState)(null),[k,ie]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(!1),[ae,M]=(0,Q.useState)(null),oe=(0,Q.useRef)(void 0),N=(0,Q.useRef)([]);function P(e){oe.current&&clearTimeout(oe.current),M(e),oe.current=setTimeout(()=>M(null),4e3)}function F(e){I(),e&&P(e)}async function I(){let e=o.length>0;e?h(!0):p(!0);let[t,n,r]=await Promise.allSettled([ce(),W(),R()]);if(t.status===`fulfilled`){let n=t.value;if(e&&N.current.length>0){let e=new Set,t=new Map(N.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&&(_(e),setTimeout(()=>_(new Set),1500))}N.current=n,s(n)}n.status===`fulfilled`&&l(n.value),r.status===`fulfilled`&&d(r.value?.id??null),p(!1),h(!1)}if((0,Q.useEffect)(()=>{t&&I()},[t]),(0,Q.useEffect)(()=>{!t||!a||I()},[a]),!t)return null;let L=new Map(c.map(e=>[e.id,e])),se=e.queryCostUsd!=null||e.totalCostUsd!=null,B=o.length>0,le=o.length||1,V=Math.ceil(Math.sqrt(le)),H=Math.ceil(le/V);async function G(e,t){await z(e,{status:t===`disabled`?`active`:`disabled`}),I(),r?.()}async function K(){if(E){try{await U(E.id),P(`Account "${E.display}" removed.`),I(),r?.()}catch(e){P(`Failed to remove: ${e.message}`)}O(null)}}function q(){ie(null),C(!0)}return(0,$.jsxs)(`div`,{className:`relative border-b border-border bg-surface px-3 py-2.5 ${A?`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`}),a&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:Qi(new Date(a).getTime())})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{onClick:()=>te(!0),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:`Rotation & retry settings`,children:(0,$.jsx)(pt,{className:`size-3`})}),B&&(0,$.jsx)(`button`,{onClick:()=>j(e=>!e),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:A?`Exit fullscreen`:`Fullscreen view`,children:A?(0,$.jsx)(be,{className:`size-3`}):(0,$.jsx)(Le,{className:`size-3`})}),r&&(0,$.jsx)(`button`,{onClick:()=>{r(),I()},disabled:i||m,className:`text-xs text-text-subtle hover:text-text-primary px-1 disabled:opacity-50 cursor-pointer`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${i||m?`animate-spin`:``}`})}),(0,$.jsx)(`button`,{onClick:()=>{j(!1),n()},className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,children:(0,$.jsx)(D,{className:`size-3`})})]})]}),ae&&(0,$.jsx)(`div`,{className:`text-[11px] p-1.5 rounded bg-success/10 text-success text-center animate-in fade-in duration-200`,children:ae}),B||f?(0,$.jsx)(`div`,{className:A?`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:A?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${H}, minmax(0, 1fr))`}:void 0,children:f?(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Loading...`}):o.map(t=>(0,$.jsx)($i,{entry:t,isActive:t.accountId===(u??e.activeAccountId),accountInfo:L.get(t.accountId),onToggle:G,onDelete:(e,t)=>O({id:e,display:t}),onExport:e=>{ie(e),C(!0)},onViewProfile:(e,t)=>y({profile:e,accountId:t}),flash:g.has(t.accountId),fullscreen:A},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)(Yi,{label:`5-Hour Session`,bucket:e.session}),(0,$.jsx)(Yi,{label:`Weekly`,bucket:e.weekly}),(0,$.jsx)(Yi,{label:`Weekly (Opus)`,bucket:e.weeklyOpus}),(0,$.jsx)(Yi,{label:`Weekly (Sonnet)`,bucket:e.weeklySonnet})]}):(0,$.jsx)(`p`,{className:`text-xs text-text-subtle`,children:`No usage data available`})}),se&&(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)]})]})]}),v&&(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:()=>y(null),children:(0,$.jsx)(D,{className:`size-3`})})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[70px_1fr] gap-x-2 gap-y-0.5 text-[10px]`,children:[v.profile.account?.display_name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Name`}),(0,$.jsx)(`span`,{children:v.profile.account.display_name})]}),v.profile.account?.email&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Email`}),(0,$.jsx)(`span`,{children:v.profile.account.email})]}),v.profile.organization?.name&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Org`}),(0,$.jsx)(`span`,{children:v.profile.organization.name})]}),v.profile.organization?.organization_type&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Type`}),(0,$.jsx)(`span`,{children:v.profile.organization.organization_type})]}),v.profile.organization?.rate_limit_tier&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Tier`}),(0,$.jsx)(`span`,{children:v.profile.organization.rate_limit_tier})]}),v.profile.organization?.subscription_status&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`Status`}),(0,$.jsx)(`span`,{children:v.profile.organization.subscription_status})]})]}),(0,$.jsx)(Gi,{accountId:v.accountId})]}),(0,$.jsxs)(`div`,{className:`border-t border-border pt-2 flex gap-1.5 shrink-0`,children:[(0,$.jsxs)(`button`,{onClick:()=>x(!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)(re,{className:`size-3`}),` Add`]}),(0,$.jsxs)(`button`,{onClick:q,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)(ne,{className:`size-3`}),` Export`]}),(0,$.jsxs)(`button`,{onClick:()=>ee(!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)(Ze,{className:`size-3`}),` Import`]})]}),E&&(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:E.display}),`?`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`button`,{onClick:()=>O(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:K,className:`flex-1 px-3 py-1.5 rounded-md text-xs bg-error text-white hover:bg-error/80 cursor-pointer transition-colors`,children:`Remove`})]})]})}),(0,$.jsx)(ki,{open:b,onOpenChange:x,onSuccess:F}),(0,$.jsx)(Ai,{open:S,onOpenChange:e=>{C(e),e||ie(null)},accounts:c,preselectId:k,onMessage:P}),(0,$.jsx)(ji,{open:w,onOpenChange:ee,onSuccess:F}),(0,$.jsx)(Li,{open:T,onOpenChange:te})]})}function ta(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function na(e){return e>=90?`bg-error`:e>=70?`bg-warning`:`bg-success`}function ra({label:e,frac:t}){let n=t==null?null:Math.round(t*100);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}),(0,$.jsx)(`span`,{className:`text-xs font-medium tabular-nums ${n==null?`text-text-subtle`:ta(n)}`,children:n==null?`—`:`${n}%`})]}),(0,$.jsx)(`div`,{className:`h-2 rounded-full bg-border overflow-hidden`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full transition-all ${n==null?``:na(n)}`,style:{width:`${Math.min(n??0,100)}%`}})})]})}function ia({onClose:e,usage:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)({}),[o,s]=(0,Q.useState)(!1),c=(0,Q.useCallback)(async()=>{s(!0);try{r((await k.get(`/api/codex-accounts`)).accounts),a(await k.get(`/api/codex-accounts/usage`))}catch{}finally{s(!1)}},[]);return(0,Q.useEffect)(()=>{c()},[c]),(0,$.jsxs)(`div`,{className:`border-t border-border bg-surface px-3 py-2.5 space-y-2.5 max-h-[350px] overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`text-xs font-semibold text-text-primary`,children:`Codex Usage`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`button`,{onClick:c,disabled:o,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${o?`animate-spin`:``}`})}),(0,$.jsx)(`button`,{onClick:e,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer`,title:`Close`,children:(0,$.jsx)(D,{className:`size-3`})})]})]}),o&&n.length===0&&(0,$.jsxs)(`div`,{className:`text-xs text-text-subtle flex items-center gap-2`,children:[(0,$.jsx)(q,{className:`size-3 animate-spin`}),` Loading…`]}),!o&&n.length===0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-border/50 bg-surface/40 p-2.5 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm text-text-primary truncate flex-1 min-w-0`,children:t.activeAccountLabel||`Default login`}),(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-text-subtle border border-border rounded px-1`,children:`~/.codex`})]}),(0,$.jsx)(ra,{label:`5-Hour`,frac:t.fiveHour}),(0,$.jsx)(ra,{label:`Weekly`,frac:t.sevenDay})]}),(0,$.jsxs)(`p`,{className:`text-[11px] text-text-subtle`,children:[`Using your default `,(0,$.jsx)(`code`,{children:`~/.codex`}),` login. Add managed accounts in Settings → AI Provider → Codex.`]})]}),n.map(e=>{let t=i[e.id]??{};return(0,$.jsxs)(`div`,{className:`rounded-md border border-border/50 bg-surface/40 p-2.5 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm text-text-primary truncate flex-1 min-w-0`,children:e.label}),(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-text-subtle border border-border rounded px-1`,children:e.type}),e.planType&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:e.planType})]}),(0,$.jsx)(ra,{label:`5-Hour`,frac:t.fiveHour}),(0,$.jsx)(ra,{label:`Weekly`,frac:t.sevenDay})]},e.id)})]})}var aa={active:`bg-success`,idle:`bg-warning`,shutdown:`bg-text-3`},oa={task_assignment:{label:`task`,className:`bg-primary/20 text-primary`},idle_notification:{label:`idle`,className:`bg-warning/20 text-warning`},completion:{label:`done`,className:`bg-success/20 text-success`},shutdown_request:{label:`shutdown`,className:`bg-error/20 text-error`},shutdown_approved:{label:`shutdown ✓`,className:`bg-text-3/20 text-text-3`}};function sa({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 k.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)(Pe,{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`,aa[e.status]??`bg-text-3`)}),(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?oa[e.parsedType]:null,r=ca(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:la(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??ua(e.text)]})]},`${e.timestamp}-${t}`)}),(0,$.jsx)(`div`,{ref:c})]})})]})}function ca(e){try{return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}catch{return``}}function la(e){if(e&&(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^[a-zA-Z]{3,20}$/.test(e)))return{color:e}}function ua(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 da(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function fa({projectName:e,usageInfo:t,usageLoading:n,refreshUsage:r,lastFetchedAt:o,sessionId:c,providerId:l,onSelectSession:u,onBugReport:d,isConnected:f,onReload:p,teamActivity:m,teamMessages:h,onTeamOpen:g}){let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)([]),[x,S]=(0,Q.useState)(!1),C=Y(e=>e.notifications),w=Y(e=>c?e.notifications.has(c):!1),T=Y(e=>e.clearForSession),te=Y(e=>e.markUnread),[ne,re]=(0,Q.useState)(``),E=ct(ne,300),[ie,A]=(0,Q.useState)(null),[j,ae]=(0,Q.useState)(``),[oe,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[L,se]=(0,Q.useState)([]),[R,z]=(0,Q.useState)(null),[B,ce]=(0,Q.useState)({}),[le,V]=(0,Q.useState)(!1),H=(0,Q.useRef)(null),U=I(e=>e.openTab),W=e=>{v(t=>t===e?null:e)},G=(0,Q.useCallback)(async t=>{if(e){S(!0);try{let n=new URLSearchParams({limit:`50`,offset:`0`});t&&n.set(`q`,t);let r=await k.get(`${O(e)}/chat/sessions?${n}`);b(r.sessions),N(r.hasMore)}catch{}finally{S(!1)}}},[e]),K=(0,Q.useCallback)(async()=>{if(!(!e||P||!oe)){F(!0);try{let t=y.filter(e=>!e.pinned).length,n=new URLSearchParams({limit:`50`,offset:String(t)});E&&n.set(`q`,E);let r=await k.get(`${O(e)}/chat/sessions?${n}`);b(e=>{let t=new Set(e.map(e=>e.id)),n=r.sessions.filter(e=>!t.has(e.id));return[...e,...n]}),N(r.hasMore)}catch{}finally{F(!1)}}},[e,P,oe,y,E]);(0,Q.useEffect)(()=>{_===`history`&&y.length===0&&G()},[_]),(0,Q.useEffect)(()=>{_===`history`&&G(E||void 0)},[E]);let J=(0,Q.useCallback)(async()=>{if(e)try{let t=await k.get(`${O(e)}/tags`);se(t.tags),ce(t.counts)}catch{}},[e]);(0,Q.useEffect)(()=>{_===`history`&&e&&J()},[_,e,J]);function fe(t){u?(u(t),v(null)):U({type:`chat`,title:t.title||`Chat`,projectId:e??null,metadata:{projectName:e,sessionId:t.id,providerId:t.providerId},closable:!0})}let pe=(0,Q.useCallback)((e,t)=>{t.stopPropagation(),A(e.id),ae(e.title||``),setTimeout(()=>H.current?.select(),0)},[]),X=(0,Q.useCallback)(async()=>{if(!ie||!j.trim()||!e){A(null);return}try{await k.patch(`${O(e)}/chat/sessions/${ie}`,{title:j.trim()}),b(e=>e.map(e=>e.id===ie?{...e,title:j.trim()}:e))}catch{}A(null)},[ie,j,e]),ge=(0,Q.useCallback)(()=>A(null),[]),_e=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),!e)return;let r=`${O(e)}/chat/sessions/${n.id}/pin`;try{n.pinned?await k.del(r):await k.put(r),b(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]),ve=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),e&&window.confirm(`Delete this session? This cannot be undone.`))try{await k.del(`${O(e)}/chat/sessions/${n.id}?providerId=${n.providerId}`),b(e=>e.filter(e=>e.id!==n.id))}catch{}},[e]),ye=(0,Q.useCallback)((e,t)=>{b(n=>n.map(n=>n.id===e?{...n,tag:t}:n)),J()},[J]),be=(0,Q.useCallback)(async()=>{if(!e)return;let t=window.prompt(`Delete sessions older than how many days? (pinned sessions are kept)`,`30`);if(!t)return;let n=parseInt(t,10);if(!(!n||n<1)&&window.confirm(`Delete all unpinned sessions older than ${n} days? This cannot be undone.`)){S(!0);try{await k.del(`${O(e)}/chat/sessions?olderThanDays=${n}`),G(E||void 0)}catch{}}},[e,G,E]);(0,Q.useEffect)(()=>{if(_!==`history`)return;let t=t=>{if(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement)return;let n=parseInt(t.key);if(n>=1&&n<=L.length&&c){let t=L[n-1];t&&(k.patch(`${O(e)}/chat/sessions/${c}/tag`,{tagId:t.id}).catch(()=>{}),ye(c,{id:t.id,name:t.name,color:t.color}))}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[_,L,c,e,ye]);let Se=R===null?y:y.filter(e=>e.tag?.id===R),Ce=!l||l===`claude`,Oe=l===`codex`,ke=t.fiveHour==null?null:Math.round(t.fiveHour*100),Ae=t.sevenDay==null?null:Math.round(t.sevenDay*100),Z=ke!=null||Ae!=null?da(Math.max(ke??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:()=>W(`history`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`history`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,children:[(0,$.jsx)(Qe,{className:`size-3`}),(0,$.jsx)(`span`,{children:`History`})]}),c&&l&&l!==`mock`?(0,$.jsxs)(`button`,{onClick:()=>W(`config`),className:`flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`config`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`AI Settings`,children:[(0,$.jsx)(De,{providerId:l}),(0,$.jsx)(`span`,{className:`capitalize`,children:l})]}):(0,$.jsx)(`button`,{onClick:()=>W(`config`),className:`p-1 rounded transition-colors ${_===`config`?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary hover:bg-surface-elevated`}`,title:`AI Settings`,children:(0,$.jsx)(ue,{className:`size-3`})}),Ce||Oe?(0,$.jsxs)(`button`,{onClick:()=>W(`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 ${_===`usage`?`bg-primary/10`:``} ${Z}`,title:`Usage limits`,children:[(0,$.jsx)(vt,{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:`,ke==null?`--%`:`${ke}%`]}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Wk:`,Ae==null?`--%`:`${Ae}%`]})]}):null,m?.hasTeams&&(0,$.jsxs)(`button`,{onClick:()=>{W(`team`),g?.()},className:`relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${_===`team`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`Team activity`,children:[(0,$.jsx)(Ee,{className:`size-3`}),(0,$.jsx)(`span`,{children:`Team`}),(m.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`}),w&&c&&(0,$.jsx)(`button`,{onClick:()=>T(c),className:`p-1 rounded text-warning hover:text-warning/80 hover:bg-surface-elevated transition-colors`,title:`Mark as read`,children:(0,$.jsx)(de,{className:`size-3`})}),!w&&c&&(0,$.jsx)(`button`,{onClick:()=>te(c,e),className:`p-1 rounded text-primary hover:text-primary/80 hover:bg-surface-elevated transition-colors`,title:`Mark as unread`,children:(0,$.jsx)(Je,{className:`size-3 fill-current`})}),c&&(0,$.jsx)(Di,{sessionId:c,projectName:e}),p&&(0,$.jsxs)(`button`,{onClick:e=>{let t=e.currentTarget.querySelector(`svg`);t&&(t.classList.add(`animate-spin`),setTimeout(()=>t.classList.remove(`animate-spin`),600)),p()},className:`relative size-4 flex items-center justify-center`,title:f?`Reload messages`:`Disconnected — click to reload`,children:[(0,$.jsx)(Pe,{className:`size-3 ${f?`text-muted-foreground/60`:`text-error`}`,strokeWidth:2.5}),(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 size-1.5 rounded-full ${f?`bg-success`:`bg-error animate-pulse`}`})]})]}),_===`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)(ee,{className:`size-3 text-text-subtle shrink-0`}),(0,$.jsx)(`input`,{type:`text`,value:ne,onChange:e=>re(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:be,className:`p-0.5 rounded text-text-subtle hover:text-error transition-colors`,title:`Delete old sessions...`,children:(0,$.jsx)(lt,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:()=>G(E||void 0),disabled:x,className:`p-0.5 rounded text-text-subtle hover:text-text-secondary transition-colors disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(Pe,{className:`size-3 ${x?`animate-spin`:``}`})})]}),L.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1 overflow-x-auto border-b border-border/30 scrollbar-none`,children:[(0,$.jsxs)(`button`,{onClick:()=>z(null),className:`shrink-0 rounded-md border px-2 py-1 text-[10px] transition-colors ${R===null?`bg-primary/20 border-primary text-primary`:`border-border bg-surface text-text-secondary`}`,children:[`All (`,y.length,`)`]}),L.map(e=>(0,$.jsxs)(`button`,{onClick:()=>z(R===e.id?null:e.id),className:`shrink-0 flex items-center gap-1 rounded-md border px-2 py-1 text-[10px] transition-colors ${R===e.id?`border-current`:`border-border bg-surface`}`,style:R===e.id?{backgroundColor:e.color+`20`,color:e.color,borderColor:e.color}:void 0,children:[(0,$.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:e.color}}),e.name,` (`,B[e.id]??0,`)`]},e.id)),(0,$.jsx)(`button`,{onClick:()=>V(!le),className:`shrink-0 p-1 rounded transition-colors ${le?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary`}`,title:`Manage tags`,children:(0,$.jsx)(me,{className:`size-3`})})]}),le&&(0,$.jsx)(`div`,{className:`border-b border-border/30 px-2 py-2 max-h-[180px] overflow-y-auto bg-surface-elevated/50`,children:(0,$.jsx)(ot,{projectName:e,onTagsChanged:J})}),(0,$.jsx)(`div`,{className:`max-h-[200px] overflow-y-auto`,children:x&&y.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(q,{className:`size-3.5 animate-spin text-text-subtle`})}):Se.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3 text-[11px] text-text-subtle`,children:ne?`No matching sessions`:`No sessions yet`}):(0,$.jsxs)($.Fragment,{children:[Se.map(t=>{let n=C.get(t.id),r=!!n;return(0,$.jsx)(ze,{session:t,projectName:e,projectTags:L,onTogglePin:_e,onStartEditing:pe,onDeleteSession:ve,onTagChanged:ye,children:(0,$.jsxs)(`div`,{className:M(`flex items-center gap-2 w-full px-3 py-1.5 text-left hover:bg-surface-elevated transition-colors group`,r&&`font-medium text-foreground`,r&&dt(n.type),!r&&`text-text-secondary`),children:[(0,$.jsx)(De,{providerId:t.providerId}),t.tag&&(0,$.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:t.tag.color},title:t.tag.name}),ie===t.id?(0,$.jsxs)(`form`,{className:`flex items-center gap-1 flex-1 min-w-0`,onSubmit:e=>{e.preventDefault(),X()},children:[(0,$.jsx)(`input`,{ref:H,value:j,onChange:e=>ae(e.target.value),onBlur:X,onKeyDown:e=>{e.key===`Escape`&&ge()},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-success hover:text-success/80`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(a,{className:`size-3`})}),(0,$.jsx)(`button`,{type:`button`,className:`p-0.5 text-text-subtle hover:text-text-secondary`,onClick:e=>{e.stopPropagation(),ge()},children:(0,$.jsx)(D,{className:`size-3`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{onClick:()=>fe(t),className:`text-[11px] truncate flex-1 text-left flex items-center gap-1`,children:[t.title?.startsWith(`[PPM]`)&&(0,$.jsx)(i,{className:`size-3 text-muted-foreground shrink-0`}),t.title?.startsWith(`[PPM]`)?t.title.slice(7):t.title||`Untitled`]}),(0,$.jsx)(`button`,{onClick:e=>_e(e,t),className:`p-0.5 rounded transition-all ${t.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:t.pinned?`Unpin session`:`Pin session`,children:t.pinned?(0,$.jsx)(xe,{className:`size-3`}):(0,$.jsx)(he,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>pe(t,e),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)(s,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>ve(e,t),className:`p-0.5 rounded text-text-subtle hover:text-error hover:bg-error/20 can-hover:opacity-0 can-hover:group-hover:opacity-100 transition-opacity`,title:`Delete session`,children:(0,$.jsx)(we,{className:`size-3`})})]}),ie!==t.id&&t.updatedAt&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0 w-16 text-right`,children:Me(t.updatedAt)})]})},t.id)}),oe&&(0,$.jsxs)(`button`,{onClick:K,disabled:P,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:[P?(0,$.jsx)(q,{className:`size-3 animate-spin`}):null,P?`Loading...`:`Load more`]})]})})]}),_===`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)(Te,{compact:!0})}),_===`team`&&m?.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)(sa,{teamNames:m.teamNames,messages:h??[]})}),_===`usage`&&Ce&&(0,$.jsx)(ea,{usage:t,visible:!0,onClose:()=>v(null),onReload:r,loading:n,lastFetchedAt:o}),_===`usage`&&Oe&&(0,$.jsx)(ia,{usage:t,onClose:()=>v(null)})]})}var pa=3e3;function ma(e,t){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),o=(0,Q.useRef)(void 0),s=(0,Q.useRef)(t);s.current=t;let c=t??`__new__`;(0,Q.useEffect)(()=>{if(!e){a(!1);return}let t=!1;a(!0);let n=setTimeout(()=>{t||a(!1)},pa);return k.get(`${O(e)}/chat/drafts/${encodeURIComponent(c)}`).then(e=>{if(!t)if(e){let t=[];try{t=JSON.parse(e.attachments)}catch{}r({content:e.content,attachments:t})}else r(null)}).catch(()=>{t||r(null)}).finally(()=>{clearTimeout(n),t||a(!1)}),()=>{t=!0,clearTimeout(n)}},[e,c]);let l=(0,Q.useCallback)((t,n)=>{e&&(o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{let r=s.current??`__new__`;k.put(`${O(e)}/chat/drafts/${encodeURIComponent(r)}`,{content:t,attachments:JSON.stringify(n??[])}).catch(()=>{})},1e3))},[e]),u=(0,Q.useCallback)(()=>{if(!e)return;o.current&&clearTimeout(o.current);let t=s.current??`__new__`;k.del(`${O(e)}/chat/drafts/${encodeURIComponent(t)}`).catch(()=>{}),r(null)},[e]);return(0,Q.useEffect)(()=>()=>{o.current&&clearTimeout(o.current)},[]),{draft:n,draftLoading:i,saveDraft:l,clearDraft:u}}function ha({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)(``),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)([]),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(null),[w,ee]=(0,Q.useState)(e?.permissionMode??void 0),T=(0,Q.useRef)(null),[te,ne]=(0,Q.useState)(!1),[re,E]=(0,Q.useState)(null),[ie,M]=(0,Q.useState)(null),[oe,N]=(0,Q.useState)(null),F=(0,Q.useRef)(0),L=e?.projectName??``,R=I(e=>e.updateTab),z=ae(e=>e.version),{usageInfo:B,usageLoading:ce,lastFetchedAt:le,refreshUsage:V}=Ut(L,i),{draft:H,draftLoading:U,saveDraft:W,clearDraft:G}=ma(L,n);(0,Q.useEffect)(()=>{w||se().then(e=>{let t=e.providers[e.default_provider??`claude`];ee(t?.permission_mode??`bypassPermissions`)}).catch(()=>{})},[]),(0,Q.useEffect)(()=>{!t||!n||R(t,{metadata:{...e,sessionId:n,providerId:i,permissionMode:w}})},[n,i,w]);let{messages:K,renderedMessages:J,expandCompact:ue,isCompactExpanded:de,dismissMessage:fe,clearErrors:pe,messagesLoading:me,versionMap:he,isStreaming:X,phase:ge,isReconnecting:_e,connectingElapsed:ve,pendingApproval:ye,contextWindowPct:be,compactStatus:xe,statusMessage:Se,sessionTitle:Ce,model:we,setModel:Te,effort:Ee,setEffort:De,thinking:Oe,setThinking:ke,sendMessage:Ae,respondToApproval:Z,cancelStreaming:je,reconnect:Me,refetchMessages:Ne,isConnected:Pe,teamActivity:Fe,teamMessages:Ie,markTeamRead:Le,bashPartialOutput:Re,backgroundShells:ze,killBackgroundShell:Be}=Vt(n,i,L);(0,Q.useEffect)(()=>{if(Pe&&T.current){let{content:e,permissionMode:t}=T.current;T.current=null,Ae(e,{permissionMode:t})}},[Pe,Ae]),(0,Q.useEffect)(()=>{if(!n||!t)return;let e=()=>{if(document.hidden)return;let{panels:e}=P.getState();Object.values(e).some(e=>e.activeTabId===t)&&(Y.getState().notifications.get(n)?.manual||Y.getState().clearForSession(n))};e(),document.addEventListener(`visibilitychange`,e);let r=P.subscribe(e),i=Y.subscribe(e);return()=>{document.removeEventListener(`visibilitychange`,e),r(),i()}},[n,t]),(0,Q.useEffect)(()=>{t&&Ce&&R(t,{title:Ce})},[Ce]);let[Ve,He]=(0,Q.useState)(e?.pendingMessage),[Ue,Ge]=(0,Q.useState)(null),[Ke,qe]=(0,Q.useState)(!1),[Je,Ye]=(0,Q.useState)(0),[Xe,Qe]=(0,Q.useState)(!1),$e=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{$e.current&&!me&&Qe(!1),$e.current=!!me},[me]);let[et,tt]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{U||tt(!0)},[U]),(0,Q.useEffect)(()=>{Ve&&Pe&&n&&t&&R(t,{metadata:{...e,pendingMessage:void 0}})},[Pe,n]),(0,Q.useEffect)(()=>{Ke&&X&&qe(!1)},[Ke,X]),(0,Q.useEffect)(()=>{if(!Ke)return;let e=setTimeout(()=>qe(!1),6e4);return()=>clearTimeout(e)},[Ke]);let nt=(0,Q.useCallback)((e,t)=>{I.getState().openTab({type:`chat`,title:e||`AI Chat`,metadata:{projectName:L,providerId:i,...t&&{clearedFrom:t}},projectId:L||null,closable:!0})},[L,i]),rt=(0,Q.useCallback)(e=>{qe(!1),r(e.id),a(e.providerId),t&&R(t,{title:e.title||`Chat`}),Y.getState().clearForSession(e.id)},[t,R]),it=(0,Q.useCallback)(async(e,t)=>{if(!(!n||!L))try{let{api:r,projectUrl:a}=await j(async()=>{let{api:e,projectUrl:t}=await import(`./api-client-RtNXvS0P.js`);return{api:e,projectUrl:t}},__vite__mapDeps([32,6,1,2,21])),o=await r.post(`${a(L)}/chat/sessions/${n}/fork?providerId=${i}`,{messageId:t});I.getState().openTab({type:`chat`,title:`Fork: ${e.slice(0,30)}`,metadata:{projectName:L,sessionId:o.id,providerId:i,pendingMessage:e},projectId:L||null,closable:!0})}catch(e){console.error(`Fork failed:`,e);let t=e?.message||`Unknown error`;A.error(`Cannot fork from this message`,{description:t.includes(`not found`)||t.includes(`Invalid upToMessageId`)?`The original message is no longer available in the session transcript. Try forking from a different message.`:t})}},[n,L,i]),at=(0,Q.useCallback)((e,t,n)=>{He(e),Ge({anchorMsgId:t,ownMsgId:n})},[]),ot=(0,Q.useCallback)(()=>{Ge(null),He(void 0),qe(!1),G(),Ye(e=>e+1)},[G]),st=(0,Q.useCallback)(async(a,o)=>{if(!(!a.trim()||!n||!L)){qe(!0);try{let s=await k.post(`${O(L)}/chat/sessions/${n}/fork?providerId=${i}&mode=edit`,{messageId:o});T.current={content:a,permissionMode:w},Qe(!0),t&&R(t,{metadata:{...e,sessionId:s.id}}),r(s.id)}catch(e){qe(!1);let t=e?.message||`Unknown error`;A.error(`Cannot edit from this message`,{description:t.includes(`not found`)||t.includes(`Invalid upToMessageId`)?`The original message is no longer available in the session transcript.`:t})}}},[n,L,i,w,t,R,e]),ct=(0,Q.useCallback)(i=>{!i||i===n||(qe(!1),Qe(!0),t&&R(t,{metadata:{...e,sessionId:i}}),r(i))},[n,t,R,e]),lt=(0,Q.useCallback)((e,t)=>{if(t.length===0)return e;let n=[];for(let e of t)e.textContent&&n.push(e.textContent);let r=t.filter(e=>e.serverPath);if(r.length>0){let e=r.map(e=>e.serverPath).join(`
9
9
  `);n.push(r.length===1?`[Attached file: ${e}]`:`[Attached files:\n${e}\n]`)}return n.length===0?e:n.join(`
10
10
 
11
11
  `)+`