@hienlh/ppm 0.20.1 → 0.20.3

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 (99) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/CLAUDE.md +1 -0
  3. package/assets/skills/ppm/SKILL.md +1 -1
  4. package/assets/skills/ppm/references/http-api.md +5 -1
  5. package/dist/web/assets/accounts-settings-section-DzDmIsPe.js +1 -0
  6. package/dist/web/assets/{ai-resource-editor-BLctP1Pr.js → ai-resource-editor-D7C9wmwA.js} +1 -1
  7. package/dist/web/assets/{ai-settings-section-0hSDp7xx.js → ai-settings-section-BW5a07-Z.js} +1 -1
  8. package/dist/web/assets/{ai-settings-section-CTEU2uGa.js → ai-settings-section-DZuwllLy.js} +1 -1
  9. package/dist/web/assets/{appearance-settings-section-BkcoSV0E.js → appearance-settings-section-RfH2N1rj.js} +1 -1
  10. package/dist/web/assets/chat-tab-Bz0pk0_E.js +15 -0
  11. package/dist/web/assets/{code-editor-C4kKhamq.js → code-editor-C4o1SyuO.js} +2 -2
  12. package/dist/web/assets/{conflict-editor-BEULKwHk.js → conflict-editor-Dk65mBIe.js} +1 -1
  13. package/dist/web/assets/{csv-preview-k3eM8nFf.js → csv-preview-DENi3CFz.js} +1 -1
  14. package/dist/web/assets/{database-viewer-Cslir1dr.js → database-viewer-BiBC7ulB.js} +1 -1
  15. package/dist/web/assets/{diff-viewer-DzAIvBbn.js → diff-viewer-CSvZJHak.js} +1 -1
  16. package/dist/web/assets/{explorer-body-D6H-4cz9.js → explorer-body-QXS0h4AF.js} +1 -1
  17. package/dist/web/assets/{explorer-window-content-C5W_JzCz.js → explorer-window-content-CQgqoRsj.js} +1 -1
  18. package/dist/web/assets/{extension-manager-section-DwicI3CA.js → extension-manager-section-CyC7wX35.js} +1 -1
  19. package/dist/web/assets/{extension-webview-Z3HhC8Pd.js → extension-webview-Da8SIlRa.js} +1 -1
  20. package/dist/web/assets/{files-settings-section-ByV7bRbB.js → files-settings-section-D8cebM51.js} +1 -1
  21. package/dist/web/assets/{general-settings-section-nLksKHur.js → general-settings-section-1HVTvlIw.js} +1 -1
  22. package/dist/web/assets/{git-log-panel-iUXltiTB.js → git-log-panel-C7a4rp8f.js} +1 -1
  23. package/dist/web/assets/{glide-data-grid-C1QB4DHt.js → glide-data-grid-BT9p_4AN.js} +1 -1
  24. package/dist/web/assets/{group-chat-tab-ezXKVVpg.js → group-chat-tab-BUHGnUyW.js} +1 -1
  25. package/dist/web/assets/index-CuYtJ5xF.css +2 -0
  26. package/dist/web/assets/{index-CJWbFurD.js → index-kGmcC9cb.js} +5 -5
  27. package/dist/web/assets/{jira-watcher-section-DwARwskB.js → jira-watcher-section-BxzwW4uQ.js} +1 -1
  28. package/dist/web/assets/{keybindings-store-S7YLGd8B.js → keybindings-store-DjJum4OS.js} +1 -1
  29. package/dist/web/assets/{keyboard-shortcuts-section-BoUDvdDy.js → keyboard-shortcuts-section-DDKG3BU1.js} +1 -1
  30. package/dist/web/assets/{markdown-renderer-DKdfiSIX.js → markdown-renderer-dHeak2mE.js} +1 -1
  31. package/dist/web/assets/{markdown-renderer-DYFmMC_8.js → markdown-renderer-iBw1fCI_.js} +1 -1
  32. package/dist/web/assets/{mobile-explorer-sheet-CMdqLCV-.js → mobile-explorer-sheet-CzL8SLtz.js} +1 -1
  33. package/dist/web/assets/{notification-store-DpSYFj36.js → notification-store-DVi6Ds71.js} +1 -1
  34. package/dist/web/assets/{notifications-settings-section-CIf3-3xd.js → notifications-settings-section-shQ-ugKh.js} +1 -1
  35. package/dist/web/assets/{pdf-preview-C-7IdkIK.js → pdf-preview-DB26KSzm.js} +1 -1
  36. package/dist/web/assets/{postgres-viewer-BYXFYlLg.js → postgres-viewer-CJe2meyF.js} +1 -1
  37. package/dist/web/assets/{ppmbot-settings-section-B9dXvQ6p.js → ppmbot-settings-section-Ba4c9AI9.js} +1 -1
  38. package/dist/web/assets/{process-table-B6NeTWt8.js → process-table-PXwLsMuG.js} +1 -1
  39. package/dist/web/assets/{proxy-settings-section-CUqq7pdU.js → proxy-settings-section-BHBhK6HC.js} +1 -1
  40. package/dist/web/assets/{query-audit-section-C1TYrPIp.js → query-audit-section-BD5ZVqDz.js} +1 -1
  41. package/dist/web/assets/{remote-desktop-mobile-sheet-DuKwKe5F.js → remote-desktop-mobile-sheet-Di4QG8VX.js} +2 -2
  42. package/dist/web/assets/{remote-desktop-mobile-view-DxMTtsa6.js → remote-desktop-mobile-view-DzoZvAqc.js} +1 -1
  43. package/dist/web/assets/{remote-desktop-readiness-gate-BwjfLWqg.js → remote-desktop-readiness-gate-CHO-KJ9Z.js} +1 -1
  44. package/dist/web/assets/{remote-desktop-window-content-BIl4N5Hn.js → remote-desktop-window-content-X324gYbW.js} +1 -1
  45. package/dist/web/assets/{schedules-settings-section-C0qOb7GI.js → schedules-settings-section-a4-h6THc.js} +1 -1
  46. package/dist/web/assets/{settings-body-qbrJXX_A.js → settings-body-Fq7BVDw2.js} +2 -2
  47. package/dist/web/assets/{settings-tab-BKRgYVxf.js → settings-tab-CVLQy-ie.js} +1 -1
  48. package/dist/web/assets/{settings-window-content-DWsxJDu-.js → settings-window-content-Bi7M0iaZ.js} +1 -1
  49. package/dist/web/assets/{sql-query-editor-CsZOpCW3.js → sql-query-editor-D1r265fl.js} +1 -1
  50. package/dist/web/assets/{sqlite-viewer-DUrnCaP7.js → sqlite-viewer-DHkIotRl.js} +1 -1
  51. package/dist/web/assets/{system-monitor-body-C5cMpg7I.js → system-monitor-body-y6VUkYTL.js} +2 -2
  52. package/dist/web/assets/{system-monitor-tab-C66ywbVZ.js → system-monitor-tab-DRAOejhk.js} +1 -1
  53. package/dist/web/assets/{system-monitor-window-content-CENaXYJ-.js → system-monitor-window-content-B5i57xHD.js} +1 -1
  54. package/dist/web/assets/{tab-host-window-content-HViABGoS.js → tab-host-window-content-SkyPFFlc.js} +1 -1
  55. package/dist/web/assets/{team-member-sheet-CK6eyBRL.js → team-member-sheet-BB63u-Lf.js} +2 -2
  56. package/dist/web/assets/{team-member-window-content-D6wxg37P.js → team-member-window-content-D6tVTXuV.js} +1 -1
  57. package/dist/web/assets/{terminal-tab-BmyTawmN.js → terminal-tab-BYaHAkI5.js} +1 -1
  58. package/dist/web/assets/{tool-cards-y-XJcJHo.js → tool-cards-DRJu20sL.js} +2 -2
  59. package/dist/web/assets/use-accounts-data-Ba1_uvEE.js +1 -0
  60. package/dist/web/assets/{use-monaco-theme-BkM5rMgL.js → use-monaco-theme-Uakgj3hJ.js} +1 -1
  61. package/dist/web/assets/{use-remote-desktop-display-choice-BT2r1td1.js → use-remote-desktop-display-choice-Cd3Xalca.js} +1 -1
  62. package/dist/web/assets/{use-websocket-BvVTwMjI.js → use-websocket-BC_EGf5q.js} +1 -1
  63. package/dist/web/assets/{video-preview-BEaofjN7.js → video-preview-BUb43zWb.js} +1 -1
  64. package/dist/web/index.html +2 -2
  65. package/dist/web/sw.js +1 -1
  66. package/docs/deployment-guide.md +10 -0
  67. package/docs/lessons-learned.md +14 -0
  68. package/package.json +1 -1
  69. package/src/providers/codex-app-server/codex-event-mapper.ts +11 -0
  70. package/src/providers/codex-app-server/codex-history.ts +118 -45
  71. package/src/providers/codex-app-server/codex-provider.ts +277 -15
  72. package/src/providers/codex-app-server/codex-rollout-header.ts +99 -0
  73. package/src/providers/codex-app-server/codex-rollout-items.ts +6 -0
  74. package/src/providers/codex-app-server/codex-rollout-transfer.ts +58 -0
  75. package/src/providers/codex-app-server/codex-subagent-thread.ts +103 -0
  76. package/src/providers/codex-app-server/codex-usage-limit.ts +69 -0
  77. package/src/providers/codex-app-server/codex-usage-parser.ts +31 -14
  78. package/src/server/routes/chat.ts +23 -2
  79. package/src/server/routes/codex-accounts.ts +32 -3
  80. package/src/server/ws/chat.ts +15 -11
  81. package/src/services/codex-account-cooldown.ts +56 -0
  82. package/src/services/codex-account-login.ts +109 -34
  83. package/src/services/codex-account.service.ts +56 -10
  84. package/src/services/codex-login-callback.ts +57 -0
  85. package/src/web/components/chat/chat-tab.tsx +8 -2
  86. package/src/web/components/chat/codex-usage-panel.tsx +129 -165
  87. package/src/web/components/chat/usage-badge.tsx +38 -129
  88. package/src/web/components/chat/usage-panel-shell.tsx +153 -0
  89. package/src/web/components/settings/accounts/account-card.tsx +20 -3
  90. package/src/web/components/settings/accounts/codex-accounts-section.tsx +9 -2
  91. package/src/web/components/settings/accounts/codex-add-account-dialog.tsx +47 -27
  92. package/src/web/components/settings/accounts/codex-usage-rows.tsx +17 -6
  93. package/src/web/components/settings/accounts/use-codex-accounts.ts +90 -44
  94. package/src/web/components/ui/tooltip.tsx +14 -1
  95. package/src/web/hooks/use-usage.ts +13 -1
  96. package/dist/web/assets/accounts-settings-section-_sG1AqtH.js +0 -1
  97. package/dist/web/assets/chat-tab-CJi4uYb9.js +0 -15
  98. package/dist/web/assets/index-CoaVwAF6.css +0 -2
  99. package/dist/web/assets/use-accounts-data-BbOb2QNP.js +0 -1
@@ -1 +0,0 @@
1
- import{o as e}from"./rolldown-runtime-FhOqtrmT.js";import{S as t,x as n}from"./vendor-markdown-Ls5AcU91.js";import"./vendor-ui-CaeeFO0B.js";import{t as r}from"./copy-BewHj66E.js";import{t as i}from"./download-DG3_9xXy.js";import{t as a}from"./flask-conical-tp8gyZGh.js";import{t as o}from"./key-round-CQpDrDxg.js";import{t as s}from"./loader-circle-DPMrnLQ2.js";import{t as c}from"./x-CxoBA0po.js";import{n as l,r as u}from"./api-client-CEYCBt_0.js";import{n as d}from"./utils-IrnQujwR.js";import"./portal-container-context-DKymYOY-.js";import{n as f}from"./use-is-mobile-D1weanbj.js";import{n as p,t as m}from"./button-DX32ffge.js";import{t as h}from"./mobile-bottom-sheet-CmySDB6I.js";import"./use-visual-viewport-Bfl3Bxxb.js";import{$t as g,B as _,Dn as v,Dr as y,G as b,Gn as x,H as S,Ln as C,M as w,On as T,Pn as E,Qn as D,Qt as O,U as k,V as A,W as j,X as M,Xt as N,Y as P,Yt as F,Zt as I,en as L,ir as ee,kn as te,lr as R,nn as ne}from"./index-CJWbFurD.js";import{addAccount as re,deleteAccount as ie,exchangeOAuthCode as ae,getAISettings as oe,getAccountSettings as se,getOAuthUrl as ce,getUsageHistory as le,importAccounts as ue,patchAccount as de,testAccountToken as fe,testExport as pe,testRawToken as me,updateAccountSettings as z}from"./api-settings-D18Q4Ocp.js";import{a as B,c as V,i as he,l as ge,n as _e,o as H,r as U,t as ve,u as W}from"./use-accounts-data-BbOb2QNP.js";var G=e(t(),1),K=n(),q=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],J=Array.from({length:24},(e,t)=>t);function ye(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 be(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 xe(e){return J.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 Y(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 Se(e){return e<.3?`bg-success`:e<.7?`bg-warning`:`bg-error`}function Ce({accountId:e}){let[t,n]=(0,G.useState)(null),[r,i]=(0,G.useState)(!0),[a,o]=(0,G.useState)(`5h`);(0,G.useEffect)(()=>{i(!0),le(e).then(n).catch(()=>n([])).finally(()=>i(!1))},[e]);let c=(0,G.useMemo)(()=>t?ye(t,a):null,[t,a]),l=(0,G.useMemo)(()=>c?be(c):[],[c]),u=(0,G.useMemo)(()=>c?xe(c):[],[c]),d=Math.max(...l,.01);if(Math.max(...u,.01),r)return(0,K.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,K.jsx)(s,{className:`size-3 animate-spin text-text-subtle`})});if(!t||t.length===0)return(0,K.jsx)(`div`,{className:`text-[10px] text-text-subtle py-2 text-center`,children:`No usage history yet`});let f=t.length,p=new Set(t.map(e=>new Date(e.recorded_at+(e.recorded_at.endsWith(`Z`)?``:`Z`)).toDateString())).size;return(0,K.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`span`,{className:`text-[10px] font-medium text-text-subtle`,children:`Usage Pattern (7d)`}),(0,K.jsxs)(`div`,{className:`flex gap-0.5 text-[9px]`,children:[(0,K.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,K.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,K.jsxs)(`p`,{className:`text-[9px] text-text-subtle leading-tight`,children:[`Avg `,a===`5h`?`5-hour`:`weekly`,` limit usage over `,p,`d (`,f,` samples). Higher % = closer to rate limit. Hover cells for details.`]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Avg usage by day of week`}),(0,K.jsx)(`div`,{className:`flex flex-col gap-[2px] mt-0.5`,children:q.map((e,t)=>{let n=l[t]??0;return(0,K.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,K.jsx)(`span`,{className:`text-[8px] text-text-subtle w-5 shrink-0 text-right tabular-nums`,children:e}),(0,K.jsx)(`div`,{className:`flex-1 h-2.5 bg-surface-elevated rounded-sm overflow-hidden`,children:(0,K.jsx)(`div`,{className:`h-full rounded-sm transition-all ${Se(n)}`,style:{width:`${Math.round(n/d*100)}%`}})}),(0,K.jsxs)(`span`,{className:`text-[8px] text-text-subtle w-6 shrink-0 text-right tabular-nums`,children:[Math.round(n*100),`%`]})]},e)})})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Avg usage by hour (0h-23h)`}),(0,K.jsx)(`div`,{className:`flex gap-[1px] mt-0.5`,children:J.map(e=>{let t=u[e]??0;return(0,K.jsxs)(`div`,{className:`flex-1 flex flex-col items-center gap-[1px]`,children:[(0,K.jsx)(`div`,{className:`w-full aspect-square rounded-[2px] ${Y(t)}`,title:`${e}:00 — avg ${Math.round(t*100)}% usage`}),e%6==0&&(0,K.jsx)(`span`,{className:`text-[7px] text-text-subtle tabular-nums`,children:e})]},e)})})]}),c&&(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{className:`text-[9px] text-text-subtle`,children:`Day x Hour heatmap`}),(0,K.jsxs)(`div`,{className:`flex flex-col gap-[1px] mt-0.5`,children:[q.map((e,t)=>(0,K.jsxs)(`div`,{className:`flex items-center gap-[1px]`,children:[(0,K.jsx)(`span`,{className:`text-[7px] text-text-subtle w-4 shrink-0 text-right`,children:e.charAt(0)}),J.map(n=>{let r=c[t][n];return(0,K.jsx)(`div`,{className:`flex-1 aspect-square rounded-[1px] ${Y(r.avg)}`,title:`${e} ${n}:00 — ${r.count>0?`avg ${Math.round(r.avg*100)}% (${r.count} samples)`:`no data`}`},n)})]},e)),(0,K.jsxs)(`div`,{className:`flex items-center gap-[1px]`,children:[(0,K.jsx)(`span`,{className:`w-4 shrink-0`}),J.map(e=>(0,K.jsx)(`div`,{className:`flex-1 text-center`,children:e%6==0&&(0,K.jsx)(`span`,{className:`text-[7px] text-text-subtle tabular-nums`,children:e})},e))]})]})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[8px] text-text-subtle`,children:[(0,K.jsx)(`span`,{children:`Low`}),(0,K.jsxs)(`div`,{className:`flex gap-[2px]`,children:[(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-success/30`}),(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-success/60`}),(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/50`}),(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-warning/80`}),(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-error/80`})]}),(0,K.jsx)(`span`,{children:`High`}),(0,K.jsx)(`span`,{className:`ml-1`,children:`|`}),(0,K.jsx)(`div`,{className:`size-2 rounded-[1px] bg-surface-elevated border border-border/30`}),(0,K.jsx)(`span`,{children:`No data`})]})]})}function we({profile:e,accountId:t,onClose:n}){let r=[[`Name`,e.account?.display_name],[`Email`,e.account?.email],[`Org`,e.organization?.name],[`Type`,e.organization?.organization_type],[`Tier`,e.organization?.rate_limit_tier],[`Status`,e.organization?.subscription_status]];return(0,K.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,"data-testid":`account-profile-panel`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-medium`,children:`Profile`}),(0,K.jsx)(`button`,{className:`p-2 text-muted-foreground hover:text-foreground cursor-pointer`,onClick:n,"aria-label":`Close profile`,children:(0,K.jsx)(c,{className:`size-4`})})]}),(0,K.jsx)(`div`,{className:`grid grid-cols-[80px_1fr] gap-x-3 gap-y-1 text-xs`,children:r.map(([e,t])=>t?(0,K.jsxs)(`span`,{className:`contents`,children:[(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,K.jsx)(`span`,{className:`break-all`,children:t})]},e):null)}),(0,K.jsx)(Ce,{accountId:t})]})}function Te({display:e,onConfirm:t,onCancel:n}){let r=f(),i=(0,K.jsxs)(`div`,{className:`space-y-4`,"data-testid":`account-delete-confirm`,children:[(0,K.jsxs)(`p`,{className:`text-sm`,children:[`Remove `,(0,K.jsx)(`span`,{className:`font-medium`,children:e}),`?`]}),(0,K.jsx)(`p`,{className:`text-xs text-text-subtle`,children:`The stored token is deleted from this machine. Any export you already made keeps working.`}),(0,K.jsxs)(`div`,{className:`flex flex-col-reverse md:flex-row gap-2 md:justify-end pt-2`,children:[(0,K.jsx)(m,{variant:`outline`,onClick:n,className:`min-h-11`,children:`Cancel`}),(0,K.jsx)(m,{variant:`destructive`,autoFocus:!1,onClick:t,className:`min-h-11`,children:`Remove account`})]})]});return r?(0,K.jsx)(h,{open:!0,onClose:n,children:(0,K.jsxs)(`div`,{className:`px-4 pb-4`,children:[(0,K.jsx)(`h2`,{className:`text-base font-semibold mb-3`,children:`Remove account`}),i]})}):(0,K.jsx)(F,{open:!0,onOpenChange:e=>{e||n()},children:(0,K.jsxs)(N,{className:`sm:max-w-sm`,children:[(0,K.jsx)(g,{children:(0,K.jsx)(L,{className:`text-sm`,children:`Remove account`})}),i]})})}function Ee({open:e,onOpenChange:t,onSuccess:n}){let[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(``),[c,l]=(0,G.useState)(!1),[u,d]=(0,G.useState)(null),[f,p]=(0,G.useState)(null),[h,_]=(0,G.useState)(``),[v,y]=(0,G.useState)(!1),[b,x]=(0,G.useState)(`idle`);function S(){p(null),_(``),x(`idle`),d(null)}function C(){t(!1),S(),i(``),o(``),d(null)}async function w(){y(!0),d(null);try{let{url:e,state:t}=await ce();p(t),x(`waiting`),window.open(e,`_blank`)}catch(e){d(e.message)}y(!1)}async function T(){if(!(!h.trim()||!f)){y(!0),d(null);try{let e=h.trim();e.includes(`#`)&&(e=e.split(`#`)[0]??e);let t=await ae(e,f);C(),n(t?.status===`disabled`?`Signed in. This account is still disabled — enable it to use it.`:`Account connected via OAuth!`)}catch(e){d(e.message)}y(!1)}}async function E(){if(r.trim()){l(!0),d(null);try{let e=await re({apiKey:r.trim(),label:a.trim()||void 0});C(),n(e?.status===`disabled`?`Token updated. This account is still disabled — enable it to use it.`:`Account added!`)}catch(e){d(e.message)}l(!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,K.jsx)(F,{open:e,onOpenChange:e=>{e||C()},children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsx)(L,{className:`text-sm`,children:`Add Claude Account`}),(0,K.jsx)(I,{className:`text-xs leading-relaxed`,children:`Connect via OAuth (recommended) or paste a token manually.`})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`rounded-md border p-3 space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-[11px] font-medium`,children:`Recommended: Login with Claude`}),b===`idle`?(0,K.jsx)(m,{size:`sm`,className:`w-full h-8 text-xs`,onClick:w,disabled:v,children:v?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-3 animate-spin mr-1`}),` Opening...`]}):`Login with Claude`}):(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Authorize in the opened tab, then paste the code:`}),(0,K.jsx)(M,{placeholder:`Paste code here...`,value:h,onChange:e=>_(e.target.value),className:`text-xs h-8 font-mono`,autoFocus:!0}),(0,K.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,K.jsx)(m,{size:`sm`,className:`flex-1 h-7 text-xs`,onClick:T,disabled:!h.trim()||v,children:v?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-3 animate-spin mr-1`}),` Connecting...`]}):`Connect`}),(0,K.jsx)(m,{size:`sm`,variant:`ghost`,className:`h-7 text-xs`,onClick:S,children:`Cancel`})]})]})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`flex-1 border-t`}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`or paste token`}),(0,K.jsx)(`div`,{className:`flex-1 border-t`})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{htmlFor:`add-token`,className:`text-xs`,children:`Token`}),(0,K.jsx)(M,{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,K.jsxs)(`p`,{className:`text-[10px] text-muted-foreground`,children:[`Detected: `,D]})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{htmlFor:`add-label`,className:`text-xs`,children:`Label (optional)`}),(0,K.jsx)(M,{id:`add-label`,placeholder:`e.g. Personal, Work`,value:a,onChange:e=>o(e.target.value),className:`text-xs h-8`})]})]}),u&&(0,K.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-error/10 text-error`,children:u}),(0,K.jsxs)(O,{children:[(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs h-7`,onClick:C,children:`Cancel`}),(0,K.jsx)(m,{size:`sm`,className:`text-xs h-7`,onClick:E,disabled:!r.trim()||c,children:c?`Adding...`:`Add Token`})]})]})})}function De(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)}function Oe({open:e,onOpenChange:t,accounts:n,preselectId:a,onMessage:o}){let c=n.filter(e=>e.hasRefreshToken),[l,d]=(0,G.useState)(new Set),[f,p]=(0,G.useState)(``),[h,_]=(0,G.useState)(!1),[v,y]=(0,G.useState)(!1),[b,x]=(0,G.useState)(!1),[S,C]=(0,G.useState)(!1);e&&!S&&(d(a?new Set([a]):new Set(c.map(e=>e.id))),C(!0)),!e&&S&&C(!1);function w(){t(!1),p(``),_(!1),y(!1)}async function T(e){if(l.size===0)return;x(!0);let t=f.trim()||`ppm-hienlh`;try{let n={"Content-Type":`application/json`},r=u();r&&(n.Authorization=`Bearer ${r}`);let i=await fetch(`/api/accounts/export`,{method:`POST`,headers:n,body:JSON.stringify({password:t,accountIds:[...l],includeRefreshToken:h,refreshBeforeExport:v})});if(!i.ok){let e=await i.json();throw Error(e.error??`Export failed: ${i.status}`)}let a=await i.text();e&&await ne(a)?o?.(`Backup copied to clipboard!`):(De(a),o?.(`Backup downloaded.`)),w()}catch{}x(!1)}let E=l.size>0&&!b;return(0,K.jsx)(F,{open:e,onOpenChange:e=>{e||w()},children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsxs)(L,{className:`text-sm flex items-center gap-1.5`,children:[(0,K.jsx)(R,{className:`size-3.5`}),` Export Accounts`]}),(0,K.jsx)(I,{className:`text-xs`,children:`Select accounts and set a password to protect the backup.`})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,K.jsx)(`p`,{className:`text-[11px] font-medium text-muted-foreground`,children:`Accounts to export`}),(0,K.jsx)(`button`,{className:`text-[10px] text-primary hover:underline cursor-pointer`,onClick:()=>d(l.size===c.length?new Set:new Set(c.map(e=>e.id))),children:l.size===c.length?`Deselect all`:`Select all`})]}),c.length===0?(0,K.jsx)(`p`,{className:`text-[10px] text-muted-foreground p-2 border rounded`,children:`No exportable accounts.`}):(0,K.jsx)(`div`,{className:`max-h-36 overflow-y-auto space-y-1 border rounded p-2`,children:c.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,id:`exp-${e.id}`,checked:l.has(e.id),onChange:t=>{let n=new Set(l);t.target.checked?n.add(e.id):n.delete(e.id),d(n)},className:`size-3.5 accent-primary cursor-pointer`}),(0,K.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,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsxs)(P,{className:`text-xs`,children:[`Password `,(0,K.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,K.jsx)(M,{type:`password`,placeholder:`Leave empty for default`,value:f,onChange:e=>p(e.target.value),className:`text-xs h-8`,autoComplete:`new-password`})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,id:`exp-full`,checked:h,onChange:e=>_(e.target.checked),className:`size-3.5 accent-primary cursor-pointer`}),(0,K.jsx)(`label`,{htmlFor:`exp-full`,className:`text-[11px] cursor-pointer`,children:`Include refresh tokens (full transfer)`})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`input`,{type:`checkbox`,id:`exp-refresh`,checked:v,onChange:e=>y(e.target.checked),className:`size-3.5 accent-primary cursor-pointer`}),(0,K.jsx)(`label`,{htmlFor:`exp-refresh`,className:`text-[11px] cursor-pointer`,children:`Refresh tokens before export`})]}),h?(0,K.jsxs)(`div`,{className:`rounded-md border border-error/30 bg-error/5 p-2.5`,children:[(0,K.jsx)(`p`,{className:`text-[10px] font-medium text-error`,children:`Full transfer — source accounts will expire`}),(0,K.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Refresh tokens included. Source machine expires in ~1h after target refreshes.`})]}):v?(0,K.jsx)(`div`,{className:`rounded-md border border-warning/30 bg-warning/5 p-2.5`,children:(0,K.jsx)(`p`,{className:`text-[10px] font-medium text-warning`,children:`Refresh before export — invalidates previous shares`})}):(0,K.jsx)(`div`,{className:`rounded-md border border-success/30 bg-success/5 p-2.5`,children:(0,K.jsx)(`p`,{className:`text-[10px] font-medium text-success`,children:`Share current token (safe)`})}),(0,K.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`Encrypted with AES-256-GCM + scrypt.`})]}),(0,K.jsxs)(O,{className:`gap-1.5 flex-col sm:flex-row`,children:[(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:w,children:`Cancel`}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,disabled:!E,onClick:()=>T(!0),children:[(0,K.jsx)(r,{className:`size-3 mr-1`}),` Copy`]}),(0,K.jsx)(m,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!E,onClick:()=>T(!1),children:b?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-3 animate-spin mr-1`}),` Exporting...`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(i,{className:`size-3 mr-1`}),` Download`]})})]})]})})}function ke({open:e,onOpenChange:t,onSuccess:n}){let[r,i]=(0,G.useState)(``),[a,o]=(0,G.useState)(``),[c,l]=(0,G.useState)(!1),[u,d]=(0,G.useState)(null);function f(){t(!1),i(``),o(``),d(null)}async function p(){if(r.trim()){l(!0),d(null);try{let e=await ue({data:r.trim(),password:a.trim()||`ppm-hienlh`});f(),n(`Imported ${e.imported} account(s)`)}catch(e){d(e.message||`Import failed`)}l(!1)}}return(0,K.jsx)(F,{open:e,onOpenChange:e=>{e||f()},children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsxs)(L,{className:`text-sm flex items-center gap-1.5`,children:[(0,K.jsx)(R,{className:`size-3.5`}),` Import Accounts`]}),(0,K.jsx)(I,{className:`text-xs`,children:`Paste backup data and enter the export password. Imported accounts are temporary (~1h).`})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{className:`text-xs`,children:`Backup data`}),(0,K.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,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsxs)(P,{className:`text-xs`,children:[`Password `,(0,K.jsx)(`span`,{className:`text-muted-foreground font-normal`,children:`(optional)`})]}),(0,K.jsx)(M,{type:`password`,placeholder:`Leave empty for default`,value:a,onChange:e=>o(e.target.value),className:`text-xs h-8`,autoComplete:`current-password`})]})]}),u&&(0,K.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-error/10 text-error`,children:u}),(0,K.jsxs)(O,{children:[(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs h-7 cursor-pointer`,onClick:f,children:`Cancel`}),(0,K.jsx)(m,{size:`sm`,className:`text-xs h-7 cursor-pointer`,disabled:!r.trim()||c,onClick:p,children:c?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-3 animate-spin mr-1`}),` Importing...`]}):`Import`})]})]})})}var X=typeof window<`u`?window.matchMedia(`(min-width: 768px)`):null;function Ae(e){return X?.addEventListener(`change`,e),()=>X?.removeEventListener(`change`,e)}function je(){return X?.matches??!0}function Z(){let[e,t]=(0,G.useState)(null),[n,r]=(0,G.useState)(!0);return(0,G.useEffect)(()=>{r(!0),se().then(t).finally(()=>r(!1))},[]),n?(0,K.jsx)(`p`,{className:`text-xs text-text-subtle py-4 text-center`,children:`Loading...`}):e?(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Rotation Strategy`}),(0,K.jsxs)(_,{value:e.strategy,onValueChange:async e=>{t(await z({strategy:e}))},children:[(0,K.jsx)(k,{className:`w-full h-9 text-xs`,children:(0,K.jsx)(j,{})}),(0,K.jsxs)(A,{children:[(0,K.jsx)(S,{value:`round-robin`,children:`Round-robin`}),(0,K.jsx)(S,{value:`fill-first`,children:`Fill-first`}),(0,K.jsx)(S,{value:`lowest-usage`,children:`Lowest usage`})]})]}),(0,K.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,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Max Retry`}),(0,K.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 z({maxRetry:n}))}}),(0,K.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`How many accounts to try on failure. 0 = try all available accounts.`})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`label`,{className:`text-xs font-medium text-text-primary`,children:`Cooldown parking`}),(0,K.jsx)(b,{checked:e.cooldownEnabled,onCheckedChange:async e=>{t(await z({cooldownEnabled:e}))}})]}),(0,K.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,K.jsxs)(`div`,{className:`flex items-center justify-between text-xs border-t border-border pt-3`,children:[(0,K.jsx)(`span`,{className:`text-text-subtle`,children:`Active accounts`}),(0,K.jsx)(`span`,{className:`font-medium text-text-primary`,children:e.activeCount})]})]}):(0,K.jsx)(`p`,{className:`text-xs text-text-subtle py-4 text-center`,children:`Failed to load settings`})}function Me({open:e,onOpenChange:t}){let n=(0,G.useSyncExternalStore)(Ae,je);return e?n?(0,K.jsx)(F,{open:e,onOpenChange:t,children:(0,K.jsxs)(N,{className:`sm:max-w-sm`,children:[(0,K.jsx)(g,{children:(0,K.jsxs)(L,{className:`text-sm flex items-center gap-2`,children:[(0,K.jsx)(x,{className:`size-4`}),` Rotation & Retry`]})}),(0,K.jsx)(Z,{})]})}):(0,K.jsxs)(K.Fragment,{children:[(0,K.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,K.jsxs)(`div`,{className:d(`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,K.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,K.jsx)(`div`,{className:`w-10 h-1 rounded-full bg-border`})}),(0,K.jsxs)(`div`,{className:`flex items-center justify-between px-4 py-2 border-b border-border`,children:[(0,K.jsxs)(`span`,{className:`text-sm font-semibold flex items-center gap-2`,children:[(0,K.jsx)(x,{className:`size-4`}),` Rotation & Retry`]}),(0,K.jsx)(`button`,{onClick:()=>t(!1),className:`flex items-center justify-center size-7 rounded-md hover:bg-surface-elevated transition-colors`,children:(0,K.jsx)(c,{className:`size-4`})})]}),(0,K.jsx)(`div`,{className:`px-4 py-4 pb-8`,children:(0,K.jsx)(Z,{})})]})]}):null}var Ne=p(`inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2`,{variants:{variant:{default:`border-transparent bg-primary text-primary-foreground shadow`,secondary:`border-transparent bg-secondary text-secondary-foreground`,destructive:`border-transparent bg-destructive text-destructive-foreground shadow`,outline:`text-foreground`}},defaultVariants:{variant:`default`}});function Q({className:e,variant:t,...n}){return(0,K.jsx)(`div`,{className:d(Ne({variant:t}),e),...n})}function Pe(e){let t=Math.floor(Date.now()/1e3);return e>t?`${Math.floor((e-t)/60)}m`:`exp`}function Fe({accounts:e}){let[t,n]=(0,G.useState)([]),[r,i]=(0,G.useState)(!1),[a,o]=(0,G.useState)(!1),[c,l]=(0,G.useState)(new Map),u=e.filter(e=>e.hasRefreshToken);async function d(){if(u.length!==0){i(!0);try{let e=await pe(u.map(e=>e.id),a);n(t=>[...t,{round:t.length+1,time:new Date().toLocaleTimeString(),includeRefresh:a,items:e}])}catch{}i(!1)}}async function f(e,t){l(t=>new Map(t).set(e,{loading:!0}));try{let n=await me(t);l(t=>new Map(t).set(e,{loading:!1,...n}))}catch(t){l(n=>new Map(n).set(e,{loading:!1,status:`error`,error:t.message}))}}function p(e,t){return[{key:`r${e.round}-pre-${t.id}`,label:`Pre-export`,token:t.preExportTokenFull,preview:t.preExportToken,expires:t.preExportExpires},{key:`r${e.round}-exp-${t.id}`,label:`Exported`,token:t.exportedTokenFull,preview:t.exportedToken,expires:t.exportedExpires},{key:`r${e.round}-post-${t.id}`,label:`Post-export`,token:t.postExportTokenFull,preview:t.postExportToken,expires:t.postExportExpires}]}function h(){for(let e of t)for(let t of e.items)for(let n of p(e,t))n.token&&f(n.key,n.token)}return(0,K.jsxs)(`section`,{className:`border-t pt-4 space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,K.jsx)(`p`,{className:`text-xs font-medium`,children:`Simulate export`}),t.length>0&&(0,K.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[t.length,` round(s)`]})]}),(0,K.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Every run appends a round. Earlier rounds are kept so tokens can be compared across runs.`}),u.length===0?(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No OAuth account with a refresh token to export.`}):(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(b,{id:`sim-include-refresh`,checked:a,onCheckedChange:o,className:`cursor-pointer`}),(0,K.jsx)(P,{htmlFor:`sim-include-refresh`,className:`text-[11px] cursor-pointer`,children:`Include refresh tokens`})]}),(0,K.jsx)(m,{size:`sm`,className:`h-7 text-xs cursor-pointer`,disabled:r,onClick:()=>void d(),children:r?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-3 animate-spin mr-1`}),` Exporting...`]}):`Run export #${t.length+1}`})]}),t.length>0&&(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`w-full h-7 text-[11px] cursor-pointer`,onClick:h,children:[`Test all tokens (`,t.reduce((e,t)=>e+t.items.length*3,0),`)`]}),t.map(e=>(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsxs)(`p`,{className:`text-xs font-medium text-primary`,children:[`Round #`,e.round]}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:e.time}),(0,K.jsx)(Q,{variant:e.includeRefresh?`destructive`:`secondary`,className:`text-[9px] px-1 py-0`,children:e.includeRefresh?`with refresh`:`access only`})]}),e.items.map(t=>(0,K.jsxs)(`div`,{className:`p-2 rounded-lg border bg-card space-y-1.5`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-[11px] font-medium`,children:t.label??t.email??t.id.slice(0,8)}),t.tokenChanged&&(0,K.jsx)(Q,{variant:`secondary`,className:`text-[9px] px-1 py-0`,children:`DB token changed`})]}),p(e,t).map(e=>{let t=c.get(e.key);return(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[11px]`,children:[(0,K.jsx)(`span`,{className:`w-20 shrink-0 text-muted-foreground text-[10px]`,children:e.label}),(0,K.jsx)(`code`,{className:`flex-1 truncate font-mono text-[10px] bg-muted px-1 rounded`,children:e.preview??`N/A`}),e.expires&&(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground shrink-0`,children:Pe(e.expires)}),e.token?(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`h-6 text-[10px] px-1.5 cursor-pointer shrink-0`,disabled:t?.loading,onClick:()=>void f(e.key,e.token),children:t?.loading?(0,K.jsx)(s,{className:`size-3 animate-spin`}):`Test`}):(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`-`}),t&&!t.loading&&(0,K.jsx)(`span`,{className:`text-[10px] font-medium shrink-0 ${t.status?.startsWith(`valid`)?`text-success`:`text-error`}`,children:t.status})]},e.key)})]},`r${e.round}-${t.id}`))]},e.round))]})]})}function Ie(e){let t=Math.floor(Date.now()/1e3),n=Math.floor(Math.abs(e-t)/60);return e>t?`${n}m left`:`expired ${n}m ago`}function Le({open:e,onOpenChange:t,accounts:n}){let[r,i]=(0,G.useState)(new Map),[o,c]=(0,G.useState)(!1);async function l(e){i(t=>new Map(t).set(e,{loading:!0}));try{let t=await fe(e,o);i(n=>new Map(n).set(e,{loading:!1,result:t}))}catch(t){i(n=>new Map(n).set(e,{loading:!1,error:t.message}))}}function u(){for(let e of n.filter(e=>e.expiresAt!==null))l(e.id)}return(0,K.jsx)(F,{open:e,onOpenChange:t,children:(0,K.jsxs)(N,{className:`sm:max-w-xl max-h-[85vh] flex flex-col`,children:[(0,K.jsxs)(g,{children:[(0,K.jsxs)(L,{className:`text-sm flex items-center gap-1.5`,children:[(0,K.jsx)(a,{className:`size-4`}),` Token Test`]}),(0,K.jsx)(I,{className:`text-xs`,children:`Probe stored tokens for validity. Nothing is modified.`})]}),(0,K.jsxs)(`div`,{className:`space-y-4 overflow-y-auto flex-1 pr-1`,children:[(0,K.jsxs)(`section`,{className:`space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,K.jsx)(`p`,{className:`text-xs font-medium`,children:`Current tokens`}),(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,K.jsx)(b,{id:`token-test-refresh`,checked:o,onCheckedChange:c,className:`cursor-pointer`}),(0,K.jsx)(P,{htmlFor:`token-test-refresh`,className:`text-[11px] cursor-pointer`,children:`Also test refresh`})]}),(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`h-7 text-xs cursor-pointer`,onClick:u,children:`Test all`})]})]}),n.length===0&&(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No accounts to test.`}),(0,K.jsx)(`div`,{className:`space-y-1.5`,children:n.map(e=>{let t=r.get(e.id),n=t?.result?.accessToken.status;return(0,K.jsxs)(`div`,{className:`p-2 rounded border bg-card space-y-1`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`span`,{className:`text-xs font-medium truncate block`,children:e.label??e.email??e.id.slice(0,8)}),e.expiresAt&&(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:Ie(e.expiresAt)})]}),(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`h-7 text-xs cursor-pointer shrink-0`,disabled:t?.loading,onClick:()=>void l(e.id),children:t?.loading?(0,K.jsx)(s,{className:`size-3 animate-spin`}):`Test`})]}),t&&!t.loading&&(0,K.jsxs)(`div`,{className:`text-[11px] pl-2 border-l-2 border-muted`,children:[t.error&&(0,K.jsx)(`p`,{className:`text-error`,children:t.error}),n&&(0,K.jsxs)(`span`,{className:n.startsWith(`valid`)?`text-success`:`text-error`,children:[n,t.result?.accessToken.code?` (${t.result.accessToken.code})`:``]})]})]},e.id)})})]}),(0,K.jsx)(Fe,{accounts:n})]}),(0,K.jsx)(O,{children:(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs cursor-pointer`,onClick:()=>t(!1),children:`Close`})})]})})}function Re(){let{usages:e,accounts:t,activeAccountId:n,initialLoading:r,refreshing:c,flashIds:l,reload:u}=ve(),[d,f]=(0,G.useState)(null),[p,h]=(0,G.useState)(null),[g,_]=(0,G.useState)(null),[v,y]=(0,G.useState)(null),[b,S]=(0,G.useState)(null),[C,w]=(0,G.useState)(null);function T(e){u(),e&&f(e)}async function O(e,t){h(e);try{await de(e,{status:t===`disabled`?`active`:`disabled`})}catch(e){f(e.message)}h(null),u()}async function k(){if(g){try{await ie(g.id),f(`Account "${g.display}" removed.`),u()}catch(e){f(`Failed to remove: ${e.message}`)}_(null)}}let A=new Map(t.map(e=>[e.id,e])),j=e[0]?.usage.lastFetchedAt;return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsx)(B,{description:`Connect multiple Claude accounts. PPM rotates between them automatically to avoid rate limits.`,onRefresh:()=>void u(),refreshing:c,disabled:r,actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m,{size:`sm`,className:`cursor-pointer gap-1.5`,onClick:()=>w(`add`),children:[(0,K.jsx)(D,{className:`size-4`}),` Add account`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>{S(null),w(`export`)},children:[(0,K.jsx)(i,{className:`size-4`}),` Export`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>w(`import`),children:[(0,K.jsx)(E,{className:`size-4`}),` Import`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>w(`rotation`),children:[(0,K.jsx)(x,{className:`size-4`}),` Rotation`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>w(`token-test`),children:[(0,K.jsx)(a,{className:`size-4`}),` Token test`]})]})}),(0,K.jsx)(H,{message:d,onDismiss:()=>f(null)}),(0,K.jsxs)(`section`,{className:`space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-medium`,children:`Accounts`}),j&&(0,K.jsxs)(`span`,{className:`text-[10px] text-muted-foreground`,children:[`usage `,ge(new Date(j).getTime())]})]}),r?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 py-6 text-xs text-muted-foreground`,children:[(0,K.jsx)(s,{className:`size-4 animate-spin`}),` Loading accounts...`]}):e.length===0?(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-2 py-8 text-center`,children:[(0,K.jsx)(o,{className:`size-5 text-muted-foreground`}),(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No accounts connected yet.`}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Add one to start using PPM.`})]}):(0,K.jsx)(U,{children:e.map(e=>(0,K.jsx)(_e,{layout:`strip`,entry:e,isActive:e.accountId===n,accountInfo:A.get(e.accountId),onToggle:O,toggling:p===e.accountId,onDelete:(e,t)=>_({id:e,display:t}),onExport:e=>{S(e),w(`export`)},onViewProfile:(e,t)=>y({profile:e,accountId:t}),flash:l.has(e.accountId)},e.accountId))})]}),v&&(0,K.jsx)(we,{profile:v.profile,accountId:v.accountId,onClose:()=>y(null)}),g&&(0,K.jsx)(Te,{display:g.display,onConfirm:()=>void k(),onCancel:()=>_(null)}),(0,K.jsx)(Ee,{open:C===`add`,onOpenChange:e=>w(e?`add`:null),onSuccess:T}),(0,K.jsx)(Oe,{open:C===`export`,onOpenChange:e=>{w(e?`export`:null),e||S(null)},accounts:t,preselectId:b,onMessage:f}),(0,K.jsx)(ke,{open:C===`import`,onOpenChange:e=>w(e?`import`:null),onSuccess:T}),(0,K.jsx)(Me,{open:C===`rotation`,onOpenChange:e=>w(e?`rotation`:null)}),(0,K.jsx)(Le,{open:C===`token-test`,onOpenChange:e=>w(e?`token-test`:null),accounts:t})]})}function ze({open:e,onOpenChange:t,label:n,onLabelChange:r,apiKey:i,onApiKeyChange:a,adding:c,onAddApiKey:l,deviceWaiting:u,onStartDevice:d,device:f,error:p}){return(0,K.jsx)(F,{open:e,onOpenChange:t,children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsx)(L,{className:`text-sm`,children:`Add Codex Account`}),(0,K.jsxs)(I,{className:`text-xs leading-relaxed`,children:[`Each account keeps its own login (its own `,(0,K.jsx)(`code`,{children:`CODEX_HOME`}),`).`]})]}),(0,K.jsxs)(`div`,{className:`space-y-3`,children:[(0,K.jsxs)(`div`,{className:`rounded-md border p-3 space-y-2`,children:[(0,K.jsx)(`p`,{className:`text-[11px] font-medium`,children:`Recommended: sign in with ChatGPT`}),(0,K.jsx)(m,{size:`sm`,className:`w-full cursor-pointer gap-1.5`,onClick:d,disabled:u,children:u?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(s,{className:`size-4 animate-spin`}),` Waiting for authorization...`]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(ee,{className:`size-4`}),` Sign in with ChatGPT`]})}),f&&(0,K.jsxs)(`div`,{className:`rounded-md border border-primary/40 bg-primary/10 p-2.5 space-y-1.5`,children:[(0,K.jsx)(`p`,{className:`text-[11px]`,children:`Enter this code to authorize:`}),(0,K.jsx)(`div`,{className:`font-mono text-lg tracking-widest`,children:f.userCode}),(0,K.jsxs)(`a`,{href:f.verificationUrl,target:`_blank`,rel:`noreferrer`,className:`inline-flex items-center gap-1 text-primary hover:underline text-[11px]`,children:[(0,K.jsx)(y,{className:`size-3`}),` `,f.verificationUrl]})]})]}),(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`div`,{className:`flex-1 border-t`}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`or paste an API key`}),(0,K.jsx)(`div`,{className:`flex-1 border-t`})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{htmlFor:`codex-api-key`,className:`text-xs`,children:`OpenAI API key`}),(0,K.jsx)(M,{id:`codex-api-key`,type:`password`,placeholder:`sk-...`,value:i,onChange:e=>a(e.target.value),className:`text-xs font-mono`})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{htmlFor:`codex-label`,className:`text-xs`,children:`Label (optional)`}),(0,K.jsx)(M,{id:`codex-label`,placeholder:`e.g. Personal, Work`,value:n,onChange:e=>r(e.target.value),className:`text-xs`})]})]}),p&&(0,K.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-error/10 text-error`,children:p}),(0,K.jsxs)(O,{children:[(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs cursor-pointer`,onClick:()=>t(!1),children:`Cancel`}),(0,K.jsxs)(m,{size:`sm`,className:`text-xs cursor-pointer gap-1.5`,onClick:l,disabled:!i.trim()||c,children:[c?(0,K.jsx)(s,{className:`size-3.5 animate-spin`}):(0,K.jsx)(o,{className:`size-3.5`}),`Add key`]})]})]})})}function Be({mode:e,onOpenChange:t,password:n,onPasswordChange:r,busy:a,onExport:o,onImport:c,error:l}){let u=(0,G.useRef)(null),d=e===`export`;return(0,K.jsx)(F,{open:e!==null,onOpenChange:t,children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsxs)(L,{className:`text-sm flex items-center gap-1.5`,children:[(0,K.jsx)(R,{className:`size-4`}),` `,d?`Export Codex Accounts`:`Import Codex Accounts`]}),(0,K.jsx)(I,{className:`text-xs leading-relaxed`,children:d?`Writes a password-encrypted file containing each account's login.`:`Reads a backup file. The password must be the one it was exported with.`})]}),(0,K.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,K.jsx)(P,{htmlFor:`codex-backup-password`,className:`text-xs`,children:`Password`}),(0,K.jsx)(M,{id:`codex-backup-password`,type:`password`,placeholder:d?`Choose a password`:`Password used for the export`,value:n,onChange:e=>r(e.target.value),className:`text-xs`,autoComplete:d?`new-password`:`current-password`}),(0,K.jsx)(`p`,{className:`text-[10px] text-muted-foreground`,children:`A backup holds full logins — keep the file and its password together.`})]}),l&&(0,K.jsx)(`div`,{className:`text-[11px] p-2 rounded bg-error/10 text-error`,children:l}),(0,K.jsx)(`input`,{ref:u,type:`file`,accept:`application/json,.json`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&c(t)}}),(0,K.jsxs)(O,{children:[(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs cursor-pointer`,onClick:()=>t(!1),children:`Cancel`}),(0,K.jsxs)(m,{size:`sm`,className:`text-xs cursor-pointer gap-1.5`,disabled:!n.trim()||a,onClick:()=>d?o():u.current?.click(),children:[a?(0,K.jsx)(s,{className:`size-3.5 animate-spin`}):d?(0,K.jsx)(i,{className:`size-3.5`}):(0,K.jsx)(E,{className:`size-3.5`}),d?`Download backup`:`Choose file`]})]})]})})}var Ve=[{value:`round-robin`,label:`Round-robin`,hint:`Take the next account each time.`},{value:`fill-first`,label:`Fill-first`,hint:`Stay on one account until it runs out.`},{value:`lowest-usage`,label:`Lowest usage`,hint:`Pick whichever has the most left.`}];function He({open:e,onOpenChange:t,strategy:n,onChange:r}){return(0,K.jsx)(F,{open:e,onOpenChange:t,children:(0,K.jsxs)(N,{className:`sm:max-w-md`,children:[(0,K.jsxs)(g,{children:[(0,K.jsx)(L,{className:`text-sm`,children:`Codex Rotation`}),(0,K.jsx)(I,{className:`text-xs leading-relaxed`,children:`How a new chat chooses among your Codex accounts.`})]}),(0,K.jsx)(`div`,{className:`space-y-2`,children:Ve.map(e=>(0,K.jsxs)(`button`,{type:`button`,onClick:()=>r(e.value),"aria-current":n===e.value?`true`:void 0,className:d(`w-full text-left rounded-md border px-3 py-2.5 min-h-11 cursor-pointer transition-colors`,n===e.value?`border-primary bg-primary/10`:`border-border hover:bg-accent/50 active:bg-accent`),children:[(0,K.jsx)(`p`,{className:`text-sm font-medium`,children:e.label}),(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.hint})]},e.value))}),(0,K.jsx)(O,{children:(0,K.jsx)(m,{size:`sm`,variant:`outline`,className:`text-xs cursor-pointer`,onClick:()=>t(!1),children:`Done`})})]})})}function $(e){return e==null?null:Math.round(e*100)}function Ue({usage:e}){return(0,K.jsxs)(`div`,{className:`space-y-2`,children:[(0,K.jsx)(V,{label:`5-Hour Session`,pct:$(e.fiveHour),reset:W(e.session),resetsAt:e.session?.resetsAt}),(0,K.jsx)(V,{label:`Weekly`,pct:$(e.sevenDay),reset:W(e.weekly),resetsAt:e.weekly?.resetsAt})]})}var We=2e3,Ge=21e4;function Ke(e){let[t,n]=(0,G.useState)([]),[r,i]=(0,G.useState)(`round-robin`),[a,o]=(0,G.useState)({}),[s,c]=(0,G.useState)(!1),[d,f]=(0,G.useState)(new Set),[p,m]=(0,G.useState)(``),[h,g]=(0,G.useState)(``),[_,v]=(0,G.useState)(!1),[y,b]=(0,G.useState)(null),[x,S]=(0,G.useState)(null),[C,w]=(0,G.useState)(!1),[T,E]=(0,G.useState)(``),[D,O]=(0,G.useState)(!1),[k,A]=(0,G.useState)(!1),[j,M]=(0,G.useState)(null),N=(0,G.useRef)(null),P=(0,G.useRef)(null),F=(0,G.useCallback)(async()=>{c(!0);try{let e=await l.get(`/api/codex-accounts`);n(e.accounts),i(e.strategy),l.get(`/api/codex-accounts/usage`).then(o).catch(()=>{})}finally{c(!1)}},[]);(0,G.useEffect)(()=>{F()},[F]);let I=async()=>{if(p.trim()){v(!0),b(null);try{await l.post(`/api/codex-accounts/api-key`,{apiKey:p.trim(),label:h.trim()||void 0}),m(``),g(``),e(),await F()}catch(e){b(e.message)}finally{v(!1)}}},L=(0,G.useCallback)(t=>{let n=Date.now()+Ge,r=!1;N.current=()=>{r=!0};let i=e=>{r=!0,N.current=null,P.current=null,e&&b(e),S(null),w(!1)},a=async()=>{if(r)return;let o=null;try{o=await l.get(`/api/codex-accounts/device-login/${t}/status`)}catch{}if(!r){if(o?.state===`done`){i(),g(``),e(),await F();return}if(o?.state===`error`){i(o.error);return}if(Date.now()>n){i(`Device login timed out.`);return}setTimeout(a,We)}};a()},[F]);return(0,G.useEffect)(()=>()=>{N.current?.();let e=P.current;e&&l.del(`/api/codex-accounts/device-login/${e}`).catch(()=>{})},[]),{accounts:t,strategy:r,usages:a,loading:s,apiKey:p,setApiKey:m,label:h,setLabel:g,adding:_,err:y,setErr:b,device:x,deviceWaiting:C,backupPassword:T,setBackupPassword:E,exporting:D,importing:k,msg:j,setMsg:M,toggling:d,load:F,addApiKey:I,startDevice:async()=>{b(null);try{let e=await l.post(`/api/codex-accounts/device-login`,{label:h.trim()||void 0});S(e),w(!0),P.current=e.id,L(e.id)}catch(e){b(e.message)}},remove:async e=>{await l.del(`/api/codex-accounts/${e}`),await F()},toggle:async(e,t)=>{let n=t===`disabled`?`active`:`disabled`;f(t=>new Set(t).add(e)),b(null);try{await l.patch(`/api/codex-accounts/${e}`,{status:n}),await F()}catch(e){b(e.message||`Could not change the account`)}finally{f(t=>{let n=new Set(t);return n.delete(e),n})}},changeStrategy:async e=>{i(e);try{await l.put(`/api/codex-accounts/strategy`,{strategy:e})}catch{}},doExport:async()=>{if(!T.trim()){b(`Set a backup password first.`);return}O(!0),b(null),M(null);try{let t={"Content-Type":`application/json`},n=u();n&&(t.Authorization=`Bearer ${n}`);let r=await fetch(`/api/codex-accounts/export`,{method:`POST`,headers:t,body:JSON.stringify({password:T})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e.error??`Export failed: ${r.status}`)}let i=await r.text(),a=new Blob([i],{type:`application/json`}),o=document.createElement(`a`);o.href=URL.createObjectURL(a),o.download=`ppm-codex-accounts-backup.json`,o.click(),URL.revokeObjectURL(o.href),M(`Backup downloaded.`),e()}catch(e){b(e.message)}finally{O(!1)}},doImport:async t=>{if(!T.trim()){b(`Enter the backup password first.`);return}A(!0),b(null),M(null);try{let n=await t.text(),r=await l.post(`/api/codex-accounts/import`,{data:n,password:T});M(`Imported ${r.imported}${r.skipped?`, skipped ${r.skipped}`:``}.`),e(),await F()}catch(e){b(e.message)}finally{A(!1)}}}}function qe(){let[e,t]=(0,G.useState)(null),n=Ke(()=>t(null));return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[(0,K.jsx)(B,{description:(0,K.jsxs)(K.Fragment,{children:[`Each Codex account keeps its own login (`,(0,K.jsx)(`code`,{children:`CODEX_HOME`}),`). One is picked per chat by the rotation setting.`]}),onRefresh:()=>void n.load(),refreshing:n.loading,actions:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(m,{size:`sm`,className:`cursor-pointer gap-1.5`,onClick:()=>t(`add`),children:[(0,K.jsx)(D,{className:`size-4`}),` Add account`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>t(`export`),children:[(0,K.jsx)(i,{className:`size-4`}),` Export`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>t(`import`),children:[(0,K.jsx)(E,{className:`size-4`}),` Import`]}),(0,K.jsxs)(m,{size:`sm`,variant:`outline`,className:`cursor-pointer gap-1.5`,onClick:()=>t(`rotation`),children:[(0,K.jsx)(x,{className:`size-4`}),` Rotation`]})]})}),(0,K.jsx)(H,{message:n.msg??n.err,onDismiss:()=>{n.setMsg(null),n.setErr(null)}}),(0,K.jsxs)(`section`,{className:`space-y-2`,children:[(0,K.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,K.jsx)(`h3`,{className:`text-sm font-medium`,children:`Codex Accounts`}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground capitalize`,children:n.strategy.replace(`-`,` `)})]}),n.loading&&n.accounts.length===0?(0,K.jsxs)(`div`,{className:`flex items-center gap-2 py-6 text-xs text-muted-foreground`,children:[(0,K.jsx)(s,{className:`size-4 animate-spin`}),` Loading accounts...`]}):n.accounts.length===0?(0,K.jsxs)(`div`,{className:`flex flex-col items-center gap-2 py-8 text-center`,children:[(0,K.jsx)(o,{className:`size-5 text-muted-foreground`}),(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No Codex accounts yet.`}),(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Chats use your default `,(0,K.jsx)(`code`,{children:`~/.codex`}),` login until you add one.`]})]}):(0,K.jsx)(U,{children:n.accounts.map(e=>{let t=n.usages[e.id]??{};return(0,K.jsxs)(he,{dense:!0,className:`min-w-[300px] shrink-0 snap-start`,"data-testid":`account-card`,"data-account-id":e.id,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(`span`,{className:`text-sm font-medium truncate flex-1 min-w-0`,children:e.label}),(0,K.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-text-subtle border border-border rounded px-1 shrink-0`,children:e.type}),e.planType&&(0,K.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0`,children:e.planType}),(0,K.jsx)(b,{checked:e.status!==`disabled`,onCheckedChange:()=>void n.toggle(e.id,e.status??`active`),disabled:n.toggling.has(e.id),"aria-label":e.status===`disabled`?`Enable account`:`Disable account`,className:`cursor-pointer shrink-0`}),(0,K.jsxs)(v,{children:[(0,K.jsx)(te,{asChild:!0,children:(0,K.jsx)(`button`,{type:`button`,onClick:()=>void n.remove(e.id),"aria-label":`Remove account`,className:`p-2 rounded cursor-pointer text-text-subtle hover:text-error hover:bg-surface-elevated transition-colors shrink-0`,children:(0,K.jsx)(C,{className:`size-4`})})}),(0,K.jsx)(T,{side:`top`,children:`Remove account`})]})]}),(0,K.jsx)(Ue,{usage:t})]},e.id)})})]}),(0,K.jsx)(ze,{open:e===`add`,onOpenChange:e=>t(e?`add`:null),label:n.label,onLabelChange:n.setLabel,apiKey:n.apiKey,onApiKeyChange:n.setApiKey,adding:n.adding,onAddApiKey:()=>void n.addApiKey(),deviceWaiting:n.deviceWaiting,onStartDevice:()=>void n.startDevice(),device:n.device,error:n.err}),(0,K.jsx)(Be,{mode:e===`export`?`export`:e===`import`?`import`:null,onOpenChange:e=>{e||t(null)},password:n.backupPassword,onPasswordChange:n.setBackupPassword,busy:n.exporting||n.importing,onExport:()=>void n.doExport(),onImport:e=>void n.doImport(e),error:n.err}),(0,K.jsx)(He,{open:e===`rotation`,onOpenChange:e=>t(e?`rotation`:null),strategy:n.strategy,onChange:e=>void n.changeStrategy(e)})]})}var Je=[{id:`claude`,label:`Claude`},{id:`codex`,label:`Codex`}];function Ye(){let[e,t]=(0,G.useState)(null),[n,r]=(0,G.useState)(`claude`);(0,G.useEffect)(()=>{let e=!1;return oe().then(n=>{e||t(new Set(Object.keys(n.providers??{})))}).catch(()=>{e||t(new Set([`claude`]))}),()=>{e=!0}},[]);let i=Je.filter(t=>t.id===`claude`||e?.has(t.id)),a=i.length>1;return(0,K.jsxs)(`div`,{className:`space-y-4`,"data-testid":`accounts-pane`,"data-provider":n,children:[a&&(0,K.jsx)(`div`,{className:`flex gap-1 border-b border-border/50`,children:i.map(e=>(0,K.jsxs)(`button`,{onClick:()=>r(e.id),"data-testid":`accounts-tab-${e.id}`,"aria-current":n===e.id?`page`:void 0,className:`flex items-center gap-1.5 px-3 py-2 text-xs rounded-t transition-colors cursor-pointer ${n===e.id?`text-primary border-b-2 border-primary font-medium`:`text-text-subtle hover:text-text-secondary`}`,children:[(0,K.jsx)(w,{providerId:e.id}),e.label]},e.id))}),e===null&&!a&&(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(s,{className:`size-3 animate-spin`}),` Checking configured providers...`]}),n===`claude`?(0,K.jsx)(Re,{}):(0,K.jsx)(qe,{})]})}export{Ye as AccountsSettingsSection};
@@ -1,15 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/edit-diff-preview-xdDQvPhs.js","assets/rolldown-runtime-FhOqtrmT.js","assets/vendor-markdown-Ls5AcU91.js","assets/libesm-CdttTIAd.js","assets/markdown-renderer-DYFmMC_8.js","assets/vendor-mermaid-CfY1-PkA.js","assets/vendor-ui-CaeeFO0B.js","assets/markdown-renderer-DKdfiSIX.js","assets/index-CJWbFurD.js","assets/button-DX32ffge.js","assets/utils-IrnQujwR.js","assets/createLucideIcon-D8pyde1A.js","assets/arrow-left-CyFcsyzD.js","assets/bot-D6sx11y0.js","assets/check-DN75Ucvz.js","assets/chevron-down-Dp0rpHb8.js","assets/chevron-right-De-Wz5Lz.js","assets/chevron-up-8PbsNiJp.js","assets/circle-BCy0AUCo.js","assets/clock-C1CQUQPZ.js","assets/sparkles-Dh-_J2Rd.js","assets/copy-BewHj66E.js","assets/database-Y3ESDK4-.js","assets/download-DG3_9xXy.js","assets/use-coarse-long-press-BmI_GVW5.js","assets/eye-off-GjXVuAOn.js","assets/eye-gWwaF4Lg.js","assets/loader-circle-DPMrnLQ2.js","assets/monitor-C835ucWH.js","assets/x-CxoBA0po.js","assets/api-client-CEYCBt_0.js","assets/react-D1Yg256j.js","assets/window-store-D0HbQ1pM.js","assets/window-pip-registry-CrCYYTTf.js","assets/panel-store-BmdcSBNb.js","assets/context-menu-CJL8L98s.js","assets/portal-container-context-DKymYOY-.js","assets/mobile-bottom-sheet-CmySDB6I.js","assets/use-visual-viewport-Bfl3Bxxb.js","assets/use-is-mobile-D1weanbj.js","assets/project-store-wWZ6bjwq.js","assets/ws-auth-D111jj32.js","assets/settings-store-CzLnTR8p.js","assets/streaming-store-9XVmAMfV.js","assets/tab-store-1xYJb0gM.js","assets/apply-theme-BVXAUYoN.js","assets/resolve-theme-CMp5xxCW.js","assets/index-CoaVwAF6.css","assets/image-gallery-J8h8IY0c.js","assets/run-in-terminal-wHKwAnWP.js","assets/api-client-QfreGirP.js"])))=>i.map(i=>d[i]);
2
- import{o as e}from"./rolldown-runtime-FhOqtrmT.js";import{S as t,x as n}from"./vendor-markdown-Ls5AcU91.js";import"./vendor-ui-CaeeFO0B.js";import{t as r}from"./createLucideIcon-D8pyde1A.js";import{t as i}from"./bot-D6sx11y0.js";import{t as a}from"./brain-KDa9jFRq.js";import{t as o}from"./check-DN75Ucvz.js";import{t as s}from"./chevron-down-Dp0rpHb8.js";import{t as c}from"./chevron-right-De-Wz5Lz.js";import{t as l}from"./chevron-up-8PbsNiJp.js";import{a as u,i as d,n as f,o as p,r as m}from"./tool-cards-y-XJcJHo.js";import{t as h}from"./circle-BCy0AUCo.js";import{t as g}from"./clock-C1CQUQPZ.js";import{t as _}from"./code-DJgYrFzm.js";import{t as v}from"./sparkles-Dh-_J2Rd.js";import{t as y}from"./copy-BewHj66E.js";import{n as b,r as x}from"./use-coarse-long-press-BmI_GVW5.js";import{t as S}from"./eye-gWwaF4Lg.js";import{t as C}from"./hand-x0ejq3fS.js";import{t as w}from"./loader-circle-DPMrnLQ2.js";import{t as ee}from"./shield-off-7jKWpJBD.js";import{t as te}from"./x-CxoBA0po.js";import{i as T,n as E,r as D,s as O}from"./api-client-CEYCBt_0.js";import{q as ne}from"./vendor-mermaid-CfY1-PkA.js";import{t as k}from"./settings-store-CzLnTR8p.js";import{n as A,r as j,t as re}from"./utils-IrnQujwR.js";import"./portal-container-context-DKymYOY-.js";import{t as M}from"./panel-store-BmdcSBNb.js";import"./window-store-D0HbQ1pM.js";import{i as N}from"./project-store-wWZ6bjwq.js";import{t as ie}from"./tab-store-1xYJb0gM.js";import"./context-menu-CJL8L98s.js";import{n as ae}from"./use-is-mobile-D1weanbj.js";import{n as P}from"./streaming-store-9XVmAMfV.js";import{t as F}from"./button-DX32ffge.js";import{t as I}from"./mobile-bottom-sheet-CmySDB6I.js";import"./use-visual-viewport-Bfl3Bxxb.js";import"./ws-auth-D111jj32.js";import{Ar as oe,Bn as L,Br as se,Cr as R,Dn as z,Dr as B,En as ce,Fr as le,G as V,Hn as H,In as U,Ir as ue,Kn as de,Ln as fe,Lt as pe,M as W,Mr as me,N as he,Nn as ge,Nr as G,On as K,P as _e,Pn as ve,Pr as q,Rn as ye,Rt as be,Tn as xe,Un as Se,Wn as J,Xn as Ce,Xt as Y,Yn as we,Yt as Te,_n as Ee,ar as De,bn as Oe,cn as ke,cr as Ae,en as je,er as Me,gn as Ne,hr as Pe,jn as Fe,kn as X,nn as Ie,nr as Le,or as Re,pr as Z,qn as ze,qt as Be,r as Ve,t as He,tr as Ue,v as We,vn as Ge,wn as Ke,xr as qe,yr as Je,zn as Ye,zr as Xe,zt as Ze}from"./index-CJWbFurD.js";import{t as Qe}from"./use-websocket-BvVTwMjI.js";import{getAISettings as $e,pickAccountForTab as et}from"./api-settings-D18Q4Ocp.js";import"./use-blob-url-CrwoZJUJ.js";import{n as tt,r as nt,t as rt}from"./image-gallery-J8h8IY0c.js";import{t as it}from"./libesm-CdttTIAd.js";import{t as at}from"./use-open-team-member-CSUU7Z8N.js";import{n as ot,t as st}from"./send-to-chat-BI7-fFpG.js";import{t as ct}from"./ai-settings-section-CTEU2uGa.js";import{c as lt,l as ut,n as dt,s as ft,t as pt,u as mt}from"./use-accounts-data-BbOb2QNP.js";var ht=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`}]]),gt=r(`chevrons-down`,[[`path`,{d:`m7 6 5 5 5-5`,key:`1lc07p`}],[`path`,{d:`m7 13 5 5 5-5`,key:`1d48rs`}]]),_t=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`}]]),vt=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`}]]),yt=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`}]]),bt=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`}]]),xt=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`}]]),St=r(`slash`,[[`path`,{d:`M22 2 2 22`,key:`y4kqgn`}]]),Q=e(t(),1),Ct={maxImages:4,maxBase64PerImage:5e6,maxBase64Total:1e7};function wt(e){let t=[],n=0;for(let r of e)if(r.imageData){if(t.length>=Ct.maxImages)break;r.imageData.data.length>Ct.maxBase64PerImage||n+r.imageData.data.length>Ct.maxBase64Total||(n+=r.imageData.data.length,t.push(r.imageData))}return t}function Tt(e,t){let n=new Set(t),r=[],i=[];for(let t of e)t.serverPath&&(t.imageData&&n.has(t.imageData)?r.push(t.serverPath):i.push(t.serverPath));return{inlineImagePaths:r,pathOnlyPaths:i}}function Et(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 Dt(e,t){let n=`pc-${Et(t)}-`;return e.map(e=>e.id?{...e,id:`${n}${e.id}`}:e)}function Ot(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 kt=null;function At(){return kt||=new AudioContext,kt}function jt(e,t,n,r,i=`sine`){let a=At(),o=a.createOscillator(),s=a.createGain();o.type=i,o.frequency.value=e,s.gain.setValueAtTime(r,n),s.gain.exponentialRampToValueAtTime(.001,n+t),o.connect(s),s.connect(a.destination),o.start(n),o.stop(n+t)}function Mt(){let e=At().currentTime;jt(523,.15,e,.15),jt(659,.2,e+.12,.15)}function Nt(){let e=At().currentTime;jt(880,.12,e,.18,`square`),jt(698,.12,e+.15,.18,`square`),jt(880,.15,e+.3,.15,`square`)}function Pt(){let e=At().currentTime;jt(440,.12,e,.12),jt(523,.12,e+.1,.12),jt(659,.18,e+.2,.12)}var Ft={done:Mt,approval_request:Nt,question:Pt};function It(e){try{Ft[e]?.()}catch{}}var Lt={hasTeams:!1,teamNames:[],messageCount:0,unreadCount:0};function Rt(e){if(document.hidden)return!1;let{panels:t}=M.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 zt(e,t=`claude`,n=``,r){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(new Map),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)({}),[f,p]=(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)([]),te=(0,Q.useRef)([]),[ne,k]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(null),[re,N]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(null),oe=(0,Q.useRef)(null),L=(0,Q.useRef)(null),[se,R]=(0,Q.useState)(null),z=(0,Q.useRef)(null),[B,ce]=(0,Q.useState)(!0),le=(0,Q.useRef)(null),V=(0,Q.useRef)(null),H=(0,Q.useRef)(``),U=(0,Q.useRef)([]),ue=(0,Q.useRef)(new Map),de=(0,Q.useRef)(null),[fe,pe]=(0,Q.useState)(null),W=(0,Q.useRef)(`idle`),me=(0,Q.useRef)(null),he=(0,Q.useRef)(()=>{}),ge=(0,Q.useRef)(null),G=(0,Q.useRef)(!1),K=(0,Q.useRef)(new Set),_e=(0,Q.useRef)(0),ve=(0,Q.useRef)(null),q=(0,Q.useRef)(0),ye=(0,Q.useRef)(e);ye.current=e;let be=(0,Q.useRef)(r);be.current=r;let xe=(0,Q.useRef)([]);xe.current=i;let Se=(0,Q.useRef)(n);Se.current=n;let J=(0,Q.useRef)(null),Ce=(0,Q.useRef)(0),Y=(0,Q.useRef)({teamNames:new Set,messages:[]}),we=(0,Q.useRef)(0),[Te,Ee]=(0,Q.useState)(Lt),[De,Oe]=(0,Q.useState)([]),ke=(0,Q.useCallback)(()=>{let e=Y.current;Ee({hasTeams:e.teamNames.size>0,teamNames:Array.from(e.teamNames),messageCount:e.messages.length,unreadCount:we.current}),Oe([...e.messages])},[]),Ae=(0,Q.useCallback)(()=>{we.current=0,ke()},[ke]),je=(0,Q.useCallback)(async e=>{try{let t=await E.get(`/api/teams/${encodeURIComponent(e)}`);if(!t?.messages)return;let n=Y.current.messages,r=t.messages.filter(e=>!n.some(t=>t.timestamp===e.timestamp&&t.from===e.from));n.push(...r),n.sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),n.length>500&&n.splice(0,n.length-500),ke()}catch{}},[ke]),Me=f!==`idle`;(0,Q.useEffect)(()=>{if(e)return P.getState().setStreaming(e,f!==`idle`,n),()=>{P.getState().setStreaming(e,!1)}},[e,f,n]);let Ne=(0,Q.useCallback)((e,t)=>{let n=U.current.findIndex(e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t);if(n===-1)return!1;let r=U.current[n];if(r.type!==`tool_use`)return!1;let i=[...r.children??[],e];return U.current[n]={...r,children:i},!0},[]),Pe=(0,Q.useCallback)((e,t)=>{let n=e=>e.type===`tool_use`&&(e.tool===`Agent`||e.tool===`Task`)&&e.toolUseId===t,r=xe.current,i=-1;for(let e=r.length-1;e>=0;e--)if(r[e].events?.some(n)){i=e;break}return i===-1?!1:(a(t=>{let r=-1;for(let e=t.length-1;e>=0;e--)if(t[e].events?.some(n)){r=e;break}if(r===-1)return t;let i=t[r],a=i.events.map(t=>{if(!n(t)||t.type!==`tool_use`)return t;let r=[...t.children??[]],i=e.toolUseId,a=i?r.findIndex(t=>t.type===e.type&&t.toolUseId===i):-1;return a===-1?r.push(e):r[a]=e,{...t,children:r}});return[...t.slice(0,r),{...i,events:a},...t.slice(r+1)]}),!0)},[]),Fe=(0,Q.useCallback)(()=>{Ce.current=0;let e=H.current,t=[...U.current],n=de.current;(0,Q.startTransition)(()=>{a(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}]})})},[]),X=(0,Q.useCallback)(()=>{Ce.current||=window.setTimeout(Fe,100)},[Fe]),Ie=(0,Q.useCallback)((e,t)=>{let n=t=>t.type===`tool_use`&&(t.tool===`Agent`||t.tool===`Task`)&&t.toolUseId===e,r=U.current.findIndex(n);if(r!==-1){U.current[r]={...U.current[r],bgStatus:t},X();return}a(e=>{let r=-1;for(let t=e.length-1;t>=0;t--)if(e[t].events?.some(n)){r=t;break}if(r===-1)return e;let i=e[r],a=i.events.map(e=>n(e)?{...e,bgStatus:t}:e);return[...e.slice(0,r),{...i,events:a},...e.slice(r+1)]})},[X]),Le=(0,Q.useCallback)(e=>{let t=e,n=t?.type;if(!n)return;let r=e=>{let n=U.current,r=n.findIndex(e);r===-1?n.push(t):n[r]=t};switch(n){case`account_info`:de.current={accountId:t.accountId,accountLabel:t.accountLabel},pe({id:t.accountId,label:t.accountLabel??null}),k(null);break;case`account_retry`:t.accountId&&t.accountLabel&&(de.current={accountId:t.accountId,accountLabel:t.accountLabel},pe({id:t.accountId,label:t.accountLabel})),U.current=[t],X();break;case`status_update`:{let e=t.accountLabel?` (${t.accountLabel})`:``;k(`${t.message}${e}`);break}case`text`:{let e=t.parentToolUseId;if(e&&Ne(t,e)){X();break}if(e){Pe(t,e);break}H.current+=t.content,U.current.push(t),X();break}case`thinking`:{let e=t.parentToolUseId;if(e&&Ne(t,e)){X();break}if(e){Pe(t,e);break}U.current.push(t),X();break}case`tool_use`:{if(t.tool===`AskUserQuestion`){t.toolUseId&&K.current.add(t.toolUseId);break}let e=t.parentToolUseId;if(e&&Ne(t,e)){X();break}if(e){Pe(t,e);break}let n=t.toolUseId;r(e=>!!n&&e.type===`tool_use`&&e.toolUseId===n),X();break}case`tool_result`:{let e=t.toolUseId;if(e&&ue.current.delete(e),e&&K.current.has(e))break;let n=t.parentToolUseId;if(n&&Ne(t,n)){X();break}if(n){Pe(t,n);break}r(t=>!!e&&t.type===`tool_result`&&t.toolUseId===e),X();break}case`approval_resolved`:{let e=t.requestId;if(t.approved&&t.answers){let n=U.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,a(e=>[...e]))}y(t=>t&&t.requestId===e?null:t),J.current!=null&&(O.dismiss(J.current),J.current=null);break}case`approval_request`:if(r(e=>e.type===`approval_request`&&e.requestId===t.requestId),G.current)break;if(y({requestId:t.requestId,tool:t.tool,input:t.input}),ye.current&&!Rt(ye.current)){It(t.tool===`AskUserQuestion`?`question`:`approval_request`);let e=ye.current,n=t.tool===`AskUserQuestion`;J.current=O[n?`info`:`warning`](n?`AI has a question`:`${t.tool} needs permission`,{description:Se.current||`Session ${e.slice(0,8)}`,duration:1/0,action:{label:`Go to session`,onClick:()=>{let{panels:t}=M.getState();for(let[n,r]of Object.entries(t)){let t=r.tabs.find(t=>t.metadata?.sessionId===e);if(t){M.getState().setActiveTab(t.id,n);break}}}}})}break;case`error`:a(e=>{let n=e[e.length-1];if(n?.role===`assistant`){let r=U.current,i=r[r.length-1],a=i?.type===`error`&&i.message===t.message?r:[...r,t];return U.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&&(Y.current.teamNames.add(e),ke(),je(e));break}case`team_inbox`:{let e=t.messages;if(Array.isArray(e)){let t=Y.current.messages;t.push(...e),t.length>500&&t.splice(0,t.length-500),we.current+=e.length,ke()}break}case`team_updated`:ke();break;case`bash_output`:{let e=t.toolUseId;if(e){let n=ue.current.get(e);n?(n.content+=t.content,n.content.length>5e5&&(n.content=n.content.slice(-5e5)),n.lineCount=t.lineCount):ue.current.set(e,{content:t.content,lineCount:t.lineCount}),X()}break}case`subagent_status`:{let e=t.toolUseId,n=t.status;e&&n&&Ie(e,n);break}case`background_registry`:{let e=t.shells??[];te.current=e,ee(e);break}case`done`:{if(W.current===`idle`)break;t.contextWindowPct!=null&&x(t.contextWindowPct),ye.current&&!Rt(ye.current)&&It(`done`),Ce.current&&=(clearTimeout(Ce.current),0);let e=H.current,n=[...U.current],r=de.current,i=t.lastMessageUuid,o=t.usage;a(t=>{let a=t[t.length-1];return a?.role===`assistant`?[...t.slice(0,-1),{...a,id:`final-${Date.now()}`,content:e||a.content,events:n.length>0?n:a.events,...i&&{sdkUuid:i},...o&&{usage:o}}]:e||n.length>0?[...t,{id:`final-${Date.now()}`,role:`assistant`,content:e,events:n,timestamp:new Date().toISOString(),...i&&{sdkUuid:i},...o&&{usage:o},...r}]:t}),H.current=``,U.current=[],de.current=null,ve.current=null,ue.current.clear(),k(null);break}}},[Ne,Pe,X,Ie,ke,je]),Re=(0,Q.useCallback)(e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(t.type!==`ping`){if(t.type===`user_message`){let e=t.content;a(n=>{let r=n[n.length-1];return r?.role===`user`&&r.content===e?n:[...n,{id:`user-remote-${Date.now()}`,role:`user`,content:e,timestamp:t.timestamp??new Date().toISOString()}]});return}if(t.type===`title_updated`){j(t.title??null);return}if(t.type===`session_migrated`){let e=t.newSessionId;e&&e!==ye.current&&be.current?.(e);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;p(e),W.current=e,_(e===`connecting`?t.elapsed??0:0),e===`idle`&&C(null);return}if(t.type===`session_state`){N(!0),ae(t.sessionId??ye.current);let e=t,n=e.phase,r=W.current===`idle`;if(p(n),W.current=n,e.sessionTitle&&j(e.sessionTitle),e.model&&(L.current&&e.model!==L.current||(e.model===L.current&&(L.current=null),I(e.model),oe.current=e.model)),typeof e.effort==`string`&&(R(e.effort),z.current=e.effort),typeof e.thinking==`boolean`&&ce(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`){let e=Date.now()-q.current<5e3;r&&e||ge.current?.(),h(!1)}return}if(t.type===`turn_events`){let e=t.events,n=t.userMessage;if(!e?.length&&!n){h(!1);return}_e.current&&=(cancelAnimationFrame(_e.current),0),ve.current=n,a(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}),H.current=``,U.current=[],de.current=null,G.current=!0;let r=0,i=()=>{let t=Math.min(r+100,e.length);for(let n=r;n<t;n++)Le(e[n]);r=t,r<e.length?_e.current=requestAnimationFrame(i):(_e.current=0,G.current=!1,h(!1))};_e.current=requestAnimationFrame(i);return}Le(t)}},[Le]),{send:Z,connect:ze}=Qe({url:e&&n?`/ws/project/${encodeURIComponent(n)}/chat/${e}`:``,onMessage:Re,autoConnect:!!e&&!!n});he.current=Z,(0,Q.useEffect)(()=>{let r=!1;V.current&&V.current!==e&&(L.current=null,le.current=null,pe(null)),V.current=e??null,p(`idle`),W.current=`idle`,y(null),J.current!=null&&(O.dismiss(J.current),J.current=null),C(null),s(new Map),d({}),H.current=``,U.current=[],ve.current=null,q.current=0,ue.current.clear(),Ce.current&&=(clearTimeout(Ce.current),0),N(!1),ae(null),Y.current={teamNames:new Set,messages:[]},we.current=0,Ee(Lt),Oe([]),e&&E.get(`/api/teams`).then(t=>{r||!Array.isArray(t)||t.filter(t=>(t?.name??t?.team_name)===e).length!==0&&(Y.current.teamNames.add(e),ke(),je(e))}).catch(()=>{});let i=new Set(xe.current.map(e=>e.id));return e&&n?(l(!0),E.get(`${T(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&&d(t.versionMap),t?.canonicalSessionId&&t.canonicalSessionId!==ye.current&&be.current?.(t.canonicalSessionId);let o=ve.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}}a(e=>{let t=e.filter(e=>!i.has(e.id));return[...n,...t]}),q.current=Date.now()}).catch(()=>{r||a(e=>e.filter(e=>!i.has(e.id)))}).finally(()=>{r||l(!1)})):a([]),()=>{r=!0}},[e,t,n,ke,je]);let Be=(0,Q.useCallback)((e,t)=>{if(!e.trim()&&!t?.images?.length)return;let n=W.current!==`idle`;if(n){Ce.current&&=(clearTimeout(Ce.current),0);let e=H.current,t=[...U.current];a(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})}a(t=>[...t,{id:`user-${Date.now()}`,role:`user`,content:e,timestamp:new Date().toISOString()}]),H.current=``,U.current=[],me.current=null,n?(p(`thinking`),W.current=`thinking`):(p(`initializing`),W.current=`initializing`),y(null),J.current!=null&&(O.dismiss(J.current),J.current=null),Z(JSON.stringify({type:`message`,content:e,permissionMode:t?.permissionMode,priority:t?.priority,images:t?.images,imagePaths:t?.imagePaths,...oe.current&&{model:oe.current},...z.current&&{effort:z.current},...le.current!==null&&{thinking:le.current}}))},[Z]),Ve=(0,Q.useCallback)(e=>{I(e),oe.current=e,L.current=e,Z(JSON.stringify({type:`set_model`,model:e}))},[Z]),Ue=(0,Q.useCallback)(e=>{R(e),z.current=e,Z(JSON.stringify({type:`set_effort`,effort:e}))},[Z]),We=(0,Q.useCallback)(e=>{ce(e),le.current=e,Z(JSON.stringify({type:`set_thinking`,enabled:e}))},[Z]),Ge=(0,Q.useCallback)((e,t,n)=>{if(Z(JSON.stringify({type:`approval_response`,requestId:e,approved:t,data:n})),t&&n){let t=U.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)}a(e=>[...e])}y(null),J.current!=null&&(O.dismiss(J.current),J.current=null)},[Z]),Ke=(0,Q.useCallback)(()=>{if(W.current===`idle`)return;Z(JSON.stringify({type:`cancel`}));let e=H.current,t=[...U.current];a(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}),H.current=``,U.current=[],ue.current.clear(),me.current=null,p(`idle`),W.current=`idle`,y(null),J.current!=null&&(O.dismiss(J.current),J.current=null)},[Z]),qe=(0,Q.useCallback)(e=>{e&&Z(JSON.stringify({type:`kill_background_shell`,shellId:e}))},[Z]),Je=(0,Q.useCallback)(e=>{if(!e)return;let t=e.replace(/\.output$/,``);return te.current.find(n=>n.shellId===t||n.outputPath.endsWith(e)||n.outputPath.endsWith(`${t}.output`))},[]);(0,Q.useEffect)(()=>{e&&He.getState().setSessionShells(e,w)},[e,w]),(0,Q.useEffect)(()=>{if(e)return He.getState().retainSession(e),()=>{He.getState().releaseSession(e)}},[e]);let Ye=(0,Q.useCallback)(()=>{N(!1),h(!0),ze()},[ze]),Xe=(0,Q.useCallback)(()=>{!e||!n||fetch(`${T(n)}/chat/sessions/${e}/messages?providerId=${t}`,{headers:{Authorization:`Bearer ${D()}`}}).then(e=>e.json()).then(e=>{if(W.current!==`idle`)return;let t=e.ok?Array.isArray(e.data)?{messages:e.data,versionMap:void 0}:e.data:null;t?.versionMap&&d(t.versionMap),Array.isArray(t?.messages)&&t.messages.length>0&&(a(t.messages),H.current=``,U.current=[]),q.current=Date.now()}).catch(()=>{})},[e,t,n]);ge.current=Xe;let Ze=(0,Q.useCallback)(async(e,t)=>{if(!n)throw Error(`No project context available`);let r=e.replace(/^pc-[^-]+-/,``),i=`${T(n)}/chat/pre-compact-messages?jsonlPath=${encodeURIComponent(t)}&before=${encodeURIComponent(r)}`,a=Dt(await E.get(i),t);return s(t=>{let n=new Map(t);return n.set(e,a),n}),a.length},[n]),$e=(0,Q.useCallback)(e=>o.has(e),[o]),et=(0,Q.useCallback)(e=>{a(t=>t.filter(t=>t.id!==e))},[]),tt=(0,Q.useCallback)(()=>{a(e=>e.filter(e=>e.role!==`system`))},[]);return{messages:i,renderedMessages:(0,Q.useMemo)(()=>Ot(i,o),[i,o]),expandCompact:Ze,isCompactExpanded:$e,dismissMessage:et,clearErrors:tt,messagesLoading:c,versionMap:u,isStreaming:Me,phase:f,isReconnecting:m,connectingElapsed:g,pendingApproval:v,contextWindowPct:b,compactStatus:S,statusMessage:ne,sessionTitle:A,liveAccount:fe,model:F,setModel:Ve,effort:se,setEffort:Ue,thinking:B,setThinking:We,teamActivity:Te,teamMessages:De,markTeamRead:Ae,bashPartialOutput:ue,backgroundShells:w,killBackgroundShell:qe,findBackgroundShellByOutput:Je,sendMessage:Be,respondToApproval:Ge,cancelStreaming:Ke,reconnect:Ye,refetchMessages:Xe,isConnected:re&&ie===e}}var Bt=12e4;function Vt(e,t=`claude`,n){let r=JSON.stringify([e,t,n]),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(null),l=(0,Q.useRef)(0),u=(0,Q.useCallback)((i=!1)=>{if(!e)return Promise.resolve();let o=++l.current;s(!0);let c=i?`&refresh=1`:``,u=n?`&session=${encodeURIComponent(n)}`:``;return E.get(`${T(e)}/chat/usage?providerId=${t}${u}${c}`).then(e=>{o===l.current&&a({scope:r,usage:e??{},fetchedAt:e?.lastFetchedAt??null})}).catch(()=>{}).finally(()=>{o===l.current&&s(!1)})},[e,t,n,r]);(0,Q.useEffect)(()=>(a(null),s(!1),u(),c.current=setInterval(()=>u(),Bt),()=>{++l.current,c.current&&clearInterval(c.current)}),[u]);let d=(0,Q.useCallback)(()=>u(!0),[u]),f=i?.scope===r?i:null;return{usageInfo:f?.usage??{},usageLoading:o,lastFetchedAt:f?.fetchedAt??null,refreshUsage:d}}var Ht={damping:.7,stiffness:.05,mass:1.25},Ut=70,Wt=1e3/60,Gt=350,Kt=!1;globalThis.document?.addEventListener(`mousedown`,()=>{Kt=!0}),globalThis.document?.addEventListener(`mouseup`,()=>{Kt=!1}),globalThis.document?.addEventListener(`click`,()=>{Kt=!1});var qt=(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(!Kt)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<=Ut}}},[]),f=(0,Q.useCallback)((e={})=>{typeof e==`string`&&(e={animation:e}),e.preserveScrollPosition||l(!0);let t=Date.now()+(Number(e.wait)||0),n=Xt(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))/Wt;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:Xt(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=Jt(e=>{g.current?.removeEventListener(`scroll`,m),g.current?.removeEventListener(`wheel`,h),e?.addEventListener(`scroll`,m,{passive:!0}),e?.addEventListener(`wheel`,h,{passive:!0})},[]),_=Jt(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=Xt(s.current,t?s.current.resize:s.current.initial);f({animation:e,wait:!0,preserveScrollPosition:!0,duration:e===`instant`?void 0:Gt})}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 Jt(e,t){let n=(0,Q.useCallback)(t=>(n.current=t,e(t)),t);return n}var Yt=new Map;function Xt(...e){let t={...Ht},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 Yt.has(r)||Yt.set(r,Object.freeze(t)),n?`instant`:Yt.get(r)}var Zt=60,Qt=8,$t=1400;function en(e){if(e.scrollHeight<=e.clientHeight)return!1;let t=getComputedStyle(e).overflowY;return t===`auto`||t===`scroll`}function tn(e,t){let n=[],r=e.parentElement;for(;r&&r!==t;)en(r)&&n.push(r),r=r.parentElement;return n}function nn(){return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}function rn(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 an(e,t,n,r){let i=e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-n;e.scrollTo({top:i,behavior:r?`smooth`:`auto`})}function on(e,t){let n=rn(e,t);if(!n)return()=>{};let{el:r,level:i}=n;for(let t of tn(r,e))an(t,r,Qt,!1);an(e,r,Zt,!nn()),r.dataset.flash=i;let a=setTimeout(()=>{delete r.dataset.flash},$t);return()=>{clearTimeout(a),delete r.dataset.flash}}var sn=new Set([`Write`,`Edit`,`MultiEdit`,`NotebookEdit`]),cn={create:3,write:2,notebook:2,edit:1};function ln(e){return typeof e==`string`?e:``}function un(e,t){let n=0,r=0;for(let i of it(e,t))i.added?n+=i.count??0:i.removed&&(r+=i.count??0);return{added:n,removed:r}}function dn(e){return e&&/created successfully/i.test(e)?`create`:`write`}function fn(e,t,n){switch(e){case`Write`:{let e=ln(t.file_path);return e?{filePath:e,op:dn(n),fragments:[{oldStr:``,newStr:ln(t.content)}]}:null}case`Edit`:{let e=ln(t.file_path);return e?{filePath:e,op:`edit`,fragments:[{oldStr:ln(t.old_string),newStr:ln(t.new_string)}]}:null}case`MultiEdit`:{let e=ln(t.file_path);if(!e||!Array.isArray(t.edits))return null;let n=t.edits.filter(e=>!!e&&typeof e==`object`).map(e=>({oldStr:ln(e.old_string),newStr:ln(e.new_string)}));return n.length===0?null:{filePath:e,op:`edit`,fragments:n}}case`NotebookEdit`:{let e=ln(t.notebook_path)||ln(t.file_path);return e?{filePath:e,op:`notebook`,fragments:[{oldStr:``,newStr:ln(t.new_source)}]}:null}default:return null}}function pn(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),pn(n.children,t)}}}function mn(e,t,n,r){if(e)for(let i of e){if(i.type!==`tool_use`||(i.children?.length&&mn(i.children,!0,n,r),!sn.has(i.tool)))continue;let e=i.input&&typeof i.input==`object`?i.input:null;if(!e)continue;let a=fn(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)),cn[a.op]>cn[o.op]&&(o.op=a.op),t&&(o.viaSubagent=!0),a.fragments.forEach((e,n)=>{let{added:r,removed:a}=un(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 hn(e){let t=new Map;for(let n of e)pn(n.events,t);let n=new Map;for(let r of e)mn(r.events,!1,n,t);return[...n.values()]}function gn(e,t){let n=[];for(let r=t;r>=0&&e[r]?.role===`assistant`;r--)n.unshift(e[r]);return n}var $=n();function _n(e){try{return new Date(e).toLocaleString()}catch{return``}}function vn({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 yn({content:e}){let[t,n]=(0,Q.useState)(!1);return(0,$.jsx)(vn,{icon:t?(0,$.jsx)(o,{className:`size-3.5`}):(0,$.jsx)(y,{className:`size-3.5`}),label:t?`Copied`:`Copy`,title:`Copy message to clipboard`,onClick:()=>{Ie(e),n(!0),setTimeout(()=>n(!1),1500)}})}function bn({timestamp:e,content:t,className:n,children:r}){return(0,$.jsxs)(`div`,{className:A(`flex items-center gap-0.5 flex-wrap text-xs text-text-subtle select-none`,n),children:[(0,$.jsx)(`time`,{title:_n(e),className:`pr-1 tabular-nums`,children:ce(e)}),(0,$.jsx)(yn,{content:t}),r]})}function xn(e){let t=0,n=0;for(let r of e)t+=r.linesAdded,n+=r.linesRemoved;return{added:t,removed:n}}function Sn({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:A(`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 Cn(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}=M.getState();return n[r]?.activeTabId===t}var wn={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 Tn(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 En({added:e,removed:t,editCount:n,className:r}){return(0,$.jsxs)(`span`,{className:A(`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 Dn({change:e,dense:t,selected:n,onClick:r}){let i=wn[e.op],{base:a,dir:o}=Tn(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:A(`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:A(`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)(En,{added:e.linesAdded,removed:e.linesRemoved,editCount:e.editCount,className:`text-[11px]`}),(0,$.jsx)(c,{className:`size-[11px] text-text-subtle`})]})}var On=(0,Q.lazy)(()=>ne(()=>import(`./edit-diff-preview-xdDQvPhs.js`),__vite__mapDeps([0,1,2,3])));function kn({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)(se,{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)(On,{oldStr:n.oldStr,newStr:n.newStr,filePath:e.filePath})})})]},n.editRef??r))})}function An(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 jn=null;function Mn(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function Nn({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)(()=>(jn=s,o.current?.querySelector(`button`)?.focus(),()=>{jn===s&&(jn=null)}),[s]),(0,Q.useEffect)(()=>{let o=o=>{if(jn===s&&Cn(a.current)&&!Mn(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}=An(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)(Dn,{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)(En,{added:c.linesAdded,removed:c.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void Ie(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)(te,{className:`size-3.5`})})]}),(0,$.jsx)(kn,{change:c,onJump:t})]})]})})}function Pn(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t<0?e:e.slice(t+1)}function Fn({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 In({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)(I,{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)(Fn,{label:`Back to file list`,onClick:()=>o(null),children:(0,$.jsx)(q,{className:`size-4`})}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-xs font-medium text-text-primary`,children:Pn(s.filePath)}),(0,$.jsx)(En,{added:s.linesAdded,removed:s.linesRemoved,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Fn,{label:`Close`,onClick:l,children:(0,$.jsx)(te,{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 Ie(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)(se,{className:`size-3`}),`card`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,$.jsx)(kn,{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)(En,{added:t.added,removed:t.removed,className:`shrink-0 font-mono text-[11px]`}),(0,$.jsx)(Fn,{label:`Close`,onClick:l,children:(0,$.jsx)(te,{className:`size-4`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.map((e,t)=>(0,$.jsx)(Dn,{change:e,onClick:()=>o(t)},e.filePath))})]})})})}function Ln({timestamp:e,content:t,changes:n,onJumpToEdit:r}){let[i,a]=(0,Q.useState)(!1),o=ae(),s=(0,Q.useRef)(null),c=()=>{a(!1),s.current?.focus()},l=(0,$.jsx)(bn,{timestamp:e,content:t,className:`-mt-1.5`,children:n&&n.length>0&&(0,$.jsx)(Sn,{ref:s,count:n.length,totals:xn(n),open:i,onToggle:()=>i?c():a(!0)})});return!n||n.length===0?l:(0,$.jsxs)($.Fragment,{children:[l,o?(0,$.jsx)(In,{changes:n,totals:xn(n),open:i,onClose:c,onJump:r??(()=>{})}):i&&(0,$.jsx)(Nn,{changes:n,onJump:e=>{a(!1),r?.(e)},onClose:c})]})}function Rn(e){return e.inputTokens+e.cacheReadTokens+e.cacheWriteTokens}function zn(e){return e.inputTokens+e.cacheWriteTokens}var Bn=.5,Vn=.9,Hn={cache_expired:`the session's prompt cache had already lapsed, so PPM released its subprocess`,idle_timeout:`the session sat idle with no tab open long enough for PPM to release its subprocess`,warm_idle_cap:`too many idle sessions were holding a subprocess, so this one was released early`,tab_closed:`PPM shut the session's subprocess down when the last tab disconnected`,set_model:`the model was changed, which restarts the session`,stream_ended:`the session's subprocess had already exited`,resume:`the session was resumed on a new subprocess`};function Un(e){let t=zn(e),n=Rn(e);if(!e.coldStart||n<2e4)return{level:`ok`,wastedTokens:t,reason:``};let r=e.cacheHitRate<Bn?`bad`:e.cacheHitRate<Vn?`warn`:`ok`;if(r===`ok`)return{level:r,wastedTokens:t,reason:``};let i=e.coldReason?Hn[e.coldReason]??`the session restarted (${e.coldReason})`:null;return{level:r,wastedTokens:t,reason:i?`${qn(t)} of this session's transcript was re-sent uncached because ${i}.`:`${qn(t)} of this session's transcript was re-sent uncached.`}}var Wn=.1,Gn=1.25;function Kn(e){let t=Rn(e);if(t===0)return 1;let n=e.inputTokens+e.cacheWriteTokens*Gn+e.cacheReadTokens*Wn,r=t*Wn;return r>0?Math.max(1,n/r):1}function qn(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}k`:String(e)}function Jn({usage:e}){let[t,n]=(0,Q.useState)(!1),r=Un(e);if(r.level===`ok`)return null;let i=Kn(e),a=Rn(e),o=Math.round(e.cacheHitRate*100),c=r.level===`bad`;return(0,$.jsxs)(`div`,{className:`rounded-md border px-2.5 py-2 text-[11px] ${c?`border-warning/40 bg-warning/10`:`border-border bg-surface`}`,children:[(0,$.jsxs)(`button`,{onClick:()=>n(e=>!e),"aria-expanded":t,className:`flex w-full items-start gap-2 py-1 text-left text-text-secondary transition-colors hover:text-text-primary`,children:[(0,$.jsx)(U,{className:`mt-px size-3.5 shrink-0 ${c?`text-warning`:`text-text-subtle`}`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[`Costly turn — `,o,`% of a `,qn(a),`-token transcript came from cache, so it cost about`,` `,(0,$.jsxs)(`strong`,{className:`font-semibold`,children:[i.toFixed(1),`x`]}),` a fully cached turn.`]}),(0,$.jsx)(s,{className:`mt-px size-3.5 shrink-0 transition-transform ${t?`rotate-180`:``}`})]}),t&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-col gap-2 border-t border-border pt-2`,children:[r.reason&&(0,$.jsx)(`p`,{className:`text-text-secondary`,children:r.reason}),(0,$.jsxs)(`dl`,{className:`grid grid-cols-2 gap-x-3 gap-y-1 font-mono text-[10.5px] text-text-subtle`,children:[(0,$.jsx)(Yn,{label:`From cache`,value:`${qn(e.cacheReadTokens)} (${o}%)`}),(0,$.jsx)(Yn,{label:`Written to cache`,value:qn(e.cacheWriteTokens)}),(0,$.jsx)(Yn,{label:`Fresh input`,value:qn(e.inputTokens)}),(0,$.jsx)(Yn,{label:`Output`,value:qn(e.outputTokens)}),(0,$.jsx)(Yn,{label:`Model`,value:e.model||`unknown`}),(0,$.jsx)(Yn,{label:`Cost`,value:`$${e.costUsd.toFixed(4)}`})]}),(0,$.jsx)(`p`,{className:`text-text-subtle`,children:`A turn stays cached while the session keeps running. Closing the last tab of an idle session, switching model, or a retry all restart it, and the next turn re-sends the transcript at full price.`})]})]})}function Yn({label:e,value:t}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{className:`truncate`,children:e}),(0,$.jsx)(`dd`,{className:`truncate text-right text-text-secondary`,children:t})]})}function Xn(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(()=>{E.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 Zn=new Set([`TaskCreate`,`TaskUpdate`,`TaskStop`]);function Qn(e){let t=0;for(let n of e)if(n.events)for(let e of n.events)e.type===`tool_use`&&Zn.has(e.tool)&&t++;return t}var $n={completed:{icon:`✓`,cls:`text-success`},in_progress:{icon:`▶`,cls:`text-warning`},stopped:{icon:`■`,cls:`text-text-subtle`},pending:{icon:`○`,cls:`text-text-subtle`}};function er({projectName:e,sessionId:t,messages:n}){let r=(0,Q.useMemo)(()=>Qn(n),[n]),i=Xn(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 l=i.filter(e=>e.status===`completed`).length,u=i.length,f=u?Math.round(l/u*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)(c,{className:`size-3.5 shrink-0`}):(0,$.jsx)(s,{className:`size-3.5 shrink-0`}),(0,$.jsx)(d,{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:[l,`/`,u,` 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:`${f}%`}})})]}),!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)(tr,{task:e},e.id))})]})}function tr({task:e}){let t=$n[e.status]??$n.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 nr=/read the full transcript at:\s*(\S+\.jsonl)/i;function rr(e){return e.match(nr)?.[1]?.trim()??null}var ir=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 ar({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)(Ee,{projectName:e,onSelectSession:t,className:`w-full px-4`})]})}var or=3200,sr=1e3,cr={hasAbove:!1,atBottom:!0,idx:0,total:0};function lr({scrollElement:e,userIndices:t,scrollToBottom:n}){let r=ae(),[i,a]=(0,Q.useState)(cr),[o,c]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(0),f=(0,Q.useRef)(or),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(()=>c(!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=or,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=>()=>{Cn(t)&&(e(),f.current=sr,c(!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=A(`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`&&c(!1)},children:[(0,$.jsx)(`button`,{type:`button`,onClick:b,disabled:!i.hasAbove,"aria-label":`Jump to previous message`,className:C,children:(0,$.jsx)(l,{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)(s,{className:`size-[15px]`})}),(0,$.jsx)(`button`,{type:`button`,onClick:S,disabled:i.atBottom,"aria-label":`Jump to latest`,className:C,children:(0,$.jsx)(gt,{className:`size-[13px]`})})]}):(0,$.jsx)(`button`,{ref:m,type:`button`,onClick:()=>{f.current=or,g.current=!0,c(!0)},"aria-label":`Navigate messages`,"aria-expanded":!1,title:`Navigate messages`,className:A(`group flex items-center justify-center`,r?`size-11`:`size-[30px]`),children:(0,$.jsx)(`span`,{className:A(`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)(G,{className:`size-[15px]`})})})})}function ur({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)(q,{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)(c,{className:`size-3.5`})})]})}function dr(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 fr(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=e.customInputRef.current,a=!!i&&i.ownerDocument.activeElement===i;if(!a&&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(!a&&(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(!a){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`&&a&&e.customInputRef.current?.blur()},a=r.current;return a&&(a.addEventListener(`keydown`,i),a.setAttribute(`tabindex`,`0`),a.contains(a.ownerDocument.activeElement)||a.focus()),()=>{a?.removeEventListener(`keydown`,i)}},[e,t]),{focusedOption:t,setFocusedOption:n,containerRef:r}}function pr({questions:e,onSubmit:t,onSkip:n}){let r=(0,Q.useRef)(null),i=dr(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=fr({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 mr={"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 hr(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:mr[e]??e.replace(/^antml:/,``).replace(/-/g,` `),content:r[2].trim()})}return{cleanText:e.replace(n,``).trim(),tags:t}}function gr(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 _r(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 vr(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 yr(e){let t=[],n=e;for(;;){let e=n.match(/^\[Attached image \(contents included in this message\): (.+?)\]\n*/);if(e){t.push(e[1]),n=n.slice(e[0].length);continue}break}if(t.length>0){let e=yr(n);return{files:[...t,...e.files],text:e.text}}let r=n.match(/^\[Attached file: (.+?)\]\n*/);if(r)return{files:[r[1]],text:n.slice(r[0].length)};let i=n.match(/^\[Attached files:\n([\s\S]+?)\]\n*/);return i?{files:i[1].split(`
3
- `).map(e=>e.trim()).filter(Boolean),text:n.slice(i[0].length)}:{files:[],text:n}}function br(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 xr(e){let{idePath:t,cleanText:n}=vr(e),{blocks:r,remainingText:i}=br(n),a=yr(i),{cleanText:o,tags:s}=hr(a.text.replace(/<local-command-(?:stdout|stderr)>([\s\S]*?)<\/local-command-(?:stdout|stderr)>/g,`$1`)),{command:c,cleanText:l}=gr(o),{agent:u,cleanText:d}=_r(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 Sr(e){let{agent:t,body:n,command:r}=xr(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 Cr=ne(()=>import(`./markdown-renderer-DYFmMC_8.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,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49])),wr=(0,Q.lazy)(()=>Cr.then(e=>({default:e.MarkdownRenderer})));function Tr({messages:e,messagesLoading:t,keepStaleWhileLoading:n,pendingApproval:r,onApprovalResponse:a,isStreaming:o,phase:s,onSelectSession:c,connectingElapsed:l,statusMessage:u,compactStatus:d,projectName:f,onFork:m,onEdit:h,editingMsgId:g,sessionId:_,providerId:v,onNavigateVersion:y,versionMap:b,bashPartialOutput:x,onExpandCompact:S,isCompactExpanded:C,onDismissMessage:ee,onClearErrors:te}){let{scrollRef:T,contentRef:E,scrollToBottom:D,stopScroll:O,isAtBottom:ne}=qt({initial:`instant`,resize:`instant`}),k=(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]),A=!!r||o,[j,re]=(0,Q.useState)(null),M=(0,Q.useCallback)(e=>{T(e),re(e)},[T]),N=(0,Q.useRef)(new Map),ie=(0,Q.useMemo)(()=>{let e=N.current,t=new Map;for(let n=0;n<k.length;n++){let r=k[n];if(r.role!==`assistant`||k[n+1]?.role===`assistant`)continue;let i=`${r.id}:${r.events?.length??0}`,a=e.get(i);a||(a=hn(gn(k,n)),e.set(i,a)),a.length>0&&t.set(n,a)}return t},[k]),ae=(0,Q.useRef)(null),P=(0,Q.useCallback)(e=>{j&&(ae.current?.(),ae.current=on(j,e))},[j]);(0,Q.useEffect)(()=>()=>ae.current?.(),[]);let F=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let e=j;e&&F.current!=null&&(e.scrollTop=e.scrollHeight-F.current,F.current=null)},[k.length,j]),(0,Q.useLayoutEffect)(()=>{j&&D({animation:`instant`})},[_,j]);let I=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>{j&&j.clientHeight>0&&(I.current=ne)},[ne,j]),(0,Q.useEffect)(()=>{let e=j;if(!e)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=t===0&&n>0;t=n,r&&!I.current&&O()});return n.observe(e),()=>n.disconnect()},[j,O]);let oe=(0,Q.useCallback)((e,t)=>{m?.(e,t)},[m]),L=(0,Q.useCallback)((e,t,n)=>{h?.(e,t,n)},[h]),se=(0,Q.useCallback)(e=>{ee?.(e)},[ee]),R=(0,Q.useMemo)(()=>k.reduce((e,t)=>t.role===`system`?e+1:e,0),[k]),z=(0,Q.useMemo)(()=>k.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),[k]),B=(0,Q.useCallback)(()=>{if(!S||!C)return null;for(let e of k){if(C(e.id))continue;let t=rr(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=rr(t.content||``);if(n)return{id:e.id,jsonlPath:n}}}}return null},[k,S,C])(),ce=!!B,[le,V]=(0,Q.useState)(!1),H=(0,Q.useCallback)(async()=>{if(!B||!S||le)return;let e=j;F.current=e?e.scrollHeight-e.scrollTop:null,V(!0);try{await S(B.id,B.jsonlPath)}finally{V(!1)}},[B,S,le,j]);return(0,Q.useEffect)(()=>{let e=j;if(!e||!ce)return;let t=()=>{e.scrollTop<200&&!le&&H()};return e.addEventListener(`scroll`,t,{passive:!0}),()=>e.removeEventListener(`scroll`,t)},[j,ce,le,H]),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)(ar,{projectName:f||``,onSelectSession:c||(()=>{})}):(0,$.jsxs)(`div`,{className:`relative flex-1 overflow-hidden flex flex-col min-h-0`,children:[(0,$.jsx)(er,{projectName:f,sessionId:_,messages:e}),R>1&&te&&(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:te,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)(p,{className:`size-3.5`}),`Clear all errors (`,R,`)`]})}),le&&(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)(w,{className:`size-3 animate-spin`}),`Loading previous conversation...`]}),(0,$.jsx)(`div`,{ref:M,[tt]:``,className:`flex-1 overflow-y-auto overflow-x-hidden [overflow-anchor:none]`,style:{WebkitOverflowScrolling:`touch`,overscrollBehavior:`contain`},children:(0,$.jsxs)(`div`,{ref:E,className:`w-full`,children:[k.map((e,t)=>{let n=t>0?k[t-1]:void 0,r=e.role===`user`?k.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=k[t+1],c=e.role===`assistant`&&s?.role!==`assistant`,l;if(c){let e=[];for(let n=t;n>=0&&k[n].role===`assistant`;n--){let t=Er(k[n]);t&&e.unshift(t)}l=e.join(`
4
-
5
- `)}return(0,$.jsx)(`div`,{"data-msg-index":t,className:`px-4 pt-4 select-none`,children:(0,$.jsx)(ir,{fallbackContent:e.content,children:(0,$.jsx)(Dr,{message:e,isStreaming:o&&e.id.startsWith(`streaming-`),isLastAssistantInTurn:c,turnCopyText:l,turnChanges:c?ie.get(t):void 0,onJumpToEdit:P,projectName:f,onFork:e.role===`user`&&m?oe:void 0,onEdit:e.role===`user`&&h?L:void 0,isEditing:a,onDismiss:e.role===`system`&&ee?se:void 0,prevMsgId:n?.sdkUuid??n?.id,sessionId:_,providerId:v,versionGroup:i,onNavigateVersion:y,versionNavDisabled:o,bashPartialOutput:x})})},e.id)}),A&&(0,$.jsxs)(`div`,{className:`px-4 pt-4 pb-4 space-y-4 select-none`,children:[r&&(r.tool===`AskUserQuestion`?(0,$.jsx)(Qr,{approval:r,onRespond:a}):(0,$.jsx)(Zr,{approval:r,onRespond:a})),o&&(0,$.jsx)(qr,{lastMessage:e[e.length-1],phase:s,elapsed:l,statusMessage:d===`compacting`?`Compacting messages...`:u})]})]})}),(0,$.jsx)(lr,{scrollElement:j,userIndices:z,scrollToBottom:D})]})}function Er(e){return e.events?.length?e.events.filter(e=>e.type===`text`).map(e=>e.content).join(``):e.content}var Dr=(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:d,sessionId:f,providerId:m,versionGroup:h,onNavigateVersion:g,versionNavDisabled:_,bashPartialOutput:v}){if(e.role===`user`){let t=s?()=>s(e.content,d):void 0,n=c?()=>c(e.content,d,e.id):void 0;return(0,$.jsx)(Mr,{content:e.content,messageId:e.id,timestamp:e.timestamp,projectName:o,onFork:t,onEdit:n,isEditing:l,sessionId:f,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)(me,{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)(p,{className:`size-4`})})]}):(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[e.events&&e.events.length>0?(0,$.jsx)(Wr,{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)(Xr,{content:e.content,projectName:o})}),!t&&n&&e.usage&&(0,$.jsx)(Jn,{usage:e.usage}),!t&&n&&(0,$.jsx)(Ln,{timestamp:e.timestamp,content:r??Er(e),changes:i,onJumpToEdit:a})]})}),Or=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`]);function kr(e,t){let n=re(e);return`/api/project/${encodeURIComponent(t??`_`)}/chat/uploads/${encodeURIComponent(n)}`}function Ar(e){let t=e.lastIndexOf(`.`);return t===-1?!1:Or.has(e.slice(t).toLowerCase())}var jr=new Set([`task-notification`,`environment_details`,`local-command-caveat`]);function Mr({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)(()=>xr(e),[e]),S=_.some(e=>jr.has(e.name)),[C,w]=(0,Q.useState)(!1),[ee,te]=(0,Q.useState)(!1),T=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=T.current;if(!e)return;let t=()=>te(e.scrollHeight>e.clientHeight+2);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[g]),(0,$.jsxs)(`div`,{className:A(`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:A(`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)(Pr,{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)(St,{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)(Rr,{path:b,projectName:r})]}),h.length>0&&(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:h.map((e,t)=>Ar(e)?(0,$.jsx)(Ur,{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)(R,{className:`size-3 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-32`,children:re(e)})]},t))}),y.length>0&&(0,$.jsx)(`div`,{className:`space-y-1.5`,children:y.map((e,t)=>(0,$.jsx)(Nr,{content:e},t))}),g&&(0,$.jsx)(`div`,{ref:T,className:A(`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)(Br,{text:g,projectName:r}):(0,$.jsx)(zr,{text:g})}),(ee||C)&&(0,$.jsx)(`button`,{onClick:()=>w(!C),className:A(`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)(l,{className:`size-3`}),`Show less`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(s,{className:`size-3`}),`Show more`]})}),!S&&p&&(0,$.jsx)(ur,{group:f,onNavigate:p,disabled:m})]}),!S&&(0,$.jsxs)(bn,{timestamp:n,content:e,children:[o&&(0,$.jsx)(vn,{icon:(0,$.jsx)(Le,{className:`size-3.5`}),label:`Edit`,title:`Edit this message (continue in the same tab)`,onClick:o}),a&&(0,$.jsx)(vn,{icon:(0,$.jsx)(we,{className:`size-3.5`}),label:`Fork`,title:`Retry from this message (fork into a new tab)`,onClick:a})]})]})}function Nr({content:e}){let[t,n]=(0,Q.useState)(!1);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(!t),className:A(`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)(Se,{className:`size-3.5 shrink-0`}),(0,$.jsx)(`span`,{children:`Terminal output`}),(0,$.jsx)(s,{className:A(`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 Pr({tags:e}){return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,$.jsx)(Fr,{tag:e},t))})}function Fr({tag:e}){let[t,n]=(0,Q.useState)(!1);return e.name===`task-notification`?(0,$.jsx)(Lr,{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)(L,{className:`size-2.5`}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(c,{className:A(`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 Ir(e,t){return e.match(RegExp(`<${t}>([\\s\\S]*?)</${t}>`))?.[1]?.trim()||void 0}function Lr({content:e}){let[t,n]=(0,Q.useState)(!1),r=Ir(e,`status`),i=Ir(e,`summary`),a=Ir(e,`output-file`),o=Ir(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)(oe,{className:`size-2.5 text-success`}):(0,$.jsx)(p,{className:`size-2.5 text-warning`}),(0,$.jsx)(`span`,{className:`truncate max-w-80`,children:i??`Task notification`}),(0,$.jsx)(c,{className:A(`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)(Rr,{path:a}),o&&(0,$.jsx)(`div`,{className:`text-[11px] text-text-subtle/80 max-h-60 overflow-y-auto leading-relaxed`,children:(0,$.jsx)(Xr,{content:o})})]})]})}function Rr({path:e,projectName:t}){return(0,$.jsxs)(`button`,{type:`button`,onClick:(0,Q.useCallback)(()=>{let n=ie.getState().openTab,r=t??N.getState().activeProject?.name,i=re(e),a={filePath:e};r&&(a.projectName=r),E.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)(R,{className:`size-2.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate max-w-60`,children:re(e)}),(0,$.jsx)(B,{className:`size-2 shrink-0 opacity-50`})]})}function zr({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 Br({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)(Rr,{path:e.value,projectName:t},n):(0,$.jsx)(`span`,{children:e.value},n))})}var Vr=new Map;function Hr(e){let[t,n]=(0,Q.useState)(()=>Vr.get(e)?.url??null),[r,i]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let t=Vr.get(e);if(t){n(t.url);return}let r=!1,a=D();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);Vr.set(e,{url:i}),n(i)}).catch(()=>{r||i(!0)}),()=>{r=!0}},[e]),{blobUrl:t,error:r}}function Ur({filePath:e,projectName:t}){let{blobUrl:n,error:r}=Hr(kr(e,t)),i=Ve(e=>e.open),a=re(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:e=>n&&i(n,a,nt(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,[rt]:``,className:`size-4 rounded-sm object-cover shrink-0`}):r?(0,$.jsx)(Z,{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 Wr({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}if(n.type===`text`)a+=n.content;else if(n.type===`tool_use`){let e=n.toolUseId,t=e?i.find(t=>t.kind===`tool`&&t.tool.type===`tool_use`&&t.tool.toolUseId===e):void 0;if(t){t.tool=n;continue}a&&=(i.push({kind:`text`,content:a}),``),i.push({kind:`tool`,tool:n})}else 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)(Gr,{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)(Kr,{content:e.content,animate:r,projectName:n})},`text-${a}`)}return(0,$.jsx)(f,{tool:e.tool,result:e.result,completed:e.completed,projectName:n,bashPartialOutput:r},`tool-${a}`)})})}function Gr({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)(w,{className:`size-3 animate-spin`}):(0,$.jsx)(c,{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 Kr({content:e,animate:t,projectName:n}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Xr,{content:e,projectName:n,isStreaming:t}),t&&(0,$.jsx)(`span`,{className:`text-text-subtle text-sm animate-pulse`,children:`Thinking...`})]})}function qr({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)(w,{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 Jr=/<teammate-message[^>]*>[\s\S]*?<\/teammate-message>/g;function Yr(e){return e.replace(Jr,``).replace(/\n{3,}/g,`
6
-
7
- `).trim()}function Xr({content:e,projectName:t,isStreaming:n}){let r=Yr(e);return r?(0,$.jsx)(ir,{fallbackContent:r,children:(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`animate-pulse h-4 bg-muted rounded`}),children:(0,$.jsx)(wr,{content:r,projectName:t,codeActions:!0,isStreaming:n})})}):null}function Zr({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)(J,{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 Qr({approval:e,onRespond:t}){return(0,$.jsx)(pr,{questions:e.input.questions??[],onSubmit:n=>t(e.requestId,!0,n),onSkip:()=>t(e.requestId,!1)})}function $r({shells:e,onKill:t}){let n=He(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)(w,{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)(Se,{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)(S,{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)(H,{className:`size-3.5`})})]},e.shellId))})}function ei(e){if(!e)return;let t=e.split(`:`).pop();return t&&t!==`general-purpose`?t:e}function ti(e,t){if(!e)return;let n=new Date(e).getTime(),r=t?new Date(t).getTime():Date.now();if(!Number.isFinite(n)||!Number.isFinite(r)||r<n)return;let i=Math.floor((r-n)/1e3),a=Math.floor(i/3600),o=Math.floor(i%3600/60);return a>0?`${a}h ${o}m`:o>0?`${o}m`:`${i}s`}function ni(e){return e.lastTool?e.lastToolArg?`${e.lastTool}: ${e.lastToolArg}`:e.lastTool:e.lastNarrative??e.description}function ri({teamName:e,members:t,projectName:n}){let r=at(),i=t.filter(e=>e.workState===`working`);return!e||i.length===0?null:(0,$.jsx)(`div`,{className:`shrink-0 border-t border-border bg-surface-elevated/60 px-2 py-1.5 space-y-1`,children:i.map(t=>{let i=ni(t),a=ti(t.startedAt),o=ei(t.agentType);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r({teamName:e,memberName:t.name,projectName:n}),className:`flex w-full items-center gap-2 rounded px-1 py-1.5 min-h-[36px] text-left text-xs hover:bg-surface transition-colors`,title:`Open ${t.name}'s work session`,children:[(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)(ge,{className:`size-3.5 shrink-0 text-accent-2`}),(0,$.jsx)(`span`,{className:`font-medium text-text-primary shrink-0`,children:t.name}),!!o&&(0,$.jsx)(`span`,{className:`text-text-3 shrink-0 hidden sm:inline`,children:o}),!!i&&(0,$.jsx)(`span`,{className:`flex-1 truncate text-text-subtle`,title:i,children:i}),!!a&&(0,$.jsx)(`span`,{className:`ml-auto shrink-0 text-text-3 font-mono`,children:a})]},t.name)})})}var ii=5e3;function ai(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1),l=(0,Q.useCallback)(async e=>{if(e){s(!0);try{let t=await E.get(`/api/teams/${encodeURIComponent(e)}/activity`);if(c.current)return;r(t?.members??[]),a(t?.outbound??[])}catch{}finally{c.current||s(!1)}}},[]);return(0,Q.useEffect)(()=>{if(c.current=!1,!t||!e)return r([]),a([]),()=>{c.current=!0};l(e);let n=setInterval(()=>void l(e),ii);return()=>{c.current=!0,clearInterval(n)}},[e,t,l]),{members:n,outbound:i,loading:o,refresh:(0,Q.useCallback)(()=>void l(e),[l,e])}}function oi(){let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function si(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`&&oi()!==null;return{isListening:t,interimText:r,start:(0,Q.useCallback)(t=>{let r=oi();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 ci=2e3;function li(e,t,n=ci){if(!(e>0)||!(t>0))return null;let r=Math.max(e,t);if(r<n)return null;let i=n-1,a=i/r;return{width:e>=t?i:Math.max(1,Math.round(e*a)),height:t>e?i:Math.max(1,Math.round(t*a))}}var ui=4096;function di(e,t){let n=new TextEncoder().encode(t);outer:for(let t=0;t+n.length<=e.length;t++){for(let r=0;r<n.length;r++)if(e[t+r]!==n[r])continue outer;return!0}return!1}function fi(e,t){return e===`image/gif`?!0:e===`image/webp`?di(t,`ANIM`):e===`image/png`||e===`image/apng`?di(t,`acTL`):!1}async function pi(e){if(e.type===`image/gif`)return!0;if(e.type!==`image/webp`&&e.type!==`image/png`&&e.type!==`image/apng`)return!1;try{let t=new Uint8Array(await e.slice(0,ui).arrayBuffer());return fi(e.type,t)}catch{return!0}}var mi=1600,hi=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function gi(e){return e===`image/jpeg`||e===`image/webp`?e:`image/png`}async function _i(e,t=mi){let n={kind:`asis`,file:e};if(!e.type.startsWith(`image/`)||e.type===`image/svg+xml`||typeof createImageBitmap!=`function`||typeof document>`u`)return n;let r;try{r=await createImageBitmap(e)}catch{return n}let i={width:r.width,height:r.height},a=li(i.width,i.height,t+1);if(a&&await pi(e))return r.close?.(),Math.max(i.width,i.height)<2e3&&hi.has(e.type)?{kind:`inlineable`,file:e,from:i}:{kind:`asis`,file:e,from:i};if(!a)return r.close?.(),hi.has(e.type)?{kind:`inlineable`,file:e,from:i}:{kind:`asis`,file:e,from:i};let o=r;try{try{o=await createImageBitmap(e,{resizeWidth:a.width,resizeHeight:a.height,resizeQuality:`high`}),r.close?.()}catch{o=r}let t=document.createElement(`canvas`);t.width=a.width,t.height=a.height;let n=t.getContext(`2d`);if(!n)return{kind:`asis`,file:e,from:i};n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(o,0,0,a.width,a.height);let s=gi(e.type),c=await new Promise(e=>t.toBlob(e,s,.92));if(!c||c.size===0)return{kind:`asis`,file:e,from:i};let l=s===e.type?e.name:e.name.replace(/\.[^.]+$/,``)+`.png`;return{kind:`scaled`,file:new File([c],l,{type:s}),from:i,to:a}}catch{return{kind:`asis`,file:e,from:i}}finally{o.close?.()}}var vi=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function yi(e){return vi.has(e.type)}function bi({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:A(`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)(Se,{className:`size-3.5 shrink-0 text-text-subtle`}):e.isImage?(0,$.jsx)(Z,{className:`size-3.5 shrink-0 text-text-subtle`}):(0,$.jsx)(R,{className:`size-3.5 shrink-0 text-text-subtle`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.name}),e.textContent&&(0,$.jsx)(s,{className:A(`size-3 shrink-0 text-text-subtle transition-transform`,n===e.id&&`rotate-180`)}),e.status===`uploading`?(0,$.jsx)(w,{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:`!`}):e.resized?(0,$.jsxs)(`span`,{className:`shrink-0 text-[10px] text-text-subtle`,title:`Shrunk from ${e.resized.from.width}x${e.resized.from.height} to ${e.resized.to.width}x${e.resized.to.height}`,children:[e.resized.to.width,`×`,e.resized.to.height]}):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)(te,{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:xi(i.textContent)})]})}function xi(e){let t=e.trim(),n=t.match(/^```\w*\n([\s\S]*?)\n```$/);return n?n[1]:t}function Si(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 Ci=[{id:`default`,label:`Ask before edits`,icon:C,description:`Claude will ask for approval before making each edit`},{id:`acceptEdits`,label:`Edit automatically`,icon:_,description:`Claude will edit files without asking first`},{id:`plan`,label:`Plan mode`,icon:u,description:`Claude will present a plan before editing`},{id:`bypassPermissions`,label:`Bypass permissions`,icon:ee,description:`Claude will not ask before running commands`}];function wi(e){return Ci.find(t=>t.id===e)?.label??`Unknown`}function Ti(e){return Ci.find(t=>t.id===e)?.icon??C}function Ei({value:e,onChange:t,open:n,onOpenChange:r}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&r(!1)},t=i.current?.ownerDocument??document;return t.addEventListener(`mousedown`,e),()=>t.removeEventListener(`mousedown`,e)},[n,r]),(0,Q.useEffect)(()=>{n&&(a.current=Ci.findIndex(t=>t.id===e),a.current<0&&(a.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;a.current=(a.current+t+Ci.length)%Ci.length,(i.current?.querySelector(`[data-idx="${a.current}"]`))?.focus()}if(e.key===`Enter`){e.preventDefault();let n=Ci[a.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:Ci.map((n,i)=>{let a=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)(a,{className:`size-4 mt-0.5 shrink-0 text-text-secondary`}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium text-text-primary`,children:n.label}),(0,$.jsx)(`div`,{className:`text-xs text-text-subtle leading-snug`,children:n.description})]}),s&&(0,$.jsx)(o,{className:`size-4 mt-0.5 shrink-0 text-primary`})]},n.id)})})]}):null}var Di=[{label:`Low`,value:`low`},{label:`Medium`,value:`medium`},{label:`High`,value:`high`,default:!0},{label:`Extra`,value:`xhigh`},{label:`Max`,value:`max`}];function Oi(e){return e?Di.find(t=>t.value===e)?.label??e:``}function ki(e,t){let n=Oi(t);return n?`${e} · ${n}`:e}function Ai(e){return e.replace(/^Claude\s+/i,``)}var ji=Di.find(e=>e.default).value;function Mi({model:e,effort:t,thinking:n,onModelChange:r,onEffortChange:i,onThinkingChange:s,projectName:c,providerId:l,disabled:u}){let[d,f]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(null),g=ae();(0,Q.useEffect)(()=>{!c||!l||E.get(`${T(c)}/chat/providers/${l}/models`).then(f).catch(()=>{})},[c,l]),(0,Q.useEffect)(()=>{u&&m(!1)},[u]),(0,Q.useEffect)(()=>{if(!p||g)return;let e=e=>{h.current&&!h.current.contains(e.target)&&m(!1)},t=h.current?.ownerDocument??document;return t.addEventListener(`mousedown`,e),()=>t.removeEventListener(`mousedown`,e)},[p,g]);let _=d.find(t=>t.value===e),y=_?Ai(_.label):e?Ai(e):`Model`,b=t??ji,x=d.length>1,S=ki(y,b),C=e=>{e(),g||m(!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)(Ni,{children:`Model`}),d.map(t=>(0,$.jsxs)(Fi,{active:t.value===e,onClick:()=>C(()=>r(t.value)),children:[(0,$.jsx)(`span`,{className:`flex-1 truncate`,children:Ai(t.label)}),t.value===e&&(0,$.jsx)(o,{className:`size-4 shrink-0 text-primary`})]},t.value))]}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 py-1`,children:[(0,$.jsx)(Ni,{children:`Effort`}),Di.map(e=>(0,$.jsxs)(Fi,{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)(o,{className:`size-4 shrink-0 text-primary`})]},e.value)),(0,$.jsx)(Pi,{}),(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)(a,{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:u,onClick:e=>{e.stopPropagation(),u||m(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:u?`Can't change while running`:S,children:[(0,$.jsx)(v,{className:`h-3.5 w-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`max-w-[140px] truncate`,children:S}),n&&(0,$.jsx)(a,{className:`h-3 w-3 shrink-0`})]}),p&&!u&&(g?(0,$.jsx)(I,{open:p,onClose:()=>m(!1),children:(0,$.jsx)(`div`,{className:`px-1 pb-2`,children:w})}):(0,$.jsx)(`div`,{ref:h,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 Ni({children:e}){return(0,$.jsx)(`div`,{className:`px-3 py-1.5 text-xs font-medium text-text-secondary`,children:e})}function Pi(){return(0,$.jsx)(`div`,{className:`my-1 border-t border-border`})}function Fi({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 Ii=6e4,Li=new Map;function Ri(e,t,n){let r=`${e}\0${t??``}\0${n??``}`,i=Li.get(r);if(i&&Date.now()<i.expiresAt)return i.promise;let a=new URLSearchParams;t&&a.set(`providerId`,t),n&&a.set(`sessionId`,n);let o=a.size>0?`?${a}`:``,s=E.get(`${T(e)}/chat/slash-items${o}`).then(e=>({items:e.items??[],recentNames:e.recentNames??[]})).catch(e=>{throw Li.get(r)?.promise===s&&Li.delete(r),e});return Li.set(r,{promise:s,expiresAt:Date.now()+Ii}),s}function zi(e){if(!e){Li.clear();return}let t=`${e}\0`;for(let e of Li.keys())e.startsWith(t)&&Li.delete(e)}async function Bi(e){try{let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result??``)),r.onerror=()=>n(r.error),r.readAsDataURL(e)}),n=t.indexOf(`,`),r=n>=0?t.slice(n+1):``;return r?{data:r,mediaType:e.type||`image/png`}:void 0}catch{return}}var Vi=(0,Q.memo)(function({tabId:e,onSend:t,isStreaming:n,onCancel:r,disabled:a,projectName:o,onSlashStateChange:s,onSlashItemsLoaded:c,slashSelected:l,onFileStateChange:u,onFileItemsLoaded:d,fileSelected:f,externalFiles:p,externalPaths:m,onExternalPathsConsumed:h,initialValue:g,clearSignal:_,onContentChange:v,getUserHistory:y,autoFocus:b,permissionMode:x,onModeChange:S,providerId:C,sessionId:ee,onProviderChange:E,model:O,onModelChange:ne,effort:k,onEffortChange:A,thinking:re,onThinkingChange:M}){let N=(0,Q.useRef)(g??``),[ie,ae]=(0,Q.useState)(()=>(g??``).trim().length>0),[P,F]=(0,Q.useState)([]),[I,oe]=(0,Q.useState)(null),[L,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(!1),[ce,le]=(0,Q.useState)(`next`),V=(0,Q.useRef)(null),U=(0,Q.useRef)(null),ue=(0,Q.useRef)(null),de=(0,Q.useRef)([]),fe=(0,Q.useRef)([]),pe=(0,Q.useRef)(0),W=(0,Q.useRef)(!1),me=(0,Q.useRef)(!1),ge=(0,Q.useRef)(typeof CSS>`u`||!CSS.supports(`field-sizing`,`content`)),G=(0,Q.useCallback)(e=>{N.current=e,V.current&&(V.current.value=e),U.current&&(U.current.value=e),ae(e.trim().length>0)},[]),K=(0,Q.useCallback)(()=>window.matchMedia(`(min-width: 768px)`).matches?V.current:U.current,[]),_e=(0,Q.useRef)(-1),ve=(0,Q.useCallback)(e=>{let t=Si(y?.()??[],_e.current,e);if(!t)return!1;_e.current=t.index;let{agent:n,text:r}=Sr(t.text);oe(n),G(r);let i=K();return i?(i.focus(),requestAnimationFrame(()=>{i.selectionStart=i.selectionEnd=r.length}),ge.current&&(i.style.height=`auto`,i.style.height=Math.min(i.scrollHeight,i===U.current?80:160)+`px`),!0):!0},[y,G,K]),q=si(),ye=(0,Q.useRef)(``),be=(0,Q.useCallback)(e=>{let t=ye.current;G(t?t+` `+e:e),ge.current&&requestAnimationFrame(()=>{let e=K();e&&(e.style.height=`auto`,e.style.height=Math.min(e.scrollHeight,160)+`px`)})},[G,K]),xe=(0,Q.useCallback)(()=>{q.isListening?q.stop():(ye.current=N.current.trim(),q.start(be))},[q.isListening,q.start,q.stop,be]);(0,Q.useEffect)(()=>{let e=()=>{q.supported&&Cn(K())&&xe()};return window.addEventListener(`toggle-voice-input`,e),()=>window.removeEventListener(`toggle-voice-input`,e)},[q.supported,xe,K]),(0,Q.useEffect)(()=>{let t=t=>{let{text:n,label:r,targetTabId:i}=t.detail??{};if(!n||(i?i!==e:!Cn(K())))return;window.dispatchEvent(new Event(st));let a={id:j(),name:r??`Terminal output`,file:new File([],`terminal-output.txt`),isImage:!1,textContent:n,status:`ready`};F(e=>[...e,a]),K()?.focus()};return window.addEventListener(ot,t),()=>window.removeEventListener(ot,t)},[K,e]),(0,Q.useEffect)(()=>{g&&!N.current&&(G(g),setTimeout(()=>{let e=V.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)},50))},[g]),(0,Q.useEffect)(()=>{_&&G(``)},[_]),(0,Q.useEffect)(()=>{b&&setTimeout(()=>{K()?.focus()},100)},[]);let Se=(0,Q.useCallback)(()=>{if(!o){de.current=[],c?.([],[]);return}Ri(o,C,ee).then(e=>{de.current=e.items,c?.(e.items,e.recentNames)}).catch(()=>{de.current=[],c?.([],[])})},[o,C,ee,c]);(0,Q.useEffect)(()=>{Se()},[Se]),(0,Q.useEffect)(()=>{let e=()=>{zi(o),Se()};return window.addEventListener(`ppm:slash-items-refresh`,e),()=>window.removeEventListener(`ppm:slash-items-refresh`,e)},[Se,o]),(0,Q.useEffect)(()=>{let e=()=>{if(!o){fe.current=[],d?.([]);return}let{fileIndex:e}=Ne.getState(),t=e.map(e=>({name:e.name,path:e.path,type:e.type}));fe.current=t,d?.(t)};e();let t=Ne.getState().fileIndex,n=Ne.getState().indexStatus;return Ne.subscribe(r=>{(r.fileIndex!==t||r.indexStatus!==n)&&(t=r.fileIndex,n=r.indexStatus,e())})},[o]),(0,Q.useEffect)(()=>{if(!l)return;let e=K();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(l.type===`agent`){let t=r.replace(/(?:^|\s)\/\S*$/,a);oe(l.name),G(t+i),s?.(!1,``),W.current=!1,e.focus(),setTimeout(()=>{e.selectionStart=e.selectionEnd=t.length},0);return}let o=r.replace(/(?:^|\s)\/\S*$/,e=>`${a(e)}${l.invokeSigil??`/`}${l.name} `);G(o+i),s?.(!1,``),W.current=!1,u?.(!1,``),me.current=!1,e.focus(),setTimeout(()=>{e.selectionStart=e.selectionEnd=o.length},0)},[l]),(0,Q.useEffect)(()=>{if(!f)return;let e=K();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;G(r.slice(0,t)+`@${f.path} `+i);let n=t+f.path.length+2;setTimeout(()=>{e.selectionStart=e.selectionEnd=n,e.focus()},0)}else{let n=t+`@${f.path} `;G(n),setTimeout(()=>{e.selectionStart=e.selectionEnd=n.length,e.focus()},0)}u?.(!1,``),me.current=!1},[f]),(0,Q.useEffect)(()=>{!p||p.length===0||Y(p)},[p]),(0,Q.useEffect)(()=>{if(!m||m.length===0)return;let e=m.map(e=>`@${e}`).join(` `),t=N.current;G(t+(t.length>0&&!t.endsWith(` `)?` `:``)+e+` `),K()?.focus(),h?.()},[m]);let J=(0,Q.useCallback)(async e=>{if(!o)return;let t=e.split(/[\\/]/).pop();if(t)try{let e={},n=D();n&&(e.Authorization=`Bearer ${n}`),await fetch(`${T(o)}/chat/uploads/${encodeURIComponent(t)}`,{method:`DELETE`,headers:e})}catch{}},[o]),Ce=(0,Q.useCallback)(async e=>{if(!o)return null;try{let t=new FormData;t.append(`files`,e);let n={},r=D();r&&(n.Authorization=`Bearer ${r}`);let i=await(await fetch(`${T(o)}/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}},[o]),Y=(0,Q.useCallback)(async e=>{for(let t of e){let e=j(),n=yi(t),r={id:e,name:t.name,file:t,isImage:n,previewUrl:n?URL.createObjectURL(t):void 0,status:`uploading`};F(e=>[...e,r]);try{let i=n?await _i(t):null,a=i?.file??t,o=n&&a!==t?URL.createObjectURL(a):void 0,s=await Ce(a),c=i&&i.kind!==`asis`?await Bi(a):void 0,l=!!c&&c.data.length<=Ct.maxBase64PerImage;o&&r.previewUrl&&URL.revokeObjectURL(r.previewUrl),F(t=>t.map(t=>t.id===e?{...t,file:a,...o&&{previewUrl:o},serverPath:s??void 0,imageData:l?c:void 0,resized:i?.to?{from:i.from,to:i.to}:void 0,status:s||l?`ready`:`error`}:t))}catch{F(t=>t.map(t=>t.id===e?{...t,status:`error`}:t))}}(U.current??V.current)?.focus()},[Ce]),we=(0,Q.useCallback)(e=>{F(t=>{let n=t.find(t=>t.id===e);return n?.previewUrl&&URL.revokeObjectURL(n.previewUrl),n?.serverPath&&J(n.serverPath),t.filter(t=>t.id!==e)})},[J]),Te=(0,Q.useCallback)(()=>{let e=N.current.trim(),r=P.filter(e=>e.status===`ready`);if(!e&&r.length===0&&!I){B(!1);return}let i=I?`Use the ${I} agent to ${e}`.trimEnd():e;s?.(!1,``),W.current=!1,u?.(!1,``),me.current=!1,q.isListening&&q.stop(),t(i,r,n?ce:void 0),G(``);for(let e of P)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);F([]),oe(null),B(!1),le(`next`),_e.current=-1,ge.current&&(V.current&&(V.current.style.height=`auto`),U.current&&(U.current.style.height=`auto`))},[P,I,t,s,u,n,ce,G]),Ee=(0,Q.useCallback)(()=>{if(!a){if(P.some(e=>e.status===`uploading`)){(N.current.trim()||P.some(e=>e.status!==`error`))&&B(!0);return}Te()}},[P,a,Te]);(0,Q.useEffect)(()=>{z&&(P.some(e=>e.status===`uploading`)||Te())},[z,P,Te]);let De=(0,Q.useCallback)(e=>{if(e.key===`Enter`&&!e.shiftKey){e.preventDefault(),Ee();return}if((e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){if(!(_e.current>=0)&&(e.key===`ArrowDown`||N.current!==``||I))return;ve(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(x??`bypassPermissions`)+1)%t.length];S?.(n)}},[Ee,x,S,ve,I]),Oe=(0,Q.useCallback)((e,t)=>{let n=e.slice(0,t),r=n.includes(`/`),i=n.includes(`@`);if(!r&&!i){W.current&&=(s?.(!1,``),!1),me.current&&=(u?.(!1,``),!1);return}if(r){let e=n.match(/(?:^|\s)\/(\S*)$/);if(e&&de.current.length>0){W.current||Se();let t=e[1]??``;s?.(!0,t),W.current=!0,me.current&&=(u?.(!1,``),!1);return}}if(i){let e=n.match(/@(\S*)$/);if(e&&fe.current.length>0){u?.(!0,e[1]??``),me.current=!0,W.current&&=(s?.(!1,``),!1);return}}W.current&&=(s?.(!1,``),!1),me.current&&=(u?.(!1,``),!1)},[s,u,Se]),ke=(0,Q.useCallback)(e=>{let t=e.target,n=t.value;N.current=n,_e.current=-1;let r=t===V.current?U.current:V.current;r&&(r.value=n),ae(n.trim().length>0),Oe(n,t.selectionStart),v?.(n,P.filter(e=>e.status===`ready`&&e.serverPath).map(e=>({name:e.name,path:e.serverPath}))),ge.current&&(pe.current&&cancelAnimationFrame(pe.current),pe.current=requestAnimationFrame(()=>{pe.current=0,t.style.height=`auto`,t.style.height=Math.min(t.scrollHeight,t===U.current?80:160)+`px`}))},[Oe,v,P]),Ae=(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(),Y(n))},[Y]),je=(0,Q.useCallback)(e=>{e.preventDefault();let t=e.dataTransfer.getData(`application/x-ppm-path`);if(t){let e=N.current;G(e+(e.length>0&&!e.endsWith(` `)?` `:``)+`@${t} `),K()?.focus();return}let n=Array.from(e.dataTransfer.files);n.length>0&&Y(n)},[Y,G,K]),Me=(0,Q.useCallback)(e=>{e.preventDefault()},[]),Pe=(0,Q.useCallback)(()=>{ue.current?.click()},[]),Fe=(0,Q.useCallback)(e=>{let t=Array.from(e.target.files??[]);t.length>0&&Y(t),e.target.value=``},[Y]),X=ie||P.some(e=>e.status!==`error`)||!!I,Ie=n&&!X;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=>{a||e.target instanceof HTMLTextAreaElement||K()?.focus()},children:[I&&(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`}),I,(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),oe(null),K()?.focus()},className:`shrink-0 rounded-sm p-0.5 hover:bg-sky-500/20 transition-colors`,"aria-label":`Remove ${I} agent`,children:(0,$.jsx)(te,{className:`size-3`})})]})}),(0,$.jsx)(bi,{attachments:P,onRemove:we}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 pt-2 md:hidden relative`,children:[(0,$.jsx)(Hi,{mode:x??`bypassPermissions`,onClick:()=>R(e=>!e)}),(0,$.jsx)(Ei,{value:x??`bypassPermissions`,onChange:e=>S?.(e),open:L,onOpenChange:R}),E&&o&&(0,$.jsx)(he,{value:C??`claude`,onChange:E,projectName:o}),ne&&o&&(0,$.jsx)(Mi,{model:O??null,effort:k??null,thinking:re??!1,onModelChange:ne,onEffortChange:A??(()=>{}),onThinkingChange:M??(()=>{}),projectName:o,providerId:C??`claude`,disabled:n}),n&&(0,$.jsx)(Wi,{value:ce,onChange:le})]}),(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(),Pe()},disabled:a,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)(xt,{className:`size-4`})}),(0,$.jsx)(`textarea`,{ref:U,defaultValue:g??``,onChange:ke,onKeyDown:De,onPaste:Ae,onDrop:je,onDragOver:Me,placeholder:n?`Follow-up...`:`Ask anything...`,disabled:a,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]`}),q.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),xe()},disabled:a,className:`flex items-center justify-center size-8 shrink-0 rounded-[10px] transition-colors disabled:opacity-50 ${q.isListening?`bg-error text-white animate-pulse`:`text-text-3 hover:text-text-primary`}`,"aria-label":q.isListening?`Stop voice input`:`Start voice input`,children:q.isListening?(0,$.jsx)(bt,{className:`size-4`}):(0,$.jsx)(Re,{className:`size-4`})}),Ie?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),r?.()},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)(H,{className:`size-3.5`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),z?B(!1):Ee()},disabled:a||!X,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":z?`Cancel queued send`:`Send`,children:z?(0,$.jsx)(w,{className:`size-4 animate-spin`}):(0,$.jsx)(se,{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)(Hi,{mode:x??`bypassPermissions`,onClick:()=>R(e=>!e)}),(0,$.jsx)(Ei,{value:x??`bypassPermissions`,onChange:e=>S?.(e),open:L,onOpenChange:R})]}),E&&o&&(0,$.jsx)(he,{value:C??`claude`,onChange:E,projectName:o}),ne&&o&&(0,$.jsx)(Mi,{model:O??null,effort:k??null,thinking:re??!1,onModelChange:ne,onEffortChange:A??(()=>{}),onThinkingChange:M??(()=>{}),projectName:o,providerId:C??`claude`,disabled:n}),n&&(0,$.jsx)(Wi,{value:ce,onChange:le})]}),(0,$.jsxs)(`div`,{className:`flex items-end gap-2 px-2.5 py-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),Pe()},disabled:a,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)(xt,{className:`size-[17px]`})}),(0,$.jsx)(`textarea`,{ref:V,defaultValue:g??``,onChange:ke,onKeyDown:De,onPaste:Ae,onDrop:je,onDragOver:Me,placeholder:n?`Follow-up or Stop...`:`Ask anything...`,disabled:a,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]`}),q.supported&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),xe()},disabled:a,className:`flex items-center justify-center size-[34px] shrink-0 rounded-[10px] transition-colors disabled:opacity-50 ${q.isListening?`bg-error text-white animate-pulse`:`text-text-3 hover:text-text-primary hover:bg-surface-elevated`}`,"aria-label":q.isListening?`Stop voice input`:`Start voice input`,children:q.isListening?(0,$.jsx)(bt,{className:`size-[17px]`}):(0,$.jsx)(Re,{className:`size-[17px]`})}),Ie?(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),r?.()},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)(H,{className:`size-4`})}):(0,$.jsx)(`button`,{onClick:e=>{e.stopPropagation(),z?B(!1):Ee()},disabled:a||!X,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":z?`Cancel queued send`:`Send message`,children:z?(0,$.jsx)(w,{className:`size-4 animate-spin`}):(0,$.jsx)(se,{className:`size-[17px]`})})]})]})]}),(0,$.jsx)(`input`,{ref:ue,type:`file`,multiple:!0,className:`hidden`,onChange:Fe})]})});function Hi({mode:e,onClick:t}){let n=Ti(e),r=wi(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 Ui=[{value:`now`,label:`Interrupt`,Icon:Fe},{value:`next`,label:`Queue`,Icon:yt},{value:`later`,label:`Later`,Icon:g}];function Wi({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=Ui.find(t=>t.value===e)??Ui[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 Gi(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 Ki(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=Gi(n,r.slice(0,n.length+i));return a<=i?{rank:2,distance:a}:null}var qi=1;function Ji(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=Ki(t,n.name),o=[e,Ki(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?qi: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 Yi({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:Ji(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,_=m.recentCount;(0,Q.useEffect)(()=>{l(0)},[t]),(0,Q.useEffect)(()=>{let e=f.current;e&&e.children[c]?.scrollIntoView({block:`nearest`})},[c]);let y=(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=>{y(e)&&e.stopPropagation()},t=f.current?.ownerDocument??document;return t.addEventListener(`keydown`,e,!0),()=>t.removeEventListener(`keydown`,e,!0)},[a,y]);let b=(0,Q.useCallback)(()=>{!s||u||(d(!0),E.del(`${T(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=_>0&&t===0,a=_>0&&t===_;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)(g,{className:`size-3`}),`Recent`]}),s&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),b()},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)(Ce,{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.iconDataUri?(0,$.jsx)(`img`,{src:e.iconDataUri,alt:``,className:`size-4 object-contain`}):e.type===`builtin`?(0,$.jsx)(Fe,{className:`size-4 text-emerald-500`}):e.type===`skill`?(0,$.jsx)(v,{className:`size-4 text-warning`}):e.type===`agent`?(0,$.jsx)(i,{className:`size-4 text-sky-500`}):(0,$.jsx)(ye,{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.invokeSigil??`/`,e.name]}),e.displayName&&e.displayName!==e.name&&(0,$.jsx)(`span`,{className:`text-xs text-text-2 truncate`,children:e.displayName}),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.invokeSigil===`$`?`Codex`: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 Xi({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()},t=s.current?.ownerDocument??document;return t.addEventListener(`keydown`,e,!0),()=>t.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)(Je,{className:`size-4 text-warning`}):(0,$.jsx)(qe,{className:`size-4 text-primary`})}),(0,$.jsx)(`span`,{className:`text-sm truncate`,children:e.path})]},e.path))})})}var Zi=e=>`${(e/1048576).toFixed(2)} MB`;function Qi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function $i(){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 ea({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 E.get(`${T(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,i=!1)=>{s(n),a(null),E.post(`${T(t)}/chat/sessions/${e}/images/strip?project=${encodeURIComponent(t)}`,{mode:n,includeAttachments:i}).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 this transcript`,c?` — it is clean.`:`.`]}):(0,$.jsxs)(`p`,{className:`text-[11px] text-text-secondary`,children:[n.total,` image`,n.total===1?``:`s`,` · `,Qi(n.bytes),` of base64, replayed on every turn`,n.attachments>0&&` · ${n.attachments} attached by you`,`.`]}),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)(U,{className:`mt-px size-3.5 shrink-0 text-warning`}),(0,$.jsxs)(`span`,{children:[n.oversized,` image`,n.oversized===1?` reaches`:`s reach`,` the `,n.limit,`px limit (largest `,n.largestSide,`px). Once a request carries several images the API rejects those outright, which fails the whole turn — removing them loses no context.`]})]}),n.oversizedAttachments>0&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border border-error/40 bg-error/10 p-2 text-[11px] text-text-secondary`,children:[(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(U,{className:`mt-px size-3.5 shrink-0 text-error`}),(0,$.jsxs)(`span`,{children:[n.oversizedAttachments,` of those `,n.oversizedAttachments===1?`is an image you`:`are images you`,` `,`attached yourself, so the buttons below leave `,n.oversizedAttachments===1?`it`:`them`,` in place. While `,n.oversizedAttachments===1?`it stays`:`they stay`,`, every turn in this session keeps failing. Removing `,n.oversizedAttachments===1?`it`:`them`,` cannot be undone: an attachment PPM sent keeps a copy on disk with its path still in the message, but one from another client does not.`]})]}),(0,$.jsxs)(F,{size:`sm`,variant:`destructive`,disabled:o!==null,onClick:()=>u(`oversized`,!0),children:[o===`oversized`?(0,$.jsx)(w,{className:`size-3.5 animate-spin`}):(0,$.jsx)(vt,{className:`size-3.5`}),`Remove oversized, attachments included`]})]}),c&&(0,$.jsxs)(`p`,{className:`text-[11px] text-success`,children:[`Removed `,c.removed,` image`,c.removed===1?``:`s`,`, freed `,Qi(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)(F,{size:`sm`,variant:`outline`,className:`flex-1`,disabled:o!==null||n.oversized===0,onClick:()=>u(`oversized`),children:[o===`oversized`?(0,$.jsx)(w,{className:`size-3.5 animate-spin`}):(0,$.jsx)(vt,{className:`size-3.5`}),`Remove oversized`,n.oversized>0?` (${n.oversized} · ${Qi(n.oversizedBytes)})`:``]}),(0,$.jsxs)(F,{size:`sm`,variant:`destructive`,className:`flex-1`,disabled:o!==null||n.total===0,onClick:()=>u(`all`),children:[o===`all`?(0,$.jsx)(w,{className:`size-3.5 animate-spin`}):(0,$.jsx)(vt,{className:`size-3.5`}),`Remove all`,n.total>0?` (${n.total} · ${Qi(n.bytes)})`:``]})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-text-subtle`,children:`These two buttons cover tool images only, and leave anything you attached alone. 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 ta({sessionId:e,projectName:t}){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{let n=!0;return E.get(`${T(t)}/chat/sessions/${e}/usage?project=${encodeURIComponent(t)}`).then(e=>{n&&r(e.turns)}).catch(e=>{n&&a(e.message)}),()=>{n=!1}},[e,t]),i)return(0,$.jsx)(`p`,{className:`text-[11px] text-error`,children:i});if(!n)return(0,$.jsx)(`p`,{className:`text-[11px] text-text-subtle`,children:`Loading token history...`});if(n.length===0)return(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`h3`,{className:`text-xs font-semibold text-foreground`,children:`Token & cache`}),(0,$.jsx)(`p`,{className:`text-[11px] text-text-subtle`,children:`No turns recorded yet. Send a message and the token split for each turn shows up here.`})]});let o=n.filter(e=>e.usage.coldStart).length,s=n.reduce((e,t)=>e+t.usage.costUsd,0),c=n.reduce((e,t)=>e+zn(t.usage),0),l=new Set(n.map(e=>e.usage.accountId).filter(Boolean)).size;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsx)(`h3`,{className:`text-xs font-semibold text-foreground`,children:`Token & cache`}),(0,$.jsxs)(`p`,{className:`text-[11px] text-text-secondary`,children:[`Last `,n.length,` turn`,n.length===1?``:`s`,` · `,o,` restarted the session ·`,` `,qn(c),` of transcript re-sent uncached · $`,s.toFixed(2),l>1&&` · spread over ${l} accounts`]}),(0,$.jsx)(`div`,{className:`max-h-[30vh] overflow-y-auto rounded-md border border-border`,children:(0,$.jsxs)(`table`,{className:`w-full font-mono text-[10.5px]`,children:[(0,$.jsx)(`thead`,{className:`sticky top-0 bg-surface text-text-subtle`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-2 py-1 text-left font-normal`,children:`When`}),(0,$.jsx)(`th`,{className:`px-2 py-1 text-left font-normal`,children:`Account`}),(0,$.jsx)(`th`,{className:`px-2 py-1 text-right font-normal`,children:`Prefix`}),(0,$.jsx)(`th`,{className:`px-2 py-1 text-right font-normal`,children:`Cached`}),(0,$.jsx)(`th`,{className:`px-2 py-1 text-right font-normal`,children:`Cost`}),(0,$.jsx)(`th`,{className:`px-2 py-1 text-left font-normal`,children:`Start`})]})}),(0,$.jsx)(`tbody`,{children:n.map(e=>{let t=Math.round(e.usage.cacheHitRate*100),n=Un(e.usage).level;return(0,$.jsxs)(`tr`,{className:`border-t border-border`,children:[(0,$.jsx)(`td`,{className:`px-2 py-1 text-text-subtle`,children:e.recordedAt.slice(11,16)||e.recordedAt.slice(0,10)}),(0,$.jsx)(`td`,{className:`max-w-24 truncate px-2 py-1 text-text-subtle`,title:e.usage.accountLabel??e.usage.accountId??``,children:e.usage.accountLabel??e.usage.accountId?.slice(0,8)??`—`}),(0,$.jsx)(`td`,{className:`px-2 py-1 text-right text-text-secondary`,children:qn(Rn(e.usage))}),(0,$.jsxs)(`td`,{className:`px-2 py-1 text-right ${n===`bad`?`text-warning`:n===`warn`?`text-text-primary`:`text-success`}`,children:[t,`%`]}),(0,$.jsxs)(`td`,{className:`px-2 py-1 text-right text-text-secondary`,children:[`$`,e.usage.costUsd.toFixed(3)]}),(0,$.jsx)(`td`,{className:`px-2 py-1 text-text-subtle`,children:e.usage.coldStart?e.usage.coldReason??`cold`:`warm`})]},e.id)})})]})}),(0,$.jsxs)(`p`,{className:`text-[11px] text-text-subtle`,children:[`A high "Cached" share is the cheap case. A turn marked `,(0,$.jsx)(`code`,{children:`idle_timeout`}),` paid for the whole transcript again because the session sat idle with no tab open long enough for PPM to release its subprocess. The cache is scoped per account, so a turn on a different account starts cold no matter how the session was resumed.`]})]})}function na({sessionId:e,projectName:t,open:n,onOpenChange:r}){let[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=ae();(0,Q.useEffect)(()=>{n&&(s(!1),a(null),E.get(`${T(t)}/chat/sessions/${e}/debug?project=${encodeURIComponent(t)}`).then(e=>{let t=e.jsonlSizeBytes==null?``:` (${Zi(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,...$i()].filter(Boolean).join(`
8
- `))}).catch(()=>a(`Failed to load debug info`)))},[n,e,t]);let l=(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)(ue,{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)(F,{size:`sm`,onClick:()=>{i&&Ie(i).then(e=>{e&&(s(!0),setTimeout(()=>s(!1),1500))})},disabled:!i,className:`w-full`,children:o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(_t,{className:`size-3.5`}),` Copied!`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(y,{className:`size-3.5`}),` Copy`]})}),(0,$.jsx)(`div`,{className:`border-t border-border pt-3`,children:n&&(0,$.jsx)(ta,{sessionId:e,projectName:t})}),(0,$.jsx)(`div`,{className:`border-t border-border pt-3`,children:n&&(0,$.jsx)(ea,{sessionId:e,projectName:t})})]});return c?(0,$.jsx)(I,{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:l})}):(0,$.jsx)(Te,{open:n,onOpenChange:r,children:(0,$.jsxs)(Y,{className:`sm:max-w-lg`,children:[(0,$.jsx)(je,{className:`sr-only`,children:`Session debug info`}),l]})})}function ra({hasUnread:e,onToggleUnread:t,onOpenDebug:n}){return(0,$.jsxs)(pe,{children:[(0,$.jsx)(Be,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:`flex items-center justify-center size-5 rounded text-text-subtle hover:text-text-secondary hover:bg-surface-elevated transition-colors`,title:`More actions`,"aria-label":`More actions`,children:(0,$.jsx)(x,{className:`size-3.5`})})}),(0,$.jsxs)(be,{align:`end`,side:`top`,className:`min-w-[190px]`,children:[(0,$.jsx)(Ze,{onClick:t,className:`max-md:py-3`,children:e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Xe,{className:`size-3.5 text-warning`}),` Mark as read`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h,{className:`size-3.5 fill-current text-primary`}),` Mark as unread`]})}),(0,$.jsxs)(Ze,{onClick:n,className:`max-md:py-3`,children:[(0,$.jsx)(ue,{className:`size-3.5`}),` Session debug info`]})]})]})}function ia(e){return Math.round((e??0)*100)>=100}function aa({usage:e,visible:t,onClose:n,onReload:r,loading:i,lastFetchedAt:a,onSelectAccount:o,selectedAccountId:s}){let[c,l]=(0,Q.useState)(null),{usages:u,accounts:d,activeAccountId:f,initialLoading:p,refreshing:m,flashIds:h,reload:g,toggle:_,togglingId:v}=pt(t),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(!1);if(!t)return null;let C=new Map(d.map(e=>[e.id,e]));function w(e,t){if(e){if(e.status===`disabled`)return`Disabled`;if(e.reauthRequired)return`Sign in again to use this account`;if(!e.hasRefreshToken&&e.expiresAt&&e.expiresAt<Math.floor(Date.now()/1e3))return`Token expired — sign in again`}let n=t?.usage.session;if(ia(n?.utilization))return`5-hour limit reached${n?.resetsAt?` — resets ${mt(n)}`:``}`;let r=t?.usage.weekly;return ia(r?.utilization)?`Weekly limit reached${r?.resetsAt?` — resets ${mt(r)}`:``}`:null}async function ee(e,t){b(await _(e,t))}async function T(e){if(!o)return;let t=w(C.get(e),u.find(t=>t.accountId===e));if(t){b(`Cannot switch to this account — ${t.toLowerCase()}.`);return}l(e),b(null);try{b(await o(e,u.find(t=>t.accountId===e)?.accountLabel??null)??null)}finally{l(null)}}let E=e.queryCostUsd!=null||e.totalCostUsd!=null,D=u.length>0,O=u.length||1,ne=Math.ceil(Math.sqrt(O)),k=Math.ceil(O/ne);return(0,$.jsxs)(`div`,{className:`relative border-b border-border bg-surface px-3 py-2.5 ${x?`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`}),a&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle`,children:ut(new Date(a).getTime())})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsxs)(`button`,{onClick:()=>ke(`accounts`),className:`flex items-center gap-1 text-[10px] text-text-subtle hover:text-text-primary px-1 cursor-pointer`,children:[`Manage accounts `,(0,$.jsx)(B,{className:`size-3`})]})}),(0,$.jsx)(K,{side:`top`,children:`Add, remove or rotate accounts`})]}),D&&(0,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsx)(`button`,{onClick:()=>S(e=>!e),className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,"aria-label":x?`Exit fullscreen`:`Fullscreen view`,children:x?(0,$.jsx)(De,{className:`size-3`}):(0,$.jsx)(Ae,{className:`size-3`})})}),(0,$.jsx)(K,{side:`top`,children:x?`Exit fullscreen`:`Fullscreen view`})]}),r&&(0,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsx)(`button`,{onClick:()=>{r(),g()},disabled:i||m,className:`text-xs text-text-subtle hover:text-text-primary px-1 disabled:opacity-50 cursor-pointer`,"aria-label":`Refresh usage`,children:(0,$.jsx)(Ce,{className:`size-3 ${i||m?`animate-spin`:``}`})})}),(0,$.jsx)(K,{side:`top`,children:`Refresh`})]}),(0,$.jsx)(`button`,{onClick:()=>{S(!1),n()},className:`text-xs text-text-subtle hover:text-text-primary px-1 cursor-pointer`,"aria-label":`Close usage panel`,children:(0,$.jsx)(te,{className:`size-3`})})]})]}),y&&(0,$.jsxs)(`div`,{className:`shrink-0 flex items-start gap-2 rounded border border-error/40 bg-error/10 px-2 py-1.5 text-[11px] text-error`,children:[(0,$.jsx)(`span`,{className:`flex-1`,children:y}),(0,$.jsx)(`button`,{onClick:()=>b(null),className:`shrink-0 text-error/70 hover:text-error cursor-pointer`,"aria-label":`Dismiss`,children:(0,$.jsx)(te,{className:`size-3`})})]}),D||p?(0,$.jsx)(`div`,{className:x?`flex-1 min-h-0 grid gap-2 overflow-hidden`:`flex gap-2 overflow-x-auto pb-1 -mx-3 px-3 snap-x snap-mandatory scrollbar-thin`,style:x?{gridTemplateColumns:`repeat(${ne}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${k}, minmax(0, 1fr))`}:void 0,children:p?(0,$.jsx)(`p`,{className:`text-[10px] text-text-subtle`,children:`Loading...`}):u.map(t=>{let n=C.get(t.accountId);return(0,$.jsx)(dt,{entry:t,isActive:t.accountId===(s??e.activeAccountId??f),accountInfo:n,flash:h.has(t.accountId),layout:x?`grid`:`strip`,onSelect:o?T:void 0,unselectableReason:w(n,t),selecting:c===t.accountId,onToggle:ee,toggling:v===t.accountId},t.accountId)})}):e.session||e.weekly||e.weeklyOpus||e.weeklySonnet?(0,$.jsxs)(`div`,{className:`space-y-2.5`,children:[(0,$.jsx)(ft,{label:`5-Hour Session`,bucket:e.session}),(0,$.jsx)(ft,{label:`Weekly`,bucket:e.weekly}),(0,$.jsx)(ft,{label:`Weekly (Opus)`,bucket:e.weeklyOpus}),(0,$.jsx)(ft,{label:`Weekly (Sonnet)`,bucket:e.weeklySonnet})]}):(0,$.jsx)(`p`,{className:`text-xs text-text-subtle`,children:`No usage data available`}),E&&(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)]})]})]})]})}function oa(e){return Math.round((e??0)*100)>=100}function sa({label:e,frac:t,bucket:n}){return(0,$.jsx)(lt,{label:e,pct:t==null?null:Math.round(t*100),reset:mt(n),resetsAt:n?.resetsAt})}function ca({onClose:e,usage:t,onReload:n,onSelectAccount:r,selectedAccountId:i}){let[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)({}),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null),_=(0,Q.useCallback)(async(e,t,n)=>{if(r){if(n){g(`Cannot switch to this account — ${n}`);return}f(e),g(null);try{g(await r(e,t)??null)}finally{f(null)}}},[r]),v=(0,Q.useCallback)(async(e,t)=>{m(e),g(null);try{await E.patch(`/api/codex-accounts/${e}`,{status:t===`disabled`?`active`:`disabled`}),o((await E.get(`/api/codex-accounts`)).accounts)}catch(e){g(e.message||`Could not change the account`)}finally{m(null)}},[]),y=(0,Q.useCallback)(async()=>{u(!0);try{o((await E.get(`/api/codex-accounts`)).accounts),c(await E.get(`/api/codex-accounts/usage`))}catch{}finally{u(!1)}},[]);(0,Q.useEffect)(()=>{y()},[y]);let b=(0,Q.useCallback)(async()=>{u(!0);try{await n?.(),c(await E.get(`/api/codex-accounts/usage`))}catch{}finally{u(!1)}},[n]);return(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,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsx)(`button`,{onClick:b,disabled:l,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer disabled:opacity-50`,"aria-label":`Refresh usage`,children:(0,$.jsx)(Ce,{className:`size-3 ${l?`animate-spin`:``}`})})}),(0,$.jsx)(K,{side:`top`,children:`Refresh`})]}),(0,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsx)(`button`,{onClick:e,className:`text-text-subtle hover:text-text-primary px-1 cursor-pointer`,"aria-label":`Close usage panel`,children:(0,$.jsx)(te,{className:`size-3`})})}),(0,$.jsx)(K,{side:`top`,children:`Close`})]})]})]}),h&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded border border-error/40 bg-error/10 px-2 py-1.5 text-[11px] text-error`,children:[(0,$.jsx)(`span`,{className:`flex-1`,children:h}),(0,$.jsx)(`button`,{onClick:()=>g(null),className:`shrink-0 text-error/70 hover:text-error cursor-pointer`,"aria-label":`Dismiss`,children:(0,$.jsx)(te,{className:`size-3`})})]}),l&&a.length===0&&(0,$.jsxs)(`div`,{className:`text-xs text-text-subtle flex items-center gap-2`,children:[(0,$.jsx)(w,{className:`size-3 animate-spin`}),` Loading…`]}),!l&&a.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)(sa,{label:`5-Hour`,frac:t.fiveHour,bucket:t.session}),(0,$.jsx)(sa,{label:`Weekly`,frac:t.sevenDay,bucket:t.weekly})]}),(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.`]})]}),a.map(e=>{let n=s[e.id]??{},a=e.id===(i??t.activeAccountId),o=e.status===`disabled`?`it is switched off.`:oa(n.fiveHour)?`it has reached its 5-hour limit.`:oa(n.sevenDay)?`it has reached its weekly limit.`:null;return(0,$.jsxs)(`div`,{className:`rounded-md border bg-surface/40 p-2.5 space-y-2 ${a?`border-primary/30 bg-primary/5`:`border-border/50`}`,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}),a&&(0,$.jsx)(`span`,{className:`text-[10px] text-primary shrink-0 font-medium`,children:`Active`}),r&&!a&&(0,$.jsxs)(z,{children:[(0,$.jsx)(X,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>_(e.id,e.label,o),disabled:d===e.id,className:[`shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors cursor-pointer disabled:cursor-wait`,o?`text-text-subtle hover:text-error hover:bg-error/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`].join(` `),children:d===e.id?`Switching…`:`Use`})}),(0,$.jsx)(K,{side:`top`,children:o?`Cannot use this account — ${o}`:`Use this account for this chat`})]}),e.status===`disabled`&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0`,children:`Off`}),(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)(V,{checked:e.status!==`disabled`,onCheckedChange:()=>void v(e.id,e.status??`active`),disabled:p===e.id,"aria-label":e.status===`disabled`?`Enable account`:`Disable account`,className:`cursor-pointer shrink-0`})]}),(0,$.jsx)(sa,{label:`5-Hour`,frac:n.fiveHour,bucket:n.session}),(0,$.jsx)(sa,{label:`Weekly`,frac:n.sevenDay,bucket:n.weekly})]},e.id)})]})}var la={working:`working`,paused:`paused`,"no-transcript":`no session`};function ua({member:e,onOpen:t}){let n=e.workState===`working`,r=ni(e),i=ti(e.startedAt,n?void 0:e.lastEventAt),a=ei(e.agentType);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>t(e.name),className:`w-full text-left min-h-[44px] px-1.5 py-1 rounded-md hover:bg-surface-elevated transition-colors group`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[n?(0,$.jsx)(w,{className:`size-3 shrink-0 animate-spin text-success`}):(0,$.jsx)(`span`,{className:A(`size-1.5 rounded-full shrink-0`,e.workState===`paused`?`bg-warning`:`bg-text-3`)}),(0,$.jsx)(`span`,{className:`font-medium truncate`,children:e.name}),a&&(0,$.jsx)(`span`,{className:`text-text-subtle text-[10px] truncate`,children:a}),e.model&&(0,$.jsxs)(`span`,{className:`text-text-subtle text-[10px]`,children:[`(`,e.model,`)`]}),(0,$.jsxs)(`span`,{className:`ml-auto flex items-center gap-1 shrink-0 text-[10px] text-text-subtle`,children:[i&&(0,$.jsx)(`span`,{children:i}),(0,$.jsx)(`span`,{className:A(n&&`text-success`),children:la[e.workState]}),(0,$.jsx)(c,{className:`size-3 opacity-0 group-hover:opacity-100 transition-opacity`})]})]}),r&&(0,$.jsx)(`div`,{className:`mt-0.5 pl-5 text-[11px] text-text-subtle truncate font-mono`,children:r})]})}function da({members:e,loading:t,onOpenMember:n,className:r}){return e.length===0?(0,$.jsx)(`div`,{className:A(`flex items-center justify-center gap-2 text-xs text-text-subtle py-4`,r),children:t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(w,{className:`size-3 animate-spin`}),`Reading member sessions…`]}):`No member sessions recorded`}):(0,$.jsx)(`div`,{className:A(`overflow-y-auto space-y-0.5`,r),children:e.map(e=>(0,$.jsx)(ua,{member:e,onOpen:n},e.name))})}var fa=[`subject`,`summary`,`text`,`message`,`content`,`description`,`reason`,`feedback`],pa=[`description`,`message`,`content`,`reason`,`feedback`],ma=new Set([`type`,`taskId`,`task_id`,`assignedBy`,`assigned_by`,`timestamp`,`request_id`,`requestId`]),ha=e=>typeof e==`string`?e.trim():e==null?``:String(e);function ga(e,t,n){for(let r of t){if(r===n)continue;let t=ha(e[r]);if(t)return{key:r,value:t}}return null}function _a(e){return Object.entries(e).filter(([e,t])=>!ma.has(e)&&ha(t)).map(([e,t])=>`${e}: ${ha(t)}`).join(` · `)}function va(e,t){let n=ha(t),r=ha(e);if(!r)return{title:n};let i;try{i=JSON.parse(r)}catch{let[e,...t]=r.split(`
9
- `),i=t.join(`
10
- `).trim();return{title:n||ha(e),...i?{detail:i}:{}}}if(!i||typeof i!=`object`||Array.isArray(i))return{title:n||r};let a=i,o=ha(a.taskId)||ha(a.task_id),s=ga(a,fa),c=ga(a,pa,s?.key);return{title:n||s?.value||_a(a)||ha(a.type)||r,...c?{detail:c.value}:{},...o?{taskId:o}:{}}}function ya({messages:e,className:t}){let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{n.current?.scrollIntoView({behavior:`smooth`})},[e.length]),e.length===0?(0,$.jsx)(`p`,{className:A(`text-xs text-text-subtle text-center py-4`,t),children:`No messages yet`}):(0,$.jsx)(`div`,{className:A(`overflow-y-auto`,t),children:(0,$.jsxs)(`div`,{className:`space-y-2`,children:[e.map((e,t)=>{let n=e.parsedType?m[e.parsedType]:null,{title:r,detail:i,taskId:a}=va(e.text,e.summary);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:xa(e.color),children:e.from}),(0,$.jsx)(`span`,{children:`→`}),(0,$.jsx)(`span`,{children:e.to}),(0,$.jsx)(`span`,{className:`ml-auto text-[10px]`,children:ba(e.timestamp)})]}),(0,$.jsxs)(`div`,{className:`mt-0.5 text-foreground/90 break-words`,children:[n&&(0,$.jsx)(`span`,{className:A(`inline-block px-1 py-0 rounded text-[9px] mr-1`,n.className),children:n.label}),a&&(0,$.jsxs)(`span`,{className:`inline-block px-1 py-0 rounded text-[9px] mr-1 bg-surface-elevated text-text-subtle`,children:[`#`,a]}),r]}),i&&(0,$.jsx)(`div`,{className:`mt-0.5 text-[11px] text-text-subtle break-words line-clamp-2`,children:i})]},`${e.timestamp}-${t}`)}),(0,$.jsx)(`div`,{ref:n})]})})}function ba(e){try{return new Date(e).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}catch{return``}}function xa(e){if(e&&(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^[a-zA-Z]{3,20}$/.test(e)))return{color:e}}function Sa(e,t){return e===t?`Team (current session)`:e}function Ca({teamNames:e,messages:t,sessionId:n,projectName:r}){let[i,a]=(0,Q.useState)(e[0]??``),[o,s]=(0,Q.useState)(`members`),c=at(),l=b();(0,Q.useEffect)(()=>{e.length>0&&!e.includes(i)&&a(e[0])},[e,i]);let{members:u,outbound:d,loading:f,refresh:p}=ai(i,!!i),m=(0,Q.useCallback)(e=>{c({teamName:i,memberName:e,projectName:r})},[c,i,r]),h=(0,Q.useMemo)(()=>{let e=d.map(e=>({from:e.from,to:e.to,text:e.text,timestamp:e.timestamp,...e.summary?{summary:e.summary}:{}}));return[...t,...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()).slice(-200)},[t,d]),g=u.filter(e=>e.workState===`working`).length,_=e=>A(`flex items-center gap-1.5 px-2.5 rounded-md text-[11px] whitespace-nowrap transition-colors`,l?`min-h-[44px]`:`py-1`,e?`bg-primary/10 text-primary font-medium`:`text-text-subtle hover:text-text-primary`);return(0,$.jsxs)(`div`,{className:`flex flex-col min-h-0`,children:[e.length>1&&(0,$.jsx)(`div`,{className:`flex items-center gap-1 overflow-x-auto min-w-0 mb-1.5`,children:e.map(e=>(0,$.jsx)(`button`,{onClick:()=>a(e),className:A(`px-2 py-0.5 text-[11px] rounded-md whitespace-nowrap transition-colors`,i===e?`bg-primary/10 text-primary font-medium`:`text-text-subtle hover:text-text-primary`),children:Sa(e,n)},e))}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 mb-1.5 shrink-0`,role:`tablist`,children:[(0,$.jsxs)(`button`,{role:`tab`,"aria-selected":o===`members`,onClick:()=>s(`members`),className:_(o===`members`),children:[(0,$.jsx)(`span`,{children:`Members`}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:u.length}),g>0&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 text-success`,children:[(0,$.jsx)(`span`,{className:`size-1.5 rounded-full bg-success animate-pulse`}),g]})]}),(0,$.jsxs)(`button`,{role:`tab`,"aria-selected":o===`messages`,onClick:()=>s(`messages`),className:_(o===`messages`),children:[(0,$.jsx)(`span`,{children:`Messages`}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:h.length})]}),(0,$.jsx)(`button`,{onClick:p,className:A(`ml-auto text-text-subtle hover:text-foreground shrink-0`,l?`p-3`:`p-1`),"aria-label":`Refresh`,children:(0,$.jsx)(Ce,{className:A(`size-3`,f&&`animate-spin`)})})]}),o===`members`?(0,$.jsx)(da,{members:u,loading:f,onOpenMember:m,className:`max-h-56`}):(0,$.jsx)(ya,{messages:h,className:`max-h-56`})]})}function wa(e){return e>=90?`text-error`:e>=70?`text-warning`:`text-success`}function Ta({projectName:e,usageInfo:t,usageLoading:n,refreshUsage:r,lastFetchedAt:a,sessionId:s,providerId:c,pickedAccountLabel:l,pickedAccountId:u,onSelectAccount:d,onSelectSession:f,onBugReport:p,isConnected:m,onReload:h,teamActivity:g,teamMessages:_,onTeamOpen:v}){let[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)([]),[C,ee]=(0,Q.useState)(!1),D=Ke(e=>e.notifications),O=Ke(e=>s?e.notifications.has(s):!1),ne=Ke(e=>e.clearForSession),k=Ke(e=>e.markUnread),[j,re]=(0,Q.useState)(``),M=xe(j,300),[N,ae]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(``),[I,oe]=(0,Q.useState)(!1),[L,se]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)([]),[B,V]=(0,Q.useState)(null),[H,U]=(0,Q.useState)({}),[ue,pe]=(0,Q.useState)(!1),[me,he]=(0,Q.useState)(!1),G=(0,Q.useRef)(null),K=ie(e=>e.openTab),ve=e=>{b(t=>t===e?null:e)},q=(0,Q.useCallback)(async t=>{if(e){ee(!0);try{let n=new URLSearchParams({limit:`50`,offset:`0`});t&&n.set(`q`,t);let r=await E.get(`${T(e)}/chat/sessions?${n}`);S(r.sessions),oe(r.hasMore)}catch{}finally{ee(!1)}}},[e]),ye=(0,Q.useCallback)(async()=>{if(!(!e||L||!I)){se(!0);try{let t=x.filter(e=>!e.pinned).length,n=new URLSearchParams({limit:`50`,offset:String(t)});M&&n.set(`q`,M);let r=await E.get(`${T(e)}/chat/sessions?${n}`);S(e=>{let t=new Set(e.map(e=>e.id)),n=r.sessions.filter(e=>!t.has(e.id));return[...e,...n]}),oe(r.hasMore)}catch{}finally{se(!1)}}},[e,L,I,x,M]);(0,Q.useEffect)(()=>{y===`history`&&x.length===0&&q()},[y]),(0,Q.useEffect)(()=>{y===`history`&&q(M||void 0)},[M]);let be=(0,Q.useCallback)(async()=>{if(e)try{let t=await E.get(`${T(e)}/tags`);z(t.tags),U(t.counts)}catch{}},[e]);(0,Q.useEffect)(()=>{y===`history`&&e&&be()},[y,e,be]);function Se(t){f?(f(t),b(null)):K({type:`chat`,title:t.title||`Chat`,projectId:e??null,metadata:{projectName:e,sessionId:t.id,providerId:t.providerId},closable:!0})}let J=(0,Q.useCallback)((e,t)=>{t.stopPropagation(),ae(e.id),F(e.title||``),setTimeout(()=>G.current?.select(),0)},[]),Y=(0,Q.useCallback)(async()=>{if(!N||!P.trim()||!e){ae(null);return}try{await E.patch(`${T(e)}/chat/sessions/${N}`,{title:P.trim()}),S(e=>e.map(e=>e.id===N?{...e,title:P.trim()}:e))}catch{}ae(null)},[N,P,e]),we=(0,Q.useCallback)(()=>ae(null),[]),Te=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),!e)return;let r=`${T(e)}/chat/sessions/${n.id}/pin`;try{n.pinned?await E.del(r):await E.put(r),S(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]),Ee=(0,Q.useCallback)(async(t,n)=>{if(t.stopPropagation(),e&&window.confirm(`Delete this session? This cannot be undone.`))try{await E.del(`${T(e)}/chat/sessions/${n.id}?providerId=${n.providerId}`),S(e=>e.filter(e=>e.id!==n.id))}catch{}},[e]),De=(0,Q.useCallback)((e,t)=>{S(n=>n.map(n=>n.id===e?{...n,tag:t}:n)),be()},[be]),ke=(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.`)){ee(!0);try{await E.del(`${T(e)}/chat/sessions?olderThanDays=${n}`),q(M||void 0)}catch{}}},[e,q,M]);(0,Q.useEffect)(()=>{if(y!==`history`)return;let t=t=>{if(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement)return;let n=parseInt(t.key);if(n>=1&&n<=R.length&&s){let t=R[n-1];t&&(E.patch(`${T(e)}/chat/sessions/${s}/tag`,{tagId:t.id}).catch(()=>{}),De(s,{id:t.id,name:t.name,color:t.color}))}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[y,R,s,e,De]);let Ae=B===null?x:x.filter(e=>e.tag?.id===B),je=!c||c===`claude`,Ne=c===`codex`,Fe=t.fiveHour==null?null:Math.round(t.fiveHour*100),X=t.sevenDay==null?null:Math.round(t.sevenDay*100),Ie=Fe!=null||X!=null?wa(Math.max(Fe??0,X??0)):`text-text-subtle`,Re=l??t.activeAccountLabel??null;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)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1 overflow-x-auto scrollbar-none`,children:[(0,$.jsxs)(`button`,{onClick:()=>ve(`history`),className:`shrink-0 flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${y===`history`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,children:[(0,$.jsx)(Pe,{className:`size-3`}),(0,$.jsx)(`span`,{children:`History`})]}),s&&c&&c!==`mock`?(0,$.jsxs)(`button`,{onClick:()=>ve(`config`),className:`shrink-0 flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${y===`config`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`AI Settings`,children:[(0,$.jsx)(W,{providerId:c}),(0,$.jsx)(`span`,{className:`capitalize`,children:c})]}):(0,$.jsx)(`button`,{onClick:()=>ve(`config`),className:`shrink-0 p-1 rounded transition-colors ${y===`config`?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary hover:bg-surface-elevated`}`,title:`AI Settings`,children:(0,$.jsx)(de,{className:`size-3`})}),je||Ne?(0,$.jsxs)(`button`,{onClick:()=>ve(`usage`),className:`shrink-0 flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium tabular-nums transition-colors hover:bg-surface-elevated ${y===`usage`?`bg-primary/10`:``} ${Ie}`,title:`Usage limits`,children:[(0,$.jsx)(ht,{className:`size-3`}),Re&&(0,$.jsxs)(`span`,{className:`text-text-secondary font-normal truncate max-w-[110px]`,title:Re,children:[`[`,Re,`]`]}),(0,$.jsxs)(`span`,{children:[`5h:`,Fe==null?`--%`:`${Fe}%`]}),(0,$.jsx)(`span`,{className:`text-text-subtle`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Wk:`,X==null?`--%`:`${X}%`]})]}):null,g?.hasTeams&&(0,$.jsxs)(`button`,{onClick:()=>{ve(`team`),v?.()},className:`shrink-0 relative flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors ${y===`team`?`text-primary bg-primary/10`:`text-text-secondary hover:text-foreground hover:bg-surface-elevated`}`,title:`Team activity`,children:[(0,$.jsx)(ge,{className:`size-3`}),(0,$.jsx)(`span`,{children:`Team`}),(g.unreadCount??0)>0&&(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 size-2 bg-primary rounded-full animate-pulse`})]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 pl-1`,children:[h&&(0,$.jsxs)(`button`,{onClick:e=>{let t=e.currentTarget.querySelector(`svg`);t&&(t.classList.add(`animate-spin`),setTimeout(()=>t.classList.remove(`animate-spin`),600)),h()},className:`relative size-4 flex items-center justify-center`,title:m?`Reload messages`:`Disconnected — click to reload`,children:[(0,$.jsx)(Ce,{className:`size-3 ${m?`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 ${m?`bg-success`:`bg-error animate-pulse`}`})]}),s&&(0,$.jsx)(ra,{hasUnread:O,onToggleUnread:()=>O?ne(s):k(s,e),onOpenDebug:()=>he(!0)})]})]}),s&&(0,$.jsx)(na,{sessionId:s,projectName:e,open:me,onOpenChange:he}),y===`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)(ze,{className:`size-3 text-text-subtle shrink-0`}),(0,$.jsx)(`input`,{type:`text`,value:j,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:ke,className:`p-0.5 rounded text-text-subtle hover:text-error transition-colors`,title:`Delete old sessions...`,children:(0,$.jsx)(le,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:()=>q(M||void 0),disabled:C,className:`p-0.5 rounded text-text-subtle hover:text-text-secondary transition-colors disabled:opacity-50`,title:`Refresh`,children:(0,$.jsx)(Ce,{className:`size-3 ${C?`animate-spin`:``}`})})]}),R.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:()=>V(null),className:`shrink-0 rounded-md border px-2 py-1 text-[10px] transition-colors ${B===null?`bg-primary/20 border-primary text-primary`:`border-border bg-surface text-text-secondary`}`,children:[`All (`,x.length,`)`]}),R.map(e=>(0,$.jsxs)(`button`,{onClick:()=>V(B===e.id?null:e.id),className:`shrink-0 flex items-center gap-1 rounded-md border px-2 py-1 text-[10px] transition-colors ${B===e.id?`border-current`:`border-border bg-surface`}`,style:B===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,` (`,H[e.id]??0,`)`]},e.id)),(0,$.jsx)(`button`,{onClick:()=>pe(!ue),className:`shrink-0 p-1 rounded transition-colors ${ue?`text-primary bg-primary/10`:`text-text-subtle hover:text-text-secondary`}`,title:`Manage tags`,children:(0,$.jsx)(Ye,{className:`size-3`})})]}),ue&&(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)(_e,{projectName:e,onTagsChanged:be})}),(0,$.jsx)(`div`,{className:`max-h-[200px] overflow-y-auto`,children:C&&x.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3`,children:(0,$.jsx)(w,{className:`size-3.5 animate-spin text-text-subtle`})}):Ae.length===0?(0,$.jsx)(`div`,{className:`flex items-center justify-center py-3 text-[11px] text-text-subtle`,children:j?`No matching sessions`:`No sessions yet`}):(0,$.jsxs)($.Fragment,{children:[Ae.map(t=>{let n=D.get(t.id),r=!!n;return(0,$.jsx)(Ge,{session:t,projectName:e,projectTags:R,onTogglePin:Te,onStartEditing:J,onDeleteSession:Ee,onTagChanged:De,children:(0,$.jsxs)(`div`,{className:A(`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&&Oe(n.type),!r&&`text-text-secondary`),children:[(0,$.jsx)(W,{providerId:t.providerId}),t.tag&&(0,$.jsx)(`span`,{className:`size-2 rounded-full shrink-0`,style:{backgroundColor:t.tag.color},title:t.tag.name}),N===t.id?(0,$.jsxs)(`form`,{className:`flex items-center gap-1 flex-1 min-w-0`,onSubmit:e=>{e.preventDefault(),Y()},children:[(0,$.jsx)(`input`,{ref:G,value:P,onChange:e=>F(e.target.value),onBlur:Y,onKeyDown:e=>{e.key===`Escape`&&we()},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)(o,{className:`size-3`})}),(0,$.jsx)(`button`,{type:`button`,className:`p-0.5 text-text-subtle hover:text-text-secondary`,onClick:e=>{e.stopPropagation(),we()},children:(0,$.jsx)(te,{className:`size-3`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{onClick:()=>Se(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=>Te(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)(Ue,{className:`size-3`}):(0,$.jsx)(Me,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>J(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)(Le,{className:`size-3`})}),(0,$.jsx)(`button`,{onClick:e=>Ee(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)(fe,{className:`size-3`})})]}),N!==t.id&&t.updatedAt&&(0,$.jsx)(`span`,{className:`text-[10px] text-text-subtle shrink-0 w-16 text-right`,children:ce(t.updatedAt)})]})},t.id)}),I&&(0,$.jsxs)(`button`,{onClick:ye,disabled:L,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:[L?(0,$.jsx)(w,{className:`size-3 animate-spin`}):null,L?`Loading...`:`Load more`]})]})})]}),y===`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)(ct,{compact:!0})}),y===`team`&&g?.hasTeams&&(0,$.jsx)(`div`,{className:`border-t border-border/30 bg-surface px-3 py-2`,children:(0,$.jsx)(Ca,{teamNames:g.teamNames,messages:_??[],sessionId:s,projectName:e})}),y===`usage`&&je&&(0,$.jsx)(aa,{usage:t,onSelectAccount:d,selectedAccountId:u??t.activeAccountId??null,visible:!0,onClose:()=>b(null),onReload:r,loading:n,lastFetchedAt:a}),y===`usage`&&Ne&&(0,$.jsx)(ca,{usage:t,onClose:()=>b(null),onReload:r,onSelectAccount:d,selectedAccountId:u??t.activeAccountId??null})]})}var Ea=3e3;function Da(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)},Ea);return E.get(`${T(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__`;E.put(`${T(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__`;E.del(`${T(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 Oa({metadata:e,tabId:t}){let[n,r]=(0,Q.useState)(e?.sessionId??null),i=(0,Q.useCallback)(e=>{r(e)},[]),[a,o]=(0,Q.useState)(e?.providerId??`claude`),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(``),[C,ee]=(0,Q.useState)(null),[D,A]=(0,Q.useState)(e?.permissionMode??void 0),j=(0,Q.useRef)(null),[re,N]=(0,Q.useState)(!1),[ae,P]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(null),[oe,L]=(0,Q.useState)(null),se=(0,Q.useRef)(0),R=e?.projectName??``,z=ie(e=>e.updateTab),B=k(e=>e.version),{usageInfo:ce,usageLoading:le,lastFetchedAt:V,refreshUsage:H}=Vt(R,a,n??void 0),{draft:U,draftLoading:ue,saveDraft:de,clearDraft:fe}=Da(R,n);(0,Q.useEffect)(()=>{D||$e().then(e=>{let t=e.providers[e.default_provider??`claude`];A(t?.permission_mode??`bypassPermissions`)}).catch(()=>{})},[]),(0,Q.useEffect)(()=>{!t||!n||z(t,{metadata:{...e,sessionId:n,providerId:a,permissionMode:D,pickedAccountId:void 0,pickedAccountLabel:void 0,pickedAccountProvider:void 0}})},[n,a,D]);let pe=e?.pickedAccountId,W=e?.pickedAccountLabel,me=e?.pickedAccountProvider,he=!!pe&&me===a;(0,Q.useEffect)(()=>{if(!t||n||he)return;let r=!1;return et(a).then(n=>{r||!n||z(t,{metadata:{...e,pickedAccountId:n.id,pickedAccountLabel:n.label,pickedAccountProvider:a}})}).catch(()=>{}),()=>{r=!0}},[t,n,a,he]);let ge=(0,Q.useCallback)(async(r,i)=>{if(n){try{await E.put(`${T(R)}/chat/sessions/${n}/account`,{accountId:r}),K({id:r,label:i}),O.success(`This chat will use the selected account from the next message.`)}catch(e){return e.message||`Could not switch account`}return null}return t&&z(t,{metadata:{...e,pickedAccountId:r,pickedAccountLabel:i,pickedAccountProvider:a}}),null},[n,R,t,e,a,z]),[G,K]=(0,Q.useState)(null),{messages:_e,renderedMessages:q,expandCompact:ye,isCompactExpanded:be,dismissMessage:xe,clearErrors:Se,messagesLoading:J,versionMap:Ce,isStreaming:Y,phase:we,isReconnecting:Te,connectingElapsed:Ee,pendingApproval:De,contextWindowPct:Oe,compactStatus:ke,statusMessage:Ae,sessionTitle:je,liveAccount:Me,model:Ne,setModel:Pe,effort:Fe,setEffort:X,thinking:Ie,setThinking:Le,sendMessage:Re,respondToApproval:Z,cancelStreaming:ze,reconnect:Be,refetchMessages:Ve,isConnected:He,teamActivity:Ue,teamMessages:Ge,markTeamRead:qe,bashPartialOutput:Je,backgroundShells:Ye,killBackgroundShell:Xe}=zt(n,a,R,i);(0,Q.useEffect)(()=>{Me&&K(Me)},[Me]),(0,Q.useEffect)(()=>{K(null)},[n]);let Ze=Ue?.teamNames?.[0]??``,{members:Qe}=ai(Ze,!!Ze);(0,Q.useEffect)(()=>{if(He&&j.current){let{content:e,permissionMode:t,images:n,imagePaths:r}=j.current;j.current=null,Re(e,{permissionMode:t,...n?.length&&{images:n},...r?.length&&{imagePaths:r}})}},[He,Re]),(0,Q.useEffect)(()=>{if(!n||!t)return;let e=()=>{if(document.hidden)return;let{panels:e}=M.getState();Object.values(e).some(e=>e.activeTabId===t)&&(Ke.getState().notifications.get(n)?.manual||Ke.getState().clearForSession(n))};e(),document.addEventListener(`visibilitychange`,e);let r=M.subscribe(e),i=Ke.subscribe(e);return()=>{document.removeEventListener(`visibilitychange`,e),r(),i()}},[n,t]),(0,Q.useEffect)(()=>{t&&je&&z(t,{title:je})},[je]);let[tt,nt]=(0,Q.useState)(e?.pendingMessage),[rt,it]=(0,Q.useState)(null),[at,ot]=(0,Q.useState)(!1),[st,ct]=(0,Q.useState)(0),[lt,ut]=(0,Q.useState)(!1),dt=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{dt.current&&!J&&ut(!1),dt.current=!!J},[J]);let[ft,pt]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{ue||pt(!0)},[ue]),(0,Q.useEffect)(()=>{tt&&He&&n&&t&&z(t,{metadata:{...e,pendingMessage:void 0}})},[He,n]),(0,Q.useEffect)(()=>{at&&Y&&ot(!1)},[at,Y]),(0,Q.useEffect)(()=>{if(!at)return;let e=setTimeout(()=>ot(!1),6e4);return()=>clearTimeout(e)},[at]);let mt=(0,Q.useCallback)((e,t)=>{ie.getState().openTab({type:`chat`,title:e||`AI Chat`,metadata:{projectName:R,providerId:a,...t&&{clearedFrom:t}},projectId:R||null,closable:!0})},[R,a]),ht=(0,Q.useCallback)(e=>{ot(!1),r(e.id),o(e.providerId),t&&z(t,{title:e.title||`Chat`}),Ke.getState().clearForSession(e.id)},[t,z]),gt=(0,Q.useCallback)(async(e,t)=>{if(!(!n||!R))try{let{api:r,projectUrl:i}=await ne(async()=>{let{api:e,projectUrl:t}=await import(`./api-client-QfreGirP.js`);return{api:e,projectUrl:t}},__vite__mapDeps([50,6,1,2,30])),o=await r.post(`${i(R)}/chat/sessions/${n}/fork?providerId=${a}`,{messageId:t});ie.getState().openTab({type:`chat`,title:`Fork: ${e.slice(0,30)}`,metadata:{projectName:R,sessionId:o.id,providerId:a,pendingMessage:e},projectId:R||null,closable:!0})}catch(e){console.error(`Fork failed:`,e);let t=e?.message||`Unknown error`;O.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,R,a]),_t=(0,Q.useCallback)((e,t,n)=>{nt(e),it({anchorMsgId:t,ownMsgId:n})},[]),vt=(0,Q.useCallback)(()=>{it(null),nt(void 0),ot(!1),fe(),ct(e=>e+1)},[fe]),yt=(0,Q.useCallback)(async(i,o)=>{if(!(!i.trim()||!n||!R)){ot(!0);try{let s=await E.post(`${T(R)}/chat/sessions/${n}/fork?providerId=${a}&mode=edit`,{messageId:o});j.current={content:i,permissionMode:D},ut(!0),t&&z(t,{metadata:{...e,sessionId:s.id}}),r(s.id)}catch(e){ot(!1);let t=e?.message||`Unknown error`;O.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,R,a,D,t,z,e]),bt=(0,Q.useCallback)(i=>{!i||i===n||(ot(!1),ut(!0),t&&z(t,{metadata:{...e,sessionId:i}}),r(i))},[n,t,z,e]),xt=(0,Q.useCallback)((e,t,n=[])=>{if(t.length===0)return e;let r=[];for(let e of t)e.textContent&&r.push(e.textContent);let{inlineImagePaths:i,pathOnlyPaths:a}=Tt(t,n);for(let e of i)r.push(`[Attached image (contents included in this message): ${e}]`);if(a.length>0){let e=a.join(`
11
- `);r.push(a.length===1?`[Attached file: ${e}]`:`[Attached files:\n${e}\n]`)}return r.length===0?e:r.join(`
12
-
13
- `)+`
14
-
15
- `+e},[]),St=(0,Q.useCallback)(async(t,i=[],s)=>{let c=wt(i),l=xt(t,i,c),u=i.filter(e=>e.isImage&&e.serverPath).map(e=>e.serverPath);if(!(!l.trim()&&c.length===0)){if(!n)try{let n=R,i=await E.post(`${T(n)}/chat/sessions`,{providerId:a,title:t.slice(0,50),clearedFrom:e?.clearedFrom,accountId:pe});r(i.id),o(i.providerId),j.current={content:l,permissionMode:D,images:c,imagePaths:u};return}catch(e){console.error(`Failed to create session:`,e);return}Re(l,{permissionMode:D,priority:s,...c.length>0&&{images:c},...u.length>0&&{imagePaths:u}})}},[n,a,R,Re,xt,D,e]),Ct=(0,Q.useRef)(s);Ct.current=s;let Et=(0,Q.useCallback)((e,t,r)=>{let i=e.trim().match(/^\/(\S+)(?:\s+([\s\S]+))?$/);if(i&&Ct.current.find(e=>e.handler===`client`&&(e.name===i[1]||e.aliases?.includes(i[1])))?.name===`clear`){fe(),mt(i[2]?.trim(),n??void 0);return}if(nt(void 0),fe(),rt&&n&&R){let n=rt.anchorMsgId;it(null),yt(xt(e,t),n);return}St(e,t,r)},[St,fe,rt,n,R,yt,xt,mt]),Dt=(0,Q.useRef)(_e);Dt.current=_e;let Ot=(0,Q.useCallback)(()=>Dt.current.filter(e=>e.role===`user`&&e.content.trim()).map(e=>e.content),[]),kt=(0,Q.useCallback)((e,t)=>{de(e,t)},[de]),At=(0,Q.useCallback)((e,t)=>{c(e),t&&g(t)},[]),jt=(0,Q.useCallback)((e,t)=>{u(e),f(t)},[]),Mt=(0,Q.useCallback)(e=>{m(e),u(!1),f(``),setTimeout(()=>m(null),50),R&&(E.post(`${T(R)}/chat/slash-recents`,{name:e.name,type:e.type}).catch(()=>{}),g(t=>[e.name,...t.filter(t=>t!==e.name)].slice(0,5)))},[R]),Nt=(0,Q.useCallback)(()=>{u(!1),f(``)},[]),Pt=(0,Q.useCallback)(()=>I(null),[]),Ft=(0,Q.useCallback)(e=>{L(e)},[]),It=(0,Q.useCallback)(e=>{I([e.path]),L(null)},[]),Lt=(0,Q.useCallback)((e,t)=>{b(e),S(t)},[]),Rt=(0,Q.useCallback)(e=>{ee(e),b(!1),S(``),setTimeout(()=>ee(null),50)},[]),Bt=(0,Q.useCallback)(()=>{b(!1),S(``)},[]);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full relative`,onDragEnter:(0,Q.useCallback)(e=>{e.preventDefault(),se.current++,(e.dataTransfer.types.includes(`application/x-ppm-path`)||e.dataTransfer.types.includes(`Files`))&&N(!0)},[]),onDragLeave:(0,Q.useCallback)(e=>{e.preventDefault(),se.current--,se.current===0&&N(!1)},[]),onDragOver:(0,Q.useCallback)(e=>{e.preventDefault()},[]),onDrop:(0,Q.useCallback)(e=>{e.preventDefault(),se.current=0,N(!1);let t=e.dataTransfer.getData(`application/x-ppm-path`);if(t){I([t]);return}let n=Array.from(e.dataTransfer.files);n.length>0&&(P(n),setTimeout(()=>P(null),100))},[]),children:[re&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm border-2 border-dashed border-primary rounded-lg pointer-events-none`,children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2 text-primary`,children:[(0,$.jsx)(ve,{className:`size-8`}),(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:`Drop files to attach`})]})}),Te&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-50 flex items-center justify-center bg-background/60 backdrop-blur-sm`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(w,{className:`size-4 animate-spin`}),(0,$.jsx)(`span`,{children:`Reconnecting...`})]})}),at&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-50 flex items-center justify-center bg-background/70 backdrop-blur-sm`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(w,{className:`size-4 animate-spin`}),(0,$.jsx)(`span`,{children:`Creating edited version…`})]})}),(0,$.jsx)($r,{shells:Ye,onKill:Xe}),(0,$.jsx)(Tr,{messages:q,onExpandCompact:ye,isCompactExpanded:be,messagesLoading:J,keepStaleWhileLoading:lt,pendingApproval:De,onApprovalResponse:Z,isStreaming:Y,phase:we,connectingElapsed:Ee,statusMessage:Ae,compactStatus:ke,projectName:R,onFork:Y?void 0:gt,onEdit:Y?void 0:_t,editingMsgId:rt?.ownMsgId,sessionId:n??void 0,providerId:a,onNavigateVersion:bt,versionMap:Ce,onSelectSession:ht,onDismissMessage:xe,onClearErrors:Se,bashPartialOutput:Je}),(0,$.jsx)(ri,{teamName:Ze,members:Qe,projectName:R}),(0,$.jsxs)(`div`,{className:`border-t border-border bg-panel shrink-0`,children:[(0,$.jsx)(Ta,{projectName:R,usageInfo:ce,usageLoading:le,refreshUsage:H,lastFetchedAt:V,sessionId:n,providerId:a,pickedAccountLabel:G?.label??(he?W:null),pickedAccountId:G?.id??(he?pe??null:null),onSelectAccount:ge,onSelectSession:ht,onBugReport:n?()=>We(B,{sessionId:n,projectName:R}):void 0,isConnected:He,onReload:()=>{He||Be(),Ve()},teamActivity:Ue,teamMessages:Ge,onTeamOpen:qe}),(0,$.jsx)(Yi,{items:s,filter:d,onSelect:Mt,onClose:Nt,visible:l,recentNames:h,projectName:R}),(0,$.jsx)(Xi,{items:_,filter:x,onSelect:Rt,onClose:Bt,visible:y}),oe&&(0,$.jsx)(Xi,{items:oe,filter:``,onSelect:It,onClose:()=>L(null),visible:!0}),rt&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1.5 text-xs text-muted-foreground border-t border-border bg-muted/40`,children:[(0,$.jsx)(`span`,{children:`Editing message — your next send replaces it`}),(0,$.jsxs)(`button`,{type:`button`,onClick:vt,className:`flex items-center gap-1 rounded px-2 py-1 min-h-[28px] hover:bg-accent hover:text-accent-foreground transition-colors`,title:`Cancel edit (send as a new message instead)`,children:[(0,$.jsx)(te,{className:`h-3.5 w-3.5`}),`Cancel`]})]}),(ft||!ue)&&(0,$.jsx)(Vi,{tabId:t,onSend:Et,isStreaming:Y,onCancel:ze,autoFocus:!e?.sessionId||!!tt,initialValue:tt??U?.content,clearSignal:st,projectName:R,onSlashStateChange:jt,onSlashItemsLoaded:At,slashSelected:p,onFileStateChange:Lt,onFileItemsLoaded:v,fileSelected:C,externalFiles:ae,externalPaths:F,onExternalPathsConsumed:Pt,onDisambiguate:Ft,onContentChange:kt,getUserHistory:Ot,permissionMode:D,onModeChange:A,providerId:a,sessionId:n??void 0,onProviderChange:n?void 0:o,model:Ne,onModelChange:Pe,effort:Fe,onEffortChange:X,thinking:Ie,onThinkingChange:Le})]})]})}export{Oa as ChatTab};