dorkos 0.98.0 → 0.101.0

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 (194) hide show
  1. package/README.md +43 -13
  2. package/dist/bin/cli.js +10649 -8676
  3. package/dist/browser/fresh-verifier.mjs +3 -2
  4. package/dist/browser/native/darwin-journal-worker.mjs +2244 -0
  5. package/dist/browser/native/darwin-process-observer +0 -0
  6. package/dist/browser/native/darwin-process-observer.c +252 -0
  7. package/dist/browser/native/darwin-process-observer.h +37 -0
  8. package/dist/browser/native/darwin-process-observer.manifest.json +1 -0
  9. package/dist/browser/native/darwin-supervisor-worker.mjs +1996 -0
  10. package/dist/browser/native/package-manifest.json +1 -0
  11. package/dist/browser/source-manifest.json +1 -1
  12. package/dist/client/assets/{AboutPage-DqTcRYx5.js → AboutPage-CwxCTicf.js} +1 -1
  13. package/dist/client/assets/ActivityRow-D0QQ0SFu.js +1 -0
  14. package/dist/client/assets/AdapterIcon-CL-MyyKy.js +1 -0
  15. package/dist/client/assets/AdapterSetupWizard-C8HOvHLF.js +2 -0
  16. package/dist/client/assets/AgentRequestCard-BLLmoAES.js +12 -0
  17. package/dist/client/assets/AppearancePage-GqrWckTQ.js +1 -0
  18. package/dist/client/assets/AttentionSignalRow-sEhnIPBB.js +1 -0
  19. package/dist/client/assets/{BaseTanStackRouterDevtoolsPanel-B-iktbLX-Bmlsorom.js → BaseTanStackRouterDevtoolsPanel-B-iktbLX-BXjzhT_D.js} +1 -1
  20. package/dist/client/assets/{BlintzCanvas-BBW7iNEC.js → BlintzCanvas-CXi0fvcM.js} +1 -1
  21. package/dist/client/assets/{CanvasCsvContent-D6qWSQm4.js → CanvasCsvContent-QhDSf8Pd.js} +2 -2
  22. package/dist/client/assets/CanvasFileContent-ZZhdofR4.js +2 -0
  23. package/dist/client/assets/CanvasModel3dContent-DMMMZh4o.js +2 -0
  24. package/dist/client/assets/{CodeMirrorDiff-DsOh9sIB.js → CodeMirrorDiff-BMG7DBg2.js} +1 -1
  25. package/dist/client/assets/{CodeMirrorEditor-BxIWDXqr.js → CodeMirrorEditor-BYdz0ipX.js} +1 -1
  26. package/dist/client/assets/ConnectionAccessLists-PW1uzcGU.js +1 -0
  27. package/dist/client/assets/{ConnectionsPage-DvxSfsfG.js → ConnectionsPage-EwitZwOE.js} +3 -3
  28. package/dist/client/assets/ConventionPage-y-Zq3Klp.js +11 -0
  29. package/dist/client/assets/ExtensionPageRoute-gZKKPhaj.js +6 -0
  30. package/dist/client/assets/{FloatingTanStackRouterDevtools-CqogiFob-BCrkUo51.js → FloatingTanStackRouterDevtools-CqogiFob-CbKIa11X.js} +1 -1
  31. package/dist/client/assets/HandlePage-CL3_n1CI.js +1 -0
  32. package/dist/client/assets/{LexicalField-mvJHHMqo.js → LexicalField-Ceoa9flp.js} +13 -13
  33. package/dist/client/assets/{ManagesPage-DScJn5uY.js → ManagesPage-Dcqdm6I8.js} +1 -1
  34. package/dist/client/assets/Marketplace-DsU-q1ZZ.js +36 -0
  35. package/dist/client/assets/MarketplaceSourcesView-D72YoKNR.js +1 -0
  36. package/dist/client/assets/McpAppFrame-B1ThSf2U.js +6 -0
  37. package/dist/client/assets/McpSigninBody-Btg3PnYN.js +1 -0
  38. package/dist/client/assets/{Model3dViewer-BYNxJNRV.js → Model3dViewer-DlcQ3-LS.js} +1 -1
  39. package/dist/client/assets/NamePage-Bzqj4Eob.js +1 -0
  40. package/dist/client/assets/NewDirectMessageMenu-89yeGqvy.js +1 -0
  41. package/dist/client/assets/{NotificationsPage-CU6oIOwb.js → NotificationsPage-CQQIdLtI.js} +1 -1
  42. package/dist/client/assets/OperatorIdentityForm-BhiB9tQp.js +1 -0
  43. package/dist/client/assets/{PermissionsPage-BIatOhyg.js → PermissionsPage-TX-d7aVQ.js} +1 -1
  44. package/dist/client/assets/PersonalityPicker-C_9JVOva.js +1 -0
  45. package/dist/client/assets/PersonalityPopover-BoTED73t.js +1 -0
  46. package/dist/client/assets/PhotoPage-C3fMlebQ.js +1 -0
  47. package/dist/client/assets/PreviewRefusedNotice-ChCgdKWN.js +1 -0
  48. package/dist/client/assets/PromptSuggestionChips-B_oUtFMI.js +1 -0
  49. package/dist/client/assets/RoomSurface-CgtNuYhl.js +39 -0
  50. package/dist/client/assets/RoomsPage-zOjjpHdA.js +1 -0
  51. package/dist/client/assets/RunsOnPopover-JTm1cYuw.js +1 -0
  52. package/dist/client/assets/SessionsPage-D4kyvHQf.js +6 -0
  53. package/dist/client/assets/SkillsPage-KYUVzuVa.js +1 -0
  54. package/dist/client/assets/TasksPage-BZapA_v6.js +1 -0
  55. package/dist/client/assets/{ToolsPage-BMW27c-X.js → ToolsPage-CWpHMlrR.js} +2 -2
  56. package/dist/client/assets/{TopologyGraph-u-ihEvQa.js → TopologyGraph-BMcPxZsA.js} +3 -3
  57. package/dist/client/assets/TourHost-VY1-sy1Y.js +1 -0
  58. package/dist/client/assets/UnlinkDialog-3p38G_9q.js +1 -0
  59. package/dist/client/assets/UnreadDivider-KSqqcHKN.js +1 -0
  60. package/dist/client/assets/_shell-DAjwimLg.js +93 -0
  61. package/dist/client/assets/_shell._home-Bp_p1VUv.js +1 -0
  62. package/dist/client/assets/_shell._home.activity-tk-XApvX.js +1 -0
  63. package/dist/client/assets/_shell._home.index-BNVhSN0y.js +3 -0
  64. package/dist/client/assets/_shell._home.tasks-BsBH_4tZ.js +1 -0
  65. package/dist/client/assets/_shell._home.workspaces-DuXnjQh0.js +1 -0
  66. package/dist/client/assets/_shell.channels-DWAHkDPV.js +10 -0
  67. package/dist/client/assets/_shell.connections-DIm3mUHy.js +6 -0
  68. package/dist/client/assets/_shell.feedback-requests-Hjv640j9.js +2 -0
  69. package/dist/client/assets/_shell.marketplace-DF6Y7mc0.js +1 -0
  70. package/dist/client/assets/_shell.marketplace_.sources-Do8cm7kq.js +1 -0
  71. package/dist/client/assets/_shell.session-DlN8iOl-.js +43 -0
  72. package/dist/client/assets/_shell.team-ctLQztjw.js +28 -0
  73. package/dist/client/assets/_shell.x._extensionId-0Q1rJtud.js +1 -0
  74. package/dist/client/assets/_shell.x._extensionId_._-0Q1rJtud.js +1 -0
  75. package/dist/client/assets/agent-attention-Dn__3LQE.js +5 -0
  76. package/dist/client/assets/{agent-browser-Bn5EG403.js → agent-browser-CCN16ZOz.js} +1 -1
  77. package/dist/client/assets/banner-DOm9_4l-.js +6 -0
  78. package/dist/client/assets/composer-insert-BpyATrmR.js +1 -0
  79. package/dist/client/assets/dorkbot-templates-cu4wApxb.js +1 -0
  80. package/dist/client/assets/file-drag-GDx2qhdk.js +1 -0
  81. package/dist/client/assets/file-exclamation-point-BKzL0QhY.js +6 -0
  82. package/dist/client/assets/format-duration-BCr6uzby.js +1 -0
  83. package/dist/client/assets/hand-DLUdsiuR.js +6 -0
  84. package/dist/client/assets/{highlighted-body-KPVGNVTW-CL9x-9e4.js → highlighted-body-KPVGNVTW-DTxMTVdP.js} +1 -1
  85. package/dist/client/assets/hover-card-qzuFUCaR.js +1 -0
  86. package/dist/client/assets/{index-nEOi__50.js → index-3lQkXKcq.js} +1 -1
  87. package/dist/client/assets/{index-CpJvQdyn.js → index-B-z7hA9x.js} +1 -1
  88. package/dist/client/assets/{index-C-wQjAlh.js → index-BIMClIrX.js} +1 -1
  89. package/dist/client/assets/{index-lrzDDn8S.js → index-BMOfHKE0.js} +1 -1
  90. package/dist/client/assets/{index-CK35WFBO.js → index-BPcwoJoz.js} +1 -1
  91. package/dist/client/assets/{index-CsQv_9cY.js → index-BW5ce4t8.js} +1 -1
  92. package/dist/client/assets/{index-C2L0bOg6.js → index-BaB-skF0.js} +3 -3
  93. package/dist/client/assets/{index-DAXybyxB.js → index-Bk98IpMn.js} +1 -1
  94. package/dist/client/assets/{index-62aJQhJd.js → index-C3XnoXTY.js} +1 -1
  95. package/dist/client/assets/{index-tY8nAJmx.js → index-C7B2uRgo.js} +2 -2
  96. package/dist/client/assets/index-C8ZMfyGc.js +1 -0
  97. package/dist/client/assets/{index-BSl_jWtK.js → index-CDTumWMC.js} +1 -1
  98. package/dist/client/assets/{index-DuWGfUC7.js → index-CF9fqPef.js} +5 -5
  99. package/dist/client/assets/{index-DEYZcwYZ.js → index-CIPHHziB.js} +1 -1
  100. package/dist/client/assets/{index-DOVEs6Rq.js → index-CIfwPLXd.js} +1 -1
  101. package/dist/client/assets/{index-DnjFcJhW.js → index-CLhD0Bno.js} +36 -36
  102. package/dist/client/assets/index-CQWqpw_G.js +1 -0
  103. package/dist/client/assets/index-CScfHuKF.js +1 -0
  104. package/dist/client/assets/index-CTXNRyRE.js +1 -0
  105. package/dist/client/assets/{index-C3fr7zOo.js → index-CTai_TxZ.js} +1 -1
  106. package/dist/client/assets/{index-CniKYwdp.js → index-CVl132_4.js} +1 -1
  107. package/dist/client/assets/index-CejezM4U.js +1 -0
  108. package/dist/client/assets/{index-Bc9XDEj8.js → index-CmlaXay_.js} +1 -1
  109. package/dist/client/assets/{index-KIOfBCox.js → index-CtOB9fS3.js} +1 -1
  110. package/dist/client/assets/{index-DyFf2nbN.js → index-D3DXMH4x.js} +1 -1
  111. package/dist/client/assets/index-D5uYwabS.js +1 -0
  112. package/dist/client/assets/{index-CaEda4s3.js → index-DA-i3I4q.js} +1 -1
  113. package/dist/client/assets/index-DFMDv6qR.js +1 -0
  114. package/dist/client/assets/index-DMYBI16t.js +1252 -0
  115. package/dist/client/assets/{index-DzBsotRj.js → index-DOxEmnH2.js} +1 -1
  116. package/dist/client/assets/{index-Dxkj6c9m.js → index-DR1JT9Uz.js} +12 -12
  117. package/dist/client/assets/{index-BO-CpekL.js → index-DT_v3O-B.js} +1 -1
  118. package/dist/client/assets/index-DbbZNAKk.js +5 -0
  119. package/dist/client/assets/{index-BBz-vkiB.js → index-Dcs6e-U_.js} +1 -1
  120. package/dist/client/assets/{index-BE54c4kA.js → index-DgH_dl1a.js} +2 -2
  121. package/dist/client/assets/{index-DPGgujWh.js → index-DgtF-nBt.js} +1 -1
  122. package/dist/client/assets/{index-BlbBz069.js → index-DwzSdOh3.js} +1 -1
  123. package/dist/client/assets/index-IgIVF9T_.js +1 -0
  124. package/dist/client/assets/{index-aFkVVlMJ.js → index-WjW-NUCp.js} +1 -1
  125. package/dist/client/assets/layers-CJHXSEKK.js +6 -0
  126. package/dist/client/assets/lightbulb-DWjxw7lb.js +6 -0
  127. package/dist/client/assets/mention-pill-akMU3IVs.js +1 -0
  128. package/dist/client/assets/message-square-off-DEagHpQY.js +6 -0
  129. package/dist/client/assets/owner-notice-CLsx0s7q.js +1 -0
  130. package/dist/client/assets/page-container-W7byjRmk.js +1 -0
  131. package/dist/client/assets/primer-trigger-DuM9vVnV.js +3 -0
  132. package/dist/client/assets/radio-B8Ozjv9U.js +6 -0
  133. package/dist/client/assets/{room-files-source-BXJ2jlgd.js → room-files-source-Bsc3YA91.js} +2 -2
  134. package/dist/client/assets/rotate-ccw-clock-CNcDcTvq.js +6 -0
  135. package/dist/client/assets/rotate-cw-xvfipJLN.js +6 -0
  136. package/dist/client/assets/scroll-area-C95q3ss7.js +1 -0
  137. package/dist/client/assets/search-x-C6SAxw7a.js +6 -0
  138. package/dist/client/assets/session-strategy-labels-C7Wduch3.js +1 -0
  139. package/dist/client/assets/shield-x-DxOGc0dW.js +6 -0
  140. package/dist/client/assets/{soul-file-11avkxYV.js → soul-file-pg0ShYy3.js} +1 -1
  141. package/dist/client/assets/untrusted-text-1hXdPgLA.js +1 -0
  142. package/dist/client/assets/use-delete-binding-CZVeHqn0.js +1 -0
  143. package/dist/client/assets/use-dev-links-Df2WkCic.js +1 -0
  144. package/dist/client/assets/use-external-adapter-catalog-B0gcY-k7.js +1 -0
  145. package/dist/client/assets/use-full-activity-feed-SYcgdMZu.js +1 -0
  146. package/dist/client/assets/use-is-below-desktop-C5_YenEp.js +1 -0
  147. package/dist/client/assets/use-jump-back-in-DWUPb1gi.js +11 -0
  148. package/dist/client/assets/use-mesh-topology-HLzZIgis.js +1 -0
  149. package/dist/client/assets/use-pending-read-BuJknrxG.js +1 -0
  150. package/dist/client/assets/{use-personality-commit-PCN2Kh8p.js → use-personality-commit-OH7d0xl_.js} +1 -1
  151. package/dist/client/assets/use-promo-activation-BgdGasXE.js +11 -0
  152. package/dist/client/assets/use-pulse-freshness-BlD-dM_g.js +1 -0
  153. package/dist/client/assets/use-rename-session-D3MuyK-F.js +1 -0
  154. package/dist/client/assets/use-room-follow-claim-CyjhzbRJ.js +1 -0
  155. package/dist/client/assets/use-roving-tab-list-Be60AWK3.js +1 -0
  156. package/dist/client/assets/use-session-canvas-Bqs6IQO7.js +64 -0
  157. package/dist/client/assets/use-session-diagnostics-CfKdB2iY.js +16 -0
  158. package/dist/client/assets/use-unclaimed-chats-lqMhotUB.js +1 -0
  159. package/dist/client/index.html +1 -1
  160. package/dist/client/manifest.webmanifest +1 -1
  161. package/dist/drizzle/20261005194144_connector_auth_flow_failure_code.sql +1 -0
  162. package/dist/drizzle/20261005230915_task_run_occurrence.sql +2 -0
  163. package/dist/drizzle/20261006231015_audit_events.sql +63 -0
  164. package/dist/drizzle/20261007230701_private_session_identity.sql +15 -0
  165. package/dist/drizzle/meta/20261005194144_snapshot.json +12238 -0
  166. package/dist/drizzle/meta/20261005230915_snapshot.json +12252 -0
  167. package/dist/drizzle/meta/20261006231015_snapshot.json +12519 -0
  168. package/dist/drizzle/meta/20261007230701_snapshot.json +12611 -0
  169. package/dist/drizzle/meta/_journal.json +28 -0
  170. package/dist/server/index.js +161811 -97213
  171. package/dist/server/index.js.map +2 -2
  172. package/package.json +5 -5
  173. package/dist/client/assets/AdapterIcon-CiK683Vv.js +0 -1
  174. package/dist/client/assets/AppearancePage-CBq2_KUY.js +0 -1
  175. package/dist/client/assets/CanvasFileContent-jV63reY5.js +0 -2
  176. package/dist/client/assets/CanvasModel3dContent-DzvsEWGD.js +0 -2
  177. package/dist/client/assets/ConnectionAccessLists-BWuegEtZ.js +0 -1
  178. package/dist/client/assets/ConventionPage-CYV7X_nF.js +0 -11
  179. package/dist/client/assets/HandlePage-CJpRpaLw.js +0 -1
  180. package/dist/client/assets/NamePage-KoYyo25o.js +0 -1
  181. package/dist/client/assets/PersonalityPopover-CFRYfO5E.js +0 -1
  182. package/dist/client/assets/PhotoPage-DkGyFlWQ.js +0 -1
  183. package/dist/client/assets/RoomsPage-ClT030eV.js +0 -1
  184. package/dist/client/assets/RunsOnPopover-CNCO9sZk.js +0 -1
  185. package/dist/client/assets/SessionsPage-5xEcQImi.js +0 -6
  186. package/dist/client/assets/SkillsPage-ic4TDV4I.js +0 -1
  187. package/dist/client/assets/TasksPage-C_GFpRgB.js +0 -1
  188. package/dist/client/assets/index-6COO_Ljw.js +0 -1
  189. package/dist/client/assets/index-BKl9b2dT.js +0 -1
  190. package/dist/client/assets/index-BVtk6Sb_.js +0 -1
  191. package/dist/client/assets/index-Bxrxl2HH.js +0 -1
  192. package/dist/client/assets/index-C6uVMs3w.js +0 -1
  193. package/dist/client/assets/index-DEvFAO8t.js +0 -1
  194. package/dist/client/assets/index-DpSk7iO1.js +0 -1680
@@ -0,0 +1,43 @@
1
+ var Lo=Object.defineProperty;var Uo=(e,t,n)=>t in e?Lo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Qe=(e,t,n)=>Uo(e,typeof t!="symbol"?t+"":t,n);import{r as i,Y as pt,j as s,O as X,bd as ue,hC as Cn,od as Js,kz as qo,Q as be,ah as zo,oe as Bo,aZ as Ho,aa as V,of as jt,X as Me,aF as et,aU as Oe,og as nt,dG as Ft,hd as Ie,he as Pe,oh as Lt,g3 as De,dC as ht,iE as Wo,bM as Go,hx as Ko,oi as Qo,kJ as Jn,h2 as Zs,hh as Vo,C as wn,oj as Yo,ok as Ut,ol as Xo,om as Jo,aB as Zo,gm as ea,bT as ta,bl as na,gV as sa,on as qe,am as Nn,e6 as Zn,f as er,oo as es,dz as ts,dx as tt,op as ra,oq as oa,or as ct,os as Pt,ad as st,ot as Tn,U as ut,hj as gt,T as An,bN as xt,cR as aa,cS as ia,cT as la,cU as ca,cV as ua,ew as da,e as ns,jD as ma,cW as fa,B as ie,jE as pa,hi as Rn,dk as ha,ou as ga,ov as xa,ow as En,ox as tr,oy as nr,h5 as ba,h6 as ya,R as _n,c7 as bt,dw as Mn,dt as On,oz as sr,du as ka,oA as Sa,oB as rr,oC as va,h3 as ja,aW as ot,gx as Ca,hM as or,hI as ar,lp as dt,oD as ir,oE as wa,oF as Na,oG as Ta,oH as Aa,oI as lr,aD as oe,oJ as Ra,oK as Ea,oL as _a,oM as Ma,oN as cr,w as qt,ab as ur,oO as Oa,ms as Qt,oP as dr,oQ as rt,iS as Ia,oR as Pa,I as Da,oS as $a,oT as Vt,dX as Fa,oU as La,oV as Ua,f9 as qa,oW as mr,it as za,jT as Ba,a$ as fr,oX as Ha,oY as Wa,oZ as pn,o_ as pr,o$ as Ga,p0 as Ka,p1 as hr,p2 as Qa,p3 as Va,p4 as Ya,p5 as Xa,p6 as ss,p7 as rs,p8 as Ja,p9 as Za,pa as os,pb as gr,pc as ei,pd as ti,pe as xr,pf as ni,pg as si,ph as br,hQ as yr,hR as ri,eH as oi,kI as ai,pi as ii,fG as li,fH as ci,fI as ui,fJ as di,fK as mi,fL as fi,fM as pi,fN as hi,W as we,pj as kr,pk as Sr,pl as hn,pm as gi,pn as as,po as xi,le as bi,h8 as yi,h9 as ki,ha as Si,hb as Yt,pp as vi,hc as is,iD as ji,bq as Ci,iF as wi,bt as Ni,pq as ls,bW as Ti,fo as vr,c0 as jr,bR as Ai,b$ as Ri,c6 as Cr,c4 as Ei,h4 as In,pr as _i,aj as Mi,ps as Oi,kS as ne,pt as Ii,kQ as Pi,pu as cs,pv as Di,pw as $i,b_ as us,a3 as Fi,g9 as wr,gd as ze,hw as mt,fi as ds,V as Ue,px as Xt,m6 as at,py as Ce,pz as ms,pA as fs,pB as ps,pC as Jt,pD as Je,eB as it,pE as Li,pF as Nr,pG as Tr,pH as Ui,pI as qi,pJ as Ar,lr as zi,pK as Rr,pL as Ve,ku as Er,pM as Bi,bp as Hi,ds as _r,lq as Wi,pN as Gi,pO as Ki,hH as Mr,pP as Qi,by as hs,nH as Or,dQ as Vi,hA as Yi,pQ as Xi,gg as Ji,hE as Zi,dM as el,pR as tl,pS as nl,ge as Ir,gf as Pn,j7 as sl,fY as Dn,lP as rl,pT as ol,pU as al,pV as il,pW as ll,ga as cl,pX as ul,pY as dl,pZ as ml,c8 as fl,id as pl,lv as hl,e$ as gl,kC as xl,d6 as bl}from"./index-DMYBI16t.js";import{P as yl}from"./PromptSuggestionChips-B_oUtFMI.js";import{F as kl,f as Sl,u as vl,a as jl,L as Cl,T as wl,r as Nl,b as Tl,c as Al,B as Rl,d as El}from"./primer-trigger-DuM9vVnV.js";import{E as _l,e as Ml,h as Ol,f as Il,P as Pl,g as Dl,d as $l,q as Fl,j as Ll,b as Ul,G as ql,B as zl,F as Pr,z as Bl,u as Hl,D as Wl,v as Gl,t as Kl,p as Ql,w as Vl,y as Yl,o as Xl,n as Jl,k as Zl,s as ec,M as tc,i as nc,S as sc,U as rc,A as oc,H as ac,I as ic,J as gs,x as lc,R as cc}from"./use-session-diagnostics-CfKdB2iY.js";import{B as uc}from"./banner-DOm9_4l-.js";import{g as dc,N as Dr,h as mc,C as ft,f as fc,M as Ye,d as pc}from"./index-DbbZNAKk.js";import{u as hc}from"./use-rename-session-D3MuyK-F.js";import{a as gc,c as xc}from"./composer-insert-BpyATrmR.js";import{A as gn,M as bc}from"./McpAppFrame-B1ThSf2U.js";import{u as yc,b as kc,f as Sc,D as vc,U as jc}from"./UnreadDivider-KSqqcHKN.js";import{S as Cc}from"./shield-x-DxOGc0dW.js";import{u as wc,M as Nc}from"./McpSigninBody-Btg3PnYN.js";import{f as Tc}from"./format-duration-BCr6uzby.js";import{J as Ac,A as Rc}from"./AgentRequestCard-BLLmoAES.js";import{F as Ec,h as _c}from"./use-session-canvas-Bqs6IQO7.js";import"./use-is-below-desktop-C5_YenEp.js";import"./layers-CJHXSEKK.js";import"./hover-card-qzuFUCaR.js";import"./file-drag-GDx2qhdk.js";import"./index-CejezM4U.js";import"./rotate-cw-xvfipJLN.js";function Mc(e){const t=Math.floor(e/1e3);if(t<3600){const o=Math.floor(t/60),a=t%60;return`${o}m ${String(a).padStart(2,"0")}s`}const n=Math.floor(t/3600),r=Math.floor(t%3600/60);return`${n}h ${String(r).padStart(2,"0")}m`}function $r(e){const[t,n]=i.useState(()=>Date.now()),r=i.useRef(null);if(i.useEffect(()=>{if(e===null){r.current&&(clearInterval(r.current),r.current=null);return}return n(Date.now()),r.current=setInterval(()=>n(Date.now()),1e3),()=>{r.current&&(clearInterval(r.current),r.current=null)}},[e]),e===null)return{formatted:"0m 00s",ms:0};const o=Math.max(0,t-e);return{formatted:Mc(o),ms:o}}function Oc(e={}){const{timeoutMs:t=3e4,onIdle:n,onReturn:r}=e,o=i.useRef(!1),a=i.useRef(null),l=i.useCallback(()=>{o.current||(o.current=!0,n==null||n())},[n]),c=i.useCallback(()=>{o.current&&(o.current=!1,r==null||r())},[r]),u=i.useCallback(()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(l,t),c()},[t,l,c]);return i.useEffect(()=>{a.current=setTimeout(l,t);const d=["mousemove","keydown","scroll","touchstart"];d.forEach(p=>document.addEventListener(p,u,{passive:!0}));const m=()=>{document.hidden?l():u()};return document.addEventListener("visibilitychange",m),()=>{a.current&&clearTimeout(a.current),d.forEach(p=>document.removeEventListener(p,u)),document.removeEventListener("visibilitychange",m)}},[t,l,u]),{isIdle:o.current}}function Ic({activeInteraction:e,onApprove:t,onAlwaysAllow:n,onDeny:r,onToggleOption:o,onNavigateOption:a,onNavigateQuestion:l,onSubmit:c,optionCount:u=0,focusedIndex:d=0}){const m=i.useRef(!1);i.useEffect(()=>{m.current=!1},[e==null?void 0:e.toolCallId]),i.useEffect(()=>{if(!e)return;function p(f){const h=f.target,g=(h.tagName==="TEXTAREA"||h.tagName==="INPUT")&&!h.disabled;if(!m.current&&!(f.metaKey||f.ctrlKey||f.altKey)){if(e.type==="approval"){if(f.key==="Enter"&&g&&h.closest("[data-approval-field]")!==null)return;f.key==="Enter"&&f.shiftKey?(f.preventDefault(),m.current=!0,n==null||n()):f.key==="Enter"?(f.preventDefault(),m.current=!0,t==null||t()):f.key==="Escape"&&(f.preventDefault(),m.current=!0,r==null||r());return}if(e.type==="question"){if(g){if(f.key==="Enter"&&!f.shiftKey){f.preventDefault(),c==null||c();return}if(f.key==="ArrowUp"){f.preventDefault(),a==null||a("up");return}if(f.key==="ArrowDown"){f.preventDefault(),a==null||a("down");return}return}const b=parseInt(f.key,10);if(b>=1&&b<=9){f.preventDefault(),b-1<u&&(o==null||o(b-1));return}switch(f.key){case"ArrowUp":f.preventDefault(),a==null||a("up");break;case"ArrowDown":f.preventDefault(),a==null||a("down");break;case" ":f.preventDefault(),o==null||o(d);break;case"ArrowLeft":case"[":f.preventDefault(),l==null||l("prev");break;case"ArrowRight":case"]":f.preventDefault(),l==null||l("next");break;case"Enter":f.preventDefault(),c==null||c();break}}}}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[e,t,n,r,o,a,l,c,u,d])}function Fr(){const[e,t]=i.useState(()=>!document.hidden);return i.useEffect(()=>{const n=()=>t(!document.hidden);return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[]),e}/**
2
+ * @license lucide-react v1.48.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Lr={name:"brain",size:24,node:[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]]};Lr.node;const Pc=pt(Lr);/**
7
+ * @license lucide-react v1.48.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const Ur={name:"file-image",size:24,node:[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]};Ur.node;const Dc=pt(Ur);/**
12
+ * @license lucide-react v1.48.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const qr={name:"file-spreadsheet",size:24,node:[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]};qr.node;const $c=pt(qr);/**
17
+ * @license lucide-react v1.48.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const zr={name:"image-off",size:24,node:[["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"}]]};zr.node;const Fc=pt(zr);/**
22
+ * @license lucide-react v1.48.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Br={name:"mouse-pointer-click",size:24,node:[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]};Br.node;const Lc=pt(Br);function Uc({color:e,isTextStreaming:t,fadeEdges:n=!0,edge:r="bottom"}){const o=t?1.8:2.5,a=n?"linear-gradient(to right, transparent, black 15%, black 85%, transparent)":void 0,l=r==="top"?"pointer-events-none absolute right-0 top-0 left-0":"pointer-events-none absolute right-0 bottom-0 left-0",c=r==="top"?"top":"bottom";return s.jsxs(X.div,{"aria-hidden":!0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.4},className:l,style:{height:n?10:0,overflow:n?"hidden":"visible",maskImage:a,WebkitMaskImage:a},children:[s.jsx("div",{className:"absolute right-0 left-0",style:{[c]:0,height:6,backgroundColor:e,opacity:.6,filter:"blur(3px)"}}),s.jsx(X.div,{initial:{x:"-100%"},animate:{x:"433%"},transition:{x:{duration:o,repeat:1/0,ease:"linear"}},className:"absolute",style:{[c]:0,width:"30%",height:2,background:`linear-gradient(to right, transparent, ${e}, white, transparent)`,willChange:"transform"}}),s.jsx(ue,{children:t&&s.jsx(X.div,{initial:{opacity:0,x:"-100%"},animate:{opacity:.9,x:"1525%"},exit:{opacity:0},transition:{x:{duration:1.1,repeat:1/0,ease:"linear"},opacity:{duration:.2}},className:"absolute",style:{[c]:0,width:"8%",height:1,background:"linear-gradient(to right, transparent, white 40%, white 60%, transparent)",willChange:"transform"}})})]})}const Zt={"word-boundary":3,substring:2,subsequence:1},qc=new Set(["/",":","-","_","."," "]);function zc(e,t){if(t===0)return!0;const n=e[t-1];if(qc.has(n))return!0;const r=e[t];return n===n.toLowerCase()&&r!==r.toLowerCase()&&r===r.toUpperCase()}function Ct(e,t){return Array.from({length:t},(n,r)=>e+r)}function wt(e,t,n){const r=1/(1+t),o=n/e.length;return(r*.6+o*.4)*.999}function Bc(e,t){let n=0,r=0,o=0;const a=[];for(let l=0;l<t.length&&n<e.length;l++)t[l]===e[n]?(n++,r++,r>o&&(o=r),a.push(l)):r=0;return n===e.length?{indices:a,maxRun:o}:null}function Hc(e,t){const n=t.indices[t.indices.length-1]-t.indices[0]+1,r=t.maxRun/t.indices.length,o=t.indices.length/n,a=t.indices.length/e.length;return(r*.4+o*.3+a*.3)*.999}function Mt(e,t){if(!e)return{match:!0,tier:null,score:0,indices:[]};const n=e.toLowerCase(),r=t.toLowerCase();if(r===n)return{match:!0,tier:"exact",score:5+wt(t,0,n.length),indices:Ct(0,n.length)};if(r.startsWith(n))return{match:!0,tier:"prefix",score:4+wt(t,0,n.length),indices:Ct(0,n.length)};for(let l=1;l<=r.length-n.length;l++)if(zc(t,l)&&r.startsWith(n,l))return{match:!0,tier:"word-boundary",score:Zt["word-boundary"]+wt(t,l,n.length),indices:Ct(l,n.length)};const o=r.indexOf(n);if(o>=0)return{match:!0,tier:"substring",score:Zt.substring+wt(t,o,n.length),indices:Ct(o,n.length)};const a=Bc(n,r);return a?{match:!0,tier:"subsequence",score:Zt.subsequence+Hc(t,a),indices:a.indices}:{match:!1,tier:null,score:0,indices:[]}}function Hr(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}function Wc(e,t){return e.length<=t?e:e.slice(0,t)+"…"}function Gc(e){return/^[/~.]/.test(e)||/\.(ts|tsx|js|jsx|json|md|py|rs|go|sh|yml|yaml|toml)$/.test(e)}function xn(e,t){if(e===null)return s.jsx("span",{className:"text-muted-foreground italic",children:"null"});if(typeof e=="boolean")return s.jsx("span",{className:"text-amber-600 dark:text-amber-400",children:String(e)});if(typeof e=="number")return s.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:e});if(typeof e=="string"){const n=Wc(e,t);return Gc(e)?s.jsx("code",{className:"bg-muted rounded px-1 py-0.5 text-xs break-all",children:n}):s.jsx("span",{className:"break-words",children:n})}if(Array.isArray(e)){const n=e.slice(0,5),r=e.length-5;return s.jsxs("div",{className:"space-y-0.5",children:[n.map((o,a)=>s.jsx("div",{className:"border-border/40 border-l pl-2",children:xn(o,80)},a)),r>0&&s.jsxs("span",{className:"text-muted-foreground text-xs italic",children:["… and ",r," more"]})]})}if(typeof e=="object"){const n=Object.entries(e);return s.jsx("div",{className:"space-y-0.5",children:n.map(([r,o])=>s.jsxs("div",{className:"border-border/40 border-l pl-2",children:[s.jsxs("span",{className:"text-muted-foreground text-xs",children:[Hr(r),": "]}),typeof o=="object"&&o!==null?s.jsx("span",{className:"text-muted-foreground italic",children:"{…}"}):xn(o,80)]},r))})}return s.jsx("span",{children:String(e)})}function Wr({toolName:e,input:t,isStreaming:n=!1}){if(!t)return null;if(n){const a=t.length>5120?t.slice(0,5120)+"…":t;return s.jsxs("pre",{className:"text-muted-foreground overflow-x-auto text-xs whitespace-pre-wrap",children:[a,s.jsx("span",{className:"animate-breath ml-0.5 inline-block size-1.5 rounded-full bg-current"})]})}let r;try{r=JSON.parse(t)}catch{const a=t.length>5120?t.slice(0,5120)+"…":t;return s.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:a})}if(typeof r!="object"||r===null||Array.isArray(r)){const a=t.length>5120?t.slice(0,5120)+"…":t;return s.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:a})}const o=Object.entries(r);return o.length===0?null:s.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:o.map(([a,l])=>s.jsxs("div",{className:"contents",children:[s.jsx("dt",{className:"text-muted-foreground py-0.5 font-medium whitespace-nowrap",children:Hr(a)}),s.jsx("dd",{className:"min-w-0 py-0.5",children:xn(l,120)})]},a))})}class Kc{constructor(t){Qe(this,"config");Qe(this,"recentCompletions",[]);Qe(this,"queue",[]);Qe(this,"isIdle",!1);Qe(this,"debounceTimer",null);this.config=t}onTaskCompleted(t,n){if(!this.config.enabled)return;const r=Date.now();this.recentCompletions.push(r),this.recentCompletions=this.recentCompletions.filter(c=>r-c<this.config.debounceWindowMs);const o=n.length,a=n.filter(c=>c.status==="completed").length;if(o>=this.config.minTasksForMajor&&a===o){this.cancelDebounce();const c={level:"major",taskId:t,timestamp:r};this.emitOrQueue(c);return}if(this.recentCompletions.length>=this.config.debounceThreshold){this.cancelDebounce(),this.debounceTimer=setTimeout(()=>{const c={level:"mini",taskId:t,timestamp:Date.now()};this.emitOrQueue(c),this.recentCompletions=[]},this.config.debounceWindowMs);return}if(Math.random()<this.config.miniProbability){const c={level:"mini",taskId:t,timestamp:r};this.emitOrQueue(c)}}setIdle(t){this.isIdle=t}onUserReturn(){if(this.queue.length>0){const n=this.queue.some(r=>r.level==="major")?this.queue.find(r=>r.level==="major"):this.queue[this.queue.length-1];this.config.onCelebrate(n),this.queue=[]}}destroy(){this.cancelDebounce(),this.queue=[],this.recentCompletions=[]}emitOrQueue(t){this.isIdle?this.queue.push(t):this.config.onCelebrate(t)}cancelDebounce(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}const Qc={background:"radial-gradient(circle, rgba(255,215,0,0.15) 0%, transparent 70%)"};function Vc(e,t=40){if(e.length<=t)return e;const n=e.split("/").pop()??e,r=n.length+2,o=Math.max(6,t-r);return`${e.slice(0,o)}…/${n}`}function zt(e){var n;const{sessions:t}=Cn();if(e)return(n=t.find(r=>r.id===e))==null?void 0:n.runtime}function Gr(){const e=Js(),t=qo(e.session);return{cwd:(t==null?void 0:t.cwd)??e.dir??null}}const Yc="dorkos:chat:last-seen:";function Xc(){try{const e=[];for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n!=null&&n.startsWith(Yc)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}catch{}}function Jc(e){let t=0;for(const n of e)n._streaming!==!0&&t++;return t}function Zc(e){if(typeof e!="object"||e===null)return!1;const{userId:t,threadKind:n,threadId:r,lastReadSeq:o}=e;return typeof t=="string"&&typeof n=="string"&&typeof r=="string"&&typeof o=="number"&&Number.isInteger(o)}function eu(e,t){const n=be(),[r,o]=i.useState(()=>({sessionId:e,lastReadSeq:null,hydrated:!1}));r.sessionId!==e&&o({sessionId:e,lastReadSeq:null,hydrated:!1});const a=i.useRef(0),l=i.useRef(null),c=i.useRef(!1),u=i.useRef(!1),d=i.useRef(e),m=i.useRef(null),p=Jc(t);i.useEffect(()=>{Xc();let S=!1;return d.current=e,a.current=0,l.current=null,c.current=!1,u.current=!1,(async()=>{let v=null;try{v=await n.getReadCursor("session",e)}catch{}S||(v&&(a.current=v.lastReadSeq,m.current=v.userId),o({sessionId:e,lastReadSeq:(v==null?void 0:v.lastReadSeq)??null,hydrated:!0}))})(),()=>{S=!0}},[n,e]);const f=i.useCallback(async()=>{if(!c.current){c.current=!0;try{for(;;){const S=l.current;if(S===null)break;if(l.current=null,S.sessionId!==d.current)continue;if(u.current)break;const v=a.current;a.current=Math.max(v,S.seq);try{const N=await n.setReadCursor("session",S.sessionId,S.seq);m.current=N.userId??m.current}catch{a.current=v,S.sessionId===d.current&&(u.current=!0);break}}}finally{c.current=!1}}},[n]),h=i.useCallback(()=>{!r.hydrated||u.current||p<=a.current||(l.current={sessionId:e,seq:p},f())},[r.hydrated,e,p,f]);zo("read_cursor",S=>{if(!Zc(S)||S.threadKind!=="session"||S.threadId!==e)return;const v=m.current;v!==null&&S.userId!==v||S.lastReadSeq<=a.current||(a.current=S.lastReadSeq,o({sessionId:e,lastReadSeq:S.lastReadSeq,hydrated:!0}))});const g=i.useMemo(()=>t.filter(S=>S._streaming!==!0).map((S,v)=>({id:S.id,seq:v+1})),[t]),b=r.lastReadSeq,k=yc(g,b===null?null:Math.min(b,p));return{lastSeenMessageId:k.lastSeenId,unreadFromStart:k.fromStart,markSeen:h,isHydrated:r.hydrated}}function Kr(e){return`msg-${e}`}function tu(e,t){const{resolveAuthor:n,now:r,lastSeenMessageId:o,unreadFromStart:a}=t,l=e.map((c,u)=>n(c,u));return kc(e.map((c,u)=>({id:c.id,authorId:l[u].id,timestamp:c.timestamp})),{now:r,lastSeenId:o,unreadFromStart:a}).map(c=>c.kind!=="item"?c:{kind:"message",key:Kr(e[c.index].id),messageIndex:c.index,message:e[c.index],grouping:c.grouping,author:l[c.index]})}function nu(e){const t=[],n=new Set;for(const r of e){const o=r.lastIndexOf("/"),a=o>=0?r.slice(0,o+1):"",l=o>=0?r.slice(o+1):r;t.push({path:r,filename:l,directory:a,isDirectory:!1});const c=r.split("/");for(let u=1;u<c.length;u++){const d=c.slice(0,u).join("/")+"/";n.has(d)||(n.add(d),t.push({path:d,filename:c[u-1]+"/",directory:u>1?c.slice(0,u-1).join("/")+"/":"",isDirectory:!0}))}}return t}function su(e,t){const n=[...e].reverse().find(r=>r.role==="user");if(n!=null&&n.content)return n.content;if((t==null?void 0:t.kind)==="first-message"&&t.kickoffMessage)return t.kickoffMessage}const Qr=Symbol("no-error-part");function ru(e){for(let t=e.length-1;t>=0;t--){const n=e[t].parts;for(let r=n.length-1;r>=0;r--){const o=n[r];if(o.type==="error")return o.category}}return Qr}function ou(e){const{messages:t,status:n,lastErrorCategory:r,queuedCount:o,draft:a}=e;if(a.trim().length>0||n==="streaming"||o>0)return null;let l=-1;for(let d=t.length-1;d>=0;d--)if(t[d].role==="user"){l=d;break}const c=l===-1?"":t[l].content.trim();if(!c)return null;const u=ru(t.slice(l+1));return u!==Qr?u==="auth_error"?c:null:n==="error"&&r==="auth_error"?c:null}const au="dorkos:signin-resume",iu=1e4;function lu(){const e=i.useRef(new Map),t=i.useRef(null);return i.useEffect(()=>{const n=Bo(au);t.current=n;const r=e.current,o=n.onMessage(a=>{r.set(a.sessionId,Date.now())});return()=>{o(),n.close(),t.current=null}},[]),i.useMemo(()=>({claimedElsewhere:n=>{const r=e.current.get(n);return r!==void 0&&Date.now()-r<iu},claim:n=>{var r;return(r=t.current)==null?void 0:r.postMessage({sessionId:n})}}),[])}function Vr(e){switch(e){case"pending":case"running":return s.jsx(Oe,{size:"xs",className:jt({status:e})});case"complete":return s.jsx(et,{className:V("size-(--size-icon-xs)",jt({status:e}))});case"error":return s.jsx(Me,{className:V("size-(--size-icon-xs)",jt({status:e}))});case"neutral":return s.jsx(Ho,{className:V("size-(--size-icon-xs)",jt({status:e}))})}}function xs({type:e,toolName:t,toolInput:n,...r}){const o=e==="approval"?"Waiting for approval":"Answering questions",a=t?nt(t,n??""):null,l=a?`${o} · ${a}`:`${o}…`;return s.jsx("div",{className:"bg-muted/50 rounded-msg-tool text-muted-foreground shadow-msg-tool border px-3 py-1 text-sm transition-colors duration-150",...r,children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Oe,{className:"shrink-0"}),s.jsx("span",{className:"truncate text-xs",children:l})]})})}function yt({expanded:e,onToggle:t,header:n,children:r,variant:o="default",dimmed:a=!1,disabled:l=!1,hideChevron:c=!1,extraContent:u,ariaLabel:d,className:m,...p}){const f=c?void 0:e;return s.jsxs("div",{className:V("bg-muted/40 mt-px rounded-md border-l-2 text-sm transition-[opacity,background-color,border-color,box-shadow] duration-200 first:mt-1","hover:bg-muted/60 hover:border-l-muted-foreground/60 hover:shadow-soft",o==="default"&&"border-l-muted-foreground/30",o==="thinking"&&"border-l-muted-foreground/20",o==="memory"&&"border-l-muted-foreground/20",a&&!e&&"opacity-50 hover:opacity-100",m),...p,children:[s.jsxs("button",{onClick:()=>!l&&t(),disabled:l,className:V("focus-ring flex w-full items-center gap-2 rounded-md px-3 py-1",l&&"cursor-default"),"aria-expanded":f,"aria-label":d,children:[n,!c&&!l&&s.jsx(X.div,{animate:{rotate:e?180:0},transition:{type:"spring",stiffness:400,damping:30},className:"ml-auto",children:s.jsx(Ft,{className:"text-muted-foreground size-(--size-icon-xs)"})})]}),u,s.jsx(ue,{initial:!1,children:e&&s.jsx(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"overflow-hidden",children:s.jsx("div",{className:"border-border/50 border-t px-3 pt-1 pb-3",children:r})})})]})}function cu({birthRecord:e,firstLightRecord:t}){return(e==null?void 0:e.greetingFailed)===!0?s.jsxs("div",{className:"text-center","data-testid":"greeting-failed-empty",children:[s.jsxs("p",{className:"text-muted-foreground text-base",children:[e.displayName," couldn’t say hello just now"]}),s.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Send a message to get started."})]}):t?s.jsx(kl,{record:t}):s.jsxs("div",{className:"text-center",children:[s.jsx("p",{className:"text-muted-foreground text-base",children:"Start a conversation"}),s.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Type a message below to begin."})]})}function uu(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function du({sessionId:e}){const t=Lt(e),n=De();if(!t||t.kind==="first-message")return null;const r=uu(t.bornAt),o=ht(t.runtime).label;return s.jsxs(X.div,{initial:n?!1:{opacity:0,y:-4},animate:{opacity:1,y:0},transition:{duration:.3},"data-testid":"birth-certificate",className:"text-muted-foreground flex items-center justify-center gap-1.5 px-4 pt-3 pb-1 text-xs",children:[s.jsx(Wo,{className:"text-primary size-3.5 shrink-0 fill-current","aria-hidden":"true"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:"text-foreground font-medium",children:t.displayName}),r&&s.jsxs(s.Fragment,{children:[s.jsx(en,{}),s.jsxs("span",{children:["born ",r]})]}),s.jsx(en,{}),s.jsxs("span",{className:"min-w-0 truncate",children:["lives in ",s.jsx("code",{className:"text-2xs",children:t.path})]}),s.jsx(en,{}),s.jsxs("span",{className:"shrink-0",children:["runs on ",o]})]})]})}function en(){return s.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground/50 shrink-0",children:"·"})}const mu="another chat";function fu(e,t){const n=t==null?void 0:t.find(r=>r.id===e);return n?Qo(n)?Jn("autonomy"):n.label:Zs(e)?Jn("autonomy"):Vo(e)}function pu({startedBy:e,modes:t}){var a;const n=Go();if(!e)return null;const r=((a=e.reason)==null?void 0:a.trim())||null,o=e.kind==="chat"?e.permission:null;return s.jsxs(s.Fragment,{children:[s.jsx(hu,{startedBy:e,reason:r,navigate:n}),o&&s.jsxs("p",{"data-testid":"started-level-line",className:"text-muted-foreground mx-auto max-w-prose px-4 pb-1 text-center text-xs",children:["Started at ",fu(o.mode,t),","," ",o.sameAsStarter?"same as":"lower than"," the chat that started it."]})]})}function hu({startedBy:e,reason:t,navigate:n}){return s.jsxs("p",{"data-testid":"started-by-line",className:"text-muted-foreground mx-auto max-w-prose px-4 pt-3 pb-1 text-center text-xs",children:[e.kind==="extension"?s.jsxs(s.Fragment,{children:["Started by the"," ",s.jsx("span",{className:"text-foreground font-medium",children:e.extensionName})," extension"]}):s.jsxs(s.Fragment,{children:["Started from"," ",s.jsx("button",{type:"button",onClick:()=>void n(Ko({session:e.sessionId})),className:"text-foreground focus-visible:ring-ring rounded-sm font-medium underline-offset-2 hover:underline focus-visible:ring-2 focus-visible:outline-none",children:e.title??mu})]}),t&&s.jsxs(s.Fragment,{children:[": ",t]})]})}function gu({content:e}){const[t,n]=i.useState(!1);return s.jsxs("div",{"data-testid":"started-prompt",className:"px-4 py-1",children:[s.jsxs("button",{type:"button","aria-expanded":t,onClick:()=>n(r=>!r),className:"text-muted-foreground hover:text-foreground focus-visible:ring-ring mx-auto flex items-center gap-1 rounded-sm text-xs focus-visible:ring-2 focus-visible:outline-none",children:["What it was asked",s.jsx(wn,{"aria-hidden":"true",className:V("size-3 transition-transform duration-200",t&&"rotate-90")})]}),t&&s.jsx("div",{className:"bg-muted/40 text-foreground mx-auto mt-2 max-w-prose rounded-md px-3 py-2 text-sm break-words whitespace-pre-wrap",children:e})]})}function xu({celebration:e,onComplete:t}){const n=i.useRef(null),r=(e==null?void 0:e.level)==="major",o=i.useCallback(()=>{t()},[t]);return i.useEffect(()=>{if(!r)return;let a=!1;Yo({kind:"burst"}).then(c=>{if(a){c();return}n.current=c});const l=setTimeout(()=>{o()},Ut.CELEBRATION_DISPLAY_MS);return()=>{var c;a=!0,(c=n.current)==null||c.call(n),n.current=null,clearTimeout(l)}},[r,o]),s.jsx(ue,{children:r&&s.jsx(X.div,{"aria-hidden":"true",className:"pointer-events-none fixed inset-0 z-50",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:1.1},transition:{duration:.6,ease:"easeOut"},style:Qc})})}function bu(e){return e.replace(/[-_]+/g," ").trim()}function yu({action:e}){const t=Xo(),n=bu(e.actionId),r=`Widget interaction${e.title?`, ${e.title}`:""}: ${n}`;return s.jsxs(X.span,{"data-testid":"ui-action-chip",title:e.payload?JSON.stringify(e.payload):void 0,className:V("ml-auto inline-flex w-fit items-center gap-2 rounded-full border py-1 pr-3 pl-1.5","bg-muted/40 shadow-soft text-xs"),initial:t?{opacity:0,y:4,scale:.9}:!1,animate:t?{opacity:1,y:0,scale:1}:!1,transition:t?Jo:void 0,children:[s.jsx("span",{className:"sr-only",children:r}),s.jsx("span",{"aria-hidden":!0,className:"bg-primary/10 text-primary flex size-5 shrink-0 items-center justify-center rounded-full",children:s.jsx(Lc,{className:"size-3"})}),s.jsxs("span",{"aria-hidden":!0,className:"text-muted-foreground truncate",children:[e.title&&s.jsx("span",{className:"text-foreground font-medium",children:e.title}),e.title&&s.jsx("span",{className:"px-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-foreground font-medium",children:n})]})]})}const ku=/<ui_action>([\s\S]*?)<\/ui_action>/;function bs(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:null}catch{return null}}function Su(e){const t=e.match(ku);if(!t)return null;const n=t[1].split(`
27
+ `);let r=null,o=null,a=null,l=null;for(let c=0;c<n.length;c++){const u=n[c],d=u.match(/^\s*Widget:\s*(.*)$/);if(d){const h=d[1].trim();r=h&&h!=="(untitled)"?h:null;continue}const m=u.match(/^\s*Action:\s*(.*)$/);if(m){o=m[1].trim();continue}const p=u.match(/^\s*Widget ID:\s*(.*)$/);if(p){a=p[1].trim()||null;continue}const f=u.match(/^\s*Payload:\s*(.*)$/);if(f){const h=f[1].trim();if(h&&h!=="(none)")l=bs(h);else if(!h){let g="";for(let b=c+1;b<n.length;b++){g+=(g?`
28
+ `:"")+n[b];const k=bs(g.trim());if(k){l=k;break}}}break}}return o?{title:r,actionId:o,widgetId:a,payload:l}:null}function vu(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return`${n}m ${r}s`}function ju({text:e,isStreaming:t,elapsedMs:n}){const[r,o]=i.useState(t),a=i.useRef(t),l=i.useRef(null);i.useEffect(()=>{a.current&&!t&&o(!1),a.current=t},[t]),i.useEffect(()=>{t&&r&&l.current&&(l.current.scrollTop=l.current.scrollHeight)},[e,t,r]);const c=n?`Thought for ${vu(n)}`:"Thinking…";return s.jsx(yt,{expanded:r,onToggle:()=>o(!r),variant:"thinking",dimmed:!t,disabled:t,ariaLabel:c,"data-testid":"thinking-block","data-streaming":t?"true":void 0,header:s.jsxs(s.Fragment,{children:[s.jsx(Pc,{className:V("text-muted-foreground size-(--size-icon-xs)",t&&"animate-breath")}),s.jsx("span",{className:V("text-3xs text-muted-foreground font-mono",t&&"animate-breath"),children:c})]}),children:s.jsx("div",{ref:l,className:"max-h-32 overflow-y-auto",children:s.jsx("pre",{className:"text-muted-foreground text-xs break-words whitespace-pre-wrap",children:e})})})}function Cu({mode:e,memories:t,isStreaming:n}){const[r,o]=i.useState(n),a=i.useRef(n);if(i.useEffect(()=>{a.current&&!n&&o(!1),a.current=n},[n]),t.length===0)return null;const l=t.length,c=n?l<=1?"Consulting memory…":`Consulting ${l} memories…`:l===1?"Recalled 1 memory":`Recalled ${l} memories`,u=e==="synthesize"?Zo:ea,d=e==="synthesize"?"sparkles":"bookopen";return s.jsx(yt,{expanded:r,onToggle:()=>o(!r),variant:"memory",dimmed:!n,disabled:n,ariaLabel:c,"data-testid":"memory-recall-block","data-streaming":n?"true":void 0,header:s.jsxs(s.Fragment,{children:[s.jsx(u,{"aria-hidden":"true","data-testid":"memory-recall-header-icon","data-icon":d,className:V("text-muted-foreground size-(--size-icon-xs)",n&&"animate-breath")}),s.jsx("span",{className:V("text-3xs text-muted-foreground font-mono",n&&"animate-breath"),children:c})]}),children:s.jsx(wu,{memories:t})})}function wu({memories:e}){return s.jsx("ul",{className:"flex flex-col gap-1 px-3 py-2",children:e.map(t=>s.jsx(Nu,{memory:t},t.path))})}function Nu({memory:e}){const t=e.path.startsWith("<synthesis:"),n=e.scope==="team"?ta:na,r=e.scope==="team"?"team":"personal",{copy:o}=sa({toastOnSettle:!0}),a=()=>{const l=t&&e.content?e.content:e.path;o(l)};if(t&&e.content){const l=e.path.replace(/^<synthesis:/,"synthesis:").replace(/>$/,"");return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:a,"aria-label":`Copy synthesized ${r} memory content`,"data-scope":e.scope,className:"focus-ring hover:bg-muted/50 flex min-h-[44px] w-full flex-col items-start gap-1 rounded-md px-2 py-1 text-left transition-colors duration-150",children:[s.jsx("span",{className:"text-sm",children:e.content}),s.jsxs("span",{className:"text-3xs text-muted-foreground flex items-center gap-1 font-mono",children:[s.jsx(n,{"aria-hidden":"true",className:"size-(--size-icon-xs)"}),l]})]})})}return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:a,"aria-label":`Copy ${r} memory path ${e.path}`,"data-scope":e.scope,className:"focus-ring hover:bg-muted/50 flex min-h-[44px] w-full items-center gap-2 rounded-md px-2 py-1 text-left transition-colors duration-150",children:[s.jsx("span",{className:"flex-1 truncate font-mono text-sm",children:Vc(e.path,40)}),s.jsx(n,{"aria-hidden":"true",className:"text-muted-foreground size-(--size-icon-xs)"})]})})}function Ot(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Yr(e){return e===void 0?"Summarized (asked by the agent)":`Summarized at ${e}% (asked by the agent)`}function Tu(e){if((e==null?void 0:e.requestedBy)==="agent")return Yr(e.contextPercent);const t=["Context compacted"];return(e==null?void 0:e.preTokens)!==void 0&&t.push(`${Ot(e.preTokens)} tokens`),e!=null&&e.trigger&&t.push(e.trigger),t.join(" · ")}function Au(e,t){return e===void 0?"Compacted context":t===void 0?`Compacted context · ${Ot(e)} tokens summarized`:`Compacted context · ${Ot(e)} → ${Ot(t)} tokens`}function Ru({trigger:e,preTokens:t,postTokens:n,failed:r,error:o,requestedBy:a,contextPercent:l}){return r?s.jsx(qe,{"data-testid":"compact-boundary-row","data-failed":"true",icon:s.jsx(Nn,{"aria-hidden":"true",className:"text-status-warning-dot size-3 shrink-0"}),label:s.jsx("span",{className:"text-status-warning-fg",children:a==="agent"?"Couldn’t compact (asked by the agent)":"Couldn’t compact"}),children:o?s.jsx("p",{className:"text-muted-foreground mt-1 text-xs",children:o}):null}):a==="agent"?s.jsx(qe,{"data-testid":"compact-boundary-row","data-requested-by":"agent",icon:s.jsx(Zn,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:Yr(l)})}):s.jsx(qe,{"data-testid":"compact-boundary-row",icon:s.jsx(Zn,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:Au(t,n)}),trailing:e?s.jsx("span",{"data-testid":"compact-boundary-trigger",className:"text-3xs text-muted-foreground/70 ml-auto font-mono uppercase",children:e}):void 0})}function Eu({part:e}){const[t,n]=i.useState(!1);return t?s.jsxs("div",{"data-testid":"message-image-missing",className:V("my-3 flex items-center gap-2 rounded-md border px-3 py-2","text-muted-foreground border-border/60 bg-muted/30 text-sm"),children:[s.jsx(Fc,{"aria-hidden":"true",className:"size-4 shrink-0"}),s.jsx("span",{children:e.alt?`${e.alt}, not available`:"This image is not available."})]}):s.jsx("figure",{className:"my-3","data-testid":"message-image",children:s.jsx("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"focus-visible:ring-ring block rounded-md focus-visible:ring-2 focus-visible:outline-none",children:s.jsx("img",{src:e.url,alt:e.alt??"Image produced by the agent",loading:"lazy",decoding:"async",onError:()=>n(!0),className:"border-border/60 bg-muted/20 max-h-[32rem] max-w-full rounded-md border object-contain"})})})}function _u({content:e}){return s.jsx(qe,{"data-testid":"staged-context-note",icon:s.jsx(er,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:"Added context for the next reply"}),children:s.jsx("p",{className:"text-muted-foreground/80 mt-1 text-xs whitespace-pre-wrap",children:e})})}function Mu(e){if(e<1e3)return"<1s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return`${n}m ${r}s`}function Ou(e){return e==="untracked"?"neutral":e==="stopped"?"complete":e}function Iu(e){const t=[];return e.toolUses&&t.push(`${e.toolUses} tool ${e.toolUses===1?"call":"calls"}`),e.durationMs&&t.push(Mu(e.durationMs)),t.length>0?t.join(" · "):null}function Pu({part:e}){const[t,n]=i.useState(!1),r=i.useRef(null),o=Iu(e),a=e.subagentText,l=e.status==="untracked",c=!!(o||e.summary||e.lastToolName||a||l);return i.useEffect(()=>{const u=r.current;u&&(u.scrollTop=u.scrollHeight)},[a]),s.jsx(yt,{expanded:t,onToggle:()=>c&&n(!t),hideChevron:!c,ariaLabel:`Background task: ${e.description}`,"data-testid":"subagent-block","data-task-id":e.taskId,"data-status":e.status,header:s.jsxs(s.Fragment,{children:[Vr(Ou(e.status)),s.jsx("span",{className:"text-3xs truncate font-mono",children:e.description}),o&&s.jsx("span",{className:"text-3xs text-muted-foreground ml-1 shrink-0",children:o})]}),children:s.jsxs("div",{className:"space-y-1.5",children:[a&&s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{className:"text-3xs text-muted-foreground/70 tracking-wide uppercase",children:"Helper output"}),s.jsx("pre",{ref:r,className:"text-foreground/90 bg-muted/50 max-h-64 overflow-y-auto rounded-md p-2 text-xs break-words whitespace-pre-wrap","data-testid":"subagent-text",children:a})]}),e.lastToolName&&e.status==="running"&&s.jsxs("p",{className:"text-3xs text-muted-foreground",children:["Last tool: ",s.jsx("span",{className:"font-mono",children:e.lastToolName})]}),e.summary&&s.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:e.summary}),l&&s.jsx("p",{className:"text-3xs text-muted-foreground","data-testid":"subagent-untracked",children:"No longer tracked. It may still be running."})]})})}function Du(e){try{const t=JSON.parse(e);if(!t||typeof t!="object")return e;const n=t;if(n.error&&typeof n.error=="object"){const r=n.error;if(typeof r.message=="string")return r.message}return typeof n.message=="string"?n.message:e}catch{return e}}function $u(e){const t=Du(e),n=t.match(/The ['"`]([^'"`]+)['"`] model requires a newer version of Codex\b/i);if(n)return{message:`The Codex version DorkOS is using is too old for ${n[1]}. Update DorkOS (or your custom Codex installation), then try again. You can also choose another model.`,category:"runtime_update_required",details:e};const r=t.match(/The ['"`]([^'"`]+)['"`] model is not supported when using Codex with a ChatGPT account\b/i);return r?{message:`${r[1]} isn’t available with a ChatGPT account. Choose another model from the model menu.`,category:"model_unavailable",details:e}:null}function Be(e){return e.notAllowed!==!0&&e.usage.state!=="limited"}function Fu(e,t){if(e.id===tt||!e.eligible)return e.reason;const n=ra(e.usage,"seven_day");if(!n||n.usedPct===null)return"usage unknown";const r=Math.min(100,Math.max(0,Math.round(100-n.usedPct))),o=oa(n.resetsAt,t);return o?`${r}% left · resets ${o}`:`${r}% left`}function Bt(e,t){return e.runtime!==void 0&&e.runtime!==t}function Lu(e,t){const n=[],r=[];for(const o of e)(Bt(o,t)?r:n).push(o);return{same:n,other:r}}function Dt(e,t){return`${e.runtime??t}:${e.id}`}function Uu(e,t,n){if(Bt(e,t)){const r=e.runtime;return!e.label&&e.id===ct?`${Pt({runtime:r,accountLabel:null,identityGate:!1})} (this computer's sign-in)`:Pt({runtime:r,accountLabel:e.label,identityGate:!0})}return e.label?e.label:e.id===ct&&e.usage.label?e.usage.label:e.usage.path?n(e.usage.path):e.id}function qu(e,t){const n=e.accounts.find(o=>o.id===e.recommendedId);if(n&&Be(n))return Dt(n,t);const r=e.accounts.find(Be);return r?Dt(r,t):null}function zu(e){return e.length===0?null:e.length===1?`${e[0]} is kept out, so it isn’t listed.`:`${`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`} are kept out, so they aren’t listed.`}function Bu(e,t){if(e&&t)return{subtitle:"Picks up in the same folder and branch, from the last checkpoint.",carries:"Carries over: files, branch, checkpoint, task",doesnt:"Doesn’t: the chat itself"};const n="Starts a new chat in the same folder, with a summary of this one.";return{subtitle:e?n:`${n} Sorted by most usage left.`,carries:"Carries over: the folder and a summary of this chat",doesnt:"Doesn’t: the chat itself"}}function Hu(e){return e.carryOver===!1}function Wu(e,t,n){return e?!0:(t==null?void 0:t.accounts.some(r=>Bt(r,n)))??!1}function Gu(e){return{id:tt,runtime:e,label:ts,color:es,eligible:!0,reason:"paid from your DorkOS account",usage:{runtime:"claude-code",accountId:tt,path:"",label:ts,color:es,subscriptionType:null,plan:null,credits:null,spend:null,windows:[],state:"unknown",limit:null,updatedAt:null}}}function Xr(e,t){const n=be();return st({queryKey:Tn.continueOptions(e),queryFn:()=>n.getContinueOptions(e),enabled:t,staleTime:0,retry:!1})}function Ku(e){const t=be();return ut({mutationFn:n=>t.continueSession(e,n),retry:!1})}function Qu(e){const t=be();return ut({mutationFn:()=>t.cancelAutoContinue(e),retry:!1})}const ys="claude-code",Vu="No other account can take this work right now.";function Yu(e){return e instanceof Error&&e.message?e.message:"Couldn’t continue on that account. Try again."}function Xu({row:e,value:t,name:n,status:r,selected:o}){const a=Be(e);return s.jsxs("label",{"data-slot":"continue-account-row","data-eligible":e.eligible,className:V("flex min-h-11 min-w-0 items-center gap-1.5 rounded-lg border px-2.5 py-2 text-sm transition-colors duration-150","has-[:focus-visible]:ring-ring has-[:focus-visible]:ring-[3px]",o?"border-foreground ring-foreground ring-1 ring-inset":"border-border",a?"hover:bg-muted/50 cursor-pointer":"cursor-not-allowed",!e.eligible&&"opacity-60"),children:[s.jsx(pa,{value:t,disabled:!a,className:"sr-only"}),s.jsx("span",{"aria-hidden":!0,className:"inline-flex",children:s.jsx(Rn,{color:e.color,name:n})}),s.jsx("span",{className:"max-w-[55%] shrink-0 truncate font-medium",children:n}),e.badge==="recommended"&&s.jsx("span",{className:V(ha.success,"border-status-success-border text-2xs shrink-0 rounded-full border px-1.5"),children:"recommended"}),s.jsx("span",{className:"text-muted-foreground ml-auto min-w-0 pl-1 text-right text-xs",children:r})]})}function Jr({open:e,onOpenChange:t,sessionId:n,account:r,cancelAutoFirst:o=!1,now:a,onCloseAutoFocus:l}){var te;const c=gt(),u=a??new Date(c),d=i.useId(),m=r.runtime??ys,{accounts:p,nameFor:f}=An(),[,h]=xt(),g=Qu(n),b=i.useRef(!1),{mutate:k,reset:S}=g;i.useEffect(()=>{if(!e){b.current=!1,S();return}!o||b.current||(b.current=!0,k())},[e,o,k,S]);const v=e&&(!o||g.isSuccess),N=Xr(n,v),j=Ku(n),[w,C]=i.useState(null),E=()=>{j.isPending||(C(null),j.reset(),t(!1))},M=P=>P?t(!0):E(),T=v?N.data:void 0,y=T==null?void 0:T.ranking,_=T&&!Hu(T.plan)?[...T.ranking.accounts,...T.credits?[Gu(m)]:[]]:[],x=_.some(Be),A=w??(y?qu(y,m):null),O=_.find(P=>Dt(P,m)===A)??null,z=O!==null&&Be(O),I=P=>Uu(P,m,f),{same:$,other:q}=Lu(_,m),B=Bu((T==null?void 0:T.advised)===!0,r.trackerItems.some(P=>P.via==="this-chat")),K=r.accountId??((te=r.limit)==null?void 0:te.accountId)??null,se=(T==null?void 0:T.advised)===!0&&m===ys&&K!==null?zu(p.filter(P=>P.id&&P.id!==K&&!$.some(H=>H.id===P.id)).map(P=>f(P.path))):null,W=()=>{!O||!Be(O)||j.mutate(Bt(O,m)?{account:O.id,runtime:O.runtime}:{account:O.id},{onSuccess:P=>{E(),P.sessionId&&h(P.sessionId)}})},F=P=>{const H=Dt(P,m);return s.jsx(Xu,{row:P,value:H,name:I(P),status:Fu(P,u),selected:H===A},H)},D=g.isError?g.error:N.isError&&v?N.error:j.isError?j.error:null,R=e&&!D&&(!v||N.isPending),Q=!R&&T!==void 0;return s.jsx(aa,{open:e,onOpenChange:M,children:s.jsxs(ia,{className:"max-h-[85vh] !min-h-0",desktopProps:{className:"sm:max-w-[380px]"},onCloseAutoFocus:l,"aria-labelledby":d,children:[s.jsxs(la,{className:"shrink-0 text-left",children:[s.jsx(ca,{id:d,className:"text-left",children:"Continue on another account"}),s.jsx(ua,{className:"text-left",children:B.subtitle})]}),s.jsxs(da,{className:"flex flex-col gap-3",children:[R&&s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(ns,{className:"h-11 rounded-lg"}),s.jsx(ns,{className:"h-11 rounded-lg"})]}),Q&&(x?s.jsxs(ma,{"aria-labelledby":d,value:A??"",onValueChange:C,className:"min-w-0 grid-cols-1 gap-1.5",children:[$.map(F),q.length>0&&s.jsx("div",{className:"text-muted-foreground mt-2 text-xs font-semibold tracking-wide uppercase",children:"Other runtimes"}),q.map(F)]}):s.jsx("p",{className:"text-muted-foreground text-sm",children:Vu})),Q&&se&&s.jsx("p",{className:"text-muted-foreground text-xs",children:se}),Q&&s.jsxs("ul",{className:"text-muted-foreground list-disc pl-4 text-xs",children:[s.jsx("li",{children:B.carries}),s.jsx("li",{children:B.doesnt})]}),D!==null&&s.jsx("p",{role:"alert",className:"text-destructive text-sm",children:Yu(D)})]}),s.jsxs(fa,{className:"shrink-0",children:[s.jsx(ie,{variant:"outline",onClick:E,disabled:j.isPending,children:"Cancel"}),s.jsxs(ie,{onClick:W,disabled:!Q||!x||!z||j.isPending,"aria-busy":j.isPending||void 0,children:[j.isPending&&s.jsx(Oe,{}),O&&Q&&x?`Continue on ${I(O)}`:"Continue"]})]})]})})}const Ju=1440*60*1e3,Zu="Paused until you continue or the account resets",ed="Paused until the task moves or the account resets",td=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited"]);function nd(e){return td.has(e)?"critical":"neutral"}function Zr(e){return e.carryOver===!1}function Ze(e,t){return e!==null&&Date.parse(e)<=t.getTime()}function $n(e){return`${e} should have reset by now.`}function sd(e,t,n,r){if(Ze(n,r))return $n(e);const o=ga(t,n,r);return o==="out"?`${e} is out of usage.`:o.startsWith("back in ")?`${e} is out of usage · ${o}.`:`${e} is out of usage ${o.slice(4)}.`}function eo(e){return e.plan.mode==="waiting"&&e.plan.resumeAt?e.plan.resumeAt:e.resetsAt}function ks(e,t,n){if(t===null)return`Waiting for ${e}`;if(Ze(t,n))return $n(e);const r=Date.parse(t)-n.getTime();return r<Ju?`Waiting for ${e} · back in ${xa(r)}`:`Waiting for ${e} · back ${En(t,n)}`}function rd(e,t){return Math.max(0,Math.ceil((Date.parse(e)-t.getTime())/1e3))}const od=new Set(["continue-on","move-now","keep-going","resume","open-moved"]);function ad(e,t){return(()=>{switch(e){case"limited":return[t.canPick&&"continue-on","wait"];case"handing-off":return["move-now",t.canPick&&"choose","wait"];case"model-limited":return[t.hasFallback&&"keep-going",t.canPick&&"continue-on","wait"];case"wait-only":case"all-accounts-out":return["wait"];case"reset-ready":return["resume"];case"moved":return["open-moved",!t.continuedHere&&"continue-here"];default:return[]}})().filter(r=>r!==!1)}const id=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited","waiting-reset"]),tn={canSubmit:!0,placeholder:null};function ld(e,t,n){if(!e)return tn;const r=tr(e);if(r==="moved")return{canSubmit:t,placeholder:null};if(!id.has(r))return tn;const o=l=>l!==null&&!Ze(l,n);return o(eo(e))||e.plan.mode==="auto"&&o(e.plan.fireAt)?{canSubmit:!1,placeholder:r==="handing-off"?ed:Zu}:tn}const cd=300*1e3;function to(e,t){const n=Date.parse(e)-Date.parse(t);return Number.isFinite(n)&&n>=0&&n<=cd}function ud(e,t){let n=null;for(const r of e)to(r.since,t)&&(n===null||Date.parse(r.since)<Date.parse(n.since))&&(n=r);return n}function bn(e,t){var n;return e?((n=t.find(r=>r.value===e))==null?void 0:n.displayName)??e:null}function dd(e,t){return{from:bn(e.modelFrom,t)??(e.scope==="model"?nr(e.window,t):null),to:bn(e.modelTo,t)}}function no(e){return e.endsWith("connectors.request_connection")||e.endsWith("connectors_request_connection")}function so(e){if(e)try{return JSON.parse(e)}catch{return}}function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function md(e){const t=so(e);if(!It(t))return;const{serviceSlug:n,reason:r}=t;if(!(typeof n!="string"||typeof r!="string"))return{serviceSlug:n,reason:r}}function ro(e){const t=so(e);if(It(t)&&typeof t.requestId=="string")return t.requestId;if(It(t)&&Array.isArray(t.content)){const n=t.content.map(r=>It(r)&&typeof r.text=="string"?r.text:"").join("");return ro(n)}}function fd(e,t){const n=ro(t.result);if(n)return e.find(o=>o.requestId===n);const r=md(t.input);if(r)return e.filter(o=>o.serviceSlug===r.serviceSlug).sort((o,a)=>a.createdAt.localeCompare(o.createdAt))[0]}function pd({sessionId:e,input:t,result:n,fallback:r}){const o=Ac(e),a=o.data?fd(o.data,{input:t,result:n}):void 0;return a?s.jsx("div",{className:"my-3","data-testid":"chat-agent-request",children:s.jsx(Rc,{request:a})}):s.jsx(s.Fragment,{children:r})}function oo(){const{accounts:e,nameFor:t,colorFor:n}=An(),r=ba("claude-code",{accountId:ct,path:null});return o=>{const a=ya({accountId:o,path:null,accounts:e,usage:o===ct?r:null,nameFor:t,colorFor:n});return{name:a.name??o,color:a.color}}}const Ss="claude-code",hd=new Set(["limited","handing-off","model-limited"]),gd=new Set(["limited","model-limited","all-accounts-out"]);function xd(e){return(e==null?void 0:e.runsOn)==="own-sign-in"&&e.chosenBy==="user"}function bd(e){return e instanceof Error&&e.message?e.message:"Couldn’t do that. Try again."}function yd(e,t){var K,se,W;const n=be(),r=_n(),[,o]=xt(),a=bt(e,{fetchUsage:!1}),l=t??a,c=l.limit,u=c?tr(c):null,d=l.runtime??Ss,m=l.visible,p=oo(),f=d===Ss&&(c!=null&&c.accountId)?p(c.accountId).name:l.name,h=Pt({runtime:d,accountLabel:f,identityGate:m}),g=Mn({sessionId:e||void 0,runtime:d}).data??[],b=c?Zr(c.plan):!0,k=u!==null&&hd.has(u)&&!b,{isLoaded:S}=An(),{data:v}=On(),N=S&&v!==void 0,j=u==="model-limited",w=Xr(e,k&&N&&(j?m:!m)),C=k&&(j?m&&(((K=w.data)==null?void 0:K.ranking.accounts.some(Be))??!1):Wu(m,(se=w.data)==null?void 0:se.ranking,d)),{continuedHere:E,continueHere:M}=sr(e,(c==null?void 0:c.since)??null),{data:T}=ka(),y=u!==null&&gd.has(u)&&!b&&(c==null?void 0:c.accountId)!==tt&&Sa(T,d)&&!xd((W=T==null?void 0:T.defaults)==null?void 0:W[d]),_=(c==null?void 0:c.since)??null,x=`${_}:${u}`,[A,O]=i.useState(null),z=F=>O(F===null?null:{key:x,message:F}),I=F=>z(bd(F)),$=ut({mutationFn:F=>n.waitForReset(e,F),retry:!1,onError:I}),q=ut({mutationFn:F=>n.continueSession(e,F),retry:!1,onError:I,onSuccess:F=>{F.sessionId&&F.sessionId!==e&&o(F.sessionId)}}),B=i.useRef(_);return i.useEffect(()=>{B.current!==null&&_===null&&r.invalidateQueries({queryKey:Tn.limitHistory(e)}),B.current=_},[_,e,r]),{account:l,limit:c,state:u,runtime:d,subject:h,identityGate:m,canPick:C,creditsOffered:y,nameOf:p,models:g,continuedHere:E,continueHere:M,wait:F=>{z(null),$.mutate(F===void 0?{}:{autoResume:F})},continueOn:F=>{z(null),q.mutate(F)},openSession:F=>o(F),pending:$.isPending||q.isPending,failure:(A==null?void 0:A.key)===x?A.message:null}}function nn({visible:e,spoken:t,spokenKey:n}){const[r,o]=i.useState({key:n,text:t});return r.key!==n&&o({key:n,text:t}),s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":!0,children:e}),s.jsx("span",{className:"sr-only",children:r.key===n?r.text:t})]})}function sn({account:e,showDot:t}){return s.jsxs(s.Fragment,{children:[t&&e.color&&s.jsx("span",{"aria-hidden":!0,className:"mr-1 inline-flex align-middle",children:s.jsx(Rn,{color:e.color,name:e.name,tooltip:!1})}),e.name]})}function kd(e,t){switch(e){case"continue-on":return"Continue on another account…";case"move-now":return"Move now";case"choose":return"Choose account…";case"keep-going":return`Keep going on ${t}, same account`;case"resume":return"Continue";case"open-moved":return"Open it →";case"continue-here":return"Continue here anyway";case"wait":return"Wait for reset"}}function Sd({sessionId:e,onSend:t,account:n,now:r}){const o=yd(e,n),a=rr(),{limit:l,state:c,subject:u,identityGate:d}=o,m=gt(c==="handing-off"?1e3:6e4),p=r??new Date(m),f=l?l.since:null,[h,g]=i.useState(null),b=o.canPick&&f!==null&&h===f,k=x=>g(x?f:null),S=i.useId();if(!l||!c)return null;const v=o.creditsOffered&&a!==null,N=l.plan,j=bn(l.modelFallback,o.models),w=ad(c,{canPick:o.canPick,hasFallback:j!==null,continuedHere:o.continuedHere}),C=`${c}:${l.since}:${u}`;let E,M=null,T=!1;switch(c){case"all-accounts-out":{E="All accounts are out.";const x=l.allOut;if(x!=null&&x.resetsAt){const A=o.nameOf(x.accountId);M=Ze(x.resetsAt,p)?$n(A.name):s.jsxs(s.Fragment,{children:["Soonest back: ",s.jsx(sn,{account:A,showDot:d}),","," ",En(x.resetsAt,p)]})}break}case"model-limited":E=`${nr(l.window,o.models)} is out on ${u} for this week.`;break;case"waiting-reset":{const x=eo(l);E=s.jsx(nn,{visible:ks(u,x,p),spoken:ks(u,x,p),spokenKey:`${C}:${Ze(x,p)}`});break}case"reset-ready":E=N.mode==="waiting"&&N.unconfirmed?`${u} should have reset by now.`:`${u} has reset.`;break;case"moved":{if(N.mode!=="continued")return null;const x=o.nameOf(N.accountId);E=s.jsxs(s.Fragment,{children:["This task continued on ",s.jsx(sn,{account:x,showDot:d}),"."]});break}default:{const x=sd(u,l.window,l.resetsAt,p);if(E=s.jsx(nn,{visible:x,spoken:x,spokenKey:`${C}:${Ze(l.resetsAt,p)}`}),c==="handing-off"&&N.mode==="auto"){const A=o.nameOf(N.target),O=rd(N.fireAt,p);T=O===0,M=s.jsx(nn,{visible:s.jsxs(s.Fragment,{children:["Moving this task to ",s.jsx(sn,{account:A,showDot:d}),T?"…":` in ${O}s…`]}),spoken:T?`Moving this task to ${A.name}.`:`Moving this task to ${A.name} in ${O} seconds.`,spokenKey:`${C}:${N.fireAt}:${A.name}:${T}`})}}}const y=x=>{switch(x){case"continue-on":case"choose":k(!0);return;case"move-now":N.mode==="auto"&&o.continueOn({account:N.target});return;case"keep-going":l.modelFallback&&o.continueOn({model:l.modelFallback});return;case"resume":t(va);return;case"open-moved":N.mode==="continued"&&o.openSession(N.sessionId);return;case"continue-here":o.continueHere();return;case"wait":o.wait();return}},_=c==="waiting-reset"&&N.mode==="waiting"&&!Zr(N);return s.jsxs(s.Fragment,{children:[s.jsxs(uc,{variant:nd(c),role:"status",icon:null,"data-slot":"account-limit-banner","data-state":c,className:"mx-4 mb-2 rounded-lg border px-3 py-2",children:[s.jsxs("p",{children:[s.jsx("strong",{className:"font-semibold",children:E}),M&&s.jsxs(s.Fragment,{children:[" ",M]})]}),_&&s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsx("input",{id:S,type:"checkbox",className:"size-3.5",checked:N.autoResume,disabled:o.pending,onChange:x=>o.wait(x.target.checked)}),s.jsx("label",{htmlFor:S,children:"Continue automatically when it resets"})]}),v&&a&&s.jsx("div",{className:"mt-1.5",children:a({runtime:o.runtime,origin:`limit:${e}`,intent:"keep-going",confirmAfterLink:{prompt:"Linked. Continue on DorkOS credits?",action:"Continue"},onChoose:()=>o.continueOn({account:tt})})}),w.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:w.map(x=>s.jsx(ie,{size:"sm",variant:od.has(x)&&!v?"default":x==="continue-here"?"ghost":"outline",className:"h-auto min-h-11 max-w-full py-1 whitespace-normal md:min-h-8",disabled:o.pending||x==="move-now"&&T,onClick:()=>y(x),children:kd(x,j)},x))}),o.failure&&s.jsx("p",{role:"alert",className:"text-destructive mt-1.5",children:o.failure})]}),o.canPick&&s.jsx(Jr,{open:b,onOpenChange:k,sessionId:e,account:{runtime:o.runtime,accountId:o.account.accountId,limit:l,trackerItems:o.account.trackerItems},cancelAutoFirst:c==="handing-off",now:r})]})}function vd(e){const t=be();return st({queryKey:Tn.limitHistory(e),queryFn:()=>t.getLimitHistory(e),enabled:e!=="",retry:!1})}const jd={moved:Ca,"resumed-reset":ot,"resumed-model":ot,"resumed-early":ot};function Cd({entry:e,now:t}){const n=gt(),r=t??new Date(n),o=oo(),a=ja(e.runtime),l=Mn({runtime:e.runtime}).data??[],[,c]=xt(),u=e.runtime==="claude-code"&&e.accountId?o(e.accountId).name:null,d=Pt({runtime:e.runtime,accountLabel:u,identityGate:a}),m=`at ${En(e.resolvedAt,r)}`,p=jd[e.resolution];let f;switch(e.resolution){case"moved":{const h=e.toAccountId?o(e.toAccountId):null,g=h?s.jsxs(s.Fragment,{children:[a&&h.color&&s.jsx("span",{"aria-hidden":!0,className:"mr-0.5 inline-flex align-middle",children:s.jsx(Rn,{color:h.color,name:h.name,tooltip:!1})}),h.name]}):null;f=s.jsxs(s.Fragment,{children:[d," ran out · moved",g&&s.jsxs(s.Fragment,{children:[" to ",e.toSessionId?s.jsx("button",{type:"button",className:"hover:text-foreground focus-visible:ring-ring rounded-sm underline underline-offset-2 outline-none focus-visible:ring-2",onClick:()=>c(e.toSessionId),children:g}):g]})," ",m]});break}case"resumed-reset":f=`Resumed after reset ${m}`;break;case"resumed-model":{const{from:h,to:g}=dd(e,l);f=g?`${h??d} ran out · continued on ${g} ${m}`:`${d} ran out · continued here ${m}`;break}case"resumed-early":f=`${d} ran out · continued here ${m}`;break}return s.jsxs("p",{"data-slot":"account-limit-marker","data-resolution":e.resolution,className:"text-muted-foreground text-2xs my-2 flex items-center gap-1.5",children:[s.jsx(p,{"aria-hidden":!0,className:"size-3 shrink-0"}),s.jsx("span",{className:"min-w-0",children:f})]})}function wd({sessionId:e,at:t,fallback:n,now:r}){const{limit:o}=bt(e,{fetchUsage:!1}),a=vd(e),[l,c]=i.useState(null),u=o!==null&&(t===""||to(o.since,t));if(u&&((l==null?void 0:l.data)!==a.dataUpdatedAt||l.error!==a.errorUpdatedAt)&&c({data:a.dataUpdatedAt,error:a.errorUpdatedAt}),u||a.isPending)return null;const d=a.data&&t?ud(a.data.entries,t):null;return d?s.jsx(Cd,{entry:d,now:r}):o===null&&l!==null&&a.dataUpdatedAt===l.data&&a.errorUpdatedAt===l.error?null:s.jsx(s.Fragment,{children:n})}function Nd(e){const{limit:t}=bt(e,{fetchUsage:!1}),{continuedHere:n}=sr(e,(t==null?void 0:t.since)??null),r=gt();return ld(t,n,new Date(r))}function Td(e){return bt(e,{fetchUsage:!1}).limit!==null}const ao="runtimes";function Ad({label:e}){const{open:t}=or();return s.jsx("button",{type:"button",onClick:()=>t(ao),className:"text-muted-foreground hover:text-foreground mt-2 block text-xs underline decoration-dotted underline-offset-2 transition-colors",children:e})}function Rd({runtime:e,sessionId:t,onRetry:n,onSigninComplete:r}){const[o,a]=i.useState(!1),l=Aa(e,{sessionId:t,onCompleted:()=>a((r==null?void 0:r())??!1)}),c=_a(e);return l.isSuccess?s.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin-success",children:[s.jsxs("p",{className:"text-status-success-fg flex items-center gap-2 text-sm",role:"status",children:[s.jsx(et,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),o?"Signed in. Sending your message again…":"Signed in."]}),!o&&n&&s.jsxs(ie,{size:"sm",onClick:n,className:"mt-2 gap-1.5",children:[s.jsx(dt,{className:"size-3"}),"Retry"]})]}):s.jsxs("div",{className:"mt-3","data-testid":"auth-error-signin",children:[s.jsx("p",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-sm",role:"status",children:l.isPending&&s.jsxs(s.Fragment,{children:[s.jsx(Oe,{size:"xs",className:"shrink-0"}),c.signInPending]})}),l.isError&&s.jsx("p",{className:"text-destructive mb-2 text-sm",role:"alert",children:l.errorMessage}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{size:"sm",onClick:l.login,disabled:l.isPending,className:"gap-1.5","data-testid":"auth-error-signin-button",children:[s.jsx(ar,{className:"size-3"}),l.isError?"Try again":c.signInLabel]}),n&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(dt,{className:"size-3"}),"Retry"]})]}),s.jsx(Ad,{label:"Use an API key instead"})]})}function vs({onRetry:e}){return s.jsx("div",{className:"mt-3","data-testid":"auth-error-remote-guidance",children:s.jsx(Ta,{...e?{onRetry:e}:{}})})}function io({onRetry:e}){const{open:t}=or();return s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[s.jsxs(ie,{size:"sm",onClick:()=>t(ao),className:"gap-1.5",children:[s.jsx(ar,{className:"size-3"}),"Fix sign-in"]}),e&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:e,className:"gap-1.5",children:[s.jsx(dt,{className:"size-3"}),"Retry"]})]})}function Ed({runtime:e,sessionId:t,onRetry:n,renderOffer:r,lead:o,children:a}){const l=!ir(),c=lr(),u=oe(f=>f.setRetryAccount),d=ht(e).label,m=r({runtime:e,origin:`auth-error:${t}`,note:`This makes new ${d} work on this computer run on your DorkOS credits.`,chosen:n?`New ${d} work on this computer now runs on your DorkOS credits. Sending your message again…`:`New ${d} work on this computer now runs on your DorkOS credits.`,...n?{confirmAfterLink:{prompt:"Linked. Send again on DorkOS credits?",action:"Send again"}}:{},onChoose:async()=>{await c.mutateAsync({runtime:e,useCredits:!0}),n&&(u({id:tt,sessionId:t}),n())}}),p=f=>s.jsxs("section",{"aria-label":"Other ways",children:[s.jsx("p",{className:"text-muted-foreground text-2xs font-medium tracking-wide uppercase",children:"Other ways"}),f]});return o?s.jsxs("div",{className:"mt-3 space-y-3","data-testid":"auth-error-credits-first",children:[m,p(a),s.jsx(Ra,{ollama:Ea(e)==="provider-picker",remote:l})]}):s.jsxs("div",{"data-testid":"auth-error-credits-other-way",children:[a,s.jsx("div",{className:"mt-3",children:p(m)})]})}function _d({sessionId:e,onRetry:t,onSigninComplete:n}){var p;const{sessions:r,isLoading:o}=Cn(),a=ir(),l=(p=r.find(f=>f.id===e))==null?void 0:p.runtime,c=wa(l),u=rr(),d=l!==void 0&&u!==null&&(c==="lead"||c==="other-way");if(!a&&!d)return s.jsx(vs,{onRetry:t});if(o)return null;const m=a?!l||!Na(l)?s.jsx(io,{onRetry:t}):s.jsx(Rd,{runtime:l,sessionId:e,onRetry:t,onSigninComplete:n}):s.jsx(vs,{onRetry:t});return d&&l&&u?s.jsx(Ed,{runtime:l,sessionId:e,onRetry:t,renderOffer:u,lead:c==="lead",children:m}):m}function Md({sessionId:e,onRetry:t,onSigninComplete:n}){return e?s.jsx(_d,{sessionId:e,onRetry:t,onSigninComplete:n}):s.jsx(io,{onRetry:t})}const Od="credits_unavailable",Id="folder-sign-in";function Pd({onRetry:e,sessionId:t,runtimeLabel:n,reason:r}){const o=oe(g=>g.setRetryAccount),a=Ma(),l=lr(),c=cr(),u=zt(t),d=qt(u??null);if(!e)return null;const m=Dd(d),p=n?`your ${n}`:"your own",f=()=>{if(d!==void 0){if(m==="pick-for-send"){t&&o({id:ct,sessionId:t}),e();return}l.mutate({runtime:d.type,useCredits:!1},{onSuccess:()=>m==="new-conversation"?c(void 0,{runtime:d.type}):e()})}},h=()=>{t&&a.mutate(t,{onSuccess:({launch:g})=>{g!=null&&g.ok&&o({id:g.accountId,sessionId:t}),e()}})};return s.jsxs("div",{className:"mt-2 flex flex-col gap-2","data-testid":"credits-error-actions",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(ie,{size:"sm",variant:"outline",onClick:e,className:"gap-1.5",children:[s.jsx(dt,{className:"size-3"}),"Retry"]}),t&&s.jsx(ie,{size:"sm",variant:"outline",onClick:f,disabled:d===void 0||l.isPending,children:m==="new-conversation"?`Start a new conversation on ${p} sign-in`:`Use ${p} sign-in`}),t&&r===Id&&s.jsx(ie,{size:"sm",variant:"outline",onClick:h,disabled:a.isPending,children:"Don’t use credits in this project"})]}),t&&m==="whole-runtime"&&s.jsxs("p",{className:"text-muted-foreground text-xs","data-testid":"credits-own-sign-in-reach",children:["This moves all ",n??"its"," conversations to ",p," sign-in, not just this one."]}),a.error&&s.jsx("p",{className:"text-muted-foreground text-xs",role:"status",children:a.error.message}),l.isError&&s.jsx("p",{className:"text-muted-foreground text-xs",role:"status",children:"Couldn’t switch to your own sign-in. Try again in a moment."})]})}function Dd(e){var t;return e===void 0||e.supportsAccounts?"pick-for-send":((t=e.credits)==null?void 0:t.scope)==="conversation"?"new-conversation":"whole-runtime"}function $d({category:e,onChooseModel:t}){return t?s.jsxs(ie,{size:"sm",onClick:t,className:"mt-3 gap-1.5",children:[s.jsx(ur,{className:"size-3"}),e==="runtime_update_required"?"Choose another model":"Choose model"]}):null}const Fd="your agent",Ld="agent",js={max_turns:{heading:"Turn limit reached",subtext:"The agent ran for its maximum number of turns.",retryable:!1},execution_error:{heading:"Agent stopped unexpectedly",subtext:"Something went wrong before it finished.",retryable:!0},budget_exceeded:{heading:"Cost limit reached",subtext:"This session hit its spending limit.",retryable:!1},output_format_error:{heading:"Output format error",subtext:"The agent couldn’t produce the required output format.",retryable:!1},auth_error:{heading:"Sign in again",subtext:"Your login stopped working. Sign in again to continue.",retryable:!0},model_unavailable:{heading:"Model unavailable",subtext:"Choose another model from the model menu.",retryable:!1},runtime_update_required:{heading:"Codex update required",subtext:"Update DorkOS or your Codex install, then try again. Or choose another model.",retryable:!1}},Ud=new Set(["max_turns","budget_exceeded","output_format_error","auth_error"]);function qd(e){return`Sign in to ${e??Fd} again`}function zd(e){return`Your ${e??Ld} login stopped working. Sign in again to continue.`}const Bd="rate_limit";function $t(e){const{code:t,at:n,sessionId:r}=e;return t===Bd&&r?s.jsx(wd,{sessionId:r,at:n??"",fallback:s.jsx(Cs,{...e})}):s.jsx(Cs,{...e})}function Cs({message:e,category:t,details:n,onRetry:r,heading:o,subtext:a,runtimeLabel:l,sessionId:c,onSigninComplete:u,onChooseModel:d,code:m,reason:p}){const[f,h]=i.useState(!1),g=m===Od,b=i.useMemo(()=>$u(e),[e]),k=(b==null?void 0:b.category)??t,S=(b==null?void 0:b.message)??e,v=b?n!=null&&n.includes(b.details??"")?n:[n,b.details].filter(Boolean).join(`
29
+ `):n,N=k==="auth_error",j=k?js[k]??js.execution_error:null,w=N?qd(l):k==="runtime_update_required"&&l?`${l} update required`:j==null?void 0:j.heading,C=N?zd(l):j==null?void 0:j.subtext,E=g?"Couldn’t reach DorkOS credits":b?w??"Error":o??w??"Error",M=S.trim(),T=k!==void 0&&Ud.has(k),y=g?M:(b&&(a==null?void 0:a.trim())===e.trim()?void 0:a)??(T?C:M||C)??M,_=y.trim(),x=i.useMemo(()=>Oa(M),[M]),A=!M||M===_||M===E,O=!A&&(!T||x)?M:null,z=A||O!==null||v!=null&&v.includes(M)?v:[v,M].filter(Boolean).join(`
30
+ `),I=(j==null?void 0:j.retryable)??!!r;return s.jsx("div",{"data-testid":"error-message-block",className:V("my-2 rounded-lg border px-4 py-3","border-destructive/30 bg-destructive/5 text-foreground"),children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Nn,{className:"text-destructive mt-0.5 size-4 shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-sm font-medium",children:E}),s.jsx("p",{className:"text-muted-foreground mt-0.5 text-sm wrap-anywhere whitespace-pre-wrap",children:s.jsx(Qt,{text:y})}),O&&s.jsx("p",{className:"text-muted-foreground mt-1 text-sm wrap-anywhere whitespace-pre-wrap",children:s.jsx(Qt,{text:O})}),z&&s.jsxs("button",{type:"button",onClick:()=>h(!f),className:"text-muted-foreground hover:text-foreground mt-2 flex items-center gap-1 text-xs","aria-expanded":f,children:[s.jsx(X.div,{animate:{rotate:f?0:-90},transition:{type:"spring",stiffness:400,damping:30},children:s.jsx(Ft,{className:"size-3"})}),"Details"]}),s.jsx(ue,{initial:!1,children:f&&z&&s.jsx(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"overflow-hidden",children:s.jsx("pre",{className:"bg-muted/50 mt-1 max-h-40 overflow-auto rounded p-2 text-xs whitespace-pre-wrap",children:s.jsx(Qt,{text:z})})})}),g&&s.jsx(Pd,{onRetry:r,sessionId:c,runtimeLabel:l,reason:p}),N&&s.jsx(Md,{sessionId:c,onRetry:r,onSigninComplete:u}),(k==="model_unavailable"||k==="runtime_update_required")&&s.jsx($d,{category:k,onChooseModel:d})]}),!N&&!g&&I&&r&&s.jsxs(ie,{variant:"outline",size:"sm",onClick:r,className:"shrink-0 gap-1.5",children:[s.jsx(dt,{className:"size-3"}),"Retry"]})]})})}const Hd=8;function Wd({toolName:e,reasonType:t,reason:n,message:r,agentId:o}){const a=n||r,l=t==="classifier",c=t==="asyncAgent",u=o!==void 0?`Helper ${o.slice(0,Hd)}`:c?"A background helper":null,m=u!==null?`${u} was blocked from using ${e}${l?" by auto mode":""}: ${a}`:l?`Blocked by auto mode: ${a}`:`Blocked: ${a}`;return s.jsxs("div",{"data-testid":"permission-denied-chip","data-reason-type":t,"data-agent-id":o,className:V("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-amber-500/30 bg-amber-500/5"),children:[s.jsx(Cc,{"aria-hidden":"true",className:"mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-500"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-sm",children:m}),c?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-muted-foreground mt-0.5 text-xs",children:"Background helpers can’t ask for approval, so this was blocked."}),s.jsx("p",{className:"text-muted-foreground mt-0.5 text-xs",children:"Do it yourself, or ask the agent to run it in the foreground."})]}):null,s.jsx("p",{className:"text-muted-foreground mt-0.5 font-mono text-xs",children:e})]})]})}const Gd=50;function Kd(e){return e.type==="tool_call"&&e.interactiveType==="approval"&&e.approvalOutcome!==void 0}function Qd(e,t){return e.approvalOutcome!==t.approvalOutcome||(e.approvalReasonGiven??!1)!==(t.approvalReasonGiven??!1)||e.approvalResolvedAt===void 0||t.approvalResolvedAt===void 0?!1:Math.abs(e.approvalResolvedAt-t.approvalResolvedAt)<=Gd}function Vd(e){const t=new Map;let n=null;for(let r=0;r<e.length;r++){const o=e[r];if(!Kd(o)){n=null;continue}if(n&&Qd(n.part,o)){n.group.indices.push(r),t.set(r,n.group);continue}const a={leadIndex:r,indices:[r],outcome:o.approvalOutcome,reasonGiven:o.approvalReasonGiven??!1};t.set(r,a),n={group:a,part:o}}return t}function Yd(e){return e.questionOutcome!==void 0?e.questionOutcome==="answered":e.status!=="pending"}function Xd(e){return e.status==="pending"?void 0:e.questionOutcome}const Jd={session:"this session",project:"this project",user:"all your Claude sessions"};function Zd(e){return e===void 0?void 0:Jd[e]}const em={duration:.12,ease:"easeOut"},tm={duration:0},ws=new Set(["Bash","Write","Edit","NotebookEdit"]),Ns=new Set(["WebFetch","WebSearch"]);function nm(e){const t=e.includes("__")?e.split("__").pop():e;return ws.has(t)||ws.has(e)?"high":Ns.has(t)||Ns.has(e)||e.startsWith("mcp__")?"medium":"low"}function sm(e){const t=Math.floor(e/60),n=e%60;return t>0?`${t}:${String(n).padStart(2,"0")}`:`${n}s`}function lo({sessionId:e,toolCallId:t,toolName:n,input:r,isActive:o=!1,onDecided:a,ref:l,timeoutMs:c,approvalStartedAt:u,approvalRemainingMs:d,approvalParked:m,approvalTitle:p,approvalDisplayName:f,approvalDescription:h,approvalBlockedPath:g,approvalDecisionReason:b,approvalHasSuggestions:k,approvalAlwaysAllowScope:S,allowsDenyReason:v=!0}){const N=be(),j=De(),w=i.useMemo(()=>nm(n),[n]),C=dr(n),E=nt(n,r),M=f||E,T=Zd(S),[y,_]=i.useState(!1),[x,A]=i.useState(null),[O,z]=i.useState(null),[I,$]=i.useState(!1),[q,B]=i.useState(""),K=i.useRef(""),[se,W]=i.useState(!1),F=o&&!se,[D,R]=i.useState(()=>Date.now()),Q=i.useRef(!1);i.useLayoutEffect(()=>{if(!Q.current){Q.current=!0;return}R(Date.now())},[c,u,d]);const[te,P]=i.useState(null),H=i.useMemo(()=>{if(!c||m===!0)return null;const L=d!==void 0?D+d:u?u+c:D+c,ye=Math.min(c,Math.max(0,c-(L-D)));return{expiresAt:L,elapsedMs:ye}},[D,c,u,d,m]),J=x||!c||!H?null:te!==null&&te.expiresAt===H.expiresAt?te.seconds:Math.max(0,Math.ceil((H.expiresAt-D)/1e3));i.useEffect(()=>{if(x||!c||!H)return;const{expiresAt:L}=H,ye=setInterval(()=>{const re=Math.max(0,Math.ceil((L-Date.now())/1e3));P({expiresAt:L,seconds:re}),re<=0&&clearInterval(ye)},1e3);return()=>clearInterval(ye)},[c,H,x]);const Z=m===!0||J===0,ae=x||J===null?"":J<=0?"Nobody answered. The agent is waiting for you.":J<=La?"One minute left to answer.":J<=Ua?"Two minutes left to answer.":"",Y=i.useCallback(async()=>{if(!(y||x)){_(!0),z(null);try{await N.approveTool(e,t),A("approved"),a==null||a()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(A("approved"),a==null||a()):(console.error("Approval failed:",L),z("Couldn’t send your answer. Try again."))}finally{_(!1)}}},[y,x,N,e,t,a]),de=i.useCallback(async()=>{if(!(y||x)){_(!0),z(null);try{await N.approveTool(e,t,!0),A("approved"),a==null||a()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(A("approved"),a==null||a()):(console.error("Always Allow failed:",L),z("Couldn’t send your answer. Try again."))}finally{_(!1)}}},[y,x,N,e,t,a]),le=i.useCallback(async()=>{if(!(y||x)){_(!0),z(null);try{await N.denyTool(e,t,K.current.trim()||void 0),A("denied"),a==null||a()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(A("denied"),a==null||a()):(console.error("Deny failed:",L),z("Couldn’t send your answer. Try again."))}finally{_(!1)}}},[y,x,N,e,t,a]);i.useImperativeHandle(l,()=>({approve(){Y()},alwaysAllow(){de()},deny(){le()}}),[Y,de,le]);const ge=s.jsx("span",{role:"status","aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:ae});if(x){const L=x==="approved";return s.jsxs(s.Fragment,{children:[s.jsx(X.div,{initial:j?!1:{opacity:0,scaleY:.9},animate:{opacity:1,scaleY:1},transition:j?tm:em,style:{originY:0},children:s.jsx(qe,{"data-testid":"tool-approval-decided","data-decision":x,icon:L?s.jsx(et,{className:"text-status-success size-(--size-icon-sm) shrink-0"}):s.jsx(Me,{className:"text-status-error size-(--size-icon-sm) shrink-0"}),label:s.jsx("span",{className:"text-3xs font-mono",children:M}),trailing:s.jsx("span",{className:V("text-2xs rounded-full px-1.5 py-0.5 font-medium",L?"bg-status-success-bg text-status-success-fg":"bg-status-error-bg text-status-error-fg"),children:L?"Allowed":"Not allowed"})})}),ge]})}return s.jsxs(s.Fragment,{children:[s.jsxs(rt.Root,{isActive:o,isResolved:!!x,onAllow:Y,onDeny:le,className:"my-1","data-testid":"tool-approval",children:[s.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[s.jsx(Ia,{className:V("size-(--size-icon-md)",w==="high"&&"text-status-error",w==="medium"&&"text-status-warning",w==="low"&&"text-muted-foreground")}),s.jsx(rt.Headline,{className:"font-semibold",children:p||"Your agent wants to use a tool"})]}),(h||b||g)&&s.jsxs(rt.Detail,{className:"mb-2",children:[h&&s.jsx("p",{children:h}),b&&!h&&s.jsx("p",{children:b}),g&&s.jsxs("p",{className:"font-mono",children:["Path: ",g]})]}),(c||Z)&&!x&&s.jsx("div",{className:"mb-2",children:s.jsx(rt.Countdown,{secondsLeft:Z?null:J,...Z?{}:{timeoutMs:c},elapsedMs:(H==null?void 0:H.elapsedMs)??0,label:Z?Pa:J===null?"":`${sm(J)} remaining`})}),s.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[C&&s.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:C}),s.jsx("span",{className:"font-mono text-xs",children:M})]}),r&&s.jsx("div",{className:"bg-muted mb-3 rounded p-2",children:s.jsx(Wr,{toolName:n,input:r})}),O&&s.jsx("p",{className:"text-status-error text-2xs mb-2",children:O}),v&&I&&s.jsx("div",{className:"mb-2",children:s.jsx(Da,{autoFocus:!0,"data-approval-field":"",value:q,maxLength:$a,disabled:y,onFocus:()=>W(!0),onBlur:()=>W(!1),onChange:L=>{B(L.target.value),K.current=L.target.value},onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),le())},placeholder:"Why not? The agent sees this.","aria-label":"Reason for not allowing",className:"text-xs"})}),s.jsxs(rt.Actions,{children:[s.jsxs(ie,{size:"sm",onClick:Y,disabled:y,className:"transition-opacity duration-150",children:[s.jsx(et,{className:"size-(--size-icon-xs)"})," Allow",F&&s.jsx(Vt,{className:"ml-1.5",children:"Enter"})]}),k&&s.jsxs(ie,{size:"sm",variant:"outline",onClick:de,disabled:y,"aria-label":T===void 0?"Always allow":`Always allow, ${T}`,className:"transition-opacity duration-150",children:[s.jsx(Fa,{className:"size-(--size-icon-xs)"})," Always allow",T!==void 0&&s.jsx("span",{className:"text-2xs opacity-70",children:`· ${T}`}),F&&s.jsx(Vt,{className:"ml-1.5",children:"Shift+Enter"})]}),s.jsxs(ie,{size:"sm",variant:"outline",onClick:le,disabled:y,className:"transition-opacity duration-150",children:[s.jsx(Me,{className:"size-(--size-icon-xs)"})," Don’t allow",o&&s.jsx(Vt,{className:"ml-1.5",children:"Esc"})]}),v&&!I&&s.jsx("button",{type:"button",onClick:()=>$(!0),disabled:y,className:V("text-muted-foreground hover:text-foreground text-2xs rounded underline","focus-visible:ring-ring underline-offset-2 focus-visible:ring-2","focus-visible:outline-none disabled:opacity-50"),children:"Add a reason"})]})]}),ge]})}function rm(e){if(!e)return[];const t=e.properties??{};return Object.entries(t).map(([n,r])=>({key:n,label:r.description??n,type:r.type??"string",options:r.enum,defaultValue:r.default}))}function om({sessionId:e,interactionId:t,serverName:n,message:r,mode:o="form",url:a,requestedSchema:l,status:c,action:u}){const d=be(),[m,p]=i.useState(!1),[f,h]=i.useState(null),[g,b]=i.useState(null),[k,S]=i.useState({}),[v,N]=i.useState(!1),j=i.useMemo(()=>rm(l),[l]),w=c!=="pending",C=i.useCallback(async(x,A)=>{if(!(m||w)){p(!0),h(null),b(null);try{await d.submitElicitation(e,t,x,A)}catch(O){if(O.code!=="INTERACTION_ALREADY_RESOLVED"){h("Couldn’t send your answer. Try again."),b(O instanceof Error?O.message:null),p(!1);return}}p(!1)}},[d,e,t,m,w]),E=i.useCallback(()=>{const x={};for(const A of j)x[A.key]=k[A.key]??A.defaultValue??"";C("accept",x)},[j,k,C]),M=i.useCallback(()=>{C("accept")},[C]),T=i.useCallback(()=>{C("decline")},[C]),y=i.useCallback((x,A)=>{S(O=>({...O,[x]:A}))},[]),_=i.useCallback(()=>{if(a){if(!qa(a)){h(`Couldn’t open ${a}. Nothing has been authorized.`),b(null);return}h(null),b(null),N(!0)}},[a]);return w?s.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 py-1 text-xs",children:[s.jsx("span",{className:"font-mono",children:n}),s.jsx("span",{children:"·"}),s.jsx("span",{children:u==="accept"?"Authorized":u==="decline"?"Declined":"Cancelled"})]}):s.jsxs(X.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.15},className:V("border-border bg-card my-2 rounded-xl border p-4","shadow-soft"),children:[s.jsxs("div",{className:"text-muted-foreground mb-2 flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"bg-muted text-3xs inline-flex items-center rounded-md px-2 py-0.5 font-mono",children:n}),s.jsx("span",{children:"needs something from you"})]}),s.jsx("p",{className:"mb-3 text-sm",children:r}),f&&s.jsxs("div",{className:"mb-2",children:[s.jsx("p",{className:"text-destructive text-xs break-words",children:f}),g&&s.jsx("p",{className:"text-muted-foreground/70 mt-1 text-xs break-words",children:g})]}),o==="url"&&a&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ie,{size:"sm",variant:"outline",onClick:_,disabled:m,children:"Open authorization page"}),v&&s.jsx(ie,{size:"sm",onClick:M,disabled:m,children:m?"Sending…":"Done"}),s.jsx(ie,{size:"sm",variant:"ghost",onClick:T,disabled:m,children:"Decline"})]}),o==="form"&&s.jsxs(s.Fragment,{children:[j.length>0?s.jsx("div",{className:"mb-3 space-y-2",children:j.map(x=>s.jsxs("div",{children:[s.jsx("label",{htmlFor:`elicitation-${t}-${x.key}`,className:"text-muted-foreground mb-1 block text-xs font-medium",children:x.label}),x.options?s.jsxs("select",{id:`elicitation-${t}-${x.key}`,className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",value:k[x.key]??String(x.defaultValue??""),onChange:A=>y(x.key,A.target.value),disabled:m,children:[s.jsx("option",{value:"",children:"Select…"}),x.options.map(A=>s.jsx("option",{value:A,children:A},A))]}):s.jsx("input",{id:`elicitation-${t}-${x.key}`,type:x.type==="number"?"number":"text",className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",placeholder:String(x.defaultValue??""),value:k[x.key]??"",onChange:A=>y(x.key,A.target.value),disabled:m})]},x.key))}):s.jsx("p",{className:"text-muted-foreground mb-3 text-xs",children:"No additional input required."}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ie,{size:"sm",onClick:E,disabled:m,children:m?"Sending…":"Accept"}),s.jsx(ie,{size:"sm",variant:"ghost",onClick:T,disabled:m,children:"Decline"})]})]})]})}const am=8,im={duration:.3,ease:[.16,1,.3,1]},lm={duration:0};function cm(e){const t=Math.round(e/1e3),n=Math.floor(t/60),r=t%60;return n>0?`${n}:${String(r).padStart(2,"0")}`:`${r}s`}function um(e){return new Date(e).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function dm(e){return`${e} action${e===1?"":"s"}`}function mm({outcome:e,items:t,resolvedAt:n,startedAt:r,reasonGiven:o,className:a}){var b;const l=De(),[c,u]=i.useState(!1),d=t.length,m=d>1,p=m?dm(d):(b=t[0])==null?void 0:b.label,f=n!==void 0&&r!==void 0?Math.max(0,n-r):null,h=e==="allowed"?et:e==="denied"?Me:ot,g=e==="allowed"?"text-status-success":e==="denied"?"text-status-error":"text-muted-foreground";return s.jsxs(X.div,{"data-testid":"approval-receipt","data-outcome":e,"data-count":d,initial:l?!1:{opacity:0,y:am},animate:{opacity:1,y:0},transition:l?lm:im,className:V("text-muted-foreground my-1 text-xs",a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{className:V("size-(--size-icon-xs) shrink-0",g),"aria-hidden":"true"}),s.jsx("span",{className:"min-w-0 truncate",children:e==="expired"?s.jsxs(s.Fragment,{children:["Expired · ",m?`${p} `:"","denied",f!==null&&` after ${cm(f)}`]}):s.jsxs(s.Fragment,{children:["You ",e==="allowed"?"allowed":"denied"," ",m?p:s.jsx("span",{className:"font-mono",children:p}),e==="denied"&&o===!0&&s.jsx(s.Fragment,{children:" · agent was told why"})]})}),n!==void 0&&s.jsx("time",{dateTime:new Date(n).toISOString(),className:"ml-auto shrink-0 tabular-nums opacity-70",children:um(n)}),m&&s.jsx("button",{type:"button",onClick:()=>u(k=>!k),"aria-expanded":c,className:V("hover:text-foreground focus-visible:ring-ring shrink-0 rounded underline","underline-offset-2 focus-visible:ring-2 focus-visible:outline-none"),children:c?"Hide":"Show"})]}),m&&c&&s.jsx("ul",{"data-testid":"approval-receipt-items",className:"mt-1 ml-6 space-y-0.5",children:t.map(k=>s.jsx("li",{className:"truncate font-mono",children:k.label},k.toolCallId))})]})}function fm({outcome:e,reasonGiven:t,members:n,lead:r,children:o}){return s.jsxs("div",{className:"flex flex-col",children:[s.jsx(mm,{outcome:e,items:n.map(a=>({toolCallId:a.toolCallId,label:a.approvalDisplayName||nt(a.toolName,a.input??"")})),resolvedAt:r.approvalResolvedAt,startedAt:r.approvalStartedAt,reasonGiven:t}),e!=="allowed"&&r.result&&s.jsx(mr,{"data-testid":"approval-receipt-result",content:r.result,className:"text-muted-foreground mt-0.5 ml-6"}),e==="allowed"&&o]})}function pm({message:e}){return s.jsx(qe,{"data-testid":"unreadable-entry-note",icon:s.jsx(za,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:e})})}function hm({title:e}){return s.jsxs("div",{"data-testid":"capability-approval-timed-out",className:V("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[s.jsx(ot,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-sm",children:"The agent stopped waiting for your answer."}),s.jsxs("p",{className:"text-muted-foreground mt-0.5 text-xs",children:["“",e,"” is still in Approvals. Answer it, then ask the agent to retry."]})]})]})}function yn({testId:e,icon:t,children:n}){return s.jsxs("div",{"data-testid":e,className:V("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[t,s.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function gm({part:e}){return e.outcome==="failed"?s.jsx(yn,{testId:"mcp-signin-failed",icon:s.jsx(Nn,{"aria-hidden":"true",className:"text-status-warning-dot mt-0.5 size-4 shrink-0"}),children:s.jsxs("p",{className:"text-sm",children:["Sign-in to “",e.serverName,"” didn’t finish. Ask your agent to retry."]})}):s.jsx(yn,{testId:"mcp-signin-receipt",icon:s.jsx(fr,{"aria-hidden":"true",className:"text-status-success mt-0.5 size-4 shrink-0"}),children:s.jsxs("p",{className:"text-sm",children:["Connected to ",e.serverName,e.toolCount===void 0?"":` · ${e.toolCount} tool${e.toolCount===1?"":"s"}`,"."]})})}function xm({part:e}){const t=wc(e.agentId,e.serverName),{adopt:n}=t,r=e.outcome!==void 0;return i.useEffect(()=>{r||n({flowId:e.flowId,authorizeUrl:e.authorizeUrl,disclosure:e.disclosure})},[r,n,e.flowId,e.authorizeUrl,e.disclosure]),e.outcome!==void 0?s.jsx(gm,{part:e}):s.jsxs(yn,{testId:"mcp-signin-card",icon:s.jsx(Ba,{"aria-hidden":"true",className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),children:[s.jsxs("p",{className:"text-sm",children:["Sign in to ",e.serverName]}),s.jsx(Nc,{flow:t,serverName:e.serverName,failedActions:s.jsx(ie,{variant:"secondary",size:"sm",onClick:()=>t.start(),className:"focus-visible:ring-2",children:"Try again"})})]})}function bm({fromName:e,toName:t}){return s.jsx(qe,{"data-testid":"model-substituted-row",icon:s.jsx(ur,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsxs("span",{className:"text-muted-foreground",children:["DorkOS credits don’t cover ",e,", so this ran on ",t,". Switch in the model menu."]})})}const co="dorkos:mcp-app-consent:";function uo(e){return`${co}${e}`}function ym(e){try{return localStorage.getItem(uo(e))==="granted"}catch{return!1}}function km(e){try{localStorage.setItem(uo(e),"granted")}catch{}Sm()}const kn=new Set;function Sm(){for(const e of kn)e()}function vm(e){kn.add(e);const t=n=>{var r;(r=n.key)!=null&&r.startsWith(co)&&e()};return window.addEventListener("storage",t),()=>{kn.delete(e),window.removeEventListener("storage",t)}}function jm(e){const t=i.useSyncExternalStore(vm,()=>ym(e),()=>!1),n=i.useCallback(()=>km(e),[e]);return{consented:t,grant:n}}const Cm="h-80";function wm({sessionId:e,serverName:t,uri:n,title:r}){const{consented:o,grant:a}=jm(t),l=oe(d=>d.openPip),c=()=>{const d=oe.getState(),m={type:"mcp_app",serverName:t,uri:n,title:r};d.openCanvasDocument(m),pn(d,"user",m)},u=()=>{l({kind:"mcp_app",sessionId:e,serverName:t,uri:n,title:r??`App · ${t}`})};return o?s.jsxs("div",{className:"overflow-hidden rounded-lg border",children:[s.jsxs("div",{className:"bg-muted/40 flex items-center justify-between border-b px-3 py-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium",children:[s.jsx(gn,{className:"text-muted-foreground size-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:r??`App · ${t}`})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{type:"button",onClick:u,"aria-label":"Pop out into a floating window",title:"Pop out",className:"text-muted-foreground hover:bg-muted hover:text-foreground rounded-md p-1 transition-colors",children:s.jsx(Ha,{className:"size-3.5"})}),s.jsx("button",{type:"button",onClick:c,title:"Open in canvas",className:"text-muted-foreground hover:bg-muted hover:text-foreground rounded-md p-1 transition-colors",children:s.jsx(Wa,{className:"size-3.5"})})]})]}),s.jsx(bc,{sessionId:e,serverName:t,uri:n,title:r,onRequestFullscreen:c,onRequestPip:u,className:Cm})]}):s.jsxs("div",{className:"bg-muted/40 flex flex-col gap-3 rounded-lg border p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[s.jsx(gn,{className:"text-muted-foreground size-4 shrink-0"}),s.jsxs("span",{children:["Interactive app from ",t]})]}),s.jsxs("div",{className:"text-muted-foreground space-y-1 text-xs",children:[s.jsxs("p",{children:["It runs code from ",t," in a sealed-off frame."]}),s.jsx("p",{children:"It can’t see your session, files or credentials."})]}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:a,className:"bg-foreground text-background hover:bg-foreground/90 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",children:"Show app"})})]})}const Nm={running:s.jsx(Oe,{size:"xs",className:"text-muted-foreground"}),success:s.jsx(et,{className:"text-muted-foreground size-(--size-icon-xs)"}),error:s.jsx(Me,{className:"text-destructive size-(--size-icon-xs)"}),cancelled:s.jsx(Me,{className:"text-muted-foreground size-(--size-icon-xs)"})};function Tm({hook:e}){const t=!!(e.stdout||e.stderr),[n,r]=i.useState(e.status==="error"),o=e.stderr||e.stdout;return s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>t&&r(a=>!a),className:V("flex w-full items-center gap-1.5 py-0.5",!t&&"cursor-default"),"aria-expanded":t?n:void 0,disabled:!t,children:[Nm[e.status],s.jsx("span",{className:V("text-3xs font-mono",e.status==="error"?"text-destructive":"text-muted-foreground"),children:e.hookName}),e.status==="error"&&s.jsx("span",{className:"text-3xs text-destructive",children:"Error"}),e.exitCode!==void 0&&s.jsxs("span",{className:"text-3xs text-muted-foreground ml-auto",children:["exit ",e.exitCode]})]}),s.jsx(ue,{initial:!1,children:n&&t&&o&&s.jsx(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"overflow-hidden",children:s.jsx("pre",{className:"text-muted-foreground max-h-32 overflow-y-auto py-1 text-xs whitespace-pre-wrap",children:o})})})]})}function Am({toolCall:e,defaultExpanded:t=!1}){const[n,r]=i.useState(t),o=!!e.progressOutput;i.useEffect(()=>{o&&!n&&r(!0)},[o]);const a=e.hooks&&e.hooks.length>0?s.jsx("div",{className:"border-border/50 space-y-0.5 border-t px-3 py-1",children:e.hooks.map(u=>s.jsx(Tm,{hook:u},u.hookId))}):void 0,l=e.startedAt&&e.completedAt?e.completedAt-e.startedAt:void 0,c=dr(e.toolName);return s.jsxs(yt,{expanded:n,onToggle:()=>r(!n),dimmed:e.status==="complete",extraContent:a,"data-testid":"tool-call-card","data-tool-name":e.toolName,"data-status":e.status,header:s.jsxs(s.Fragment,{children:[Vr(e.status),c&&s.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:c}),s.jsx("span",{className:"text-3xs flex-1 text-left font-mono",children:nt(e.toolName,e.input)}),l!==void 0&&s.jsx("span",{className:"text-muted-foreground text-3xs tabular-nums",children:Tc(l)})]}),children:[e.status==="running"&&!e.input?s.jsxs("div",{className:"text-muted-foreground flex items-center gap-1.5 py-1 text-xs",children:[s.jsx(Oe,{size:"xs"}),s.jsx("span",{children:"Preparing…"})]}):e.input!==void 0&&e.input!==""?s.jsx(Wr,{toolName:e.toolName,input:e.input,isStreaming:e.status==="running"}):null,e.progressOutput&&!e.result&&s.jsx(mr,{content:e.progressOutput,className:"mt-2 border-t pt-2"}),e.result&&s.jsx("div",{className:"mt-2 border-t pt-2",children:s.jsx(pr,{content:e.result,toolName:e.toolName,input:e.input})})]})}function Rm(e){if(e.startsWith("mcp__"))return e.split("__")[1]||void 0}function mo(e,t,n){const r=i.useRef(e),[o,a]=i.useState(!(t&&r.current==="complete"));return i.useEffect(()=>{if(t&&e==="complete"&&r.current!=="complete"&&!n){const l=setTimeout(()=>a(!1),Ut.TOOL_CALL_AUTO_HIDE_MS);return()=>clearTimeout(l)}},[e,t,n]),!t||n?!0:o}function Em({part:e,autoHide:t,expandToolCalls:n}){var a;const r=((a=e.hooks)==null?void 0:a.some(l=>l.status==="error"))??!1,o=mo(e.status,t,r);return s.jsx(ue,{children:o&&s.jsx(X.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:s.jsx(Am,{toolCall:{toolCallId:e.toolCallId,toolName:e.toolName,input:e.input||"",result:e.result,progressOutput:e.progressOutput,status:e.status,hooks:e.hooks,startedAt:e.startedAt,completedAt:e.completedAt},defaultExpanded:n})},e.toolCallId)})}function rn({part:e,sessionId:t,autoHide:n,expandToolCalls:r}){const o=e.ui?Rm(e.toolName):void 0,a=s.jsx(Em,{part:e,autoHide:n,expandToolCalls:r});return!e.ui||e.status!=="complete"||!o?a:s.jsxs("div",{className:"flex flex-col gap-2",children:[a,s.jsx(wm,{sessionId:t,serverName:o,uri:e.ui.resourceUri})]})}function _m({part:e,autoHide:t,index:n}){const r=e.isStreaming?"running":"complete",o=mo(r,t,!1);return s.jsx(ue,{children:o&&s.jsx(X.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:s.jsx(ju,{text:e.text,isStreaming:e.isStreaming??!1,elapsedMs:e.elapsedMs})},`thinking-${n}`)})}const Mm=4,Ts=2;function Om({children:e}){const[t,n]=i.useState(!1);if(e.length<=Mm||t)return s.jsx(s.Fragment,{children:e});const r=e.length-Ts;return s.jsxs(s.Fragment,{children:[e.slice(0,Ts),s.jsx(yt,{expanded:!1,onToggle:()=>n(!0),ariaLabel:`Show ${r} more steps`,className:"border-l-muted-foreground/15",header:s.jsxs("span",{className:"text-3xs text-muted-foreground font-mono",children:["and ",r," more steps…"]}),children:s.jsx(s.Fragment,{})})]})}const Im=["z-30","-ml-2 z-20 opacity-70","-ml-2 z-10 opacity-45"];function Pm({chips:e,expanded:t,controls:n,onExpand:r}){const o=De()??!1,a=e.slice(-3).reverse();return s.jsxs("button",{type:"button","data-testid":"chip-pile","aria-expanded":t,"aria-controls":n,"aria-label":`Show everything this turn touched (${e.length} more)`,onClick:r,className:V("flex shrink-0 items-center gap-1.5 rounded-full py-0.5 pr-1.5 pl-0.5","hover:bg-accent focus-visible:ring-ring outline-none focus-visible:ring-2"),children:[s.jsx(X.span,{animate:o?{rotate:0,scale:1}:Ka,transition:Ga,className:"flex origin-bottom items-center",children:a.map((l,c)=>s.jsx("span",{"aria-hidden":"true",className:V("bg-card border-border text-3xs flex size-5 items-center justify-center rounded-full border leading-none",Im[c]),children:hr[l.verb]},l.key))},e.length),s.jsx("span",{"data-testid":"chip-pile-count",className:"bg-primary text-primary-foreground text-3xs rounded-full px-1.5 tabular-nums",children:e.length})]})}const Dm=new Set;function $m(){const[e,t]=i.useState(Dm),n=i.useCallback((o,a)=>a===!0&&!e.has(o),[e]),r=i.useCallback(o=>{t(a=>a.has(o)?a:new Set(a).add(o))},[]);return{shouldPulse:n,acknowledge:r}}function Fm(e){const t=[...e].sort((n,r)=>n.lastSeq-r.lastSeq);return{visible:t.slice(-os),absorbed:t.slice(0,Math.max(0,t.length-os))}}function Lm(e){return e.map(t=>{const n=[`${t.chips.length} ${gr[t.verb].toLowerCase()}`];return t.additions!==void 0&&n.push(`${t.additions} added`),t.deletions!==void 0&&n.push(`${t.deletions} removed`),n.join(", ")}).join("; ")}function Um({verb:e,count:t,additions:n,deletions:r}){return s.jsxs("span",{"data-testid":`chip-summary-${e}`,className:"inline-flex items-center gap-1",children:[s.jsx("span",{"aria-hidden":"true",children:hr[e]}),s.jsx("span",{className:"sr-only",children:gr[e]}),s.jsx("span",{className:"tabular-nums",children:t}),(n!==void 0||r!==void 0)&&s.jsxs("span",{className:"tabular-nums",children:[n!==void 0&&s.jsxs("span",{className:"text-emerald-600 dark:text-emerald-400",children:["+",n]}),n!==void 0&&r!==void 0&&" ",r!==void 0&&s.jsxs("span",{className:"text-red-600 dark:text-red-400",children:["−",r]})]})]})}function qm({parts:e,sessionId:t,turnActive:n=!1}){const r=De()??!1,o=i.useMemo(()=>Qa(e),[e]),a=$m(),l=i.useId(),c=Va(i.useMemo(()=>Ya(t,e),[t,e])),u=i.useCallback(h=>{if(h.pattern===!0)return;const g=oe.getState();if(h.kind==="url"){const b={type:"url",url:h.fullTarget};g.openCanvasDocument(b),pn(g,"user",b);return}if(h.kind==="file"){const b={type:"file",sourcePath:h.fullTarget};g.openCanvasDocument(b),pn(g,"user",b)}},[]),d=i.useMemo(()=>Xa(o),[o]),m=n||o.some(h=>h.live),{visible:p,absorbed:f}=i.useMemo(()=>Fm(o),[o]);return o.length===0?null:s.jsxs("div",{"data-testid":"touch-chip-strip",className:"mt-2 flex flex-col gap-2",children:[s.jsx(ue,{initial:!1,mode:"wait",children:m?s.jsxs(X.div,{"data-testid":"chip-live-row",role:"group","aria-label":"Latest activity",exit:r?{opacity:0}:{opacity:0,height:0},transition:r?ss:rs,className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[f.length>0&&s.jsx(Pm,{chips:f,expanded:c.expanded,controls:l,onExpand:c.toggleExpanded}),s.jsx(ue,{initial:!1,children:p.map(h=>s.jsx(Ja,{chip:h,onOpen:u,animated:!0,pulseUpgrade:a.shouldPulse(h.key,h.upgraded),onUpgradeSeen:a.acknowledge},h.key))})]},"live"):s.jsxs(X.div,{"data-testid":"chip-summary-line",role:"group","aria-label":Lm(d),initial:{opacity:0},animate:{opacity:1},transition:r?ss:rs,className:"text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs",children:[d.map((h,g)=>s.jsxs(i.Fragment,{children:[g>0&&s.jsx("span",{"aria-hidden":"true",children:"·"}),s.jsx(Um,{verb:h.verb,count:h.chips.length,additions:h.additions,deletions:h.deletions})]},h.verb)),s.jsx("span",{"aria-hidden":"true",children:"·"}),s.jsx("button",{type:"button","aria-expanded":c.expanded,"aria-controls":l,onClick:c.toggleExpanded,className:V("hover:text-foreground rounded-sm underline underline-offset-2","focus-visible:ring-ring outline-none focus-visible:ring-2"),children:c.expanded?"hide":"show all"})]},"settled")}),c.expanded&&s.jsx(Za,{id:l,chips:o,onOpen:u,verbFilter:c.verbFilter,onVerbFilterChange:c.setVerbFilter,order:c.order,onOrderChange:c.setOrder})]})}function As(e){return e.type==="thinking"?!0:e.type==="tool_call"&&!e.interactiveType&&!no(e.toolName)}function zm({message:e}){const{sessionId:t,isStreaming:n,isLatestWidgetMessage:r,isFinalMessage:o,activeToolCallId:a,onToolRef:l,focusedOptionIndex:c,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f,textEffect:h,runtimeLabel:g,allowsDenyReason:b}=ei(),{expandToolCalls:k,autoHideToolCalls:S}=oe(),v=e.parts??[],N=i.useCallback(y=>{l==null||l(y)},[l]),j=i.useCallback(y=>{l==null||l(y)},[l]),w=Vd(v);let C=-1;for(let y=v.length-1;y>=0;y--)if(v[y].type==="text"){C=y;break}function E(y,_){if(y.type==="text")return s.jsx("div",{className:"msg-prose",children:s.jsx(ti,{content:y.text,isStreaming:n&&_===C,textEffect:h,sessionId:t,isLatestWidgetMessage:r})},`text-${_}`);if(y.type==="background_task")return s.jsx(Pu,{part:y},y.taskId);if(y.type==="error"&&y.code===xr)return s.jsx(pm,{message:y.message},`unreadable-${_}`);if(y.type==="error")return s.jsx($t,{message:y.message,category:y.category,details:y.details,code:y.code,reason:y.reason,at:e.timestamp,onRetry:o&&y.category!==void 0?d:void 0,onSigninComplete:m,onChooseModel:p,runtimeLabel:g,sessionId:t},`error-${_}`);if(y.type==="thinking")return s.jsx(_m,{part:y,autoHide:S,index:_},`thinking-${_}`);if(y.type==="elicitation")return s.jsx(om,{sessionId:t,interactionId:y.interactionId,serverName:y.serverName,message:y.message,mode:y.mode,url:y.url,requestedSchema:y.requestedSchema,status:y.status,action:y.action},`elicitation-${y.interactionId}`);if(y.type==="memory_recall")return s.jsx(Cu,{mode:y.mode,memories:y.memories,isStreaming:y.isStreaming??!1},`memory-recall-${_}`);if(y.type==="permission_denied")return s.jsx(Wd,{toolName:y.toolName,reasonType:y.reasonType,reason:y.reason,message:y.message,agentId:y.agentId},`permission-denied-${y.toolCallId}-${_}`);if(y.type==="model_substituted")return s.jsx(bm,{fromName:y.fromName,toName:y.toName},`model-substituted-${_}`);if(y.type==="compact_boundary")return s.jsx(Ru,{trigger:y.trigger,preTokens:y.preTokens,postTokens:y.postTokens,failed:y.failed,error:y.error,requestedBy:y.requestedBy,contextPercent:y.contextPercent},`compact-boundary-${_}`);if(y.type==="capability_approval")return y.outcome==="timeout"?s.jsx(hm,{title:ni(y.approval)},`capability-approval-${y.approval.approvalId}`):s.jsx(si,{approval:y.approval},`capability-approval-${y.approval.approvalId}`);if(y.type==="mcp_signin")return s.jsx(xm,{part:y},`mcp-signin-${y.agentId}-${y.flowId}`);if(y.type==="image")return s.jsx(Eu,{part:y},`image-${y.attachmentId}-${_}`);if(y.type!=="tool_call")return null;const x=y;if(x.interactiveType==="approval"&&x.status==="pending"){if(x.toolCallId===f)return s.jsx(xs,{type:"approval",toolName:x.toolName,toolInput:x.input},x.toolCallId);const O=x.toolCallId===a;return s.jsx(lo,{ref:O?N:void 0,sessionId:t,toolCallId:x.toolCallId,toolName:x.toolName,input:x.input||"",timeoutMs:x.timeoutMs,approvalStartedAt:x.approvalStartedAt,approvalRemainingMs:x.approvalRemainingMs,approvalParked:x.approvalParked,approvalTitle:x.approvalTitle,approvalDisplayName:x.approvalDisplayName,approvalDescription:x.approvalDescription,approvalBlockedPath:x.approvalBlockedPath,approvalDecisionReason:x.approvalDecisionReason,approvalHasSuggestions:x.approvalHasSuggestions,approvalAlwaysAllowScope:x.approvalAlwaysAllowScope,isActive:O,onDecided:u?()=>u(x.toolCallId):void 0,allowsDenyReason:b},x.toolCallId)}const A=w.get(_);if(A){if(A.leadIndex!==_)return null;const O=A.indices.map(z=>v[z]).filter(z=>z.type==="tool_call");return s.jsx(fm,{outcome:A.outcome,reasonGiven:A.reasonGiven,members:O,lead:x,children:O.map(z=>s.jsx(rn,{part:z,sessionId:t,autoHide:S,expandToolCalls:k},z.toolCallId))},`approval-receipt-${x.toolCallId}`)}if(x.interactiveType==="question"){if(x.toolCallId===f)return s.jsx(xs,{type:"question",toolName:x.toolName,toolInput:x.input},x.toolCallId);const O=x.toolCallId===a;return s.jsx(br,{ref:O?j:void 0,sessionId:t,toolCallId:x.toolCallId,questions:x.questions??[],answers:x.answers??(Yd(x)?{}:void 0),outcome:Xd(x),result:x.result,isActive:O,focusedOptionIndex:O?c:-1,onDecided:u?z=>u(x.toolCallId,z):void 0},x.toolCallId)}return no(x.toolName)?s.jsx(pd,{sessionId:t,input:x.input,result:x.result,fallback:s.jsx(rn,{part:x,sessionId:t,autoHide:S,expandToolCalls:k})},x.toolCallId):s.jsx(rn,{part:x,sessionId:t,autoHide:S,expandToolCalls:k},x.toolCallId)}const M=[];let T=[];for(let y=0;y<v.length;y++){const _=v[y];As(_)?T.push(y):(T.length>0&&(M.push(T.length===1?{type:"single",index:T[0]}:{type:"run",indices:[...T]}),T=[]),M.push({type:"single",index:y}))}return T.length>0&&M.push(T.length===1?{type:"single",index:T[0]}:{type:"run",indices:[...T]}),s.jsxs(s.Fragment,{children:[M.map(y=>{if(y.type==="single"){const x=v[y.index];return As(x)?s.jsx("div",{className:"my-3",children:E(x,y.index)},`spacer-${y.index}`):E(x,y.index)}const _=y.indices.map(x=>E(v[x],x));return s.jsx("div",{className:"my-3",children:s.jsx(Om,{children:_})},`run-${y.indices[0]}`)}),s.jsx(qm,{parts:v,sessionId:t,turnActive:e._streaming===!0})]})}const Bm=/^Please read the following uploaded file\(s\):\n((?:- .+\n)+)\n?/,Hm=/^[a-f0-9]{8}-/,Wm=new Set(["png","jpg","jpeg","gif","webp","svg"]);function Gm(e){const t=e.match(Bm);if(!t)return{files:[],textContent:e};const r=t[1].split(`
31
+ `).filter(a=>a.startsWith("- ")).map(a=>{var m;const l=a.slice(2).trim(),u=(l.split("/").pop()??l).replace(Hm,""),d=((m=u.split(".").pop())==null?void 0:m.toLowerCase())??"";return{path:l,displayName:u,isImage:Wm.has(d)}}),o=e.slice(t[0].length).trim();return{files:r,textContent:o}}function Km(e){var n;switch(((n=e.split(".").pop())==null?void 0:n.toLowerCase())??""){case"txt":case"md":case"log":return ri;case"ts":case"tsx":case"js":case"jsx":case"json":case"py":case"rs":case"go":return Ec;case"csv":case"xls":case"xlsx":return $c;case"png":case"jpg":case"jpeg":case"gif":case"webp":case"svg":return Dc;default:return yr}}function Qm({files:e}){const t=oe(n=>n.selectedCwd);return e.length===0?null:s.jsx("div",{className:"flex flex-wrap gap-1.5 pb-1.5",children:e.map(n=>{const r=n.path.split("/").pop()??n.path;if(n.isImage){const a=`/api/uploads/${encodeURIComponent(r)}?cwd=${encodeURIComponent(t??"")}`;return s.jsx(X.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.15},children:s.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:s.jsx("img",{src:a,alt:n.displayName,loading:"lazy",className:"border-border/50 max-h-[120px] max-w-[200px] cursor-pointer rounded-lg border object-contain transition-[filter] duration-150 hover:brightness-95"})})},n.path)}const o=Km(n.displayName);return s.jsxs(X.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.15},className:"bg-muted flex items-center gap-1 rounded-md px-2 py-1 text-xs",children:[s.jsx(o,{className:"text-muted-foreground size-3 shrink-0"}),s.jsx("span",{className:"max-w-40 truncate",children:n.displayName})]},n.path)})})}function Vm({message:e}){const[t,n]=i.useState(!1),r=i.useMemo(()=>Gm(e.content),[e.content]),o=i.useMemo(()=>Su(e.content),[e.content]);if(o)return s.jsx(yu,{action:o});if(e.messageType==="command")return s.jsx("div",{className:"text-msg-command-fg font-mono text-sm break-words",children:e.content});if(e.messageType==="local_command_output")return s.jsx(pr,{content:e.content,toolName:""});if(e.messageType==="compaction"){const a=Tu(e.compactMetadata),l=e.content.trim(),c=s.jsx("div",{className:"bg-border/40 h-px flex-1"});return l.length===0?s.jsxs("div",{"data-testid":"compaction-row",className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[c,s.jsx("span",{children:a}),c]}):s.jsxs("div",{className:"w-full","data-testid":"compaction-row",children:[s.jsxs("button",{onClick:()=>n(!t),className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[c,s.jsx(wn,{className:V("size-3 transition-transform duration-200",t&&"rotate-90")}),s.jsx("span",{children:a}),c]}),t&&s.jsx("div",{className:"text-msg-compaction-fg mt-2 text-xs whitespace-pre-wrap",children:e.content})]})}return s.jsxs("div",{children:[r.files.length>0&&s.jsx(Qm,{files:r.files}),r.textContent&&s.jsx("div",{className:"break-words whitespace-pre-wrap",children:r.textContent})]})}function Ym({tasks:e,isCollapsed:t,onToggleCollapse:n}){const r=e.length,o=e.filter(c=>c.status==="completed").length,a=o===r&&r>0,l=r>0?o/r*100:0;return s.jsxs("button",{onClick:n,className:"text-muted-foreground hover:text-foreground flex w-full items-center gap-2 text-xs",children:[t?s.jsx(wn,{className:"size-(--size-icon-xs) shrink-0"}):s.jsx(Ft,{className:"size-(--size-icon-xs) shrink-0"}),s.jsx("div",{className:"bg-muted h-0.5 flex-1 overflow-hidden rounded-full",children:s.jsx("div",{"data-slot":"progress-fill",className:`h-full rounded-full transition-[width,background-color] duration-300 ease-out ${a?"bg-green-500":"bg-blue-500"}`,style:{width:`${l}%`}})}),s.jsxs("span",{className:"shrink-0 tabular-nums",children:[o,"/",r," ",r===1?"task":"tasks"]})]})}function Xm({activeForm:e,isCollapsed:t}){return s.jsx(ue,{children:e&&!t&&s.jsxs(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"mb-1 flex items-center gap-2 text-xs text-blue-400",children:[s.jsx(Oe,{size:"xs",className:"shrink-0"}),s.jsx("span",{className:"truncate",children:e})]})})}const Jm={in_progress:"",pending:"waiting ",completed:"done "};function Rs({tasks:e,onScrollToTask:t}){return s.jsx(s.Fragment,{children:e.map((n,r)=>s.jsxs("span",{children:[s.jsx("button",{onClick:o=>{o.stopPropagation(),t(n.id)},className:"hover:text-foreground underline decoration-dotted",children:n.subject}),r<e.length-1&&", "]},n.id))})}function Zm({task:e,taskMap:t,statusSince:n,onScrollToTask:r}){var d,m;const o=$r(n),a=Jm[e.status]??"",l=((d=e.blockedBy)==null?void 0:d.map(p=>t.get(p)).filter(p=>p!=null))??[],c=((m=e.blocks)==null?void 0:m.map(p=>t.get(p)).filter(p=>p!=null))??[],u=[];return n!==null&&u.push(s.jsxs("span",{children:[a,o.formatted]},"time")),e.owner&&u.push(s.jsx("span",{children:e.owner},"owner")),l.length>0&&u.push(s.jsxs("span",{className:"inline-flex items-center gap-1",children:["← ",s.jsx(Rs,{tasks:l,onScrollToTask:r})]},"blocked-by")),c.length>0&&u.push(s.jsxs("span",{className:"inline-flex items-center gap-1",children:["→ ",s.jsx(Rs,{tasks:c,onScrollToTask:r})]},"blocks")),s.jsxs(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"mt-0.5 ml-6 space-y-1",children:[e.description&&s.jsx("p",{className:"text-muted-foreground text-xs whitespace-pre-wrap",children:e.description}),u.length>0&&s.jsx("div",{className:"text-muted-foreground text-2xs flex flex-wrap items-center gap-1",children:u.map((p,f)=>s.jsxs("span",{className:"flex items-center gap-1",children:[f>0&&s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),p]},f))})]})}const Es={in_progress:s.jsx(Oe,{size:"xs",className:"text-status-info shrink-0"}),pending:s.jsx(oi,{className:"text-muted-foreground size-(--size-icon-xs) shrink-0"}),completed:s.jsx(fr,{className:"text-status-success size-(--size-icon-xs) shrink-0"})};function ef({task:e,isBlocked:t,isExpanded:n,onToggleExpand:r,onHover:o,isHighlightedAsDep:a,isHighlightedAsDependent:l,taskMap:c,statusSince:u,isCelebrating:d,onCelebrationComplete:m,onScrollToTask:p}){const f=h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),r())};return s.jsxs(X.li,{"data-task-id":e.id,children:[s.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":n,"data-task-id":e.id,onClick:r,onKeyDown:f,onMouseEnter:()=>o(e.id),onMouseLeave:()=>o(null),className:V("hover:bg-muted/40 focus-visible:bg-muted/40 relative flex items-center gap-2 rounded py-0.5 text-xs transition-colors",e.status==="completed"&&"text-muted-foreground/50 line-through",e.status==="in_progress"&&"text-foreground font-medium",e.status==="pending"&&!t&&"text-muted-foreground",e.status==="pending"&&t&&"text-muted-foreground/50",a&&"border-l-2 border-blue-400 pl-1.5",l&&"border-l-2 border-amber-400 pl-1.5",!a&&!l&&"border-l-2 border-transparent pl-1.5"),children:[d&&s.jsx(X.div,{"aria-hidden":"true",className:"absolute inset-0 rounded",initial:{backgroundPosition:"-200% 0"},animate:{backgroundPosition:"200% 0"},transition:{duration:.4,ease:"easeOut"},style:{backgroundImage:"linear-gradient(90deg, transparent 0%, rgba(255,215,0,0.2) 50%, transparent 100%)",backgroundSize:"200% 100%"}}),d?s.jsx(X.span,{initial:{scale:1},animate:{scale:[1,1.4,1]},transition:{type:"spring",stiffness:400,damping:10},onAnimationComplete:()=>m==null?void 0:m(),children:Es[e.status]}):Es[e.status],s.jsx("span",{className:"truncate",children:e.subject})]}),s.jsx(ue,{children:n&&s.jsx(Zm,{task:e,taskMap:c,statusSince:u,onScrollToTask:p})})]})}function tf(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(r=>{const o=t.get(r);return o&&o.status!=="completed"}):!1}const nf=10,sf="max-h-[30svh] sm:max-h-[40svh]";function rf({tasks:e,taskMap:t,activeForm:n,isCollapsed:r,onToggleCollapse:o,celebratingTaskId:a,onCelebrationComplete:l,statusTimestamps:c}){const[u,d]=i.useState(null),[m,p]=i.useState(null),f=i.useCallback(k=>{d(S=>S===k?null:k)},[]),h=i.useCallback(k=>{const S=document.querySelector(`[data-task-id="${k}"]`);S&&(S.scrollIntoView({behavior:"smooth",block:"nearest"}),S.classList.add("bg-blue-500/10"),setTimeout(()=>S.classList.remove("bg-blue-500/10"),1e3))},[]);if(e.length===0)return null;const g=e.slice(0,nf),b=m?t.get(m):null;return s.jsxs("div",{className:"border-t px-4 py-2",children:[s.jsx(Xm,{activeForm:n,isCollapsed:r}),s.jsx(Ym,{tasks:e,isCollapsed:r,onToggleCollapse:o}),s.jsx(ue,{children:!r&&s.jsx(X.ul,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:V("mt-1 space-y-0.5 overflow-y-auto",sf),children:g.map(k=>{var C,E;const S=k.id===a&&k.status==="completed",v=tf(k,t),N=c.get(k.id),j=((C=b==null?void 0:b.blockedBy)==null?void 0:C.includes(k.id))??!1,w=((E=b==null?void 0:b.blocks)==null?void 0:E.includes(k.id))??!1;return s.jsx(ef,{task:k,isBlocked:v,isExpanded:u===k.id,onToggleExpand:()=>f(k.id),onHover:p,isHighlightedAsDep:j,isHighlightedAsDependent:w,taskMap:t,statusSince:(N==null?void 0:N.since)??null,isCelebrating:S,onCelebrationComplete:l,onScrollToTask:h},k.id)})})})]})}function of({color:e}){const t=[{bx:"-8px",by:"-10px",delay:"0s"},{bx:"8px",by:"-8px",delay:"0.03s"},{bx:"-6px",by:"6px",delay:"0.06s"},{bx:"10px",by:"4px",delay:"0.09s"},{bx:"0px",by:"-12px",delay:"0.04s"},{bx:"-10px",by:"0px",delay:"0.07s"},{bx:"6px",by:"10px",delay:"0.05s"},{bx:"-4px",by:"-6px",delay:"0.08s"}];return s.jsx("div",{className:"pointer-events-none absolute inset-0",children:t.map((n,r)=>s.jsx("span",{className:"absolute top-1/2 left-1/2 size-[3px] rounded-full",style:{backgroundColor:e,"--bx":n.bx,"--by":n.by,animation:`burst-particle 0.5s ease-out ${n.delay} forwards`}},r))})}const af=350;function lf({status:e,color:t}){return s.jsxs("svg",{className:"check-appear h-6 w-[22px]",viewBox:"0 0 22 24","data-status":e,children:[s.jsx("circle",{cx:"11",cy:"12",r:"7",fill:"none",stroke:t,strokeWidth:"1.5",opacity:"0.3"}),e==="error"&&s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"8",y1:"9",x2:"14",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"}),s.jsx("line",{x1:"14",y1:"9",x2:"8",y2:"15",stroke:t,strokeWidth:"2",strokeLinecap:"round"})]}),e==="untracked"&&s.jsx("line",{x1:"8",y1:"12",x2:"14",y2:"12",stroke:t,strokeWidth:"2",strokeLinecap:"round",opacity:"0.5"}),e!=="error"&&e!=="untracked"&&s.jsx("polyline",{points:"7,12 10,15 15,9",fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function cf({agent:e,index:t}){const n=i.useMemo(()=>({animationDelay:`${t*.09}s`}),[t]),[r,o]=i.useState(e.status==="running"?"running":"done"),a=i.useRef(e.status),l=i.useRef(null);return i.useEffect(()=>{const c=a.current;if(a.current=e.status,c==="running"&&e.status!=="running"){o("celebrating"),l.current=setTimeout(()=>o("done"),af);return}c!=="running"&&e.status==="running"&&(l.current&&clearTimeout(l.current),l.current=null,o("running"))},[e.status]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[]),r==="done"?s.jsx("div",{className:"relative inline-flex",children:s.jsx(lf,{status:e.status,color:e.color})}):s.jsxs("div",{className:"group relative inline-flex",children:[s.jsx("svg",{className:"h-6 w-[22px] shrink-0",style:{"--c":e.color},viewBox:"0 0 22 24","aria-label":e.description,children:s.jsxs("g",{className:"r-all",style:n,children:[s.jsx("circle",{cx:"11",cy:"4.5",r:"2.8",fill:"var(--c)"}),s.jsx("circle",{cx:"12.3",cy:"3.7",r:"0.6",fill:"hsl(0 0% 100% / 0.7)"}),s.jsx("ellipse",{cx:"11",cy:"10.5",rx:"2.5",ry:"3.5",fill:"var(--c)"}),s.jsxs("g",{className:"r-rua",style:n,children:[s.jsx("line",{x1:"12",y1:"9",x2:"14",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("g",{className:"r-rfa",style:n,children:s.jsx("line",{x1:"14",y1:"11",x2:"14.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),s.jsxs("g",{className:"r-lua",style:n,children:[s.jsx("line",{x1:"10",y1:"9",x2:"8",y2:"11",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("g",{className:"r-lfa",style:n,children:s.jsx("line",{x1:"8",y1:"11",x2:"7.5",y2:"13",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),s.jsxs("g",{className:"r-rt",style:n,children:[s.jsx("line",{x1:"11",y1:"14",x2:"13",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("g",{className:"r-rs",style:n,children:s.jsx("line",{x1:"13",y1:"17",x2:"13.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]}),s.jsxs("g",{className:"r-lt",style:n,children:[s.jsx("line",{x1:"11",y1:"14",x2:"9",y2:"17",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"}),s.jsx("g",{className:"r-ls",style:n,children:s.jsx("line",{x1:"9",y1:"17",x2:"8.5",y2:"21",stroke:"var(--c)",strokeWidth:"1.8",strokeLinecap:"round"})})]})]})}),r==="celebrating"&&s.jsx(of,{color:e.color}),r==="running"&&s.jsxs("div",{"data-testid":"agent-runner-tooltip",className:V("pointer-events-none absolute bottom-[calc(100%+8px)] left-1/2 hidden","-translate-x-1/2 translate-y-1 opacity-0 transition-[opacity,translate] duration-150","group-hover:translate-y-0 group-hover:opacity-100","border-border bg-popover z-10 rounded-lg border px-3 py-2 whitespace-nowrap","text-foreground text-2xs shadow-lg md:block"),children:[s.jsxs("div",{className:"mb-0.5 flex items-center gap-1.5 font-semibold",children:[s.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:e.color}}),e.description]}),s.jsxs("div",{className:"text-muted-foreground text-3xs font-mono",children:[e.toolUses??0," tool calls · ",Math.round((e.durationMs??0)/1e3),"s"]}),e.lastToolName&&s.jsxs("div",{className:"text-muted-foreground/60 text-3xs mt-0.5 font-mono",children:["Last: ",e.lastToolName]}),s.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}function uf({bashTasks:e}){const t=De(),n=e.filter(o=>o.taskType==="bash"),r=n.length;return r===0?null:s.jsxs("div",{role:"status","aria-live":"polite","aria-label":`${r} bash task${r!==1?"s":""} running`,className:"flex items-center gap-1.5",children:[s.jsx(ue,{mode:"popLayout",children:n.map(o=>s.jsxs(X.div,{initial:{scale:0,opacity:0},animate:{scale:1,opacity:1},exit:{scale:0,opacity:0},transition:{duration:.25},className:"relative flex size-3 items-center justify-center",children:[o.status==="running"&&!t&&s.jsx("span",{className:"task-dot-tasks absolute inset-0 rounded-full opacity-40",style:{backgroundColor:o.color,animation:"task-dot-tasks 2s ease-in-out infinite"}}),s.jsx("span",{className:"relative size-1.5 rounded-full",style:{backgroundColor:o.color}})]},o.taskId))}),s.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[r," task",r!==1?"s":""]})]})}const df=3e3;function mf({taskType:e,onConfirm:t}){const[n,r]=i.useState(!1),o=i.useRef(null);i.useEffect(()=>()=>{o.current&&clearTimeout(o.current)},[]),i.useEffect(()=>{if(n)return o.current=setTimeout(()=>{r(!1)},df),()=>{o.current&&clearTimeout(o.current)}},[n]);const a=i.useCallback(()=>{if(e==="bash"){t();return}n?(o.current&&clearTimeout(o.current),r(!1),t()):r(!0)},[e,n,t]),l=i.useCallback(c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),a())},[a]);return s.jsx("button",{onClick:a,onKeyDown:l,className:V("flex shrink-0 items-center justify-center rounded transition-colors duration-150","focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-1",n?"bg-destructive/5 text-destructive hover:bg-destructive/10 text-3xs px-1.5 py-0.5 font-medium":"text-muted-foreground/40 hover:text-destructive size-4"),"aria-label":n?"Press again to stop task":"Stop task",tabIndex:0,children:n?"Stop?":s.jsx(Me,{className:"size-3"})})}function _s({task:e,onStop:t}){const n=e.taskType==="agent"?e.description??"Background agent":e.command??"Background task",r=e.durationMs?Math.round(e.durationMs/1e3):0,o=e.status==="running";return s.jsxs("div",{className:V("flex items-center gap-2 rounded-md px-2 py-1 text-xs",o?"bg-muted":"bg-muted/50 opacity-60"),children:[s.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:e.color}}),s.jsx("span",{className:"text-muted-foreground/60 text-3xs shrink-0 tracking-wider uppercase",children:e.taskType}),s.jsx("span",{className:"text-foreground min-w-0 flex-1 truncate",children:n}),e.taskType==="agent"&&e.toolUses!==void 0&&e.toolUses>0&&s.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[e.toolUses," tools"]}),e.taskType==="agent"&&e.lastToolName&&s.jsxs("span",{className:"text-muted-foreground/60 text-3xs hidden max-w-24 shrink-0 truncate font-mono md:inline",children:["Last: ",e.lastToolName]}),r>0&&s.jsxs("span",{className:"text-muted-foreground/60 text-3xs shrink-0 font-mono",children:[r,"s"]}),o&&s.jsx(mf,{taskType:e.taskType,onConfirm:t})]})}function ff({tasks:e,ambientTasks:t=[],onStopTask:n}){return s.jsx(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"border-border overflow-hidden border-t px-2 py-1.5",children:s.jsxs("div",{className:"flex flex-col gap-1",children:[e.map(r=>s.jsx(_s,{task:r,onStop:()=>n(r.taskId)},r.taskId)),t.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-muted-foreground/60 text-3xs mt-1 px-2",children:[t.length," housekeeping task",t.length!==1?"s":""," the agent runs for itself"]}),t.map(r=>s.jsx(_s,{task:r,onStop:()=>n(r.taskId)},r.taskId))]})]})})}const Sn=4;function pf(e){return e==="stopped"?"complete":e}const hf="relative after:absolute after:-inset-x-1 after:-inset-y-2.5 md:after:hidden",fo=[.16,1,.3,1],gf={width:{duration:.4,ease:fo},opacity:{duration:.25}};function xf({tasks:e,onStopTask:t}){const[n,r]=i.useState(!1),o=De(),{shown:a,ambient:l}=_l(e),c=a.filter(k=>k.taskType==="agent"),u=a.filter(k=>k.taskType==="bash"),d=a.length,m=c.slice(0,Sn),p=c.length-Sn,f=c.reduce((k,S)=>k+(S.toolUses??0),0),h=Math.max(0,...a.map(k=>Math.round((k.durationMs??0)/1e3))),g=o?{duration:0}:{duration:.35,ease:fo},b=d>0;return s.jsx(ue,{children:(d>0||l.length>0)&&s.jsxs(X.div,{...b?{role:"status","aria-live":"polite","aria-label":`${d} background task${d!==1?"s":""} running`}:{role:"group","aria-label":"Background tasks"},initial:{opacity:0,y:6,maxHeight:0},animate:{opacity:1,y:0,maxHeight:n?400:44},exit:{opacity:0,maxHeight:0},transition:g,className:"border-border bg-card overflow-hidden rounded-lg border",children:[s.jsxs("div",{className:"flex min-h-9 items-center gap-2 px-2 py-1.5",children:[c.length>0&&s.jsx(bf,{visibleAgents:m,overflowAgentCount:p,allAgentTasks:c}),c.length>0&&u.length>0&&s.jsx("div",{className:"bg-border h-4 w-px shrink-0"}),u.length>0&&s.jsx(uf,{bashTasks:u}),d>0&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[s.jsx("strong",{className:"text-foreground font-semibold",children:d})," task",d!==1?"s":""," running"]}),s.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto font-mono whitespace-nowrap",children:[f>0&&s.jsxs(s.Fragment,{children:[f," tools · "]}),h,"s"]})]}),s.jsxs("button",{type:"button",onClick:()=>r(k=>!k),className:V("text-muted-foreground hover:text-foreground flex shrink-0 items-center gap-1 transition-colors duration-150",d>0?"ml-1":"ml-auto",hf),"aria-label":n?"Collapse task details":"Expand task details","aria-expanded":n,children:[d>0&&s.jsx("span",{className:"text-3xs tabular-nums",children:d}),s.jsx(Ft,{className:V("size-3.5 transition-transform duration-200",n&&"rotate-180")})]})]}),s.jsx(ue,{children:n&&s.jsx(ff,{tasks:a,ambientTasks:l,onStopTask:t})})]},"background-task-bar")})}function bf({visibleAgents:e,overflowAgentCount:t,allAgentTasks:n}){return s.jsxs("div",{className:"flex items-center gap-0",children:[s.jsx(ue,{mode:"popLayout",children:e.map((r,o)=>s.jsx(X.div,{initial:{width:0,opacity:0},animate:{width:22,opacity:1},exit:{width:0,opacity:0},transition:gf,className:"shrink-0",children:s.jsx(cf,{agent:{taskId:r.taskId,description:r.description??"",status:pf(r.status),color:r.color,toolUses:r.toolUses,lastToolName:r.lastToolName,durationMs:r.durationMs,summary:r.summary},index:o})},r.taskId))}),t>0&&s.jsx(yf,{count:t,overflowTasks:n.slice(Sn)})]})}function yf({count:e,overflowTasks:t}){return s.jsxs("div",{className:"group relative",children:[s.jsxs("div",{className:"text-muted-foreground bg-muted text-3xs flex size-6 shrink-0 items-center justify-center rounded-full font-semibold","aria-label":`${e} more helper${e===1?"":"s"} running`,children:["+",e]}),s.jsxs("div",{"data-testid":"overflow-badge-tooltip",className:V("pointer-events-none absolute bottom-[calc(100%+8px)] left-1/2 hidden","-translate-x-1/2 translate-y-1 opacity-0 transition-[opacity,translate] duration-150","group-hover:translate-y-0 group-hover:opacity-100","border-border bg-popover z-10 rounded-lg border px-3 py-2 whitespace-nowrap","text-foreground text-2xs shadow-lg md:block"),children:[t.map(n=>s.jsxs("div",{className:"flex items-center gap-1.5 py-0.5",children:[s.jsx("div",{className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:n.color}}),s.jsx("span",{className:"text-3xs",children:n.description})]},n.taskId)),s.jsx("div",{className:"border-t-border absolute top-full left-1/2 -translate-x-1/2 border-5 border-transparent"})]})]})}const on="after:absolute after:-inset-1 md:after:hidden";function kf({queue:e,editingId:t,onEdit:n,onRemove:r,onSend:o,onMoveUp:a,statusNote:l,onSwitchNow:c}){return e.length===0?null:s.jsxs(X.div,{variants:Pe,initial:"initial",animate:"animate",exit:"exit",transition:Ie,className:"mb-1.5 overflow-hidden",children:[s.jsxs("div",{className:"text-muted-foreground mb-1 flex items-baseline gap-1 text-xs",children:[s.jsxs("span",{className:"font-medium",children:["Queued (",e.length,")"]}),s.jsxs("span",{className:"truncate",children:["· ",l]})]}),s.jsx("div",{className:"space-y-0.5",children:s.jsx(ue,{mode:"popLayout",children:e.map((u,d)=>s.jsx(X.div,{initial:{opacity:0,y:-4},animate:{opacity:1,y:0,transition:{type:"spring",stiffness:320,damping:28}},exit:{opacity:0,scale:.95,transition:{duration:.15}},layout:!0,children:s.jsxs("div",{className:V("group flex w-full items-center gap-2 rounded-md border-l-2 border-l-transparent pr-2 transition-colors md:gap-1",t===u.id?"border-l-primary bg-muted":"hover:bg-muted/50"),children:[s.jsxs("button",{type:"button",onClick:()=>n(u.id),"aria-current":t===u.id?!0:void 0,className:"focus-ring flex min-w-0 flex-1 items-center gap-2 rounded-md py-1.5 pl-3 text-left",children:[s.jsxs("span",{className:"text-muted-foreground shrink-0 text-xs font-medium",children:[d+1,"."]}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"text-muted-foreground line-clamp-1 text-sm",children:u.content}),u.notice!==null&&s.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.notice}),u.waiting!==void 0&&s.jsx("span",{className:"text-muted-foreground/70 line-clamp-1 text-xs",children:u.waiting.line})]}),!u.mine&&s.jsxs("span",{className:"text-muted-foreground/60 flex shrink-0 items-center",title:"Queued from another window",children:[s.jsx(gn,{className:"size-3","aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Queued from another window"})]})]}),u.waiting!==void 0&&c!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:c,title:u.waiting.switchHint,"aria-describedby":`switch-now-${u.id}`,className:"focus-ring text-muted-foreground hover:text-foreground shrink-0 rounded-sm px-1.5 py-1 text-xs font-medium transition-colors",children:"Switch now"}),s.jsx("span",{id:`switch-now-${u.id}`,className:"sr-only",children:u.waiting.switchHint})]}),d>0&&s.jsx("button",{type:"button",onClick:()=>a(u.id),className:V("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100",on),"aria-label":`Move queued message ${d+1} earlier`,children:s.jsx(ai,{className:"size-3"})}),d>0&&s.jsx("button",{type:"button",onClick:()=>o(u.id),"aria-label":`Send queued message ${d+1} next`,className:V("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors",on),children:s.jsx(ii,{className:"size-3"})}),s.jsx("button",{type:"button",onClick:()=>r(u.id),className:V("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:focus-visible:opacity-100",on),"aria-label":`Remove queued message ${d+1}`,children:s.jsx(Me,{className:"size-3"})})]})},u.id))})})]})}function Sf({open:e,onOpenChange:t,queuedCount:n,onConfirm:r}){const o=n===1?"message":"messages";return s.jsx(li,{open:e,onOpenChange:t,children:s.jsxs(ci,{children:[s.jsxs(ui,{children:[s.jsxs(di,{children:["Stop, and put ",n," queued ",o," back?"]}),s.jsxs(mi,{children:["The agent stops. Your ",o," ",n===1?"goes":"go"," back to the composer."]})]}),s.jsxs(fi,{children:[s.jsx(pi,{children:"Keep going"}),s.jsx(hi,{onClick:r,children:"Stop"})]})]})})}const vf={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4}},jf={duration:.3,ease:"easeInOut"};function Cf({text:e,animationKey:t}){return s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-start overflow-hidden py-0.5",children:s.jsx(ue,{mode:"wait",children:s.jsx(X.span,{variants:vf,initial:"initial",animate:"animate",exit:"exit",transition:jf,className:"text-muted-foreground truncate text-sm",children:e},t)})})}function wf(e){const t=be();return st({queryKey:["workspace-for-session",e??null],queryFn:()=>t.resolveWorkspace(e),enabled:!!e}).data??null}async function po(e,t,n){try{return await e.runCommandIntent(t,"compact",n),!0}catch(r){const o=r.code==="SESSION_LOCKED";return we.error(o?"Your agent is busy. Try again in a moment.":"Couldn’t compact the conversation."),!1}}function ho(e){const t=/^\/(\S+)([\s\S]*)$/.exec(e.trim());return t?{token:t[1],rest:t[2].trim()}:null}function Nf(e){const t=ho(e);return t?kr(t.token)?!0:Sr(e.trim())!==null:!1}function Tf(e,t,n={}){const{mutateAsync:r}=hc(e),o=be(),{startFreshSession:a,compact:l}=n,[c,u]=i.useState(0),d=i.useCallback(p=>{u(h=>h+1);const f=()=>u(h=>Math.max(0,h-1));p.then(f,f)},[]);return{tryRun:i.useCallback(p=>{const f=ho(p),h=f?kr(f.token):null;if(f&&(h==null?void 0:h.fulfillment)==="runtime"&&l){if(!l.supported)return we.error(`Compact isn’t available on ${l.runtimeLabel||"this agent"}`),{handled:!0,ran:!1};if(!t)return we.error("No active session to compact"),{handled:!0,ran:!1};const S=po(o,t,f.rest||void 0);return d(S),{handled:!0,ran:!0,confirmed:S}}const g=Sr(p);if(!g)return{handled:!1};let b;return{handled:!0,ran:g.command.run(g.args,{sessionId:t,renameSession:S=>{t&&(b=r({sessionId:t,title:S}).then(()=>(we.success(`Renamed session to “${S}”`),!0),()=>!1),d(b))},notify:(S,v)=>v==="error"?we.error(S):we.success(S),startFreshSession:S=>a==null?void 0:a(S),focusUsageSurface:()=>hn.getState().reveal()}),...b?{confirmed:b}:{}}},[r,o,t,a,l,d]),commandPending:c>0}}function go(e,t){return{supported:(e==null?void 0:e.compact.supported)!==!1,runtimeLabel:t}}function Ms(e){const t=e.trim().toLowerCase();return t.startsWith("/")?t:`/${t}`}function Af(e){return xi.map(t=>{var r,o;const n=t.fulfillment==="runtime"&&((o=(r=e==null?void 0:e.commandIntents)==null?void 0:r[t.id])==null?void 0:o.supported)===!1;return{command:t.id,fullCommand:t.canonical,description:t.description,argumentHint:t.argumentHint,aliases:[...t.aliases],...n?{disabled:!0,disabledReason:`Not available on ${e.runtimeLabel}`}:{}}})}function Rf(e,t){const n=gi(),r=Af(t),o=as.filter(c=>!(c.command!==void 0&&n.has(`/${c.command}`))),a=new Set(as.map(c=>c.command)),l=e.filter(c=>{if(c.command!==void 0&&a.has(c.command))return!1;const u=[c.fullCommand,...c.aliases??[]].map(Ms);return c.command!==void 0&&u.push(Ms(c.command)),!u.some(d=>n.has(d))});return[...r,...o,...l]}const Ef=3e4;function _f({percent:e,compactSupported:t,isStreaming:n}){return!(e===null||e<bi||!t||n)}function Mf({sessionId:e,percent:t,compactSupported:n,isStreaming:r}){const o=be(),[a,l]=i.useState(!1),c=i.useRef(!1),u=i.useRef(null),d=i.useCallback(()=>{c.current=!1,l(!1),u.current!==null&&(clearTimeout(u.current),u.current=null)},[]);i.useEffect(()=>{r&&c.current&&d()},[r,d]),i.useEffect(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]);const m=i.useCallback(()=>{c.current||!e||(c.current=!0,l(!0),u.current=setTimeout(()=>{u.current=null,c.current=!1,l(!1)},Ef),po(o,e).then(p=>{p||d()}))},[e,o,d]);return{visible:_f({percent:t,compactSupported:n,isStreaming:r}),percent:t??0,pending:a,onCompact:m}}function Of({children:e,onSwitchAgent:t,onViewProfile:n,onNewSession:r}){return s.jsxs(yi,{children:[s.jsx(ki,{className:"min-w-0",children:e}),s.jsxs(Si,{className:"w-48",children:[s.jsxs(Yt,{onClick:t,children:[s.jsx(vi,{className:"mr-2 size-4"}),"Switch agent"]}),s.jsx(is,{}),s.jsxs(Yt,{onClick:n,children:[s.jsx(ji,{className:"mr-2 size-4"}),"View profile"]}),s.jsx(is,{}),s.jsxs(Yt,{onClick:r,children:[s.jsx(er,{className:"mr-2 size-4"}),"New session"]})]})]})}function If({agentName:e,agentColor:t,agentEmoji:n,agentPath:r,nameHidden:o}){const a=Ci(r),{open:l}=wi(),c=i.useCallback(()=>{r&&Ni.getState().openProfileDocked(r)},[r]),u=i.useCallback(()=>{if(a===void 0)return c();l(a)},[a,l,c]),d=i.useCallback(()=>{oe.getState().openGlobalPaletteWithSearch("@")},[]),m=cr(),p=i.useCallback(()=>{m(r??void 0)},[m,r]);return!e||!t||!n?null:s.jsx("span",{className:"inline-flex min-w-0 items-center",children:r?s.jsx(Of,{onSwitchAgent:d,onViewProfile:u,onNewSession:p,children:s.jsx(ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:o,onClick:u,className:"max-w-full"})}):s.jsx(ls,{size:"xs",name:e,color:t,emoji:n,nameHidden:o,className:"max-w-full"})})}function Pf({sessionId:e,account:t}){const[n,r]=i.useState(!1),[o,a]=i.useState(!1),l=i.useRef(null);return s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:l,className:"contents",children:s.jsx(Ti,{sessionId:e,account:t,open:n,onOpenChange:r,onContinue:()=>{r(!1),a(!0)}})}),s.jsx(Jr,{open:o,onOpenChange:a,sessionId:e,account:t,onCloseAutoFocus:c=>{var d;const u=(d=l.current)==null?void 0:d.querySelector("button");u&&(c.preventDefault(),u.focus())}})]})}function Df({ctx:e,items:t}){return s.jsx("span",{className:"inline-flex min-w-0 items-center gap-2",children:t.map((n,r)=>{const o=n.component;return s.jsxs(i.Fragment,{children:[r>0&&s.jsx("span",{className:"text-muted-foreground/30 shrink-0","aria-hidden":"true",children:"·"}),s.jsx("span",{role:"group","aria-label":n.label,"data-testid":`extension-status-item-${n.id}`,className:"inline-flex min-w-0 items-center",children:s.jsx(vr,{fallback:null,onError:a=>xo(n,a),children:s.jsx(o,{...e})})})]},n.id)})})}function xo(e,t){console.warn(`[extensions] ${e.extensionId}'s status-bar item "${e.id}" failed to draw and is hidden.`,t)}function $f({ctx:e,items:t}){return s.jsx(s.Fragment,{children:t.map(n=>{const r=n.component;return s.jsxs("div",{role:"group","aria-label":n.label,"data-testid":`session-row-extension-${n.id}`,className:"flex items-center gap-2 px-1 py-1 text-sm",children:[s.jsx("span",{className:"shrink-0",children:n.label}),s.jsx("span",{className:"min-w-0 flex-1"}),s.jsx("span",{className:"text-muted-foreground inline-flex min-w-0 items-center text-xs",children:s.jsx(vr,{fallback:null,onError:o=>xo(n,o),children:s.jsx(r,{...e})})})]},n.id)})})}function Ff(e){const{costUsd:t,costBasis:n,...r}=e;return r}function Lf(e){var m;const{sessionId:t,agent:n,status:r,runtimeChip:o,onUpdateSession:a}=e,l={},c=e.density!=="full";n.name&&n.color&&n.emoji&&(l.agent=s.jsx(If,{agentName:n.name,agentColor:n.color,agentEmoji:n.emoji,agentPath:n.path,nameHidden:e.density==="avatar"})),r.cwd&&(l.cwd=s.jsx(Ml,{cwd:r.cwd})),e.gitStatus&&(l.git=s.jsx(ql,{data:e.gitStatus,workspace:e.workspace,compact:c})),o.runtime!==null&&(l.runtime=s.jsx(Ol,{runtime:o.runtime,model:o.model,onChangeRuntime:o.onChangeRuntime,canSelect:o.canSelect,account:o.account,compact:!0}));const u=jr(e.account);u!==null&&(l.account=s.jsx(Pf,{sessionId:t,account:e.account})),e.extensions.items.length>0&&(l.extensions=s.jsx(Df,{ctx:e.extensions.ctx,items:e.extensions.items})),l.model=s.jsx(Il,{model:r.model,onChangeModel:p=>a({model:p}),effort:r.effort,onChangeEffort:p=>a({effort:p??void 0}),fastMode:r.fastMode,onChangeFastMode:p=>a({fastMode:p}),disabled:!t,sessionId:t||void 0,runtime:o.runtime,onCredits:e.account.onCredits,compact:c}),(m=e.plan)!=null&&m.active||(l.permission=s.jsx(Pl,{mode:r.permissionMode,onChangeMode:e.onChangeMode,disabled:!t,pending:!r.permissionModeKnown,runtime:o.runtime,modelSupportsAutoMode:e.modelSupportsAutoMode,compact:c,makeDefault:e.makeDefault,onOpenChange:e.onPermissionPickerOpenChange})),e.plan&&(l.plan=s.jsx(Dl,{descriptor:e.plan.descriptor,active:e.plan.active,onToggle:e.plan.onToggle,disabled:!t})),e.contextPercent!==null&&(l.context=s.jsx($l,{percent:e.contextPercent,contextUsage:e.contextUsage,compact:e.compact,reading:e.contextReading}));const d=e.usage&&e.usageSource==="account"&&!e.supportsCostTracking?Ff(e.usage):e.usage;return d&&Ai(d)&&(e.supportsCostTracking||e.usageSource==="account")&&!Fl({account:u})&&(l.usage=s.jsx(Ri,{usage:d,observedAt:e.usageObservedAt,now:e.now})),e.liveSubagentCount>0&&(l.subagents=s.jsx(Ll,{count:e.liveSubagentCount,running:e.runningSubagents,waiting:e.waitingOnSubagents})),l.connection=s.jsx(Ul,{connectionState:e.connectionState,compact:c}),l}const Uf=[],qf="(max-width: 639px)";function zf({sessionId:e,sessionStatus:t,isStreaming:n,syncConnectionState:r,agentName:o,agentColor:a,agentEmoji:l,agentPath:c}){var Le,ce;const{ref:u,budget:d}=zl(),m=Cr(e),p=Pr(e,t,n,m.runtime),f=bt(e||null),{pins:h}=Bl(),g=Hl(e),b=Wl(e,f,g.usage),k=b.usage,S=gt(),v=new Date(S),N=Ei(k,b.observedAt,v),j=g.contextUsage,w=((Le=In(e))==null?void 0:Le.contextUsage)??null,C=hn(G=>G.open),E=hn(G=>G.setOpen),{data:M}=Gl(p.cwd),T=wf(p.cwd),{project:y}=_i(p.cwd),_=Mi(qf),x=i.useMemo(()=>({sessionId:e,cwd:p.cwd,project:y,trackerItems:f.trackerItems,compact:_}),[e,p.cwd,y,f.trackerItems,_]),A=Kl(x),{data:O}=On(),z=Ql(g.activeSubagents).running,I=g.runningSubagentCount??z.length,{data:$}=Mn({sessionId:e||void 0,runtime:m.runtime??void 0}),q=((ce=$==null?void 0:$.find(G=>G.value===p.model))==null?void 0:ce.supportsAutoMode)??!1,B=qt(m.runtime),K=(B==null?void 0:B.permissionModes.values)??Uf,se=B==null?void 0:B.permissionModes.default,W=Oi(e),F=ne(G=>G.recordAutoConfirmed),[D,R]=i.useState(!1),Q=Ii(e),te=ne(G=>G.recordAutonomyConfirmed),[P,H]=i.useState(null),J=Pi(),Z=Vl({sessionId:e,runtime:m.runtime,declaredModes:K,runtimeDefaultMode:se}),[ae,Y]=i.useState(!1),de=J.acknowledgedAt!==null||Q,le=i.useCallback(G=>{const ee=K.find(he=>he.id===G),Se=ee!==void 0&&cs(ee);return p.updateSession({permissionMode:G,...Se&&de?{acknowledgedAutonomy:!0}:{}},{onError:he=>{(he==null?void 0:he.code)==="AUTONOMY_ACK_REQUIRED"&&ee&&H(ee)}})},[K,de,p,H]),ge=i.useCallback(G=>{if(G==="auto"&&!W){R(!0);return}const ee=K.find(Se=>Se.id===G);if(ee&&cs(ee)&&!de){H(ee);return}le(G).then(Se=>{Se&&Z.offerFor(G)})},[W,de,K,le,Z,H,R]),L=i.useCallback(()=>{F(e),le("auto"),R(!1)},[F,e,le,R]),ye=i.useCallback(G=>{if(!P)return;te(e),G&&J.acknowledge();const ee=P.id;p.updateSession({permissionMode:ee,acknowledgedAutonomy:!0}).then(Se=>{Se&&Z.offerFor(ee)}),H(null)},[P,te,e,p,J,Z,H]),re=Di(K),Te=re!==void 0&&p.permissionMode===re.id,ke=$i(e),je=ne(G=>G.recordModeBeforePlan),Ae=i.useCallback(G=>{if(!re)return;if(G){je(e,p.permissionMode),le(re.id);return}const ee=ke,kt=ee!==void 0&&K.some(Wt=>Wt.id===ee)&&(ee!=="auto"||q)?ee:se;kt&&le(kt)},[re,je,e,p,le,ke,K,q,se]),me=m.runtime?ht(m.runtime).label:"",_e=go(B==null?void 0:B.commandIntents,me),pe=g.contextPercent,fe=Mf({sessionId:e,percent:pe,compactSupported:_e.supported,isStreaming:n}),[xe,Re]=i.useState(!1);Yl(()=>Re(G=>!G));const $e={cwd:p.cwd,git:Xl(M)?Jl(M.branch,M.clean,M.detached):null,contextPercent:pe,connectionState:r,permissionMode:p.permissionMode,permissionDescriptor:(B==null?void 0:B.permissionModes.values.find(G=>G.id===p.permissionMode))??null,plan:re?{active:Te}:null,runtime:m.runtime===null||O===void 0?null:{isDefault:m.runtime===O.defaultRuntime,canSelect:m.canSelect},account:jr(f),usage:k,usageStale:N,subagentsInFlight:I,extensionItems:A.promotion},He=fe.visible&&d.density==="full",Ee=fe.visible&&!He,We=Lf({sessionId:e,agent:{name:o,color:a,emoji:l,path:c},status:p,onUpdateSession:p.updateSession,onChangeMode:ge,makeDefault:ae?Z.line:null,onPermissionPickerOpenChange:Y,modelSupportsAutoMode:q,plan:re?{descriptor:re,active:Te,onToggle:Ae}:null,gitStatus:M,workspace:T,runtimeChip:m,account:f,contextPercent:pe,contextUsage:j,contextReading:w,compact:He?{pending:fe.pending,onCompact:fe.onCompact}:null,usage:k,usageSource:b.source,usageObservedAt:b.observedAt,now:v,supportsCostTracking:(B==null?void 0:B.supportsCostTracking)??!0,runningSubagents:z,liveSubagentCount:I,waitingOnSubagents:g.lifecycle==="idle",connectionState:r,density:d.density,extensions:{ctx:x,items:A.visible}}),{items:Ge,overflow:Fe}=Zl(ec({ctx:$e,pins:h,nodes:We}),d);return s.jsxs("div",{ref:u,className:"relative pt-2",children:[!ae&&Z.line&&s.jsx(tc,{...Z.line,placement:"overlay"}),s.jsx(nc,{items:Ge,trailing:s.jsx(sc,{open:xe,onOpenChange:Re,diagnostics:g,controls:{plan:re?{active:Te,onToggle:Ae}:null},promotionContext:$e,overflowCount:Fe,addOns:A.visible.length>0?s.jsx($f,{ctx:x,items:A.visible}):void 0,urgentAction:Ee?{label:`Compact conversation · ${fe.percent}% full`,onAction:fe.onCompact,pending:fe.pending}:null})}),s.jsx(rc,{usage:k??null,accountUsage:b.accountUsage,observedAt:b.observedAt,open:C,onOpenChange:E}),s.jsx(oc,{open:D,onOpenChange:R,onConfirm:L}),s.jsx(us,{descriptor:P,onCancel:()=>H(null),onConfirm:ye,canRemember:J.canRemember}),s.jsx(us,{descriptor:Z.pendingDescriptor,canRemember:!1,consentNote:"Every new session will start here, and DorkOS will remember that you have read this.",onCancel:Z.cancel,onConfirm:Z.confirm})]})}const Bf=Object.freeze({completed:"Completed",aborted_tools:"Tool stopped",aborted_streaming:"Reply stopped",max_turns:"Turn limit reached",blocking_limit:"Blocking limit",rapid_refill_breaker:"Rate limit",prompt_too_long:"Prompt too long",image_error:"Image error",model_error:"Model error",stop_hook_prevented:"Stopped by hook",hook_stopped:"Hook stopped",tool_deferred:"Tool deferred"});function Hf(e){return e!==void 0&&e!=="completed"}function Wf(e){const t=Bf[e];return t!==void 0?t:Gf(e)}function Gf(e){if(e.length===0)return"Ended";const t=e.replace(/[_-]+/g," ").trim().split(/\s+/);if(t.length===0)return"Ended";const[n,...r]=t;return[n.charAt(0).toUpperCase()+n.slice(1).toLowerCase(),...r.map(a=>a.toLowerCase())].join(" ")}function Kf({terminalReason:e}){const t=Hf(e),n=t?Wf(e):"";return s.jsx(ue,{children:t&&s.jsx(X.div,{initial:{opacity:0,y:-4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.2,ease:"easeOut"},className:"flex px-4 py-1","data-testid":"terminal-reason-chip",children:s.jsx(Fi,{variant:"secondary","aria-label":`Session ended: ${n}`,children:n})},e)})}const Qf="The turn ended before completing.";function Vf({sessionId:e,onRetry:t,onSigninComplete:n,onChooseModel:r}){var f;const o=zt(e),a=((f=In(e))==null?void 0:f.lastError)??null,l=(a==null?void 0:a.category)==="auth_error"||(a==null?void 0:a.category)==="model_unavailable"||(a==null?void 0:a.category)==="runtime_update_required",c=!l&&o?`${ht(o).label} stopped unexpectedly`:void 0,u=(a==null?void 0:a.message)??Qf,d=l?void 0:u,m=o?wr(o):void 0,p=a?[a.code,a.details].filter(Boolean).join(`
32
+ `):void 0;return s.jsx(X.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{delay:.3,duration:.2,ease:"easeOut"},className:"mx-4 mb-2","data-testid":"turn-failed-notice",children:s.jsx($t,{category:(a==null?void 0:a.category)??"execution_error",heading:c,message:u,subtext:d,details:p||void 0,onRetry:t,onSigninComplete:n,onChooseModel:r,runtimeLabel:m,sessionId:e,...a!=null&&a.code?{code:a.code}:{},...a!=null&&a.reason?{reason:a.reason}:{}})})}const Yf=["Type @ to mention a file","Type / to browse commands","End a line with \\ to keep typing","Drop or paste files to attach"];function Xf(e,t,n){const r=i.useCallback(g=>{var v;if(!e||!t.current)return;const b=ne.getState(),k=(v=n.current)==null?void 0:v.get(e);if(k!==void 0&&b.getSession(e).mountGeneration!==k)return;const S=typeof g=="function"?g(b.getSession(e).messages):g;b.updateSession(e,{messages:S})},[e,t,n]),o=i.useCallback(g=>{e&&ne.getState().updateSession(e,{input:g})},[e]),a=i.useCallback(g=>{e&&ne.getState().updateSession(e,{status:g})},[e]),l=i.useCallback(g=>{e&&ne.getState().updateSession(e,{error:g})},[e]),c=i.useCallback(g=>{e&&ne.getState().updateSession(e,{sessionStatus:g})},[e]),u=i.useCallback(g=>{e&&ne.getState().updateSession(e,{estimatedTokens:g})},[e]),d=i.useCallback(g=>{e&&ne.getState().updateSession(e,{streamStartTime:g})},[e]),m=i.useCallback(g=>{e&&ne.getState().updateSession(e,{isTextStreaming:g})},[e]),p=i.useCallback(g=>{e&&ne.getState().updateSession(e,{systemStatus:g})},[e]),f=i.useCallback(g=>{e&&ne.getState().updateSession(e,{operationProgress:g})},[e]),h=i.useCallback(g=>{e&&ne.getState().updateSession(e,{promptSuggestions:g})},[e]);return{setMessages:r,setInput:o,setStatus:a,setError:l,setSessionStatus:c,setEstimatedTokens:u,setStreamStartTime:d,setIsTextStreaming:m,setSystemStatus:p,setOperationProgress:f,setPromptSuggestions:h}}function Fn(e){const t=[],n=[];for(const r of e)r.type==="text"?t.push(r.text):r.type==="tool_call"&&n.push({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input||"",result:r.result,progressOutput:r.progressOutput,status:r.status,interactiveType:r.interactiveType,questions:r.questions,answers:r.answers,timeoutMs:r.timeoutMs,hooks:r.hooks,startedAt:r.startedAt,completedAt:r.completedAt,approvalStartedAt:r.approvalStartedAt,approvalRemainingMs:r.approvalRemainingMs,approvalParked:r.approvalParked,approvalTitle:r.approvalTitle,approvalDisplayName:r.approvalDisplayName,approvalDescription:r.approvalDescription,approvalBlockedPath:r.approvalBlockedPath,approvalDecisionReason:r.approvalDecisionReason,approvalHasSuggestions:r.approvalHasSuggestions,approvalAlwaysAllowScope:r.approvalAlwaysAllowScope});return{content:t.join(`
33
+ `),toolCalls:n}}function lt(e){const t=e.parts?[...e.parts]:[];if(t.length===0&&(e.content&&t.push({type:"text",text:e.content}),e.toolCalls))for(const r of e.toolCalls)t.push({type:"tool_call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,result:r.result,status:r.status,...r.questions||r.questionOutcome?{interactiveType:"question",questions:r.questions,answers:r.answers,questionOutcome:r.questionOutcome}:{},...r.approvalOutcome?{interactiveType:"approval",approvalOutcome:r.approvalOutcome,approvalResolvedAt:r.approvalResolvedAt,approvalStartedAt:r.approvalStartedAt,approvalReasonGiven:r.approvalReasonGiven}:{}});const n=Fn(t);return{id:e.id,role:e.role,content:n.content,toolCalls:n.toolCalls.length>0?n.toolCalls:void 0,parts:t,timestamp:e.timestamp||"",messageType:e.messageType,compactMetadata:e.compactMetadata,commandName:e.commandName,commandArgs:e.commandArgs}}function Jf(e,t,n){const r=new Set(e.map(d=>d.id)),o=e.filter(d=>d._streaming),a=o.find(d=>d.role==="user"),l=o.find(d=>d.role==="assistant"),c=[];let u=-1;for(let d=0;d<t.length;d++){const m=t[d];if(!r.has(m.id)){if(a&&m.role==="user"&&m.content===a.content){u=d,n(p=>p.map(f=>f.id===a.id?{...lt(m),_streaming:!1}:f));continue}if(l&&u>=0&&d===u+1&&m.role==="assistant"){const p=lt(m),f=new Set(p.parts.filter(b=>b.type==="background_task").map(b=>b.taskId)),h=l.parts.filter(b=>b.type==="background_task"&&!f.has(b.taskId)),g=h.length>0?[...p.parts,...h]:p.parts;n(b=>b.map(k=>k.id===l.id?{...p,parts:g,_streaming:!1}:k));continue}c.push(m)}}c.length>0&&n(d=>[...d,...c.map(lt)])}function Zf({sessionId:e,sid:t,transport:n,sessionCwd:r,enableMessagePolling:o,isStreaming:a,setMessages:l}){const c=Fr(),u=r.cwd,d=i.useRef(u);i.useEffect(()=>{d.current=u},[u]);const m=st({queryKey:["messages",e,u],queryFn:()=>n.getMessages(e,u??void 0),staleTime:ze.MESSAGE_STALE_TIME_MS,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>a||!o?!1:c?ze.ACTIVE_TAB_REFETCH_MS:ze.BACKGROUND_TAB_REFETCH_MS});return i.useEffect(()=>{const p=ne.getState();t&&p.updateSession(t,{historySeeded:!1}),p.getSession(e??"").status!=="streaming"&&l([])},[e,u,t,l]),i.useEffect(()=>{if(!m.data)return;const p=m.data.messages,f=ne.getState().getSession(t).historySeeded;if(!f&&p.length>0){if(a)return;t&&ne.getState().updateSession(t,{historySeeded:!0}),l(p.map(lt));return}f&&!a&&Jf(ne.getState().getSession(t).messages,p,l)},[m.data,a,t,l]),{historyQuery:m}}function bo(e,t){if(e===t)return;const{opened:n,counts:r,mergeUsage:o}=mt.getState(),a=ds("session",e),l=Date.parse(n[a]??"");Number.isNaN(l)||o([{key:ds("session",t),lastUsedAt:l,useCount:r[a]??1}])}function vn(e,t,n){e&&n.then(r=>{if(!r)return;const o=ne.getState();o.getSession(e).input.trim()===t.trim()&&o.updateSession(e,{input:""})},()=>{})}const Nt=new Map;function ep(e,t){const r=(Nt.get(e)??Promise.resolve()).then(t),o=r.then(()=>{},()=>{});return Nt.set(e,o),o.then(()=>{Nt.get(e)===o&&Nt.delete(e)}),r}const Xe=new Set;function tp({sessionId:e,input:t,status:n,transport:r,queryClient:o,selectedCwd:a,onSessionIdChangeReplace:l,transformContent:c,launchRuntime:u,agentPath:d,agentLookupPending:m,agentLookupFailed:p,launchAccount:f,takeSeedContext:h,setInput:g,setError:b,tryNativeCommand:k}){const S=i.useRef(a);i.useEffect(()=>{S.current=a},[a]);const v=i.useRef(u);i.useEffect(()=>{v.current=u},[u]);const N=i.useRef(f);i.useEffect(()=>{N.current=f},[f]);const{data:j}=On(),w=i.useRef(j==null?void 0:j.defaultRuntime);i.useEffect(()=>{w.current=j==null?void 0:j.defaultRuntime},[j==null?void 0:j.defaultRuntime]);const C=ac(e,u),E=i.useRef(C.mode);i.useEffect(()=>{E.current=C.mode},[C.mode]);const M=i.useRef(c);i.useEffect(()=>{M.current=c});const T=i.useRef(h);i.useEffect(()=>{T.current=h});const y=i.useRef(l);i.useEffect(()=>{y.current=l});const _=i.useCallback(async(W,F,D={})=>{var de,le,ge;if(!D.kickoff){const L=k(W);if(L.handled){F&&L.ran&&(L.confirmed?vn(e,W,L.confirmed):g(""));return}}const R=e,Q=D.cwd??S.current;b(null);const te=o.getQueryData(Ue.list(Q))??[],P=Xt(R),H=(P==null?void 0:P.draft)??!te.some(L=>L.id===R),J=(P==null?void 0:P.draft)===!1?!1:H||Xe.has(R);if(J&&(m||p))return;J&&Xe.add(R),D.kickoff||(mt.getState().recordOpened("session",R),Q&&mt.getState().recordOpened("agent",Q)),at.attachSession(R,Q);let Z;try{Z=!D.kickoff&&M.current?await M.current(W):W}catch(L){if(D.kickoff)throw L;b({heading:"Couldn’t send message",message:L.message||"The attachment didn’t upload. Try again.",retryable:!1});return}const ae=Ce.getState();if(H){const L=new Date().toISOString();ms(o,Q,{id:R,title:`Session ${R.slice(0,8)}`,createdAt:L,updatedAt:L,permissionMode:((de=o.getQueryData(Ue.detail(R,Q)))==null?void 0:de.permissionMode)??E.current??"default",runtime:v.current??w.current??"claude-code"})}const Y=crypto.randomUUID();D.kickoff||ae.setOptimisticUserMessage(R,{id:Y,content:W}),ae.setTriggerPending(R,!0),F&&g("");try{const L=fs(oe.getState(),Q??null),{uiState:ye,commit:re}=ps(R,L),ke={clientMessageId:Y,context:ye?{uiState:ye}:void 0};J&&(ke.create=!0),J&&v.current&&(ke.runtime=v.current),J&&d&&(ke.agentPath=d),J&&N.current&&(ke.account=N.current);const je=oe.getState().retryAccount;(je==null?void 0:je.sessionId)===R&&(ke.account=je.id,oe.getState().setRetryAccount(null));const Ae=(le=T.current)==null?void 0:le.call(T);Ae&&(ke.seedContext=Ae);const{sessionId:me}=await r.postMessage(R,Z,Q??void 0,ke);if(Xe.delete(R),P){const pe={...P,draft:!1};Jt(R,pe),Jt(me,pe)}if(re(me),me!==R){Ce.getState().migrateSessionContinuity(R,me),oe.getState().carryCanvasWritesAcross(R,me),at.attachSession(me,Q),bo(R,me),Je.getState().migrate(R,me);const pe=o.getQueryData(Ue.list(Q))??[],fe=pe.find(xe=>xe.id===R);fe&&!pe.some(xe=>xe.id===me)&&ms(o,Q,{...fe,id:me}),o.setQueryData(Ue.list(Q),xe=>xe==null?void 0:xe.filter(Re=>Re.id!==R))}(ge=y.current)==null||ge.call(y,me);const _e=me;setTimeout(()=>{var xe;const pe=it.getState().rekeys[_e]??_e,fe=Ce.getState().getSession(pe);fe.triggerPending&&((xe=fe.status)==null?void 0:xe.lifecycle)!=="streaming"&&Ce.getState().setTriggerPending(pe,!1)},Ut.TRIGGER_PENDING_TIMEOUT_MS)}catch(L){if(Ce.getState().setOptimisticUserMessage(R,null),Ce.getState().setTriggerPending(R,!1),D.kickoff)throw L;b({heading:"Couldn’t send message",message:L.message||"Couldn’t reach DorkOS. Try again.",retryable:!0})}},[e,r,o,g,b,k,d,m,p]),x=i.useCallback(async(W,F)=>{!W.trim()||n==="streaming"||await _(W.trim(),(F==null?void 0:F.clearInput)===!0,{...F!=null&&F.cwd?{cwd:F.cwd}:{}})},[n,_]),A=i.useCallback(()=>x(t,{clearInput:!0}),[t,x]),O=i.useCallback(async(W,F,D)=>{if(!e)return!1;const R=e,Q=S.current;b(null);const te=(o.getQueryData(Ue.list(Q))??[]).some(H=>H.id===R),P=Xt(R);return((P==null?void 0:P.draft)??!te)&&Xe.add(R),ep(R,async()=>{var J;let H;try{H=M.current?await M.current(W):W}catch(Z){return b({heading:D,message:Z.message||"The attachment didn’t upload. Try again.",retryable:!1}),!1}try{const Z=fs(oe.getState(),Q??null),{uiState:ae,commit:Y}=ps(R,Z),de={...ae?{uiState:ae}:{},...F==="queue"?{queued:!0}:{}},le=Object.keys(de).length>0?de:void 0,ge=((J=Xt(R))==null?void 0:J.draft)===!1?!1:Xe.has(R);if(ge&&(m||p))return!1;const{sessionId:L}=await r.postMessage(R,H,Q??void 0,{context:le,disposition:F,...ge?{create:!0,...v.current&&{runtime:v.current},...N.current&&{account:N.current},...d&&{agentPath:d}}:{}});return ge&&Xe.delete(R),P&&Jt(L,{...P,draft:!1}),Y(L),!0}catch(Z){return b({heading:D,message:Z.message||"Couldn’t reach DorkOS. Try again.",retryable:!1}),!1}})},[e,r,o,b,d,m,p]),z=i.useCallback(W=>O(W,"queue","Couldn’t queue message"),[O]),I=i.useCallback(W=>O(W,"steer","Couldn’t steer the agent"),[O]),$=i.useCallback(W=>O(W,"stage","Couldn’t add context"),[O]),q=i.useCallback(async()=>{if(!e)return{receipt:{outcome:"not-running",reason:"no-open-turn",runtime:"unknown"},cancelled:[]};try{const{receipt:W,cancelledQueued:F}=await r.interruptSession(e);return{receipt:W,cancelled:F??[]}}catch{return{receipt:{outcome:"failed",reason:"delivery-failed",runtime:"unknown"},cancelled:[]}}},[e,r]),B=i.useCallback(async W=>{b(null),await _(W,!1)},[_,b]),K=i.useCallback(async(W,F)=>{await _(W,!1,{kickoff:!0,...F?{cwd:F}:{}})},[_]),se=i.useCallback((W,F)=>{},[]);return{handleSubmit:A,submitContent:x,enqueueContent:z,steerContent:I,addContextContent:$,stop:q,retryMessage:B,submitKickoff:K,markToolCallResponded:se}}const Tt=new Set,Os=new Set,At=new Set;function np(e){var t;return e.role==="user"||e.content.trim().length>0||(((t=e.toolCalls)==null?void 0:t.length)??0)>0?!0:e.parts.some(n=>n.type==="tool_call")}function sp({sessionId:e,cwd:t,status:n,messages:r,hydrated:o,canStart:a=!0,submitKickoff:l,submitContent:c}){const u=Lt(e),d=r.length,m=r.some(np);i.useEffect(()=>{if(!e)return;if(!u){t&&d===0&&n==="idle"&&Je.getState().claimByPath(t,e);return}if(u.fired||Tt.has(e)||!a||d>0||n!=="idle")return;Tt.add(e),Je.getState().markFired(e);const p=u.kind==="first-message";(p?c:l)(u.kickoffMessage,u.path||void 0).catch(h=>{console.warn("[chat] first-turn trigger failed for newborn session",e,h),Os.has(e)?p||Je.getState().markGreetingFailed(e):(Os.add(e),Tt.delete(e),Je.getState().resetFired(e))})},[e,t,u,n,d,a,l,c]),i.useEffect(()=>{if(!(!e||!u)&&u.kind!=="first-message"&&!(!u.fired&&!Tt.has(e))&&!u.greetingFailed){if(m){At.delete(e);return}if(n==="streaming"){At.add(e);return}o&&At.has(e)&&(At.delete(e),Je.getState().markGreetingFailed(e))}},[e,u,n,m,o])}function rp(e,t){return i.useEffect(()=>{Li(),at.connectList(),e&&at.attachSession(e,t)},[e,t]),i.useEffect(()=>()=>at.releaseSession(),[]),Nr(e??"")}function op(e,t){const n=Tr(e),r=i.useRef(t);i.useEffect(()=>{r.current=t}),i.useEffect(()=>{var o;!n||!e||(bo(e,n),(o=r.current)==null||o.call(r,n))},[n,e])}const ap=500;function ip(e,t,n){const r=i.useRef(new Map),[o,a]=i.useState(null),l=t.length>0?t[0].seq:-1;i.useEffect(()=>{const p=r.current;if(!e||!n){e&&p.delete(e),a(null);return}let f=p.get(e);(!f||f.turnSeq!==l)&&(f={turnSeq:l,anchor:Date.now()},p.set(e,f)),a(f.anchor)},[e,n,l]);const c=i.useMemo(()=>{let p=0;for(const f of t)f.type==="text_delta"&&(p+=f.text.length);return p/4},[t]),[u,d]=i.useState(!1),m=i.useRef({sid:null,tokens:0});return i.useEffect(()=>{const p=m.current,f=e===p.sid&&c>p.tokens;if(m.current={sid:e,tokens:c},f&&!u&&d(!0),!f&&!u)return;const h=setTimeout(()=>d(!1),ap);return()=>clearTimeout(h)},[e,c,u]),{streamStartTime:o,estimatedTokens:c,isTextStreaming:u}}function lp(e,t,n,r){const o=i.useRef(new Map),a=i.useRef(r);i.useEffect(()=>{a.current=r}),i.useEffect(()=>{var d;if(!e)return;const l=o.current,c=n??0;let u=l.get(e);(!u||u.floor!==c)&&(u={floor:c,seen:c},l.set(e,u));for(const m of t)m.seq<=u.seen||(m.type==="todo_update"&&((d=a.current)==null||d.call(a,{action:m.action,task:m.task,tasks:m.tasks,previousId:m.previousId})),u.seen=m.seq)},[e,t,n])}function cp(e){let t=null,n=null;for(const r of e){if(r.type==="operation_progress"){t=r.state==="started"?{operation:r.operation,determinate:r.determinate,...r.percent!==void 0?{percent:r.percent}:{},...r.message!==void 0?{message:r.message}:{}}:null;continue}if(r.type==="system_status"){r.status||(n={message:r.message});continue}n=null}return{operationProgress:t,systemStatus:n}}function up(e,t){return e===null||t===null?e===t:e.operation===t.operation&&e.determinate===t.determinate&&e.percent===t.percent&&e.message===t.message}function dp(e,t){return((e==null?void 0:e.message)??null)===((t==null?void 0:t.message)??null)}function mp(e,t,n,r){const o=i.useRef(new Map),a=i.useRef(new Map),l=i.useRef(n),c=i.useRef(r);i.useEffect(()=>{l.current=n,c.current=r}),i.useEffect(()=>{if(!e)return;const{operationProgress:u,systemStatus:d}=cp(t),m=o.current.get(e)??null;up(m,u)||(l.current(u),o.current.set(e,u));const p=a.current.get(e)??null;dp(p,d)||(c.current(d),a.current.set(e,d))},[e,t])}function fp(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="capability_approval"&&r.approval.approvalId===t)return r}}function pp(e,t){const n=fp(e,t.approval.approvalId);n?n.approval=t.approval:e.push({type:"capability_approval",approval:t.approval})}function hp(e,t){const n=e.findIndex(o=>o.type==="capability_approval"&&o.approval.approvalId===t.approvalId);if(n===-1)return;if(t.outcome!=="timeout"){e.splice(n,1);return}const r=e[n];r.outcome="timeout"}function gp(e,t,n){return e.findIndex(r=>r.type==="mcp_signin"&&r.agentId===t&&r.serverName===n&&r.outcome===void 0)}function xp(e,t){const n={type:"mcp_signin",serverName:t.serverName,agentId:t.agentId,flowId:t.flowId,authorizeUrl:t.authorizeUrl,disclosure:t.disclosure},r=gp(e,t.agentId,t.serverName);r===-1?e.push(n):e[r]=n}function bp(e,t){const n=e.findIndex(o=>o.type==="mcp_signin"&&o.flowId===t.flowId);if(n===-1)return;const r=e[n];r.outcome=t.outcome,t.toolCount!==void 0&&(r.toolCount=t.toolCount)}const Is="__in_progress_turn__",yp="__optimistic_user__";function kp(e){return{id:yp,role:"user",content:e,parts:[{type:"text",text:e}],timestamp:"",_streaming:!0}}function Sp(e){return{id:`steer-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0}}function vp(e){return{id:`staged-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0,_stagedContext:!0}}function Ne(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="tool_call"&&r.toolCallId===t)return r}}function Ht(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="elicitation"&&r.interactionId===t)return r}}function jp(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="background_task"&&r.taskId===t)return r}}function Cp(e,t){yo(e);const n=e[e.length-1];n&&n.type==="text"?n.text+=t.text:e.push({type:"text",text:t.text})}function wp(e,t){const n=e[e.length-1];n&&n.type==="thinking"&&n.isStreaming?n.text+=t.text:e.push({type:"thinking",text:t.text,isStreaming:!0})}function yo(e){for(const t of e)t.type==="thinking"&&t.isStreaming&&(t.isStreaming=!1)}function Np(e,t,n){const r=Ne(e,t.toolCallId);if(r){t.input!==void 0&&(r.input=(r.input??"")+t.input);return}const o=n.get(t.toolCallId);n.delete(t.toolCallId),e.push({type:"tool_call",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input??"",status:t.status,...o&&o.length>0?{hooks:o}:{}})}function Tp(e,t){const n=Ne(e,t.toolCallId);n?(n.result=t.result,n.status=t.status,t.ui!==void 0&&(n.ui=t.ui),t.result!==void 0&&(n.progressOutput=void 0)):e.push({type:"tool_call",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input??"",result:t.result,status:t.status,...t.ui!==void 0?{ui:t.ui}:{}})}function Ap(e,t){const n=Ne(e,t.toolCallId);n&&(n.progressOutput=(n.progressOutput??"")+t.content)}function ko(e,t){const n={interactiveType:"approval",input:t.input,status:"pending",timeoutMs:t.timeoutMs,approvalStartedAt:t.startedAt,approvalRemainingMs:t.remainingMs,approvalTitle:t.title,approvalDisplayName:t.displayName,approvalDescription:t.description,approvalBlockedPath:t.blockedPath,approvalDecisionReason:t.decisionReason,approvalHasSuggestions:t.hasSuggestions,approvalAlwaysAllowScope:t.alwaysAllowScope},r=Ne(e,t.id);r?Object.assign(r,n):e.push({type:"tool_call",toolCallId:t.id,toolName:t.toolName,...n})}function So(e,t){const n=Ne(e,t.id),r={timeoutMs:t.timeoutMs,approvalStartedAt:t.startedAt,approvalRemainingMs:t.remainingMs};n?(n.interactiveType="question",n.questions=t.questions,n.status="pending",Object.assign(n,r)):e.push({type:"tool_call",toolCallId:t.id,toolName:"AskUserQuestion",input:"",status:"pending",interactiveType:"question",questions:t.questions,...r})}function vo(e,t){const n={serverName:t.serverName,message:t.message,mode:t.mode,url:t.url,elicitationId:t.elicitationId,requestedSchema:t.requestedSchema,status:"pending",startedAt:t.startedAt,remainingMs:t.remainingMs,timeoutMs:t.timeoutMs},r=Ht(e,t.id);r?Object.assign(r,n):e.push({type:"elicitation",interactionId:t.id,...n})}function Rp(e){return e==="denied"||e==="expired"||e==="cancelled"?"error":e==="answered"?"complete":"running"}function Ep(e,t){const n=Ne(e,t.id);if(n){n.status==="pending"&&(n.status=Rp(t.resolution),n.approvalRemainingMs=void 0);const o=Ui(t);o&&(n.interactiveType="approval",n.approvalOutcome=o,n.approvalResolvedAt=t.at,t.reasonGiven===!0&&(n.approvalReasonGiven=!0),n.approvalStartedAt=t.startedAt??n.approvalStartedAt);const a=qi(t);a&&(n.questionOutcome=a)}const r=Ht(e,t.id);r&&r.status==="pending"&&(r.status="submitted",r.remainingMs=void 0)}function _p(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="tool_call"&&r.hooks){const o=r.hooks.find(a=>a.hookId===t);if(o)return o}}}function Mp(e,t){for(const n of e.values()){const r=n.find(o=>o.hookId===t);if(r)return r}}function Op(e,t,n){const r=_p(e,t.hookId)??Mp(n,t.hookId);if(r){r.status=t.status,t.hookName!==void 0&&(r.hookName=t.hookName),t.stdout!==void 0&&(r.stdout=t.stdout),t.stderr!==void 0&&(r.stderr=t.stderr),t.exitCode!==void 0&&(r.exitCode=t.exitCode);return}if(!t.toolCallId)return;const o={hookId:t.hookId,hookName:t.hookName??"",hookEvent:t.hookEvent??"",status:t.status,stdout:t.stdout??"",stderr:t.stderr??"",...t.exitCode!==void 0?{exitCode:t.exitCode}:{}},a=Ne(e,t.toolCallId);a?a.hooks=[...a.hooks??[],o]:n.set(t.toolCallId,[...n.get(t.toolCallId)??[],o])}function Ip(e,t){const n=e[0];if(n&&n.type==="memory_recall"){const a=new Set(n.memories.map(c=>c.path)),l=t.memories.filter(c=>!a.has(c.path));l.length>0&&(n.memories=[...n.memories,...l]);return}const r=new Set,o=t.memories.filter(a=>r.has(a.path)?!1:(r.add(a.path),!0));e.unshift({type:"memory_recall",mode:t.mode,memories:o,isStreaming:!0})}function Pp(e,t){e.push({type:"image",attachmentId:t.attachmentId,url:t.url,mediaType:t.mediaType,size:t.size,...t.alt!==void 0?{alt:t.alt}:{}})}function Dp(e,t){e.push({type:"compact_boundary",...t.trigger!==void 0?{trigger:t.trigger}:{},...t.preTokens!==void 0?{preTokens:t.preTokens}:{},...t.postTokens!==void 0?{postTokens:t.postTokens}:{},...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.requestedBy!==void 0?{requestedBy:t.requestedBy}:{},...t.contextPercent!==void 0?{contextPercent:t.contextPercent}:{}})}function $p(e,t){e.push({type:"permission_denied",toolCallId:t.toolCallId,toolName:t.toolName,message:t.message,...t.reasonType!==void 0?{reasonType:t.reasonType}:{},...t.reason!==void 0?{reason:t.reason}:{},...t.agentId!==void 0?{agentId:t.agentId}:{}})}function Fp(e,t){t.operation!=="compaction"||t.state!=="failed"||e.push({type:"compact_boundary",failed:!0,...t.error!==void 0?{error:t.error}:{},...t.requestedBy!==void 0?{requestedBy:t.requestedBy}:{}})}function Lp(e,t){yo(e);const n=t.code!==void 0?t.details!==void 0?`[${t.code}] ${t.details}`:`[${t.code}]`:t.details;e.push({type:"error",message:t.message,...t.category!==void 0?{category:t.category}:{},...n!==void 0?{details:n}:{},...t.code!==void 0?{code:t.code}:{},...t.reason!==void 0?{reason:t.reason}:{}})}function Up(e,t){const n=jp(e,t.taskId);n?(n.status=t.status,t.description!==void 0&&(n.description=t.description),t.toolUses!==void 0&&(n.toolUses=t.toolUses),t.lastToolName!==void 0&&(n.lastToolName=t.lastToolName),t.summary!==void 0&&(n.summary=t.summary),t.ambient!==void 0&&(n.ambient=t.ambient)):e.push({type:"background_task",taskId:t.taskId,taskType:"agent",status:t.status,startedAt:0,description:t.description,toolUses:t.toolUses,lastToolName:t.lastToolName,summary:t.summary,ambient:t.ambient})}const qp={approval:"approval_required",question:"question_prompt",elicitation:"elicitation_prompt"};function zp(e){const{type:t,...n}=e;return{...n,seq:0,type:qp[t]}}function Bp(e,t){const n=Ne(e,t);return(n==null?void 0:n.interactiveType)!==void 0?!0:Ht(e,t)!==void 0}function Hp(e,t){switch(t.type){case"approval_required":ko(e,t);break;case"question_prompt":So(e,t);break;case"elicitation_prompt":vo(e,t);break}}function Wp(e,t,n){const r=Ne(e,t.id);if(r){!n&&r.result===void 0&&(r.status="pending"),r.approvalStartedAt=t.startedAt,r.approvalRemainingMs=t.remainingMs,t.timeoutMs!==void 0&&(r.timeoutMs=t.timeoutMs),r.approvalParked=t.parked===!0?!0:void 0;return}const o=Ht(e,t.id);o&&(o.startedAt=t.startedAt,o.remainingMs=t.remainingMs,t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs))}function Gp(e,t,n){for(const r of t){if(Bp(e,r.id)){Wp(e,r,n.has(r.id));continue}Hp(e,zp(r)),Kp(e,r)}}function Kp(e,t){if(t.parked!==!0)return;const n=Ne(e,t.id);n&&(n.approvalParked=!0)}function Qp(e){const t=new Set;for(const n of e)n.type==="interaction_resolved"&&t.add(n.id);return t}function jn(e){const t=[],n=new Map;for(const r of e)switch(r.type){case"text_delta":Cp(t,r);break;case"thinking_delta":wp(t,r);break;case"tool_call":Np(t,r,n);break;case"tool_result":Tp(t,r);break;case"tool_progress":Ap(t,r);break;case"approval_required":ko(t,r);break;case"question_prompt":So(t,r);break;case"elicitation_prompt":vo(t,r);break;case"capability_approval_required":pp(t,r);break;case"capability_approval_resolved":hp(t,r);break;case"mcp_signin_required":xp(t,r);break;case"mcp_signin_resolved":bp(t,r);break;case"interaction_resolved":Ep(t,r);break;case"subagent_update":Up(t,r);break;case"hook_update":Op(t,r,n);break;case"memory_recall":Ip(t,r);break;case"image_attachment":Pp(t,r);break;case"compact_boundary":Dp(t,r);break;case"permission_denied":$p(t,r);break;case"model_substituted":t.push({type:"model_substituted",from:r.from,fromName:r.fromName,to:r.to,toName:r.toName,reason:r.reason});break;case"operation_progress":Fp(t,r);break;case"error":Lp(t,r);break}return t}function Ps(e,t){if(e.length===0)return null;const n=Fn(e);return{id:t,role:"assistant",content:n.content,toolCalls:n.toolCalls.length>0?n.toolCalls:[],parts:e,timestamp:"",_streaming:!0}}function Vp(e,t){const n=[];let r=[],o=0;for(const c of e){if(c.type!=="turn_input"&&c.type!=="context_staged"){r.push(c);continue}const u=jn(r),d=Ps(u,`${Is}-${o}`);d&&n.push(d),o+=1,n.push(c.type==="turn_input"?Sp(c):vp(c)),r=[]}const a=jn(r);Gp(a,t,Qp(e));const l=Ps(a,Is);return l&&n.push(l),n}function Yp(e){const t=new Set;for(const n of e)for(const r of n.parts)r.type==="tool_call"&&t.add(r.toolCallId);return t}function Xp(e){return e.type==="tool_call"&&e.result===void 0&&e.answers===void 0&&e.approvalOutcome===void 0&&(e.questionOutcome===void 0||e.questionOutcome==="unresolved")}function Jp(e,t){const n=e.parts.filter(o=>o.type!=="tool_call"||!t.has(o.toolCallId)||!Xp(o));if(n.length===e.parts.length)return e;if(n.length===0)return null;const r=Fn(n);return{...e,parts:n,content:r.content,toolCalls:r.toolCalls.length>0?r.toolCalls:void 0}}function Zp(e){let t=e.length;for(;t>0&&e[t-1].role==="assistant";)t-=1;return t}function eh(e,t,n=[],r=null){const o=Vp(t,n),a=Yp(o),l=e.map(lt),c=a.size===0?l.length:Zp(l),u=[];for(const[d,m]of l.entries()){const p=d<c?m:Jp(m,a);p&&u.push(p)}return r&&u.push(kp(r.content)),u.push(...o),u}function Ds(e){const t=new Map;for(const n of e)n.type!=="tool_call"||n.approvalOutcome===void 0||t.set(n.toolCallId,{outcome:n.approvalOutcome,resolvedAt:n.approvalResolvedAt,startedAt:n.approvalStartedAt,displayName:n.approvalDisplayName,reasonGiven:n.approvalReasonGiven});return t}function th(e,t){return e.interactiveType==="approval"&&e.approvalOutcome===t.outcome&&e.approvalResolvedAt===t.resolvedAt&&e.approvalStartedAt===t.startedAt&&e.approvalReasonGiven===t.reasonGiven}function nh(e,t){return t.size===0?e:e.map(n=>{if(!n.parts)return n;let r=!1;const o=n.parts.map(a=>{if(a.type!=="tool_call")return a;const l=t.get(a.toolCallId);return!l||th(a,l)?a:(r=!0,{...a,interactiveType:"approval",approvalOutcome:l.outcome,approvalResolvedAt:l.resolvedAt,approvalStartedAt:l.startedAt,approvalReasonGiven:l.reasonGiven,...l.displayName!==void 0?{approvalDisplayName:l.displayName}:{}})});return r?{...n,parts:o}:n})}function sh({sessionId:e,transport:t,sessionCwd:n,streamState:r,queryClient:o,onStreamingDone:a}){var v;const l=n.cwd,c=i.useRef(e),u=i.useRef(l),d=i.useRef(a);i.useEffect(()=>{c.current=e,u.current=l,d.current=a});const m=i.useRef(new Map),p=i.useRef(new Map),f=i.useRef(new Map),h=i.useRef(new Map),g=i.useRef(new Map),b=((v=r.status)==null?void 0:v.lifecycle)??null,k=r.hydrationGeneration,S=r.userTurnCount;i.useEffect(()=>{var y,_,x;if(!e)return;const N=g.current.get(e);g.current.set(e,S),N!==void 0&&S!==N&&h.current.set(e,!1);const j=p.current.get(e);if(p.current.set(e,k),j!==k){m.current.set(e,b),b==="streaming"&&f.current.set(e,((y=Ce.getState().getSession(e).optimisticUserMessage)==null?void 0:y.id)??null);return}const w=m.current.get(e)??null;if(m.current.set(e,b),b==="streaming"&&w!=="streaming"&&f.current.set(e,((_=Ce.getState().getSession(e).optimisticUserMessage)==null?void 0:_.id)??null),!(w==="streaming"&&b!=="streaming"&&b!==null))return;const E=e,M=f.current.get(E)??null,T=Ds(jn(Ce.getState().getSession(E).inProgressTurn));t.getMessages(E,u.current??void 0).then(A=>{var B;const O=Ce.getState(),z=O.getSession(E),I=((B=z.status)==null?void 0:B.lifecycle)==="streaming",$=new Map([...Ds(z.messages.flatMap(K=>K.parts??[])),...T]);O.setHistoryMessages(E,nh(A.messages,$),{preserveInProgressTurn:I});const q=z.optimisticUserMessage;(q===null||q.id===M)&&O.setOptimisticUserMessage(E,null)}).catch(A=>{console.warn("[turn-end-reconcile] history reload failed",{sessionId:E,error:A instanceof Error?A.message:String(A)})}),o.invalidateQueries({queryKey:["tasks",E]}),h.current.get(E)!==!0&&(h.current.set(E,!0),(x=d.current)==null||x.call(d))},[e,b,k,S,t,o])}function rh(e){return e.streamReadyCursor!==null||e.messages.length>0||e.inProgressTurn.length>0||e.optimisticUserMessage!==null}function jo(e,t){const n=rh(e)?eh(e.messages,e.inProgressTurn,e.pendingInteractions,e.optimisticUserMessage):t;return Sl(n)}function oh(e,t={}){const n=be(),r=_n(),o=oe(Y=>Y.selectedCwd),a=oe(Y=>Y.enableMessagePolling),l=oe(Y=>Y.pendingAccount),c=Gr(),u=e??"",{messages:d,input:m,status:p,error:f,sessionStatus:h,systemStatus:g,operationProgress:b,promptSuggestions:k}=Ar(u),S=rp(e,c.cwd);op(e,t.onSessionIdChangeReplace);const v=zi(u),N=i.useMemo(()=>jo(S,d),[S,d]),j=ic(S,p),{streamStartTime:w,estimatedTokens:C,isTextStreaming:E}=ip(e,S.inProgressTurn,j==="streaming");lp(e,S.inProgressTurn,S.streamReadyCursor,t.onTaskEvent);const M=i.useRef(!0);i.useEffect(()=>(M.current=!0,()=>{M.current=!1}),[]);const T=i.useRef(new Map);i.useLayoutEffect(()=>{u&&(T.current.has(u)||T.current.set(u,ne.getState().getSession(u).mountGeneration))},[u]);const{setMessages:y,setInput:_,setError:x,setSystemStatus:A,setOperationProgress:O}=Xf(u,M,T);mp(e,S.inProgressTurn,O,A),u&&ne.getState().initSession(u),i.useEffect(()=>{e&&(ne.getState().initSession(e),ne.getState().touchSession(e),T.current.set(e,ne.getState().getSession(e).mountGeneration))},[e]),i.useEffect(()=>{if(e)return it.getState().clearUnseen(e),it.subscribe(Y=>{Y.unseen[e]!==void 0&&it.getState().clearUnseen(e)})},[e]);const{historyQuery:z}=Zf({sessionId:e,sid:u,transport:n,sessionCwd:c,enableMessagePolling:a,isStreaming:j==="streaming",setMessages:y}),I=Tf(o,e,{startFreshSession:t.startFreshSession,compact:t.compactIntent}),{handleSubmit:$,submitContent:q,enqueueContent:B,steerContent:K,addContextContent:se,stop:W,retryMessage:F,submitKickoff:D,markToolCallResponded:R}=tp({sessionId:e,input:m,status:j,transport:n,queryClient:r,selectedCwd:o,onSessionIdChangeReplace:t.onSessionIdChangeReplace,transformContent:t.transformContent,launchRuntime:t.launchRuntime,agentPath:t.agentPath,agentLookupPending:t.agentLookupPending,agentLookupFailed:t.agentLookupFailed,launchAccount:(l==null?void 0:l.sessionId)===u?l.id:null,takeSeedContext:t.takeSeedContext,setInput:_,setError:x,tryNativeCommand:I.tryRun}),Q=S.streamReadyCursor!==null,te=i.useCallback((Y,de)=>q(Y,de?{cwd:de}:void 0),[q]);sp({sessionId:e,cwd:o,status:j,messages:N,hydrated:Q,canStart:!t.agentLookupPending&&!t.agentLookupFailed,submitKickoff:D,submitContent:te}),sh({sessionId:e,transport:n,sessionCwd:c,streamState:S,queryClient:r,onStreamingDone:t.onStreamingDone});const P=z.isLoading&&N.length===0,H=i.useMemo(()=>N.flatMap(Y=>Y.toolCalls||[]).filter(Y=>Y.interactiveType&&Y.status==="pending"),[N]),J=H[0]||null,Z=J!==null,ae=(J==null?void 0:J.interactiveType)||null;return{messages:N,input:m,setInput:_,handleSubmit:$,submitContent:q,enqueueContent:B,steerContent:K,addContextContent:se,status:j,error:f,stop:W,retryMessage:F,isLoadingHistory:P,hydrated:Q,sessionStatus:h,streamStartTime:w,estimatedTokens:C,isTextStreaming:E,isWaitingForUser:Z,waitingType:ae,activeInteraction:J,pendingInteractions:H,markToolCallResponded:R,systemStatus:g,operationProgress:b,promptSuggestions:k,syncConnectionState:v,tryNativeCommand:I.tryRun,commandPending:I.commandPending}}function ah(e){switch(e.outcome){case"acked":return{message:"You stopped this reply.",isFailure:!1};case"closed":return{message:"Stopped. Your agent didn’t answer, so DorkOS ended it.",isFailure:!1};case"not-running":return{message:null,isFailure:!1};case"unconfirmed":return{message:`Stop requested. ${lh(e.runtime)} didn’t confirm, so it may still be working.`,isFailure:!1};case"failed":return{message:"Couldn’t stop it. Try again.",isFailure:!0}}}function ih(e,t){return!Rr(e)||e.outcome==="not-running"&&t}function lh(e){switch(e){case"claude-code":return"Claude Code";case"codex":return"Codex";case"opencode":return"OpenCode";case"doe":return"DorkOS";default:return"Your agent"}}function ch(){const e=oe(d=>d.showTaskCelebrations),[t,n]=i.useState(null),[r,o]=i.useState(null),a=i.useRef(null),l=i.useRef(!1);i.useEffect(()=>{const d=window.matchMedia("(prefers-reduced-motion: reduce)");l.current=d.matches;const m=p=>{l.current=p.matches};return d.addEventListener("change",m),()=>d.removeEventListener("change",m)},[]),Oc({timeoutMs:Ve.IDLE_TIMEOUT_MS,onIdle:i.useCallback(()=>{var d;(d=a.current)==null||d.setIdle(!0)},[]),onReturn:i.useCallback(()=>{var d,m;(d=a.current)==null||d.setIdle(!1),(m=a.current)==null||m.onUserReturn()},[])}),i.useEffect(()=>{const d=new Kc({enabled:e,miniProbability:Ve.MINI_PROBABILITY,debounceWindowMs:Ve.DEBOUNCE_WINDOW_MS,debounceThreshold:Ve.DEBOUNCE_THRESHOLD,minTasksForMajor:Ve.MIN_TASKS_FOR_MAJOR,idleTimeoutMs:Ve.IDLE_TIMEOUT_MS,onCelebrate:m=>{l.current&&m.level==="major"?n({...m,level:"mini"}):n(m),m.level==="mini"&&o(m.taskId)}});return a.current=d,()=>d.destroy()},[e]);const c=i.useCallback((d,m)=>{var p;d.action==="update"&&d.task.status==="completed"&&d.task.id&&((p=a.current)==null||p.onTaskCompleted(d.task.id,m))},[]),u=i.useCallback(()=>{n(null),o(null)},[]);return{handleTaskEvent:c,activeCelebration:t,celebratingTaskId:r,clearCelebration:u}}function an(){return{tasks:new Map,statusTimestamps:new Map,legacyCreateCount:0}}function uh(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&r!==""&&(t[n]=r);return t}function ln(e,t,n){switch(t.action){case"snapshot":{e.tasks.clear(),e.statusTimestamps.clear();const r=t.tasks??[t.task];for(const o of r)e.tasks.set(o.id,o),e.statusTimestamps.set(o.id,{status:o.status,since:n});return}case"create":{const r=t.task.id||`legacy:${e.legacyCreateCount++}`,o=r===t.task.id?t.task:{...t.task,id:r};e.tasks.set(r,o),e.statusTimestamps.set(r,{status:o.status,since:n});return}case"id_assigned":{const r=t.previousId;if(!r)return;const o=e.tasks.get(r);if(!o)return;const a=t.task.id;e.tasks.delete(r),e.tasks.set(a,{...o,id:a});const l=e.statusTimestamps.get(r);e.statusTimestamps.delete(r),e.statusTimestamps.set(a,l??{status:o.status,since:n});return}case"remove":{e.tasks.delete(t.task.id),e.statusTimestamps.delete(t.task.id);return}case"update":{if(!t.task.id)return;const r=e.tasks.get(t.task.id);if(!r)return;e.tasks.set(t.task.id,{...r,...uh(t.task)}),t.task.status&&t.task.status!==r.status&&e.statusTimestamps.set(t.task.id,{status:t.task.status,since:n});return}}}function $s(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(r=>{const o=t.get(r);return o&&o.status!=="completed"}):!1}function dh(e,t){return[...e].sort((n,r)=>{const o=n.status==="in_progress"?0:n.status==="pending"&&!$s(n,t)?1:n.status==="pending"?2:3,a=r.status==="in_progress"?0:r.status==="pending"&&!$s(r,t)?1:r.status==="pending"?2:3;return o-a})}const mh=10;let Fs=0;function Rt(e){return e==="streaming"||e==="blocked"}function fh(e,t=!1){const n=be(),o=Gr().cwd,a=oe(T=>T.enableMessagePolling),l=Fr(),[c,u]=i.useState(an()),d=Er(e??""),[m,p]=i.useState(()=>!Rt(d)),f=i.useRef([]),h=i.useRef(0),{data:g}=st({queryKey:["tasks",e,o],queryFn:async()=>{const T=++Fs;return{...await n.getTasks(e,o??void 0),fetchOrder:T}},staleTime:3e4,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>!a||t?!1:l?ze.ACTIVE_TAB_REFETCH_MS:ze.BACKGROUND_TAB_REFETCH_MS}),b=i.useRef(null);i.useEffect(()=>{const T=`${e??""}::${o??""}`,y=b.current!==T;if(b.current=T,y&&(f.current=[],h.current=0,u(an())),!g||g.fetchOrder<=h.current)return;h.current=g.fetchOrder;const _=an();g.tasks.length>0&&ln(_,{action:"snapshot",task:g.tasks[0],tasks:g.tasks},Date.now()),f.current=f.current.filter(({order:x})=>x>g.fetchOrder);for(const{event:x,receivedAt:A}of f.current)ln(_,x,A);u(_)},[g,e,o]);const k=i.useCallback(T=>{const y=Date.now();T.action==="snapshot"&&(f.current=[]),f.current.push({order:++Fs,event:T,receivedAt:y}),u(_=>{const x={tasks:new Map(_.tasks),statusTimestamps:new Map(_.statusTimestamps),legacyCreateCount:_.legacyCreateCount};return ln(x,T,y),x})},[]),S=i.useRef(!1),v=i.useCallback(()=>{p(T=>(S.current=!T,!T))},[]),N=i.useRef(Rt(d));i.useEffect(()=>{const T=Rt(d);T!==N.current&&(N.current=T,T?S.current||p(!1):p(!0))},[d]);const j=i.useRef(null);i.useEffect(()=>{const T=`${e??""}::${o??""}`;if(j.current===T)return;j.current=T;const y=Rt(d);N.current=y,S.current=!1,p(!y)},[e,o,d]);const w=Array.from(c.tasks.values()),C=dh(w,c.tasks),E=w.find(T=>T.status==="in_progress"),M=(E==null?void 0:E.activeForm)??null;return{tasks:C.slice(0,mh),taskMap:c.tasks,activeForm:M,isCollapsed:m,toggleCollapse:v,handleTaskEvent:k,statusTimestamps:c.statusTimestamps}}function ph(e){const t=i.useRef(null),[n,r]=i.useState(0),[o,a]=i.useState(!1),[l,c]=i.useState(0),u=i.useCallback(S=>{t.current=S,c(S&&"getOptionCount"in S?S.getOptionCount():0)},[]);i.useEffect(()=>{r(0),c(0),a(!1)},[e==null?void 0:e.toolCallId]);const d=i.useMemo(()=>e!=null&&e.interactiveType?{type:e.interactiveType,toolCallId:e.toolCallId}:null,[e]),m=i.useCallback(()=>{const S=t.current;S&&"approve"in S&&S.approve()},[]),p=i.useCallback(()=>{const S=t.current;S&&"alwaysAllow"in S&&S.alwaysAllow()},[]),f=i.useCallback(()=>{const S=t.current;S&&"deny"in S&&S.deny()},[]),h=i.useCallback(S=>{const v=t.current;v&&"toggleOption"in v&&(v.toggleOption(S),r(S),a(!0))},[]),g=i.useCallback(S=>{if(!o){a(!0);return}r(v=>{const N=t.current,j=N&&"getOptionCount"in N?N.getOptionCount():0;return j===0?v:S==="up"?v<=0?j-1:v-1:v>=j-1?0:v+1})},[o]),b=i.useCallback(S=>{const v=t.current;v&&"navigateQuestion"in v&&(v.navigateQuestion(S),r(0),a(!0),c(v.getOptionCount()))},[]),k=i.useCallback(()=>{const S=t.current;S&&"submit"in S&&S.submit()},[]);return Ic({activeInteraction:d,onApprove:m,onAlwaysAllow:p,onDeny:f,onToggleOption:h,onNavigateOption:g,onNavigateQuestion:b,onSubmit:k,optionCount:l,focusedIndex:n}),{handleToolRef:u,focusedOptionIndex:o?n:-1}}const cn={name:{exact:0,prefix:1,"word-boundary":2,substring:6,subsequence:8},alias:{exact:3,prefix:4,"word-boundary":5,substring:7,subsequence:9},description:{exact:10,prefix:11,"word-boundary":12,substring:13,subsequence:14}},hh={match:!1,bucket:Number.POSITIVE_INFINITY,score:0};function Ls(e){return e.startsWith("/")?e.slice(1):e}function Us(e,t){return e.bucket<t.bucket||e.bucket===t.bucket&&e.score>t.score}function gh(e,t){let n=hh;const r=Mt(e,Ls(t.fullCommand));r.match&&r.tier&&(n={match:!0,bucket:cn.name[r.tier],score:r.score});for(const o of t.aliases??[]){const a=Mt(e,Ls(o));if(!a.match||!a.tier)continue;const l={bucket:cn.alias[a.tier],score:a.score};Us(l,n)&&(n={match:!0,...l,matchedAlias:o})}if(t.description){const o=Mt(e,t.description);if(o.match&&o.tier){const a={bucket:cn.description[o.tier],score:o.score};Us(a,n)&&(n={match:!0,...a})}}return n}function Et(e,t,n){var a;const r=e.length;if(r===0)return 0;let o=(t%r+r)%r;for(let l=0;l<r;l++){if(!((a=e[o])!=null&&a.disabled))return o;o=(o+n+r)%r}return t}function xh({commands:e,input:t,cursorPos:n}){const[r,o]=i.useState(!1),[a,l]=i.useState(""),[c,u]=i.useState(-1),d=i.useMemo(()=>a?e.map(w=>({cmd:w,rank:gh(a,w)})).filter(w=>w.rank.match).sort((w,C)=>w.rank.bucket-C.rank.bucket||C.rank.score-w.rank.score).map(({cmd:w,rank:C})=>({...w,matchedAlias:C.matchedAlias})):e,[e,a]),[m,p]=i.useState(null),f=m!==null&&m.query===a&&m.open===r?m.index:Et(d,0,1),h=d[f],g=d.length===0||h!==void 0&&!h.disabled?f:Et(d,0,1),b=i.useCallback((w,C)=>{const M=w.slice(0,C).match(/(^|\s)\/([\w:-]*)$/);return M?(o(!0),l(M[2]),u((M.index??0)+M[1].length),!0):(o(!1),!1)},[]),k=i.useCallback(w=>{const C=t.slice(0,c),E=t.slice(c+1+a.length);return o(!1),C+w.fullCommand+(E.startsWith(" ")?"":" ")+E},[t,a,c]),S=i.useCallback(()=>{p({query:a,open:r,index:Et(d,g+1,1)})},[d,g,a,r]),v=i.useCallback(()=>{p({query:a,open:r,index:Et(d,g-1,-1)})},[d,g,a,r]),N=i.useCallback(()=>{const w=d[g];return w&&!w.disabled?k(w):(w||o(!1),null)},[d,g,k]),j=i.useCallback(()=>{o(!1),l("")},[]);return{showCommands:r,setShowCommands:o,commandQuery:a,selectedIndex:g,filteredCommands:d,slashTriggerPos:c,detectCommandTrigger:b,handleCommandSelect:k,handleArrowUp:v,handleArrowDown:S,handleKeyboardSelect:N,resetCommand:j}}function bh({fileEntries:e,input:t,cursorPos:n}){const[r,o]=i.useState(!1),[a,l]=i.useState(""),[c,u]=i.useState(0),[d,m]=i.useState(-1),p=i.useMemo(()=>r?a?e.map(v=>({...v,...Mt(a,v.path)})).filter(v=>v.match).sort((v,N)=>N.score-v.score).slice(0,50):e.slice(0,50).map(v=>({...v,indices:[]})):[],[e,a,r]);i.useEffect(()=>{u(0)},[a,r]),i.useEffect(()=>{p.length>0&&c>=p.length&&u(p.length-1)},[p.length,c]);const f=i.useCallback((v,N)=>{const w=v.slice(0,N).match(/(^|\s)@([\w./:-]*)$/);return w?(o(!0),l(w[2]),m((w.index??0)+w[1].length),!0):(o(!1),!1)},[]),h=i.useCallback(v=>{const N=t.slice(0,d),j=t.slice(d+1+a.length);if(v.isDirectory){const C=N+"@"+v.path+j,E=N.length+1+v.path.length;return l(v.path),u(0),{newValue:C,newCursorPos:E,keepOpen:!0}}const w=N+"@"+v.path+" "+j;return o(!1),{newValue:w,keepOpen:!1}},[t,d,a]),g=i.useCallback(()=>{u(v=>p.length===0?0:(v+1)%p.length)},[p.length]),b=i.useCallback(()=>{u(v=>p.length===0?0:(v-1+p.length)%p.length)},[p.length]),k=i.useCallback(()=>p.length>0&&c<p.length?h(p[c]):(o(!1),null),[p,c,h]),S=i.useCallback(()=>{o(!1),l("")},[]);return{showFiles:r,setShowFiles:o,fileQuery:a,fileSelectedIndex:c,filteredFiles:p,fileTriggerPos:d,detectFileTrigger:f,handleFileSelect:h,handleArrowUp:b,handleArrowDown:g,handleKeyboardSelect:k,resetFiles:S}}function yh({input:e,setInput:t,commands:n,fileEntries:r}){const[o,a]=i.useState(0),l=xh({commands:n,input:e,cursorPos:o}),c=bh({fileEntries:r,input:e,cursorPos:o}),u=i.useCallback((C,E)=>{if(c.detectFileTrigger(C,E)){l.setShowCommands(!1);return}if(l.detectCommandTrigger(C,E)){c.setShowFiles(!1);return}c.setShowFiles(!1),l.setShowCommands(!1)},[c,l]),d=i.useRef({value:e,cursor:0});i.useEffect(()=>{d.current.value=e},[e]);const m=i.useCallback(C=>{t(C),d.current={value:C,cursor:d.current.cursor||C.length},u(C,d.current.cursor)},[t,u]),p=i.useCallback(C=>{a(C),d.current={value:d.current.value,cursor:C},u(d.current.value,C)},[u]),f=i.useCallback(C=>{const E=l.handleCommandSelect(C);t(E)},[l,t]),h=i.useCallback(C=>{const E=c.handleFileSelect(C);t(E.newValue),E.newCursorPos!==void 0&&a(E.newCursorPos)},[c,t]),g=i.useCallback(()=>{c.showFiles?c.handleArrowDown():l.handleArrowDown()},[c,l]),b=i.useCallback(()=>{c.showFiles?c.handleArrowUp():l.handleArrowUp()},[c,l]),k=i.useCallback(()=>{if(c.showFiles){const C=c.handleKeyboardSelect();C&&(t(C.newValue),C.newCursorPos!==void 0&&a(C.newCursorPos))}else if(l.showCommands){const C=l.handleKeyboardSelect();C&&t(C)}},[c,l,t]),S=i.useCallback(()=>{l.setShowCommands(!1),c.setShowFiles(!1)},[l,c]),v=l.showCommands||c.showFiles,N=c.showFiles&&c.filteredFiles.length>0||l.showCommands&&l.filteredCommands.length>0,j=c.showFiles?"file-palette-listbox":l.showCommands?"command-palette-listbox":void 0,w=c.showFiles&&c.filteredFiles.length>0?`file-item-${c.fileSelectedIndex}`:l.showCommands&&l.filteredCommands.length>0?`command-item-${l.selectedIndex}`:void 0;return{commands:{show:l.showCommands,filtered:l.filteredCommands,selectedIndex:l.selectedIndex},files:{show:c.showFiles,filtered:c.filteredFiles,selectedIndex:c.fileSelectedIndex},isPaletteOpen:v,paletteHasResults:N,activeDescendantId:w,paletteListboxId:j,handleInputChange:m,handleCursorChange:p,handleArrowUp:b,handleArrowDown:g,handleKeyboardSelect:k,handleCommandSelect:f,handleFileSelect:h,dismissPalettes:S}}function kh(e,t,n,r){const o=oe(u=>u.setIsStreaming),a=oe(u=>u.setIsWaitingForUser),l=oe(u=>u.setActiveForm),c=oe(u=>u.setIsTextStreaming);i.useEffect(()=>(o(e==="streaming"),()=>o(!1)),[e,o]),i.useEffect(()=>(a(t),()=>a(!1)),[t,a]),i.useEffect(()=>(l(n),()=>l(null)),[n,l]),i.useEffect(()=>(c(r),()=>c(!1)),[r,c])}function Sh(){const e=be(),t=oe(f=>f.selectedCwd),[n,r]=i.useState([]),o=i.useCallback(f=>{const h=f.map(g=>({id:crypto.randomUUID(),file:g,status:"pending",progress:0}));r(g=>[...g,...h])},[]),a=i.useCallback(f=>{r(h=>h.filter(g=>g.id!==f))},[]),l=i.useCallback(()=>{r([])},[]),c=i.useCallback(f=>{r(h=>h.map(g=>g.id===f&&g.status==="error"?{...g,status:"pending",progress:0,error:void 0}:g))},[]),u=i.useRef(null),d=ut({meta:{suppressErrorToast:!0},mutationFn:async f=>{if(!t)throw new Error("No working directory selected");r(k=>k.map(S=>f.some(v=>v.id===S.id)?{...S,status:"uploading"}:S));const h=k=>{r(S=>S.map(v=>v.status==="uploading"?{...v,progress:k.percentage}:v))},g=new AbortController;u.current=g;const b=f.map(k=>k.file);return e.uploadFiles(b,t,h,g.signal)},onSettled:()=>{u.current=null},onSuccess:(f,h)=>{r(g=>g.map(b=>{const k=h.findIndex(S=>S.id===b.id);return k===-1?b:{...b,status:"uploaded",progress:100,result:f[k]}}))},onError:f=>{r(h=>h.map(g=>g.status==="uploading"?{...g,status:"error",error:f.message}:g))}}),m=i.useCallback(()=>{var f;(f=u.current)==null||f.abort()},[]),p=i.useCallback(async()=>{const f=n.filter(k=>k.status==="error");if(f.length>0)throw new Error(f.length===1?`${f[0].file.name} did not upload. Retry it or remove it, then send again.`:`${f.length} attachments did not upload. Retry them or remove them, then send again.`);const h=n.filter(k=>k.status==="uploaded"&&k.result).map(k=>k.result.savedPath),g=n.filter(k=>k.status==="pending");if(g.length===0)return h;const b=await d.mutateAsync(g);return[...h,...b.map(k=>k.savedPath)]},[n,d]);return{pendingFiles:n,addFiles:o,removeFile:a,retryFile:c,clearFiles:l,cancelUpload:m,uploadAndGetPaths:p,hasPendingFiles:n.length>0,hasFailedUpload:n.some(f=>f.status==="error"),isUploading:d.isPending}}const un=new Set,dn=new Set;function vh(e,t){return`${e}\0${t}`}function jh({sessionId:e,prompt:t,autoSend:n,input:r,setInput:o,messageCount:a,hydrated:l,status:c,submitBlocked:u=!1,submit:d,onSeeded:m,onConsumed:p}){const f=t!=null&&t.trim()?t:void 0,h=e&&f?vh(e,f):null;i.useEffect(()=>{if(!(!h||!f)&&!un.has(h)&&l){if(un.add(h),r.length>0||a>0){dn.add(h),p==null||p();return}o(f),m==null||m(),n||p==null||p()}},[h,f,n,r,l,a,o,m,p]),i.useEffect(()=>{!h||!f||!n||dn.has(h)||un.has(h)&&r===f&&(!l||a>0||c==="streaming"||u||(dn.add(h),p==null||p(),d()))},[h,f,n,r,l,a,c,u,d,p])}const qs=Bi-256,zs=`
34
+ …(context truncated)`,Bs={"/":"the home team room","/activity":"the activity feed","/team":"the team page","/session":"a chat session","/tasks":"the scheduled-work page","/channels":"a channel","/workspaces":"the workspaces page","/connections":"the connections page","/marketplace":"the marketplace","/feedback-requests":"the feedback requests page"};function Ch(e){const t=`/${e.split("/").filter(Boolean)[0]??""}`;return Bs[e]??Bs[t]??`the ${e} page`}function wh(e){const t=['The person opened this conversation by pressing "Ask DorkBot" in the DorkOS sidebar, so they are asking for help with DorkOS itself. Greet them with what you can see below and offer the next step; do not repeat this back to them.'];e.originPath!==null&&t.push(`They were on ${Ch(e.originPath)} (${e.originPath}).`),t.push(e.agentNames.length===1?"They have 1 agent registered.":`They have ${e.agentNames.length} agents registered.`),e.agentNames.length>0&&t.push(`Their agents: ${e.agentNames.join(", ")}.`),e.version!==null&&t.push(e.updateReady?`They are running DorkOS v${e.version}, and a newer version is ready to install.`:`They are running DorkOS v${e.version}.`),e.erroredSessionIds.length>0&&t.push(`These conversations ended in an error and may be what they want help with: ${e.erroredSessionIds.join(", ")}.`);const n=t.join(`
35
+ `);return n.length<=qs?n:n.slice(0,qs-zs.length)+zs}const Nh="dorkbot-help",_t=new Set;function Th({sessionId:e,seed:t,messageCount:n,hydrated:r,onConsumed:o}){const a=t===Nh&&e!==null,{data:l}=Hi({enabled:a}),{data:c}=_r(),u=it(Wi(f=>Object.entries(f.statuses).filter(([,h])=>h.lifecycle==="error").map(([h])=>h))),d=i.useRef({agentNames:[],version:null,updateReady:!1,erroredSessionIds:[]}),m=i.useRef({armed:a,sessionId:e,messageCount:n}),p=i.useRef(o);return i.useEffect(()=>{const f=(c==null?void 0:c.latestVersion)??null,h=(c==null?void 0:c.version)??null;d.current={agentNames:((l==null?void 0:l.agents)??[]).map(g=>g.displayName??g.name),version:h,updateReady:f!==null&&h!==null&&Gi(f,h),erroredSessionIds:u}},[l,c,u]),i.useEffect(()=>{m.current={armed:a,sessionId:e,messageCount:n},p.current=o},[a,e,n,o]),i.useEffect(()=>{!a||e===null||!r||n===0||_t.has(e)||(_t.add(e),o==null||o())},[a,e,r,n,o]),i.useCallback(()=>{var h;const f=m.current;if(!(!f.armed||f.sessionId===null)&&!(f.messageCount>0)&&!_t.has(f.sessionId))return _t.add(f.sessionId),(h=p.current)==null||h.call(p),wh({...d.current,originPath:Ki()})},[])}function Ah(e,t,n,r=!1){if(e!=="error"||t||r)return!1;let o=-1;for(let l=n.length-1;l>=0;l--)if(n[l].role==="user"){o=l;break}return!n.slice(o+1).some(l=>l.parts.some(c=>c.type==="error"&&c.code!==xr))}const Rh=4e3;function Eh(e){const t=e.approvalDisplayName||nt(e.toolName,e.input??"");return e.approvalOutcome==="allowed"?`Allowed ${t}. Recorded in the conversation.`:e.approvalOutcome==="denied"?`Didn’t allow ${t}. Recorded in the conversation.`:`${t} wasn’t answered in time, so it didn’t run. Recorded in the conversation.`}function _h(e,t){const n=i.useRef(null),r=i.useRef(null),[o,a]=i.useState({text:"",nonce:0});return i.useEffect(()=>{r.current!==t&&(r.current=t,n.current=null);const l=e.filter(d=>d.type==="tool_call"&&d.approvalOutcome!==void 0);if(n.current===null){n.current=new Set(l.map(d=>d.toolCallId));return}const c=l.filter(d=>!n.current.has(d.toolCallId));if(c.length===0)return;for(const d of c)n.current.add(d.toolCallId);const u=c.length===1?Eh(c[0]):`Answered ${c.length} permission requests. Recorded in the conversation.`;a(d=>({text:u,nonce:d.nonce+1}))},[e,t]),i.useEffect(()=>{if(o.text==="")return;const l=setTimeout(()=>a(c=>({text:"",nonce:c.nonce})),Rh);return()=>clearTimeout(l)},[o]),o.text===""?"":o.nonce%2===0?o.text:`${o.text}​`}const Hs=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],Ws=5e3,Mh=1e3,Oh=1500,Ih=new Set;function Ph(e){const t=i.useRef(new Map),n=Mr({byTask:new Map,assigned:0}),[r,o]=i.useState(Ih),[,a]=i.useState(0),l=i.useMemo(()=>{const u=new Map;for(const d of e)for(const m of d.parts)m.type==="background_task"&&u.set(m.taskId,m);return u},[e]);i.useEffect(()=>{if(!Array.from(l.values()).some(m=>m.taskType==="bash"&&m.status==="running"&&Date.now()-m.startedAt<Ws))return;const d=setInterval(()=>{a(m=>m+1)},Mh);return()=>clearInterval(d)},[l]);const c=i.useRef(new Set);return i.useLayoutEffect(()=>{for(const[u,d]of l)t.current.get(u)==="running"&&d.status!=="running"&&!gs(d)&&o(p=>p.has(u)?p:new Set(p).add(u)),t.current.set(u,d.status)},[l]),i.useEffect(()=>{for(const u of r)c.current.has(u)||(c.current.add(u),setTimeout(()=>{c.current.delete(u),o(d=>{if(!d.has(u))return d;const m=new Set(d);return m.delete(u),m})},Oh))},[r]),i.useMemo(()=>{const u=Date.now(),d=[],m=n.read();let p=m.assigned;for(const[f,h]of l){const g=h.status==="running",b=r.has(f);if(!g&&!b||h.taskType==="bash"&&g&&u-h.startedAt<Ws)continue;let k=m.byTask.get(f);k===void 0&&(k=Hs[p%Hs.length],p+=1,m.byTask.set(f,k),n.write({byTask:m.byTask,assigned:p})),d.push({taskId:h.taskId,taskType:h.taskType,status:h.status,color:k,startedAt:h.startedAt,description:h.description,toolUses:h.toolUses,lastToolName:h.lastToolName,durationMs:h.durationMs,summary:h.summary,command:h.command,ambient:gs(h)})}return d},[l,r,n])}const Dh=new Set(["streaming","blocked"]);function $h(e,t){return e.length===0||e[0].waitingOn!==void 0||t&&Dh.has(t)?e:e.slice(1)}function mn(e,t,n){return`${e} ${e===1?t:n}`}const Gs={"delivery-owed":"a helper’s report","waiting-on-person":"your answer","timer-pending":"a reminder the agent set"},Fh={"timer-pending":"Switching now cancels the reminder."};function Lh(e){const{agents:t,shells:n,other:r}=e.holding,o=[t>0?mn(t,"helper","helpers"):void 0,n>0?mn(n,"command","commands"):void 0,r>0?mn(r,"background job","background jobs"):void 0].filter(d=>d!==void 0),a=o.length===0?void 0:o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.at(-1)}`,l=e.pins,c=l.includes("cwd")&&e.targetFolderName?`moves to ${e.targetFolderName}`:l.includes("agentIdentity")?"switches agents":l.includes("systemPromptAppend")?"loads new instructions":"applies new settings";return{line:`${a!==void 0?`Held for ${a}.`:e.because!==void 0&&Gs[e.because]!==void 0?`Held for ${Gs[e.because]}.`:"Held until the agent is free."} Sending it ${c}.`,switchHint:a!==void 0?`Switching now stops ${a}.`:(e.because!==void 0?Fh[e.because]:void 0)??"Switching now stops what the agent is doing."}}const Uh={"session-idle":null,unsupported:"Queued. This agent can’t take a message mid-task.","not-steerable":"Couldn’t cut in. It’s waiting in line.","not-stageable":null,"turn-owned-elsewhere":"Couldn’t cut in: something else is running it. It’s waiting in line.","pending-interaction":"Queued. The agent needs your answer first."};function qh(e){return e!=null&&e.degradedBecause?Uh[e.degradedBecause]:null}function Ks(e){return(e==null?void 0:e.code)==="QUEUED_MESSAGE_NOT_FOUND"}function zh({sessionId:e,waiting:t,onEnqueue:n}){const r=be(),o=Qi(e??""),[a,l]=i.useState(null),c=i.useMemo(()=>t.map(j=>({id:j.id,content:j.content,mine:r.clientId===void 0||j.enqueuedBy===r.clientId,notice:qh(o[j.id]),...j.waitingOn?{waiting:Lh(j.waitingOn)}:{}})),[t,o,r.clientId]),u=i.useMemo(()=>{if(a===null)return null;const j=c.findIndex(w=>w.id===a);return j===-1?null:j},[a,c]),d=i.useCallback(()=>{var j;if(e)return(j=Ce.getState().getSession(e).queuedMessages[0])==null?void 0:j.id},[e]),m=i.useCallback((j,w)=>{j().catch(C=>{Ks(C)||we.error(w)})},[]),p=i.useCallback(async j=>{const w=j.trim();return!w||!e?!1:n(w)},[e,n]),f=i.useCallback((j,w)=>{e&&m(()=>r.updateQueuedMessage(e,j,{content:w}),"Couldn’t save that change")},[e,r,m]),h=i.useCallback(j=>{l(w=>w===j?null:w),e&&m(()=>r.removeQueuedMessage(e,j),"Couldn’t take that message off the queue")},[e,r,m]),g=i.useCallback((j,w)=>{if(!e)return;const C=E=>r.updateQueuedMessage(e,j,{move:{before:E}});m(async()=>{try{await C(w)}catch(E){if(!Ks(E))throw E;const M=d();if(M===void 0||M===j)return;await C(M)}},"Couldn’t move that message")},[e,r,m,d]),b=i.useCallback(j=>c.findIndex(C=>C.id===j)<=0?!1:(l(C=>C===j?null:C),g(j,c[0].id),!0),[c,g]),k=i.useCallback(j=>{const w=c.findIndex(C=>C.id===j);w<=0||g(j,c[w-1].id)},[c,g]),S=i.useCallback(j=>{const w=c.find(C=>C.id===j);return w?(l(j),w.content):null},[c]),v=i.useCallback(()=>{l(null)},[]),N=i.useCallback(j=>{a!==null&&(f(a,j),l(null))},[a,f]);return{queue:c,editingId:a,editingIndex:u,addToQueue:p,removeFromQueue:h,sendNow:b,moveUp:k,startEditing:S,cancelEditing:v,saveEditing:N,updateQueued:f}}function Co(e,t){return e===null?null:`${e} ${t??""}`}function Bh({input:e,setInput:t,sessionId:n,selectedCwd:r,waiting:o,onEnqueue:a,onSteer:l,onStage:c,tryNativeCommand:u,chatInputRef:d}){const m=i.useRef(""),p=i.useRef(null),f=Co(n,r);i.useEffect(()=>{m.current="",p.current=null},[f]);const h=zh({sessionId:n,waiting:o,onEnqueue:a}),g=h.cancelEditing;i.useEffect(()=>{g()},[f,g]);const b=i.useCallback(()=>{const I=h.editingId;if(I===null)return;const $=e.trim();$&&(h.updateQueued(I,$),Nf($)&&we.warning("Saved as a command. It runs instead of sending."))},[e,h]),k=hs(h.editingId),S=hs(h.updateQueued);i.useEffect(()=>{const I=n;return()=>{const $=k.read();if($===null||!I)return;const q=ne.getState(),B=q.getSession(I).input.trim();B&&S.read()($,B),q.updateSession(I,{input:m.current})}},[f]);const v=i.useCallback(I=>{const $=e.trim();if(!$)return;const q=u($);if(q.handled){if(!q.ran)return;q.confirmed?vn(n,$,q.confirmed):t("");return}if(p.current===$)return;p.current=$,mt.getState().recordOpened("session",n),r&&mt.getState().recordOpened("agent",r);const B=I($);B.finally(()=>{p.current===$&&(p.current=null)}),vn(n,$,B)},[e,r,n,t,u]),N=i.useCallback(()=>v(I=>h.addToQueue(I)),[v,h]),j=i.useCallback(()=>{l&&v(l)},[v,l]),w=i.useCallback(()=>{c&&v(c)},[v,c]),C=i.useCallback(I=>{var B,K;if(h.editingId===I){(B=d.current)==null||B.focus();return}const $=h.editingId!==null;$&&b();const q=h.startEditing(I);q!==null&&($||(m.current=e),t(q),(K=d.current)==null||K.focus())},[e,h,b,t,d]),E=i.useCallback(()=>{if(h.editingId===null)return;const I=e.trim();if(!I)return;const $=u(I);if($.handled){$.ran&&(h.cancelEditing(),t(m.current));return}h.saveEditing(I),t(m.current)},[e,h,t,u]),M=i.useCallback(()=>{h.cancelEditing(),t(m.current)},[h,t]),T=i.useCallback(I=>{h.editingId===I&&t(m.current),h.removeFromQueue(I)},[h,t]),y=i.useCallback(I=>{const $=h.editingId===I;$&&b(),h.sendNow(I)&&$&&t(m.current)},[h,b,t]),_=i.useCallback(I=>{h.moveUp(I)},[h]),x=i.useCallback(I=>{var B;const $=(B=h.queue[I])==null?void 0:B.id;if($!==void 0&&$===h.editingId)return;b();const q=$===void 0?null:h.startEditing($);if(q===null){h.cancelEditing(),t(m.current);return}t(q)},[h,b,t]),A=i.useCallback(()=>{b(),h.cancelEditing(),t(m.current)},[b,h,t]),O=i.useCallback(()=>{const{editingIndex:I,queue:$}=h;if(I===null){if($.length===0)return;m.current=e,x($.length-1)}else I>0?x(I-1):A()},[x,e,A,h]),z=i.useCallback(()=>{const{editingIndex:I,queue:$}=h;I!==null&&(I<$.length-1?x(I+1):A())},[x,A,h]);return{queue:h.queue,editingId:h.editingId,editingIndex:h.editingIndex,handleQueue:N,handleSteer:j,handleStage:w,handleQueueEdit:C,handleQueueSaveEdit:E,handleQueueCancelEdit:M,handleQueueRemove:T,handleQueueSend:y,handleQueueMoveUp:_,handleQueueNavigateUp:O,handleQueueNavigateDown:z,leaveQueueForStop:A}}const Hh=5e3,Qs=3;function wo(){try{const e=Number(localStorage.getItem(Or.PLACEHOLDER_HINT_CYCLES));return Number.isFinite(e)&&e>0?e:0}catch{return 0}}function Wh(){const e=wo()+1;try{localStorage.setItem(Or.PLACEHOLDER_HINT_CYCLES,String(e))}catch{}return e}function Gh(e){const t=[...e];for(let n=t.length-1;n>0;n--){const r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}function Kh({defaultText:e,hints:t,enabled:n,intervalMs:r=Hh}){const[o]=i.useState(()=>t.length>0?Gh(t):[]),[a,l]=i.useState(()=>wo()>=Qs),[c,u]=i.useState({key:0,hintIndex:-1}),d=i.useRef(0),m=i.useRef(0),p=i.useRef(!1);return i.useEffect(()=>{if(a||!n||t.length===0){p.current&&(p.current=!1,d.current+=1,u({key:d.current,hintIndex:-1}));return}const h=setInterval(()=>{if(d.current+=1,p.current=!p.current,!p.current){u({key:d.current,hintIndex:-1});return}const g=m.current%t.length;m.current+=1,m.current%t.length===0&&Wh()>=Qs&&l(!0),u({key:d.current,hintIndex:g})},r);return()=>clearInterval(h)},[n,t.length,r,a]),{text:c.hintIndex>=0?o[c.hintIndex]??e:e,key:c.key}}const fn=/[.!?…:](?=\s|$)|\n/g;function Vs(e,t,n){const r=e.startsWith(t)?t.length:0,o=e.slice(0,r),a=e.slice(r);if(a.trim()==="")return{chunk:"",announced:o};if(n)return{chunk:a.trim(),announced:e};fn.lastIndex=0;let l=-1;for(let c=fn.exec(a);c!==null;c=fn.exec(a))l=c.index+c[0].length;return l===-1?{chunk:"",announced:o}:{chunk:a.slice(0,l).trim(),announced:e.slice(0,r+l)}}const Qh=1500,Vh=4e3,Yh=400;function Xh({messageId:e,text:t,isStreaming:n}){const r=i.useRef(new Map),[o,a]=i.useState({text:"",nonce:0});return i.useEffect(()=>{if(e===void 0)return;if(r.current.get(e)===void 0){if(!n)return;r.current.clear(),r.current.set(e,{announced:t.length<=Yh?"":t})}const c=r.current.get(e),{chunk:u,announced:d}=Vs(t,c.announced,!1);c.announced=d,u!==""&&a(p=>({text:u,nonce:p.nonce+1}));const m=setTimeout(()=>{const p=Vs(t,c.announced,!0);c.announced=p.announced,p.chunk!==""&&a(f=>({text:p.chunk,nonce:f.nonce+1}))},Qh);return()=>clearTimeout(m)},[e,t,n]),i.useEffect(()=>{if(o.text==="")return;const l=setTimeout(()=>a(c=>({text:"",nonce:c.nonce})),Vh);return()=>clearTimeout(l)},[o]),o.text===""?"":o.nonce%2===0?o.text:`${o.text}​`}function Jh({onAllow:e,onNotNow:t}){return s.jsxs(Vi,{"data-slot":"notification-permission-primer",gap:"none",className:"flex-row flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2",children:[s.jsx(Yi,{className:"text-muted-foreground size-4 shrink-0","aria-hidden":!0}),s.jsx("p",{className:"text-muted-foreground min-w-0 flex-1 text-xs",children:"Get notified when this needs you, even in another tab."}),s.jsxs("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto",children:[s.jsx(ie,{variant:"ghost",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:t,children:"Not now"}),s.jsx(ie,{variant:"outline",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:e,children:"Turn on notifications"})]})]})}function Zh(e){const t=vl(),{permission:n,request:r}=Xi(),{prefs:o,setPrefs:a}=Ji(),{data:l}=_r(),c=l!==void 0,[u,d]=i.useState(!1),m=Zi()||n==="unsupported";i.useEffect(()=>{if(m||!e)return;const g=setTimeout(jl,Cl);return()=>clearTimeout(g)},[m,e]);const p=i.useCallback(()=>{d(!0),r().then(()=>{a({browserPermissionPrimerDismissed:!0})})},[r,a]),f=i.useCallback(()=>{d(!0),a({browserPermissionPrimerDismissed:!0})},[a]);return{eligible:!m&&c&&t&&!u&&n==="default"&&!o.browserPermissionPrimerDismissed,allow:p,notNow:f}}function eg({text:e,indices:t,startOffset:n=0}){const r=new Set(t.map(o=>o-n));return s.jsx(s.Fragment,{children:e.split("").map((o,a)=>r.has(a)?s.jsx("span",{className:"text-foreground font-semibold",children:o},a):s.jsx("span",{children:o},a))})}function tg({filteredFiles:e,selectedIndex:t,onSelect:n}){return i.useEffect(()=>{const r=document.getElementById(`file-item-${t}`);r&&r.scrollIntoView({block:"nearest"})},[t]),s.jsx(X.div,{initial:{opacity:0,scale:.98,y:4},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.98,y:4},transition:{duration:.15,ease:[0,0,.2,1]},className:"bg-popover max-h-80 overflow-hidden rounded-lg border shadow-lg",onMouseDown:r=>r.preventDefault(),children:s.jsx("div",{id:"file-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?s.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No files found."}):e.map((r,o)=>{const a=o===t,l=r.isDirectory?el:yr;return s.jsxs("div",{id:`file-item-${o}`,role:"option","aria-selected":a,"data-selected":a,tabIndex:a?0:-1,onClick:()=>n(r),onKeyDown:c=>{c.key==="Enter"&&n(r)},className:"data-[selected=true]:bg-accent hover:bg-muted flex cursor-pointer items-start gap-2 rounded-md px-2 py-1.5 transition-colors duration-100",children:[s.jsx(l,{className:"text-muted-foreground mt-0.5 size-4 shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:"text-foreground truncate text-sm font-medium",children:s.jsx(eg,{text:r.filename,indices:r.indices,startOffset:r.directory.length})}),r.directory&&s.jsx("p",{className:"text-muted-foreground/70 truncate text-xs leading-normal",children:r.directory})]})]},r.path)})})})}function ng(e){const t=be();return st({queryKey:["files",{cwd:e??null}],queryFn:()=>t.listFiles(e),enabled:!!e,staleTime:ze.FILES_STALE_TIME_MS,gcTime:ze.FILES_GC_TIME_MS})}const No={reactions:!1,threads:!1,runWith:!0,attachments:!0,mentions:!1,streamHealth:!1,presence:!1,turnStatus:!0,asks:!0};function Ys(e){return e>=1e3?`~${(e/1e3).toFixed(1)}k tokens`:`~${Math.round(e)} tokens`}function sg(e){const{formatted:t}=$r(e.status==="streaming"?e.streamStartTime:null),n=Zs(e.permissionMode),r=i.useRef(e.status),o=i.useRef(t),a=i.useRef(e.estimatedTokens),[l,c]=i.useState(!1);return i.useEffect(()=>{e.status==="streaming"&&(o.current=t,a.current=e.estimatedTokens,r.current!=="streaming"&&c(!1))},[e.status,t,e.estimatedTokens]),i.useEffect(()=>{r.current==="streaming"&&e.status==="idle"&&a.current>0&&c(!0),r.current=e.status},[e.status]),i.useEffect(()=>{if(!l)return;const u=setTimeout(()=>c(!1),Ut.TURN_COMPLETE_DISMISS_MS);return()=>clearTimeout(u)},[l]),dc({capabilities:No,asks:e.asks??Dr,stalled:!1,presence:mc,turn:{status:e.status,isWaitingForUser:e.isWaitingForUser,waitingType:e.waitingType,operationProgress:e.operationProgress==null?null:{message:e.operationProgress.message??null,determinate:e.operationProgress.determinate,percent:e.operationProgress.percent??null},systemStatus:e.systemStatus??null,elapsed:t,activity:e.activity,tokens:Ys(e.estimatedTokens),isBypass:n,showComplete:l,lastElapsed:o.current,lastTokens:Ys(a.current)}})}function rg(e){const{sessionId:t,placeholder:n,files:r}=e,o=i.useRef(e);i.useEffect(()=>{o.current=e});const a=i.useCallback(b=>o.current.files.addFiles(b),[]),l=i.useCallback(b=>o.current.files.removeFile(b),[]),c=i.useCallback(b=>o.current.files.retryFile(b),[]),u=i.useCallback(()=>o.current.files.cancelUpload(),[]),{pendingFiles:d,hasFailedUpload:m,isUploading:p}=r,f=i.useMemo(()=>({staged:d,add:a,remove:l,retry:c,cancel:u,hasFailed:m,isUploading:p,holdsSendWhileUploading:!0}),[d,m,p,a,l,c,u]),h=i.useCallback(async b=>{await o.current.submit(b.text)},[]),g=i.useCallback(async b=>{if(!await o.current.enqueue(b.text))throw new Error("Couldn’t queue that message. Try again.")},[]);return i.useMemo(()=>({kind:"session",id:t,placeholder:n,canSend:t!=="",...t===""?{canSendReason:"Pick a conversation, or start a new one."}:{},send:h,queue:g,attachments:f}),[t,n,f,h,g])}const og={duration:.16,delay:.08,ease:[.16,1,.3,1]},ag={duration:0};function ig({sessionId:e,activeInteraction:t,pendingApprovals:n,focusedOptionIndex:r,onToolRef:o,onToolDecided:a,queueDepth:l=0,allowsDenyReason:c=!0}){const u=g=>a(t.toolCallId,g),d=De(),{answerAll:m,isAnswering:p,error:f}=tl(),h=i.useMemo(()=>n.map(g=>({sessionId:e,cwd:"",interaction:{type:"approval",id:g.toolCallId,startedAt:g.approvalStartedAt??0,remainingMs:g.timeoutMs??0,toolName:g.toolName,input:g.input??"",hasSuggestions:g.approvalHasSuggestions??!1}})),[n,e]);return s.jsxs(s.Fragment,{children:[n.length>=2&&s.jsx(nl,{className:"mb-1.5",headline:`${n.length} tools are waiting on you`,items:n.map(g=>({id:g.toolCallId,line:nt(g.toolName,g.input??"")})),onAllowAll:()=>void m(h,"allow"),onDenyAll:()=>void m(h,"deny"),isAnswering:p,error:f}),s.jsx(ue,{mode:"wait",initial:!1,children:s.jsx(X.div,{initial:d?!1:{opacity:0,y:6},animate:{opacity:1,y:0},transition:d?ag:og,children:t.interactiveType==="approval"?s.jsx(lo,{ref:o,sessionId:e,toolCallId:t.toolCallId,toolName:t.toolName,input:t.input||"",isActive:!0,onDecided:u,timeoutMs:t.timeoutMs,approvalStartedAt:t.approvalStartedAt,approvalRemainingMs:t.approvalRemainingMs,approvalParked:t.approvalParked,approvalTitle:t.approvalTitle,approvalDisplayName:t.approvalDisplayName,approvalDescription:t.approvalDescription,approvalBlockedPath:t.approvalBlockedPath,approvalDecisionReason:t.approvalDecisionReason,approvalHasSuggestions:t.approvalHasSuggestions,approvalAlwaysAllowScope:t.approvalAlwaysAllowScope,allowsDenyReason:c}):t.interactiveType==="question"&&t.questions?s.jsx(br,{ref:o,sessionId:e,toolCallId:t.toolCallId,questions:t.questions,answers:t.answers,isActive:!0,focusedOptionIndex:r,onDecided:u}):null},t.toolCallId)}),l>0&&s.jsx("p",{className:"text-muted-foreground px-1 pt-2 text-xs",children:l===1?"1 message sends once you answer.":`${l} messages send once you answer.`})]})}function lg({filteredCommands:e,selectedIndex:t,onSelect:n}){const r=i.useMemo(()=>{const o=[],a=new Map;let l=0;for(const c of e){const u=c.namespace??"built-in";a.has(u)||a.set(u,[]),a.get(u).push({cmd:c,index:l++})}for(const[c,u]of a)o.push({namespace:c,items:u});return o},[e]);return i.useEffect(()=>{const o=document.getElementById(`command-item-${t}`);o&&o.scrollIntoView({block:"nearest"})},[t]),s.jsx(X.div,{initial:{opacity:0,scale:.98,y:4},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.98,y:4},transition:{duration:.15,ease:[0,0,.2,1]},className:"bg-popover max-h-80 overflow-hidden rounded-lg border shadow-lg",onMouseDown:o=>o.preventDefault(),children:s.jsx("div",{id:"command-palette-listbox",role:"listbox",className:"max-h-72 overflow-y-auto p-1.5",children:e.length===0?s.jsx("div",{className:"text-muted-foreground px-2 py-4 text-center text-sm",children:"No commands found."}):r.map(({namespace:o,items:a},l)=>s.jsxs("div",{children:[l>0&&s.jsx("div",{className:"bg-border mx-2 my-1.5 h-px"}),s.jsx("div",{className:"text-muted-foreground/70 text-2xs px-2 pt-1.5 pb-1 font-medium tracking-wide uppercase",children:o}),a.map(({cmd:c,index:u})=>{const d=u===t,m=c.disabled===!0;return s.jsxs("div",{id:`command-item-${u}`,role:"option","aria-selected":d,"aria-disabled":m,"data-selected":d,"data-disabled":m,tabIndex:d?0:-1,onClick:()=>{m||n(c)},onKeyDown:p=>{p.key==="Enter"&&!m&&n(c)},className:m?"cursor-not-allowed rounded-md px-2 py-1.5 opacity-45":"data-[selected=true]:bg-accent hover:bg-muted cursor-pointer rounded-md px-2 py-1.5 transition-colors duration-100",children:[s.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[s.jsx("span",{className:"text-foreground shrink-0 font-mono text-[13px] font-medium",children:c.fullCommand}),c.argumentHint&&s.jsx("span",{className:"text-muted-foreground/50 shrink-0 font-mono text-xs",children:c.argumentHint}),m&&c.disabledReason?s.jsx("span",{className:"text-muted-foreground/70 text-2xs ml-auto shrink-0",children:c.disabledReason}):c.matchedAlias&&s.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto shrink-0 font-mono italic",children:["matched /",c.matchedAlias.replace(/^\//,"")]})]}),c.description&&s.jsx("p",{className:"text-muted-foreground mt-0.5 truncate text-xs leading-normal",children:c.description})]},c.fullCommand)})]},o))})})}function cg(e,t,n,r){return e!==null?`Edit queued message ${e+1} of ${n}. Press Enter to save`:t&&n>0?`Compose another (${n} queued)`:t?"Compose next. It sends when ready":r}function ug({chatInputRef:e,input:t,autocomplete:n,steerContent:r,addContextContent:o,tryNativeCommand:a,commandPending:l,agentLookupPending:c=!1,agentLookupError:u=!1,status:d,stop:m,setInput:p,sessionId:f,sessionStatus:h,waiting:g,interaction:b,sync:k}){var Fe,Le;const{active:S,pendingApprovals:v,focusedOptionIndex:N,onToolRef:j,onToolDecided:w}=b,C=d==="streaming",E=oe(ce=>ce.isTextStreaming),[M]=Ir(),T=be(),{data:y}=Pn(M),_=sl(y??null,M??""),x=y?Dn(y):void 0,{target:A}=rl(),O=(A==null?void 0:A.placeholder)??"Send a message…",z=ol(f),I=Nd(f),$=zt(f),q=qt($),B=al(f),K=((q==null?void 0:q.supportsSteer)??!1)&&(B??!0),se=(q==null?void 0:q.supportsContextStaging)??!1,W=((Fe=q==null?void 0:q.permissionModes)==null?void 0:Fe.denyReason)??!0,F=i.useCallback(async ce=>{if((A==null?void 0:A.queue)===void 0)return!1;try{return await A.queue({text:ce}),!0}catch{return!1}},[A]),D=Bh({input:t,setInput:p,sessionId:f,selectedCwd:M,waiting:g,onEnqueue:F,onSteer:r,onStage:o,tryNativeCommand:a,chatInputRef:e}),[R,Q]=i.useState(null),te=i.useRef(null),P=i.useCallback(ce=>{const G=te.current;if(te.current=null,ce.length===0)return;const ee=ce.map(he=>G&&he.id===G.id?G.content:he.content).join(`
36
+
37
+ `),Se=ne.getState().getSession(f).input.trim();p(Se?`${Se}
38
+
39
+ ${ee}`:ee)},[f,p]),[H,J]=i.useState(null),Z=H===f&&C,ae=i.useRef(null),Y=i.useCallback(()=>{ae.current=null,J(null)},[]);i.useEffect(()=>{C||Y()},[C,f,Y]);const de=i.useRef(C);i.useEffect(()=>{de.current=C},[C]);const le=D.leaveQueueForStop,ge=i.useRef(D.editingId);i.useEffect(()=>{ge.current=D.editingId},[D.editingId]);const L=i.useCallback(()=>{const ce=ge.current;if(ce!==null){const G=ne.getState().getSession(f).input.trim();G&&(te.current={id:ce,content:G}),le()}ae.current=f,J(f),m().then(G=>{P(G.cancelled),ih(G.receipt,de.current)&&Y();const ee=ah(G.receipt);ee.message!==null&&!Rr(G.receipt)&&(ee.isFailure?we.error(ee.message):we.warning(ee.message))}).catch(()=>{Y()})},[f,m,P,Y,le]),ye=i.useCallback(()=>{if(!(ae.current===f||Z)){if(g.length===0){L();return}Q({sessionId:f,queuedCount:g.length})}},[f,Z,g.length,L]),re=i.useCallback(()=>{ae.current===f||Z||(Q(null),L())},[f,Z,L]);i.useEffect(()=>{(R==null?void 0:R.sessionId)===f&&g.length===0&&Q(null)},[R,f,g.length]);const{messages:Te}=Ar(f),ke=Nr(f),je=i.useMemo(()=>jo(ke,Te),[ke,Te]),Ae=Ph(je),me=i.useCallback(async ce=>{if(f)try{await T.stopTask(f,ce)}catch(G){console.error("[chat] Failed to stop task:",G)}},[f,T]),_e=i.useCallback(()=>{f&&T.switchSessionProcess(f).catch(()=>{we.error("Couldn’t switch. Try again.")})},[f,T]),pe=i.useRef(t);i.useEffect(()=>{pe.current=t});const fe=i.useCallback(ce=>{var he;const G=pe.current,ee=G.length>0&&!/\s$/.test(G)?" ":"",Se=`${G}${ee}${ce}`;p(Se),(he=e.current)==null||he.focusAt(Se.length)},[p,e]);i.useEffect(()=>gc(fe),[fe]);const xe=!C&&D.editingIndex===null,Re=Kh({defaultText:O,hints:Yf,enabled:xe&&t===""}),$e=il(),He=i.useCallback(()=>{n.dismissPalettes(),!(A===null||!A.canSend)&&A.send({text:t})},[n,A,t]),Ee=i.useCallback(()=>{n.dismissPalettes(),D.handleQueue()},[n,D]),We=i.useCallback(()=>{n.dismissPalettes(),D.handleSteer()},[n,D]),Ge=i.useCallback(()=>{n.dismissPalettes(),D.handleStage()},[n,D]);return s.jsx(ft.Composer,{className:"chat-input-container",onPathDropped:ce=>fe(xc(ce)),inputRef:e,value:t,onChange:n.handleInputChange,onSubmit:He,head:s.jsx(ue,{children:C&&s.jsx(Uc,{color:_.color,isTextStreaming:E,edge:"top"})}),asks:S?s.jsx(ig,{sessionId:f,activeInteraction:S,pendingApprovals:v,focusedOptionIndex:N,onToolRef:j,onToolDecided:w,queueDepth:D.queue.length,allowsDenyReason:W}):null,overlays:s.jsx(s.Fragment,{children:s.jsxs(ue,{children:[n.commands.show&&s.jsx(lg,{filteredCommands:n.commands.filtered,selectedIndex:n.commands.selectedIndex,onSelect:n.handleCommandSelect}),n.files.show&&s.jsx(tg,{filteredFiles:n.files.filtered,selectedIndex:n.files.selectedIndex,onSelect:n.handleFileSelect})]})}),queue:s.jsx(ue,{children:D.queue.length>0&&s.jsx(kf,{queue:D.queue,editingId:D.editingId,onEdit:D.handleQueueEdit,onRemove:D.handleQueueRemove,onSend:D.handleQueueSend,onMoveUp:D.handleQueueMoveUp,onSwitchNow:_e,statusNote:z?"Waiting for your answer above":((Le=D.queue[0])==null?void 0:Le.waiting)!==void 0?"Sending when the agent is free":"Sending one at a time as the agent finishes"})}),aboveInput:s.jsx(xf,{tasks:Ae,onStopTask:me}),footer:s.jsx(ft.Footer,{asChild:!0,children:s.jsx(zf,{sessionId:f,sessionStatus:h,isStreaming:C,syncConnectionState:k.connectionState,agentName:x,agentColor:_.color,agentEmoji:_.emoji,agentPath:M??void 0})}),input:{isStreaming:C,commandPending:l,...c||u?{canSubmit:!1,canSubmitReason:u?"Check this folder again before you start.":"Checking this folder…"}:{},...I.canSubmit?{}:{canSubmit:!1},onStop:ye,stopPending:Z,onEscape:n.dismissPalettes,onClear:()=>{p(""),n.dismissPalettes()},isPaletteOpen:n.isPaletteOpen,paletteHasResults:n.paletteHasResults,onArrowUp:n.handleArrowUp,onArrowDown:n.handleArrowDown,onCommandSelect:n.handleKeyboardSelect,activeDescendantId:n.activeDescendantId,paletteListboxId:n.paletteListboxId,onCursorChange:n.handleCursorChange,richText:$e,editingQueueItem:D.editingIndex!==null,...D.editingIndex===null?{}:{editingPosition:D.editingIndex+1},queueDepth:D.queue.length,onQueue:Ee,...K?{onSteer:We}:{},...se?{onStage:Ge}:{},onSaveEdit:D.handleQueueSaveEdit,onCancelEdit:D.handleQueueCancelEdit,onQueueNavigateUp:D.handleQueueNavigateUp,onQueueNavigateDown:D.handleQueueNavigateDown,queueHasItems:D.queue.length>0,contextKey:Co(f,M)??void 0,placeholder:I.placeholder??cg(D.editingIndex,C,D.queue.length,O),placeholderOverlay:xe&&I.canSubmit?s.jsx(Cf,{text:Re.text,animationKey:Re.key}):null},children:s.jsx(Sf,{open:(R==null?void 0:R.sessionId)===f,onOpenChange:ce=>{ce||Q(null)},queuedCount:(R==null?void 0:R.queuedCount)??0,onConfirm:re})})}const dg=e=>{const t=e;return t.role==="user"?s.jsx(Vm,{message:t}):s.jsx(zm,{message:t})};function mg({message:e,grouping:t,author:n,sessionId:r,isNew:o=!1,isStreaming:a=!1,isLatestWidgetMessage:l=!0,isFinalMessage:c=!0,activeToolCallId:u=null,onToolRef:d,focusedOptionIndex:m=-1,onToolDecided:p,onRetry:f,onSigninComplete:h,onChooseModel:g,inputZoneToolCallId:b=null,textEffect:k,runtimeLabel:S,allowsDenyReason:v,feedPosition:N}){const j=i.useId(),w=`${j}-author`,C=`${j}-content`,E=i.useRef(null),M=t.position==="first"||t.position==="only",y=e.role==="user"&&e.messageType!=="local_command_output",_=y&&e.messageType!=="command"&&e.messageType!=="compaction"&&e.content.trim().length>0,x=e.timestamp?fc(e.timestamp):"",A=x.length>0,O=A?e.timestamp:void 0,z=i.useCallback(()=>{var I;return(I=E.current)==null?void 0:I.focus()},[]);return s.jsx(ll,{value:{sessionId:r,isStreaming:a,isLatestWidgetMessage:l,isFinalMessage:c,activeToolCallId:u,onToolRef:d,focusedOptionIndex:m,onToolDecided:p,onRetry:f,onSigninComplete:h,onChooseModel:g,inputZoneToolCallId:b,textEffect:k,runtimeLabel:S,allowsDenyReason:v},children:s.jsxs(Ye.Root,{ref:E,role:y?"user":"assistant",position:t.position,isNew:o,"data-testid":"message-item","data-role":e.role,...M?{"aria-labelledby":w}:{"aria-label":A?`${n.displayName}, ${x}`:n.displayName},"aria-describedby":C,...Sc(N),children:[s.jsx(Ye.Gutter,{author:n,at:O}),s.jsxs(Ye.Body,{children:[s.jsx(Ye.Author,{id:w,author:n,at:O}),s.jsx(Ye.Content,{id:C,children:dg(e,{rowId:e.id})}),_&&s.jsx(Ye.Actions,{runWith:{prompt:e.content,sessionId:r},onExit:z})]})]})})}const Xs="Conversation",fg=[];function pg(e){for(let t=e.length-1;t>=0;t--)if(e[t].content.includes(ul))return t;return-1}function hg({messages:e,sessionId:t,isLoadingHistory:n=!1,hydrated:r=!1,isTextStreaming:o=!1,activeToolCallId:a=null,onToolRef:l,focusedOptionIndex:c=-1,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f=null,textEffect:h,runtimeLabel:g,allowsDenyReason:b,landOnRow:k,foldFirstPrompt:S=!1}){const v=Mr(null);v.read()===null&&e.length>0&&v.write(e.length);const N=i.useMemo(()=>pg(e),[e]),j=i.useMemo(()=>S?e.findIndex(R=>R.role==="user"&&R.messageType===void 0&&!R._stagedContext):-1,[S,e]),w=Lt(t),C=oe(R=>R.selectedCwd),E=zt(t),{data:M}=Pn(C),T=i.useMemo(()=>({agent:M?{id:M.id,displayName:Dn(M),...cl(M)}:null,runtime:E}),[M,E]),y=e[e.length-1],_=(y==null?void 0:y.role)==="assistant"?y:void 0,x=Xh({messageId:_==null?void 0:_.id,text:(_==null?void 0:_.content)??"",isStreaming:_!==void 0&&o}),A=_h((y==null?void 0:y.parts)??fg,t),{lastSeenMessageId:O,unreadFromStart:z,markSeen:I,isHydrated:$}=eu(t,e),[q,B]=i.useState(()=>Date.now()),K=i.useRef(null);i.useLayoutEffect(()=>{const R=Date.now(),Q=new Date(R).toDateString();if(K.current===null){K.current=Q;return}K.current!==Q&&(K.current=Q,B(R))},[e]);const se=i.useMemo(()=>tu(e,{resolveAuthor:R=>Nl(R,T),now:q,lastSeenMessageId:O,unreadFromStart:z}),[e,T,q,O,z]),W=i.useMemo(()=>se.map(R=>R.kind==="day-divider"?{kind:"day-divider",id:R.key,label:R.label}:R.kind==="unread-divider"?{kind:"unread-divider",id:R.key}:{kind:"message",id:R.key,payload:R.message,grouping:R.grouping,author:R.author,at:R.message.timestamp}),[se]),F=i.useCallback((R,Q)=>{const te=se[Q.index];if(te.kind==="day-divider")return s.jsx(vc,{label:te.label});if(te.kind==="unread-divider")return s.jsx(jc,{});const{message:P,messageIndex:H}=te;if(P._stagedContext)return s.jsx(_u,{content:P.content});if(H===j)return s.jsx(gu,{content:P.content});const J=H===e.length-1,Z=J&&P.role==="assistant",ae=N===-1||H>=N,Y=v.read();return s.jsx(mg,{message:P,grouping:te.grouping,author:te.author,sessionId:t,isNew:Y!==null&&H>=Y,isStreaming:Z&&o,isLatestWidgetMessage:ae,isFinalMessage:J,activeToolCallId:a,onToolRef:l,focusedOptionIndex:c,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f,textEffect:h,runtimeLabel:g,allowsDenyReason:b,feedPosition:{index:H+1,total:e.length}})},[se,e.length,N,j,t,v,o,a,l,c,u,d,m,p,f,h,g,b]),D=w&&w.kind!=="first-message"&&w.fired&&!w.greetingFailed&&r?w:null;return s.jsx(ft.Timeline,{conversationId:t,label:Xs,rows:W,renderRow:F,landOn:"unread",landingReady:$,...k===void 0?{}:{landOnRow:k},onReachedBottom:I,transcriptAnnouncement:x,approvalAnnouncement:A,className:"pt-12 [--conversation-thumb-top:3rem]",loading:n?s.jsx(pc,{label:Xs,busy:!0,className:"flex h-full items-center justify-center","data-testid":"transcript-feed-loading",children:s.jsxs("div",{className:"text-muted-foreground flex items-center gap-2 text-sm",children:[s.jsx(wl,{}),"Loading conversation…"]})}):void 0,empty:s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(cu,{birthRecord:w,firstLightRecord:D})}),"data-testid":"message-list",feedTestId:"transcript-feed"})}function gg({sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:r=!1,launchSeed:o,onLaunchConsumed:a,landOnRow:l}){var Qn,Vn,Yn;const[,c]=xt(),u=_n(),d=i.useRef(null),m=i.useRef(null),p=i.useCallback(()=>{var U,ve;(ve=(U=m.current)==null?void 0:U.querySelector('[data-testid="model-config-trigger"]'))==null||ve.click()},[]),f=fh(e),h=dl(e??""),g=ch(),{play:b}=Tl(),[k]=Ir(),{data:S,isPending:v,isError:N,refetch:j}=Pn(k),{sessions:w}=Cn(),C=e!==null&&!w.some(U=>U.id===e),E=ml(e),M=Sh(),T=i.useCallback(async U=>{let ve=U;if(M.hasPendingFiles){const Ke=await M.uploadAndGetPaths(),Xn=k?Ke.map(vt=>vt.startsWith(k)?vt.slice(k.length).replace(/^\//,""):vt):Ke;Xn.length>0&&(ve=`Please read the following uploaded file(s):
40
+ ${Xn.map(Fo=>`- ${Fo}`).join(`
41
+ `)}
42
+
43
+ ${ve}`),M.clearFiles()}return ve},[M,k]),y=i.useCallback(U=>{f.handleTaskEvent(U);const ve=f.tasks.map(Ke=>Ke.id===U.task.id?{...Ke,...U.task}:Ke);g.handleTaskEvent(U,ve)},[f,g]);i.useCallback(U=>{c(U),u.invalidateQueries({queryKey:Ue.bySession(U)})},[c,u]);const _=i.useCallback(U=>{c(U,{replace:!0}),u.invalidateQueries({queryKey:Ue.bySession(U)})},[c,u]),x=i.useCallback(U=>{c(crypto.randomUUID(),{continuedFrom:U??void 0,draft:!0})},[c]),A=Cr(e??""),O=qt(A.runtime),z=A.runtime?ht(A.runtime).label:"",I=((Qn=O==null?void 0:O.permissionModes)==null?void 0:Qn.denyReason)??!0,$=i.useMemo(()=>go(O==null?void 0:O.commandIntents,z),[O,z]),q=i.useRef(null),B=i.useCallback(()=>{var U;return(U=q.current)==null?void 0:U.call(q)},[]),{messages:K,input:se,setInput:W,handleSubmit:F,submitContent:D,enqueueContent:R,steerContent:Q,addContextContent:te,status:P,error:H,stop:J,isLoadingHistory:Z,hydrated:ae,sessionStatus:Y,streamStartTime:de,estimatedTokens:le,isTextStreaming:ge,isWaitingForUser:L,waitingType:ye,activeInteraction:re,pendingInteractions:Te,markToolCallResponded:ke,systemStatus:je,operationProgress:Ae,promptSuggestions:me,syncConnectionState:_e,retryMessage:pe,tryNativeCommand:fe,commandPending:xe}=oh(e,{transformContent:T,onTaskEvent:y,onSessionIdChangeReplace:_,startFreshSession:x,compactIntent:$,launchRuntime:t,...S&&k?{agentPath:k}:{},agentLookupPending:k!==null&&v,agentLookupFailed:k!==null&&N,takeSeedContext:B,onStreamingDone:i.useCallback(()=>{b("turn-end"),u.invalidateQueries({queryKey:["commands"]})},[b,u])}),Re=i.useCallback(U=>D(U,{clearInput:!0}),[D]),{permissionMode:$e,permissionModeKnown:He}=Pr(e,Y,P==="streaming"),Ee=lc(e,A.runtime,He?$e:void 0),We=fl(U=>U.setOpen);i.useEffect(()=>{We(!1)},[e,We]);const{handleToolRef:Ge,focusedOptionIndex:Fe}=ph(re);kh(P,L,f.activeForm,ge),i.useEffect(()=>{var U;(U=d.current)==null||U.focusUnlessTouch()},[e]);const Le=i.useCallback(()=>{var U;(U=d.current)==null||U.focusUnlessTouch()},[]);jh({sessionId:e,prompt:n,autoSend:r,input:se,setInput:W,messageCount:K.length,hydrated:ae,status:P,submitBlocked:C&&k!==null&&(v||N),submit:F,onSeeded:Le,onConsumed:a});const ce=Th({sessionId:e,seed:o,messageCount:K.length,hydrated:ae,onConsumed:a});i.useEffect(()=>{q.current=ce},[ce]);const G=A.runtime?wr(A.runtime):void 0,{data:ee}=Al(k,e??void 0,A.runtime??void 0),Se=i.useMemo(()=>Rf((ee==null?void 0:ee.commands)??[],{commandIntents:O==null?void 0:O.commandIntents,runtimeLabel:z}),[ee,O,z]),{data:he}=ng(k),kt=i.useMemo(()=>he!=null&&he.files?nu(he.files):[],[he]),Wt=yh({input:se,setInput:W,commands:Se,fileEntries:kt}),Ln=i.useCallback(()=>{const U=[...K].reverse().find(ve=>ve.role==="user");U!=null&&U.content&&D(U.content)},[K,D]),Un=Lt(e??""),To=i.useCallback(()=>{const U=su(K,Un);U&&pe(U)},[K,Un,pe]),qn=P==="idle"&&me.length>0&&se.length===0,Ao=pl("chat.suggestion-chips"),Ro=Td(e??""),Eo=Ah(P,H,K,Ro),_o=i.useMemo(()=>K.some(U=>U.role==="user"),[K]),zn=i.useCallback(U=>{var ve;W(U),(ve=d.current)==null||ve.focus()},[W]),Mo=Dr,St=hl(e??""),Gt=Er(e??""),Oo=i.useMemo(()=>$h(St,Gt),[St,Gt]),Bn=(Yn=(Vn=In(e??""))==null?void 0:Vn.lastError)==null?void 0:Yn.category,Kt=lu(),Hn=i.useCallback(()=>{const U=e??"";if(Kt.claimedElsewhere(U))return!1;const ve=ou({messages:K,status:P,lastErrorCategory:Bn,queuedCount:St.length,draft:ne.getState().getSession(U).input});return ve===null?!1:(Kt.claim(U),D(ve),!0)},[K,P,Bn,St.length,e,D,Kt]),Io=S?`Message ${Dn(S)}…`:"Send a message…",Po=rg({sessionId:e??"",placeholder:Io,submit:Re,enqueue:R,files:M}),{eligible:Wn,allow:Gn,notNow:Kn}=Zh(P==="streaming"),Do=i.useMemo(()=>[{id:"prompt-suggestions",show:qn,render:()=>s.jsx(yl,{suggestions:me,onChipClick:zn})},{id:"permission-primer",show:Wn,render:()=>s.jsx(Jh,{onAllow:Gn,onNotNow:Kn})},{id:"read-only-mode",show:Ee.eligible,render:()=>s.jsx(cc,{runtimeLabel:Ee.runtimeLabel,onShown:Ee.markShown,onDismiss:Ee.dismiss})}],[qn,me,zn,Wn,Gn,Kn,Ee]),$o=sg({asks:Mo,status:P,streamStartTime:de,estimatedTokens:le,permissionMode:$e,isWaitingForUser:L??!1,waitingType:ye??"approval",operationProgress:Ae,systemStatus:je,activity:h});return s.jsx(ft.Root,{surface:"session",capabilities:No,target:Po,children:s.jsxs("div",{ref:m,"data-testid":"chat-panel","data-turn-status":P,"data-turn-lifecycle":Gt??void 0,className:"flex h-full w-full flex-col",children:[s.jsx(du,{sessionId:e}),s.jsx(pu,{startedBy:E,modes:O==null?void 0:O.permissionModes.values}),s.jsx(hg,{messages:K,sessionId:e,isLoadingHistory:Z,hydrated:ae,isTextStreaming:ge,activeToolCallId:(re==null?void 0:re.toolCallId)??null,onToolRef:Ge,focusedOptionIndex:Fe,onToolDecided:ke,onRetry:Ln,onSigninComplete:Hn,onChooseModel:p,inputZoneToolCallId:(re==null?void 0:re.toolCallId)??null,runtimeLabel:G,allowsDenyReason:I,...l===void 0?{}:{landOnRow:l},foldFirstPrompt:E!==null}),s.jsx(Kf,{terminalReason:Y==null?void 0:Y.terminalReason}),s.jsx(ft.LiveLane,{state:$o,scope:"session"}),s.jsx(Rl,{candidates:Do,ready:ae,name:"session-bottom-slot",className:"px-4 pb-2"}),P==="idle"&&Ao.map(U=>s.jsx(U.component,{},U.id)),s.jsx(xu,{celebration:g.activeCelebration,onComplete:g.clearCelebration}),s.jsx(rf,{tasks:f.tasks,taskMap:f.taskMap,activeForm:f.activeForm,isCollapsed:f.isCollapsed,onToggleCollapse:f.toggleCollapse,celebratingTaskId:g.celebratingTaskId,onCelebrationComplete:g.clearCelebration,statusTimestamps:f.statusTimestamps}),Eo&&s.jsx(Vf,{sessionId:e,onRetry:_o?Ln:void 0,onSigninComplete:Hn,onChooseModel:p}),H&&s.jsx("div",{className:"mx-4 mb-2",children:s.jsx($t,{message:H.message,heading:H.heading,subtext:H.message,onRetry:H.retryable?To:void 0})}),C&&N&&s.jsx("div",{className:"mx-4 mb-2",children:s.jsx($t,{heading:"Couldn’t check this folder",message:"DorkOS couldn’t tell if an agent owns this folder. Try again.",onRetry:()=>void j()})}),e&&s.jsx(Sd,{sessionId:e,onSend:U=>void D(U)}),s.jsx(ug,{chatInputRef:d,input:se,autocomplete:Wt,steerContent:Q,addContextContent:te,tryNativeCommand:fe,commandPending:xe,agentLookupPending:C&&k!==null&&v,agentLookupError:C&&k!==null&&N,status:P,stop:J,setInput:W,sessionId:e??"",sessionStatus:Y,waiting:Oo,interaction:{active:re,pendingApprovals:Te.filter(U=>U.interactiveType==="approval"),focusedOptionIndex:Fe,onToolRef:Ge,onToolDecided:ke},sync:{connectionState:_e}})]})})}function xg(e,t){const n=e===null||t===void 0?null:`${e}:${t}`,r=i.useRef(null),o=i.useCallback(()=>{if(!(n===null||r.current===n))return r.current=n,t===void 0?void 0:Kr(t)},[n,t]);return n===null?void 0:o}function bg(){const[e]=xt(),{runtime:t,prompt:n,send:r,seed:o,message:a}=Js(),l=gl(),c=xg(e,a),{data:u}=xl(e,{enabled:!1,select:p=>p.title}),d=Tr(e);_c(e,{canonical:d===null}),El();const m=i.useCallback(()=>{l==null||l({search:p=>({...p,prompt:void 0,send:void 0,seed:void 0}),replace:!0})},[l]);return s.jsxs(s.Fragment,{children:[s.jsx(bl,{children:u!=null&&u.trim()?u:"Session"}),s.jsx(gg,{sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:r==="1",launchSeed:o,onLaunchConsumed:m,...c===void 0?{}:{landOnRow:c}})]})}const qg=bg;export{qg as component};