dorkos 0.101.0 → 0.103.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 (208) hide show
  1. package/README.md +10 -10
  2. package/dist/bin/cli.js +2935 -1738
  3. package/dist/browser/native/package-manifest.json +1 -1
  4. package/dist/browser/source-manifest.json +1 -1
  5. package/dist/client/assets/{AboutPage-CwxCTicf.js → AboutPage-BNVLNd3q.js} +1 -1
  6. package/dist/client/assets/{ActivityRow-D0QQ0SFu.js → ActivityRow-CvjAfRBM.js} +1 -1
  7. package/dist/client/assets/AdapterIcon-wGSXBn-k.js +1 -0
  8. package/dist/client/assets/AdapterSetupWizard-CmSJ2sno.js +2 -0
  9. package/dist/client/assets/{AgentRequestCard-BLLmoAES.js → AgentRequestCard-D62XQXBM.js} +4 -4
  10. package/dist/client/assets/{AppearancePage-GqrWckTQ.js → AppearancePage-Bds0L-wm.js} +1 -1
  11. package/dist/client/assets/{AttentionSignalRow-sEhnIPBB.js → AttentionSignalRow-C6RkjCWK.js} +1 -1
  12. package/dist/client/assets/{BaseTanStackRouterDevtoolsPanel-B-iktbLX-BXjzhT_D.js → BaseTanStackRouterDevtoolsPanel-B-iktbLX-CerNarG-.js} +24 -24
  13. package/dist/client/assets/{BlintzCanvas-CXi0fvcM.js → BlintzCanvas-CUqethk_.js} +24 -24
  14. package/dist/client/assets/{CanvasCsvContent-QhDSf8Pd.js → CanvasCsvContent-DdbIUPMJ.js} +1 -1
  15. package/dist/client/assets/CanvasFileContent-CX2VNF4o.js +2 -0
  16. package/dist/client/assets/CanvasModel3dContent-OprkQsgq.js +2 -0
  17. package/dist/client/assets/{CodeMirrorDiff-BMG7DBg2.js → CodeMirrorDiff-BnMdmI0K.js} +1 -1
  18. package/dist/client/assets/{CodeMirrorEditor-BYdz0ipX.js → CodeMirrorEditor-C7T-DaVA.js} +1 -1
  19. package/dist/client/assets/ConnectionAccessLists-B3QGnSxM.js +1 -0
  20. package/dist/client/assets/ConnectionsPage-E3br6maQ.js +11 -0
  21. package/dist/client/assets/{ConventionPage-y-Zq3Klp.js → ConventionPage-vMN5qEwP.js} +3 -3
  22. package/dist/client/assets/{ExtensionPageRoute-gZKKPhaj.js → ExtensionPageRoute-DFkPAzjs.js} +2 -2
  23. package/dist/client/assets/{FloatingTanStackRouterDevtools-CqogiFob-CbKIa11X.js → FloatingTanStackRouterDevtools-CqogiFob-BP4itJWW.js} +1 -1
  24. package/dist/client/assets/HandlePage-De4D_IVs.js +1 -0
  25. package/dist/client/assets/{LexicalField-Ceoa9flp.js → LexicalField-BbUXXxTw.js} +1 -1
  26. package/dist/client/assets/{ManagesPage-Dcqdm6I8.js → ManagesPage-DsNSZHug.js} +1 -1
  27. package/dist/client/assets/Marketplace-D4zHIIak.js +36 -0
  28. package/dist/client/assets/MarketplaceSourcesView-DILS8-ca.js +1 -0
  29. package/dist/client/assets/{McpAppFrame-B1ThSf2U.js → McpAppFrame-Cl_2azg-.js} +2 -2
  30. package/dist/client/assets/McpSigninBody-TpoSImsV.js +1 -0
  31. package/dist/client/assets/{Model3dViewer-DlcQ3-LS.js → Model3dViewer-C-iyu5eV.js} +1 -1
  32. package/dist/client/assets/NamePage-C-3w8oeg.js +1 -0
  33. package/dist/client/assets/NewDirectMessageMenu-bJE7b4lX.js +1 -0
  34. package/dist/client/assets/{NotificationsPage-CQQIdLtI.js → NotificationsPage-CL23qwVw.js} +1 -1
  35. package/dist/client/assets/OperatorIdentityForm-ixaqUfIO.js +1 -0
  36. package/dist/client/assets/{PermissionsPage-TX-d7aVQ.js → PermissionsPage-D4xbxTkc.js} +1 -1
  37. package/dist/client/assets/{PersonalityPicker-C_9JVOva.js → PersonalityPicker-CTvPlN-k.js} +1 -1
  38. package/dist/client/assets/{PersonalityPopover-BoTED73t.js → PersonalityPopover-Coy0eaIg.js} +1 -1
  39. package/dist/client/assets/PhotoPage-DpEEXO3e.js +1 -0
  40. package/dist/client/assets/PreviewRefusedNotice-B2GLqLYi.js +1 -0
  41. package/dist/client/assets/{PromptSuggestionChips-B_oUtFMI.js → PromptSuggestionChips-YdKEWyNT.js} +1 -1
  42. package/dist/client/assets/RoomSurface-BwIBBvYq.js +44 -0
  43. package/dist/client/assets/{RoomsPage-zOjjpHdA.js → RoomsPage-DaEXPz65.js} +1 -1
  44. package/dist/client/assets/RunsOnPopover-tvbVPKVf.js +1 -0
  45. package/dist/client/assets/SessionsPage-CAdV_XBY.js +1 -0
  46. package/dist/client/assets/SkillsPage-B4F19LmV.js +1 -0
  47. package/dist/client/assets/{TasksPage-BZapA_v6.js → TasksPage-BXcaEx3V.js} +1 -1
  48. package/dist/client/assets/ToolsPage-BYBwPql_.js +2 -0
  49. package/dist/client/assets/{TopologyGraph-BMcPxZsA.js → TopologyGraph-CZ2Y5I2e.js} +1 -1
  50. package/dist/client/assets/TourHost-BNpDrN0O.js +1 -0
  51. package/dist/client/assets/UnlinkDialog-Zyuh5qZY.js +1 -0
  52. package/dist/client/assets/{UnreadDivider-KSqqcHKN.js → UnreadDivider-Dh67_mAz.js} +1 -1
  53. package/dist/client/assets/_shell-lcu5vkQ7.js +98 -0
  54. package/dist/client/assets/{_shell._home-Bp_p1VUv.js → _shell._home-CPV1Z64k.js} +1 -1
  55. package/dist/client/assets/_shell._home.activity-CEvkKYBD.js +1 -0
  56. package/dist/client/assets/_shell._home.index-tGnRLvY-.js +3 -0
  57. package/dist/client/assets/{_shell._home.tasks-BsBH_4tZ.js → _shell._home.tasks-CtpZNevK.js} +1 -1
  58. package/dist/client/assets/_shell._home.workspaces-D6tkWdS8.js +1 -0
  59. package/dist/client/assets/{_shell.channels-DWAHkDPV.js → _shell.channels-DbrQXIVv.js} +4 -4
  60. package/dist/client/assets/_shell.connections-C3Ho4S8R.js +6 -0
  61. package/dist/client/assets/{_shell.feedback-requests-Hjv640j9.js → _shell.feedback-requests-D9l7SJi1.js} +1 -1
  62. package/dist/client/assets/_shell.marketplace-BfY-kBJk.js +1 -0
  63. package/dist/client/assets/_shell.marketplace_.sources-B0km_EUs.js +1 -0
  64. package/dist/client/assets/_shell.session-O8MC-USm.js +54 -0
  65. package/dist/client/assets/{_shell.team-ctLQztjw.js → _shell.team-DvJK7irE.js} +4 -4
  66. package/dist/client/assets/_shell.x._extensionId-_-fII74H.js +1 -0
  67. package/dist/client/assets/_shell.x._extensionId_._-_-fII74H.js +1 -0
  68. package/dist/client/assets/agent-attention-BvnWcLpc.js +5 -0
  69. package/dist/client/assets/{agent-browser-CCN16ZOz.js → agent-browser-DsDp0cSX.js} +1 -1
  70. package/dist/client/assets/{banner-DOm9_4l-.js → banner-Cja2VfwN.js} +2 -2
  71. package/dist/client/assets/{file-exclamation-point-BKzL0QhY.js → file-exclamation-point-D8KYFYSh.js} +1 -1
  72. package/dist/client/assets/{highlighted-body-KPVGNVTW-DTxMTVdP.js → highlighted-body-KPVGNVTW-Chp5pHWq.js} +1 -1
  73. package/dist/client/assets/{hover-card-qzuFUCaR.js → hover-card-FvX18DHP.js} +1 -1
  74. package/dist/client/assets/{index-Dcs6e-U_.js → index-BFPRILKF.js} +1 -1
  75. package/dist/client/assets/{index-CtOB9fS3.js → index-BKCteC7q.js} +1 -1
  76. package/dist/client/assets/index-Bbffv0TQ.js +1247 -0
  77. package/dist/client/assets/{index-BMOfHKE0.js → index-BhatJcNc.js} +1 -1
  78. package/dist/client/assets/index-BroohPSu.js +1 -0
  79. package/dist/client/assets/{index-DT_v3O-B.js → index-Bt4vTnDj.js} +1 -1
  80. package/dist/client/assets/{index-DwzSdOh3.js → index-BwkmCRvO.js} +1 -1
  81. package/dist/client/assets/{index-CTai_TxZ.js → index-BzS1K2wS.js} +1 -1
  82. package/dist/client/assets/{index-C3XnoXTY.js → index-C6F5gzX-.js} +1 -1
  83. package/dist/client/assets/{index-BaB-skF0.js → index-CIzSi3tA.js} +3 -3
  84. package/dist/client/assets/{index-BPcwoJoz.js → index-CLCbHvV5.js} +1 -1
  85. package/dist/client/assets/{index-DA-i3I4q.js → index-CXjobHw0.js} +1 -1
  86. package/dist/client/assets/{index-DgH_dl1a.js → index-CYcJ7ENW.js} +2 -2
  87. package/dist/client/assets/{index-3lQkXKcq.js → index-CeqzGl3y.js} +1 -1
  88. package/dist/client/assets/{index-DgtF-nBt.js → index-CknNaeS2.js} +1 -1
  89. package/dist/client/assets/{index-Bk98IpMn.js → index-CtK6WJzD.js} +1 -1
  90. package/dist/client/assets/{index-C8ZMfyGc.js → index-CvxLe-_3.js} +1 -1
  91. package/dist/client/assets/{index-CF9fqPef.js → index-D24Ttd-y.js} +4 -4
  92. package/dist/client/assets/{index-CIPHHziB.js → index-D6Jn2eBq.js} +1 -1
  93. package/dist/client/assets/{index-D3DXMH4x.js → index-DDibi3-x.js} +1 -1
  94. package/dist/client/assets/{index-C7B2uRgo.js → index-DElGMXW8.js} +2 -2
  95. package/dist/client/assets/{index-CmlaXay_.js → index-DGNJkiFb.js} +1 -1
  96. package/dist/client/assets/{index-WjW-NUCp.js → index-DI2T-dXr.js} +1 -1
  97. package/dist/client/assets/{index-CLhD0Bno.js → index-DZf_utaG.js} +1 -1
  98. package/dist/client/assets/{index-CTXNRyRE.js → index-D_XtXoLp.js} +1 -1
  99. package/dist/client/assets/{index-CDTumWMC.js → index-DjdQaKwP.js} +1 -1
  100. package/dist/client/assets/index-Do18O9VZ.js +1 -0
  101. package/dist/client/assets/{index-CVl132_4.js → index-Do1vOFrm.js} +1 -1
  102. package/dist/client/assets/{index-BIMClIrX.js → index-Dv1DkyeB.js} +1 -1
  103. package/dist/client/assets/{index-IgIVF9T_.js → index-DyvLJ_Z5.js} +1 -1
  104. package/dist/client/assets/index-HgvJwMGi.js +5 -0
  105. package/dist/client/assets/{index-DR1JT9Uz.js → index-OxwtxTFo.js} +3 -3
  106. package/dist/client/assets/index-QSDTjavn.js +1 -0
  107. package/dist/client/assets/{index-DOxEmnH2.js → index-ZLdoJdwS.js} +1 -1
  108. package/dist/client/assets/index-_GlgFH88.css +1 -0
  109. package/dist/client/assets/{index-CScfHuKF.js → index-euarUu2E.js} +1 -1
  110. package/dist/client/assets/{index-B-z7hA9x.js → index-jYh6X22t.js} +1 -1
  111. package/dist/client/assets/{index-CIfwPLXd.js → index-uQ1vTS05.js} +1 -1
  112. package/dist/client/assets/{index-CejezM4U.js → index-xfBvKz-h.js} +1 -1
  113. package/dist/client/assets/{index-BW5ce4t8.js → index-znQ5q2gV.js} +1 -1
  114. package/dist/client/assets/{layers-CJHXSEKK.js → layers-8-cbYlfw.js} +1 -1
  115. package/dist/client/assets/{lightbulb-DWjxw7lb.js → lightbulb-DoB0IKly.js} +1 -1
  116. package/dist/client/assets/{mention-pill-akMU3IVs.js → mention-pill-BHC6tMG9.js} +1 -1
  117. package/dist/client/assets/{message-square-off-DEagHpQY.js → message-square-off-CEHuZJtY.js} +1 -1
  118. package/dist/client/assets/{owner-notice-CLsx0s7q.js → owner-notice-dtDSKfGs.js} +1 -1
  119. package/dist/client/assets/{page-container-W7byjRmk.js → page-container-BOrdASM1.js} +1 -1
  120. package/dist/client/assets/primer-trigger-CC-cR5zN.js +3 -0
  121. package/dist/client/assets/{radio-B8Ozjv9U.js → radio-BfZPhctR.js} +1 -1
  122. package/dist/client/assets/{room-files-source-Bsc3YA91.js → room-files-source-BHupFaLE.js} +2 -2
  123. package/dist/client/assets/{rotate-ccw-clock-CNcDcTvq.js → rotate-ccw-clock-BvzfP8lR.js} +1 -1
  124. package/dist/client/assets/{rotate-cw-xvfipJLN.js → rotate-cw-BDweizfR.js} +1 -1
  125. package/dist/client/assets/{scroll-area-C95q3ss7.js → scroll-area-Dph6w3a6.js} +1 -1
  126. package/dist/client/assets/{search-x-C6SAxw7a.js → search-x-CoFJOP2l.js} +2 -2
  127. package/dist/client/assets/{shield-x-DxOGc0dW.js → shield-x-BZ6rhiT0.js} +1 -1
  128. package/dist/client/assets/{soul-file-pg0ShYy3.js → soul-file-H8fwhgiL.js} +1 -1
  129. package/dist/client/assets/use-delete-binding-CUsepFIL.js +1 -0
  130. package/dist/client/assets/use-dev-links-DYYe0vvP.js +1 -0
  131. package/dist/client/assets/{use-external-adapter-catalog-B0gcY-k7.js → use-external-adapter-catalog-CAl3MNq-.js} +1 -1
  132. package/dist/client/assets/use-full-activity-feed-Bb7BUusp.js +1 -0
  133. package/dist/client/assets/use-is-below-desktop-CIgGSgoL.js +1 -0
  134. package/dist/client/assets/use-jump-back-in-BdLBzvDr.js +11 -0
  135. package/dist/client/assets/use-mesh-topology-wYtCBbF_.js +1 -0
  136. package/dist/client/assets/use-pending-read-9UcfnDwF.js +1 -0
  137. package/dist/client/assets/{use-personality-commit-OH7d0xl_.js → use-personality-commit-CaxUHrX5.js} +1 -1
  138. package/dist/client/assets/{use-promo-activation-BgdGasXE.js → use-promo-activation-rNaAOdoh.js} +2 -2
  139. package/dist/client/assets/use-pulse-freshness-CygG3s-S.js +1 -0
  140. package/dist/client/assets/use-room-follow-claim-BIK37Iy3.js +1 -0
  141. package/dist/client/assets/{use-roving-tab-list-Be60AWK3.js → use-roving-tab-list-DQgkKGzc.js} +1 -1
  142. package/dist/client/assets/{use-session-canvas-Bqs6IQO7.js → use-session-canvas-Dpy5BEId.js} +5 -5
  143. package/dist/client/assets/use-session-diagnostics-atu9cfgr.js +16 -0
  144. package/dist/client/assets/use-unclaimed-chats-qUI5vY5K.js +1 -0
  145. package/dist/client/index.html +2 -2
  146. package/dist/drizzle/20261008170031_session_touches.sql +5 -0
  147. package/dist/drizzle/20261009171311_chat_messages.sql +41 -0
  148. package/dist/drizzle/20261009173712_started_by_report_back.sql +1 -0
  149. package/dist/drizzle/meta/20261008170031_snapshot.json +12642 -0
  150. package/dist/drizzle/meta/20261009171311_snapshot.json +12906 -0
  151. package/dist/drizzle/meta/20261009173712_snapshot.json +12914 -0
  152. package/dist/drizzle/meta/_journal.json +21 -0
  153. package/dist/server/index.js +23608 -19236
  154. package/dist/server/index.js.map +2 -2
  155. package/package.json +6 -6
  156. package/dist/client/assets/AdapterIcon-CL-MyyKy.js +0 -1
  157. package/dist/client/assets/AdapterSetupWizard-C8HOvHLF.js +0 -2
  158. package/dist/client/assets/CanvasFileContent-ZZhdofR4.js +0 -2
  159. package/dist/client/assets/CanvasModel3dContent-DMMMZh4o.js +0 -2
  160. package/dist/client/assets/ConnectionAccessLists-PW1uzcGU.js +0 -1
  161. package/dist/client/assets/ConnectionsPage-EwitZwOE.js +0 -11
  162. package/dist/client/assets/HandlePage-CL3_n1CI.js +0 -1
  163. package/dist/client/assets/Marketplace-DsU-q1ZZ.js +0 -36
  164. package/dist/client/assets/MarketplaceSourcesView-D72YoKNR.js +0 -1
  165. package/dist/client/assets/McpSigninBody-Btg3PnYN.js +0 -1
  166. package/dist/client/assets/NamePage-Bzqj4Eob.js +0 -1
  167. package/dist/client/assets/NewDirectMessageMenu-89yeGqvy.js +0 -1
  168. package/dist/client/assets/OperatorIdentityForm-BhiB9tQp.js +0 -1
  169. package/dist/client/assets/PhotoPage-C3fMlebQ.js +0 -1
  170. package/dist/client/assets/PreviewRefusedNotice-ChCgdKWN.js +0 -1
  171. package/dist/client/assets/RoomSurface-CgtNuYhl.js +0 -39
  172. package/dist/client/assets/RunsOnPopover-JTm1cYuw.js +0 -1
  173. package/dist/client/assets/SessionsPage-D4kyvHQf.js +0 -6
  174. package/dist/client/assets/SkillsPage-KYUVzuVa.js +0 -1
  175. package/dist/client/assets/ToolsPage-CWpHMlrR.js +0 -2
  176. package/dist/client/assets/TourHost-VY1-sy1Y.js +0 -1
  177. package/dist/client/assets/UnlinkDialog-3p38G_9q.js +0 -1
  178. package/dist/client/assets/_shell-DAjwimLg.js +0 -93
  179. package/dist/client/assets/_shell._home.activity-tk-XApvX.js +0 -1
  180. package/dist/client/assets/_shell._home.index-BNVhSN0y.js +0 -3
  181. package/dist/client/assets/_shell._home.workspaces-DuXnjQh0.js +0 -1
  182. package/dist/client/assets/_shell.connections-DIm3mUHy.js +0 -6
  183. package/dist/client/assets/_shell.marketplace-DF6Y7mc0.js +0 -1
  184. package/dist/client/assets/_shell.marketplace_.sources-Do8cm7kq.js +0 -1
  185. package/dist/client/assets/_shell.session-DlN8iOl-.js +0 -43
  186. package/dist/client/assets/_shell.x._extensionId-0Q1rJtud.js +0 -1
  187. package/dist/client/assets/_shell.x._extensionId_._-0Q1rJtud.js +0 -1
  188. package/dist/client/assets/agent-attention-Dn__3LQE.js +0 -5
  189. package/dist/client/assets/hand-DLUdsiuR.js +0 -6
  190. package/dist/client/assets/index-CQWqpw_G.js +0 -1
  191. package/dist/client/assets/index-D5uYwabS.js +0 -1
  192. package/dist/client/assets/index-DFMDv6qR.js +0 -1
  193. package/dist/client/assets/index-DMYBI16t.js +0 -1252
  194. package/dist/client/assets/index-DbbZNAKk.js +0 -5
  195. package/dist/client/assets/index-Dgp1LmEk.css +0 -1
  196. package/dist/client/assets/primer-trigger-DuM9vVnV.js +0 -3
  197. package/dist/client/assets/use-delete-binding-CZVeHqn0.js +0 -1
  198. package/dist/client/assets/use-dev-links-Df2WkCic.js +0 -1
  199. package/dist/client/assets/use-full-activity-feed-SYcgdMZu.js +0 -1
  200. package/dist/client/assets/use-is-below-desktop-C5_YenEp.js +0 -1
  201. package/dist/client/assets/use-jump-back-in-DWUPb1gi.js +0 -11
  202. package/dist/client/assets/use-mesh-topology-HLzZIgis.js +0 -1
  203. package/dist/client/assets/use-pending-read-BuJknrxG.js +0 -1
  204. package/dist/client/assets/use-pulse-freshness-BlD-dM_g.js +0 -1
  205. package/dist/client/assets/use-rename-session-D3MuyK-F.js +0 -1
  206. package/dist/client/assets/use-room-follow-claim-CyjhzbRJ.js +0 -1
  207. package/dist/client/assets/use-session-diagnostics-CfKdB2iY.js +0 -16
  208. package/dist/client/assets/use-unclaimed-chats-lqMhotUB.js +0 -1
@@ -0,0 +1,54 @@
1
+ var eo=Object.defineProperty;var to=(e,t,n)=>t in e?eo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Qe=(e,t,n)=>to(e,typeof t!="symbol"?t+"":t,n);import{r as i,V as We,j as s,U as Y,be as ie,h3 as En,a5 as ge,kY as rr,w as et,ii as no,nM as so,nN as ar,ai as ro,nO as ao,a_ as oo,ab as G,nP as Nt,X as Ie,aG as tt,aV as Pe,nQ as st,dI as gt,nR as De,nS as $e,nT as zt,g5 as Fe,dE as xt,ia as io,bN as bt,x as yt,nU as co,l5 as as,lK as or,l6 as lo,C as _n,nV as uo,nW as mo,nX as fo,nY as Mn,gb as ir,mC as cr,ad as po,gd as ho,nZ as go,n_ as Bt,aC as xo,go as bo,bU as yo,bm as ko,gX as vo,n$ as ze,an as On,e8 as os,f as lr,o0 as is,dB as cs,dA as nt,o1 as So,o2 as jo,o3 as mt,o4 as Lt,ae as rt,o5 as In,a7 as ft,iX as kt,dz as Pn,bO as vt,cS as Co,cT as wo,cU as No,cV as To,cW as Ro,ey as Ao,e as ls,jd as Eo,cX as _o,B as re,je as Mo,o6 as Dn,dl as Oo,o7 as Io,o8 as Po,o9 as $n,oa as ur,ob as dr,oc as Do,od as $o,a6 as Fn,c7 as St,dx as Ln,du as Un,oe as mr,dv as Fo,of as Lo,og as fr,oh as Uo,oi as qo,aX as ct,gz as zo,hd as pr,h9 as hr,lL as pt,oj as gr,ok as Bo,ol as Ho,om as Wo,on as Go,oo as xr,aE as se,op as Ko,oq as Qo,or as Vo,os as Yo,v as br,A as Ht,ac as yr,ot as Xo,l$ as Yt,ou as kr,ov as it,iq as Jo,ow as Zo,I as ei,ox as ti,oy as Xt,dZ as ni,oz as si,oA as ri,fb as ai,oB as vr,h$ as oi,jt as ii,b0 as Sr,oC as ci,oD as li,oE as xn,oF as jr,oG as ui,oH as di,oI as Cr,oJ as mi,oK as fi,oL as pi,oM as hi,oN as us,oO as ds,oP as gi,oQ as xi,oR as ms,oS as wr,oT as bi,oU as Nr,oV as bn,oW as Tr,oX as yi,oY as ki,oZ as Rr,hh as Ar,hi as vi,o_ as Si,eJ as ji,l4 as Ci,o$ as wi,fI as Ni,fJ as Ti,fK as Ri,fL as Ai,fM as Ei,fN as _i,fO as Mi,fP as Oi,cP as Re,p0 as Ii,p1 as Er,p2 as _r,p3 as yn,p4 as Pi,p5 as fs,p6 as Di,hW as $i,hX as Fi,hY as Li,hZ as Jt,p7 as Ui,h_ as ps,i9 as qi,br as zi,ib as Bi,bu as Hi,p8 as hs,bX as Wi,fq as Mr,c0 as Or,bS as Gi,b$ as Ki,c6 as Ir,c4 as Qi,lM as qn,p9 as Vi,ak as Yi,pa as Xi,le as ee,pb as Ji,pc as Zi,a1 as ec,gc as Pr,gf as Be,fk as gs,hG as qe,pd as Zt,kC as lt,pe as we,pf as xs,pg as bs,ph as ys,pi as en,pj as Je,eD as ut,pk as tc,pl as Dr,pm as $r,pn as nc,po as sc,pp as Fr,lO as rc,pq as Lr,pr as Ve,kT as Ur,ps as ac,bq as oc,dt as qr,lN as ic,pt as cc,pu as lc,h8 as zr,pv as uc,bz as ks,ne as Br,dS as dc,h0 as mc,pw as fc,gi as pc,h5 as hc,dO as gc,px as xc,py as bc,gg as Hr,gh as zn,iI as yc,f_ as Bn,kj as kc,pz as vc,pA as Sc,pB as jc,pC as Cc,pD as wc,pE as Nc,pF as Tc,c8 as Rc,hH as Ac,lS as Ec,f1 as _c,k$ as Mc,d7 as Oc}from"./index-Bbffv0TQ.js";import{P as Ic}from"./PromptSuggestionChips-YdKEWyNT.js";import{F as Pc,f as Dc,u as $c,a as Fc,L as Lc,T as Uc,r as qc,b as zc,c as Bc,B as Hc,d as Wc}from"./primer-trigger-CC-cR5zN.js";import{E as Gc,F as Kc,e as Qc,h as Vc,f as Yc,P as Xc,g as Jc,d as Zc,q as el,j as tl,b as nl,G as sl,B as rl,H as Wr,z as al,u as ol,D as il,v as cl,t as ll,p as ul,w as dl,y as ml,o as fl,n as pl,k as hl,s as gl,M as xl,i as bl,S as yl,U as kl,A as vl,I as Sl,J as jl,K as vs,x as Cl,R as wl}from"./use-session-diagnostics-atu9cfgr.js";import{B as Nl}from"./banner-Cja2VfwN.js";import{f as kn,g as Tl,N as Gr,h as Rl,C as ht,M as Ye,d as Al}from"./index-HgvJwMGi.js";import{a as El,c as _l}from"./composer-insert-BpyATrmR.js";import{A as vn,M as Ml}from"./McpAppFrame-Cl_2azg-.js";import{u as Ol,b as Il,f as Pl,D as Dl,U as $l}from"./UnreadDivider-Dh67_mAz.js";import{S as Fl}from"./shield-x-BZ6rhiT0.js";import{u as Ll,M as Ul}from"./McpSigninBody-TpoSImsV.js";import{f as ql}from"./format-duration-BCr6uzby.js";import{J as zl,A as Bl}from"./AgentRequestCard-D62XQXBM.js";import{F as Hl,h as Wl}from"./use-session-canvas-Dpy5BEId.js";import"./use-is-below-desktop-CIgGSgoL.js";import"./layers-8-cbYlfw.js";import"./hover-card-FvX18DHP.js";import"./file-drag-GDx2qhdk.js";import"./index-xfBvKz-h.js";import"./rotate-cw-BDweizfR.js";function Gl(e){const t=Math.floor(e/1e3);if(t<3600){const a=Math.floor(t/60),o=t%60;return`${a}m ${String(o).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 Kr(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 a=Math.max(0,t-e);return{formatted:Gl(a),ms:a}}function Kl(e={}){const{timeoutMs:t=3e4,onIdle:n,onReturn:r}=e,a=i.useRef(!1),o=i.useRef(null),c=i.useCallback(()=>{a.current||(a.current=!0,n==null||n())},[n]),l=i.useCallback(()=>{a.current&&(a.current=!1,r==null||r())},[r]),u=i.useCallback(()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(c,t),l()},[t,c,l]);return i.useEffect(()=>{o.current=setTimeout(c,t);const d=["mousemove","keydown","scroll","touchstart"];d.forEach(p=>document.addEventListener(p,u,{passive:!0}));const m=()=>{document.hidden?c():u()};return document.addEventListener("visibilitychange",m),()=>{o.current&&clearTimeout(o.current),d.forEach(p=>document.removeEventListener(p,u)),document.removeEventListener("visibilitychange",m)}},[t,c,u]),{isIdle:a.current}}function Ql({activeInteraction:e,onApprove:t,onAlwaysAllow:n,onDeny:r,onToggleOption:a,onNavigateOption:o,onNavigateQuestion:c,onSubmit:l,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(),l==null||l();return}if(f.key==="ArrowUp"){f.preventDefault(),o==null||o("up");return}if(f.key==="ArrowDown"){f.preventDefault(),o==null||o("down");return}return}const x=parseInt(f.key,10);if(x>=1&&x<=9){f.preventDefault(),x-1<u&&(a==null||a(x-1));return}switch(f.key){case"ArrowUp":f.preventDefault(),o==null||o("up");break;case"ArrowDown":f.preventDefault(),o==null||o("down");break;case" ":f.preventDefault(),a==null||a(d);break;case"ArrowLeft":case"[":f.preventDefault(),c==null||c("prev");break;case"ArrowRight":case"]":f.preventDefault(),c==null||c("next");break;case"Enter":f.preventDefault(),l==null||l();break}}}}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[e,t,n,r,a,o,c,l,u,d])}function Qr(){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 Vr={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"}]]};Vr.node;const Vl=We(Vr);/**
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 Yr={name:"corner-up-left",size:24,node:[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]};Yr.node;const Yl=We(Yr);/**
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 Xr={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"}]]};Xr.node;const Xl=We(Xr);/**
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 Jr={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"}]]};Jr.node;const Jl=We(Jr);/**
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 Zr={name:"git-branch-plus",size:24,node:[["path",{d:"M6 3v12",key:"qpgusn"}],["path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"1d02ji"}],["path",{d:"M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"chk6ph"}],["path",{d:"M15 6a9 9 0 0 0-9 9",key:"or332x"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]};Zr.node;const Zl=We(Zr);/**
27
+ * @license lucide-react v1.48.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const ea={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"}]]};ea.node;const eu=We(ea);/**
32
+ * @license lucide-react v1.48.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const ta={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"}]]};ta.node;const tu=We(ta);function nu({color:e,isTextStreaming:t,fadeEdges:n=!0,edge:r="bottom"}){const a=t?1.8:2.5,o=n?"linear-gradient(to right, transparent, black 15%, black 85%, transparent)":void 0,c=r==="top"?"pointer-events-none absolute right-0 top-0 left-0":"pointer-events-none absolute right-0 bottom-0 left-0",l=r==="top"?"top":"bottom";return s.jsxs(Y.div,{"aria-hidden":!0,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.4},className:c,style:{height:n?10:0,overflow:n?"hidden":"visible",maskImage:o,WebkitMaskImage:o},children:[s.jsx("div",{className:"absolute right-0 left-0",style:{[l]:0,height:6,backgroundColor:e,opacity:.6,filter:"blur(3px)"}}),s.jsx(Y.div,{initial:{x:"-100%"},animate:{x:"433%"},transition:{x:{duration:a,repeat:1/0,ease:"linear"}},className:"absolute",style:{[l]:0,width:"30%",height:2,background:`linear-gradient(to right, transparent, ${e}, white, transparent)`,willChange:"transform"}}),s.jsx(ie,{children:t&&s.jsx(Y.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:{[l]:0,width:"8%",height:1,background:"linear-gradient(to right, transparent, white 40%, white 60%, transparent)",willChange:"transform"}})})]})}const tn={"word-boundary":3,substring:2,subsequence:1},su=new Set(["/",":","-","_","."," "]);function ru(e,t){if(t===0)return!0;const n=e[t-1];if(su.has(n))return!0;const r=e[t];return n===n.toLowerCase()&&r!==r.toLowerCase()&&r===r.toUpperCase()}function Tt(e,t){return Array.from({length:t},(n,r)=>e+r)}function Rt(e,t,n){const r=1/(1+t),a=n/e.length;return(r*.6+a*.4)*.999}function au(e,t){let n=0,r=0,a=0;const o=[];for(let c=0;c<t.length&&n<e.length;c++)t[c]===e[n]?(n++,r++,r>a&&(a=r),o.push(c)):r=0;return n===e.length?{indices:o,maxRun:a}:null}function ou(e,t){const n=t.indices[t.indices.length-1]-t.indices[0]+1,r=t.maxRun/t.indices.length,a=t.indices.length/n,o=t.indices.length/e.length;return(r*.4+a*.3+o*.3)*.999}function Dt(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+Rt(t,0,n.length),indices:Tt(0,n.length)};if(r.startsWith(n))return{match:!0,tier:"prefix",score:4+Rt(t,0,n.length),indices:Tt(0,n.length)};for(let c=1;c<=r.length-n.length;c++)if(ru(t,c)&&r.startsWith(n,c))return{match:!0,tier:"word-boundary",score:tn["word-boundary"]+Rt(t,c,n.length),indices:Tt(c,n.length)};const a=r.indexOf(n);if(a>=0)return{match:!0,tier:"substring",score:tn.substring+Rt(t,a,n.length),indices:Tt(a,n.length)};const o=au(n,r);return o?{match:!0,tier:"subsequence",score:tn.subsequence+ou(t,o),indices:o.indices}:{match:!1,tier:null,score:0,indices:[]}}function na(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,t=>t.toUpperCase())}function iu(e,t){return e.length<=t?e:e.slice(0,t)+"…"}function cu(e){return/^[/~.]/.test(e)||/\.(ts|tsx|js|jsx|json|md|py|rs|go|sh|yml|yaml|toml)$/.test(e)}function Sn(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=iu(e,t);return cu(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((a,o)=>s.jsx("div",{className:"border-border/40 border-l pl-2",children:Sn(a,80)},o)),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,a])=>s.jsxs("div",{className:"border-border/40 border-l pl-2",children:[s.jsxs("span",{className:"text-muted-foreground text-xs",children:[na(r),": "]}),typeof a=="object"&&a!==null?s.jsx("span",{className:"text-muted-foreground italic",children:"{…}"}):Sn(a,80)]},r))})}return s.jsx("span",{children:String(e)})}function sa({toolName:e,input:t,isStreaming:n=!1}){if(!t)return null;if(n){const o=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:[o,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 o=t.length>5120?t.slice(0,5120)+"…":t;return s.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}if(typeof r!="object"||r===null||Array.isArray(r)){const o=t.length>5120?t.slice(0,5120)+"…":t;return s.jsx("pre",{className:"overflow-x-auto text-xs whitespace-pre-wrap",children:o})}const a=Object.entries(r);return a.length===0?null:s.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:a.map(([o,c])=>s.jsxs("div",{className:"contents",children:[s.jsx("dt",{className:"text-muted-foreground py-0.5 font-medium whitespace-nowrap",children:na(o)}),s.jsx("dd",{className:"min-w-0 py-0.5",children:Sn(c,120)})]},o))})}class lu{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(l=>r-l<this.config.debounceWindowMs);const a=n.length,o=n.filter(l=>l.status==="completed").length;if(a>=this.config.minTasksForMajor&&o===a){this.cancelDebounce();const l={level:"major",taskId:t,timestamp:r};this.emitOrQueue(l);return}if(this.recentCompletions.length>=this.config.debounceThreshold){this.cancelDebounce(),this.debounceTimer=setTimeout(()=>{const l={level:"mini",taskId:t,timestamp:Date.now()};this.emitOrQueue(l),this.recentCompletions=[]},this.config.debounceWindowMs);return}if(Math.random()<this.config.miniProbability){const l={level:"mini",taskId:t,timestamp:r};this.emitOrQueue(l)}}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 uu={background:"radial-gradient(circle, rgba(255,215,0,0.15) 0%, transparent 70%)"};function du(e,t=40){if(e.length<=t)return e;const n=e.split("/").pop()??e,r=n.length+2,a=Math.max(6,t-r);return`${e.slice(0,a)}…/${n}`}function Wt(e){var n;const{sessions:t}=En();if(e)return(n=t.find(r=>r.id===e))==null?void 0:n.runtime}const mu=typeof window<"u"&&window.location.pathname===so;let nn=null,Ss=!mu;function fu(e){return Ss?nn===e?!0:(nn=null,!1):(Ss=!0,nn=e,!0)}function pu(e){var r;const t=ge(),n=((r=rr(e))==null?void 0:r.draft)===!0;i.useEffect(()=>{if(!e||n)return;let a=!1;const o=()=>{a||document.visibilityState!=="visible"||(a=!0,document.removeEventListener("visibilitychange",o),fu(e)||et.getState().recordOpened("session",e),t.markSessionOpened(e).catch(c=>{no(t,c)}))};if(o(),!a)return document.addEventListener("visibilitychange",o),()=>document.removeEventListener("visibilitychange",o)},[e,n,t])}function ra(){const e=ar(),t=rr(e.session);return{cwd:(t==null?void 0:t.cwd)??e.dir??null}}const hu="dorkos:chat:last-seen:";function gu(){try{const e=[];for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n!=null&&n.startsWith(hu)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}catch{}}function xu(e){let t=0;for(const n of e)n._streaming!==!0&&t++;return t}function bu(e){if(typeof e!="object"||e===null)return!1;const{userId:t,threadKind:n,threadId:r,lastReadSeq:a}=e;return typeof t=="string"&&typeof n=="string"&&typeof r=="string"&&typeof a=="number"&&Number.isInteger(a)}function yu(e,t){const n=ge(),[r,a]=i.useState(()=>({sessionId:e,lastReadSeq:null,hydrated:!1}));r.sessionId!==e&&a({sessionId:e,lastReadSeq:null,hydrated:!1});const o=i.useRef(0),c=i.useRef(null),l=i.useRef(!1),u=i.useRef(!1),d=i.useRef(e),m=i.useRef(null),p=xu(t);i.useEffect(()=>{gu();let v=!1;return d.current=e,o.current=0,c.current=null,l.current=!1,u.current=!1,(async()=>{let S=null;try{S=await n.getReadCursor("session",e)}catch{}v||(S&&(o.current=S.lastReadSeq,m.current=S.userId),a({sessionId:e,lastReadSeq:(S==null?void 0:S.lastReadSeq)??null,hydrated:!0}))})(),()=>{v=!0}},[n,e]);const f=i.useCallback(async()=>{if(!l.current){l.current=!0;try{for(;;){const v=c.current;if(v===null)break;if(c.current=null,v.sessionId!==d.current)continue;if(u.current)break;const S=o.current;o.current=Math.max(S,v.seq);try{const N=await n.setReadCursor("session",v.sessionId,v.seq);m.current=N.userId??m.current}catch{o.current=S,v.sessionId===d.current&&(u.current=!0);break}}}finally{l.current=!1}}},[n]),h=i.useCallback(()=>{!r.hydrated||u.current||p<=o.current||(c.current={sessionId:e,seq:p},f())},[r.hydrated,e,p,f]);ro("read_cursor",v=>{if(!bu(v)||v.threadKind!=="session"||v.threadId!==e)return;const S=m.current;S!==null&&v.userId!==S||v.lastReadSeq<=o.current||(o.current=v.lastReadSeq,a({sessionId:e,lastReadSeq:v.lastReadSeq,hydrated:!0}))});const g=i.useMemo(()=>t.filter(v=>v._streaming!==!0).map((v,S)=>({id:v.id,seq:S+1})),[t]),x=r.lastReadSeq,y=Ol(g,x===null?null:Math.min(x,p));return{lastSeenMessageId:y.lastSeenId,unreadFromStart:y.fromStart,markSeen:h,isHydrated:r.hydrated}}function aa(e){return`msg-${e}`}function ku(e,t){const{resolveAuthor:n,now:r,lastSeenMessageId:a,unreadFromStart:o}=t,c=e.map((l,u)=>n(l,u));return Il(e.map((l,u)=>({id:l.id,authorId:c[u].id,timestamp:l.timestamp})),{now:r,lastSeenId:a,unreadFromStart:o}).map(l=>l.kind!=="item"?l:{kind:"message",key:aa(e[l.index].id),messageIndex:l.index,message:e[l.index],grouping:l.grouping,author:c[l.index]})}function vu(e){const t=[],n=new Set;for(const r of e){const a=r.lastIndexOf("/"),o=a>=0?r.slice(0,a+1):"",c=a>=0?r.slice(a+1):r;t.push({path:r,filename:c,directory:o,isDirectory:!1});const l=r.split("/");for(let u=1;u<l.length;u++){const d=l.slice(0,u).join("/")+"/";n.has(d)||(n.add(d),t.push({path:d,filename:l[u-1]+"/",directory:u>1?l.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 oa=Symbol("no-error-part");function ju(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 a=n[r];if(a.type==="error")return a.category}}return oa}function Cu(e){const{messages:t,status:n,lastErrorCategory:r,queuedCount:a,draft:o}=e;if(o.trim().length>0||n==="streaming"||a>0)return null;let c=-1;for(let d=t.length-1;d>=0;d--)if(t[d].role==="user"){c=d;break}const l=c===-1?"":t[c].content.trim();if(!l)return null;const u=ju(t.slice(c+1));return u!==oa?u==="auth_error"?l:null:n==="error"&&r==="auth_error"?l:null}const wu="dorkos:signin-resume",Nu=1e4;function Tu(){const e=i.useRef(new Map),t=i.useRef(null);return i.useEffect(()=>{const n=ao(wu);t.current=n;const r=e.current,a=n.onMessage(o=>{r.set(o.sessionId,Date.now())});return()=>{a(),n.close(),t.current=null}},[]),i.useMemo(()=>({claimedElsewhere:n=>{const r=e.current.get(n);return r!==void 0&&Date.now()-r<Nu},claim:n=>{var r;return(r=t.current)==null?void 0:r.postMessage({sessionId:n})}}),[])}function ia(e){switch(e){case"pending":case"running":return s.jsx(Pe,{size:"xs",className:Nt({status:e})});case"complete":return s.jsx(tt,{className:G("size-(--size-icon-xs)",Nt({status:e}))});case"error":return s.jsx(Ie,{className:G("size-(--size-icon-xs)",Nt({status:e}))});case"neutral":return s.jsx(oo,{className:G("size-(--size-icon-xs)",Nt({status:e}))})}}function js({type:e,toolName:t,toolInput:n,...r}){const a=e==="approval"?"Waiting for approval":"Answering questions",o=t?st(t,n??""):null,c=o?`${a} · ${o}`:`${a}…`;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(Pe,{className:"shrink-0"}),s.jsx("span",{className:"truncate text-xs",children:c})]})})}function jt({expanded:e,onToggle:t,header:n,children:r,variant:a="default",dimmed:o=!1,disabled:c=!1,hideChevron:l=!1,extraContent:u,ariaLabel:d,className:m,...p}){const f=l?void 0:e;return s.jsxs("div",{className:G("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",a==="default"&&"border-l-muted-foreground/30",a==="thinking"&&"border-l-muted-foreground/20",a==="memory"&&"border-l-muted-foreground/20",o&&!e&&"opacity-50 hover:opacity-100",m),...p,children:[s.jsxs("button",{onClick:()=>!c&&t(),disabled:c,className:G("focus-ring flex w-full items-center gap-2 rounded-md px-3 py-1",c&&"cursor-default"),"aria-expanded":f,"aria-label":d,children:[n,!l&&!c&&s.jsx(Y.div,{animate:{rotate:e?180:0},transition:{type:"spring",stiffness:400,damping:30},className:"ml-auto",children:s.jsx(gt,{className:"text-muted-foreground size-(--size-icon-xs)"})})]}),u,s.jsx(ie,{initial:!1,children:e&&s.jsx(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,className:"overflow-hidden",children:s.jsx("div",{className:"border-border/50 border-t px-3 pt-1 pb-3",children:r})})})]})}function Ru({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(Pc,{record:t}):s.jsxs("div",{className:"text-center",children:[s.jsx("p",{className:"text-muted-foreground text-base",children:"Start a chat"}),s.jsx("p",{className:"text-muted-foreground/60 mt-2 text-sm",children:"Type a message below to begin."})]})}function Au(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Eu({sessionId:e}){const t=zt(e),n=Fe();if(!t||t.kind==="first-message")return null;const r=Au(t.bornAt),a=xt(t.runtime).label;return s.jsxs(Y.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(io,{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(sn,{}),s.jsxs("span",{children:["born ",r]})]}),s.jsx(sn,{}),s.jsxs("span",{className:"min-w-0 truncate",children:["lives in ",s.jsx("code",{className:"text-2xs",children:t.path})]}),s.jsx(sn,{}),s.jsxs("span",{className:"shrink-0",children:["runs on ",a]})]})]})}function sn(){return s.jsx("span",{"aria-hidden":"true",className:"text-muted-foreground/50 shrink-0",children:"·"})}const _u="another chat";function Mu(e,t){const n=t==null?void 0:t.find(r=>r.id===e);return n?co(n)?as("autonomy"):n.label:or(e)?as("autonomy"):lo(e)}function Ou({startedBy:e,modes:t}){var o;const n=bt();if(!e)return null;const r=((o=e.reason)==null?void 0:o.trim())||null,a=e.kind==="chat"?e.permission:null;return s.jsxs(s.Fragment,{children:[s.jsx(Iu,{startedBy:e,reason:r,navigate:n}),a&&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 ",Mu(a.mode,t),","," ",a.sameAsStarter?"same as":"lower than"," the chat that started it."]})]})}function Iu({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(yt({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??_u})]}),t&&s.jsxs(s.Fragment,{children:[": ",t]})]})}function Pu({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(_n,{"aria-hidden":"true",className:G("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 Du(e){return e.replace(/[-_]+/g," ").trim()}function $u({action:e}){const t=uo(),n=Du(e.actionId),r=`Widget interaction${e.title?`, ${e.title}`:""}: ${n}`;return s.jsxs(Y.span,{"data-testid":"ui-action-chip",title:e.payload?JSON.stringify(e.payload):void 0,className:G("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?mo: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(tu,{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 Fu=/<ui_action>([\s\S]*?)<\/ui_action>/;function Cs(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:null}catch{return null}}function Lu(e){const t=e.match(Fu);if(!t)return null;const n=t[1].split(`
37
+ `);let r=null,a=null,o=null,c=null;for(let l=0;l<n.length;l++){const u=n[l],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){a=m[1].trim();continue}const p=u.match(/^\s*Widget ID:\s*(.*)$/);if(p){o=p[1].trim()||null;continue}const f=u.match(/^\s*Payload:\s*(.*)$/);if(f){const h=f[1].trim();if(h&&h!=="(none)")c=Cs(h);else if(!h){let g="";for(let x=l+1;x<n.length;x++){g+=(g?`
38
+ `:"")+n[x];const y=Cs(g.trim());if(y){c=y;break}}}break}}return a?{title:r,actionId:a,widgetId:o,payload:c}:null}function jn(e){if(e)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function le(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.length>0?n:void 0}function Uu(e){const t=jn(e);if(t){if(Array.isArray(t.content))for(const n of t.content){const r=typeof(n==null?void 0:n.text)=="string"?jn(n.text):void 0;if(r)return r}return t}}function ca(e){const t=fo(e.toolName);if(t!=="chat_send"&&t!=="session_start"&&t!=="chat_stop")return null;const n=jn(e.input),r=Uu(e.result),a=qu(e,r),o=a===void 0&&(r==null?void 0:r.status)==="approval_required",c=le(n,"delivery");return{tool:t,...le(n,t==="chat_stop"?"chat":"to")!==void 0?{to:le(n,t==="chat_stop"?"chat":"to")}:{},...le(n,t==="session_start"?"prompt":"message")!==void 0?{message:le(n,t==="session_start"?"prompt":"message")}:{},...le(n,"summary")!==void 0?{summary:le(n,"summary")}:{},...c==="queue"||c==="steer"||c==="interrupt"?{delivery:c}:{},...le(n,"reason")!==void 0?{reason:le(n,"reason")}:{},...le(r,"messageId")!==void 0?{messageId:le(r,"messageId")}:{},...(le(r,"chatId")??le(r,"sessionId"))!==void 0?{chatId:le(r,"chatId")??le(r,"sessionId")}:{},...a!==void 0?{error:a}:{},...o?{waiting:o}:{},...t==="chat_stop"&&a===void 0&&(r==null?void 0:r.stopped)===!1?{notRunning:!0}:{},...le(r,"note")!==void 0?{note:le(r,"note")}:{}}}const At="It could not be sent.";function qu(e,t){var n;if((t==null?void 0:t.status)==="denied")return le(t,"message")??At;if((t==null?void 0:t.ok)===!1||typeof(t==null?void 0:t.error)=="string")return le(t,"error")??le(t,"message")??At;if(e.status==="error")return t?le(t,"error")??le(t,"message")??At:((n=e.result)==null?void 0:n.trim())||At}function zu(e,t=60){const n=e.trim().split(new RegExp("(?<=[.!?])\\s"))[0]??"";if(n.length<=t)return n;const r=n.slice(0,t),a=r.lastIndexOf(" ");return`${(a>t/2?r.slice(0,a):r).replace(/[\s,;:.]+$/,"")}…`}function Bu(e,t){if(e){for(let n=t.length-1;n>=0;n--)if(t[n].to.chatId===e)return t[n].to}}function Hu(e,t){if(e.messageId)return t.find(n=>n.id===e.messageId);if(e.tool==="session_start"&&e.chatId)return t.find(n=>n.kind==="start"&&n.to.chatId===e.chatId)}function Wu(e,t){if(e&&e.trim())return e.trim();const r=((t??"").split(`
39
+ `).find(a=>a.trim()!=="")??"").replace(/^#+\s*/,"").trim();return r.length>72?`${r.slice(0,71)}…`:r}function Gu(e,t){if(t.error)return{label:"Failed",tone:"error"};if(t.waiting)return{label:"Waiting for approval",tone:"muted"};if(!e)return{label:t.pending?"Sending":"Sent",tone:"muted"};switch(e.status){case"queued":return{label:e.position?`Queued · #${e.position}`:"Queued",tone:"muted"};case"steered":return{label:"Steered in",tone:"done"};case"working":return{label:e.delivery==="interrupt"?"Interrupted, working":"Working",tone:"active"};case"delivered":return{label:e.delivery==="interrupt"?"Interrupted, then delivered":"Delivered",tone:"done"};case"replied":return{label:"Replied",tone:"done"};case"failed":return{label:"Failed",tone:"error"};default:return{label:"Sent",tone:"muted"}}}function Ku(e){const t=[];return e.kind==="report"&&t.push("Report"),e.kind==="start"&&t.push("Started this chat"),e.delivery==="steer"&&t.push("Steered in"),e.delivery==="interrupt"&&t.push("Interrupted"),t}function Qu(e,t){var n,r;for(const a of e){if((n=a.chatMessages)!=null&&n.some(c=>c.id===t))return a.id;const o=[...a.toolCalls??[],...(a.parts??[]).filter(c=>c.type==="tool_call")];for(const c of o)if(((r=ca(c))==null?void 0:r.messageId)===t)return a.id}}function Vu(e,t){if(t.length===0)return e;const n=[];let r=0;const a=o=>({id:`chat-stop-${o.id}`,role:"user",content:"",parts:[],timestamp:o.at,_chatStop:o});for(const o of e){const c=o.timestamp==="",l=c?Number.NaN:Date.parse(o.timestamp),u=d=>c||!Number.isNaN(l)&&Date.parse(d.at)<l;for(;r<t.length&&u(t[r]);)n.push(a(t[r])),r+=1;n.push(o)}for(;r<t.length;)n.push(a(t[r])),r+=1;return n}function Yu({stamp:e}){const t=Ku(e);return t.length===0?null:s.jsx(s.Fragment,{children:t.map(n=>s.jsx("span",{"data-testid":"chat-message-tag",className:"bg-muted text-muted-foreground rounded px-1.5 py-px text-[11px] leading-4 font-medium",children:n},n))})}function la({stamp:e}){const t=bt(),n=e.from.chatTitle??"another chat";return s.jsxs("span",{"data-testid":"chat-from-mark",className:"inline-flex min-w-0 flex-wrap items-center gap-1.5 text-xs",children:[s.jsxs("span",{className:"text-muted-foreground inline-flex min-w-0 items-center gap-1",children:[s.jsx("span",{"aria-hidden":!0,children:"·"}),s.jsx("span",{children:"from"}),s.jsx("button",{type:"button",onClick:()=>void t(yt({session:e.from.chatId,message:e.id})),className:"focus-ring text-foreground/80 hover:text-foreground max-w-48 truncate underline-offset-4 hover:underline",children:n})]}),s.jsx(Yu,{stamp:e})]})}function Xu({sessionId:e,messageId:t}){const n=bt();return s.jsxs("button",{type:"button","data-testid":"chat-reply-to",onClick:()=>void n(yt({session:e,message:t})),className:"focus-ring text-muted-foreground hover:text-foreground focus-visible:text-foreground mb-1 inline-flex items-center gap-1 text-xs underline-offset-4 hover:underline",children:[s.jsx(Yl,{"aria-hidden":!0,className:"size-3"}),"Reply to your message"]})}function Ju({stamps:e,sessionId:t}){return s.jsx("div",{className:"space-y-2","data-testid":"received-chat-messages",children:e.map((n,r)=>s.jsxs("div",{"data-testid":"received-chat-message","data-kind":n.kind,className:"border-status-info-border bg-status-info-bg rounded-r-md border-l-2 py-1.5 pr-2 pl-3",children:[n.replyToId&&t&&s.jsx(Xu,{sessionId:t,messageId:n.replyToId}),r>0&&s.jsxs("div",{className:"text-muted-foreground mb-1 flex flex-wrap items-center gap-1.5 text-xs",children:[s.jsx("span",{className:"text-foreground/80 font-medium",children:n.from.agentName}),s.jsx(la,{stamp:n})]}),s.jsx("div",{className:"msg-prose",children:s.jsx(Mn,{content:n.text,isStreaming:!1,...t?{sessionId:t}:{}})})]},n.id))})}const Zu={muted:"text-muted-foreground",active:"text-foreground",done:"text-muted-foreground",error:"text-destructive"};function ed(e){return e.charAt(0).toUpperCase()+e.slice(1)}function td(e,t,n){if(e.error)return e.error;if(e.waiting)return"Waiting for a person to approve it.";if(e.tool==="chat_stop")return e.note??(e.notRunning?"Nothing was running there.":"Asked it to stop.");if(!t)return e.note??"Sent.";const r=ed(n);switch(t.status){case"queued":return t.position?`Waiting for ${n} to finish its turn. Number ${t.position} in line.`:`Waiting for ${n} to finish its turn.`;case"steered":return`Joined ${n}’s running turn.`;case"working":return t.delivery==="interrupt"?`Stopped ${n}’s turn. ${r} is on this now.`:`${r} is working on it.`;case"delivered":return`${r} read it and finished its turn.`;case"replied":return`${r} replied.`;case"failed":return t.failureReason??"It was not delivered.";default:return"Sent."}}function nd(e,t){return e.error?{label:"Failed",tone:"error"}:e.waiting?{label:"Waiting for approval",tone:"muted"}:t?{label:"Stopping",tone:"muted"}:e.notRunning?{label:"Not running",tone:"muted"}:{label:"Stopped",tone:"done"}}function sd({part:e,sent:t,at:n,sessionId:r}){const[a,o]=i.useState(!1),c=i.useId(),l=bt(),u=ca(e);if(!u)return null;const d=e.status==="pending"||e.status==="running",m=Hu(u,t),p=(m==null?void 0:m.to.chatId)??u.chatId??(u.tool==="chat_stop"?u.to:void 0),f=(m==null?void 0:m.to)??Bu(p,t),h=(f==null?void 0:f.agentName)??"the agent",g=f==null?void 0:f.chatTitle,x=ir({id:(f==null?void 0:f.agentId)??u.to??p??"chat"}),y=u.tool==="chat_stop"?nd(u,d):Gu(m,{...u,pending:d}),v=Wu((m==null?void 0:m.summary)??u.summary,(m==null?void 0:m.text)??u.message),S=n?kn(n):m?kn(m.sentAt):"",N=u.error??((m==null?void 0:m.status)==="failed"?m.failureReason:void 0),C=N?zu(N):u.tool==="chat_stop"?u.reason:v!==g?v:"",T=u.tool==="session_start"?Zl:u.tool==="chat_stop"?cr:po,w=u.tool==="session_start"?"Started spin-off chat":u.tool==="chat_stop"?u.error||u.notRunning?"Tried to stop":"Stopped":"To",E=u.tool==="session_start"?g??(v||"a new chat"):u.tool==="chat_stop"?g??"a chat":(f==null?void 0:f.agentName)??g??"a chat",_=()=>{p&&l(yt({session:p,...m?{message:m.id}:{}}))};return s.jsxs("div",{"data-testid":"sent-chat-card","data-tool":u.tool,"data-state":y.label,className:"border-border/70 bg-background my-1.5 rounded-lg border text-sm",children:[s.jsxs("button",{type:"button",onClick:()=>o(R=>!R),"aria-expanded":a,...a?{"aria-controls":c}:{},className:"focus-ring hover:bg-muted/40 flex w-full min-w-0 items-center gap-2 rounded-lg px-3 py-2 text-left transition-colors duration-150",children:[s.jsx(ho,{size:"xs",emoji:x.emoji,color:x.color}),s.jsx(T,{"aria-hidden":!0,className:"text-muted-foreground hidden size-3.5 shrink-0 sm:block"}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[s.jsxs("span",{className:"text-muted-foreground",children:[w," "]}),s.jsx("span",{className:"font-medium",children:E}),u.tool==="chat_send"&&g&&(f==null?void 0:f.agentName)&&s.jsxs("span",{className:"text-muted-foreground",children:[" · ",g]}),C&&(u.tool!=="session_start"||N)&&s.jsxs("span",{"data-testid":"sent-chat-aside",className:G("text-muted-foreground",!N&&"hidden sm:inline"),children:[" ","· ",C]})]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[s.jsx("span",{className:G("text-xs",Zu[y.tone]),"data-testid":"sent-chat-state",children:y.label}),S&&s.jsx("time",{className:"text-muted-foreground hidden text-xs tabular-nums sm:inline",children:S}),s.jsx(gt,{"aria-hidden":!0,className:G("text-muted-foreground size-3.5 transition-transform duration-200",a&&"rotate-180")})]})]}),a&&s.jsxs("div",{id:c,className:"border-border/60 space-y-2 border-t px-3 py-2",children:[((m==null?void 0:m.text)??u.message??u.reason)&&s.jsx("div",{className:"msg-prose",children:s.jsx(Mn,{content:(m==null?void 0:m.text)??u.message??u.reason??"",isStreaming:!1,...r?{sessionId:r}:{}})}),s.jsxs("p",{className:"text-muted-foreground text-xs",children:[td(u,m,h),u.note&&u.tool!=="chat_stop"&&m?` ${u.note}`:""]}),p&&!u.error&&!u.waiting&&s.jsx("button",{type:"button",onClick:_,className:"focus-ring text-foreground text-xs font-medium underline-offset-4 hover:underline",children:"Open chat →"})]})]})}function rd({notice:e}){const t=bt();return s.jsxs("div",{"data-testid":"chat-stop-line",className:"text-muted-foreground flex flex-wrap items-center gap-1.5 text-xs",children:[s.jsx(cr,{"aria-hidden":!0,className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["Stopped by ",s.jsx("span",{className:"text-foreground/80 font-medium",children:e.by.agentName})," · ",s.jsx("button",{type:"button",onClick:()=>void t(yt({session:e.by.chatId})),className:"focus-ring hover:text-foreground underline-offset-4 hover:underline",children:e.by.chatTitle??"another chat"}),e.reason?`: ${e.reason}`:""]})]})}function ad({celebration:e,onComplete:t}){const n=i.useRef(null),r=(e==null?void 0:e.level)==="major",a=i.useCallback(()=>{t()},[t]);return i.useEffect(()=>{if(!r)return;let o=!1;go({kind:"burst"}).then(l=>{if(o){l();return}n.current=l});const c=setTimeout(()=>{a()},Bt.CELEBRATION_DISPLAY_MS);return()=>{var l;o=!0,(l=n.current)==null||l.call(n),n.current=null,clearTimeout(c)}},[r,a]),s.jsx(ie,{children:r&&s.jsx(Y.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:uu})})}function od(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 id({text:e,isStreaming:t,elapsedMs:n}){const[r,a]=i.useState(t),o=i.useRef(t),c=i.useRef(null);i.useEffect(()=>{o.current&&!t&&a(!1),o.current=t},[t]),i.useEffect(()=>{t&&r&&c.current&&(c.current.scrollTop=c.current.scrollHeight)},[e,t,r]);const l=n?`Thought for ${od(n)}`:"Thinking…";return s.jsx(jt,{expanded:r,onToggle:()=>a(!r),variant:"thinking",dimmed:!t,disabled:t,ariaLabel:l,"data-testid":"thinking-block","data-streaming":t?"true":void 0,header:s.jsxs(s.Fragment,{children:[s.jsx(Vl,{className:G("text-muted-foreground size-(--size-icon-xs)",t&&"animate-breath")}),s.jsx("span",{className:G("text-3xs text-muted-foreground font-mono",t&&"animate-breath"),children:l})]}),children:s.jsx("div",{ref:c,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 cd({mode:e,memories:t,isStreaming:n}){const[r,a]=i.useState(n),o=i.useRef(n);if(i.useEffect(()=>{o.current&&!n&&a(!1),o.current=n},[n]),t.length===0)return null;const c=t.length,l=n?c<=1?"Consulting memory…":`Consulting ${c} memories…`:c===1?"Recalled 1 memory":`Recalled ${c} memories`,u=e==="synthesize"?xo:bo,d=e==="synthesize"?"sparkles":"bookopen";return s.jsx(jt,{expanded:r,onToggle:()=>a(!r),variant:"memory",dimmed:!n,disabled:n,ariaLabel:l,"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:G("text-muted-foreground size-(--size-icon-xs)",n&&"animate-breath")}),s.jsx("span",{className:G("text-3xs text-muted-foreground font-mono",n&&"animate-breath"),children:l})]}),children:s.jsx(ld,{memories:t})})}function ld({memories:e}){return s.jsx("ul",{className:"flex flex-col gap-1 px-3 py-2",children:e.map(t=>s.jsx(ud,{memory:t},t.path))})}function ud({memory:e}){const t=e.path.startsWith("<synthesis:"),n=e.scope==="team"?yo:ko,r=e.scope==="team"?"team":"personal",{copy:a}=vo({toastOnSettle:!0}),o=()=>{const c=t&&e.content?e.content:e.path;a(c)};if(t&&e.content){const c=e.path.replace(/^<synthesis:/,"synthesis:").replace(/>$/,"");return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:o,"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)"}),c]})]})})}return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:o,"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:du(e.path,40)}),s.jsx(n,{"aria-hidden":"true",className:"text-muted-foreground size-(--size-icon-xs)"})]})})}function $t(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function ua(e){return e===void 0?"Summarized (asked by the agent)":`Summarized at ${e}% (asked by the agent)`}function dd(e){if((e==null?void 0:e.requestedBy)==="agent")return ua(e.contextPercent);const t=["Context compacted"];return(e==null?void 0:e.preTokens)!==void 0&&t.push(`${$t(e.preTokens)} tokens`),e!=null&&e.trigger&&t.push(e.trigger),t.join(" · ")}function md(e,t){return e===void 0?"Compacted context":t===void 0?`Compacted context · ${$t(e)} tokens summarized`:`Compacted context · ${$t(e)} → ${$t(t)} tokens`}function fd({trigger:e,preTokens:t,postTokens:n,failed:r,error:a,requestedBy:o,contextPercent:c}){return r?s.jsx(ze,{"data-testid":"compact-boundary-row","data-failed":"true",icon:s.jsx(On,{"aria-hidden":"true",className:"text-status-warning-dot size-3 shrink-0"}),label:s.jsx("span",{className:"text-status-warning-fg",children:o==="agent"?"Couldn’t compact (asked by the agent)":"Couldn’t compact"}),children:a?s.jsx("p",{className:"text-muted-foreground mt-1 text-xs",children:a}):null}):o==="agent"?s.jsx(ze,{"data-testid":"compact-boundary-row","data-requested-by":"agent",icon:s.jsx(os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:ua(c)})}):s.jsx(ze,{"data-testid":"compact-boundary-row",icon:s.jsx(os,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:md(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 pd({part:e}){const[t,n]=i.useState(!1);return t?s.jsxs("div",{"data-testid":"message-image-missing",className:G("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(eu,{"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 hd({content:e}){return s.jsx(ze,{"data-testid":"staged-context-note",icon:s.jsx(lr,{"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 gd(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 xd(e){return e==="untracked"?"neutral":e==="stopped"?"complete":e}function bd(e){const t=[];return e.toolUses&&t.push(`${e.toolUses} tool ${e.toolUses===1?"call":"calls"}`),e.durationMs&&t.push(gd(e.durationMs)),t.length>0?t.join(" · "):null}function yd({part:e}){const[t,n]=i.useState(!1),r=i.useRef(null),a=bd(e),o=e.subagentText,c=e.status==="untracked",l=!!(a||e.summary||e.lastToolName||o||c);return i.useEffect(()=>{const u=r.current;u&&(u.scrollTop=u.scrollHeight)},[o]),s.jsx(jt,{expanded:t,onToggle:()=>l&&n(!t),hideChevron:!l,ariaLabel:`Background task: ${e.description}`,"data-testid":"subagent-block","data-task-id":e.taskId,"data-status":e.status,header:s.jsxs(s.Fragment,{children:[ia(xd(e.status)),s.jsx("span",{className:"text-3xs truncate font-mono",children:e.description}),a&&s.jsx("span",{className:"text-3xs text-muted-foreground ml-1 shrink-0",children:a})]}),children:s.jsxs("div",{className:"space-y-1.5",children:[o&&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:o})]}),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}),c&&s.jsx("p",{className:"text-3xs text-muted-foreground","data-testid":"subagent-untracked",children:"No longer tracked. It may still be running."})]})})}function kd(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 vd(e){const t=kd(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 He(e){return e.notAllowed!==!0&&e.usage.state!=="limited"}function Sd(e,t){if(e.id===nt||!e.eligible)return e.reason;const n=So(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))),a=jo(n.resetsAt,t);return a?`${r}% left · resets ${a}`:`${r}% left`}function Gt(e,t){return e.runtime!==void 0&&e.runtime!==t}function jd(e,t){const n=[],r=[];for(const a of e)(Gt(a,t)?r:n).push(a);return{same:n,other:r}}function Ut(e,t){return`${e.runtime??t}:${e.id}`}function Cd(e,t,n){if(Gt(e,t)){const r=e.runtime;return!e.label&&e.id===mt?`${Lt({runtime:r,accountLabel:null,identityGate:!1})} (this computer's sign-in)`:Lt({runtime:r,accountLabel:e.label,identityGate:!0})}return e.label?e.label:e.id===mt&&e.usage.label?e.usage.label:e.usage.path?n(e.usage.path):e.id}function wd(e,t){const n=e.accounts.find(a=>a.id===e.recommendedId);if(n&&He(n))return Ut(n,t);const r=e.accounts.find(He);return r?Ut(r,t):null}function Nd(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 Td(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 Rd(e){return e.carryOver===!1}function Ad(e,t,n){return e?!0:(t==null?void 0:t.accounts.some(r=>Gt(r,n)))??!1}function Ed(e){return{id:nt,runtime:e,label:cs,color:is,eligible:!0,reason:"paid from your DorkOS account",usage:{runtime:"claude-code",accountId:nt,path:"",label:cs,color:is,subscriptionType:null,plan:null,credits:null,spend:null,windows:[],state:"unknown",limit:null,updatedAt:null}}}function da(e,t){const n=ge();return rt({queryKey:In.continueOptions(e),queryFn:()=>n.getContinueOptions(e),enabled:t,staleTime:0,retry:!1})}function _d(e){const t=ge();return ft({mutationFn:n=>t.continueSession(e,n),retry:!1})}function Md(e){const t=ge();return ft({mutationFn:()=>t.cancelAutoContinue(e),retry:!1})}const ws="claude-code",Od="No other account can take this work right now.";function Id(e){return e instanceof Error&&e.message?e.message:"Couldn’t continue on that account. Try again."}function Pd({row:e,value:t,name:n,status:r,selected:a}){const o=He(e);return s.jsxs("label",{"data-slot":"continue-account-row","data-eligible":e.eligible,className:G("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]",a?"border-foreground ring-foreground ring-1 ring-inset":"border-border",o?"hover:bg-muted/50 cursor-pointer":"cursor-not-allowed",!e.eligible&&"opacity-60"),children:[s.jsx(Mo,{value:t,disabled:!o,className:"sr-only"}),s.jsx("span",{"aria-hidden":!0,className:"inline-flex",children:s.jsx(Dn,{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:G(Oo.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 ma({open:e,onOpenChange:t,sessionId:n,account:r,cancelAutoFirst:a=!1,now:o,onCloseAutoFocus:c}){var ae;const l=kt(),u=o??new Date(l),d=i.useId(),m=r.runtime??ws,{accounts:p,nameFor:f}=Pn(),[,h]=vt(),g=Md(n),x=i.useRef(!1),{mutate:y,reset:v}=g;i.useEffect(()=>{if(!e){x.current=!1,v();return}!a||x.current||(x.current=!0,y())},[e,a,y,v]);const S=e&&(!a||g.isSuccess),N=da(n,S),C=_d(n),[T,w]=i.useState(null),E=()=>{C.isPending||(w(null),C.reset(),t(!1))},_=A=>A?t(!0):E(),R=S?N.data:void 0,I=R==null?void 0:R.ranking,b=R&&!Rd(R.plan)?[...R.ranking.accounts,...R.credits?[Ed(m)]:[]]:[],j=b.some(He),k=T??(I?wd(I,m):null),M=b.find(A=>Ut(A,m)===k)??null,z=M!==null&&He(M),O=A=>Cd(A,m,f),{same:$,other:U}=jd(b,m),H=Td((R==null?void 0:R.advised)===!0,r.trackerItems.some(A=>A.via==="this-chat")),V=r.accountId??((ae=r.limit)==null?void 0:ae.accountId)??null,te=(R==null?void 0:R.advised)===!0&&m===ws&&V!==null?Nd(p.filter(A=>A.id&&A.id!==V&&!$.some(B=>B.id===A.id)).map(A=>f(A.path))):null,W=()=>{!M||!He(M)||C.mutate(Gt(M,m)?{account:M.id,runtime:M.runtime}:{account:M.id},{onSuccess:A=>{E(),A.sessionId&&h(A.sessionId)}})},F=A=>{const B=Ut(A,m);return s.jsx(Pd,{row:A,value:B,name:O(A),status:Sd(A,u),selected:B===k},B)},P=g.isError?g.error:N.isError&&S?N.error:C.isError?C.error:null,D=e&&!P&&(!S||N.isPending),Q=!D&&R!==void 0;return s.jsx(Co,{open:e,onOpenChange:_,children:s.jsxs(wo,{className:"max-h-[85vh] !min-h-0",desktopProps:{className:"sm:max-w-[380px]"},onCloseAutoFocus:c,"aria-labelledby":d,children:[s.jsxs(No,{className:"shrink-0 text-left",children:[s.jsx(To,{id:d,className:"text-left",children:"Continue on another account"}),s.jsx(Ro,{className:"text-left",children:H.subtitle})]}),s.jsxs(Ao,{className:"flex flex-col gap-3",children:[D&&s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(ls,{className:"h-11 rounded-lg"}),s.jsx(ls,{className:"h-11 rounded-lg"})]}),Q&&(j?s.jsxs(Eo,{"aria-labelledby":d,value:k??"",onValueChange:w,className:"min-w-0 grid-cols-1 gap-1.5",children:[$.map(F),U.length>0&&s.jsx("div",{className:"text-muted-foreground mt-2 text-xs font-semibold tracking-wide uppercase",children:"Other runtimes"}),U.map(F)]}):s.jsx("p",{className:"text-muted-foreground text-sm",children:Od})),Q&&te&&s.jsx("p",{className:"text-muted-foreground text-xs",children:te}),Q&&s.jsxs("ul",{className:"text-muted-foreground list-disc pl-4 text-xs",children:[s.jsx("li",{children:H.carries}),s.jsx("li",{children:H.doesnt})]}),P!==null&&s.jsx("p",{role:"alert",className:"text-destructive text-sm",children:Id(P)})]}),s.jsxs(_o,{className:"shrink-0",children:[s.jsx(re,{variant:"outline",onClick:E,disabled:C.isPending,children:"Cancel"}),s.jsxs(re,{onClick:W,disabled:!Q||!j||!z||C.isPending,"aria-busy":C.isPending||void 0,children:[C.isPending&&s.jsx(Pe,{}),M&&Q&&j?`Continue on ${O(M)}`:"Continue"]})]})]})})}const Dd=1440*60*1e3,$d="Paused until you continue or the account resets",Fd="Paused until the task moves or the account resets",Ld=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited"]);function Ud(e){return Ld.has(e)?"critical":"neutral"}function fa(e){return e.carryOver===!1}function Ze(e,t){return e!==null&&Date.parse(e)<=t.getTime()}function Hn(e){return`${e} should have reset by now.`}function qd(e,t,n,r){if(Ze(n,r))return Hn(e);const a=Io(t,n,r);return a==="out"?`${e} is out of usage.`:a.startsWith("back in ")?`${e} is out of usage · ${a}.`:`${e} is out of usage ${a.slice(4)}.`}function pa(e){return e.plan.mode==="waiting"&&e.plan.resumeAt?e.plan.resumeAt:e.resetsAt}function Ns(e,t,n){if(t===null)return`Waiting for ${e}`;if(Ze(t,n))return Hn(e);const r=Date.parse(t)-n.getTime();return r<Dd?`Waiting for ${e} · back in ${Po(r)}`:`Waiting for ${e} · back ${$n(t,n)}`}function zd(e,t){return Math.max(0,Math.ceil((Date.parse(e)-t.getTime())/1e3))}const Bd=new Set(["continue-on","move-now","keep-going","resume","open-moved"]);function Hd(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 Wd=new Set(["limited","handing-off","wait-only","all-accounts-out","model-limited","waiting-reset"]),rn={canSubmit:!0,placeholder:null};function Gd(e,t,n){if(!e)return rn;const r=ur(e);if(r==="moved")return{canSubmit:t,placeholder:null};if(!Wd.has(r))return rn;const a=c=>c!==null&&!Ze(c,n);return a(pa(e))||e.plan.mode==="auto"&&a(e.plan.fireAt)?{canSubmit:!1,placeholder:r==="handing-off"?Fd:$d}:rn}const Kd=300*1e3;function ha(e,t){const n=Date.parse(e)-Date.parse(t);return Number.isFinite(n)&&n>=0&&n<=Kd}function Qd(e,t){let n=null;for(const r of e)ha(r.since,t)&&(n===null||Date.parse(r.since)<Date.parse(n.since))&&(n=r);return n}function Cn(e,t){var n;return e?((n=t.find(r=>r.value===e))==null?void 0:n.displayName)??e:null}function Vd(e,t){return{from:Cn(e.modelFrom,t)??(e.scope==="model"?dr(e.window,t):null),to:Cn(e.modelTo,t)}}function ga(e){return e.endsWith("connectors.request_connection")||e.endsWith("connectors_request_connection")}function xa(e){if(e)try{return JSON.parse(e)}catch{return}}function Ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yd(e){const t=xa(e);if(!Ft(t))return;const{serviceSlug:n,reason:r}=t;if(!(typeof n!="string"||typeof r!="string"))return{serviceSlug:n,reason:r}}function ba(e){const t=xa(e);if(Ft(t)&&typeof t.requestId=="string")return t.requestId;if(Ft(t)&&Array.isArray(t.content)){const n=t.content.map(r=>Ft(r)&&typeof r.text=="string"?r.text:"").join("");return ba(n)}}function Xd(e,t){const n=ba(t.result);if(n)return e.find(a=>a.requestId===n);const r=Yd(t.input);if(r)return e.filter(a=>a.serviceSlug===r.serviceSlug).sort((a,o)=>o.createdAt.localeCompare(a.createdAt))[0]}function Jd({sessionId:e,input:t,result:n,fallback:r}){const a=zl(e),o=a.data?Xd(a.data,{input:t,result:n}):void 0;return o?s.jsx("div",{className:"my-3","data-testid":"chat-agent-request",children:s.jsx(Bl,{request:o})}):s.jsx(s.Fragment,{children:r})}function ya(){const{accounts:e,nameFor:t,colorFor:n}=Pn(),r=Do("claude-code",{accountId:mt,path:null});return a=>{const o=$o({accountId:a,path:null,accounts:e,usage:a===mt?r:null,nameFor:t,colorFor:n});return{name:o.name??a,color:o.color}}}const Ts="claude-code",Zd=new Set(["limited","handing-off","model-limited"]),em=new Set(["limited","model-limited","all-accounts-out"]);function tm(e){return(e==null?void 0:e.runsOn)==="own-sign-in"&&e.chosenBy==="user"}function nm(e){return e instanceof Error&&e.message?e.message:"Couldn’t do that. Try again."}function sm(e,t){var V,te,W;const n=ge(),r=Fn(),[,a]=vt(),o=St(e,{fetchUsage:!1}),c=t??o,l=c.limit,u=l?ur(l):null,d=c.runtime??Ts,m=c.visible,p=ya(),f=d===Ts&&(l!=null&&l.accountId)?p(l.accountId).name:c.name,h=Lt({runtime:d,accountLabel:f,identityGate:m}),g=Ln({sessionId:e||void 0,runtime:d}).data??[],x=l?fa(l.plan):!0,y=u!==null&&Zd.has(u)&&!x,{isLoaded:v}=Pn(),{data:S}=Un(),N=v&&S!==void 0,C=u==="model-limited",T=da(e,y&&N&&(C?m:!m)),w=y&&(C?m&&(((V=T.data)==null?void 0:V.ranking.accounts.some(He))??!1):Ad(m,(te=T.data)==null?void 0:te.ranking,d)),{continuedHere:E,continueHere:_}=mr(e,(l==null?void 0:l.since)??null),{data:R}=Fo(),I=u!==null&&em.has(u)&&!x&&(l==null?void 0:l.accountId)!==nt&&Lo(R,d)&&!tm((W=R==null?void 0:R.defaults)==null?void 0:W[d]),b=(l==null?void 0:l.since)??null,j=`${b}:${u}`,[k,M]=i.useState(null),z=F=>M(F===null?null:{key:j,message:F}),O=F=>z(nm(F)),$=ft({mutationFn:F=>n.waitForReset(e,F),retry:!1,onError:O}),U=ft({mutationFn:F=>n.continueSession(e,F),retry:!1,onError:O,onSuccess:F=>{F.sessionId&&F.sessionId!==e&&a(F.sessionId)}}),H=i.useRef(b);return i.useEffect(()=>{H.current!==null&&b===null&&r.invalidateQueries({queryKey:In.limitHistory(e)}),H.current=b},[b,e,r]),{account:c,limit:l,state:u,runtime:d,subject:h,identityGate:m,canPick:w,creditsOffered:I,nameOf:p,models:g,continuedHere:E,continueHere:_,wait:F=>{z(null),$.mutate(F===void 0?{}:{autoResume:F})},continueOn:F=>{z(null),U.mutate(F)},openSession:F=>a(F),pending:$.isPending||U.isPending,failure:(k==null?void 0:k.key)===j?k.message:null}}function an({visible:e,spoken:t,spokenKey:n}){const[r,a]=i.useState({key:n,text:t});return r.key!==n&&a({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 on({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(Dn,{color:e.color,name:e.name,tooltip:!1})}),e.name]})}function rm(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 am({sessionId:e,onSend:t,account:n,now:r}){const a=sm(e,n),o=fr(),{limit:c,state:l,subject:u,identityGate:d}=a,m=kt(l==="handing-off"?1e3:6e4),p=r??new Date(m),f=c?c.since:null,[h,g]=i.useState(null),x=a.canPick&&f!==null&&h===f,y=j=>g(j?f:null),v=i.useId();if(!c||!l)return null;const S=a.creditsOffered&&o!==null,N=c.plan,C=Cn(c.modelFallback,a.models),T=Hd(l,{canPick:a.canPick,hasFallback:C!==null,continuedHere:a.continuedHere}),w=`${l}:${c.since}:${u}`;let E,_=null,R=!1;switch(l){case"all-accounts-out":{E="All accounts are out.";const j=c.allOut;if(j!=null&&j.resetsAt){const k=a.nameOf(j.accountId);_=Ze(j.resetsAt,p)?Hn(k.name):s.jsxs(s.Fragment,{children:["Soonest back: ",s.jsx(on,{account:k,showDot:d}),","," ",$n(j.resetsAt,p)]})}break}case"model-limited":E=`${dr(c.window,a.models)} is out on ${u} for this week.`;break;case"waiting-reset":{const j=pa(c);E=s.jsx(an,{visible:Ns(u,j,p),spoken:Ns(u,j,p),spokenKey:`${w}:${Ze(j,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 j=a.nameOf(N.accountId);E=s.jsxs(s.Fragment,{children:["This task continued on ",s.jsx(on,{account:j,showDot:d}),"."]});break}default:{const j=qd(u,c.window,c.resetsAt,p);if(E=s.jsx(an,{visible:j,spoken:j,spokenKey:`${w}:${Ze(c.resetsAt,p)}`}),l==="handing-off"&&N.mode==="auto"){const k=a.nameOf(N.target),M=zd(N.fireAt,p);R=M===0,_=s.jsx(an,{visible:s.jsxs(s.Fragment,{children:["Moving this task to ",s.jsx(on,{account:k,showDot:d}),R?"…":` in ${M}s…`]}),spoken:R?`Moving this task to ${k.name}.`:`Moving this task to ${k.name} in ${M} seconds.`,spokenKey:`${w}:${N.fireAt}:${k.name}:${R}`})}}}const I=j=>{switch(j){case"continue-on":case"choose":y(!0);return;case"move-now":N.mode==="auto"&&a.continueOn({account:N.target});return;case"keep-going":c.modelFallback&&a.continueOn({model:c.modelFallback});return;case"resume":t(Uo);return;case"open-moved":N.mode==="continued"&&a.openSession(N.sessionId);return;case"continue-here":a.continueHere();return;case"wait":a.wait();return}},b=l==="waiting-reset"&&N.mode==="waiting"&&!fa(N);return s.jsxs(s.Fragment,{children:[s.jsxs(Nl,{variant:Ud(l),role:"status",icon:null,"data-slot":"account-limit-banner","data-state":l,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}),_&&s.jsxs(s.Fragment,{children:[" ",_]})]}),b&&s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsx("input",{id:v,type:"checkbox",className:"size-3.5",checked:N.autoResume,disabled:a.pending,onChange:j=>a.wait(j.target.checked)}),s.jsx("label",{htmlFor:v,children:"Continue automatically when it resets"})]}),S&&o&&s.jsx("div",{className:"mt-1.5",children:o({runtime:a.runtime,origin:`limit:${e}`,intent:"keep-going",confirmAfterLink:{prompt:"Linked. Continue on DorkOS credits?",action:"Continue"},onChoose:()=>a.continueOn({account:nt})})}),T.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:T.map(j=>s.jsx(re,{size:"sm",variant:Bd.has(j)&&!S?"default":j==="continue-here"?"ghost":"outline",className:"h-auto min-h-11 max-w-full py-1 whitespace-normal md:min-h-8",disabled:a.pending||j==="move-now"&&R,onClick:()=>I(j),children:rm(j,C)},j))}),a.failure&&s.jsx("p",{role:"alert",className:"text-destructive mt-1.5",children:a.failure})]}),a.canPick&&s.jsx(ma,{open:x,onOpenChange:y,sessionId:e,account:{runtime:a.runtime,accountId:a.account.accountId,limit:c,trackerItems:a.account.trackerItems},cancelAutoFirst:l==="handing-off",now:r})]})}function om(e){const t=ge();return rt({queryKey:In.limitHistory(e),queryFn:()=>t.getLimitHistory(e),enabled:e!=="",retry:!1})}const im={moved:zo,"resumed-reset":ct,"resumed-model":ct,"resumed-early":ct};function cm({entry:e,now:t}){const n=kt(),r=t??new Date(n),a=ya(),o=qo(e.runtime),c=Ln({runtime:e.runtime}).data??[],[,l]=vt(),u=e.runtime==="claude-code"&&e.accountId?a(e.accountId).name:null,d=Lt({runtime:e.runtime,accountLabel:u,identityGate:o}),m=`at ${$n(e.resolvedAt,r)}`,p=im[e.resolution];let f;switch(e.resolution){case"moved":{const h=e.toAccountId?a(e.toAccountId):null,g=h?s.jsxs(s.Fragment,{children:[o&&h.color&&s.jsx("span",{"aria-hidden":!0,className:"mr-0.5 inline-flex align-middle",children:s.jsx(Dn,{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:()=>l(e.toSessionId),children:g}):g]})," ",m]});break}case"resumed-reset":f=`Resumed after reset ${m}`;break;case"resumed-model":{const{from:h,to:g}=Vd(e,c);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 lm({sessionId:e,at:t,fallback:n,now:r}){const{limit:a}=St(e,{fetchUsage:!1}),o=om(e),[c,l]=i.useState(null),u=a!==null&&(t===""||ha(a.since,t));if(u&&((c==null?void 0:c.data)!==o.dataUpdatedAt||c.error!==o.errorUpdatedAt)&&l({data:o.dataUpdatedAt,error:o.errorUpdatedAt}),u||o.isPending)return null;const d=o.data&&t?Qd(o.data.entries,t):null;return d?s.jsx(cm,{entry:d,now:r}):a===null&&c!==null&&o.dataUpdatedAt===c.data&&o.errorUpdatedAt===c.error?null:s.jsx(s.Fragment,{children:n})}function um(e){const{limit:t}=St(e,{fetchUsage:!1}),{continuedHere:n}=mr(e,(t==null?void 0:t.since)??null),r=kt();return Gd(t,n,new Date(r))}function dm(e){return St(e,{fetchUsage:!1}).limit!==null}const ka="runtimes";function mm({label:e}){const{open:t}=pr();return s.jsx("button",{type:"button",onClick:()=>t(ka),className:"text-muted-foreground hover:text-foreground mt-2 block text-xs underline decoration-dotted underline-offset-2 transition-colors",children:e})}function fm({runtime:e,sessionId:t,onRetry:n,onSigninComplete:r}){const[a,o]=i.useState(!1),c=Go(e,{sessionId:t,onCompleted:()=>o((r==null?void 0:r())??!1)}),l=Vo(e);return c.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(tt,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),a?"Signed in. Sending your message again…":"Signed in."]}),!a&&n&&s.jsxs(re,{size:"sm",onClick:n,className:"mt-2 gap-1.5",children:[s.jsx(pt,{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:c.isPending&&s.jsxs(s.Fragment,{children:[s.jsx(Pe,{size:"xs",className:"shrink-0"}),l.signInPending]})}),c.isError&&s.jsx("p",{className:"text-destructive mb-2 text-sm",role:"alert",children:c.errorMessage}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(re,{size:"sm",onClick:c.login,disabled:c.isPending,className:"gap-1.5","data-testid":"auth-error-signin-button",children:[s.jsx(hr,{className:"size-3"}),c.isError?"Try again":l.signInLabel]}),n&&s.jsxs(re,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(pt,{className:"size-3"}),"Retry"]})]}),s.jsx(mm,{label:"Use an API key instead"})]})}function Rs({onRetry:e}){return s.jsx("div",{className:"mt-3","data-testid":"auth-error-remote-guidance",children:s.jsx(Wo,{...e?{onRetry:e}:{}})})}function va({onRetry:e}){const{open:t}=pr();return s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[s.jsxs(re,{size:"sm",onClick:()=>t(ka),className:"gap-1.5",children:[s.jsx(hr,{className:"size-3"}),"Fix sign-in"]}),e&&s.jsxs(re,{variant:"outline",size:"sm",onClick:e,className:"gap-1.5",children:[s.jsx(pt,{className:"size-3"}),"Retry"]})]})}function pm({runtime:e,sessionId:t,onRetry:n,renderOffer:r,lead:a,children:o}){const c=!gr(),l=xr(),u=se(f=>f.setRetryAccount),d=xt(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 l.mutateAsync({runtime:e,useCredits:!0}),n&&(u({id:nt,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 a?s.jsxs("div",{className:"mt-3 space-y-3","data-testid":"auth-error-credits-first",children:[m,p(o),s.jsx(Ko,{ollama:Qo(e)==="provider-picker",remote:c})]}):s.jsxs("div",{"data-testid":"auth-error-credits-other-way",children:[o,s.jsx("div",{className:"mt-3",children:p(m)})]})}function hm({sessionId:e,onRetry:t,onSigninComplete:n}){var p;const{sessions:r,isLoading:a}=En(),o=gr(),c=(p=r.find(f=>f.id===e))==null?void 0:p.runtime,l=Bo(c),u=fr(),d=c!==void 0&&u!==null&&(l==="lead"||l==="other-way");if(!o&&!d)return s.jsx(Rs,{onRetry:t});if(a)return null;const m=o?!c||!Ho(c)?s.jsx(va,{onRetry:t}):s.jsx(fm,{runtime:c,sessionId:e,onRetry:t,onSigninComplete:n}):s.jsx(Rs,{onRetry:t});return d&&c&&u?s.jsx(pm,{runtime:c,sessionId:e,onRetry:t,renderOffer:u,lead:l==="lead",children:m}):m}function gm({sessionId:e,onRetry:t,onSigninComplete:n}){return e?s.jsx(hm,{sessionId:e,onRetry:t,onSigninComplete:n}):s.jsx(va,{onRetry:t})}const xm="credits_unavailable",bm="folder-sign-in";function ym({onRetry:e,sessionId:t,runtimeLabel:n,reason:r}){const a=se(g=>g.setRetryAccount),o=Yo(),c=xr(),l=br(),u=Wt(t),d=Ht(u??null);if(!e)return null;const m=km(d),p=n?`your ${n}`:"your own",f=()=>{if(d!==void 0){if(m==="pick-for-send"){t&&a({id:mt,sessionId:t}),e();return}c.mutate({runtime:d.type,useCredits:!1},{onSuccess:()=>m==="new-conversation"?l(void 0,{runtime:d.type}):e()})}},h=()=>{t&&o.mutate(t,{onSuccess:({launch:g})=>{g!=null&&g.ok&&a({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(re,{size:"sm",variant:"outline",onClick:e,className:"gap-1.5",children:[s.jsx(pt,{className:"size-3"}),"Retry"]}),t&&s.jsx(re,{size:"sm",variant:"outline",onClick:f,disabled:d===void 0||c.isPending,children:m==="new-conversation"?`Start a new chat on ${p} sign-in`:`Use ${p} sign-in`}),t&&r===bm&&s.jsx(re,{size:"sm",variant:"outline",onClick:h,disabled:o.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"," chats to ",p," sign-in, not just this one."]}),o.error&&s.jsx("p",{className:"text-muted-foreground text-xs",role:"status",children:o.error.message}),c.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 km(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 vm({category:e,onChooseModel:t}){return t?s.jsxs(re,{size:"sm",onClick:t,className:"mt-3 gap-1.5",children:[s.jsx(yr,{className:"size-3"}),e==="runtime_update_required"?"Choose another model":"Choose model"]}):null}const Sm="your agent",jm="agent",As={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 chat 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}},Cm=new Set(["max_turns","budget_exceeded","output_format_error","auth_error"]);function wm(e){return`Sign in to ${e??Sm} again`}function Nm(e){return`Your ${e??jm} login stopped working. Sign in again to continue.`}const Tm="rate_limit";function qt(e){const{code:t,at:n,sessionId:r}=e;return t===Tm&&r?s.jsx(lm,{sessionId:r,at:n??"",fallback:s.jsx(Es,{...e})}):s.jsx(Es,{...e})}function Es({message:e,category:t,details:n,onRetry:r,heading:a,subtext:o,runtimeLabel:c,sessionId:l,onSigninComplete:u,onChooseModel:d,code:m,reason:p}){const[f,h]=i.useState(!1),g=m===xm,x=i.useMemo(()=>vd(e),[e]),y=(x==null?void 0:x.category)??t,v=(x==null?void 0:x.message)??e,S=x?n!=null&&n.includes(x.details??"")?n:[n,x.details].filter(Boolean).join(`
40
+ `):n,N=y==="auth_error",C=y?As[y]??As.execution_error:null,T=N?wm(c):y==="runtime_update_required"&&c?`${c} update required`:C==null?void 0:C.heading,w=N?Nm(c):C==null?void 0:C.subtext,E=g?"Couldn’t reach DorkOS credits":x?T??"Error":a??T??"Error",_=v.trim(),R=y!==void 0&&Cm.has(y),I=g?_:(x&&(o==null?void 0:o.trim())===e.trim()?void 0:o)??(R?w:_||w)??_,b=I.trim(),j=i.useMemo(()=>Xo(_),[_]),k=!_||_===b||_===E,M=!k&&(!R||j)?_:null,z=k||M!==null||S!=null&&S.includes(_)?S:[S,_].filter(Boolean).join(`
41
+ `),O=(C==null?void 0:C.retryable)??!!r;return s.jsx("div",{"data-testid":"error-message-block",className:G("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(On,{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(Yt,{text:I})}),M&&s.jsx("p",{className:"text-muted-foreground mt-1 text-sm wrap-anywhere whitespace-pre-wrap",children:s.jsx(Yt,{text:M})}),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(Y.div,{animate:{rotate:f?0:-90},transition:{type:"spring",stiffness:400,damping:30},children:s.jsx(gt,{className:"size-3"})}),"Details"]}),s.jsx(ie,{initial:!1,children:f&&z&&s.jsx(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,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(Yt,{text:z})})})}),g&&s.jsx(ym,{onRetry:r,sessionId:l,runtimeLabel:c,reason:p}),N&&s.jsx(gm,{sessionId:l,onRetry:r,onSigninComplete:u}),(y==="model_unavailable"||y==="runtime_update_required")&&s.jsx(vm,{category:y,onChooseModel:d})]}),!N&&!g&&O&&r&&s.jsxs(re,{variant:"outline",size:"sm",onClick:r,className:"shrink-0 gap-1.5",children:[s.jsx(pt,{className:"size-3"}),"Retry"]})]})})}const Rm=8;function Am({toolName:e,reasonType:t,reason:n,message:r,agentId:a}){const o=n||r,c=t==="classifier",l=t==="asyncAgent",u=a!==void 0?`Helper ${a.slice(0,Rm)}`:l?"A background helper":null,m=u!==null?`${u} was blocked from using ${e}${c?" by auto mode":""}: ${o}`:c?`Blocked by auto mode: ${o}`:`Blocked: ${o}`;return s.jsxs("div",{"data-testid":"permission-denied-chip","data-reason-type":t,"data-agent-id":a,className:G("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(Fl,{"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}),l?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 Em=50;function _m(e){return e.type==="tool_call"&&e.interactiveType==="approval"&&e.approvalOutcome!==void 0}function Mm(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)<=Em}function Om(e){const t=new Map;let n=null;for(let r=0;r<e.length;r++){const a=e[r];if(!_m(a)){n=null;continue}if(n&&Mm(n.part,a)){n.group.indices.push(r),t.set(r,n.group);continue}const o={leadIndex:r,indices:[r],outcome:a.approvalOutcome,reasonGiven:a.approvalReasonGiven??!1};t.set(r,o),n={group:o,part:a}}return t}function Im(e){return e.questionOutcome!==void 0?e.questionOutcome==="answered":e.status!=="pending"}function Pm(e){return e.status==="pending"?void 0:e.questionOutcome}const Dm={session:"this chat",project:"this project",user:"all your Claude chats"};function $m(e){return e===void 0?void 0:Dm[e]}const Fm={duration:.12,ease:"easeOut"},Lm={duration:0},_s=new Set(["Bash","Write","Edit","NotebookEdit"]),Ms=new Set(["WebFetch","WebSearch"]);function Um(e){const t=e.includes("__")?e.split("__").pop():e;return _s.has(t)||_s.has(e)?"high":Ms.has(t)||Ms.has(e)||e.startsWith("mcp__")?"medium":"low"}function qm(e){const t=Math.floor(e/60),n=e%60;return t>0?`${t}:${String(n).padStart(2,"0")}`:`${n}s`}function Sa({sessionId:e,toolCallId:t,toolName:n,input:r,isActive:a=!1,onDecided:o,ref:c,timeoutMs:l,approvalStartedAt:u,approvalRemainingMs:d,approvalParked:m,approvalTitle:p,approvalDisplayName:f,approvalDescription:h,approvalBlockedPath:g,approvalDecisionReason:x,approvalHasSuggestions:y,approvalAlwaysAllowScope:v,allowsDenyReason:S=!0}){const N=ge(),C=Fe(),T=i.useMemo(()=>Um(n),[n]),w=kr(n),E=st(n,r),_=f||E,R=$m(v),[I,b]=i.useState(!1),[j,k]=i.useState(null),[M,z]=i.useState(null),[O,$]=i.useState(!1),[U,H]=i.useState(""),V=i.useRef(""),[te,W]=i.useState(!1),F=a&&!te,[P,D]=i.useState(()=>Date.now()),Q=i.useRef(!1);i.useLayoutEffect(()=>{if(!Q.current){Q.current=!0;return}D(Date.now())},[l,u,d]);const[ae,A]=i.useState(null),B=i.useMemo(()=>{if(!l||m===!0)return null;const L=d!==void 0?P+d:u?u+l:P+l,pe=Math.min(l,Math.max(0,l-(L-P)));return{expiresAt:L,elapsedMs:pe}},[P,l,u,d,m]),X=j||!l||!B?null:ae!==null&&ae.expiresAt===B.expiresAt?ae.seconds:Math.max(0,Math.ceil((B.expiresAt-P)/1e3));i.useEffect(()=>{if(j||!l||!B)return;const{expiresAt:L}=B,pe=setInterval(()=>{const ce=Math.max(0,Math.ceil((L-Date.now())/1e3));A({expiresAt:L,seconds:ce}),ce<=0&&clearInterval(pe)},1e3);return()=>clearInterval(pe)},[l,B,j]);const J=m===!0||X===0,Z=j||X===null?"":X<=0?"Nobody answered. The agent is waiting for you.":X<=si?"One minute left to answer.":X<=ri?"Two minutes left to answer.":"",K=i.useCallback(async()=>{if(!(I||j)){b(!0),z(null);try{await N.approveTool(e,t),k("approved"),o==null||o()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(k("approved"),o==null||o()):(console.error("Approval failed:",L),z("Couldn’t send your answer. Try again."))}finally{b(!1)}}},[I,j,N,e,t,o]),oe=i.useCallback(async()=>{if(!(I||j)){b(!0),z(null);try{await N.approveTool(e,t,!0),k("approved"),o==null||o()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(k("approved"),o==null||o()):(console.error("Always Allow failed:",L),z("Couldn’t send your answer. Try again."))}finally{b(!1)}}},[I,j,N,e,t,o]),de=i.useCallback(async()=>{if(!(I||j)){b(!0),z(null);try{await N.denyTool(e,t,V.current.trim()||void 0),k("denied"),o==null||o()}catch(L){L.code==="INTERACTION_ALREADY_RESOLVED"?(k("denied"),o==null||o()):(console.error("Deny failed:",L),z("Couldn’t send your answer. Try again."))}finally{b(!1)}}},[I,j,N,e,t,o]);i.useImperativeHandle(c,()=>({approve(){K()},alwaysAllow(){oe()},deny(){de()}}),[K,oe,de]);const me=s.jsx("span",{role:"status","aria-live":"assertive","aria-atomic":"true",className:"sr-only",children:Z});if(j){const L=j==="approved";return s.jsxs(s.Fragment,{children:[s.jsx(Y.div,{initial:C?!1:{opacity:0,scaleY:.9},animate:{opacity:1,scaleY:1},transition:C?Lm:Fm,style:{originY:0},children:s.jsx(ze,{"data-testid":"tool-approval-decided","data-decision":j,icon:L?s.jsx(tt,{className:"text-status-success size-(--size-icon-sm) shrink-0"}):s.jsx(Ie,{className:"text-status-error size-(--size-icon-sm) shrink-0"}),label:s.jsx("span",{className:"text-3xs font-mono",children:_}),trailing:s.jsx("span",{className:G("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"})})}),me]})}return s.jsxs(s.Fragment,{children:[s.jsxs(it.Root,{isActive:a,isResolved:!!j,onAllow:K,onDeny:de,className:"my-1","data-testid":"tool-approval",children:[s.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[s.jsx(Jo,{className:G("size-(--size-icon-md)",T==="high"&&"text-status-error",T==="medium"&&"text-status-warning",T==="low"&&"text-muted-foreground")}),s.jsx(it.Headline,{className:"font-semibold",children:p||"Your agent wants to use a tool"})]}),(h||x||g)&&s.jsxs(it.Detail,{className:"mb-2",children:[h&&s.jsx("p",{children:h}),x&&!h&&s.jsx("p",{children:x}),g&&s.jsxs("p",{className:"font-mono",children:["Path: ",g]})]}),(l||J)&&!j&&s.jsx("div",{className:"mb-2",children:s.jsx(it.Countdown,{secondsLeft:J?null:X,...J?{}:{timeoutMs:l},elapsedMs:(B==null?void 0:B.elapsedMs)??0,label:J?Zo:X===null?"":`${qm(X)} remaining`})}),s.jsxs("div",{className:"mb-2 flex items-center gap-1.5",children:[w&&s.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:w}),s.jsx("span",{className:"font-mono text-xs",children:_})]}),r&&s.jsx("div",{className:"bg-muted mb-3 rounded p-2",children:s.jsx(sa,{toolName:n,input:r})}),M&&s.jsx("p",{className:"text-status-error text-2xs mb-2",children:M}),S&&O&&s.jsx("div",{className:"mb-2",children:s.jsx(ei,{autoFocus:!0,"data-approval-field":"",value:U,maxLength:ti,disabled:I,onFocus:()=>W(!0),onBlur:()=>W(!1),onChange:L=>{H(L.target.value),V.current=L.target.value},onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),de())},placeholder:"Why not? The agent sees this.","aria-label":"Reason for not allowing",className:"text-xs"})}),s.jsxs(it.Actions,{children:[s.jsxs(re,{size:"sm",onClick:K,disabled:I,className:"transition-opacity duration-150",children:[s.jsx(tt,{className:"size-(--size-icon-xs)"})," Allow",F&&s.jsx(Xt,{className:"ml-1.5",children:"Enter"})]}),y&&s.jsxs(re,{size:"sm",variant:"outline",onClick:oe,disabled:I,"aria-label":R===void 0?"Always allow":`Always allow, ${R}`,className:"transition-opacity duration-150",children:[s.jsx(ni,{className:"size-(--size-icon-xs)"})," Always allow",R!==void 0&&s.jsx("span",{className:"text-2xs opacity-70",children:`· ${R}`}),F&&s.jsx(Xt,{className:"ml-1.5",children:"Shift+Enter"})]}),s.jsxs(re,{size:"sm",variant:"outline",onClick:de,disabled:I,className:"transition-opacity duration-150",children:[s.jsx(Ie,{className:"size-(--size-icon-xs)"})," Don’t allow",a&&s.jsx(Xt,{className:"ml-1.5",children:"Esc"})]}),S&&!O&&s.jsx("button",{type:"button",onClick:()=>$(!0),disabled:I,className:G("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"})]})]}),me]})}function zm(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 Bm({sessionId:e,interactionId:t,serverName:n,message:r,mode:a="form",url:o,requestedSchema:c,status:l,action:u}){const d=ge(),[m,p]=i.useState(!1),[f,h]=i.useState(null),[g,x]=i.useState(null),[y,v]=i.useState({}),[S,N]=i.useState(!1),C=i.useMemo(()=>zm(c),[c]),T=l!=="pending",w=i.useCallback(async(j,k)=>{if(!(m||T)){p(!0),h(null),x(null);try{await d.submitElicitation(e,t,j,k)}catch(M){if(M.code!=="INTERACTION_ALREADY_RESOLVED"){h("Couldn’t send your answer. Try again."),x(M instanceof Error?M.message:null),p(!1);return}}p(!1)}},[d,e,t,m,T]),E=i.useCallback(()=>{const j={};for(const k of C)j[k.key]=y[k.key]??k.defaultValue??"";w("accept",j)},[C,y,w]),_=i.useCallback(()=>{w("accept")},[w]),R=i.useCallback(()=>{w("decline")},[w]),I=i.useCallback((j,k)=>{v(M=>({...M,[j]:k}))},[]),b=i.useCallback(()=>{if(o){if(!ai(o)){h(`Couldn’t open ${o}. Nothing has been authorized.`),x(null);return}h(null),x(null),N(!0)}},[o]);return T?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(Y.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},transition:{duration:.15},className:G("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})]}),a==="url"&&o&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(re,{size:"sm",variant:"outline",onClick:b,disabled:m,children:"Open authorization page"}),S&&s.jsx(re,{size:"sm",onClick:_,disabled:m,children:m?"Sending…":"Done"}),s.jsx(re,{size:"sm",variant:"ghost",onClick:R,disabled:m,children:"Decline"})]}),a==="form"&&s.jsxs(s.Fragment,{children:[C.length>0?s.jsx("div",{className:"mb-3 space-y-2",children:C.map(j=>s.jsxs("div",{children:[s.jsx("label",{htmlFor:`elicitation-${t}-${j.key}`,className:"text-muted-foreground mb-1 block text-xs font-medium",children:j.label}),j.options?s.jsxs("select",{id:`elicitation-${t}-${j.key}`,className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",value:y[j.key]??String(j.defaultValue??""),onChange:k=>I(j.key,k.target.value),disabled:m,children:[s.jsx("option",{value:"",children:"Select…"}),j.options.map(k=>s.jsx("option",{value:k,children:k},k))]}):s.jsx("input",{id:`elicitation-${t}-${j.key}`,type:j.type==="number"?"number":"text",className:"border-input bg-background w-full rounded-md border px-3 py-1.5 text-sm",placeholder:String(j.defaultValue??""),value:y[j.key]??"",onChange:k=>I(j.key,k.target.value),disabled:m})]},j.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(re,{size:"sm",onClick:E,disabled:m,children:m?"Sending…":"Accept"}),s.jsx(re,{size:"sm",variant:"ghost",onClick:R,disabled:m,children:"Decline"})]})]})]})}const Hm=8,Wm={duration:.3,ease:[.16,1,.3,1]},Gm={duration:0};function Km(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 Qm(e){return new Date(e).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}function Vm(e){return`${e} action${e===1?"":"s"}`}function Ym({outcome:e,items:t,resolvedAt:n,startedAt:r,reasonGiven:a,className:o}){var x;const c=Fe(),[l,u]=i.useState(!1),d=t.length,m=d>1,p=m?Vm(d):(x=t[0])==null?void 0:x.label,f=n!==void 0&&r!==void 0?Math.max(0,n-r):null,h=e==="allowed"?tt:e==="denied"?Ie:ct,g=e==="allowed"?"text-status-success":e==="denied"?"text-status-error":"text-muted-foreground";return s.jsxs(Y.div,{"data-testid":"approval-receipt","data-outcome":e,"data-count":d,initial:c?!1:{opacity:0,y:Hm},animate:{opacity:1,y:0},transition:c?Gm:Wm,className:G("text-muted-foreground my-1 text-xs",o),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(h,{className:G("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 ${Km(f)}`]}):s.jsxs(s.Fragment,{children:["You ",e==="allowed"?"allowed":"denied"," ",m?p:s.jsx("span",{className:"font-mono",children:p}),e==="denied"&&a===!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:Qm(n)}),m&&s.jsx("button",{type:"button",onClick:()=>u(y=>!y),"aria-expanded":l,className:G("hover:text-foreground focus-visible:ring-ring shrink-0 rounded underline","underline-offset-2 focus-visible:ring-2 focus-visible:outline-none"),children:l?"Hide":"Show"})]}),m&&l&&s.jsx("ul",{"data-testid":"approval-receipt-items",className:"mt-1 ml-6 space-y-0.5",children:t.map(y=>s.jsx("li",{className:"truncate font-mono",children:y.label},y.toolCallId))})]})}function Xm({outcome:e,reasonGiven:t,members:n,lead:r,children:a}){return s.jsxs("div",{className:"flex flex-col",children:[s.jsx(Ym,{outcome:e,items:n.map(o=>({toolCallId:o.toolCallId,label:o.approvalDisplayName||st(o.toolName,o.input??"")})),resolvedAt:r.approvalResolvedAt,startedAt:r.approvalStartedAt,reasonGiven:t}),e!=="allowed"&&r.result&&s.jsx(vr,{"data-testid":"approval-receipt-result",content:r.result,className:"text-muted-foreground mt-0.5 ml-6"}),e==="allowed"&&a]})}function Jm({message:e}){return s.jsx(ze,{"data-testid":"unreadable-entry-note",icon:s.jsx(oi,{"aria-hidden":"true",className:"text-muted-foreground size-3 shrink-0"}),label:s.jsx("span",{className:"text-muted-foreground",children:e})})}function Zm({title:e}){return s.jsxs("div",{"data-testid":"capability-approval-timed-out",className:G("my-2 flex items-start gap-2 rounded-md border px-3 py-2","text-foreground border-border bg-muted/40"),children:[s.jsx(ct,{"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 wn({testId:e,icon:t,children:n}){return s.jsxs("div",{"data-testid":e,className:G("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 ef({part:e}){return e.outcome==="failed"?s.jsx(wn,{testId:"mcp-signin-failed",icon:s.jsx(On,{"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(wn,{testId:"mcp-signin-receipt",icon:s.jsx(Sr,{"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 tf({part:e}){const t=Ll(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(ef,{part:e}):s.jsxs(wn,{testId:"mcp-signin-card",icon:s.jsx(ii,{"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(Ul,{flow:t,serverName:e.serverName,failedActions:s.jsx(re,{variant:"secondary",size:"sm",onClick:()=>t.start(),className:"focus-visible:ring-2",children:"Try again"})})]})}function nf({fromName:e,toName:t}){return s.jsx(ze,{"data-testid":"model-substituted-row",icon:s.jsx(yr,{"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 ja="dorkos:mcp-app-consent:";function Ca(e){return`${ja}${e}`}function sf(e){try{return localStorage.getItem(Ca(e))==="granted"}catch{return!1}}function rf(e){try{localStorage.setItem(Ca(e),"granted")}catch{}af()}const Nn=new Set;function af(){for(const e of Nn)e()}function of(e){Nn.add(e);const t=n=>{var r;(r=n.key)!=null&&r.startsWith(ja)&&e()};return window.addEventListener("storage",t),()=>{Nn.delete(e),window.removeEventListener("storage",t)}}function cf(e){const t=i.useSyncExternalStore(of,()=>sf(e),()=>!1),n=i.useCallback(()=>rf(e),[e]);return{consented:t,grant:n}}const lf="h-80";function uf({sessionId:e,serverName:t,uri:n,title:r}){const{consented:a,grant:o}=cf(t),c=se(d=>d.openPip),l=()=>{const d=se.getState(),m={type:"mcp_app",serverName:t,uri:n,title:r};d.openCanvasDocument(m),xn(d,"user",m)},u=()=>{c({kind:"mcp_app",sessionId:e,serverName:t,uri:n,title:r??`App · ${t}`})};return a?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(vn,{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(ci,{className:"size-3.5"})}),s.jsx("button",{type:"button",onClick:l,title:"Open in canvas",className:"text-muted-foreground hover:bg-muted hover:text-foreground rounded-md p-1 transition-colors",children:s.jsx(li,{className:"size-3.5"})})]})]}),s.jsx(Ml,{sessionId:e,serverName:t,uri:n,title:r,onRequestFullscreen:l,onRequestPip:u,className:lf})]}):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(vn,{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 chat, files or credentials."})]}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:o,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 df={running:s.jsx(Pe,{size:"xs",className:"text-muted-foreground"}),success:s.jsx(tt,{className:"text-muted-foreground size-(--size-icon-xs)"}),error:s.jsx(Ie,{className:"text-destructive size-(--size-icon-xs)"}),cancelled:s.jsx(Ie,{className:"text-muted-foreground size-(--size-icon-xs)"})};function mf({hook:e}){const t=!!(e.stdout||e.stderr),[n,r]=i.useState(e.status==="error"),a=e.stderr||e.stdout;return s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>t&&r(o=>!o),className:G("flex w-full items-center gap-1.5 py-0.5",!t&&"cursor-default"),"aria-expanded":t?n:void 0,disabled:!t,children:[df[e.status],s.jsx("span",{className:G("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(ie,{initial:!1,children:n&&t&&a&&s.jsx(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,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:a})})})]})}function ff({toolCall:e,defaultExpanded:t=!1}){const[n,r]=i.useState(t),a=!!e.progressOutput;i.useEffect(()=>{a&&!n&&r(!0)},[a]);const o=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(mf,{hook:u},u.hookId))}):void 0,c=e.startedAt&&e.completedAt?e.completedAt-e.startedAt:void 0,l=kr(e.toolName);return s.jsxs(jt,{expanded:n,onToggle:()=>r(!n),dimmed:e.status==="complete",extraContent:o,"data-testid":"tool-call-card","data-tool-name":e.toolName,"data-status":e.status,header:s.jsxs(s.Fragment,{children:[ia(e.status),l&&s.jsx("span",{className:"bg-muted text-muted-foreground text-3xs rounded px-1 py-0.5 font-medium",children:l}),s.jsx("span",{className:"text-3xs flex-1 text-left font-mono",children:st(e.toolName,e.input)}),c!==void 0&&s.jsx("span",{className:"text-muted-foreground text-3xs tabular-nums",children:ql(c)})]}),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(Pe,{size:"xs"}),s.jsx("span",{children:"Preparing…"})]}):e.input!==void 0&&e.input!==""?s.jsx(sa,{toolName:e.toolName,input:e.input,isStreaming:e.status==="running"}):null,e.progressOutput&&!e.result&&s.jsx(vr,{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(jr,{content:e.result,toolName:e.toolName,input:e.input})})]})}function pf(e){if(e.startsWith("mcp__"))return e.split("__")[1]||void 0}function wa(e,t,n){const r=i.useRef(e),[a,o]=i.useState(!(t&&r.current==="complete"));return i.useEffect(()=>{if(t&&e==="complete"&&r.current!=="complete"&&!n){const c=setTimeout(()=>o(!1),Bt.TOOL_CALL_AUTO_HIDE_MS);return()=>clearTimeout(c)}},[e,t,n]),!t||n?!0:a}function hf({part:e,autoHide:t,expandToolCalls:n}){var o;const r=((o=e.hooks)==null?void 0:o.some(c=>c.status==="error"))??!1,a=wa(e.status,t,r);return s.jsx(ie,{children:a&&s.jsx(Y.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:s.jsx(ff,{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 cn({part:e,sessionId:t,autoHide:n,expandToolCalls:r}){const a=e.ui?pf(e.toolName):void 0,o=s.jsx(hf,{part:e,autoHide:n,expandToolCalls:r});return!e.ui||e.status!=="complete"||!a?o:s.jsxs("div",{className:"flex flex-col gap-2",children:[o,s.jsx(uf,{sessionId:t,serverName:a,uri:e.ui.resourceUri})]})}function gf({part:e,autoHide:t,index:n}){const r=e.isStreaming?"running":"complete",a=wa(r,t,!1);return s.jsx(ie,{children:a&&s.jsx(Y.div,{exit:{height:0,opacity:0},transition:{duration:.3,ease:[.4,0,.2,1]},className:"overflow-hidden",children:s.jsx(id,{text:e.text,isStreaming:e.isStreaming??!1,elapsedMs:e.elapsedMs})},`thinking-${n}`)})}const xf=4,Os=2;function bf({children:e}){const[t,n]=i.useState(!1);if(e.length<=xf||t)return s.jsx(s.Fragment,{children:e});const r=e.length-Os;return s.jsxs(s.Fragment,{children:[e.slice(0,Os),s.jsx(jt,{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 yf=["z-30","-ml-2 z-20 opacity-70","-ml-2 z-10 opacity-45"];function kf({chips:e,expanded:t,controls:n,onExpand:r}){const a=Fe()??!1,o=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:G("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(Y.span,{animate:a?{rotate:0,scale:1}:di,transition:ui,className:"flex origin-bottom items-center",children:o.map((c,l)=>s.jsx("span",{"aria-hidden":"true",className:G("bg-card border-border text-3xs flex size-5 items-center justify-center rounded-full border leading-none",yf[l]),children:Cr[c.verb]},c.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 vf=new Set;function Sf(){const[e,t]=i.useState(vf),n=i.useCallback((a,o)=>o===!0&&!e.has(a),[e]),r=i.useCallback(a=>{t(o=>o.has(a)?o:new Set(o).add(a))},[]);return{shouldPulse:n,acknowledge:r}}function jf(e){const t=[...e].sort((n,r)=>n.lastSeq-r.lastSeq);return{visible:t.slice(-ms),absorbed:t.slice(0,Math.max(0,t.length-ms))}}function Cf(e){return e.map(t=>{const n=[`${t.chips.length} ${wr[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 wf({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:Cr[e]}),s.jsx("span",{className:"sr-only",children:wr[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 Nf({parts:e,sessionId:t,turnActive:n=!1}){const r=Fe()??!1,a=i.useMemo(()=>mi(e),[e]),o=Sf(),c=i.useId(),l=fi(i.useMemo(()=>pi(t,e),[t,e])),u=i.useCallback(h=>{if(h.pattern===!0)return;const g=se.getState();if(h.kind==="url"){const x={type:"url",url:h.fullTarget};g.openCanvasDocument(x),xn(g,"user",x);return}if(h.kind==="file"){const x={type:"file",sourcePath:h.fullTarget};g.openCanvasDocument(x),xn(g,"user",x)}},[]),d=i.useMemo(()=>hi(a),[a]),m=n||a.some(h=>h.live),{visible:p,absorbed:f}=i.useMemo(()=>jf(a),[a]);return a.length===0?null:s.jsxs("div",{"data-testid":"touch-chip-strip",className:"mt-2 flex flex-col gap-2",children:[s.jsx(ie,{initial:!1,mode:"wait",children:m?s.jsxs(Y.div,{"data-testid":"chip-live-row",role:"group","aria-label":"Latest activity",exit:r?{opacity:0}:{opacity:0,height:0},transition:r?us:ds,className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[f.length>0&&s.jsx(kf,{chips:f,expanded:l.expanded,controls:c,onExpand:l.toggleExpanded}),s.jsx(ie,{initial:!1,children:p.map(h=>s.jsx(gi,{chip:h,onOpen:u,animated:!0,pulseUpgrade:o.shouldPulse(h.key,h.upgraded),onUpgradeSeen:o.acknowledge},h.key))})]},"live"):s.jsxs(Y.div,{"data-testid":"chip-summary-line",role:"group","aria-label":Cf(d),initial:{opacity:0},animate:{opacity:1},transition:r?us:ds,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(wf,{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":l.expanded,"aria-controls":c,onClick:l.toggleExpanded,className:G("hover:text-foreground rounded-sm underline underline-offset-2","focus-visible:ring-ring outline-none focus-visible:ring-2"),children:l.expanded?"hide":"show all"})]},"settled")}),l.expanded&&s.jsx(xi,{id:c,chips:a,onOpen:u,verbFilter:l.verbFilter,onVerbFilterChange:l.setVerbFilter,order:l.order,onOrderChange:l.setOrder})]})}function Is(e){return e.type==="thinking"?!0:e.type==="tool_call"&&!e.interactiveType&&!ga(e.toolName)&&!bn(e.toolName)}function Tf({message:e}){const{sessionId:t,isStreaming:n,isLatestWidgetMessage:r,isFinalMessage:a,activeToolCallId:o,onToolRef:c,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f,textEffect:h,runtimeLabel:g,allowsDenyReason:x}=bi(),{expandToolCalls:y,autoHideToolCalls:v}=se(),S=e.parts??[],{sent:N}=Nr(t),C=i.useCallback(b=>{c==null||c(b)},[c]),T=i.useCallback(b=>{c==null||c(b)},[c]),w=Om(S.map(b=>b.type==="tool_call"&&bn(b.toolName)?{...b,interactiveType:void 0}:b));let E=-1;for(let b=S.length-1;b>=0;b--)if(S[b].type==="text"){E=b;break}function _(b,j){if(b.type==="text")return s.jsx("div",{className:"msg-prose",children:s.jsx(Mn,{content:b.text,isStreaming:n&&j===E,textEffect:h,sessionId:t,isLatestWidgetMessage:r})},`text-${j}`);if(b.type==="background_task")return s.jsx(yd,{part:b},b.taskId);if(b.type==="error"&&b.code===Tr)return s.jsx(Jm,{message:b.message},`unreadable-${j}`);if(b.type==="error")return s.jsx(qt,{message:b.message,category:b.category,details:b.details,code:b.code,reason:b.reason,at:e.timestamp,onRetry:a&&b.category!==void 0?d:void 0,onSigninComplete:m,onChooseModel:p,runtimeLabel:g,sessionId:t},`error-${j}`);if(b.type==="thinking")return s.jsx(gf,{part:b,autoHide:v,index:j},`thinking-${j}`);if(b.type==="elicitation")return s.jsx(Bm,{sessionId:t,interactionId:b.interactionId,serverName:b.serverName,message:b.message,mode:b.mode,url:b.url,requestedSchema:b.requestedSchema,status:b.status,action:b.action},`elicitation-${b.interactionId}`);if(b.type==="memory_recall")return s.jsx(cd,{mode:b.mode,memories:b.memories,isStreaming:b.isStreaming??!1},`memory-recall-${j}`);if(b.type==="permission_denied")return s.jsx(Am,{toolName:b.toolName,reasonType:b.reasonType,reason:b.reason,message:b.message,agentId:b.agentId},`permission-denied-${b.toolCallId}-${j}`);if(b.type==="model_substituted")return s.jsx(nf,{fromName:b.fromName,toName:b.toName},`model-substituted-${j}`);if(b.type==="compact_boundary")return s.jsx(fd,{trigger:b.trigger,preTokens:b.preTokens,postTokens:b.postTokens,failed:b.failed,error:b.error,requestedBy:b.requestedBy,contextPercent:b.contextPercent},`compact-boundary-${j}`);if(b.type==="capability_approval")return b.outcome==="timeout"?s.jsx(Zm,{title:yi(b.approval)},`capability-approval-${b.approval.approvalId}`):s.jsx(ki,{approval:b.approval},`capability-approval-${b.approval.approvalId}`);if(b.type==="mcp_signin")return s.jsx(tf,{part:b},`mcp-signin-${b.agentId}-${b.flowId}`);if(b.type==="image")return s.jsx(pd,{part:b},`image-${b.attachmentId}-${j}`);if(b.type!=="tool_call")return null;const k=b;if(k.interactiveType==="approval"&&k.status==="pending"){if(k.toolCallId===f)return s.jsx(js,{type:"approval",toolName:k.toolName,toolInput:k.input},k.toolCallId);const z=k.toolCallId===o;return s.jsx(Sa,{ref:z?C:void 0,sessionId:t,toolCallId:k.toolCallId,toolName:k.toolName,input:k.input||"",timeoutMs:k.timeoutMs,approvalStartedAt:k.approvalStartedAt,approvalRemainingMs:k.approvalRemainingMs,approvalParked:k.approvalParked,approvalTitle:k.approvalTitle,approvalDisplayName:k.approvalDisplayName,approvalDescription:k.approvalDescription,approvalBlockedPath:k.approvalBlockedPath,approvalDecisionReason:k.approvalDecisionReason,approvalHasSuggestions:k.approvalHasSuggestions,approvalAlwaysAllowScope:k.approvalAlwaysAllowScope,isActive:z,onDecided:u?()=>u(k.toolCallId):void 0,allowsDenyReason:x},k.toolCallId)}const M=w.get(j);if(M){if(M.leadIndex!==j)return null;const z=M.indices.map(O=>S[O]).filter(O=>O.type==="tool_call");return s.jsx(Xm,{outcome:M.outcome,reasonGiven:M.reasonGiven,members:z,lead:k,children:z.map(O=>s.jsx(cn,{part:O,sessionId:t,autoHide:v,expandToolCalls:y},O.toolCallId))},`approval-receipt-${k.toolCallId}`)}if(k.interactiveType==="question"){if(k.toolCallId===f)return s.jsx(js,{type:"question",toolName:k.toolName,toolInput:k.input},k.toolCallId);const z=k.toolCallId===o;return s.jsx(Rr,{ref:z?T:void 0,sessionId:t,toolCallId:k.toolCallId,questions:k.questions??[],answers:k.answers??(Im(k)?{}:void 0),outcome:Pm(k),result:k.result,isActive:z,focusedOptionIndex:z?l:-1,onDecided:u?O=>u(k.toolCallId,O):void 0},k.toolCallId)}return bn(k.toolName)?s.jsx(sd,{part:k,sent:N,...e.timestamp?{at:e.timestamp}:{},...t?{sessionId:t}:{}},k.toolCallId):ga(k.toolName)?s.jsx(Jd,{sessionId:t,input:k.input,result:k.result,fallback:s.jsx(cn,{part:k,sessionId:t,autoHide:v,expandToolCalls:y})},k.toolCallId):s.jsx(cn,{part:k,sessionId:t,autoHide:v,expandToolCalls:y},k.toolCallId)}const R=[];let I=[];for(let b=0;b<S.length;b++){const j=S[b];Is(j)?I.push(b):(I.length>0&&(R.push(I.length===1?{type:"single",index:I[0]}:{type:"run",indices:[...I]}),I=[]),R.push({type:"single",index:b}))}return I.length>0&&R.push(I.length===1?{type:"single",index:I[0]}:{type:"run",indices:[...I]}),s.jsxs(s.Fragment,{children:[R.map(b=>{if(b.type==="single"){const k=S[b.index];return Is(k)?s.jsx("div",{className:"my-3",children:_(k,b.index)},`spacer-${b.index}`):_(k,b.index)}const j=b.indices.map(k=>_(S[k],k));return s.jsx("div",{className:"my-3",children:s.jsx(bf,{children:j})},`run-${b.indices[0]}`)}),s.jsx(Nf,{parts:S,sessionId:t,turnActive:e._streaming===!0})]})}const Rf=/^Please read the following uploaded file\(s\):\n((?:- .+\n)+)\n?/,Af=/^[a-f0-9]{8}-/,Ef=new Set(["png","jpg","jpeg","gif","webp","svg"]);function _f(e){const t=e.match(Rf);if(!t)return{files:[],textContent:e};const r=t[1].split(`
42
+ `).filter(o=>o.startsWith("- ")).map(o=>{var m;const c=o.slice(2).trim(),u=(c.split("/").pop()??c).replace(Af,""),d=((m=u.split(".").pop())==null?void 0:m.toLowerCase())??"";return{path:c,displayName:u,isImage:Ef.has(d)}}),a=e.slice(t[0].length).trim();return{files:r,textContent:a}}function Mf(e){var n;switch(((n=e.split(".").pop())==null?void 0:n.toLowerCase())??""){case"txt":case"md":case"log":return vi;case"ts":case"tsx":case"js":case"jsx":case"json":case"py":case"rs":case"go":return Hl;case"csv":case"xls":case"xlsx":return Jl;case"png":case"jpg":case"jpeg":case"gif":case"webp":case"svg":return Xl;default:return Ar}}function Of({files:e}){const t=se(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 o=`/api/uploads/${encodeURIComponent(r)}?cwd=${encodeURIComponent(t??"")}`;return s.jsx(Y.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{duration:.15},children:s.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",children:s.jsx("img",{src:o,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 a=Mf(n.displayName);return s.jsxs(Y.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(a,{className:"text-muted-foreground size-3 shrink-0"}),s.jsx("span",{className:"max-w-40 truncate",children:n.displayName})]},n.path)})})}function If({message:e}){var c;const t=(c=Si())==null?void 0:c.sessionId,[n,r]=i.useState(!1),a=i.useMemo(()=>_f(e.content),[e.content]),o=i.useMemo(()=>Lu(e.content),[e.content]);if(o)return s.jsx($u,{action:o});if(e.chatMessages&&e.chatMessages.length>0)return s.jsx(Ju,{stamps:e.chatMessages,...t?{sessionId:t}:{}});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(jr,{content:e.content,toolName:""});if(e.messageType==="compaction"){const l=dd(e.compactMetadata),u=e.content.trim(),d=s.jsx("div",{className:"bg-border/40 h-px flex-1"});return u.length===0?s.jsxs("div",{"data-testid":"compaction-row",className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,s.jsx("span",{children:l}),d]}):s.jsxs("div",{className:"w-full","data-testid":"compaction-row",children:[s.jsxs("button",{onClick:()=>r(!n),className:"text-msg-compaction-fg flex w-full items-center gap-2 text-xs",children:[d,s.jsx(_n,{className:G("size-3 transition-transform duration-200",n&&"rotate-90")}),s.jsx("span",{children:l}),d]}),n&&s.jsx("div",{className:"text-msg-compaction-fg mt-2 text-xs whitespace-pre-wrap",children:e.content})]})}return s.jsxs("div",{children:[a.files.length>0&&s.jsx(Of,{files:a.files}),a.textContent&&s.jsx("div",{className:"break-words whitespace-pre-wrap",children:a.textContent})]})}function Pf({tasks:e,isCollapsed:t,onToggleCollapse:n}){const r=e.length,a=e.filter(l=>l.status==="completed").length,o=a===r&&r>0,c=r>0?a/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(_n,{className:"size-(--size-icon-xs) shrink-0"}):s.jsx(gt,{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 ${o?"bg-green-500":"bg-blue-500"}`,style:{width:`${c}%`}})}),s.jsxs("span",{className:"shrink-0 tabular-nums",children:[a,"/",r," ",r===1?"task":"tasks"]})]})}function Df({activeForm:e,isCollapsed:t}){return s.jsx(ie,{children:e&&!t&&s.jsxs(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,className:"mb-1 flex items-center gap-2 text-xs text-blue-400",children:[s.jsx(Pe,{size:"xs",className:"shrink-0"}),s.jsx("span",{className:"truncate",children:e})]})})}const $f={in_progress:"",pending:"waiting ",completed:"done "};function Ps({tasks:e,onScrollToTask:t}){return s.jsx(s.Fragment,{children:e.map((n,r)=>s.jsxs("span",{children:[s.jsx("button",{onClick:a=>{a.stopPropagation(),t(n.id)},className:"hover:text-foreground underline decoration-dotted",children:n.subject}),r<e.length-1&&", "]},n.id))})}function Ff({task:e,taskMap:t,statusSince:n,onScrollToTask:r}){var d,m;const a=Kr(n),o=$f[e.status]??"",c=((d=e.blockedBy)==null?void 0:d.map(p=>t.get(p)).filter(p=>p!=null))??[],l=((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:[o,a.formatted]},"time")),e.owner&&u.push(s.jsx("span",{children:e.owner},"owner")),c.length>0&&u.push(s.jsxs("span",{className:"inline-flex items-center gap-1",children:["← ",s.jsx(Ps,{tasks:c,onScrollToTask:r})]},"blocked-by")),l.length>0&&u.push(s.jsxs("span",{className:"inline-flex items-center gap-1",children:["→ ",s.jsx(Ps,{tasks:l,onScrollToTask:r})]},"blocks")),s.jsxs(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,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 Ds={in_progress:s.jsx(Pe,{size:"xs",className:"text-status-info shrink-0"}),pending:s.jsx(ji,{className:"text-muted-foreground size-(--size-icon-xs) shrink-0"}),completed:s.jsx(Sr,{className:"text-status-success size-(--size-icon-xs) shrink-0"})};function Lf({task:e,isBlocked:t,isExpanded:n,onToggleExpand:r,onHover:a,isHighlightedAsDep:o,isHighlightedAsDependent:c,taskMap:l,statusSince:u,isCelebrating:d,onCelebrationComplete:m,onScrollToTask:p}){const f=h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),r())};return s.jsxs(Y.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:()=>a(e.id),onMouseLeave:()=>a(null),className:G("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",o&&"border-l-2 border-blue-400 pl-1.5",c&&"border-l-2 border-amber-400 pl-1.5",!o&&!c&&"border-l-2 border-transparent pl-1.5"),children:[d&&s.jsx(Y.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(Y.span,{initial:{scale:1},animate:{scale:[1,1.4,1]},transition:{type:"spring",stiffness:400,damping:10},onAnimationComplete:()=>m==null?void 0:m(),children:Ds[e.status]}):Ds[e.status],s.jsx("span",{className:"truncate",children:e.subject})]}),s.jsx(ie,{children:n&&s.jsx(Ff,{task:e,taskMap:l,statusSince:u,onScrollToTask:p})})]})}function Uf(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(r=>{const a=t.get(r);return a&&a.status!=="completed"}):!1}const qf=10,zf="max-h-[30svh] sm:max-h-[40svh]";function Bf({tasks:e,taskMap:t,activeForm:n,isCollapsed:r,onToggleCollapse:a,celebratingTaskId:o,onCelebrationComplete:c,statusTimestamps:l}){const[u,d]=i.useState(null),[m,p]=i.useState(null),f=i.useCallback(y=>{d(v=>v===y?null:y)},[]),h=i.useCallback(y=>{const v=document.querySelector(`[data-task-id="${y}"]`);v&&(v.scrollIntoView({behavior:"smooth",block:"nearest"}),v.classList.add("bg-blue-500/10"),setTimeout(()=>v.classList.remove("bg-blue-500/10"),1e3))},[]);if(e.length===0)return null;const g=e.slice(0,qf),x=m?t.get(m):null;return s.jsxs("div",{className:"border-t px-4 py-2",children:[s.jsx(Df,{activeForm:n,isCollapsed:r}),s.jsx(Pf,{tasks:e,isCollapsed:r,onToggleCollapse:a}),s.jsx(ie,{children:!r&&s.jsx(Y.ul,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,className:G("mt-1 space-y-0.5 overflow-y-auto",zf),children:g.map(y=>{var w,E;const v=y.id===o&&y.status==="completed",S=Uf(y,t),N=l.get(y.id),C=((w=x==null?void 0:x.blockedBy)==null?void 0:w.includes(y.id))??!1,T=((E=x==null?void 0:x.blocks)==null?void 0:E.includes(y.id))??!1;return s.jsx(Lf,{task:y,isBlocked:S,isExpanded:u===y.id,onToggleExpand:()=>f(y.id),onHover:p,isHighlightedAsDep:C,isHighlightedAsDependent:T,taskMap:t,statusSince:(N==null?void 0:N.since)??null,isCelebrating:v,onCelebrationComplete:c,onScrollToTask:h},y.id)})})})]})}function Hf({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 Wf=350;function Gf({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 Kf({agent:e,index:t}){const n=i.useMemo(()=>({animationDelay:`${t*.09}s`}),[t]),[r,a]=i.useState(e.status==="running"?"running":"done"),o=i.useRef(e.status),c=i.useRef(null);return i.useEffect(()=>{const l=o.current;if(o.current=e.status,l==="running"&&e.status!=="running"){a("celebrating"),c.current=setTimeout(()=>a("done"),Wf);return}l!=="running"&&e.status==="running"&&(c.current&&clearTimeout(c.current),c.current=null,a("running"))},[e.status]),i.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),r==="done"?s.jsx("div",{className:"relative inline-flex",children:s.jsx(Gf,{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(Hf,{color:e.color}),r==="running"&&s.jsxs("div",{"data-testid":"agent-runner-tooltip",className:G("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 Qf({bashTasks:e}){const t=Fe(),n=e.filter(a=>a.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(ie,{mode:"popLayout",children:n.map(a=>s.jsxs(Y.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:[a.status==="running"&&!t&&s.jsx("span",{className:"task-dot-tasks absolute inset-0 rounded-full opacity-40",style:{backgroundColor:a.color,animation:"task-dot-tasks 2s ease-in-out infinite"}}),s.jsx("span",{className:"relative size-1.5 rounded-full",style:{backgroundColor:a.color}})]},a.taskId))}),s.jsxs("span",{className:"text-muted-foreground text-xs whitespace-nowrap",children:[r," task",r!==1?"s":""]})]})}const Vf=3e3;function Yf({taskType:e,onConfirm:t}){const[n,r]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),i.useEffect(()=>{if(n)return a.current=setTimeout(()=>{r(!1)},Vf),()=>{a.current&&clearTimeout(a.current)}},[n]);const o=i.useCallback(()=>{if(e==="bash"){t();return}n?(a.current&&clearTimeout(a.current),r(!1),t()):r(!0)},[e,n,t]),c=i.useCallback(l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),o())},[o]);return s.jsx("button",{onClick:o,onKeyDown:c,className:G("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(Ie,{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,a=e.status==="running";return s.jsxs("div",{className:G("flex items-center gap-2 rounded-md px-2 py-1 text-xs",a?"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"]}),a&&s.jsx(Yf,{taskType:e.taskType,onConfirm:t})]})}function Xf({tasks:e,ambientTasks:t=[],onStopTask:n}){return s.jsx(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,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 Tn=4;function Jf(e){return e==="stopped"?"complete":e}const Zf="relative after:absolute after:-inset-x-1 after:-inset-y-2.5 md:after:hidden",Na=[.16,1,.3,1],ep={width:{duration:.4,ease:Na},opacity:{duration:.25}};function tp({tasks:e,onStopTask:t}){const[n,r]=i.useState(!1),a=Fe(),{shown:o,ambient:c}=Gc(e),l=o.filter(y=>y.taskType==="agent"),u=o.filter(y=>y.taskType==="bash"),d=o.length,m=l.slice(0,Tn),p=l.length-Tn,f=l.reduce((y,v)=>y+(v.toolUses??0),0),h=Math.max(0,...o.map(y=>Math.round((y.durationMs??0)/1e3))),g=a?{duration:0}:{duration:.35,ease:Na},x=d>0;return s.jsx(ie,{children:(d>0||c.length>0)&&s.jsxs(Y.div,{...x?{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:[l.length>0&&s.jsx(np,{visibleAgents:m,overflowAgentCount:p,allAgentTasks:l}),l.length>0&&u.length>0&&s.jsx("div",{className:"bg-border h-4 w-px shrink-0"}),u.length>0&&s.jsx(Qf,{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(y=>!y),className:G("text-muted-foreground hover:text-foreground flex shrink-0 items-center gap-1 transition-colors duration-150",d>0?"ml-1":"ml-auto",Zf),"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(gt,{className:G("size-3.5 transition-transform duration-200",n&&"rotate-180")})]})]}),s.jsx(ie,{children:n&&s.jsx(Xf,{tasks:o,ambientTasks:c,onStopTask:t})})]},"background-task-bar")})}function np({visibleAgents:e,overflowAgentCount:t,allAgentTasks:n}){return s.jsxs("div",{className:"flex items-center gap-0",children:[s.jsx(ie,{mode:"popLayout",children:e.map((r,a)=>s.jsx(Y.div,{initial:{width:0,opacity:0},animate:{width:22,opacity:1},exit:{width:0,opacity:0},transition:ep,className:"shrink-0",children:s.jsx(Kf,{agent:{taskId:r.taskId,description:r.description??"",status:Jf(r.status),color:r.color,toolUses:r.toolUses,lastToolName:r.lastToolName,durationMs:r.durationMs,summary:r.summary},index:a})},r.taskId))}),t>0&&s.jsx(sp,{count:t,overflowTasks:n.slice(Tn)})]})}function sp({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:G("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 ln="after:absolute after:-inset-1 md:after:hidden";function rp({queue:e,editingId:t,onEdit:n,onRemove:r,onSend:a,onMoveUp:o,statusNote:c,onSwitchNow:l}){return e.length===0?null:s.jsxs(Y.div,{variants:$e,initial:"initial",animate:"animate",exit:"exit",transition:De,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:["· ",c]})]}),s.jsx("div",{className:"space-y-0.5",children:s.jsx(ie,{mode:"popLayout",children:e.map((u,d)=>s.jsx(Y.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:G("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(vn,{className:"size-3","aria-hidden":"true"}),s.jsx("span",{className:"sr-only",children:"Queued from another window"})]})]}),u.waiting!==void 0&&l!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:l,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:()=>o(u.id),className:G("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",ln),"aria-label":`Move queued message ${d+1} earlier`,children:s.jsx(Ci,{className:"size-3"})}),d>0&&s.jsx("button",{type:"button",onClick:()=>a(u.id),"aria-label":`Send queued message ${d+1} next`,className:G("focus-ring text-muted-foreground hover:text-foreground relative flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors",ln),children:s.jsx(wi,{className:"size-3"})}),s.jsx("button",{type:"button",onClick:()=>r(u.id),className:G("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",ln),"aria-label":`Remove queued message ${d+1}`,children:s.jsx(Ie,{className:"size-3"})})]})},u.id))})})]})}function ap({open:e,onOpenChange:t,queuedCount:n,onConfirm:r}){const a=n===1?"message":"messages";return s.jsx(Ni,{open:e,onOpenChange:t,children:s.jsxs(Ti,{children:[s.jsxs(Ri,{children:[s.jsxs(Ai,{children:["Stop, and put ",n," queued ",a," back?"]}),s.jsxs(Ei,{children:["The agent stops. Your ",a," ",n===1?"goes":"go"," back to the composer."]})]}),s.jsxs(_i,{children:[s.jsx(Mi,{children:"Keep going"}),s.jsx(Oi,{onClick:r,children:"Stop"})]})]})})}const op={initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4}},ip={duration:.3,ease:"easeInOut"};function cp({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(ie,{mode:"wait",children:s.jsx(Y.span,{variants:op,initial:"initial",animate:"animate",exit:"exit",transition:ip,className:"text-muted-foreground truncate text-sm",children:e},t)})})}function lp(e){const t=ge();return rt({queryKey:["workspace-for-session",e??null],queryFn:()=>t.resolveWorkspace(e),enabled:!!e}).data??null}async function Ta(e,t,n){try{return await e.runCommandIntent(t,"compact",n),!0}catch(r){const a=r.code==="SESSION_LOCKED";return Re.error(a?"Your agent is busy. Try again in a moment.":"Couldn’t compact the chat."),!1}}function Ra(e){const t=/^\/(\S+)([\s\S]*)$/.exec(e.trim());return t?{token:t[1],rest:t[2].trim()}:null}function up(e){const t=Ra(e);return t?Er(t.token)?!0:_r(e.trim())!==null:!1}function dp(e,t,n={}){const{mutateAsync:r}=Ii(e),a=ge(),{startFreshSession:o,compact:c}=n,[l,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=Ra(p),h=f?Er(f.token):null;if(f&&(h==null?void 0:h.fulfillment)==="runtime"&&c){if(!c.supported)return Re.error(`Compact isn’t available on ${c.runtimeLabel||"this agent"}`),{handled:!0,ran:!1};if(!t)return Re.error("No open chat to compact"),{handled:!0,ran:!1};const v=Ta(a,t,f.rest||void 0);return d(v),{handled:!0,ran:!0,confirmed:v}}const g=_r(p);if(!g)return{handled:!1};let x;return{handled:!0,ran:g.command.run(g.args,{sessionId:t,renameSession:v=>{t&&(x=r({sessionId:t,title:v}).then(()=>(Re.success(`Renamed chat to “${v}”`),!0),()=>!1),d(x))},notify:(v,S)=>S==="error"?Re.error(v):Re.success(v),startFreshSession:v=>o==null?void 0:o(v),focusUsageSurface:()=>yn.getState().reveal()}),...x?{confirmed:x}:{}}},[r,a,t,o,c,d]),commandPending:l>0}}function Aa(e,t){return{supported:(e==null?void 0:e.compact.supported)!==!1,runtimeLabel:t}}function Fs(e){const t=e.trim().toLowerCase();return t.startsWith("/")?t:`/${t}`}function mp(e){return Di.map(t=>{var r,a;const n=t.fulfillment==="runtime"&&((a=(r=e==null?void 0:e.commandIntents)==null?void 0:r[t.id])==null?void 0:a.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 fp(e,t){const n=Pi(),r=mp(t),a=fs.filter(l=>!(l.command!==void 0&&n.has(`/${l.command}`))),o=new Set(fs.map(l=>l.command)),c=e.filter(l=>{if(l.command!==void 0&&o.has(l.command))return!1;const u=[l.fullCommand,...l.aliases??[]].map(Fs);return l.command!==void 0&&u.push(Fs(l.command)),!u.some(d=>n.has(d))});return[...r,...a,...c]}const pp=3e4;function hp({percent:e,compactSupported:t,isStreaming:n}){return!(e===null||e<Kc||!t||n)}function gp({sessionId:e,percent:t,compactSupported:n,isStreaming:r}){const a=ge(),[o,c]=i.useState(!1),l=i.useRef(!1),u=i.useRef(null),d=i.useCallback(()=>{l.current=!1,c(!1),u.current!==null&&(clearTimeout(u.current),u.current=null)},[]);i.useEffect(()=>{r&&l.current&&d()},[r,d]),i.useEffect(()=>()=>{u.current!==null&&clearTimeout(u.current)},[]);const m=i.useCallback(()=>{l.current||!e||(l.current=!0,c(!0),u.current=setTimeout(()=>{u.current=null,l.current=!1,c(!1)},pp),Ta(a,e).then(p=>{p||d()}))},[e,a,d]);return{visible:hp({percent:t,compactSupported:n,isStreaming:r}),percent:t??0,pending:o,onCompact:m}}function xp({children:e,onSwitchAgent:t,onViewProfile:n,onNewSession:r}){return s.jsxs($i,{children:[s.jsx(Fi,{className:"min-w-0",children:e}),s.jsxs(Li,{className:"w-48",children:[s.jsxs(Jt,{onClick:t,children:[s.jsx(Ui,{className:"mr-2 size-4"}),"Switch agent"]}),s.jsx(ps,{}),s.jsxs(Jt,{onClick:n,children:[s.jsx(qi,{className:"mr-2 size-4"}),"View profile"]}),s.jsx(ps,{}),s.jsxs(Jt,{onClick:r,children:[s.jsx(lr,{className:"mr-2 size-4"}),"New chat"]})]})]})}function bp({agentName:e,agentColor:t,agentEmoji:n,agentPath:r,nameHidden:a}){const o=zi(r),{open:c}=Bi(),l=i.useCallback(()=>{r&&Hi.getState().openProfileDocked(r)},[r]),u=i.useCallback(()=>{if(o===void 0)return l();c(o)},[o,c,l]),d=i.useCallback(()=>{se.getState().openGlobalPaletteWithSearch("@")},[]),m=br(),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(xp,{onSwitchAgent:d,onViewProfile:u,onNewSession:p,children:s.jsx(hs,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,onClick:u,className:"max-w-full"})}):s.jsx(hs,{size:"xs",name:e,color:t,emoji:n,nameHidden:a,className:"max-w-full"})})}function yp({sessionId:e,account:t}){const[n,r]=i.useState(!1),[a,o]=i.useState(!1),c=i.useRef(null);return s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:c,className:"contents",children:s.jsx(Wi,{sessionId:e,account:t,open:n,onOpenChange:r,onContinue:()=>{r(!1),o(!0)}})}),s.jsx(ma,{open:a,onOpenChange:o,sessionId:e,account:t,onCloseAutoFocus:l=>{var d;const u=(d=c.current)==null?void 0:d.querySelector("button");u&&(l.preventDefault(),u.focus())}})]})}function kp({ctx:e,items:t}){return s.jsx("span",{className:"inline-flex min-w-0 items-center gap-2",children:t.map((n,r)=>{const a=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(Mr,{fallback:null,onError:o=>Ea(n,o),children:s.jsx(a,{...e})})})]},n.id)})})}function Ea(e,t){console.warn(`[extensions] ${e.extensionId}'s status-bar item "${e.id}" failed to draw and is hidden.`,t)}function vp({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(Mr,{fallback:null,onError:a=>Ea(n,a),children:s.jsx(r,{...e})})})]},n.id)})})}function Sp(e){const{costUsd:t,costBasis:n,...r}=e;return r}function jp(e){var m;const{sessionId:t,agent:n,status:r,runtimeChip:a,onUpdateSession:o}=e,c={},l=e.density!=="full";n.name&&n.color&&n.emoji&&(c.agent=s.jsx(bp,{agentName:n.name,agentColor:n.color,agentEmoji:n.emoji,agentPath:n.path,nameHidden:e.density==="avatar"})),r.cwd&&(c.cwd=s.jsx(Qc,{cwd:r.cwd})),e.gitStatus&&(c.git=s.jsx(sl,{data:e.gitStatus,workspace:e.workspace,compact:l})),a.runtime!==null&&(c.runtime=s.jsx(Vc,{runtime:a.runtime,model:a.model,onChangeRuntime:a.onChangeRuntime,canSelect:a.canSelect,account:a.account,compact:!0}));const u=Or(e.account);u!==null&&(c.account=s.jsx(yp,{sessionId:t,account:e.account})),e.extensions.items.length>0&&(c.extensions=s.jsx(kp,{ctx:e.extensions.ctx,items:e.extensions.items})),c.model=s.jsx(Yc,{model:r.model,onChangeModel:p=>o({model:p}),effort:r.effort,onChangeEffort:p=>o({effort:p??void 0}),fastMode:r.fastMode,onChangeFastMode:p=>o({fastMode:p}),disabled:!t,sessionId:t||void 0,runtime:a.runtime,onCredits:e.account.onCredits,compact:l}),(m=e.plan)!=null&&m.active||(c.permission=s.jsx(Xc,{mode:r.permissionMode,onChangeMode:e.onChangeMode,disabled:!t,pending:!r.permissionModeKnown,runtime:a.runtime,modelSupportsAutoMode:e.modelSupportsAutoMode,compact:l,makeDefault:e.makeDefault,onOpenChange:e.onPermissionPickerOpenChange})),e.plan&&(c.plan=s.jsx(Jc,{descriptor:e.plan.descriptor,active:e.plan.active,onToggle:e.plan.onToggle,disabled:!t})),e.contextPercent!==null&&(c.context=s.jsx(Zc,{percent:e.contextPercent,contextUsage:e.contextUsage,compact:e.compact,reading:e.contextReading}));const d=e.usage&&e.usageSource==="account"&&!e.supportsCostTracking?Sp(e.usage):e.usage;return d&&Gi(d)&&(e.supportsCostTracking||e.usageSource==="account")&&!el({account:u})&&(c.usage=s.jsx(Ki,{usage:d,observedAt:e.usageObservedAt,now:e.now})),e.liveSubagentCount>0&&(c.subagents=s.jsx(tl,{count:e.liveSubagentCount,running:e.runningSubagents,waiting:e.waitingOnSubagents})),c.connection=s.jsx(nl,{connectionState:e.connectionState,compact:l}),c}const Cp=[],wp="(max-width: 639px)";function Np({sessionId:e,sessionStatus:t,isStreaming:n,syncConnectionState:r,agentName:a,agentColor:o,agentEmoji:c,agentPath:l}){var _e,Le;const{ref:u,budget:d}=rl(),m=Ir(e),p=Wr(e,t,n,m.runtime),f=St(e||null),{pins:h}=al(),g=ol(e),x=il(e,f,g.usage),y=x.usage,v=kt(),S=new Date(v),N=Qi(y,x.observedAt,S),C=g.contextUsage,T=((_e=qn(e))==null?void 0:_e.contextUsage)??null,w=yn(ne=>ne.open),E=yn(ne=>ne.setOpen),{data:_}=cl(p.cwd),R=lp(p.cwd),{project:I}=Vi(p.cwd),b=Yi(wp),j=i.useMemo(()=>({sessionId:e,cwd:p.cwd,project:I,trackerItems:f.trackerItems,compact:b}),[e,p.cwd,I,f.trackerItems,b]),k=ll(j),{data:M}=Un(),z=ul(g.activeSubagents).running,O=g.runningSubagentCount??z.length,{data:$}=Ln({sessionId:e||void 0,runtime:m.runtime??void 0}),U=((Le=$==null?void 0:$.find(ne=>ne.value===p.model))==null?void 0:Le.supportsAutoMode)??!1,H=Ht(m.runtime),V=(H==null?void 0:H.permissionModes.values)??Cp,te=H==null?void 0:H.permissionModes.default,W=Xi(e),F=ee(ne=>ne.recordAutoConfirmed),[P,D]=i.useState(!1),Q=dl({sessionId:e,runtime:m.runtime,declaredModes:V,runtimeDefaultMode:te}),[ae,A]=i.useState(!1),B=i.useCallback(ne=>p.updateSession({permissionMode:ne}),[p]),X=i.useCallback(ne=>{if(ne==="auto"&&!W){D(!0);return}B(ne).then(ve=>{ve&&Q.offerFor(ne)})},[W,B,Q,D]),J=i.useCallback(()=>{F(e),B("auto"),D(!1)},[F,e,B,D]),Z=Ji(V),K=Z!==void 0&&p.permissionMode===Z.id,oe=Zi(e),de=ee(ne=>ne.recordModeBeforePlan),me=i.useCallback(ne=>{if(!Z)return;if(ne){de(e,p.permissionMode),B(Z.id);return}const ve=oe,Oe=ve!==void 0&&V.some(Ge=>Ge.id===ve)&&(ve!=="auto"||U)?ve:te;Oe&&B(Oe)},[Z,de,e,p,B,oe,V,U,te]),L=m.runtime?xt(m.runtime).label:"",pe=Aa(H==null?void 0:H.commandIntents,L),ce=g.contextPercent,je=gp({sessionId:e,percent:ce,compactSupported:pe.supported,isStreaming:n}),[ke,Ne]=i.useState(!1);ml(()=>Ne(ne=>!ne));const Ee={cwd:p.cwd,git:fl(_)?pl(_.branch,_.clean,_.detached):null,contextPercent:ce,connectionState:r,permissionMode:p.permissionMode,permissionDescriptor:(H==null?void 0:H.permissionModes.values.find(ne=>ne.id===p.permissionMode))??null,plan:Z?{active:K}:null,runtime:m.runtime===null||M===void 0?null:{isDefault:m.runtime===M.defaultRuntime,canSelect:m.canSelect},account:Or(f),usage:y,usageStale:N,subagentsInFlight:O,extensionItems:k.promotion},ue=je.visible&&d.density==="full",Me=je.visible&&!ue,be=jp({sessionId:e,agent:{name:a,color:o,emoji:c,path:l},status:p,onUpdateSession:p.updateSession,onChangeMode:X,makeDefault:ae?Q.line:null,onPermissionPickerOpenChange:A,modelSupportsAutoMode:U,plan:Z?{descriptor:Z,active:K,onToggle:me}:null,gitStatus:_,workspace:R,runtimeChip:m,account:f,contextPercent:ce,contextUsage:C,contextReading:T,compact:ue?{pending:je.pending,onCompact:je.onCompact}:null,usage:y,usageSource:x.source,usageObservedAt:x.observedAt,now:S,supportsCostTracking:(H==null?void 0:H.supportsCostTracking)??!0,runningSubagents:z,liveSubagentCount:O,waitingOnSubagents:g.lifecycle==="idle",connectionState:r,density:d.density,extensions:{ctx:j,items:k.visible}}),{items:Ce,overflow:xe}=hl(gl({ctx:Ee,pins:h,nodes:be}),d);return s.jsxs("div",{ref:u,className:"relative pt-2",children:[!ae&&Q.line&&s.jsx(xl,{...Q.line,placement:"overlay"}),s.jsx(bl,{items:Ce,trailing:s.jsx(yl,{open:ke,onOpenChange:Ne,diagnostics:g,controls:{plan:Z?{active:K,onToggle:me}:null},promotionContext:Ee,overflowCount:xe,addOns:k.visible.length>0?s.jsx(vp,{ctx:j,items:k.visible}):void 0,urgentAction:Me?{label:`Compact chat · ${je.percent}% full`,onAction:je.onCompact,pending:je.pending}:null})}),s.jsx(kl,{usage:y??null,accountUsage:x.accountUsage,observedAt:x.observedAt,open:w,onOpenChange:E}),s.jsx(vl,{open:P,onOpenChange:D,onConfirm:J})]})}const Tp=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 Rp(e){return e!==void 0&&e!=="completed"}function Ap(e){const t=Tp[e];return t!==void 0?t:Ep(e)}function Ep(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(o=>o.toLowerCase())].join(" ")}function _p({terminalReason:e}){const t=Rp(e),n=t?Ap(e):"";return s.jsx(ie,{children:t&&s.jsx(Y.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(ec,{variant:"secondary","aria-label":`Chat ended: ${n}`,children:n})},e)})}const Mp="The turn ended before completing.";function Op({sessionId:e,onRetry:t,onSigninComplete:n,onChooseModel:r}){var f;const a=Wt(e),o=((f=qn(e))==null?void 0:f.lastError)??null,c=(o==null?void 0:o.category)==="auth_error"||(o==null?void 0:o.category)==="model_unavailable"||(o==null?void 0:o.category)==="runtime_update_required",l=!c&&a?`${xt(a).label} stopped unexpectedly`:void 0,u=(o==null?void 0:o.message)??Mp,d=c?void 0:u,m=a?Pr(a):void 0,p=o?[o.code,o.details].filter(Boolean).join(`
43
+ `):void 0;return s.jsx(Y.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(qt,{category:(o==null?void 0:o.category)??"execution_error",heading:l,message:u,subtext:d,details:p||void 0,onRetry:t,onSigninComplete:n,onChooseModel:r,runtimeLabel:m,sessionId:e,...o!=null&&o.code?{code:o.code}:{},...o!=null&&o.reason?{reason:o.reason}:{}})})}const Ip=["Type @ to mention a file","Type / to browse commands","End a line with \\ to keep typing","Drop or paste files to attach"];function Pp(e,t,n){const r=i.useCallback(g=>{var S;if(!e||!t.current)return;const x=ee.getState(),y=(S=n.current)==null?void 0:S.get(e);if(y!==void 0&&x.getSession(e).mountGeneration!==y)return;const v=typeof g=="function"?g(x.getSession(e).messages):g;x.updateSession(e,{messages:v})},[e,t,n]),a=i.useCallback(g=>{e&&ee.getState().updateSession(e,{input:g})},[e]),o=i.useCallback(g=>{e&&ee.getState().updateSession(e,{status:g})},[e]),c=i.useCallback(g=>{e&&ee.getState().updateSession(e,{error:g})},[e]),l=i.useCallback(g=>{e&&ee.getState().updateSession(e,{sessionStatus:g})},[e]),u=i.useCallback(g=>{e&&ee.getState().updateSession(e,{estimatedTokens:g})},[e]),d=i.useCallback(g=>{e&&ee.getState().updateSession(e,{streamStartTime:g})},[e]),m=i.useCallback(g=>{e&&ee.getState().updateSession(e,{isTextStreaming:g})},[e]),p=i.useCallback(g=>{e&&ee.getState().updateSession(e,{systemStatus:g})},[e]),f=i.useCallback(g=>{e&&ee.getState().updateSession(e,{operationProgress:g})},[e]),h=i.useCallback(g=>{e&&ee.getState().updateSession(e,{promptSuggestions:g})},[e]);return{setMessages:r,setInput:a,setStatus:o,setError:c,setSessionStatus:l,setEstimatedTokens:u,setStreamStartTime:d,setIsTextStreaming:m,setSystemStatus:p,setOperationProgress:f,setPromptSuggestions:h}}function Wn(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(`
44
+ `),toolCalls:n}}function dt(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=Wn(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,...e.chatMessages&&e.chatMessages.length>0?{chatMessages:e.chatMessages}:{}}}function Dp(e,t,n){const r=new Set(e.map(d=>d.id)),a=e.filter(d=>d._streaming),o=a.find(d=>d.role==="user"),c=a.find(d=>d.role==="assistant"),l=[];let u=-1;for(let d=0;d<t.length;d++){const m=t[d];if(!r.has(m.id)){if(o&&m.role==="user"&&m.content===o.content){u=d,n(p=>p.map(f=>f.id===o.id?{...dt(m),_streaming:!1}:f));continue}if(c&&u>=0&&d===u+1&&m.role==="assistant"){const p=dt(m),f=new Set(p.parts.filter(x=>x.type==="background_task").map(x=>x.taskId)),h=c.parts.filter(x=>x.type==="background_task"&&!f.has(x.taskId)),g=h.length>0?[...p.parts,...h]:p.parts;n(x=>x.map(y=>y.id===c.id?{...p,parts:g,_streaming:!1}:y));continue}l.push(m)}}l.length>0&&n(d=>[...d,...l.map(dt)])}function $p({sessionId:e,sid:t,transport:n,sessionCwd:r,enableMessagePolling:a,isStreaming:o,setMessages:c}){const l=Qr(),u=r.cwd,d=i.useRef(u);i.useEffect(()=>{d.current=u},[u]);const m=rt({queryKey:["messages",e,u],queryFn:()=>n.getMessages(e,u??void 0),staleTime:Be.MESSAGE_STALE_TIME_MS,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>o||!a?!1:l?Be.ACTIVE_TAB_REFETCH_MS:Be.BACKGROUND_TAB_REFETCH_MS});return i.useEffect(()=>{const p=ee.getState();t&&p.updateSession(t,{historySeeded:!1}),p.getSession(e??"").status!=="streaming"&&c([])},[e,u,t,c]),i.useEffect(()=>{if(!m.data)return;const p=m.data.messages,f=ee.getState().getSession(t).historySeeded;if(!f&&p.length>0){if(o)return;t&&ee.getState().updateSession(t,{historySeeded:!0}),c(p.map(dt));return}f&&!o&&Dp(ee.getState().getSession(t).messages,p,c)},[m.data,o,t,c]),{historyQuery:m}}function _a(e,t){if(e===t)return;const{opened:n,counts:r,mergeUsage:a}=et.getState(),o=gs("session",e),c=Date.parse(n[o]??"");Number.isNaN(c)||a([{key:gs("session",t),lastUsedAt:c,useCount:r[o]??1}])}function Rn(e,t,n){e&&n.then(r=>{if(!r)return;const a=ee.getState();a.getSession(e).input.trim()===t.trim()&&a.updateSession(e,{input:""})},()=>{})}const Et=new Map;function Fp(e,t){const r=(Et.get(e)??Promise.resolve()).then(t),a=r.then(()=>{},()=>{});return Et.set(e,a),a.then(()=>{Et.get(e)===a&&Et.delete(e)}),r}const Xe=new Set;function Lp({sessionId:e,input:t,status:n,transport:r,queryClient:a,selectedCwd:o,onSessionIdChangeReplace:c,transformContent:l,launchRuntime:u,agentPath:d,agentLookupPending:m,agentLookupFailed:p,launchAccount:f,takeSeedContext:h,setInput:g,setError:x,tryNativeCommand:y}){const v=i.useRef(o);i.useEffect(()=>{v.current=o},[o]);const S=i.useRef(u);i.useEffect(()=>{S.current=u},[u]);const N=i.useRef(f);i.useEffect(()=>{N.current=f},[f]);const{data:C}=Un(),T=i.useRef(C==null?void 0:C.defaultRuntime);i.useEffect(()=>{T.current=C==null?void 0:C.defaultRuntime},[C==null?void 0:C.defaultRuntime]);const w=Sl(e,u),E=i.useRef(w.mode);i.useEffect(()=>{E.current=w.mode},[w.mode]);const _=i.useRef(l);i.useEffect(()=>{_.current=l});const R=i.useRef(h);i.useEffect(()=>{R.current=h});const I=i.useRef(c);i.useEffect(()=>{I.current=c});const b=i.useCallback(async(W,F,P={})=>{var oe,de,me;if(!P.kickoff){const L=y(W);if(L.handled){F&&L.ran&&(L.confirmed?Rn(e,W,L.confirmed):g(""));return}}const D=e,Q=P.cwd??v.current;x(null);const ae=a.getQueryData(qe.list(Q))??[],A=Zt(D),B=(A==null?void 0:A.draft)??!ae.some(L=>L.id===D),X=(A==null?void 0:A.draft)===!1?!1:B||Xe.has(D);if(X&&(m||p))return;X&&Xe.add(D),P.kickoff||(et.getState().recordOpened("session",D),Q&&et.getState().recordOpened("agent",Q)),lt.attachSession(D,Q);let J;try{J=!P.kickoff&&_.current?await _.current(W):W}catch(L){if(P.kickoff)throw L;x({heading:"Couldn’t send message",message:L.message||"The attachment didn’t upload. Try again.",retryable:!1});return}const Z=we.getState();if(B){const L=new Date().toISOString();xs(a,Q,{id:D,title:`Chat ${D.slice(0,8)}`,createdAt:L,updatedAt:L,permissionMode:((oe=a.getQueryData(qe.detail(D,Q)))==null?void 0:oe.permissionMode)??E.current??"default",runtime:S.current??T.current??"claude-code"})}const K=crypto.randomUUID();P.kickoff||Z.setOptimisticUserMessage(D,{id:K,content:W}),Z.setTriggerPending(D,!0),F&&g("");try{const L=bs(se.getState(),Q??null),{uiState:pe,commit:ce}=ys(D,L),ke={clientMessageId:K,context:pe?{uiState:pe}:void 0};X&&(ke.create=!0),X&&S.current&&(ke.runtime=S.current),X&&d&&(ke.agentPath=d),X&&N.current&&(ke.account=N.current);const Ne=se.getState().retryAccount;(Ne==null?void 0:Ne.sessionId)===D&&(ke.account=Ne.id,se.getState().setRetryAccount(null));const Ee=(de=R.current)==null?void 0:de.call(R);Ee&&(ke.seedContext=Ee);const{sessionId:ue}=await r.postMessage(D,J,Q??void 0,ke);if(Xe.delete(D),A){const be={...A,draft:!1};en(D,be),en(ue,be)}if(ce(ue),ue!==D){we.getState().migrateSessionContinuity(D,ue),se.getState().carryCanvasWritesAcross(D,ue),lt.attachSession(ue,Q),_a(D,ue),Je.getState().migrate(D,ue);const be=a.getQueryData(qe.list(Q))??[],Ce=be.find(xe=>xe.id===D);Ce&&!be.some(xe=>xe.id===ue)&&xs(a,Q,{...Ce,id:ue}),a.setQueryData(qe.list(Q),xe=>xe==null?void 0:xe.filter(_e=>_e.id!==D))}(me=I.current)==null||me.call(I,ue);const Me=ue;setTimeout(()=>{var xe;const be=ut.getState().rekeys[Me]??Me,Ce=we.getState().getSession(be);Ce.triggerPending&&((xe=Ce.status)==null?void 0:xe.lifecycle)!=="streaming"&&we.getState().setTriggerPending(be,!1)},Bt.TRIGGER_PENDING_TIMEOUT_MS)}catch(L){if(we.getState().setOptimisticUserMessage(D,null),we.getState().setTriggerPending(D,!1),P.kickoff)throw L;x({heading:"Couldn’t send message",message:L.message||"Couldn’t reach DorkOS. Try again.",retryable:!0})}},[e,r,a,g,x,y,d,m,p]),j=i.useCallback(async(W,F)=>{!W.trim()||n==="streaming"||await b(W.trim(),(F==null?void 0:F.clearInput)===!0,{...F!=null&&F.cwd?{cwd:F.cwd}:{}})},[n,b]),k=i.useCallback(()=>j(t,{clearInput:!0}),[t,j]),M=i.useCallback(async(W,F,P)=>{if(!e)return!1;const D=e,Q=v.current;x(null);const ae=(a.getQueryData(qe.list(Q))??[]).some(B=>B.id===D),A=Zt(D);return((A==null?void 0:A.draft)??!ae)&&Xe.add(D),Fp(D,async()=>{var X;let B;try{B=_.current?await _.current(W):W}catch(J){return x({heading:P,message:J.message||"The attachment didn’t upload. Try again.",retryable:!1}),!1}try{const J=bs(se.getState(),Q??null),{uiState:Z,commit:K}=ys(D,J),oe={...Z?{uiState:Z}:{},...F==="queue"?{queued:!0}:{}},de=Object.keys(oe).length>0?oe:void 0,me=((X=Zt(D))==null?void 0:X.draft)===!1?!1:Xe.has(D);if(me&&(m||p))return!1;const{sessionId:L}=await r.postMessage(D,B,Q??void 0,{context:de,disposition:F,...me?{create:!0,...S.current&&{runtime:S.current},...N.current&&{account:N.current},...d&&{agentPath:d}}:{}});return me&&Xe.delete(D),A&&en(L,{...A,draft:!1}),K(L),!0}catch(J){return x({heading:P,message:J.message||"Couldn’t reach DorkOS. Try again.",retryable:!1}),!1}})},[e,r,a,x,d,m,p]),z=i.useCallback(W=>M(W,"queue","Couldn’t queue message"),[M]),O=i.useCallback(W=>M(W,"steer","Couldn’t steer the agent"),[M]),$=i.useCallback(W=>M(W,"stage","Couldn’t add context"),[M]),U=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]),H=i.useCallback(async W=>{x(null),await b(W,!1)},[b,x]),V=i.useCallback(async(W,F)=>{await b(W,!1,{kickoff:!0,...F?{cwd:F}:{}})},[b]),te=i.useCallback((W,F)=>{},[]);return{handleSubmit:k,submitContent:j,enqueueContent:z,steerContent:O,addContextContent:$,stop:U,retryMessage:H,submitKickoff:V,markToolCallResponded:te}}const _t=new Set,Ls=new Set,Mt=new Set;function Up(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 qp({sessionId:e,cwd:t,status:n,messages:r,hydrated:a,canStart:o=!0,submitKickoff:c,submitContent:l}){const u=zt(e),d=r.length,m=r.some(Up);i.useEffect(()=>{if(!e)return;if(!u){t&&d===0&&n==="idle"&&Je.getState().claimByPath(t,e);return}if(u.fired||_t.has(e)||!o||d>0||n!=="idle")return;_t.add(e),Je.getState().markFired(e);const p=u.kind==="first-message";(p?l:c)(u.kickoffMessage,u.path||void 0).catch(h=>{console.warn("[chat] first-turn trigger failed for newborn session",e,h),Ls.has(e)?p||Je.getState().markGreetingFailed(e):(Ls.add(e),_t.delete(e),Je.getState().resetFired(e))})},[e,t,u,n,d,o,c,l]),i.useEffect(()=>{if(!(!e||!u)&&u.kind!=="first-message"&&!(!u.fired&&!_t.has(e))&&!u.greetingFailed){if(m){Mt.delete(e);return}if(n==="streaming"){Mt.add(e);return}a&&Mt.has(e)&&(Mt.delete(e),Je.getState().markGreetingFailed(e))}},[e,u,n,m,a])}function zp(e,t){return i.useEffect(()=>{tc(),lt.connectList(),e&&lt.attachSession(e,t)},[e,t]),i.useEffect(()=>()=>lt.releaseSession(),[]),Dr(e??"")}function Bp(e,t){const n=$r(e),r=i.useRef(t);i.useEffect(()=>{r.current=t}),i.useEffect(()=>{var a;!n||!e||(_a(e,n),(a=r.current)==null||a.call(r,n))},[n,e])}const Hp=500;function Wp(e,t,n){const r=i.useRef(new Map),[a,o]=i.useState(null),c=t.length>0?t[0].seq:-1;i.useEffect(()=>{const p=r.current;if(!e||!n){e&&p.delete(e),o(null);return}let f=p.get(e);(!f||f.turnSeq!==c)&&(f={turnSeq:c,anchor:Date.now()},p.set(e,f)),o(f.anchor)},[e,n,c]);const l=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&&l>p.tokens;if(m.current={sid:e,tokens:l},f&&!u&&d(!0),!f&&!u)return;const h=setTimeout(()=>d(!1),Hp);return()=>clearTimeout(h)},[e,l,u]),{streamStartTime:a,estimatedTokens:l,isTextStreaming:u}}function Gp(e,t,n,r){const a=i.useRef(new Map),o=i.useRef(r);i.useEffect(()=>{o.current=r}),i.useEffect(()=>{var d;if(!e)return;const c=a.current,l=n??0;let u=c.get(e);(!u||u.floor!==l)&&(u={floor:l,seen:l},c.set(e,u));for(const m of t)m.seq<=u.seen||(m.type==="todo_update"&&((d=o.current)==null||d.call(o,{action:m.action,task:m.task,tasks:m.tasks,previousId:m.previousId})),u.seen=m.seq)},[e,t,n])}function Kp(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 Qp(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 Vp(e,t){return((e==null?void 0:e.message)??null)===((t==null?void 0:t.message)??null)}function Yp(e,t,n,r){const a=i.useRef(new Map),o=i.useRef(new Map),c=i.useRef(n),l=i.useRef(r);i.useEffect(()=>{c.current=n,l.current=r}),i.useEffect(()=>{if(!e)return;const{operationProgress:u,systemStatus:d}=Kp(t),m=a.current.get(e)??null;Qp(m,u)||(c.current(u),a.current.set(e,u));const p=o.current.get(e)??null;Vp(p,d)||(l.current(d),o.current.set(e,d))},[e,t])}function Xp(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 Jp(e,t){const n=Xp(e,t.approval.approvalId);n?n.approval=t.approval:e.push({type:"capability_approval",approval:t.approval})}function Zp(e,t){const n=e.findIndex(a=>a.type==="capability_approval"&&a.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 eh(e,t,n){return e.findIndex(r=>r.type==="mcp_signin"&&r.agentId===t&&r.serverName===n&&r.outcome===void 0)}function th(e,t){const n={type:"mcp_signin",serverName:t.serverName,agentId:t.agentId,flowId:t.flowId,authorizeUrl:t.authorizeUrl,disclosure:t.disclosure},r=eh(e,t.agentId,t.serverName);r===-1?e.push(n):e[r]=n}function nh(e,t){const n=e.findIndex(a=>a.type==="mcp_signin"&&a.flowId===t.flowId);if(n===-1)return;const r=e[n];r.outcome=t.outcome,t.toolCount!==void 0&&(r.toolCount=t.toolCount)}const Us="__in_progress_turn__",sh="__optimistic_user__";function rh(e){return{id:sh,role:"user",content:e,parts:[{type:"text",text:e}],timestamp:"",_streaming:!0}}function ah(e){return{id:`steer-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0,...e.chatMessages&&e.chatMessages.length>0?{chatMessages:e.chatMessages}:{}}}function oh(e){return{id:`staged-${e.messageId}`,role:"user",content:e.content,parts:[{type:"text",text:e.content}],timestamp:"",_streaming:!0,_stagedContext:!0}}function Ae(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 Kt(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 ih(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 ch(e,t){Ma(e);const n=e[e.length-1];n&&n.type==="text"?n.text+=t.text:e.push({type:"text",text:t.text})}function lh(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 Ma(e){for(const t of e)t.type==="thinking"&&t.isStreaming&&(t.isStreaming=!1)}function uh(e,t,n){const r=Ae(e,t.toolCallId);if(r){t.input!==void 0&&(r.input=(r.input??"")+t.input);return}const a=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,...a&&a.length>0?{hooks:a}:{}})}function dh(e,t){const n=Ae(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 mh(e,t){const n=Ae(e,t.toolCallId);n&&(n.progressOutput=(n.progressOutput??"")+t.content)}function Oa(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=Ae(e,t.id);r?Object.assign(r,n):e.push({type:"tool_call",toolCallId:t.id,toolName:t.toolName,...n})}function Ia(e,t){const n=Ae(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 Pa(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=Kt(e,t.id);r?Object.assign(r,n):e.push({type:"elicitation",interactionId:t.id,...n})}function fh(e){return e==="denied"||e==="expired"||e==="cancelled"?"error":e==="answered"?"complete":"running"}function ph(e,t){const n=Ae(e,t.id);if(n){n.status==="pending"&&(n.status=fh(t.resolution),n.approvalRemainingMs=void 0);const a=nc(t);a&&(n.interactiveType="approval",n.approvalOutcome=a,n.approvalResolvedAt=t.at,t.reasonGiven===!0&&(n.approvalReasonGiven=!0),n.approvalStartedAt=t.startedAt??n.approvalStartedAt);const o=sc(t);o&&(n.questionOutcome=o)}const r=Kt(e,t.id);r&&r.status==="pending"&&(r.status="submitted",r.remainingMs=void 0)}function hh(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="tool_call"&&r.hooks){const a=r.hooks.find(o=>o.hookId===t);if(a)return a}}}function gh(e,t){for(const n of e.values()){const r=n.find(a=>a.hookId===t);if(r)return r}}function xh(e,t,n){const r=hh(e,t.hookId)??gh(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 a={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}:{}},o=Ae(e,t.toolCallId);o?o.hooks=[...o.hooks??[],a]:n.set(t.toolCallId,[...n.get(t.toolCallId)??[],a])}function bh(e,t){const n=e[0];if(n&&n.type==="memory_recall"){const o=new Set(n.memories.map(l=>l.path)),c=t.memories.filter(l=>!o.has(l.path));c.length>0&&(n.memories=[...n.memories,...c]);return}const r=new Set,a=t.memories.filter(o=>r.has(o.path)?!1:(r.add(o.path),!0));e.unshift({type:"memory_recall",mode:t.mode,memories:a,isStreaming:!0})}function yh(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 kh(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 vh(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 Sh(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 jh(e,t){Ma(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 Ch(e,t){const n=ih(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 wh={approval:"approval_required",question:"question_prompt",elicitation:"elicitation_prompt"};function Nh(e){const{type:t,...n}=e;return{...n,seq:0,type:wh[t]}}function Th(e,t){const n=Ae(e,t);return(n==null?void 0:n.interactiveType)!==void 0?!0:Kt(e,t)!==void 0}function Rh(e,t){switch(t.type){case"approval_required":Oa(e,t);break;case"question_prompt":Ia(e,t);break;case"elicitation_prompt":Pa(e,t);break}}function Ah(e,t,n){const r=Ae(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 a=Kt(e,t.id);a&&(a.startedAt=t.startedAt,a.remainingMs=t.remainingMs,t.timeoutMs!==void 0&&(a.timeoutMs=t.timeoutMs))}function Eh(e,t,n){for(const r of t){if(Th(e,r.id)){Ah(e,r,n.has(r.id));continue}Rh(e,Nh(r)),_h(e,r)}}function _h(e,t){if(t.parked!==!0)return;const n=Ae(e,t.id);n&&(n.approvalParked=!0)}function Mh(e){const t=new Set;for(const n of e)n.type==="interaction_resolved"&&t.add(n.id);return t}function An(e){const t=[],n=new Map;for(const r of e)switch(r.type){case"text_delta":ch(t,r);break;case"thinking_delta":lh(t,r);break;case"tool_call":uh(t,r,n);break;case"tool_result":dh(t,r);break;case"tool_progress":mh(t,r);break;case"approval_required":Oa(t,r);break;case"question_prompt":Ia(t,r);break;case"elicitation_prompt":Pa(t,r);break;case"capability_approval_required":Jp(t,r);break;case"capability_approval_resolved":Zp(t,r);break;case"mcp_signin_required":th(t,r);break;case"mcp_signin_resolved":nh(t,r);break;case"interaction_resolved":ph(t,r);break;case"subagent_update":Ch(t,r);break;case"hook_update":xh(t,r,n);break;case"memory_recall":bh(t,r);break;case"image_attachment":yh(t,r);break;case"compact_boundary":kh(t,r);break;case"permission_denied":vh(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":Sh(t,r);break;case"error":jh(t,r);break}return t}function qs(e,t){if(e.length===0)return null;const n=Wn(e);return{id:t,role:"assistant",content:n.content,toolCalls:n.toolCalls.length>0?n.toolCalls:[],parts:e,timestamp:"",_streaming:!0}}function Oh(e,t){const n=[];let r=[],a=0;for(const l of e){if(l.type!=="turn_input"&&l.type!=="context_staged"){r.push(l);continue}const u=An(r),d=qs(u,`${Us}-${a}`);d&&n.push(d),a+=1,n.push(l.type==="turn_input"?ah(l):oh(l)),r=[]}const o=An(r);Eh(o,t,Mh(e));const c=qs(o,Us);return c&&n.push(c),n}function Ih(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 Ph(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 Dh(e,t){const n=e.parts.filter(a=>a.type!=="tool_call"||!t.has(a.toolCallId)||!Ph(a));if(n.length===e.parts.length)return e;if(n.length===0)return null;const r=Wn(n);return{...e,parts:n,content:r.content,toolCalls:r.toolCalls.length>0?r.toolCalls:void 0}}function $h(e){let t=e.length;for(;t>0&&e[t-1].role==="assistant";)t-=1;return t}function Fh(e,t,n=[],r=null){const a=Oh(t,n),o=Ih(a),c=e.map(dt),l=o.size===0?c.length:$h(c),u=[];for(const[d,m]of c.entries()){const p=d<l?m:Dh(m,o);p&&u.push(p)}return r&&u.push(rh(r.content)),u.push(...a),u}function zs(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 Lh(e,t){return e.interactiveType==="approval"&&e.approvalOutcome===t.outcome&&e.approvalResolvedAt===t.resolvedAt&&e.approvalStartedAt===t.startedAt&&e.approvalReasonGiven===t.reasonGiven}function Uh(e,t){return t.size===0?e:e.map(n=>{if(!n.parts)return n;let r=!1;const a=n.parts.map(o=>{if(o.type!=="tool_call")return o;const c=t.get(o.toolCallId);return!c||Lh(o,c)?o:(r=!0,{...o,interactiveType:"approval",approvalOutcome:c.outcome,approvalResolvedAt:c.resolvedAt,approvalStartedAt:c.startedAt,approvalReasonGiven:c.reasonGiven,...c.displayName!==void 0?{approvalDisplayName:c.displayName}:{}})});return r?{...n,parts:a}:n})}function qh({sessionId:e,transport:t,sessionCwd:n,streamState:r,queryClient:a,onStreamingDone:o}){var S;const c=n.cwd,l=i.useRef(e),u=i.useRef(c),d=i.useRef(o);i.useEffect(()=>{l.current=e,u.current=c,d.current=o});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),x=((S=r.status)==null?void 0:S.lifecycle)??null,y=r.hydrationGeneration,v=r.userTurnCount;i.useEffect(()=>{var I,b,j;if(!e)return;const N=g.current.get(e);g.current.set(e,v),N!==void 0&&v!==N&&h.current.set(e,!1);const C=p.current.get(e);if(p.current.set(e,y),C!==y){m.current.set(e,x),x==="streaming"&&f.current.set(e,((I=we.getState().getSession(e).optimisticUserMessage)==null?void 0:I.id)??null);return}const T=m.current.get(e)??null;if(m.current.set(e,x),x==="streaming"&&T!=="streaming"&&f.current.set(e,((b=we.getState().getSession(e).optimisticUserMessage)==null?void 0:b.id)??null),!(T==="streaming"&&x!=="streaming"&&x!==null))return;const E=e,_=f.current.get(E)??null,R=zs(An(we.getState().getSession(E).inProgressTurn));t.getMessages(E,u.current??void 0).then(k=>{var H;const M=we.getState(),z=M.getSession(E),O=((H=z.status)==null?void 0:H.lifecycle)==="streaming",$=new Map([...zs(z.messages.flatMap(V=>V.parts??[])),...R]);M.setHistoryMessages(E,Uh(k.messages,$),{preserveInProgressTurn:O});const U=z.optimisticUserMessage;(U===null||U.id===_)&&M.setOptimisticUserMessage(E,null)}).catch(k=>{console.warn("[turn-end-reconcile] history reload failed",{sessionId:E,error:k instanceof Error?k.message:String(k)})}),a.invalidateQueries({queryKey:["tasks",E]}),h.current.get(E)!==!0&&(h.current.set(E,!0),(j=d.current)==null||j.call(d))},[e,x,y,v,t,a])}function zh(e){return e.streamReadyCursor!==null||e.messages.length>0||e.inProgressTurn.length>0||e.optimisticUserMessage!==null}function Da(e,t){const n=zh(e)?Fh(e.messages,e.inProgressTurn,e.pendingInteractions,e.optimisticUserMessage):t;return Dc(n)}function Bh(e,t={}){const n=ge(),r=Fn(),a=se(K=>K.selectedCwd),o=se(K=>K.enableMessagePolling),c=se(K=>K.pendingAccount),l=ra(),u=e??"",{messages:d,input:m,status:p,error:f,sessionStatus:h,systemStatus:g,operationProgress:x,promptSuggestions:y}=Fr(u),v=zp(e,l.cwd);Bp(e,t.onSessionIdChangeReplace);const S=rc(u),N=i.useMemo(()=>Da(v,d),[v,d]),C=jl(v,p),{streamStartTime:T,estimatedTokens:w,isTextStreaming:E}=Wp(e,v.inProgressTurn,C==="streaming");Gp(e,v.inProgressTurn,v.streamReadyCursor,t.onTaskEvent);const _=i.useRef(!0);i.useEffect(()=>(_.current=!0,()=>{_.current=!1}),[]);const R=i.useRef(new Map);i.useLayoutEffect(()=>{u&&(R.current.has(u)||R.current.set(u,ee.getState().getSession(u).mountGeneration))},[u]);const{setMessages:I,setInput:b,setError:j,setSystemStatus:k,setOperationProgress:M}=Pp(u,_,R);Yp(e,v.inProgressTurn,M,k),u&&ee.getState().initSession(u),i.useEffect(()=>{e&&(ee.getState().initSession(e),ee.getState().touchSession(e),R.current.set(e,ee.getState().getSession(e).mountGeneration))},[e]),i.useEffect(()=>{if(e)return ut.getState().clearUnseen(e),ut.subscribe(K=>{K.unseen[e]!==void 0&&ut.getState().clearUnseen(e)})},[e]);const{historyQuery:z}=$p({sessionId:e,sid:u,transport:n,sessionCwd:l,enableMessagePolling:o,isStreaming:C==="streaming",setMessages:I}),O=dp(a,e,{startFreshSession:t.startFreshSession,compact:t.compactIntent}),{handleSubmit:$,submitContent:U,enqueueContent:H,steerContent:V,addContextContent:te,stop:W,retryMessage:F,submitKickoff:P,markToolCallResponded:D}=Lp({sessionId:e,input:m,status:C,transport:n,queryClient:r,selectedCwd:a,onSessionIdChangeReplace:t.onSessionIdChangeReplace,transformContent:t.transformContent,launchRuntime:t.launchRuntime,agentPath:t.agentPath,agentLookupPending:t.agentLookupPending,agentLookupFailed:t.agentLookupFailed,launchAccount:(c==null?void 0:c.sessionId)===u?c.id:null,takeSeedContext:t.takeSeedContext,setInput:b,setError:j,tryNativeCommand:O.tryRun}),Q=v.streamReadyCursor!==null,ae=i.useCallback((K,oe)=>U(K,oe?{cwd:oe}:void 0),[U]);qp({sessionId:e,cwd:a,status:C,messages:N,hydrated:Q,canStart:!t.agentLookupPending&&!t.agentLookupFailed,submitKickoff:P,submitContent:ae}),qh({sessionId:e,transport:n,sessionCwd:l,streamState:v,queryClient:r,onStreamingDone:t.onStreamingDone});const A=z.isLoading&&N.length===0,B=i.useMemo(()=>N.flatMap(K=>K.toolCalls||[]).filter(K=>K.interactiveType&&K.status==="pending"),[N]),X=B[0]||null,J=X!==null,Z=(X==null?void 0:X.interactiveType)||null;return{messages:N,input:m,setInput:b,handleSubmit:$,submitContent:U,enqueueContent:H,steerContent:V,addContextContent:te,status:C,error:f,stop:W,retryMessage:F,isLoadingHistory:A,hydrated:Q,sessionStatus:h,streamStartTime:T,estimatedTokens:w,isTextStreaming:E,isWaitingForUser:J,waitingType:Z,activeInteraction:X,pendingInteractions:B,markToolCallResponded:D,systemStatus:g,operationProgress:x,promptSuggestions:y,syncConnectionState:S,tryNativeCommand:O.tryRun,commandPending:O.commandPending}}function Hh(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. ${Gh(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 Wh(e,t){return!Lr(e)||e.outcome==="not-running"&&t}function Gh(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 Kh(){const e=se(d=>d.showTaskCelebrations),[t,n]=i.useState(null),[r,a]=i.useState(null),o=i.useRef(null),c=i.useRef(!1);i.useEffect(()=>{const d=window.matchMedia("(prefers-reduced-motion: reduce)");c.current=d.matches;const m=p=>{c.current=p.matches};return d.addEventListener("change",m),()=>d.removeEventListener("change",m)},[]),Kl({timeoutMs:Ve.IDLE_TIMEOUT_MS,onIdle:i.useCallback(()=>{var d;(d=o.current)==null||d.setIdle(!0)},[]),onReturn:i.useCallback(()=>{var d,m;(d=o.current)==null||d.setIdle(!1),(m=o.current)==null||m.onUserReturn()},[])}),i.useEffect(()=>{const d=new lu({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=>{c.current&&m.level==="major"?n({...m,level:"mini"}):n(m),m.level==="mini"&&a(m.taskId)}});return o.current=d,()=>d.destroy()},[e]);const l=i.useCallback((d,m)=>{var p;d.action==="update"&&d.task.status==="completed"&&d.task.id&&((p=o.current)==null||p.onTaskCompleted(d.task.id,m))},[]),u=i.useCallback(()=>{n(null),a(null)},[]);return{handleTaskEvent:l,activeCelebration:t,celebratingTaskId:r,clearCelebration:u}}function un(){return{tasks:new Map,statusTimestamps:new Map,legacyCreateCount:0}}function Qh(e){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&r!==""&&(t[n]=r);return t}function dn(e,t,n){switch(t.action){case"snapshot":{e.tasks.clear(),e.statusTimestamps.clear();const r=t.tasks??[t.task];for(const a of r)e.tasks.set(a.id,a),e.statusTimestamps.set(a.id,{status:a.status,since:n});return}case"create":{const r=t.task.id||`legacy:${e.legacyCreateCount++}`,a=r===t.task.id?t.task:{...t.task,id:r};e.tasks.set(r,a),e.statusTimestamps.set(r,{status:a.status,since:n});return}case"id_assigned":{const r=t.previousId;if(!r)return;const a=e.tasks.get(r);if(!a)return;const o=t.task.id;e.tasks.delete(r),e.tasks.set(o,{...a,id:o});const c=e.statusTimestamps.get(r);e.statusTimestamps.delete(r),e.statusTimestamps.set(o,c??{status:a.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,...Qh(t.task)}),t.task.status&&t.task.status!==r.status&&e.statusTimestamps.set(t.task.id,{status:t.task.status,since:n});return}}}function Bs(e,t){var n;return(n=e.blockedBy)!=null&&n.length?e.blockedBy.some(r=>{const a=t.get(r);return a&&a.status!=="completed"}):!1}function Vh(e,t){return[...e].sort((n,r)=>{const a=n.status==="in_progress"?0:n.status==="pending"&&!Bs(n,t)?1:n.status==="pending"?2:3,o=r.status==="in_progress"?0:r.status==="pending"&&!Bs(r,t)?1:r.status==="pending"?2:3;return a-o})}const Yh=10;let Hs=0;function Ot(e){return e==="streaming"||e==="blocked"}function Xh(e,t=!1){const n=ge(),a=ra().cwd,o=se(R=>R.enableMessagePolling),c=Qr(),[l,u]=i.useState(un()),d=Ur(e??""),[m,p]=i.useState(()=>!Ot(d)),f=i.useRef([]),h=i.useRef(0),{data:g}=rt({queryKey:["tasks",e,a],queryFn:async()=>{const R=++Hs;return{...await n.getTasks(e,a??void 0),fetchOrder:R}},staleTime:3e4,refetchOnWindowFocus:!1,enabled:e!==null,refetchInterval:()=>!o||t?!1:c?Be.ACTIVE_TAB_REFETCH_MS:Be.BACKGROUND_TAB_REFETCH_MS}),x=i.useRef(null);i.useEffect(()=>{const R=`${e??""}::${a??""}`,I=x.current!==R;if(x.current=R,I&&(f.current=[],h.current=0,u(un())),!g||g.fetchOrder<=h.current)return;h.current=g.fetchOrder;const b=un();g.tasks.length>0&&dn(b,{action:"snapshot",task:g.tasks[0],tasks:g.tasks},Date.now()),f.current=f.current.filter(({order:j})=>j>g.fetchOrder);for(const{event:j,receivedAt:k}of f.current)dn(b,j,k);u(b)},[g,e,a]);const y=i.useCallback(R=>{const I=Date.now();R.action==="snapshot"&&(f.current=[]),f.current.push({order:++Hs,event:R,receivedAt:I}),u(b=>{const j={tasks:new Map(b.tasks),statusTimestamps:new Map(b.statusTimestamps),legacyCreateCount:b.legacyCreateCount};return dn(j,R,I),j})},[]),v=i.useRef(!1),S=i.useCallback(()=>{p(R=>(v.current=!R,!R))},[]),N=i.useRef(Ot(d));i.useEffect(()=>{const R=Ot(d);R!==N.current&&(N.current=R,R?v.current||p(!1):p(!0))},[d]);const C=i.useRef(null);i.useEffect(()=>{const R=`${e??""}::${a??""}`;if(C.current===R)return;C.current=R;const I=Ot(d);N.current=I,v.current=!1,p(!I)},[e,a,d]);const T=Array.from(l.tasks.values()),w=Vh(T,l.tasks),E=T.find(R=>R.status==="in_progress"),_=(E==null?void 0:E.activeForm)??null;return{tasks:w.slice(0,Yh),taskMap:l.tasks,activeForm:_,isCollapsed:m,toggleCollapse:S,handleTaskEvent:y,statusTimestamps:l.statusTimestamps}}function Jh(e){const t=i.useRef(null),[n,r]=i.useState(0),[a,o]=i.useState(!1),[c,l]=i.useState(0),u=i.useCallback(v=>{t.current=v,l(v&&"getOptionCount"in v?v.getOptionCount():0)},[]);i.useEffect(()=>{r(0),l(0),o(!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 v=t.current;v&&"approve"in v&&v.approve()},[]),p=i.useCallback(()=>{const v=t.current;v&&"alwaysAllow"in v&&v.alwaysAllow()},[]),f=i.useCallback(()=>{const v=t.current;v&&"deny"in v&&v.deny()},[]),h=i.useCallback(v=>{const S=t.current;S&&"toggleOption"in S&&(S.toggleOption(v),r(v),o(!0))},[]),g=i.useCallback(v=>{if(!a){o(!0);return}r(S=>{const N=t.current,C=N&&"getOptionCount"in N?N.getOptionCount():0;return C===0?S:v==="up"?S<=0?C-1:S-1:S>=C-1?0:S+1})},[a]),x=i.useCallback(v=>{const S=t.current;S&&"navigateQuestion"in S&&(S.navigateQuestion(v),r(0),o(!0),l(S.getOptionCount()))},[]),y=i.useCallback(()=>{const v=t.current;v&&"submit"in v&&v.submit()},[]);return Ql({activeInteraction:d,onApprove:m,onAlwaysAllow:p,onDeny:f,onToggleOption:h,onNavigateOption:g,onNavigateQuestion:x,onSubmit:y,optionCount:c,focusedIndex:n}),{handleToolRef:u,focusedOptionIndex:a?n:-1}}const mn={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}},Zh={match:!1,bucket:Number.POSITIVE_INFINITY,score:0};function Ws(e){return e.startsWith("/")?e.slice(1):e}function Gs(e,t){return e.bucket<t.bucket||e.bucket===t.bucket&&e.score>t.score}function eg(e,t){let n=Zh;const r=Dt(e,Ws(t.fullCommand));r.match&&r.tier&&(n={match:!0,bucket:mn.name[r.tier],score:r.score});for(const a of t.aliases??[]){const o=Dt(e,Ws(a));if(!o.match||!o.tier)continue;const c={bucket:mn.alias[o.tier],score:o.score};Gs(c,n)&&(n={match:!0,...c,matchedAlias:a})}if(t.description){const a=Dt(e,t.description);if(a.match&&a.tier){const o={bucket:mn.description[a.tier],score:a.score};Gs(o,n)&&(n={match:!0,...o})}}return n}function It(e,t,n){var o;const r=e.length;if(r===0)return 0;let a=(t%r+r)%r;for(let c=0;c<r;c++){if(!((o=e[a])!=null&&o.disabled))return a;a=(a+n+r)%r}return t}function tg({commands:e,input:t,cursorPos:n}){const[r,a]=i.useState(!1),[o,c]=i.useState(""),[l,u]=i.useState(-1),d=i.useMemo(()=>o?e.map(T=>({cmd:T,rank:eg(o,T)})).filter(T=>T.rank.match).sort((T,w)=>T.rank.bucket-w.rank.bucket||w.rank.score-T.rank.score).map(({cmd:T,rank:w})=>({...T,matchedAlias:w.matchedAlias})):e,[e,o]),[m,p]=i.useState(null),f=m!==null&&m.query===o&&m.open===r?m.index:It(d,0,1),h=d[f],g=d.length===0||h!==void 0&&!h.disabled?f:It(d,0,1),x=i.useCallback((T,w)=>{const _=T.slice(0,w).match(/(^|\s)\/([\w:-]*)$/);return _?(a(!0),c(_[2]),u((_.index??0)+_[1].length),!0):(a(!1),!1)},[]),y=i.useCallback(T=>{const w=t.slice(0,l),E=t.slice(l+1+o.length);return a(!1),w+T.fullCommand+(E.startsWith(" ")?"":" ")+E},[t,o,l]),v=i.useCallback(()=>{p({query:o,open:r,index:It(d,g+1,1)})},[d,g,o,r]),S=i.useCallback(()=>{p({query:o,open:r,index:It(d,g-1,-1)})},[d,g,o,r]),N=i.useCallback(()=>{const T=d[g];return T&&!T.disabled?y(T):(T||a(!1),null)},[d,g,y]),C=i.useCallback(()=>{a(!1),c("")},[]);return{showCommands:r,setShowCommands:a,commandQuery:o,selectedIndex:g,filteredCommands:d,slashTriggerPos:l,detectCommandTrigger:x,handleCommandSelect:y,handleArrowUp:S,handleArrowDown:v,handleKeyboardSelect:N,resetCommand:C}}function ng({fileEntries:e,input:t,cursorPos:n}){const[r,a]=i.useState(!1),[o,c]=i.useState(""),[l,u]=i.useState(0),[d,m]=i.useState(-1),p=i.useMemo(()=>r?o?e.map(S=>({...S,...Dt(o,S.path)})).filter(S=>S.match).sort((S,N)=>N.score-S.score).slice(0,50):e.slice(0,50).map(S=>({...S,indices:[]})):[],[e,o,r]);i.useEffect(()=>{u(0)},[o,r]),i.useEffect(()=>{p.length>0&&l>=p.length&&u(p.length-1)},[p.length,l]);const f=i.useCallback((S,N)=>{const T=S.slice(0,N).match(/(^|\s)@([\w./:-]*)$/);return T?(a(!0),c(T[2]),m((T.index??0)+T[1].length),!0):(a(!1),!1)},[]),h=i.useCallback(S=>{const N=t.slice(0,d),C=t.slice(d+1+o.length);if(S.isDirectory){const w=N+"@"+S.path+C,E=N.length+1+S.path.length;return c(S.path),u(0),{newValue:w,newCursorPos:E,keepOpen:!0}}const T=N+"@"+S.path+" "+C;return a(!1),{newValue:T,keepOpen:!1}},[t,d,o]),g=i.useCallback(()=>{u(S=>p.length===0?0:(S+1)%p.length)},[p.length]),x=i.useCallback(()=>{u(S=>p.length===0?0:(S-1+p.length)%p.length)},[p.length]),y=i.useCallback(()=>p.length>0&&l<p.length?h(p[l]):(a(!1),null),[p,l,h]),v=i.useCallback(()=>{a(!1),c("")},[]);return{showFiles:r,setShowFiles:a,fileQuery:o,fileSelectedIndex:l,filteredFiles:p,fileTriggerPos:d,detectFileTrigger:f,handleFileSelect:h,handleArrowUp:x,handleArrowDown:g,handleKeyboardSelect:y,resetFiles:v}}function sg({input:e,setInput:t,commands:n,fileEntries:r}){const[a,o]=i.useState(0),c=tg({commands:n,input:e,cursorPos:a}),l=ng({fileEntries:r,input:e,cursorPos:a}),u=i.useCallback((w,E)=>{if(l.detectFileTrigger(w,E)){c.setShowCommands(!1);return}if(c.detectCommandTrigger(w,E)){l.setShowFiles(!1);return}l.setShowFiles(!1),c.setShowCommands(!1)},[l,c]),d=i.useRef({value:e,cursor:0});i.useEffect(()=>{d.current.value=e},[e]);const m=i.useCallback(w=>{t(w),d.current={value:w,cursor:d.current.cursor||w.length},u(w,d.current.cursor)},[t,u]),p=i.useCallback(w=>{o(w),d.current={value:d.current.value,cursor:w},u(d.current.value,w)},[u]),f=i.useCallback(w=>{const E=c.handleCommandSelect(w);t(E)},[c,t]),h=i.useCallback(w=>{const E=l.handleFileSelect(w);t(E.newValue),E.newCursorPos!==void 0&&o(E.newCursorPos)},[l,t]),g=i.useCallback(()=>{l.showFiles?l.handleArrowDown():c.handleArrowDown()},[l,c]),x=i.useCallback(()=>{l.showFiles?l.handleArrowUp():c.handleArrowUp()},[l,c]),y=i.useCallback(()=>{if(l.showFiles){const w=l.handleKeyboardSelect();w&&(t(w.newValue),w.newCursorPos!==void 0&&o(w.newCursorPos))}else if(c.showCommands){const w=c.handleKeyboardSelect();w&&t(w)}},[l,c,t]),v=i.useCallback(()=>{c.setShowCommands(!1),l.setShowFiles(!1)},[c,l]),S=c.showCommands||l.showFiles,N=l.showFiles&&l.filteredFiles.length>0||c.showCommands&&c.filteredCommands.length>0,C=l.showFiles?"file-palette-listbox":c.showCommands?"command-palette-listbox":void 0,T=l.showFiles&&l.filteredFiles.length>0?`file-item-${l.fileSelectedIndex}`:c.showCommands&&c.filteredCommands.length>0?`command-item-${c.selectedIndex}`:void 0;return{commands:{show:c.showCommands,filtered:c.filteredCommands,selectedIndex:c.selectedIndex},files:{show:l.showFiles,filtered:l.filteredFiles,selectedIndex:l.fileSelectedIndex},isPaletteOpen:S,paletteHasResults:N,activeDescendantId:T,paletteListboxId:C,handleInputChange:m,handleCursorChange:p,handleArrowUp:x,handleArrowDown:g,handleKeyboardSelect:y,handleCommandSelect:f,handleFileSelect:h,dismissPalettes:v}}function rg(e,t,n,r){const a=se(u=>u.setIsStreaming),o=se(u=>u.setIsWaitingForUser),c=se(u=>u.setActiveForm),l=se(u=>u.setIsTextStreaming);i.useEffect(()=>(a(e==="streaming"),()=>a(!1)),[e,a]),i.useEffect(()=>(o(t),()=>o(!1)),[t,o]),i.useEffect(()=>(c(n),()=>c(null)),[n,c]),i.useEffect(()=>(l(r),()=>l(!1)),[r,l])}function ag(){const e=ge(),t=se(f=>f.selectedCwd),[n,r]=i.useState([]),a=i.useCallback(f=>{const h=f.map(g=>({id:crypto.randomUUID(),file:g,status:"pending",progress:0}));r(g=>[...g,...h])},[]),o=i.useCallback(f=>{r(h=>h.filter(g=>g.id!==f))},[]),c=i.useCallback(()=>{r([])},[]),l=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=ft({meta:{suppressErrorToast:!0},mutationFn:async f=>{if(!t)throw new Error("No working directory selected");r(y=>y.map(v=>f.some(S=>S.id===v.id)?{...v,status:"uploading"}:v));const h=y=>{r(v=>v.map(S=>S.status==="uploading"?{...S,progress:y.percentage}:S))},g=new AbortController;u.current=g;const x=f.map(y=>y.file);return e.uploadFiles(x,t,h,g.signal)},onSettled:()=>{u.current=null},onSuccess:(f,h)=>{r(g=>g.map(x=>{const y=h.findIndex(v=>v.id===x.id);return y===-1?x:{...x,status:"uploaded",progress:100,result:f[y]}}))},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(y=>y.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(y=>y.status==="uploaded"&&y.result).map(y=>y.result.savedPath),g=n.filter(y=>y.status==="pending");if(g.length===0)return h;const x=await d.mutateAsync(g);return[...h,...x.map(y=>y.savedPath)]},[n,d]);return{pendingFiles:n,addFiles:a,removeFile:o,retryFile:l,clearFiles:c,cancelUpload:m,uploadAndGetPaths:p,hasPendingFiles:n.length>0,hasFailedUpload:n.some(f=>f.status==="error"),isUploading:d.isPending}}const fn=new Set,pn=new Set;function og(e,t){return`${e}\0${t}`}function ig({sessionId:e,prompt:t,autoSend:n,input:r,setInput:a,messageCount:o,hydrated:c,status:l,submitBlocked:u=!1,submit:d,onSeeded:m,onConsumed:p}){const f=t!=null&&t.trim()?t:void 0,h=e&&f?og(e,f):null;i.useEffect(()=>{if(!(!h||!f)&&!fn.has(h)&&c){if(fn.add(h),r.length>0||o>0){pn.add(h),p==null||p();return}a(f),m==null||m(),n||p==null||p()}},[h,f,n,r,c,o,a,m,p]),i.useEffect(()=>{!h||!f||!n||pn.has(h)||fn.has(h)&&r===f&&(!c||o>0||l==="streaming"||u||(pn.add(h),p==null||p(),d()))},[h,f,n,r,c,o,l,u,d,p])}const Ks=ac-256,Qs=`
45
+ …(context truncated)`,Vs={"/":"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 cg(e){const t=`/${e.split("/").filter(Boolean)[0]??""}`;return Vs[e]??Vs[t]??`the ${e} page`}function lg(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 ${cg(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(`
46
+ `);return n.length<=Ks?n:n.slice(0,Ks-Qs.length)+Qs}const ug="dorkbot-help",Pt=new Set;function dg({sessionId:e,seed:t,messageCount:n,hydrated:r,onConsumed:a}){const o=t===ug&&e!==null,{data:c}=oc({enabled:o}),{data:l}=qr(),u=ut(ic(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:o,sessionId:e,messageCount:n}),p=i.useRef(a);return i.useEffect(()=>{const f=(l==null?void 0:l.latestVersion)??null,h=(l==null?void 0:l.version)??null;d.current={agentNames:((c==null?void 0:c.agents)??[]).map(g=>g.displayName??g.name),version:h,updateReady:f!==null&&h!==null&&cc(f,h),erroredSessionIds:u}},[c,l,u]),i.useEffect(()=>{m.current={armed:o,sessionId:e,messageCount:n},p.current=a},[o,e,n,a]),i.useEffect(()=>{!o||e===null||!r||n===0||Pt.has(e)||(Pt.add(e),a==null||a())},[o,e,r,n,a]),i.useCallback(()=>{var h;const f=m.current;if(!(!f.armed||f.sessionId===null)&&!(f.messageCount>0)&&!Pt.has(f.sessionId))return Pt.add(f.sessionId),(h=p.current)==null||h.call(p),lg({...d.current,originPath:lc()})},[])}function mg(e,t,n,r=!1){if(e!=="error"||t||r)return!1;let a=-1;for(let c=n.length-1;c>=0;c--)if(n[c].role==="user"){a=c;break}return!n.slice(a+1).some(c=>c.parts.some(l=>l.type==="error"&&l.code!==Tr))}const fg=4e3;function pg(e){const t=e.approvalDisplayName||st(e.toolName,e.input??"");return e.approvalOutcome==="allowed"?`Allowed ${t}. Recorded in the chat.`:e.approvalOutcome==="denied"?`Didn’t allow ${t}. Recorded in the chat.`:`${t} wasn’t answered in time, so it didn’t run. Recorded in the chat.`}function hg(e,t){const n=i.useRef(null),r=i.useRef(null),[a,o]=i.useState({text:"",nonce:0});return i.useEffect(()=>{r.current!==t&&(r.current=t,n.current=null);const c=e.filter(d=>d.type==="tool_call"&&d.approvalOutcome!==void 0);if(n.current===null){n.current=new Set(c.map(d=>d.toolCallId));return}const l=c.filter(d=>!n.current.has(d.toolCallId));if(l.length===0)return;for(const d of l)n.current.add(d.toolCallId);const u=l.length===1?pg(l[0]):`Answered ${l.length} permission requests. Recorded in the chat.`;o(d=>({text:u,nonce:d.nonce+1}))},[e,t]),i.useEffect(()=>{if(a.text==="")return;const c=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),fg);return()=>clearTimeout(c)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}const Ys=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],Xs=5e3,gg=1e3,xg=1500,bg=new Set;function yg(e){const t=i.useRef(new Map),n=zr({byTask:new Map,assigned:0}),[r,a]=i.useState(bg),[,o]=i.useState(0),c=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(c.values()).some(m=>m.taskType==="bash"&&m.status==="running"&&Date.now()-m.startedAt<Xs))return;const d=setInterval(()=>{o(m=>m+1)},gg);return()=>clearInterval(d)},[c]);const l=i.useRef(new Set);return i.useLayoutEffect(()=>{for(const[u,d]of c)t.current.get(u)==="running"&&d.status!=="running"&&!vs(d)&&a(p=>p.has(u)?p:new Set(p).add(u)),t.current.set(u,d.status)},[c]),i.useEffect(()=>{for(const u of r)l.current.has(u)||(l.current.add(u),setTimeout(()=>{l.current.delete(u),a(d=>{if(!d.has(u))return d;const m=new Set(d);return m.delete(u),m})},xg))},[r]),i.useMemo(()=>{const u=Date.now(),d=[],m=n.read();let p=m.assigned;for(const[f,h]of c){const g=h.status==="running",x=r.has(f);if(!g&&!x||h.taskType==="bash"&&g&&u-h.startedAt<Xs)continue;let y=m.byTask.get(f);y===void 0&&(y=Ys[p%Ys.length],p+=1,m.byTask.set(f,y),n.write({byTask:m.byTask,assigned:p})),d.push({taskId:h.taskId,taskType:h.taskType,status:h.status,color:y,startedAt:h.startedAt,description:h.description,toolUses:h.toolUses,lastToolName:h.lastToolName,durationMs:h.durationMs,summary:h.summary,command:h.command,ambient:vs(h)})}return d},[c,r,n])}const kg=new Set(["streaming","blocked"]);function vg(e,t){return e.length===0||e[0].waitingOn!==void 0||t&&kg.has(t)?e:e.slice(1)}function hn(e,t,n){return`${e} ${e===1?t:n}`}const Js={"delivery-owed":"a helper’s report","waiting-on-person":"your answer","timer-pending":"a reminder the agent set"},Sg={"timer-pending":"Switching now cancels the reminder."};function jg(e){const{agents:t,shells:n,other:r}=e.holding,a=[t>0?hn(t,"helper","helpers"):void 0,n>0?hn(n,"command","commands"):void 0,r>0?hn(r,"background job","background jobs"):void 0].filter(d=>d!==void 0),o=a.length===0?void 0:a.length===1?a[0]:`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`,c=e.pins,l=c.includes("cwd")&&e.targetFolderName?`moves to ${e.targetFolderName}`:c.includes("agentIdentity")?"switches agents":c.includes("systemPromptAppend")?"loads new instructions":"applies new settings";return{line:`${o!==void 0?`Held for ${o}.`:e.because!==void 0&&Js[e.because]!==void 0?`Held for ${Js[e.because]}.`:"Held until the agent is free."} Sending it ${l}.`,switchHint:o!==void 0?`Switching now stops ${o}.`:(e.because!==void 0?Sg[e.because]:void 0)??"Switching now stops what the agent is doing."}}const Cg={"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 wg(e){return e!=null&&e.degradedBecause?Cg[e.degradedBecause]:null}function Zs(e){return(e==null?void 0:e.code)==="QUEUED_MESSAGE_NOT_FOUND"}function Ng({sessionId:e,waiting:t,onEnqueue:n}){const r=ge(),a=uc(e??""),[o,c]=i.useState(null),l=i.useMemo(()=>t.map(C=>({id:C.id,content:C.content,mine:r.clientId===void 0||C.enqueuedBy===r.clientId,notice:wg(a[C.id]),...C.waitingOn?{waiting:jg(C.waitingOn)}:{}})),[t,a,r.clientId]),u=i.useMemo(()=>{if(o===null)return null;const C=l.findIndex(T=>T.id===o);return C===-1?null:C},[o,l]),d=i.useCallback(()=>{var C;if(e)return(C=we.getState().getSession(e).queuedMessages[0])==null?void 0:C.id},[e]),m=i.useCallback((C,T)=>{C().catch(w=>{Zs(w)||Re.error(T)})},[]),p=i.useCallback(async C=>{const T=C.trim();return!T||!e?!1:n(T)},[e,n]),f=i.useCallback((C,T)=>{e&&m(()=>r.updateQueuedMessage(e,C,{content:T}),"Couldn’t save that change")},[e,r,m]),h=i.useCallback(C=>{c(T=>T===C?null:T),e&&m(()=>r.removeQueuedMessage(e,C),"Couldn’t take that message off the queue")},[e,r,m]),g=i.useCallback((C,T)=>{if(!e)return;const w=E=>r.updateQueuedMessage(e,C,{move:{before:E}});m(async()=>{try{await w(T)}catch(E){if(!Zs(E))throw E;const _=d();if(_===void 0||_===C)return;await w(_)}},"Couldn’t move that message")},[e,r,m,d]),x=i.useCallback(C=>l.findIndex(w=>w.id===C)<=0?!1:(c(w=>w===C?null:w),g(C,l[0].id),!0),[l,g]),y=i.useCallback(C=>{const T=l.findIndex(w=>w.id===C);T<=0||g(C,l[T-1].id)},[l,g]),v=i.useCallback(C=>{const T=l.find(w=>w.id===C);return T?(c(C),T.content):null},[l]),S=i.useCallback(()=>{c(null)},[]),N=i.useCallback(C=>{o!==null&&(f(o,C),c(null))},[o,f]);return{queue:l,editingId:o,editingIndex:u,addToQueue:p,removeFromQueue:h,sendNow:x,moveUp:y,startEditing:v,cancelEditing:S,saveEditing:N,updateQueued:f}}function $a(e,t){return e===null?null:`${e} ${t??""}`}function Tg({input:e,setInput:t,sessionId:n,selectedCwd:r,waiting:a,onEnqueue:o,onSteer:c,onStage:l,tryNativeCommand:u,chatInputRef:d}){const m=i.useRef(""),p=i.useRef(null),f=$a(n,r);i.useEffect(()=>{m.current="",p.current=null},[f]);const h=Ng({sessionId:n,waiting:a,onEnqueue:o}),g=h.cancelEditing;i.useEffect(()=>{g()},[f,g]);const x=i.useCallback(()=>{const O=h.editingId;if(O===null)return;const $=e.trim();$&&(h.updateQueued(O,$),up($)&&Re.warning("Saved as a command. It runs instead of sending."))},[e,h]),y=ks(h.editingId),v=ks(h.updateQueued);i.useEffect(()=>{const O=n;return()=>{const $=y.read();if($===null||!O)return;const U=ee.getState(),H=U.getSession(O).input.trim();H&&v.read()($,H),U.updateSession(O,{input:m.current})}},[f]);const S=i.useCallback(O=>{const $=e.trim();if(!$)return;const U=u($);if(U.handled){if(!U.ran)return;U.confirmed?Rn(n,$,U.confirmed):t("");return}if(p.current===$)return;p.current=$,et.getState().recordOpened("session",n),r&&et.getState().recordOpened("agent",r);const H=O($);H.finally(()=>{p.current===$&&(p.current=null)}),Rn(n,$,H)},[e,r,n,t,u]),N=i.useCallback(()=>S(O=>h.addToQueue(O)),[S,h]),C=i.useCallback(()=>{c&&S(c)},[S,c]),T=i.useCallback(()=>{l&&S(l)},[S,l]),w=i.useCallback(O=>{var H,V;if(h.editingId===O){(H=d.current)==null||H.focus();return}const $=h.editingId!==null;$&&x();const U=h.startEditing(O);U!==null&&($||(m.current=e),t(U),(V=d.current)==null||V.focus())},[e,h,x,t,d]),E=i.useCallback(()=>{if(h.editingId===null)return;const O=e.trim();if(!O)return;const $=u(O);if($.handled){$.ran&&(h.cancelEditing(),t(m.current));return}h.saveEditing(O),t(m.current)},[e,h,t,u]),_=i.useCallback(()=>{h.cancelEditing(),t(m.current)},[h,t]),R=i.useCallback(O=>{h.editingId===O&&t(m.current),h.removeFromQueue(O)},[h,t]),I=i.useCallback(O=>{const $=h.editingId===O;$&&x(),h.sendNow(O)&&$&&t(m.current)},[h,x,t]),b=i.useCallback(O=>{h.moveUp(O)},[h]),j=i.useCallback(O=>{var H;const $=(H=h.queue[O])==null?void 0:H.id;if($!==void 0&&$===h.editingId)return;x();const U=$===void 0?null:h.startEditing($);if(U===null){h.cancelEditing(),t(m.current);return}t(U)},[h,x,t]),k=i.useCallback(()=>{x(),h.cancelEditing(),t(m.current)},[x,h,t]),M=i.useCallback(()=>{const{editingIndex:O,queue:$}=h;if(O===null){if($.length===0)return;m.current=e,j($.length-1)}else O>0?j(O-1):k()},[j,e,k,h]),z=i.useCallback(()=>{const{editingIndex:O,queue:$}=h;O!==null&&(O<$.length-1?j(O+1):k())},[j,k,h]);return{queue:h.queue,editingId:h.editingId,editingIndex:h.editingIndex,handleQueue:N,handleSteer:C,handleStage:T,handleQueueEdit:w,handleQueueSaveEdit:E,handleQueueCancelEdit:_,handleQueueRemove:R,handleQueueSend:I,handleQueueMoveUp:b,handleQueueNavigateUp:M,handleQueueNavigateDown:z,leaveQueueForStop:k}}const Rg=5e3,er=3;function Fa(){try{const e=Number(localStorage.getItem(Br.PLACEHOLDER_HINT_CYCLES));return Number.isFinite(e)&&e>0?e:0}catch{return 0}}function Ag(){const e=Fa()+1;try{localStorage.setItem(Br.PLACEHOLDER_HINT_CYCLES,String(e))}catch{}return e}function Eg(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 _g({defaultText:e,hints:t,enabled:n,intervalMs:r=Rg}){const[a]=i.useState(()=>t.length>0?Eg(t):[]),[o,c]=i.useState(()=>Fa()>=er),[l,u]=i.useState({key:0,hintIndex:-1}),d=i.useRef(0),m=i.useRef(0),p=i.useRef(!1);return i.useEffect(()=>{if(o||!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&&Ag()>=er&&c(!0),u({key:d.current,hintIndex:g})},r);return()=>clearInterval(h)},[n,t.length,r,o]),{text:l.hintIndex>=0?a[l.hintIndex]??e:e,key:l.key}}const gn=/[.!?…:](?=\s|$)|\n/g;function tr(e,t,n){const r=e.startsWith(t)?t.length:0,a=e.slice(0,r),o=e.slice(r);if(o.trim()==="")return{chunk:"",announced:a};if(n)return{chunk:o.trim(),announced:e};gn.lastIndex=0;let c=-1;for(let l=gn.exec(o);l!==null;l=gn.exec(o))c=l.index+l[0].length;return c===-1?{chunk:"",announced:a}:{chunk:o.slice(0,c).trim(),announced:e.slice(0,r+c)}}const Mg=1500,Og=4e3,Ig=400;function Pg({messageId:e,text:t,isStreaming:n}){const r=i.useRef(new Map),[a,o]=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<=Ig?"":t})}const l=r.current.get(e),{chunk:u,announced:d}=tr(t,l.announced,!1);l.announced=d,u!==""&&o(p=>({text:u,nonce:p.nonce+1}));const m=setTimeout(()=>{const p=tr(t,l.announced,!0);l.announced=p.announced,p.chunk!==""&&o(f=>({text:p.chunk,nonce:f.nonce+1}))},Mg);return()=>clearTimeout(m)},[e,t,n]),i.useEffect(()=>{if(a.text==="")return;const c=setTimeout(()=>o(l=>({text:"",nonce:l.nonce})),Og);return()=>clearTimeout(c)},[a]),a.text===""?"":a.nonce%2===0?a.text:`${a.text}​`}function Dg({onAllow:e,onNotNow:t}){return s.jsxs(dc,{"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(mc,{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(re,{variant:"ghost",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:t,children:"Not now"}),s.jsx(re,{variant:"outline",size:"sm",responsive:!1,className:"h-7 px-2 text-xs",onClick:e,children:"Turn on notifications"})]})]})}function $g(e){const t=$c(),{permission:n,request:r}=fc(),{prefs:a,setPrefs:o}=pc(),{data:c}=qr(),l=c!==void 0,[u,d]=i.useState(!1),m=hc()||n==="unsupported";i.useEffect(()=>{if(m||!e)return;const g=setTimeout(Fc,Lc);return()=>clearTimeout(g)},[m,e]);const p=i.useCallback(()=>{d(!0),r().then(()=>{o({browserPermissionPrimerDismissed:!0})})},[r,o]),f=i.useCallback(()=>{d(!0),o({browserPermissionPrimerDismissed:!0})},[o]);return{eligible:!m&&l&&t&&!u&&n==="default"&&!a.browserPermissionPrimerDismissed,allow:p,notNow:f}}function Fg({text:e,indices:t,startOffset:n=0}){const r=new Set(t.map(a=>a-n));return s.jsx(s.Fragment,{children:e.split("").map((a,o)=>r.has(o)?s.jsx("span",{className:"text-foreground font-semibold",children:a},o):s.jsx("span",{children:a},o))})}function Lg({filteredFiles:e,selectedIndex:t,onSelect:n}){return i.useEffect(()=>{const r=document.getElementById(`file-item-${t}`);r&&r.scrollIntoView({block:"nearest"})},[t]),s.jsx(Y.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,a)=>{const o=a===t,c=r.isDirectory?gc:Ar;return s.jsxs("div",{id:`file-item-${a}`,role:"option","aria-selected":o,"data-selected":o,tabIndex:o?0:-1,onClick:()=>n(r),onKeyDown:l=>{l.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(c,{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(Fg,{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 Ug(e){const t=ge();return rt({queryKey:["files",{cwd:e??null}],queryFn:()=>t.listFiles(e),enabled:!!e,staleTime:Be.FILES_STALE_TIME_MS,gcTime:Be.FILES_GC_TIME_MS})}const La={reactions:!1,threads:!1,runWith:!0,attachments:!0,mentions:!1,streamHealth:!1,presence:!1,turnStatus:!0,asks:!0};function nr(e){return e>=1e3?`~${(e/1e3).toFixed(1)}k tokens`:`~${Math.round(e)} tokens`}function qg(e){const{formatted:t}=Kr(e.status==="streaming"?e.streamStartTime:null),n=or(e.permissionMode),r=i.useRef(e.status),a=i.useRef(t),o=i.useRef(e.estimatedTokens),[c,l]=i.useState(!1);return i.useEffect(()=>{e.status==="streaming"&&(a.current=t,o.current=e.estimatedTokens,r.current!=="streaming"&&l(!1))},[e.status,t,e.estimatedTokens]),i.useEffect(()=>{r.current==="streaming"&&e.status==="idle"&&o.current>0&&l(!0),r.current=e.status},[e.status]),i.useEffect(()=>{if(!c)return;const u=setTimeout(()=>l(!1),Bt.TURN_COMPLETE_DISMISS_MS);return()=>clearTimeout(u)},[c]),Tl({capabilities:La,asks:e.asks??Gr,stalled:!1,presence:Rl,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:nr(e.estimatedTokens),isBypass:n,showComplete:c,lastElapsed:a.current,lastTokens:nr(o.current)}})}function zg(e){const{sessionId:t,placeholder:n,files:r}=e,a=i.useRef(e);i.useEffect(()=>{a.current=e});const o=i.useCallback(x=>a.current.files.addFiles(x),[]),c=i.useCallback(x=>a.current.files.removeFile(x),[]),l=i.useCallback(x=>a.current.files.retryFile(x),[]),u=i.useCallback(()=>a.current.files.cancelUpload(),[]),{pendingFiles:d,hasFailedUpload:m,isUploading:p}=r,f=i.useMemo(()=>({staged:d,add:o,remove:c,retry:l,cancel:u,hasFailed:m,isUploading:p,holdsSendWhileUploading:!0}),[d,m,p,o,c,l,u]),h=i.useCallback(async x=>{await a.current.submit(x.text)},[]),g=i.useCallback(async x=>{if(!await a.current.enqueue(x.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 chat, or start a new one."}:{},send:h,queue:g,attachments:f}),[t,n,f,h,g])}const Bg={duration:.16,delay:.08,ease:[.16,1,.3,1]},Hg={duration:0};function Wg({sessionId:e,activeInteraction:t,pendingApprovals:n,focusedOptionIndex:r,onToolRef:a,onToolDecided:o,queueDepth:c=0,allowsDenyReason:l=!0}){const u=g=>o(t.toolCallId,g),d=Fe(),{answerAll:m,isAnswering:p,error:f}=xc(),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(bc,{className:"mb-1.5",headline:`${n.length} tools are waiting on you`,items:n.map(g=>({id:g.toolCallId,line:st(g.toolName,g.input??"")})),onAllowAll:()=>void m(h,"allow"),onDenyAll:()=>void m(h,"deny"),isAnswering:p,error:f}),s.jsx(ie,{mode:"wait",initial:!1,children:s.jsx(Y.div,{initial:d?!1:{opacity:0,y:6},animate:{opacity:1,y:0},transition:d?Hg:Bg,children:t.interactiveType==="approval"?s.jsx(Sa,{ref:a,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:l}):t.interactiveType==="question"&&t.questions?s.jsx(Rr,{ref:a,sessionId:e,toolCallId:t.toolCallId,questions:t.questions,answers:t.answers,isActive:!0,focusedOptionIndex:r,onDecided:u}):null},t.toolCallId)}),c>0&&s.jsx("p",{className:"text-muted-foreground px-1 pt-2 text-xs",children:c===1?"1 message sends once you answer.":`${c} messages send once you answer.`})]})}function Gg({filteredCommands:e,selectedIndex:t,onSelect:n}){const r=i.useMemo(()=>{const a=[],o=new Map;let c=0;for(const l of e){const u=l.namespace??"built-in";o.has(u)||o.set(u,[]),o.get(u).push({cmd:l,index:c++})}for(const[l,u]of o)a.push({namespace:l,items:u});return a},[e]);return i.useEffect(()=>{const a=document.getElementById(`command-item-${t}`);a&&a.scrollIntoView({block:"nearest"})},[t]),s.jsx(Y.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:a=>a.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:a,items:o},c)=>s.jsxs("div",{children:[c>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:a}),o.map(({cmd:l,index:u})=>{const d=u===t,m=l.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(l)},onKeyDown:p=>{p.key==="Enter"&&!m&&n(l)},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:l.fullCommand}),l.argumentHint&&s.jsx("span",{className:"text-muted-foreground/50 shrink-0 font-mono text-xs",children:l.argumentHint}),m&&l.disabledReason?s.jsx("span",{className:"text-muted-foreground/70 text-2xs ml-auto shrink-0",children:l.disabledReason}):l.matchedAlias&&s.jsxs("span",{className:"text-muted-foreground/60 text-2xs ml-auto shrink-0 font-mono italic",children:["matched /",l.matchedAlias.replace(/^\//,"")]})]}),l.description&&s.jsx("p",{className:"text-muted-foreground mt-0.5 truncate text-xs leading-normal",children:l.description})]},l.fullCommand)})]},a))})})}function Kg(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 Qg({chatInputRef:e,input:t,autocomplete:n,steerContent:r,addContextContent:a,tryNativeCommand:o,commandPending:c,agentLookupPending:l=!1,agentLookupError:u=!1,status:d,stop:m,setInput:p,sessionId:f,sessionStatus:h,waiting:g,interaction:x,sync:y}){var Oe,Ge;const{active:v,pendingApprovals:S,focusedOptionIndex:N,onToolRef:C,onToolDecided:T}=x,w=d==="streaming",E=se(fe=>fe.isTextStreaming),[_]=Hr(),R=ge(),{data:I}=zn(_),b=yc(I??null,_??""),j=I?Bn(I):void 0,{target:k}=kc(),M=(k==null?void 0:k.placeholder)??"Send a message…",z=vc(f),O=um(f),$=Wt(f),U=Ht($),H=Sc(f),V=((U==null?void 0:U.supportsSteer)??!1)&&(H??!0),te=(U==null?void 0:U.supportsContextStaging)??!1,W=((Oe=U==null?void 0:U.permissionModes)==null?void 0:Oe.denyReason)??!0,F=i.useCallback(async fe=>{if((k==null?void 0:k.queue)===void 0)return!1;try{return await k.queue({text:fe}),!0}catch{return!1}},[k]),P=Tg({input:t,setInput:p,sessionId:f,selectedCwd:_,waiting:g,onEnqueue:F,onSteer:r,onStage:a,tryNativeCommand:o,chatInputRef:e}),[D,Q]=i.useState(null),ae=i.useRef(null),A=i.useCallback(fe=>{const he=ae.current;if(ae.current=null,fe.length===0)return;const Se=fe.map(Te=>he&&Te.id===he.id?he.content:Te.content).join(`
47
+
48
+ `),Ue=ee.getState().getSession(f).input.trim();p(Ue?`${Ue}
49
+
50
+ ${Se}`:Se)},[f,p]),[B,X]=i.useState(null),J=B===f&&w,Z=i.useRef(null),K=i.useCallback(()=>{Z.current=null,X(null)},[]);i.useEffect(()=>{w||K()},[w,f,K]);const oe=i.useRef(w);i.useEffect(()=>{oe.current=w},[w]);const de=P.leaveQueueForStop,me=i.useRef(P.editingId);i.useEffect(()=>{me.current=P.editingId},[P.editingId]);const L=i.useCallback(()=>{const fe=me.current;if(fe!==null){const he=ee.getState().getSession(f).input.trim();he&&(ae.current={id:fe,content:he}),de()}Z.current=f,X(f),m().then(he=>{A(he.cancelled),Wh(he.receipt,oe.current)&&K();const Se=Hh(he.receipt);Se.message!==null&&!Lr(he.receipt)&&(Se.isFailure?Re.error(Se.message):Re.warning(Se.message))}).catch(()=>{K()})},[f,m,A,K,de]),pe=i.useCallback(()=>{if(!(Z.current===f||J)){if(g.length===0){L();return}Q({sessionId:f,queuedCount:g.length})}},[f,J,g.length,L]),ce=i.useCallback(()=>{Z.current===f||J||(Q(null),L())},[f,J,L]);i.useEffect(()=>{(D==null?void 0:D.sessionId)===f&&g.length===0&&Q(null)},[D,f,g.length]);const{messages:je}=Fr(f),ke=Dr(f),Ne=i.useMemo(()=>Da(ke,je),[ke,je]),Ee=yg(Ne),ue=i.useCallback(async fe=>{if(f)try{await R.stopTask(f,fe)}catch(he){console.error("[chat] Failed to stop task:",he)}},[f,R]),Me=i.useCallback(()=>{f&&R.switchSessionProcess(f).catch(()=>{Re.error("Couldn’t switch. Try again.")})},[f,R]),be=i.useRef(t);i.useEffect(()=>{be.current=t});const Ce=i.useCallback(fe=>{var Te;const he=be.current,Se=he.length>0&&!/\s$/.test(he)?" ":"",Ue=`${he}${Se}${fe}`;p(Ue),(Te=e.current)==null||Te.focusAt(Ue.length)},[p,e]);i.useEffect(()=>El(Ce),[Ce]);const xe=!w&&P.editingIndex===null,_e=_g({defaultText:M,hints:Ip,enabled:xe&&t===""}),Le=jc(),ne=i.useCallback(()=>{n.dismissPalettes(),!(k===null||!k.canSend)&&k.send({text:t})},[n,k,t]),ve=i.useCallback(()=>{n.dismissPalettes(),P.handleQueue()},[n,P]),at=i.useCallback(()=>{n.dismissPalettes(),P.handleSteer()},[n,P]),ot=i.useCallback(()=>{n.dismissPalettes(),P.handleStage()},[n,P]);return s.jsx(ht.Composer,{className:"chat-input-container",onPathDropped:fe=>Ce(_l(fe)),inputRef:e,value:t,onChange:n.handleInputChange,onSubmit:ne,head:s.jsx(ie,{children:w&&s.jsx(nu,{color:b.color,isTextStreaming:E,edge:"top"})}),asks:v?s.jsx(Wg,{sessionId:f,activeInteraction:v,pendingApprovals:S,focusedOptionIndex:N,onToolRef:C,onToolDecided:T,queueDepth:P.queue.length,allowsDenyReason:W}):null,overlays:s.jsx(s.Fragment,{children:s.jsxs(ie,{children:[n.commands.show&&s.jsx(Gg,{filteredCommands:n.commands.filtered,selectedIndex:n.commands.selectedIndex,onSelect:n.handleCommandSelect}),n.files.show&&s.jsx(Lg,{filteredFiles:n.files.filtered,selectedIndex:n.files.selectedIndex,onSelect:n.handleFileSelect})]})}),queue:s.jsx(ie,{children:P.queue.length>0&&s.jsx(rp,{queue:P.queue,editingId:P.editingId,onEdit:P.handleQueueEdit,onRemove:P.handleQueueRemove,onSend:P.handleQueueSend,onMoveUp:P.handleQueueMoveUp,onSwitchNow:Me,statusNote:z?"Waiting for your answer above":((Ge=P.queue[0])==null?void 0:Ge.waiting)!==void 0?"Sending when the agent is free":"Sending one at a time as the agent finishes"})}),aboveInput:s.jsx(tp,{tasks:Ee,onStopTask:ue}),footer:s.jsx(ht.Footer,{asChild:!0,children:s.jsx(Np,{sessionId:f,sessionStatus:h,isStreaming:w,syncConnectionState:y.connectionState,agentName:j,agentColor:b.color,agentEmoji:b.emoji,agentPath:_??void 0})}),input:{isStreaming:w,commandPending:c,...l||u?{canSubmit:!1,canSubmitReason:u?"Check this folder again before you start.":"Checking this folder…"}:{},...O.canSubmit?{}:{canSubmit:!1},onStop:pe,stopPending:J,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:Le,editingQueueItem:P.editingIndex!==null,...P.editingIndex===null?{}:{editingPosition:P.editingIndex+1},queueDepth:P.queue.length,onQueue:ve,...V?{onSteer:at}:{},...te?{onStage:ot}:{},onSaveEdit:P.handleQueueSaveEdit,onCancelEdit:P.handleQueueCancelEdit,onQueueNavigateUp:P.handleQueueNavigateUp,onQueueNavigateDown:P.handleQueueNavigateDown,queueHasItems:P.queue.length>0,contextKey:$a(f,_)??void 0,placeholder:O.placeholder??Kg(P.editingIndex,w,P.queue.length,M),placeholderOverlay:xe&&O.canSubmit?s.jsx(cp,{text:_e.text,animationKey:_e.key}):null},children:s.jsx(ap,{open:(D==null?void 0:D.sessionId)===f,onOpenChange:fe=>{fe||Q(null)},queuedCount:(D==null?void 0:D.queuedCount)??0,onConfirm:ce})})}const Vg=e=>{const t=e;return t.role==="user"?s.jsx(If,{message:t}):s.jsx(Tf,{message:t})};function Yg({message:e,grouping:t,author:n,sessionId:r,isNew:a=!1,isStreaming:o=!1,isLatestWidgetMessage:c=!0,isFinalMessage:l=!0,activeToolCallId:u=null,onToolRef:d,focusedOptionIndex:m=-1,onToolDecided:p,onRetry:f,onSigninComplete:h,onChooseModel:g,inputZoneToolCallId:x=null,textEffect:y,runtimeLabel:v,allowsDenyReason:S,feedPosition:N}){var $;const C=i.useId(),T=`${C}-author`,w=`${C}-content`,E=i.useRef(null),_=t.position==="first"||t.position==="only",R=e.role==="user",I=R&&e.messageType!=="local_command_output",b=R?($=e.chatMessages)==null?void 0:$[0]:void 0,j=I&&b===void 0&&e.messageType!=="command"&&e.messageType!=="compaction"&&e.content.trim().length>0,k=e.timestamp?kn(e.timestamp):"",M=k.length>0,z=M?e.timestamp:void 0,O=i.useCallback(()=>{var U;return(U=E.current)==null?void 0:U.focus()},[]);return s.jsx(Cc,{value:{sessionId:r,isStreaming:o,isLatestWidgetMessage:c,isFinalMessage:l,activeToolCallId:u,onToolRef:d,focusedOptionIndex:m,onToolDecided:p,onRetry:f,onSigninComplete:h,onChooseModel:g,inputZoneToolCallId:x,textEffect:y,runtimeLabel:v,allowsDenyReason:S},children:s.jsxs(Ye.Root,{ref:E,role:I?"user":"assistant",position:t.position,isNew:a,"data-testid":"message-item","data-role":e.role,..._?{"aria-labelledby":T}:{"aria-label":M?`${n.displayName}, ${k}`:n.displayName},"aria-describedby":w,...Pl(N),children:[s.jsx(Ye.Gutter,{author:n,at:z}),s.jsxs(Ye.Body,{children:[s.jsx(Ye.Author,{id:T,author:n,at:z,...b?{mark:s.jsx(la,{stamp:b}),className:"flex-wrap gap-y-0.5"}:{}}),s.jsx(Ye.Content,{id:w,children:Vg(e,{rowId:e.id})}),j&&s.jsx(Ye.Actions,{runWith:{prompt:e.content,sessionId:r},onExit:O})]})]})})}const sr="Conversation",Xg=[];function Jg(e){for(let t=e.length-1;t>=0;t--)if(e[t].content.includes(wc))return t;return-1}function Zg({messages:e,sessionId:t,isLoadingHistory:n=!1,hydrated:r=!1,isTextStreaming:a=!1,activeToolCallId:o=null,onToolRef:c,focusedOptionIndex:l=-1,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f=null,textEffect:h,runtimeLabel:g,allowsDenyReason:x,landOnRow:y,foldFirstPrompt:v=!1}){const{stops:S}=Nr(t),N=i.useMemo(()=>Vu(e,S),[e,S]),C=i.useMemo(()=>{let A=0;return N.map(B=>B._chatStop?-1:A++)},[N]),T=zr(null);T.read()===null&&e.length>0&&T.write(e.length);const w=i.useMemo(()=>Jg(N),[N]),E=i.useMemo(()=>v?N.findIndex(A=>A.role==="user"&&A.messageType===void 0&&!A._stagedContext&&!A._chatStop):-1,[v,N]),_=zt(t),R=se(A=>A.selectedCwd),I=Wt(t),{data:b}=zn(R),j=i.useMemo(()=>({agent:b?{id:b.id,displayName:Bn(b),...ir(b)}:null,runtime:I}),[b,I]),k=e[e.length-1],M=(k==null?void 0:k.role)==="assistant"?k:void 0,z=Pg({messageId:M==null?void 0:M.id,text:(M==null?void 0:M.content)??"",isStreaming:M!==void 0&&a}),O=hg((k==null?void 0:k.parts)??Xg,t),{lastSeenMessageId:$,unreadFromStart:U,markSeen:H,isHydrated:V}=yu(t,e),[te,W]=i.useState(()=>Date.now()),F=i.useRef(null);i.useLayoutEffect(()=>{const A=Date.now(),B=new Date(A).toDateString();if(F.current===null){F.current=B;return}F.current!==B&&(F.current=B,W(A))},[N]);const P=i.useMemo(()=>ku(N,{resolveAuthor:A=>qc(A,j),now:te,lastSeenMessageId:$,unreadFromStart:U}),[N,j,te,$,U]),D=i.useMemo(()=>P.map(A=>A.kind==="day-divider"?{kind:"day-divider",id:A.key,label:A.label}:A.kind==="unread-divider"?{kind:"unread-divider",id:A.key}:{kind:"message",id:A.key,payload:A.message,grouping:A.grouping,author:A.author,at:A.message.timestamp}),[P]),Q=i.useCallback((A,B)=>{var pe,ce;const X=P[B.index];if(X.kind==="day-divider")return s.jsx(Dl,{label:X.label});if(X.kind==="unread-divider")return s.jsx($l,{});const{message:J,messageIndex:Z}=X;if(J._stagedContext)return s.jsx(hd,{content:J.content});if(J._chatStop)return s.jsx("div",{className:"px-4 py-1",children:s.jsx(rd,{notice:J._chatStop})});if(Z===E)return s.jsx(Pu,{content:((ce=(pe=J.chatMessages)==null?void 0:pe[0])==null?void 0:ce.text)??J.content});const K=C[Z]??Z,oe=K===e.length-1,de=oe&&J.role==="assistant",me=w===-1||Z>=w,L=T.read();return s.jsx(Yg,{message:J,grouping:X.grouping,author:X.author,sessionId:t,isNew:L!==null&&K>=L,isStreaming:de&&a,isLatestWidgetMessage:me,isFinalMessage:oe,activeToolCallId:o,onToolRef:c,focusedOptionIndex:l,onToolDecided:u,onRetry:d,onSigninComplete:m,onChooseModel:p,inputZoneToolCallId:f,textEffect:h,runtimeLabel:g,allowsDenyReason:x,feedPosition:{index:K+1,total:e.length}})},[P,e.length,C,w,E,t,T,a,o,c,l,u,d,m,p,f,h,g,x]),ae=_&&_.kind!=="first-message"&&_.fired&&!_.greetingFailed&&r?_:null;return s.jsx(ht.Timeline,{conversationId:t,label:sr,rows:D,renderRow:Q,landOn:"unread",landingReady:V,...y===void 0?{}:{landOnRow:y},onReachedBottom:H,transcriptAnnouncement:z,approvalAnnouncement:O,className:"pt-12 [--conversation-thumb-top:3rem]",loading:n?s.jsx(Al,{label:sr,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(Uc,{}),"Loading chat…"]})}):void 0,empty:s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx(Ru,{birthRecord:_,firstLightRecord:ae})}),"data-testid":"message-list",feedTestId:"transcript-feed"})}function ex({sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:r=!1,launchSeed:a,onLaunchConsumed:o,landOnRow:c}){var ts,ns,ss;const[,l]=vt(),u=Fn(),d=i.useRef(null),m=i.useRef(null),p=i.useCallback(()=>{var q,ye;(ye=(q=m.current)==null?void 0:q.querySelector('[data-testid="model-config-trigger"]'))==null||ye.click()},[]),f=Xh(e),h=Nc(e??""),g=Kh(),{play:x}=zc(),[y]=Hr(),{data:v,isPending:S,isError:N,refetch:C}=zn(y),{sessions:T}=En(),w=e!==null&&!T.some(q=>q.id===e),E=Tc(e),_=ag(),R=i.useCallback(async q=>{let ye=q;if(_.hasPendingFiles){const Ke=await _.uploadAndGetPaths(),rs=y?Ke.map(wt=>wt.startsWith(y)?wt.slice(y.length).replace(/^\//,""):wt):Ke;rs.length>0&&(ye=`Please read the following uploaded file(s):
51
+ ${rs.map(Za=>`- ${Za}`).join(`
52
+ `)}
53
+
54
+ ${ye}`),_.clearFiles()}return ye},[_,y]),I=i.useCallback(q=>{f.handleTaskEvent(q);const ye=f.tasks.map(Ke=>Ke.id===q.task.id?{...Ke,...q.task}:Ke);g.handleTaskEvent(q,ye)},[f,g]);i.useCallback(q=>{l(q),u.invalidateQueries({queryKey:qe.bySession(q)})},[l,u]);const b=i.useCallback(q=>{l(q,{replace:!0}),u.invalidateQueries({queryKey:qe.bySession(q)})},[l,u]),j=i.useCallback(q=>{l(crypto.randomUUID(),{continuedFrom:q??void 0,draft:!0})},[l]),k=Ir(e??""),M=Ht(k.runtime),z=k.runtime?xt(k.runtime).label:"",O=((ts=M==null?void 0:M.permissionModes)==null?void 0:ts.denyReason)??!0,$=i.useMemo(()=>Aa(M==null?void 0:M.commandIntents,z),[M,z]),U=i.useRef(null),H=i.useCallback(()=>{var q;return(q=U.current)==null?void 0:q.call(U)},[]),{messages:V,input:te,setInput:W,handleSubmit:F,submitContent:P,enqueueContent:D,steerContent:Q,addContextContent:ae,status:A,error:B,stop:X,isLoadingHistory:J,hydrated:Z,sessionStatus:K,streamStartTime:oe,estimatedTokens:de,isTextStreaming:me,isWaitingForUser:L,waitingType:pe,activeInteraction:ce,pendingInteractions:je,markToolCallResponded:ke,systemStatus:Ne,operationProgress:Ee,promptSuggestions:ue,syncConnectionState:Me,retryMessage:be,tryNativeCommand:Ce,commandPending:xe}=Bh(e,{transformContent:R,onTaskEvent:I,onSessionIdChangeReplace:b,startFreshSession:j,compactIntent:$,launchRuntime:t,...v&&y?{agentPath:y}:{},agentLookupPending:y!==null&&S,agentLookupFailed:y!==null&&N,takeSeedContext:H,onStreamingDone:i.useCallback(()=>{x("turn-end"),u.invalidateQueries({queryKey:["commands"]})},[x,u])}),_e=i.useCallback(q=>P(q,{clearInput:!0}),[P]),{permissionMode:Le,permissionModeKnown:ne}=Wr(e,K,A==="streaming"),ve=Cl(e,k.runtime,ne?Le:void 0),at=Rc(q=>q.setOpen);i.useEffect(()=>{at(!1)},[e,at]);const{handleToolRef:ot,focusedOptionIndex:Oe}=Jh(ce);rg(A,L,f.activeForm,me),i.useEffect(()=>{var q;(q=d.current)==null||q.focusUnlessTouch()},[e]);const Ge=i.useCallback(()=>{var q;(q=d.current)==null||q.focusUnlessTouch()},[]);ig({sessionId:e,prompt:n,autoSend:r,input:te,setInput:W,messageCount:V.length,hydrated:Z,status:A,submitBlocked:w&&y!==null&&(S||N),submit:F,onSeeded:Ge,onConsumed:o});const fe=dg({sessionId:e,seed:a,messageCount:V.length,hydrated:Z,onConsumed:o});i.useEffect(()=>{U.current=fe},[fe]);const he=k.runtime?Pr(k.runtime):void 0,{data:Se}=Bc(y,e??void 0,k.runtime??void 0),Ue=i.useMemo(()=>fp((Se==null?void 0:Se.commands)??[],{commandIntents:M==null?void 0:M.commandIntents,runtimeLabel:z}),[Se,M,z]),{data:Te}=Ug(y),Ua=i.useMemo(()=>Te!=null&&Te.files?vu(Te.files):[],[Te]),qa=sg({input:te,setInput:W,commands:Ue,fileEntries:Ua}),Gn=i.useCallback(()=>{const q=[...V].reverse().find(ye=>ye.role==="user");q!=null&&q.content&&P(q.content)},[V,P]),Kn=zt(e??""),za=i.useCallback(()=>{const q=Su(V,Kn);q&&be(q)},[V,Kn,be]),Qn=A==="idle"&&ue.length>0&&te.length===0,Ba=Ac("chat.suggestion-chips"),Ha=dm(e??""),Wa=mg(A,B,V,Ha),Ga=i.useMemo(()=>V.some(q=>q.role==="user"),[V]),Vn=i.useCallback(q=>{var ye;W(q),(ye=d.current)==null||ye.focus()},[W]),Ka=Gr,Ct=Ec(e??""),Qt=Ur(e??""),Qa=i.useMemo(()=>vg(Ct,Qt),[Ct,Qt]),Yn=(ss=(ns=qn(e??""))==null?void 0:ns.lastError)==null?void 0:ss.category,Vt=Tu(),Xn=i.useCallback(()=>{const q=e??"";if(Vt.claimedElsewhere(q))return!1;const ye=Cu({messages:V,status:A,lastErrorCategory:Yn,queuedCount:Ct.length,draft:ee.getState().getSession(q).input});return ye===null?!1:(Vt.claim(q),P(ye),!0)},[V,A,Yn,Ct.length,e,P,Vt]),Va=v?`Message ${Bn(v)}…`:"Send a message…",Ya=zg({sessionId:e??"",placeholder:Va,submit:_e,enqueue:D,files:_}),{eligible:Jn,allow:Zn,notNow:es}=$g(A==="streaming"),Xa=i.useMemo(()=>[{id:"prompt-suggestions",show:Qn,render:()=>s.jsx(Ic,{suggestions:ue,onChipClick:Vn})},{id:"permission-primer",show:Jn,render:()=>s.jsx(Dg,{onAllow:Zn,onNotNow:es})},{id:"read-only-mode",show:ve.eligible,render:()=>s.jsx(wl,{runtimeLabel:ve.runtimeLabel,onShown:ve.markShown,onDismiss:ve.dismiss})}],[Qn,ue,Vn,Jn,Zn,es,ve]),Ja=qg({asks:Ka,status:A,streamStartTime:oe,estimatedTokens:de,permissionMode:Le,isWaitingForUser:L??!1,waitingType:pe??"approval",operationProgress:Ee,systemStatus:Ne,activity:h});return s.jsx(ht.Root,{surface:"session",capabilities:La,target:Ya,children:s.jsxs("div",{ref:m,"data-testid":"chat-panel","data-turn-status":A,"data-turn-lifecycle":Qt??void 0,className:"flex h-full w-full flex-col",children:[s.jsx(Eu,{sessionId:e}),s.jsx(Ou,{startedBy:E,modes:M==null?void 0:M.permissionModes.values}),s.jsx(Zg,{messages:V,sessionId:e,isLoadingHistory:J,hydrated:Z,isTextStreaming:me,activeToolCallId:(ce==null?void 0:ce.toolCallId)??null,onToolRef:ot,focusedOptionIndex:Oe,onToolDecided:ke,onRetry:Gn,onSigninComplete:Xn,onChooseModel:p,inputZoneToolCallId:(ce==null?void 0:ce.toolCallId)??null,runtimeLabel:he,allowsDenyReason:O,...c===void 0?{}:{landOnRow:c},foldFirstPrompt:E!==null}),s.jsx(_p,{terminalReason:K==null?void 0:K.terminalReason}),s.jsx(ht.LiveLane,{state:Ja,scope:"session"}),s.jsx(Hc,{candidates:Xa,ready:Z,name:"session-bottom-slot",className:"px-4 pb-2"}),A==="idle"&&Ba.map(q=>s.jsx(q.component,{},q.id)),s.jsx(ad,{celebration:g.activeCelebration,onComplete:g.clearCelebration}),s.jsx(Bf,{tasks:f.tasks,taskMap:f.taskMap,activeForm:f.activeForm,isCollapsed:f.isCollapsed,onToggleCollapse:f.toggleCollapse,celebratingTaskId:g.celebratingTaskId,onCelebrationComplete:g.clearCelebration,statusTimestamps:f.statusTimestamps}),Wa&&s.jsx(Op,{sessionId:e,onRetry:Ga?Gn:void 0,onSigninComplete:Xn,onChooseModel:p}),B&&s.jsx("div",{className:"mx-4 mb-2",children:s.jsx(qt,{message:B.message,heading:B.heading,subtext:B.message,onRetry:B.retryable?za:void 0})}),w&&N&&s.jsx("div",{className:"mx-4 mb-2",children:s.jsx(qt,{heading:"Couldn’t check this folder",message:"DorkOS couldn’t tell if an agent owns this folder. Try again.",onRetry:()=>void C()})}),e&&s.jsx(am,{sessionId:e,onSend:q=>void P(q)}),s.jsx(Qg,{chatInputRef:d,input:te,autocomplete:qa,steerContent:Q,addContextContent:ae,tryNativeCommand:Ce,commandPending:xe,agentLookupPending:w&&y!==null&&S,agentLookupError:w&&y!==null&&N,status:A,stop:X,setInput:W,sessionId:e??"",sessionStatus:K,waiting:Qa,interaction:{active:ce,pendingApprovals:je.filter(q=>q.interactiveType==="approval"),focusedOptionIndex:Oe,onToolRef:ot,onToolDecided:ke},sync:{connectionState:Me}})]})})}function tx(e,t){const n=e===null||t===void 0?null:`${e}:${t}`,r=i.useRef(null),a=i.useCallback(()=>{if(n===null||r.current===n||(r.current=n,t===void 0||e===null))return;const o=we.getState().getSession(e).messages;return aa(Qu(o,t)??t)},[n,t,e]);return n===null?void 0:a}function nx(){const[e]=vt();pu(e);const{runtime:t,prompt:n,send:r,seed:a,message:o}=ar(),c=_c(),l=tx(e,o),{data:u}=Mc(e,{enabled:!1,select:p=>p.title}),d=$r(e);Wl(e,{canonical:d===null}),Wc();const m=i.useCallback(()=>{c==null||c({search:p=>({...p,prompt:void 0,send:void 0,seed:void 0}),replace:!0})},[c]);return s.jsxs(s.Fragment,{children:[s.jsx(Oc,{children:u!=null&&u.trim()?u:"Chat"}),s.jsx(ex,{sessionId:e,launchRuntime:t,launchPrompt:n,launchSend:r==="1",launchSeed:a,onLaunchConsumed:m,...l===void 0?{}:{landOnRow:l}})]})}const Cx=nx;export{Cx as component};